modal

package
v0.65.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 10 Imported by: 3 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package modal provides a declarative modal dialog library with automatic hit region management for mouse support.

The library eliminates off-by-one hit region bugs via a render-then-measure pattern and provides automatic keyboard navigation (Tab/Shift+Tab, Enter, Esc) and hover state management.

Quick Start

m := modal.New("Confirm Delete", modal.WithVariant(modal.VariantDanger)).
    AddSection(modal.Text("Are you sure you want to delete this item?")).
    AddSection(modal.Spacer()).
    AddSection(modal.Buttons(
        modal.Btn(" Delete ", "delete", modal.BtnDanger()),
        modal.Btn(" Cancel ", "cancel"),
    ))

// In View():
content := m.Render(screenW, screenH, mouseHandler)

// In Update():
if action, cmd := m.HandleKey(keyMsg); action != "" {
    switch action {
    case "delete":
        return performDelete()
    case "cancel":
        return closeModal()
    }
}

Built-in Sections

  • Text(s string) - static text, auto-wrapped
  • Spacer() - blank line
  • Buttons(btns ...ButtonDef) - button row with focus/hover styling
  • Checkbox(id, label string, checked *bool) - toggleable checkbox
  • Input(id string, model *textinput.Model, opts...) - text input
  • Textarea(id string, model *textarea.Model, height int, opts...) - multiline
  • List(id string, items []ListItem, selectedIdx *int, opts...) - scrollable list
  • When(condition func() bool, section) - conditional rendering
  • Custom(renderFn, updateFn) - escape hatch for complex content

Options

  • WithWidth(w int) - set modal width (default: 50)
  • WithVariant(v Variant) - set visual style (Default, Danger, Warning, Info)
  • WithHints(show bool) - show/hide keyboard hints at bottom
  • WithPrimaryAction(actionID string) - action for implicit Enter submit
  • WithCloseOnBackdropClick(close bool) - close on backdrop click

See the package-level documentation for detailed integration guides.

Index

Constants

View Source
const (
	DefaultWidth  = 50
	MinModalWidth = 30
	MaxModalWidth = 120
	ModalPadding  = 6 // border(2) + horizontal padding(4)
)

Default modal dimensions

Variables

This section is empty.

Functions

This section is empty.

Types

type BtnOption

type BtnOption func(*ButtonDef)

BtnOption is a functional option for buttons.

func BtnDanger

func BtnDanger() BtnOption

BtnDanger marks the button as a danger/destructive action.

func BtnPrimary

func BtnPrimary() BtnOption

BtnPrimary is a no-op for compatibility (primary styling is default for focused).

type ButtonDef

type ButtonDef struct {
	Label    string
	ID       string
	IsDanger bool
}

ButtonDef defines a button in a button row.

func Btn

func Btn(label, id string, opts ...BtnOption) ButtonDef

Btn creates a button definition.

type ChromeRenderer added in v0.59.0

type ChromeRenderer func(content string, width, height int) string

ChromeRenderer lets an embedder own only the outer modal frame. Width and height are the exact outer dimensions, including the host's one-cell border. Content is already themed, sized to width-4, and padded once on each side; renderers such as Sidecar's RenderGradientBorder add their own padding=1 to preserve the modal's two-cell content inset.

type CustomRenderFunc

type CustomRenderFunc func(contentWidth int, focusID, hoverID string) RenderedSection

CustomRenderFunc is the signature for custom section render functions.

type CustomUpdateFunc

type CustomUpdateFunc func(msg tea.Msg, focusID string) (action string, cmd tea.Cmd)

CustomUpdateFunc is the signature for custom section update functions.

type FocusableInfo

type FocusableInfo struct {
	ID      string // Unique identifier for this element
	OffsetX int    // X offset relative to section top-left (within content area)
	OffsetY int    // Y offset relative to section top-left (within content area)
	Width   int    // Width in characters
	Height  int    // Height in lines
}

FocusableInfo describes a focusable element within a section.

type InputOption

type InputOption func(*inputSection)

InputOption is a functional option for Input sections.

func WithSubmitAction

func WithSubmitAction(actionID string) InputOption

WithSubmitAction sets the action ID returned on submit.

func WithSubmitOnEnter

func WithSubmitOnEnter(submit bool) InputOption

WithSubmitOnEnter enables or disables submit-on-enter behavior.

type ListItem

type ListItem struct {
	ID          string             // Unique identifier for this item
	Label       string             // Display text
	ThemedLabel func(Theme) string // Optional label resolved from the current modal theme
	Data        any                // Optional associated data
}

ListItem represents an item in a list section.

type ListOption

type ListOption func(*listSection)

ListOption is a functional option for List sections.

func WithMaxVisible

func WithMaxVisible(n int) ListOption

WithMaxVisible sets the maximum number of visible items.

type Modal struct {
	// contains filtered or unexported fields
}

Modal represents a declarative modal dialog with automatic hit region management.

func New

func New(title string, opts ...Option) *Modal

New creates a new Modal with the given title and options.

func (*Modal) AddSection

func (m *Modal) AddSection(s Section) *Modal

AddSection adds a section to the modal. Returns the modal for chaining.

func (*Modal) FocusedID

func (m *Modal) FocusedID() string

FocusedID returns the currently focused element ID.

func (*Modal) HandleKey

func (m *Modal) HandleKey(msg tea.KeyMsg) (action string, cmd tea.Cmd)

HandleKey processes keyboard input. Returns:

  • action: the action ID if triggered ("cancel" for Esc, button/input ID for Enter, etc.)
  • cmd: any tea.Cmd from bubbles models (cursor blink, etc.)

func (*Modal) HandleMouse

func (m *Modal) HandleMouse(msg tea.MouseMsg, handler *mouse.Handler) string

HandleMouse processes mouse input. Returns the action ID if a clickable element was clicked, empty string otherwise.

func (*Modal) HandleMsg added in v0.54.0

func (m *Modal) HandleMsg(msg tea.Msg) (action string, cmd tea.Cmd)

HandleMsg routes a non-key message, such as Bubble Tea v2's PasteMsg, to the focused section. Key messages retain the modal's normal shortcut and submit handling through HandleKey.

func (*Modal) HoveredID

func (m *Modal) HoveredID() string

HoveredID returns the currently hovered element ID.

func (*Modal) InputValue added in v0.54.0

func (m *Modal) InputValue(id string) string

InputValue returns the current text of the input section with the given id, or "" when no such section exists.

Read the value through this rather than through the caller's own textinput.Model field. Modals are built from a Bubble Tea model that is passed and returned BY VALUE: a builder with a pointer receiver captures `&m.SomeInput` on whichever copy was current at build time, and the copy the framework goes on to use is a different struct. Keystrokes reach the modal (and therefore the captured pointer), while the live model's field stays empty — so reading the field silently yields "" no matter what the operator typed, and the modal renders the text they typed the whole time.

This accessor reads through the same pointer the keystrokes wrote to, which is the one place the two views are guaranteed to agree.

func (*Modal) Render

func (m *Modal) Render(screenW, screenH int, handler *mouse.Handler) string

Render renders the modal and registers hit regions. Returns the styled modal content string.

func (*Modal) Reset

func (m *Modal) Reset()

Reset resets the modal state (focus, hover, scroll).

func (*Modal) Scroll

func (m *Modal) Scroll(delta int)

Scroll adjusts the scroll offset by delta lines. Positive delta scrolls down, negative scrolls up. The offset is clamped to valid bounds during Render.

func (*Modal) ScrollOffset

func (m *Modal) ScrollOffset() int

ScrollOffset returns the current scroll offset.

func (*Modal) SetFocus

func (m *Modal) SetFocus(id string)

SetFocus sets focus to a specific element by ID.

func (*Modal) SetScrollOffset

func (m *Modal) SetScrollOffset(offset int)

SetScrollOffset sets the scroll offset to a specific value. The offset is clamped to valid bounds during Render.

func (*Modal) SetTheme added in v0.59.0

func (m *Modal) SetTheme(theme Theme)

SetTheme replaces only presentation state. Focus, hover, scroll and child input values are preserved.

type Option

type Option func(*Modal)

Option is a functional option for configuring a Modal.

func WithChromeRenderer added in v0.59.0

func WithChromeRenderer(renderer ChromeRenderer) Option

WithChromeRenderer delegates the outer frame while retaining modal-owned, themed inner content and interaction layout.

func WithCloseOnBackdropClick

func WithCloseOnBackdropClick(close bool) Option

WithCloseOnBackdropClick controls whether clicking the backdrop dismisses the modal. Defaults to true.

func WithHints

func WithHints(show bool) Option

WithHints enables the keyboard hint line at the bottom.

func WithPrimaryAction

func WithPrimaryAction(actionID string) Option

WithPrimaryAction sets the action ID returned when input submits implicitly.

func WithTheme added in v0.59.0

func WithTheme(theme Theme) Option

WithTheme supplies the instance-owned palette used by modal chrome and all built-in sections.

func WithVariant

func WithVariant(v Variant) Option

WithVariant sets the modal visual variant.

func WithWidth

func WithWidth(w int) Option

WithWidth sets the modal width.

type RenderedSection

type RenderedSection struct {
	Content    string          // Rendered string content
	Focusables []FocusableInfo // Focusable elements with hit region info
}

RenderedSection is the result of rendering a section.

type Section

type Section interface {
	// Render returns the rendered section content and focusable elements.
	// contentWidth is the available width for content (modal width minus border/padding).
	// focusID is the ID of the currently focused element (for styling).
	// hoverID is the ID of the currently hovered element (for styling).
	Render(contentWidth int, focusID, hoverID string) RenderedSection

	// Update handles input when this section contains the focused element.
	// Returns action string if the input triggers an action, plus any tea.Cmd.
	Update(msg tea.Msg, focusID string) (action string, cmd tea.Cmd)
}

Section is the interface for modal content sections.

func Buttons

func Buttons(btns ...ButtonDef) Section

Buttons creates a button row section.

func CenteredMuted added in v0.62.0

func CenteredMuted(s string) Section

CenteredMuted creates a centered muted text section.

func CenteredText added in v0.62.0

func CenteredText(s string) Section

CenteredText creates a static centered text section.

func CenteredTitle added in v0.62.0

func CenteredTitle(s string) Section

CenteredTitle creates a centered bold title section styled with theme primary color.

func Checkbox

func Checkbox(id, label string, checked *bool) Section

Checkbox creates a checkbox section.

func Custom

func Custom(renderFn CustomRenderFunc, updateFn CustomUpdateFunc) Section

Custom creates a custom section with user-provided render and update functions. If updateFn is nil, updates are no-ops.

func Input

func Input(id string, model *textinput.Model, opts ...InputOption) Section

Input creates an input section wrapping a textinput.Model.

func InputWithLabel

func InputWithLabel(id, label string, model *textinput.Model, opts ...InputOption) Section

InputWithLabel creates an input section with a label.

func List

func List(id string, items []ListItem, selectedIdx *int, opts ...ListOption) Section

List creates a list section with selectable items. selectedIdx is a pointer to the currently selected index (can be nil for no selection).

func Spacer

func Spacer() Section

Spacer creates a blank line section.

func Text

func Text(s string) Section

Text creates a static text section.

func Textarea

func Textarea(id string, model *textarea.Model, height int, opts ...TextareaOption) Section

Textarea creates a textarea section wrapping a textarea.Model.

func TextareaWithLabel

func TextareaWithLabel(id, label string, model *textarea.Model, height int, opts ...TextareaOption) Section

TextareaWithLabel creates a textarea section with a label.

func ThemedCustom added in v0.59.0

func ThemedCustom(renderFn ThemedCustomRenderFunc, updateFn CustomUpdateFunc) Section

ThemedCustom creates a custom section whose render callback receives the modal's current instance theme.

func When

func When(condition func() bool, section Section) Section

When creates a conditional section that only renders when condition() returns true.

type TextareaOption

type TextareaOption func(*textareaSection)

TextareaOption is a functional option for Textarea sections.

type Theme added in v0.59.0

type Theme struct {
	Primary       string
	Secondary     string
	Accent        string
	Success       string
	Warning       string
	Error         string
	Info          string
	ReadyToClose  string
	PendingReview string
	PendingOther  string
	TextPrimary   string
	TextSecondary string
	TextMuted     string
	TextSubtle    string
	TextSelection string
	OnPrimary     string
	OnWarning     string
	OnError       string
	Background    string
	Surface       string
	SurfaceRaised string
	Selection     string
	Border        string
	BorderMuted   string
	BorderActive  string
	Link          string
}

Theme is the semantic palette for a declarative modal. Empty fields inherit the standalone defaults. Theme values are copied into each Modal, so two modals can render with different palettes without shared mutable state.

func DefaultTheme added in v0.59.0

func DefaultTheme() Theme

DefaultTheme returns the palette historically used by the standalone modal package.

type ThemedCustomRenderFunc added in v0.59.0

type ThemedCustomRenderFunc func(contentWidth int, focusID, hoverID string, theme Theme) RenderedSection

ThemedCustomRenderFunc receives the modal's current instance theme on every render, including after SetTheme. It is the escape hatch for complex content that needs semantic styling without capturing a parent model's stale styles.

type Variant

type Variant int

Variant represents the visual style of the modal.

const (
	VariantDefault Variant = iota // Primary border color
	VariantDanger                 // Red border, danger button styles
	VariantWarning                // Yellow/amber border
	VariantInfo                   // Blue border
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL