-
Notifications
You must be signed in to change notification settings - Fork 1
/
horizontal.go
109 lines (105 loc) · 2.41 KB
/
horizontal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package table
import (
"fmt"
"io"
"strings"
)
func (t *Table) MergeRowsHorizontal(
out io.Writer,
items FormattedItemList,
maxWidthArg int,
sep string,
compact bool,
) {
margin := uint16(len(sep))
colN := t.ColumnCount()
if maxWidthArg > MAX_WIDTH {
maxWidthArg = MAX_WIDTH
}
maxWidth := uint16(maxWidthArg)
groupCount := int((maxWidth + margin) / (t.TableWidth(margin) + margin))
if groupCount < 1 {
groupCount = 1
}
getWidth := func(colI int, groupI int) uint16 {
return t.columnWidth[t.Columns[colI].Name]
}
if compact {
extra, cellWidth := t.compactCalcH(items, maxWidth, margin, groupCount)
if extra > 0 {
groupCount += extra
getWidth = func(colI int, groupI int) uint16 {
return cellWidth[groupI*colN+colI]
}
}
}
itemN := items.Len()
lineCount := (itemN-1)/groupCount + 1
for lineI := 0; lineI < lineCount; lineI++ {
line := make([]string, 0, groupCount)
for groupI := 0; groupI < groupCount; groupI++ {
itemIdx := lineI*groupCount + groupI
if itemIdx >= itemN {
line = append(line, "")
break
}
item := items.Get(itemIdx)
cell := make([]string, colN)
for colI, col := range t.Columns {
al := col.Alignment
if al == nil {
al = AlignmentLeft
}
cell[colI] = al(
item[colI],
getWidth(colI, groupI),
)
}
line = append(line, strings.Join(cell, innerSep))
}
fmt.Fprintln(out, strings.Join(line, sep))
}
}
func (t *Table) compactCalcH(
items FormattedItemList,
maxWidth uint16,
margin uint16,
groupCountInit int,
) (extra int, cellWidth []uint16) {
colN := uint16(t.ColumnCount())
for {
groupCount := groupCountInit + extra + 1
cellWidthNew := t.mergedRowsWidthH(items, groupCount)
totalWidth := margin*(uint16(groupCount)-1) + innerMargin*(colN-1)*uint16(groupCount)
for _, w := range cellWidthNew {
totalWidth += w
}
if totalWidth > maxWidth {
return
}
cellWidth = cellWidthNew
extra += 1
}
return 0, nil
}
func (t *Table) mergedRowsWidthH(
items FormattedItemList,
groupCount int,
) []uint16 {
itemN := items.Len()
colN := t.ColumnCount()
width := make([]uint16, 0, groupCount*colN)
for groupI := 0; groupI < groupCount; groupI++ {
for colI := 0; colI < colN; colI++ {
mw := uint16(0)
for itemIdx := int(groupI); itemIdx < itemN; itemIdx += int(groupCount) {
w := visualWidth(items.Get(itemIdx)[colI])
if w > mw {
mw = w
}
}
width = append(width, mw)
}
}
return width
}