File: row.go

package info (click to toggle)
golang-github-achannarasappa-term-grid 0.2.4-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 132 kB
  • sloc: makefile: 2
file content (106 lines) | stat: -rw-r--r-- 2,017 bytes parent folder | download
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
package grid

import (
	"math"
	"strings"

	"github.com/muesli/reflow/ansi"
)

// Row contains settings for a single row within the parent Grid
type Row struct {
	Width int
	Cells []Cell
}

func getWidthFlexCells(widthTotal int, count int) (int, int) {

	if count <= 0 {
		return widthTotal, 0
	}

	remainder := widthTotal % count
	width := int(math.Floor(float64(widthTotal) / float64(count)))

	return width, remainder
}

func updateCells(widthTotal int, widthGutter int, cells []Cell) []Cell {

	widthFlex := widthTotal
	countFlexWidthCells := 0
	var cellsFiltered = make([]Cell, 0)

	for _, cell := range cells {

		if cell.Width < 0 {
			continue
		}

		if cell.VisibleMinWidth > 0 && cell.VisibleMinWidth > widthTotal {
			continue
		}

		if cell.Width <= 0 {
			countFlexWidthCells++
		}

		widthFlex -= cell.Width
		cellsFiltered = append(cellsFiltered, cell)
	}

	widthFlex = widthFlex - (widthGutter * (len(cellsFiltered) - 1))

	if widthFlex <= 0 {
		return cellsFiltered
	}

	widthFlexCellsWithoutRemainder, widthRemainder := getWidthFlexCells(widthFlex, countFlexWidthCells)

	for i, cell := range cellsFiltered {

		if cell.Width <= 0 && widthRemainder > 0 {
			widthRemainder--
			cellsFiltered[i].Width = widthFlexCellsWithoutRemainder + 1
			continue
		}

		if cell.Width <= 0 {
			cellsFiltered[i].Width = widthFlexCellsWithoutRemainder
			continue
		}

	}

	return cellsFiltered

}

func renderRow(row Row, config gridConfig) string {
	lines := []string{}
	heightMax := 0
	widthLinePreviousCells := 0
	cells := updateCells(row.Width, config.widthGutter, row.Cells)
	cellLastIndex := (len(cells) - 1)

	for i, cell := range cells {

		if i == cellLastIndex {
			config.widthGutter = 0
		}

		lines, heightMax = getLines(cell, lines, heightMax, widthLinePreviousCells, config)

		widthLinePreviousCells += cell.Width + config.widthGutter
	}

	for i := range lines {

		if ansi.PrintableRuneWidth(lines[i]) > row.Width {
			lines[i] = lines[i][:row.Width]
		}

	}

	return strings.Join(lines, "\n")
}