gitstack

grindlemire/go-tui code browser

20.4 KB markdown 641 lines 2026-06-06 · d6d303e raw
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# Element Reference

## Overview

`Element` is the building block of go-tui UIs. Every visible piece of content (text, borders, containers, scrollable regions) is an Element. Elements form a tree: a root element contains children, which contain their own children, and so on. The layout engine computes positions using CSS flexbox, and the renderer draws the result to a character buffer.

You can create elements two ways: in `.gsx` templates (the common path) or programmatically with `tui.New()`.

```gsx
// In .gsx — the compiler turns this into tui.New(...) calls
<div class="flex-col gap-1 p-1 border-rounded">
    <span class="font-bold text-cyan">Hello</span>
    <span>World</span>
</div>
```

```go
// Programmatic equivalent
root := tui.New(
    tui.WithDirection(tui.Column),
    tui.WithGap(1),
    tui.WithPadding(1),
    tui.WithBorder(tui.BorderRounded),
)
title := tui.New(
    tui.WithText("Hello"),
    tui.WithTextStyle(tui.NewStyle().Bold().Foreground(tui.ANSIColor(tui.Cyan))),
)
body := tui.New(tui.WithText("World"))
root.AddChild(title, body)
```

`Element` implements the `Viewable`, `Focusable`, and `Layoutable` interfaces.

## Creating Elements

### New

```go
func New(opts ...Option) *Element
```

Creates a new Element with the given options. By default, elements use Auto width and height, Row direction, and a transparent background, with border and text unset.

```go
box := tui.New(
    tui.WithWidth(40),
    tui.WithHeight(10),
    tui.WithBorder(tui.BorderRounded),
    tui.WithText("Content"),
)
```

In `.gsx` files, elements are created with HTML-like tags:

```gsx
<div width={40} height={10} border={tui.BorderRounded}>
    <span>Content</span>
</div>
```

## Option Functions

`Option` is defined as `func(*Element)`. Pass options to `tui.New()` to configure an element at creation time. The `.gsx` compiler translates element attributes and Tailwind classes into these same option calls.

### Dimensions

| Function | Description |
|----------|-------------|
| `WithWidth(cells int)` | Fixed width in terminal cells |
| `WithWidthPercent(percent float64)` | Width as a percentage of parent's available width |
| `WithWidthAuto()` | Width sized to content (default) |
| `WithHeight(cells int)` | Fixed height in terminal rows |
| `WithHeightPercent(percent float64)` | Height as a percentage of parent's available height |
| `WithHeightAuto()` | Height sized to content (default) |
| `WithSize(width, height int)` | Sets both width and height in terminal cells |
| `WithMinWidth(cells int)` | Minimum width constraint |
| `WithMinHeight(cells int)` | Minimum height constraint |
| `WithMaxWidth(cells int)` | Maximum width constraint |
| `WithMaxHeight(cells int)` | Maximum height constraint |

```go
// Fixed 40x10 box
tui.New(tui.WithSize(40, 10))

// Half-width panel with minimum
tui.New(tui.WithWidthPercent(50), tui.WithMinWidth(20))
```

### Flex Container

These options control how an element lays out its children.

| Function | Description |
|----------|-------------|
| `WithDirection(d Direction)` | Main axis: `tui.Row` (horizontal, default) or `tui.Column` (vertical) |
| `WithJustify(j Justify)` | Main axis alignment: `JustifyStart`, `JustifyCenter`, `JustifyEnd`, `JustifySpaceBetween`, `JustifySpaceAround`, `JustifySpaceEvenly` |
| `WithAlign(a Align)` | Cross axis alignment: `AlignStart`, `AlignCenter`, `AlignEnd`, `AlignStretch` |
| `WithGap(cells int)` | Space between children on the main axis |

```go
// Vertical layout with centered children and 1-cell gap
tui.New(
    tui.WithDirection(tui.Column),
    tui.WithAlign(tui.AlignCenter),
    tui.WithGap(1),
)
```

### Flex Item

These options control how an element behaves as a child within a flex container.

| Function | Description |
|----------|-------------|
| `WithFlexGrow(factor float64)` | How much this element grows relative to siblings to fill extra space |
| `WithFlexShrink(factor float64)` | How much this element shrinks relative to siblings when space is tight |
| `WithAlignSelf(a Align)` | Overrides the parent's `AlignItems` for this element |

```go
// Sidebar (fixed) + main content (grows to fill)
sidebar := tui.New(tui.WithWidth(30))
content := tui.New(tui.WithFlexGrow(1))
```

### Spacing

| Function | Description |
|----------|-------------|
| `WithPadding(cells int)` | Uniform padding on all sides (inside the border) |
| `WithPaddingTRBL(top, right, bottom, left int)` | Per-side padding in CSS order |
| `WithMargin(cells int)` | Uniform margin on all sides (outside the border) |
| `WithMarginTRBL(top, right, bottom, left int)` | Per-side margin in CSS order |

```go
// 1-cell padding all around, 2-cell top margin
tui.New(
    tui.WithPadding(1),
    tui.WithMarginTRBL(2, 0, 0, 0),
)
```

### Visual

| Function | Description |
|----------|-------------|
| `WithBorder(style BorderStyle)` | Border shape: `BorderNone`, `BorderSingle`, `BorderDouble`, `BorderRounded`, `BorderThick` |
| `WithBorderStyle(style Style)` | Color and attributes for the border lines |
| `WithBorderTitle(title string)` | Title text centered in the top border line |
| `WithBackground(style Style)` | Background fill style |
| `WithText(content string)` | Text content for this element |
| `WithTextStyle(style Style)` | Text color and attributes. Setting this prevents style inheritance from the parent |
| `WithTextAlign(align TextAlign)` | Text alignment: `TextAlignLeft` (default), `TextAlignCenter`, `TextAlignRight` |

```go
// Cyan-bordered box with bold white text on a blue background
tui.New(
    tui.WithBorder(tui.BorderRounded),
    tui.WithBorderStyle(tui.NewStyle().Foreground(tui.ANSIColor(tui.Cyan))),
    tui.WithBackground(tui.NewStyle().Background(tui.ANSIColor(tui.Blue))),
    tui.WithText("Status: OK"),
    tui.WithTextStyle(tui.NewStyle().Bold().Foreground(tui.ANSIColor(tui.White))),
)
```

### Gradient

| Function | Description |
|----------|-------------|
| `WithTextGradient(g Gradient)` | Gradient applied per-character to text (overrides `textStyle.Fg`) |
| `WithBackgroundGradient(g Gradient)` | Gradient fill for the element background |
| `WithBorderGradient(g Gradient)` | Gradient applied around the border perimeter |

```go
tui.New(
    tui.WithText("Rainbow"),
    tui.WithTextGradient(tui.NewGradient(
        tui.ANSIColor(tui.Red),
        tui.ANSIColor(tui.Cyan),
    )),
)
```

### Focus

| Function | Description |
|----------|-------------|
| `WithFocusable(focusable bool)` | Whether this element can receive focus |
| `WithOnFocus(fn func(*Element))` | Callback when focus is gained. Implicitly sets `focusable = true` |
| `WithOnBlur(fn func(*Element))` | Callback when focus is lost. Implicitly sets `focusable = true` |
| `WithOnActivate(fn func())` | Callback when Enter is pressed while focused. Implicitly sets `focusable = true` |

```go
tui.New(
    tui.WithFocusable(true),
    tui.WithOnFocus(func(el *tui.Element) {
        el.SetBorderStyle(tui.NewStyle().Foreground(tui.ANSIColor(tui.Cyan)))
    }),
    tui.WithOnBlur(func(el *tui.Element) {
        el.SetBorderStyle(tui.NewStyle())
    }),
)
```

### Scroll

| Function | Description |
|----------|-------------|
| `WithScrollable(mode ScrollMode)` | Enables scrolling: `ScrollVertical`, `ScrollHorizontal`, or `ScrollBoth`. Implicitly sets `focusable = true` and applies default scrollbar styles |
| `WithScrollOffset(x, y int)` | Initial scroll position. Useful for preserving scroll state across re-renders via `State[int]` |
| `WithScrollbarStyle(style Style)` | Style for the scrollbar track |
| `WithScrollbarThumbStyle(style Style)` | Style for the scrollbar thumb |
| `WithScrollbarHidden(hidden bool)` | Hide the scrollbar and reclaim its gutter column. Scrolling still works via keyboard, mouse wheel, and programmatic calls |

```go
tui.New(
    tui.WithScrollable(tui.ScrollVertical),
    tui.WithScrollOffset(0, scrollY.Get()),
    tui.WithScrollbarThumbStyle(tui.NewStyle().Foreground(tui.ANSIColor(tui.Cyan))),
)
```

### Behavior

| Function | Description |
|----------|-------------|
| `WithHR()` | Configures the element as a horizontal rule. Sets height to 1 and `AlignSelf` to stretch. Uses `─` by default, `═` for `BorderDouble`, `━` for `BorderThick` |
| `WithTruncate(truncate bool)` | Enables text truncation with ellipsis (`…`) when text overflows the element width |
| `WithHidden(hidden bool)` | Excludes the element from layout and rendering |
| `WithOverflow(mode OverflowMode)` | How content beyond element bounds is handled: `OverflowVisible` (default) or `OverflowHidden` |
| `WithOnUpdate(fn func())` | Hook called before each render. Useful for polling or animation logic |

```go
// Truncated text in a fixed-width cell
tui.New(
    tui.WithWidth(20),
    tui.WithText("This is a very long string that will be truncated"),
    tui.WithTruncate(true),
)
```

## Accessors

Get and set methods for reading and modifying element properties after creation. Setters that affect layout or rendering call `MarkDirty()` automatically.

### Style (Layout)

```go
func (e *Element) Style() LayoutStyle
func (e *Element) SetStyle(style LayoutStyle)
```

Read or replace the full layout style. `SetStyle` marks the element dirty.

### Border

```go
func (e *Element) Border() BorderStyle
func (e *Element) SetBorder(border BorderStyle)
func (e *Element) BorderStyle() Style
func (e *Element) SetBorderStyle(style Style)
func (e *Element) BorderTitle() string
func (e *Element) SetBorderTitle(title string)
```

`Border()` returns the border shape (`BorderSingle`, `BorderRounded`, etc.). `BorderStyle()` returns the color/attribute style used to draw the border lines. `BorderTitle()` returns the title text drawn in the top border, or `""` when no title is set.

### Background

```go
func (e *Element) Background() *Style
func (e *Element) SetBackground(style *Style)
```

Returns `nil` when the background is transparent. Pass `nil` to `SetBackground` to make it transparent again.

### Text

```go
func (e *Element) Text() string
func (e *Element) SetText(content string)
func (e *Element) TextStyle() Style
func (e *Element) SetTextStyle(style Style)
func (e *Element) TextAlign() TextAlign
func (e *Element) SetTextAlign(align TextAlign)
```

`SetText` marks the element dirty. `SetTextStyle` prevents style inheritance from the parent element for this element's text.

### Truncate

```go
func (e *Element) Truncate() bool
func (e *Element) SetTruncate(truncate bool)
```

When enabled, text that overflows the element's content width is cut off with an ellipsis character (`…`).

### Hidden

```go
func (e *Element) Hidden() bool
func (e *Element) SetHidden(hidden bool)
```

Hidden elements are excluded from both layout and rendering. Their children are also skipped.

### Overflow

```go
func (e *Element) Overflow() OverflowMode
func (e *Element) SetOverflow(mode OverflowMode)
```

Controls whether content that exceeds element bounds is visible or clipped.

## Tree Methods

Elements form a tree. These methods manipulate the parent-child relationships.

### AddChild

```go
func (e *Element) AddChild(children ...*Element)
```

Appends one or more children. Each child's parent is set to this element, and the element is marked dirty. If the root element has callback hooks registered (for focus or child-added notifications), they fire for each new child.

```go
container := tui.New(tui.WithDirection(tui.Column))
container.AddChild(
    tui.New(tui.WithText("First")),
    tui.New(tui.WithText("Second")),
)
```

### RemoveChild

```go
func (e *Element) RemoveChild(child *Element) bool
```

Removes a specific child. Returns `true` if the child was found and removed. The removed child's parent is set to `nil`.

### RemoveAllChildren

```go
func (e *Element) RemoveAllChildren()
```

Removes all children from this element.

### Children

```go
func (e *Element) Children() []*Element
```

Returns the slice of child elements.

### Parent

```go
func (e *Element) Parent() *Element
```

Returns the parent element, or `nil` for the root.

### SetOnChildAdded

```go
func (e *Element) SetOnChildAdded(fn func(*Element))
```

Registers a callback that fires whenever a descendant is added anywhere in this element's subtree. Used internally by the framework for focus management.

## Layout Methods

The layout engine uses these methods during the flexbox calculation pass.

### LayoutStyle / LayoutChildren

```go
func (e *Element) LayoutStyle() LayoutStyle
func (e *Element) LayoutChildren() []Layoutable
```

Part of the `Layoutable` interface. `LayoutStyle` returns the element's style with border padding added (borders consume 1 cell on each side). `LayoutChildren` returns visible children only; hidden elements are excluded.

### SetLayout / GetLayout

```go
func (e *Element) SetLayout(l LayoutResult)
func (e *Element) GetLayout() LayoutResult
```

Called by the layout engine to store and retrieve computed layout results.

### Calculate

```go
func (e *Element) Calculate(availableWidth, availableHeight int)
```

Runs the flexbox layout algorithm on this element and all its descendants. Wraps the package-level `tui.Calculate()` function.

```go
root.Calculate(80, 24) // Layout for an 80x24 terminal
```

### Rect / ContentRect

```go
func (e *Element) Rect() Rect
func (e *Element) ContentRect() Rect
```

`Rect` returns the border box (the full area including border and padding). `ContentRect` returns the inner content area (inside border and padding). Both are populated after `Calculate` runs.

### IntrinsicSize

```go
func (e *Element) IntrinsicSize() (width, height int)
```

Returns the natural content-based dimensions. For text elements, this is the text width plus padding and border. For containers, it's computed from children. Scrollable elements return `(0, 0)` since they rely on explicit sizing or `flexGrow`. Horizontal rules return `(0, 1)`.

### Dirty Flags

```go
func (e *Element) IsDirty() bool
func (e *Element) SetDirty(dirty bool)
func (e *Element) MarkDirty()
```

`MarkDirty` walks up the parent chain setting dirty flags, and also marks the owning App as dirty (triggering a re-render on the next frame). `IsDirty` and `SetDirty` are used by the layout engine.

### IsHR

```go
func (e *Element) IsHR() bool
```

Returns `true` if this element was configured with `WithHR()`.

## Focus Methods

Focus determines which element receives keyboard input.

### Query

```go
func (e *Element) IsFocusable() bool
func (e *Element) IsFocused() bool
func (e *Element) SetFocusable(focusable bool)
```

Check or change whether an element can receive focus, and whether it currently has it.

### Focus / Blur

```go
func (e *Element) Focus()
func (e *Element) Blur()
```

`Focus` marks the element as focused and calls the `onFocus` callback if one is registered. `Blur` clears the focused state and calls `onBlur`. These don't cascade to children. Only the target element is affected.

### SetOnFocus / SetOnBlur

```go
func (e *Element) SetOnFocus(fn func(*Element))
func (e *Element) SetOnBlur(fn func(*Element))
```

Register focus/blur callbacks after creation. Both implicitly set `focusable = true`.

### HandleEvent

```go
func (e *Element) HandleEvent(event Event) bool
```

Dispatches an event to this element. For scrollable elements, handles arrow keys, Page Up/Down, Home/End, and mouse wheel events. Returns `true` if the event was consumed.

Built-in scroll key handling:
- **Up/Down arrows**: scroll vertically by 1 row
- **Left/Right arrows**: scroll horizontally by 1 column
- **Page Up/Page Down**: scroll by viewport height
- **Home**: scroll to top-left
- **End**: scroll to bottom
- **Mouse wheel**: scroll vertically by 1 row per tick

### ContainsPoint

```go
func (e *Element) ContainsPoint(x, y int) bool
```

Returns `true` if the point falls within the element's computed layout bounds. Useful for hit testing in `HandleMouse` implementations.

## Scroll Methods

Scroll methods only work on elements created with `WithScrollable()`.

### Query

```go
func (e *Element) IsScrollable() bool
func (e *Element) ScrollModeValue() ScrollMode
func (e *Element) ScrollOffset() (x, y int)
func (e *Element) ContentSize() (width, height int)
func (e *Element) ViewportSize() (width, height int)
func (e *Element) MaxScroll() (maxX, maxY int)
```

| Method | Returns |
|--------|---------|
| `IsScrollable()` | Whether scrolling is enabled |
| `ScrollModeValue()` | The scroll mode (`ScrollVertical`, `ScrollHorizontal`, `ScrollBoth`) |
| `ScrollOffset()` | Current scroll position |
| `ContentSize()` | Total content dimensions (computed during layout, may exceed viewport) |
| `ViewportSize()` | Visible area dimensions |
| `MaxScroll()` | Maximum valid scroll offset in each direction |

### Control

```go
func (e *Element) ScrollTo(x, y int)
func (e *Element) ScrollBy(dx, dy int)
func (e *Element) ScrollToTop()
func (e *Element) ScrollToBottom()
```

`ScrollTo` sets an absolute position, clamped to valid range. `ScrollBy` adjusts relative to the current position. `ScrollToBottom` scrolls immediately and also sets a pending flag so that after the next layout pass (when content size may have changed), it re-scrolls to the new bottom. This makes it reliable for following new content.

### IsAtBottom

```go
func (e *Element) IsAtBottom() bool
```

Returns `true` if the element is scrolled to the bottom. Useful for implementing sticky-scroll behavior (auto-follow new content, but stop following when the user scrolls up).

### ScrollIntoView

```go
func (e *Element) ScrollIntoView(child *Element)
```

Scrolls the minimum amount needed to make `child` fully visible within this element's viewport. Does nothing if `child` is not a descendant or if scrolling is disabled.

## Watcher and Discovery Methods

Background operations (timers, channel watchers) and tree traversal hooks.

### Watchers

```go
func (e *Element) AddWatcher(w Watcher)
func (e *Element) Watchers() []Watcher
func (e *Element) WalkWatchers(fn func(Watcher))
```

`AddWatcher` attaches a timer or channel watcher to this element. Watchers start automatically when the element tree is set as the app root. `WalkWatchers` traverses the tree and calls `fn` for every watcher (skipping hidden elements).

### Focus Discovery

```go
func (e *Element) WalkFocusables(fn func(Focusable))
func (e *Element) SetOnFocusableAdded(fn func(Focusable))
```

`WalkFocusables` does a depth-first walk calling `fn` for each focusable element. `SetOnFocusableAdded` registers a callback for when new focusable descendants are added. Both are used by the App for automatic focus management.

### Pre-Render Hook

```go
func (e *Element) SetOnUpdate(fn func())
```

Sets a function called before each render pass. Useful for polling, animations, or other per-frame logic.

### Hit Testing

```go
func (e *Element) ElementAt(x, y int) *Element
func (e *Element) ElementAtPoint(x, y int) Focusable
```

`ElementAt` finds the deepest element containing the given point. Children are checked in reverse order (last child renders on top, so it gets priority). Returns `nil` if no element contains the point.

`ElementAtPoint` does the same thing but returns a `Focusable` interface to satisfy the internal mouse hit-testing contract.

## Rendering

```go
func (e *Element) Render(buf *Buffer, width, height int)
```

The main rendering entry point. Runs layout (if dirty) and then renders the full element tree to the buffer.

```go
func RenderTree(buf *Buffer, root *Element)
```

Package-level function that traverses the element tree and draws each element to the buffer. Handles background fills, borders, text, gradients, scroll clipping, and overflow clipping. Called by `Element.Render()` after layout.

## Enums

### TextAlign

Controls horizontal text alignment within an element's content area.

| Constant | Description |
|----------|-------------|
| `TextAlignLeft` | Left-aligned (default) |
| `TextAlignCenter` | Centered horizontally |
| `TextAlignRight` | Right-aligned |

Text alignment only takes effect when the element is wider than its text content, e.g. when you set an explicit `WithWidth` larger than the text. For auto-sized elements, the text fills the element exactly, and the parent's `AlignItems` handles positioning.

### ScrollMode

Controls which directions an element can scroll.

| Constant | Description |
|----------|-------------|
| `ScrollNone` | Scrolling disabled (default) |
| `ScrollVertical` | Vertical scrolling only |
| `ScrollHorizontal` | Horizontal scrolling only |
| `ScrollBoth` | Both vertical and horizontal scrolling |

### OverflowMode

Controls how content beyond element bounds is handled.

| Constant | Description |
|----------|-------------|
| `OverflowVisible` | Content renders outside bounds (default) |
| `OverflowHidden` | Content is clipped at element bounds |