### Run Getting Started Example
Source: https://github.com/grindlemire/go-tui/blob/main/README.md
Navigate to the '01-getting-started' example directory and run the Go program.
```bash
cd examples/01-getting-started && go run .
```
--------------------------------
### Project Setup Commands
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/21-directory-tree.md
Commands to create a new project directory, initialize a Go module, and install the go-tui library.
```bash
mkdir directory-tree && cd directory-tree
go mod init directory-tree
go get github.com/grindlemire/go-tui
```
--------------------------------
### Full TextArea Example with Submit
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/built-in-components.md
Demonstrates a complete TextArea setup with custom dimensions, border, placeholder, submit key binding, and an on-submit handler.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
ta := tui.NewTextArea(
tui.WithTextAreaWidth(60),
tui.WithTextAreaMaxHeight(10),
tui.WithTextAreaBorder(tui.BorderRounded),
tui.WithTextAreaPlaceholder("Write a note..."),
tui.WithTextAreaSubmitKey(tui.KeyCtrlS),
tui.WithTextAreaOnSubmit(func(text string) {
fmt.Printf("Saved: %s\n", text)
}),
)
app, err := tui.NewApp(
tui.WithRootComponent(ta),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Main Application Setup with Streaming Data
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/16-streaming.md
Sets up the TUI application, creates a buffered channel for streaming data, and starts a producer goroutine. Handles application startup and shutdown.
```go
func main() {
dataCh := make(chan string, 100)
app, err := tui.NewApp(
tui.WithRootComponent(Streaming(dataCh)),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create app: %v\n", err)
os.Exit(1)
}
defer app.Close()
go produce(dataCh, app.StopCh())
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "App error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Main Application Setup with Event Producer
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/18-dashboard.md
Sets up the TUI application, configures root component, enables mouse support, and starts an event producer goroutine. Handles app errors and ensures clean shutdown.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
eventCh := make(chan string, 100)
app, err := tui.NewApp(
tui.WithRootComponent(Dashboard(eventCh)),
tui.WithMouse(),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create app: %v\n", err)
os.Exit(1)
}
defer app.Close()
go produceEvents(eventCh, app.StopCh())
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "App error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Install go-tui CLI and Library
Source: https://github.com/grindlemire/go-tui/blob/main/README.md
Installs the go-tui command-line tool and the library using go get and go install.
```bash
go get github.com/grindlemire/go-tui
go install github.com/grindlemire/go-tui/cmd/tui@latest
```
--------------------------------
### Main Application Setup with Producer Goroutine
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/12-watchers.md
Sets up the TUI application, creates a message channel, and starts a producer goroutine. The producer sends formatted messages to the channel and respects the application's stop signal via `app.StopCh()` for clean shutdown.
```go
package main
import (
"fmt"
"os"
"time"
tui "github.com/grindlemire/go-tui"
)
func main() {
msgCh := make(chan string, 100)
app, err := tui.NewApp(
tui.WithRootComponent(FeedApp(msgCh)),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer app.Close()
// Start producer, using StopCh to know when to exit
go func() {
defer close(msgCh)
i := 0
for {
select {
case <-app.StopCh():
return
case msgCh <- fmt.Sprintf("[%s] Event #%d", time.Now().Format("15:04:05"), i):
i++
}
time.Sleep(2 * time.Second)
}
}()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Read Cell Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/buffer.md
Shows how to get a cell at a specific position and check its rune.
```go
c := buf.Cell(5, 3)
if c.Rune == '>' {
// ...
}
```
--------------------------------
### Initializer Implementation Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/07-components.md
Example of implementing the Initializer interface to establish a WebSocket connection and set up a read loop, with cleanup logic.
```go
func (c *conn) Init() func() {
c.ws = connectWebSocket(c.url)
go c.readLoop()
return func() {
c.ws.Close()
}
}
```
--------------------------------
### Main Application Setup
Source: https://github.com/grindlemire/go-tui/blob/main/README.md
Sets up and runs the go-tui application using the Counter component as the root.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(tui.WithRootComponent(Counter()))
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Generating Example Code
Source: https://github.com/grindlemire/go-tui/blob/main/CLAUDE.md
Use the built CLI tool to generate code for the examples directory.
```bash
./tui generate ./examples/...
```
--------------------------------
### Get Buffer Rectangle Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/buffer.md
Demonstrates retrieving the buffer's rectangular bounds.
```go
r := buf.Rect() // Rect{X: 0, Y: 0, Width: 80, Height: 24}
```
--------------------------------
### GSX Plugin Setup
Source: https://github.com/grindlemire/go-tui/blob/main/editor/nvim/README.md
Call the setup function to initialize the GSX plugin in your Neovim configuration.
```lua
require("gsx").setup()
```
--------------------------------
### KeyMap Example for Application Control
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/events.md
Provides an example of a KeyMap implementation for an application, binding Escape and 'q' to stop the application.
```go
func (a *myApp) KeyMap() tui.KeyMap {
return tui.KeyMap{
tui.On(tui.KeyEscape, func(ke tui.KeyEvent) {
ke.App().Stop()
}),
tui.On(tui.Rune('q'), func(ke tui.KeyEvent) {
ke.App().Stop()
}),
}
}
```
--------------------------------
### Color Support Check Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/styling.md
An example demonstrating how to use DetectCapabilities, SupportsColor, and EffectiveColor to check for and utilize terminal color support.
```go
caps := tui.DetectCapabilities()
coral := tui.RGBColor(255, 127, 80)
if caps.SupportsColor(coral) {
// terminal handles 24-bit color natively
} else {
fallback := caps.EffectiveColor(coral)
// fallback is the nearest ANSI approximation
}
```
--------------------------------
### Go-TUI Application Setup
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/05-elements.md
This is the main Go program setup for a TUI application. It initializes a new TUI app with a root component and runs it, handling potential errors.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(
tui.WithRootComponent(Elements()),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create app: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "App error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Pure Components Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/07-components.md
Example of defining pure components (Badge, InfoRow, Card) using templ syntax for UI elements.
```go
package main
import (
"fmt"
tui "github.com/grindlemire/go-tui"
)
templ Badge(label string, style string) {
{label}
}
templ InfoRow(label string, value string) {
{label}{value}
}
templ Card(title string) {
{title}
{children...}
}
```
--------------------------------
### Watcher Implementation Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/07-components.md
Example of implementing the WatcherProvider interface to update a timer every second.
```go
func (t *timer) Watchers() []tui.Watcher {
return []tui.Watcher{
tui.OnTimer(time.Second, func() {
t.elapsed.Update(func(v int) int { return v + 1 })
}),
}
}
```
--------------------------------
### Go-TUI Key Binding Examples
Source: https://github.com/grindlemire/go-tui/blob/main/CLAUDE.md
Provides examples of implementing the KeyListener interface to handle keyboard input using tui.KeyMap. Shows binding to specific keys, runes, and using special matchers like tui.AnyRune and tui.AnyKey.
```go
func (c *myComponent) KeyMap() tui.KeyMap {
return tui.KeyMap{
tui.On(tui.KeyEnter, c.onEnter), // Specific key, broadcast
tui.OnStop(tui.KeyEscape, c.onEscape), // Specific key, stop propagation
tui.On(tui.Rune('q'), func(ke tui.KeyEvent) { ... }), // Specific character
tui.OnStop(tui.AnyRune, c.onTyping), // All printable chars, exclusive
tui.OnPreemptStop(tui.AnyKey, c.onBlock), // Preemptive, stops propagation
}
}
```
--------------------------------
### Install GSX Tree-sitter Parser
Source: https://github.com/grindlemire/go-tui/blob/main/editor/nvim/README.md
Install the 'gsx' tree-sitter parser using the :TSInstall command.
```vim
:TSInstall gsx
```
--------------------------------
### Manual Installation for GSX Plugin
Source: https://github.com/grindlemire/go-tui/blob/main/editor/nvim/README.md
Manually install the GSX plugin by cloning the repository and adding its path to Neovim's runtimepath.
```lua
vim.opt.rtp:prepend("/path/to/go-tui/editor/nvim")
require("gsx").setup()
```
--------------------------------
### Set String Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/buffer.md
Writes 'Hello, world!' at (2, 0) and returns its display width.
```go
w := buf.SetString(2, 0, "Hello, world!", tui.NewStyle())
// w == 13
```
--------------------------------
### Draw Box Examples
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/styling.md
Examples demonstrating how to draw a simple box and a box with a title using the DrawBox and DrawBoxWithTitle functions.
```go
buf := tui.NewBuffer(40, 10)
rect := tui.NewRect(0, 0, 40, 10)
style := tui.NewStyle().Foreground(tui.ANSIColor(tui.Cyan))
tui.DrawBox(buf, rect, tui.BorderRounded, style)
tui.DrawBoxWithTitle(buf, rect, tui.BorderSingle, "My Panel", style)
```
--------------------------------
### ChannelWatcher Usage Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/watchers.md
Example of creating a ChannelWatcher to process string messages from a channel and append them to a list state.
```go
dataCh := make(chan string)
w := tui.NewChannelWatcher(dataCh, func(s string) {
messages.Update(func(list []string) []string {
return append(list, s)
})
})
```
--------------------------------
### Install tui CLI Tool
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/01-getting-started.md
Install the go-tui command-line interface tool, used for compiling .gsx files.
```bash
go install github.com/grindlemire/go-tui/cmd/tui@latest
```
--------------------------------
### vim-plug Installation for GSX Plugin
Source: https://github.com/grindlemire/go-tui/blob/main/editor/nvim/README.md
Install the GSX plugin using vim-plug, specifying the runtime path.
```vim
Plug 'grindlemire/go-tui', { 'rtp': 'editor/nvim' }
```
--------------------------------
### Point Operations Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/layout.md
Example usage of Point's Add and In methods. Initialize points and a rectangle, then perform operations to see the results.
```go
a := tui.Point{X: 10, Y: 5}
b := tui.Point{X: 3, Y: 2}
c := a.Add(b) // {X: 13, Y: 7}
r := tui.NewRect(0, 0, 80, 24)
a.In(r) // true
```
--------------------------------
### Complete Focus Group Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/focus.md
Demonstrates a three-panel layout with FocusGroup-driven Tab cycling. Each panel highlights its border when active. This example requires the go-tui library.
```go
package main
import (
"fmt"
tui "github.com/grindlemire/go-tui"
)
type panels struct {
panelA *tui.State[bool]
panelB *tui.State[bool]
panelC *tui.State[bool]
focusGroup *tui.FocusGroup
}
func Panels() *panels {
a := tui.NewState(false)
b := tui.NewState(false)
c := tui.NewState(false)
return &panels{
panelA: a,
panelB: b,
panelC: c,
focusGroup: tui.MustNewFocusGroup(a, b, c),
}
}
func (p *panels) KeyMap() tui.KeyMap {
km := p.focusGroup.KeyMap()
km = append(km,
tui.On(tui.KeyEscape, func(ke tui.KeyEvent) {
ke.App().Stop()
}),
)
return km
}
func panelStyle(active bool) string {
if active {
return "text-cyan font-bold"
}
return "font-dim"
}
func panelBorder(active bool) tui.Style {
if active {
return tui.NewStyle().Foreground(tui.ANSIColor(tui.Cyan))
}
return tui.NewStyle().Foreground(tui.ANSIColor(tui.White))
}
templ (p *panels) Render() {
}
templ Panel(title string, active bool) {
{title}
if active {
{fmt.Sprintf("%s is active", title)}
} else {
Press Tab to focus
}
}
```
--------------------------------
### Complete GSX Application Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/02-gsx-syntax.md
This GSX file demonstrates a full application with helper functions, a pure component, a stateful struct component, and rendering logic. It's designed to showcase various GSX syntax features in a cohesive example.
```gsx
package main
import (
"fmt"
tui "github.com/grindlemire/go-tui"
)
// Helper function: formats an item label
func itemLabel(index int, name string, selected bool) string {
prefix := " "
if selected {
prefix = "> "
}
return fmt.Sprintf("%s%d. %s", prefix, index+1, name)
}
// Helper function: returns a style class based on selection
func itemClass(selected bool) string {
if selected {
return "text-cyan font-bold"
}
return ""
}
// Pure component with children slot
templ Panel(title string) {
{title}
{children...}
}
// Struct component with state and key handling
type listApp struct {
items []string
selected *tui.State[int]
}
func ListApp() *listApp {
return &listApp{
items: []string{"Alpha", "Bravo", "Charlie", "Delta"},
selected: tui.NewState(0),
}
}
func (l *listApp) KeyMap() tui.KeyMap {
return tui.KeyMap{
tui.On(tui.KeyEscape, func(ke tui.KeyEvent) { ke.App().Stop() }),
tui.On(tui.KeyUp, func(ke tui.KeyEvent) {
l.selected.Update(func(v int) int {
if v > 0 {
return v - 1
}
return v
})
}),
tui.On(tui.KeyDown, func(ke tui.KeyEvent) {
l.selected.Update(func(v int) int {
if v < len(l.items)-1 {
return v + 1
}
return v
})
}),
}
}
templ (l *listApp) Render() {
@Panel("Select an Item") {
for i, item := range l.items {
{itemLabel(i, item, i == l.selected.Get())}
}
if l.selected.Get() >= 0 {
{fmt.Sprintf("Selected: %s", l.items[l.selected.Get()])}
}
}
}
```
--------------------------------
### Set Cell Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/buffer.md
Demonstrates setting a cell at the top-left corner with a bold 'X' character.
```go
buf.SetCell(0, 0, tui.NewCell('X', tui.NewStyle().Bold()))
```
--------------------------------
### Build and Run Markdown Example
Source: https://github.com/grindlemire/go-tui/blob/main/examples/24-markdown/README.md
Commands to generate the markdown GMX file and then run the tui application.
```bash
go run ../../cmd/tui generate markdown.gsx
go run .
```
--------------------------------
### Example GSX Component with go-tui
Source: https://github.com/grindlemire/go-tui/blob/main/editor/vscode/README.md
This example demonstrates a Counter component using go-tui. It includes state management, event handling for buttons and keyboard input, and rendering the UI. The component uses templ syntax for defining its structure and behavior.
```gsx
package main
import (
"fmt"
tui "github.com/grindlemire/go-tui"
)
type counter struct {
count *tui.State[int]
incBtn *tui.Ref
decBtn *tui.Ref
}
func Counter() *counter {
return &counter{
count: tui.NewState(0),
incBtn: tui.NewRef(),
decBtn: tui.NewRef(),
}
}
func (c *counter) KeyMap() tui.KeyMap {
return tui.KeyMap{
tui.On(tui.Rune('+'), func(ke tui.KeyEvent) { c.count.Update(func(v int) int { return v + 1 }) }),
tui.On(tui.Rune('-'), func(ke tui.KeyEvent) { c.count.Update(func(v int) int { return v - 1 }) }),
tui.On(tui.Rune('q'), func(ke tui.KeyEvent) { ke.App().Stop() }),
}
}
func (c *counter) HandleMouse(me tui.MouseEvent) bool {
return tui.HandleClicks(me,
tui.Click(c.incBtn, func() { c.count.Update(func(v int) int { return v + 1 }) }),
tui.Click(c.decBtn, func() { c.count.Update(func(v int) int { return v - 1 }) }),
)
}
templ (c *counter) Render() {
{fmt.Sprintf("Count: %d", c.count.Get())}
+/- or click buttons, q to quit
}
```
--------------------------------
### Main Function Setup
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/16-streaming.md
Sets up the main application entry point, including creating a data channel and initializing the streaming application. This is used to run the live stream viewer.
```go
package main
import (
"fmt"
"math/rand"
"os"
"time"
tui "github.com/grindlemire/go-tui"
)
func main() {
```
--------------------------------
### Project Setup with Go Modules
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/20-animation.md
Sets up a new project directory, initializes Go modules, and fetches the go-tui library. This is the initial step for creating a new go-tui animation project.
```bash
mkdir animation && cd animation
go mod init animation
go get github.com/grindlemire/go-tui
```
--------------------------------
### Background Gradient Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/03-styling.md
Create background gradients using classes like `bg-gradient-{start}-{end}`. This example shows a blue-to-cyan horizontal gradient with white text.
```gsx
Blue-to-cyan background
```
--------------------------------
### Initialize Project and Add Dependency
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/01-getting-started.md
Create a new project directory, initialize Go modules, and add the go-tui dependency.
```bash
mkdir hello-tui && cd hello-tui
go mod init hello-tui
go get github.com/grindlemire/go-tui
```
--------------------------------
### Get Buffer Rectangle
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/buffer.md
Returns the buffer's boundaries as a Rect object, starting at coordinates (0, 0).
```go
func (b *Buffer) Rect() Rect
```
--------------------------------
### Go Main Application Setup
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/02-gsx-syntax.md
This Go file sets up and runs the TUI application. It initializes the app with the root component and handles potential errors during startup and execution.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(
tui.WithRootComponent(ListApp()),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Project Setup Commands
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/18-dashboard.md
Initialize a new Go module for the dashboard project and fetch the necessary go-tui library.
```bash
mkdir dashboard && cd dashboard
go mod init dashboard
go get github.com/grindlemire/go-tui
```
--------------------------------
### Get Stop Channel
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/app.md
Returns a channel that is closed when the application terminates. This is intended for manual watcher setup; using `WatcherProvider` on components is the preferred approach.
```go
func (a *App) StopCh() <-chan struct{}
```
--------------------------------
### Main Application Setup for Stream Demo
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/17-inline-streaming.md
Sets up the main application with a specific inline height and the root component for the streaming demo. Handles application errors during initialization and execution.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(
tui.WithInlineHeight(3),
tui.WithRootComponent(StreamDemo()),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Main Application Setup
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/10-scrolling.md
This Go code sets up the main application using go-tui, providing the scrollable file list as the root component and enabling mouse support. It handles potential errors during app initialization and execution.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(
tui.WithRootComponent(FileList()),
tui.WithMouse(),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Text Gradient Examples
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/03-styling.md
Apply text gradients using classes like `text-gradient-{start}-{end}`. You can specify horizontal, vertical, or diagonal directions.
```gsx
Horizontal gradient (default)Explicit horizontalVertical gradientDiagonal downDiagonal up
```
--------------------------------
### Border Gradient Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/03-styling.md
Apply gradients to borders using classes like `border-gradient-{start}-{end}`. The gradient animates around the border's perimeter.
```gsx
Gradient border
```
--------------------------------
### Configure App with Root Component and Frame Rate
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/app.md
This example shows how to create a new App instance with specific configurations. It sets a root component and a custom frame rate for rendering. Use AppOption functions to customize behavior.
```go
app, err := tui.NewApp(
tui.WithRootComponent(MyApp()),
tui.WithFrameRate(30),
)
```
--------------------------------
### Get Event Queue Channel
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/app.md
Provides access to the event queue channel for manual watcher setup. It is recommended to use `WatcherProvider` on components instead for managing watchers.
```go
func (a *App) EventQueue() chan<- func()
```
--------------------------------
### Go-TUI Main Application Entry Point
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/06-state.md
Sets up and runs the go-tui application. It initializes the demo application and starts the TUI event loop.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
```
--------------------------------
### Apply Horizontal Gradient Text with GSX
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/styling.md
Use GSX classes like `text-gradient-{start}-{end}` for horizontal text gradients. Example uses cyan and magenta.
```gsx
Horizontal gradient text
```
--------------------------------
### Apply Vertical Gradient Text with GSX
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/styling.md
Use GSX classes like `text-gradient-{start}-{end}-{direction}` with `-v` for vertical text gradients. Example uses red and yellow.
```gsx
Vertical gradient text
```
--------------------------------
### Single-Frame Printing with go-tui
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/llm.md
Examples of rendering go-tui components to standard output or as strings without starting an interactive application. Supports printing to stdout, returning as ANSI string, or writing to an io.Writer.
```go
// Print to stdout (auto-detects terminal width, falls back to 80)
tui.Print(MyComponent("hello"))
// Return as ANSI string (no trailing newline)
s := tui.Sprint(view, tui.WithPrintWidth(80))
// Write to any io.Writer (appends trailing newline)
tui.Fprint(w, view, tui.WithPrintWidth(120))
```
--------------------------------
### Main Application Entry Point in Go
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/22-event-loop.md
This Go code sets up the main application entry point, handling command-line arguments to select different modes ('run', 'step', 'select') and initiating the corresponding mode's execution.
```go
package main
import (
"fmt"
"os"
"time"
tui "github.com/grindlemire/go-tui"
)
//go:generate go run ../../cmd/tui generate feed.gsx
func main() {
mode := "run"
if len(os.Args) > 1 {
mode = os.Args[1]
}
switch mode {
case "run":
runMode()
case "step":
stepMode()
case "select":
selectMode()
default:
fmt.Fprintf(os.Stderr, "Unknown mode %q. Use: run, step, or select\n", mode)
os.Exit(1)
}
}
func startProducer(paused func() bool) <-chan string {
ch := make(chan string, 10)
go func() {
for i := 1; ; i++ {
time.Sleep(200 * time.Millisecond)
if paused() {
continue
}
select {
```
--------------------------------
### Main Application Entry Point (Go)
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/18-dashboard.md
Sets up and runs the Go-TUI application, initializing it with the Dashboard component as the root.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(
tui.WithRootComponent(Dashboard()),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create app: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "App error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Terminal Interface and ANSI Implementation
Source: https://github.com/grindlemire/go-tui/blob/main/design.md
Defines the Terminal interface for abstracting terminal operations like getting size, flushing buffers, clearing, cursor manipulation, and raw mode. An example ANSITerminal implementation using ANSI escape sequences is also provided.
```go
// pkg/tui/terminal.go
type Terminal interface {
Size() (width, height int)
Flush(buf *Buffer)
Clear()
SetCursor(x, y int)
HideCursor()
ShowCursor()
EnableRawMode() error
DisableRawMode() error
}
// pkg/tui/terminal_ansi.go
type ANSITerminal struct {
out io.Writer
in io.Reader
oldState *term.State // from golang.org/x/term if needed, or raw syscall
}
```
--------------------------------
### Create and Run a New App
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/app.md
This snippet demonstrates the typical setup for a go-tui application. It creates a new App with a root component and then runs the application's event loop. Ensure to handle potential errors during app creation and execution.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(
tui.WithRootComponent(MyApp()),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Create go-tui Application Entry Point
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/01-getting-started.md
Sets up the main application using tui.NewApp, providing the root component and handling errors.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(
tui.WithRootComponent(Hello()),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Initializer Interface
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/07-components.md
Implement this interface to run setup code when a component first mounts. The returned function, if non-nil, runs when the component leaves the tree.
```go
type Initializer interface {
Init() func()
}
```
--------------------------------
### Key Matching Examples
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/08-events.md
Demonstrates different ways to match keys in a KeyMap. This includes matching special keys like Escape, specific printable characters like 'q', and any printable character using AnyRune.
```go
func (a *myApp) KeyMap() tui.KeyMap {
return tui.KeyMap{
// Match the Escape key (special key)
tui.On(tui.KeyEscape, func(ke tui.KeyEvent) { ke.App().Stop() }),
// Match the 'q' character (printable rune)
tui.On(tui.Rune('q'), func(ke tui.KeyEvent) { ke.App().Stop() }),
// Match any printable character
tui.On(tui.AnyRune,func(ke tui.KeyEvent) {
a.lastChar.Set(string(ke.Rune))
}),
}
}
```
--------------------------------
### Verify Tree-sitter Parser Installation
Source: https://github.com/grindlemire/go-tui/blob/main/editor/nvim/README.md
Check the installation status of tree-sitter parsers, specifically looking for 'gsx'.
```vim
:TSInstallInfo
```
--------------------------------
### Main Application Setup for Directory Tree TUI
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/21-directory-tree.md
Initializes and runs the go-tui application, setting up the directory tree component and handling command-line arguments for the root directory.
```go
package main
import (
"fmt"
"os"
"path/filepath"
tui "github.com/grindlemire/go-tui"
)
func main() {
root := "."
if len(os.Args) > 1 {
root = os.Args[1]
}
absRoot, err := filepath.Abs(root)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
app, err := tui.NewApp(
tui.WithRootComponent(DirectoryTree(absRoot)),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Key Constants Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/events.md
Illustrates the usage of special key constants like KeyEscape, KeyEnter, and KeyRune for event handling.
```go
// Example usage within a handler (not a direct snippet from source, but illustrative)
// tui.On(tui.KeyEnter, func(ke tui.KeyEvent) {
// fmt.Println("Enter pressed")
// })
// KeyRune example:
// tui.On(tui.KeyRune, func(ke tui.KeyEvent) {
// if ke.IsRune() {
// fmt.Printf("Rune typed: %c\n", ke.Rune)
// }
// })
```
--------------------------------
### Modal GSX Usage Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/built-in-components.md
Example of using the component in GSX. Controls positioning and content styling.
```gsx
Title
```
--------------------------------
### Sprint: Get ANSI String Output
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/19-print.md
Shows how to use tui.Sprint to get the ANSI-styled string representation of a component.
```go
s := tui.Sprint(view, tui.WithPrintWidth(80))
fmt.Println(s) // you decide where it goes
```
--------------------------------
### Clone go-tui Repository
Source: https://github.com/grindlemire/go-tui/blob/main/editor/vscode/README.md
Clone the go-tui repository to install the extension from source. This is the first step in the manual installation process.
```bash
git clone https://github.com/grindlemire/go-tui.git
```
--------------------------------
### Feed DataItem Watcher Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/watchers.md
Example of using the Watch convenience function to process DataItem from a channel and append them to a list.
```go
func (f *feed) Watchers() []tui.Watcher {
return []tui.Watcher{
tui.Watch(f.dataCh, func(item DataItem) {
f.items.Update(func(list []DataItem) []DataItem {
return append(list, item)
})
}),
}
}
```
--------------------------------
### Creating a TUI Element with Options
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/llm.md
Demonstrates programmatic element creation using various configuration options like size, alignment, styling, and behavior.
```go
el := tui.New(
tui.WithWidth(30),
tui.WithHeight(10),
tui.WithWidthPercent(50),
tui.WithWidthAuto(),
tui.WithMinWidth(10),
tui.WithMaxWidth(60),
tui.WithDirection(tui.Column),
tui.WithJustify(tui.JustifyCenter),
tui.WithAlign(tui.AlignCenter),
tui.WithGap(2),
tui.WithFlexGrow(1.0),
tui.WithFlexShrink(0),
tui.WithPadding(2),
tui.WithMargin(1),
tui.WithBorder(tui.BorderRounded),
tui.WithBackground(tui.Cyan),
tui.WithText("content"),
tui.WithTextStyle(tui.NewStyle().Bold()),
tui.WithTextAlign(tui.TextAlignCenter),
tui.WithScrollable(tui.ScrollVertical),
tui.WithFocusable(true),
tui.WithHidden(true),
tui.WithTruncate(true),
tui.WithTextGradient(tui.NewGradient(tui.Cyan, tui.Magenta)),
tui.WithBackgroundGradient(tui.NewGradient(tui.Blue, tui.Cyan)),
tui.WithBorderGradient(tui.NewGradient(tui.Cyan, tui.Magenta)),
)
```
--------------------------------
### go-tui PrintOption Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/llm.md
Demonstrates the use of `WithPrintWidth` option for controlling the output width when printing go-tui components.
```go
// PrintOption
tui.WithPrintWidth(w int) // Explicit width; default: auto-detect, fallback 80
```
--------------------------------
### Struct Component Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/07-components.md
Example of a struct component (UserProfile) that uses pure components for rendering user profile information.
```go
type userProfile struct {
name string
role string
email string
}
func UserProfile(name, role, email string) *userProfile {
return &userProfile{name: name, role: role, email: email}
}
func (u *userProfile) KeyMap() tui.KeyMap {
return tui.KeyMap{
tui.On(tui.KeyEscape, func(ke tui.KeyEvent) { ke.App().Stop() }),
}
}
templ (u *userProfile) Render() {
}
```
--------------------------------
### Go-TUI Application Setup
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/09-refs-and-clicks.md
This Go code sets up a new TUI application, specifying the root component and handling potential errors during initialization and execution.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(
tui.WithRootComponent(ColorMixer()),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create app: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "App error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Main Application Setup for Go-TUI
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/07-components.md
This snippet initializes and runs a Go-TUI application, setting the root component and handling potential errors during startup and execution. It ensures the application is properly closed using defer.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(
tui.WithRootComponent(Dashboard()),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Conventional Commit Examples
Source: https://github.com/grindlemire/go-tui/blob/main/CLAUDE.md
Examples of using gcommit with conventional commit format for various types of changes, including breaking changes.
```bash
gcommit -m "feat: add table element support"
```
```bash
gcommit -m "fix(layout): correct flexbox gap calculation"
```
```bash
gcommit -m "feat!: change State API to require type parameter"
```
```bash
gcommit -m "chore: update golang.org/x dependencies"
```
--------------------------------
### Go-TUI Application Setup
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/08-events.md
This Go code sets up a new tui.App with the Explorer component as the root. It handles potential errors during app creation and execution. Ensure you have the tui library imported.
```go
package main
import (
"fmt"
"os"
tui "github.com/grindlemire/go-tui"
)
func main() {
app, err := tui.NewApp(
tui.WithRootComponent(Explorer()),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
defer app.Close()
if err := app.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
--------------------------------
### Programmatic Styling Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/guides/03-styling.md
Demonstrates how to use programmatic styles to dynamically color text based on integer values. This is useful for runtime-dependent styling.
```go
package main
import (
"fmt"
tui "github.com/grindlemire/go-tui"
)
type statusApp struct {
value *tui.State[int]
}
func StatusApp() *statusApp {
return &statusApp{
value: tui.NewState(0),
}
}
func (s *statusApp) KeyMap() tui.KeyMap {
return tui.KeyMap{
tui.On(tui.KeyEscape, func(ke tui.KeyEvent) { ke.App().Stop() }),
tui.On(tui.Rune('+'), func(ke tui.KeyEvent) {
s.value.Update(func(v int) int { return v + 1 })
}),
tui.On(tui.Rune('-'), func(ke tui.KeyEvent) {
s.value.Update(func(v int) int { return v - 1 })
}),
}
}
func valueStyle(v int) tui.Style {
if v > 0 {
return tui.NewStyle().Bold().Foreground(tui.Green)
}
if v < 0 {
return tui.NewStyle().Bold().Foreground(tui.Red)
}
return tui.NewStyle().Dim()
}
templ (s *statusApp) Render() {
{fmt.Sprintf("Value: %d", s.value.Get())}Press + / - to change, Esc to quit
}
```
--------------------------------
### Calculate Function Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/layout.md
Example of using the Calculate function to perform layout on a root element. After calculation, you can retrieve the computed Rect and ContentRect.
```go
root := tui.New(
tui.WithDirection(tui.Column),
tui.WithText("Hello"),
)
tui.Calculate(root, 80, 24)
r := root.Rect() // computed border box
cr := root.ContentRect() // computed content area
```
--------------------------------
### Start Method Signature
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/reference/watchers.md
Called automatically by the framework to start a watcher. It fires the handler once, binds to future changes, and launches a goroutine for shutdown.
```go
func (w *stateWatcher[T]) Start(eventQueue chan<- func(), stopCh <-chan struct{})
```
--------------------------------
### Bottom Sheet Modal Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/llm.md
Example of a bottom sheet modal variant, aligned to the bottom and without backdrop click to close. Useful for actions.
```gsx
Action?
```
--------------------------------
### Building the CLI Application
Source: https://github.com/grindlemire/go-tui/blob/main/CLAUDE.md
Compile the main application binary, outputting it as 'tui' in the current directory.
```bash
go build -o tui ./cmd/tui
```
--------------------------------
### Modal Dialog Example
Source: https://github.com/grindlemire/go-tui/blob/main/docs/content/llm.md
Example of a modal dialog with confirmation buttons, designed to be centered. Modals require full-screen mode and are ignored in inline mode.
```gsx