### Basic Viewport Usage Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md A complete example demonstrating how to initialize and use the Viewport component within a Bubble Tea application, including setting content and handling window resizing. ```go package main import ( "fmt" "log" "strings" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/viewport" ) type Model struct { viewport viewport.Model } func (m Model) Init() tea.Cmd { return nil } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { var cmd tea.Cmd m.viewport, cmd = m.viewport.Update(msg) sswitch msg := msg.(type) { case tea.KeyPressMsg: switch msg.String() { case "q", "ctrl+c": return m, tea.Quit } case tea.WindowSizeMsg: m.viewport.SetWidth(msg.Width) m.viewport.SetHeight(msg.Height - 2) } return m, cmd } func (m Model) View() string { return fmt.Sprintf( "%s\n%s", m.viewport.View(), "(press q to quit)", ) } func main() { vp := viewport.New( viewport.WithWidth(80), viewport.WithHeight(24), ) // Long content content := strings.Repeat("Line of text\n", 50) vp.SetContent(content) m := Model{viewport: vp} p := tea.NewProgram(m) if _, err := p.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Full FilePicker Usage Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/filepicker.md A complete example demonstrating how to integrate the FilePicker into a Bubble Tea application. It shows initialization, handling user input, window resizing, and file selection. ```go package main import ( "fmt" "log" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/filepicker" ) type Model struct { filepicker filepicker.Model selectedFile string done bool } func (m Model) Init() tea.Cmd { return m.filepicker.Init() } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: switch msg.String() { case "q", "esc": m.done = true return m, tea.Quit } case tea.WindowSizeMsg: m.filepicker.SetHeight(msg.Height - 4) } var cmd tea.Cmd m.filepicker, cmd = m.filepicker.Update(msg) // A file was selected if m.filepicker.Path != "" { m.selectedFile = m.filepicker.Path m.done = true return m, tea.Quit } return m, cmd } func (m Model) View() string { if m.done { return fmt.Sprintf("Selected: %s\n", m.selectedFile) } return m.filepicker.View() } func main() { fp := filepicker.New() fp.AllowedTypes = []string{'.txt', '.md', '.go'} fp.DirAllowed = false fp.FileAllowed = true fp.ShowHidden = false m := Model{filepicker: fp} p := tea.NewProgram(m) if _, err := p.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Start Stopwatch Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/stopwatch.md The `Start` method returns a Tea command that will start the stopwatch. This is used to initiate the counting process. ```go func (m Model) Start() tea.Cmd { return m.start() } ``` -------------------------------- ### Full Usage Example of Key Bindings Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/key.md This example demonstrates a complete Bubble Tea application with custom key bindings for navigation and quitting. It shows how to define a KeyMap, initialize it with default bindings, and use `key.Matches` in the Update function to handle key presses. ```go package main import ( "fmt" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/key" ) type KeyMap struct { Up key.Binding Down key.Binding Quit key.Binding } func (k KeyMap) ShortHelp() []key.Binding { return []key.Binding{k.Up, k.Down, k.Quit} } func (k KeyMap) FullHelp() [][]key.Binding { return [][]key.Binding{{k.Up, k.Down}, {k.Quit}} } var DefaultKeyMap = KeyMap{ Up: key.NewBinding( key.WithKeys("k", "up"), key.WithHelp("↑/k", "move up"), ), Down: key.NewBinding( key.WithKeys("j", "down"), key.WithHelp("↓/j", "move down"), ), Quit: key.NewBinding( key.WithKeys("q", "ctrl+c"), key.WithHelp("q", "quit"), ), } type Model struct { position int keyMap KeyMap } func (m Model) Init() tea.Cmd { return nil } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: switch { case key.Matches(msg, m.keyMap.Up): m.position-- case key.Matches(msg, m.keyMap.Down): m.position++ case key.Matches(msg, m.keyMap.Quit): return m, tea.Quit } } return m, nil } func (m Model) View() string { return fmt.Sprintf("Position: %d\nPress q to quit\n", m.position) } func main() { m := Model{keyMap: DefaultKeyMap} p := tea.NewProgram(m) if _, err := p.Run(); err != nil { panic(err) } } ``` -------------------------------- ### Full Progress Bar Usage Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/progress.md A complete example demonstrating how to use the Progress component within a Bubble Tea application. It includes initialization, updating progress over time, and handling user input. ```go package main import ( "fmt" "log" "time" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/progress" "charm.land/lipgloss/v2" ) type Model struct { progress progress.Model done bool } func (m Model) Init() tea.Cmd { return tea.Tick(100*time.Millisecond, func(t time.Time) tea.Msg { return tickMsg{} }) } type tickMsg struct{} func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: if msg.String() == "q" { m.done = true } case progress.FrameMsg: var cmd tea.Cmd m.progress, cmd = m.progress.Update(msg) return m, cmd case tickMsg: if !m.done { current := m.progress.Value() m.progress.SetValue(current + 0.01) return m, tea.Tick(100*time.Millisecond, func(t time.Time) tea.Msg { return tickMsg{} }) } } return m, nil } func (m Model) View() string { if m.done { return "Done!\n" } return fmt.Sprintf("Loading: %s\n", m.progress.View()) } func main() { p := progress.New( progress.WithDefaultBlend(), progress.WithWidth(50), ) m := Model{progress: p} prog := tea.NewProgram(m) if _, err := prog.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Direct Cursor Usage Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/cursor.md Demonstrates how to use the cursor component directly to build a custom text editing interface. This example shows how to manage text, cursor position, and handle key presses for editing. ```go package main import ( "fmt" "log" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/cursor" "charm.land/lipgloss/v2" ) type Model struct { cursor cursor.Model text []rune position int } func (m Model) Init() tea.Cmd { return m.cursor.Focus() } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { var cmd tea.Cmd switch msg := msg.(type) { case tea.KeyPressMsg: switch msg.String() { case "left": if m.position > 0 { m.position-- } case "right": if m.position < len(m.text) { m.position++ } case "backspace": if m.position > 0 { m.text = append(m.text[:m.position-1], m.text[m.position:]...) m.position-- } case "q": return m, tea.Quit default: m.text = append(m.text[:m.position], append([]rune(msg.String()), m.text[m.position:]...)...) m.position++ } } m.cursor, cmd = m.cursor.Update(msg) return m, cmd } func (m Model) View() string { // Build text with cursor before := string(m.text[:m.position]) char := " " if m.position < len(m.text) { char = string(m.text[m.position]) } after := string(m.text[m.position+1:]) m.cursor.SetChar(char) return fmt.Sprintf( "Text: %s%s%s\n(q to quit)\n", before, m.cursor.View(), after, ) } func main() { m := Model{ cursor: cursor.New(), text: []rune{}, } m.cursor.Style = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("205")) p := tea.NewProgram(m) if _, err := p.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Initialize and Configure TextArea Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textarea.md Example of creating a new textarea, setting its prompt and line number visibility, and then focusing it for user input. ```go ta := textarea.New() ta.Prompt = "> " ta.ShowLineNumbers = true ta.Focus() ``` -------------------------------- ### Stopwatch Usage Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/stopwatch.md A complete example demonstrating how to integrate and use the Stopwatch component within a Bubble Tea application. It shows initialization, handling user input for control, and rendering the stopwatch's state. ```go package main import ( "fmt" "log" "time" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/stopwatch" ) type Model struct { stopwatch stopwatch.Model done bool } func (m Model) Init() tea.Cmd { return m.stopwatch.Init() } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: switch msg.String() { case "q": m.done = true case " ": return m, m.stopwatch.Toggle() case "r": return m, m.stopwatch.Reset() } case stopwatch.TickMsg: var cmd tea.Cmd m.stopwatch, cmd = m.stopwatch.Update(msg) return m, cmd } return m, nil } func (m Model) View() string { if m.done { return "Goodbye!\n" } status := "stopped" if m.stopwatch.Running() { status = "running" } return fmt.Sprintf( "Elapsed: %s (%s)\nSpace: toggle, R: reset, Q: quit\n", m.stopwatch.View(), status, ) } func main() { m := Model{ stopwatch: stopwatch.New( stopwatch.WithInterval(100*time.Millisecond), ), } p := tea.NewProgram(m) if _, err := p.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Viewport Gutter Function Example (Line Numbers) Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md This example demonstrates how to create a GutterFunc to display line numbers in the viewport. It handles soft wrapping and indicates lines beyond the total content. ```go func(info viewport.GutterContext) string { if info.Soft { return " │ " } if info.Index >= info.TotalLines { return " ~ │ " } return fmt.Sprintf("%4d │ ", info.Index+1) } ``` -------------------------------- ### Initialize Progress Bar with Custom Width and Colors Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/progress.md Example demonstrating how to create a progress bar with a specified width and custom gradient colors using the New and WithOptions functions. ```go progress := progress.New( progress.WithWidth(50), progress.WithColors(lipgloss.Color("#5A56E0"), lipgloss.Color("#EE6FF8")), ) ``` -------------------------------- ### FilePicker State Management Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/filepicker.md Demonstrates how to save and restore the FilePicker's cursor position and current directory during navigation. ```go // Save state before navigating savedCursor := m.filepicker.Cursor() // Navigate m.filepicker.CurrentDirectory = "/some/path" // Picker handles restoring cursor position ``` -------------------------------- ### Move Cursor to Start Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textinput.md Moves the cursor to the beginning of the input field. ```go func (m *Model) CursorStart(){ } ``` -------------------------------- ### Table Usage Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/table.md A complete Bubble Tea application demonstrating the integration and usage of the Table component. It shows initialization, updating, and rendering. ```go package main import ( "fmt" "log" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/table" ) type Model struct { table table.Model } func (m Model) Init() tea.Cmd { return nil } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { var cmd tea.Cmd m.table, cmd = m.table.Update(msg) sswitch msg := msg.(type) { case tea.KeyPressMsg: switch msg.String() { case "q", "esc", "ctrl+c": return m, tea.Quit } case tea.WindowSizeMsg: m.table.SetWidth(msg.Width) m.table.SetHeight(msg.Height - 4) } return m, cmd } func (m Model) View() string { return fmt.Sprintf( "Table\n%s\n(Press q to quit)", m.table.View(), ) } func main() { columns := []table.Column{ {Title: "ID", Width: 4}, {Title: "Name", Width: 15}, {Title: "Country", Width: 10}, } rows := []table.Row{ {"1", "Ramsés II", "Egypt"}, {"2", "Ramesses III", "Egypt"}, {"3", "Khafre", "Egypt"}, } t := table.New( table.WithColumns(columns), table.WithRows(rows), table.WithHeight(7), table.WithFocused(true), ) m := Model{table: t} p := tea.NewProgram(m) if _, err := p.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Basic Text Input Usage Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textinput.md A complete Bubble Tea application demonstrating the basic usage of the textinput component, including initialization, focus, and handling user input. ```go package main import ( "fmt" "log" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/textinput" ) type Model struct { input textinput.Model } func (m Model) Init() tea.Cmd { return m.input.Focus() } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: if msg.String() == "enter" { return m, tea.Quit } } var cmd tea.Cmd m.input, cmd = m.input.Update(msg) return m, cmd } func (m Model) View() string { return fmt.Sprintf( "Enter your name:\n%s\n(press enter to quit)\n", m.input.View(), ) } func main() { input := textinput.New() input.Placeholder = "Jane Doe" input.Focus() m := Model{input: input} p := tea.NewProgram(m) if _, err := p.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Initialize Stopwatch Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/stopwatch.md The `Init` method initializes the stopwatch and returns a command to send the first `TickMsg`, starting the timer. ```go func (m Model) Init() tea.Cmd { return m.Start() // Assuming Start() returns the correct command } ``` -------------------------------- ### Companion Package Upgrades Source: https://github.com/charmbracelet/bubbles/blob/main/UPGRADE_GUIDE_V2.md Upgrade Bubble Tea, Bubbles, and Lip Gloss together to their v2 versions using go get. ```sh go get charm.land/bubbletea/v2@latest go get charm.land/bubbles/v2@latest go get charm.land/lipgloss/v2@latest ``` -------------------------------- ### Basic Textarea Usage Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textarea.md This Go code demonstrates a basic usage of the Textarea component within a Bubbletea application. It shows how to initialize, update, and view the textarea, and how to handle user input and submission. ```go package main import ( "fmt" "log" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/textarea" "charm.land/lipgloss/v2" ) type Model struct { textarea textarea.Model done bool } func (m Model) Init() tea.Cmd { return m.textarea.Focus() } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: if msg.String() == "ctrl+c" { m.done = true } } var cmd tea.Cmd m.textarea, cmd = m.textarea.Update(msg) return m, cmd } func (m Model) View() string { if m.done { return fmt.Sprintf("Final content:\n%s\n", m.textarea.Value()) } return fmt.Sprintf( "Compose your message (Ctrl+C to submit):\n%s\n", m.textarea.View(), ) } func main() { ta := textarea.New() ta.Prompt = "> " ta.Placeholder = "Enter your text here..." ta.ShowLineNumbers = true ta.SetWidth(60) ta.SetHeight(10) m := Model{textarea: ta} p := tea.NewProgram(m) if _, err := p.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Full Paginator Usage Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/paginator.md A complete Bubble Tea application demonstrating how to use the Paginator component to display and navigate through a list of items. Includes initialization, update logic for navigation, and view rendering. ```go package main import ( "fmt" "log" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/paginator" ) type Model struct { paginator paginator.Model data []string } func (m Model) Init() tea.Cmd { return nil } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { var cmd tea.Cmd m.paginator, cmd = m.paginator.Update(msg) switch msg := msg.(type) { case tea.KeyPressMsg: switch msg.String() { case "q", "ctrl+c": return m, tea.Quit } } return m, cmd } func (m Model) View() string { start, end := m.paginator.GetSliceBounds(len(m.data)) pageData := m.data[start:end] output := "Items on this page:\n" for _, item := range pageData { output += fmt.Sprintf(" - %s\n", item) } output += "\n" + m.paginator.View() + "\n" output += "(h/l: prev/next page, q: quit)" return output } func main() { data := make([]string, 100) for i := 0; i < 100; i++ { data[i] = fmt.Sprintf("Item %d", i+1) } m := Model{ paginator: paginator.New( paginator.WithPerPage(5), ), data: data, } m.paginator.SetTotalPages(len(data)) m.paginator.Type = paginator.Dots p := tea.NewProgram(m) if _, err := p.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Get Current Styles Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textinput.md Returns the current style configuration for the text input. ```go func (m Model) Styles() Styles{ } ``` -------------------------------- ### Get Maximum Width Setting Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/help.md Returns the currently set maximum width for help display. ```go func (m Model) Width() int ``` -------------------------------- ### Configure Spinner with Lipgloss Style Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/spinner.md Applies a Lipgloss style to the spinner's output. The example demonstrates setting the spinner text to be bold. ```go spinner := spinner.New( spinner.WithStyle(lipgloss.NewStyle().Bold(true)), ) ``` -------------------------------- ### Set Focus and Get Command Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textinput.md Sets focus to the text input and returns a Bubble Tea command to apply the focus. ```go func (m *Model) Focus() tea.Cmd{ } ``` -------------------------------- ### Get Elapsed Time Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/stopwatch.md The `Elapsed` method returns the total duration that the stopwatch has been running. This value represents the accumulated time since the stopwatch was started or last reset. ```go func (m Model) Elapsed() time.Duration { return m.elapsed } ``` -------------------------------- ### Spinner Usage Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/spinner.md A complete Bubble Tea application demonstrating how to use the spinner component to show a loading indicator. The spinner ticks and updates its view until the user presses 'q' to quit. ```go package main import ( "fmt" "time" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/spinner" ) type Model struct { spinner spinner.Model done bool } func (m Model) Init() tea.Cmd { return m.spinner.Tick() } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: if msg.String() == "q" { m.done = true } case spinner.TickMsg: var cmd tea.Cmd m.spinner, cmd = m.spinner.Update(msg) return m, cmd } return m, nil } func (m Model) View() string { if m.done { return "Done!\n" } return fmt.Sprintf("Loading... %s\n", m.spinner.View()) } func main() { m := Model{spinner: spinner.New()} if _, err := tea.NewProgram(m).Run(); err != nil { panic(err) } } ``` -------------------------------- ### Get Slice Bounds for Current Page Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/paginator.md Returns the start and end indices for slicing a data slice based on the current page and PerPage settings. Useful for displaying data for the current page. ```go data := []Item{...} start, end := paginator.GetSliceBounds(len(data)) pageData := data[start:end] ``` -------------------------------- ### Focus Cursor and Start Blinking Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/cursor.md Generates a Bubble Tea command to focus the cursor, which will initiate its blinking behavior. ```go func (m *Model) Focus() tea.Cmd ``` -------------------------------- ### Help Model View Method Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/help.md Renders the help view based on the Model's ShowAll flag. It displays either the short or full keybindings provided by the KeyMap. Returns an empty string if no bindings are available. ```go func (m Model) View(k KeyMap) string { return help.View(myComponent.KeyMap) } ``` -------------------------------- ### Dynamic Color Function Example Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/progress.md Illustrates a dynamic color function for the progress bar that changes color based on progress thresholds: red below 30%, yellow below 70%, and green otherwise. ```go progress.WithColorFunc(func(total, current float64) color.Color { if total <= 0.3 { return lipgloss.Color("#FF0000") // Red } if total <= 0.7 { return lipgloss.Color("#FFFF00") // Yellow } return lipgloss.Color("#00FF00") // Green }) ``` -------------------------------- ### Get Default FilePicker Styles Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/filepicker.md Retrieves the default styling configuration for the FilePicker, providing sensible color defaults. ```go func DefaultStyles() Styles ``` -------------------------------- ### Configure File Picker Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/configuration.md Set up a file picker with options for allowed file types, visibility of hidden files, and selection modes. Customize cursor and auto-height behavior. ```go fp := filepicker.New() fp.CurrentDirectory = "." fp.AllowedTypes = []string{'.txt', '.md'} // File extensions fp.ShowHidden = false // Show dotfiles fp.DirAllowed = false // Allow selecting dirs fp.FileAllowed = true // Allow selecting files fp.ShowPermissions = true // Show chmod fp.ShowSize = true // Show file size fp.AutoHeight = true // Auto-size height fp.Cursor = ">" // Cursor character ``` -------------------------------- ### Create New Timer Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/timer.md Creates a new timer instance with a specified timeout duration and optional configurations. The timer starts running by default with a 1-second interval. ```go timer := timer.New(time.Second * 30, timer.WithInterval(100*time.Millisecond)) ``` -------------------------------- ### FilePicker Configuration: All Directories and Files Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/filepicker.md Configure the FilePicker to allow selection of both directories and files, with no type restrictions. ```go fp := filepicker.New() fp.DirAllowed = true fp.FileAllowed = true fp.AllowedTypes = []string{} ``` -------------------------------- ### XOffset Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md Gets the horizontal scroll offset in columns. ```APIDOC ## XOffset ### Description Returns the horizontal scroll offset in columns. ### Returns - Offset in columns (int) ``` -------------------------------- ### Help Component: Apply Styles Explicitly Source: https://github.com/charmbracelet/bubbles/blob/main/UPGRADE_GUIDE_V2.md Demonstrates how to apply default styles to the Help component, adapting to terminal background colors. ```go // Before h := help.New() // Colors auto-adapted to terminal background // After h := help.New() h.Styles = help.DefaultStyles(isDark) ``` -------------------------------- ### YOffset Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md Gets the vertical scroll offset in lines. ```APIDOC ## YOffset ### Description Returns the vertical scroll offset in lines. ### Returns - Offset in rows (int) ``` -------------------------------- ### Configure Table with Columns, Rows, and Dimensions Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/configuration.md Create a table component with defined columns, rows, and dimensions. This snippet shows how to set up the table with focus state and styling. ```go table := table.New( table.WithColumns([]table.Column{ {Title: "ID", Width: 10}, {Title: "Name", Width: 20}, }), table.WithRows(rows), table.WithHeight(20), table.WithWidth(60), table.WithFocused(true), ) ``` -------------------------------- ### HorizontalScrollPercent Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md Gets the horizontal scroll position as a percentage. ```APIDOC ## HorizontalScrollPercent ### Description Returns horizontal scroll position as a percentage (0.0 to 1.0). ### Returns - Scroll percentage (float64) ``` -------------------------------- ### Integrate Help Component with KeyMap Interface Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/help.md Demonstrates the integration pattern for the help component within a custom Bubble Tea component. Shows how to include the help model and render it in the view, and how to toggle help visibility. ```go // In your component type Model struct { KeyMap KeyMap Help help.Model } // In your view func (m Model) View() string { return fmt.Sprintf( "Content here\n\n%s", m.Help.View(m.KeyMap), ) } // Users can toggle help modes case key.Matches(msg, toggleHelpBinding): m.Help.ShowAll = !m.Help.ShowAll ``` -------------------------------- ### ScrollPercent Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md Gets the vertical scroll position as a percentage. ```APIDOC ## ScrollPercent ### Description Returns vertical scroll position as a percentage (0.0 to 1.0). ### Returns - Scroll percentage (float64) ``` -------------------------------- ### New Help Model Creation Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/help.md Creates a new help model with default settings. The ShowAll field can be modified after creation to control the display format. ```go func New() Model { help := help.New() help.ShowAll = true } ``` -------------------------------- ### Stopwatch Control Flow Commands Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/stopwatch.md Illustrates the various commands available to control the Stopwatch component. These include starting, stopping, toggling, resetting, checking the running state, and retrieving the elapsed time. ```go // Start the stopwatch cmd := m.stopwatch.Start() // Stop the stopwatch (doesn't reset) cmd := m.stopwatch.Stop() // Toggle between running/stopped cmd := m.stopwatch.Toggle() // Reset to zero and stop cmd := m.stopwatch.Reset() // Check if running if m.stopwatch.Running() { // Stopwatch is currently counting up } // Get elapsed time elapsed := m.stopwatch.Elapsed() fmt.Printf("Elapsed: %v\n", elapsed) ``` -------------------------------- ### Importing Bubbles v2 Components Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/README.md Demonstrates how to import various components from the Bubbles v2 library. ```go import ( "charm.land/bubbles/v2/spinner" "charm.land/bubbles/v2/textinput" // ... etc ) ``` -------------------------------- ### Get Textarea Styles Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textarea.md Returns the current styling configuration of the textarea. ```go func (m Model) Styles() Styles ``` -------------------------------- ### LineNumber Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textarea.md Gets the current line number the cursor is on. The line numbering is 1-based. ```APIDOC ## LineNumber ### Description Returns the current line number (1-based). ### Returns Line number ``` -------------------------------- ### Basic List Component Usage Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/list.md This Go code snippet demonstrates how to initialize and run a basic list component. It includes defining custom list items, a delegate for rendering, and handling basic key presses for quitting. ```go package main import ( "fmt" "log" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/list" "charm.land/lipgloss/v2" ) type Item string func (i Item) FilterValue() string { return string(i) } type ItemDelegate struct{} func (d ItemDelegate) Height() int { return 1 } func (d ItemDelegate) Spacing() int { return 0 } func (d ItemDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil } func (d ItemDelegate) Render(w *strings.Builder, m list.Model, index int, listItem list.Item) { i := listItem.(Item) if index == m.Index() { fmt.Fprint(w, "> "+string(i)) } else { fmt.Fprint(w, " "+string(i)) } } type Model struct { list list.Model } func (m Model) Init() tea.Cmd { return nil } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: if msg.String() == "q" { return m, tea.Quit } } var cmd tea.Cmd m.list, cmd = m.list.Update(msg) return m, cmd } func (m Model) View() string { return m.list.View() } func main() { items := []list.Item{ Item("First item"), Item("Second item"), Item("Third item"), } l := list.New(items, ItemDelegate{}, 80, 24) l.Title = "My List" m := Model{list: l} p := tea.NewProgram(m) if _, err := p.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Get Input Width Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textinput.md Returns the configured width of the text input field in columns. ```go func (m Model) Width() int{ } ``` -------------------------------- ### Create New Viewport with Options Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md Initializes a new viewport component with specified width and height configurations. This is the primary way to create a viewport instance. ```go vp := viewport.New( viewport.WithWidth(80), viewport.WithHeight(24), ) ``` -------------------------------- ### Column Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textarea.md Gets the current cursor column position on the active line. The column numbering is 0-based. ```APIDOC ## Column ### Description Returns the cursor column on the current line. ### Returns Column (0-based) ``` -------------------------------- ### Get Horizontal Scroll Offset Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md Returns the current horizontal scroll offset in terms of columns. ```go func (m Model) XOffset() int ``` -------------------------------- ### New Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/filepicker.md Creates a new file picker instance with default settings. You can then customize properties like allowed file types and selection behavior. ```APIDOC ## New ### Description Creates a new file picker with default settings. ### Returns - Model: Initialized Model ### Default Values - CurrentDirectory: "." - Cursor: ">" - AllowedTypes: [] (all files) - ShowPermissions: true - ShowSize: true - ShowHidden: false - DirAllowed: false - FileAllowed: true - AutoHeight: true ### Example ```go fp := filepicker.New() fp.AllowedTypes = []string{'.txt', '.md', '.go'} fp.DirAllowed = true ``` ``` -------------------------------- ### Get Vertical Scroll Offset Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md Returns the current vertical scroll offset in terms of lines. ```go func (m Model) YOffset() int ``` -------------------------------- ### Full Bubble Tea Application with Help Component Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/help.md A complete Bubble Tea application demonstrating the integration and usage of the help component, including keymap definitions, model structure, update logic, and view rendering. ```go package main import ( "fmt" tea "charm.land/bubbletea/v2" "charm.land/bubbles/v2/help" "charm.land/bubbles/v2/key" ) type KeyMap struct { Up key.Binding Down key.Binding Toggle key.Binding Quit key.Binding } func (km KeyMap) ShortHelp() []key.Binding { return []key.Binding{km.Up, km.Down, km.Toggle, km.Quit} } func (km KeyMap) FullHelp() [][]key.Binding { return [][]key.Binding{ {km.Up, km.Down}, {km.Toggle}, {km.Quit}, } } var DefaultKeyMap = KeyMap{ Up: key.NewBinding( key.WithKeys("k", "up"), key.WithHelp("k", "move up"), ), Down: key.NewBinding( key.WithKeys("j", "down"), key.WithHelp("j", "move down"), ), Toggle: key.NewBinding( key.WithKeys("space"), key.WithHelp("space", "toggle"), ), Quit: key.NewBinding( key.WithKeys("q", "ctrl+c"), key.WithHelp("q", "quit"), ), } type Model struct { keyMap KeyMap help help.Model pos int } func (m Model) Init() tea.Cmd { return nil } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: switch { case key.Matches(msg, m.keyMap.Up): if m.pos > 0 { m.pos-- } case key.Matches(msg, m.keyMap.Down): m.pos++ case key.Matches(msg, m.keyMap.Toggle): m.help.ShowAll = !m.help.ShowAll case key.Matches(msg, m.keyMap.Quit): return m, tea.Quit } case tea.WindowSizeMsg: m.help.SetWidth(msg.Width) } return m, nil } func (m Model) View() string { return fmt.Sprintf( "Position: %d\n\n%s\n", m.pos, m.help.View(m.keyMap), ) } func main() { m := Model{ keyMap: DefaultKeyMap, help: help.New(), } p := tea.NewProgram(m) if _, err := p.Run(); err != nil { panic(err) } } ``` -------------------------------- ### Integrate Key Bindings with Help Component Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/key.md Implement the `help.KeyMap` interface to automatically display key bindings and their associated help text in help menus. This enhances user discoverability. ```go type KeyMap struct { Up key.Binding Down key.Binding } // Implement help.KeyMap interface func (km KeyMap) ShortHelp() []key.Binding { return []key.Binding{km.Up, km.Down} } func (km KeyMap) FullHelp() [][]key.Binding { return [][]key.Binding{{km.Up, km.Down}} } ``` -------------------------------- ### Get FilePicker Height Setting Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/filepicker.md Retrieves the currently configured height setting for the FilePicker display. ```go func (m Model) Height() int ``` -------------------------------- ### Get Default FilePicker KeyMap Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/filepicker.md Retrieves the default key bindings for navigating and interacting with the FilePicker. ```go func DefaultKeyMap() KeyMap ``` -------------------------------- ### Init Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/filepicker.md Initializes the file picker component, which includes reading the current directory to populate the file list. ```APIDOC ## Init ### Description Initializes the file picker and reads the current directory. ### Returns - tea.Cmd: Command that reads directory ``` -------------------------------- ### Get Horizontal Scroll Percentage Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md Returns the horizontal scroll position as a floating-point number between 0.0 and 1.0. ```go func (m Model) HorizontalScrollPercent() float64 ``` -------------------------------- ### Get Vertical Scroll Percentage Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md Returns the vertical scroll position as a floating-point number between 0.0 and 1.0. ```go func (m Model) ScrollPercent() float64 ``` -------------------------------- ### Render Multi-Column Help View Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/help.md Renders a multi-column help view where each group of bindings becomes a column. Skips disabled bindings and ensures consistent row spacing. ```go func (m Model) FullHelpView(groups [][]key.Binding) string ``` ```go full := help.FullHelpView([][]key.Binding{ {upKey, downKey}, {pageUpKey, pageDownKey}, {quitKey}, }) ``` -------------------------------- ### Help Display Styles Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/types.md Styling configuration for help display, covering various elements like ellipsis, keys, descriptions, and separators. ```go type Styles struct { Ellipsis lipgloss.Style ShortKey lipgloss.Style ShortDesc lipgloss.Style ShortSeparator lipgloss.Style FullKey lipgloss.Style FullDesc lipgloss.Style FullSeparator lipgloss.Style } ``` -------------------------------- ### Get Cursor Position Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textarea.md Returns the cursor's position as a tuple of (line, column). Both values are 0-based. ```go func (m Model) CursorPos() (int, int) ``` -------------------------------- ### New Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/viewport.md Creates a new viewport instance with default settings. Accepts options to customize its behavior and appearance. ```APIDOC ## New ### Description Creates a new viewport with default settings. Accepts optional configuration functions. ### Method `func New(opts ...Option) Model` ### Parameters #### Options - `opts` (...Option) - Optional configuration functions to customize the viewport. ### Returns - `Model` - An initialized viewport model. ### Example ```go vp := viewport.New( viewport.WithWidth(80), viewport.WithHeight(24), ) ``` ``` -------------------------------- ### Get Cursor Column Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textarea.md Returns the cursor's column position on the current line. The column is 0-based. ```go func (m Model) Column() int ``` -------------------------------- ### Help Model View Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/help.md Renders the help view based on the `ShowAll` flag. It displays either the full multi-column help or a compact single-line view. ```APIDOC ## View Renders the help view based on the ShowAll flag. ### Method Signature ```go func (m Model) View(k KeyMap) string ``` ### Parameters - **k** (KeyMap) - Component's keybindings to display ### Returns Rendered help string ### Behavior - If ShowAll is true, returns FullHelpView() - If ShowAll is false, returns ShortHelpView() - Returns empty string if no bindings available ### Example ```go help.View(myComponent.KeyMap) ``` ``` -------------------------------- ### Get Current Line Number Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textarea.md Returns the current line number the cursor is on. The line number is 1-based. ```go func (m Model) LineNumber() int ``` -------------------------------- ### Get Progress Value Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/progress.md Returns the current progress value of the progress bar, ranging from 0.0 to 1.0. ```go func (m Model) Value() float64 ``` -------------------------------- ### Configure Viewport with Dimensions and Behavior Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/configuration.md Initialize a viewport with specific width and height, and enable features like soft wrapping and mouse wheel scrolling. This snippet demonstrates setting these properties. ```go vp := viewport.New( viewport.WithWidth(80), viewport.WithHeight(24), ) vp.SoftWrap = true // Wrap text instead of scroll vp.FillHeight = false // Fill empty space vp.MouseWheelEnabled = true // Allow mouse scroll vp.MouseWheelDelta = 3 // Lines per wheel tick vp.LeftGutterFunc = lineNumbers // Custom gutter vp.StyleLineFunc = customStyle // Per-line styling ``` -------------------------------- ### Cursor - Get Cursor Position on Current Page Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/list.md Returns the cursor position (0-based) on the current page. ```go func (m Model) Cursor() int ``` -------------------------------- ### Get Cursor Position Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textinput.md Returns the current position of the cursor within the input string, measured in runes. ```go func (m Model) Position() int ``` -------------------------------- ### Focus Management for Components Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/README.md Demonstrates how to enable and disable input handling for components using Focus() and Blur(). ```go input.Focus() // Enable input handling input.Blur() // Disable input handling ``` -------------------------------- ### FilterState - Get Current Filtering State Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/list.md Returns the current filtering state of the list, which can be Unfiltered, Filtering, or FilterApplied. ```go func (m Model) FilterState() FilterState ``` -------------------------------- ### VisibleItems - Get Currently Visible Items Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/list.md Returns a slice of the currently visible items, which may be filtered or all items. ```go func (m Model) VisibleItems() []Item ``` -------------------------------- ### FullHelpView Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/help.md Renders a multi-column help view where each group of bindings becomes a column. It skips disabled bindings and ensures consistent spacing. ```APIDOC ## FullHelpView ### Description Renders a multi-column help view where each group of bindings becomes a column. It skips disabled bindings and ensures consistent spacing. ### Method Signature `func (m Model) FullHelpView(groups [][]key.Binding) string` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **groups** ([][]key.Binding) - Required - Groups of bindings (each group becomes a column) ### Returns - **string** - Rendered help string ### Example ```go full := help.FullHelpView([][]key.Binding{ {upKey, downKey}, {pageUpKey, pageDownKey}, {quitKey}, }) ``` ``` -------------------------------- ### SelectedItem - Get Currently Selected Item Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/list.md Returns the currently selected item. Returns nil if no item is selected. ```go func (m Model) SelectedItem() Item ``` -------------------------------- ### Configure Stopwatch Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/configuration.md Create a stopwatch instance and set a custom tick interval. Ideal for measuring elapsed time. ```go stopwatch := stopwatch.New( stopwatch.WithInterval(100 * time.Millisecond), ) ``` -------------------------------- ### Position Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textinput.md Gets the current cursor position within the textinput field. The position is returned as a 0-based rune count. ```APIDOC ## Position ### Description Returns the cursor position in runes. ### Returns - int: Cursor position (0-based) ``` -------------------------------- ### Configure Progress Bar Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/configuration.md Set up a progress bar with custom blend, width, and animation spring options. Use this to visually represent task completion. ```go progress := progress.New( progress.WithDefaultBlend(), progress.WithWidth(50), progress.WithoutPercentage(), progress.WithSpringOptions(20, 1.0), ) ``` -------------------------------- ### Get Current Input Value Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/textinput.md Retrieves the current string value entered by the user in the text input field. ```go func (m Model) Value() string ``` -------------------------------- ### New List Model Function Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/list.md Creates and initializes a new list component. Use this to set up the list with initial items, a delegate, and dimensions. ```go func New(items []Item, delegate ItemDelegate, width, height int) Model ``` ```go items := []list.Item{ StringItem("Item 1"), StringItem("Item 2"), } delegate := list.NewDefaultDelegate() list := list.New(items, delegate, 80, 24) ``` -------------------------------- ### Configure Paginator Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/configuration.md Set up a paginator with custom items per page and total pages. Allows for controlling display styles and markers. ```go paginator := paginator.New( paginator.WithPerPage(10), paginator.WithTotalPages(100), ) paginator.Type = paginator.Dots // Display style paginator.ActiveDot = "•" // Current page marker paginator.InactiveDot = "○" // Other page marker paginator.ArabicFormat = "%d/%d" // Format for Arabic type ``` -------------------------------- ### Model.GetSliceBounds Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/paginator.md Determines the starting and ending indices for slicing a data collection based on the current page and items per page. ```APIDOC ## GetSliceBounds Returns the slice bounds for the current page. ### Method Signature ```go func (m *Model) GetSliceBounds(length int) (start int, end int) ``` ### Parameters - **length** (int): The total length of the data slice. ### Returns - **start** (int): The starting index for the current page's slice. - **end** (int): The ending index for the current page's slice. ### Usage Example ```go data := []Item{...} start, end := paginator.GetSliceBounds(len(data)) pageData := data[start:end] ``` ``` -------------------------------- ### Initialize FilePicker Model Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/filepicker.md Initializes the FilePicker model, which includes reading the current directory to populate the file list. ```go func (m Model) Init() tea.Cmd ``` -------------------------------- ### WithHelp Source: https://github.com/charmbracelet/bubbles/blob/main/_autodocs/api-reference/key.md Sets the help text for a binding. This option function is used to associate display text for the key combination and a description of the action. ```APIDOC ## WithHelp ### Description Sets the help text for a binding. ### Signature ```go func WithHelp(key, desc string) BindingOpt ``` ### Parameters #### Key - **key** (string) - Display text for the key combination (e.g., "↑/k"). #### Description - **desc** (string) - Description of the action (e.g., "move up"). ### Returns - **BindingOpt**: A BindingOpt function that sets the help text for a binding. ### Example ```go key.WithHelp("enter", "confirm") ``` ```