package terminalui // ListIndex maps selectable items to their display lines. A group or section // heading is part of the scrollable content but cannot acquire keyboard focus. type ListIndex struct { lines []listLine positions []int } type listLine struct { text string item int heading int isHeading bool } func (v *ListIndex) heading() int { if len(v.lines) == 0 { return -1 } return v.lines[len(v.lines)-1].heading } func (v *ListIndex) Heading(text string) { v.lines = append(v.lines, listLine{text: text, item: -1, heading: len(v.lines), isHeading: true}) } func (v *ListIndex) Gap() { if len(v.lines) > 0 { v.lines = append(v.lines, listLine{item: -1, heading: v.heading()}) } } func (v *ListIndex) Item(sticky bool) { line := len(v.lines) head := v.heading() if sticky { head = line } v.lines = append(v.lines, listLine{item: len(v.positions), heading: head, isHeading: sticky}) v.positions = append(v.positions, line) } // Window keeps the selected item visible. Pin its heading above a clipped // group and reserve an overflow marker below when more items follow. func (v *ListIndex) Window(cursor, height int, overflow string, draw func(int, bool) string) []string { out := make([]string, max(0, height)) if len(v.positions) == 0 || height <= 0 { return out } cursor = min(max(0, cursor), len(v.positions)-1) selected := v.positions[cursor] start := min(max(0, selected-height/2), max(0, len(v.lines)-height)) // Move a partial window away from an orphaned heading or gap at its foot. orphan := func() bool { if height < 3 || start+height >= len(v.lines) { return false } last := v.lines[start+height-2] return last.item < 0 || last.isHeading && v.lines[start+height-1].item >= 0 } for orphan() && start > 0 && selected < start+height-3 { start-- } for orphan() && selected > start+1 { start++ } end := min(start+height, len(v.lines)) paint := func(l listLine, active bool) string { if l.item < 0 { return l.text } return draw(l.item, active) } for i := start; i < end; i++ { out[i-start] = paint(v.lines[i], i == selected) } if height < 3 { return out } if start > 0 && start < selected { head := v.lines[start+1].heading if v.lines[start+1].item >= 0 && head >= 0 && head <= start { out[0] = paint(v.lines[head], false) } else { out[0] = overflow } } if end < len(v.lines) && end-1 != selected { out[height-1] = overflow if end-2 != selected && v.lines[end-2].isHeading { out[height-2] = "" } } return out }