modal

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 11 Imported by: 0 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 declarative modal dialog components with automatic hit region management, focus handling, scrolling, and keyboard/mouse interaction.

Index

Constants

View Source
const (
	// BackdropRegionID names the region a modal registers over the whole
	// surface it was drawn on. A host that composites the box somewhere other
	// than where the modal thought it was — panemodal, placing it in a pane —
	// registers its own under this ID so the surface behind the box still
	// absorbs clicks.
	BackdropRegionID = "modal-backdrop"

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

	// DefaultMarginX/Y are the cells left clear around the modal box.
	DefaultMarginX = 2
	DefaultMarginY = 1

	// RoomyMarginX is the surface a content-sized box tries to leave visible on
	// each side of itself, and the width a pane host requires before it will
	// show the surface behind the box at all. The two are the same number on
	// purpose: a box that grows to DefaultMarginX of its surface can never leave
	// a readable ring, so the host would always fall back to a takeover, which
	// is how a three-row picker came to own a whole pane.
	RoomyMarginX = 8

	// MinRoomyWidth is the narrowest box worth keeping a ring around. Below it
	// the rows need the columns more than the surface behind them does.
	MinRoomyWidth = 40

	// MinListRows/MaxListRows bound PreferredListRows.
	MinListRows = 8
	MaxListRows = 14

	// ChromeWidth/ChromeHeight are what the box itself costs: border plus
	// padding. A caller budgeting its own content needs the same numbers.
	ChromeWidth  = 6
	ChromeHeight = 4
)

Default modal dimensions

Variables

This section is empty.

Functions

func ContentBoxWidth added in v1.0.0

func ContentBoxWidth(surfaceWidth int) int

ContentBoxWidth is the widest a content-sized box may be on a surface this wide. It keeps RoomyMarginX clear on each side so a host that dims the surface around the box has something left to dim, and falls back to the ordinary margin on a surface too narrow for that to leave a usable box.

func ListRows added in v1.0.0

func ListRows(surfaceHeight, seen int) int

ListRows is how long a content-sized list actually draws itself: the preferred length, less what it has never needed, but never below MinListRows.

seen is the most rows the list has wanted since it was opened — a high-water mark, not the current count. A box sized to the current count breathes under the user's hands as a query is refined; a box sized to the preferred length whatever happens reserves two dozen rows for a picker that has one hit and reads as broken on a large screen. Growing once into the results and then holding still is the balance: refining a query, which is where the jitter was unbearable, never resizes anything.

func ListRowsFor added in v1.0.0

func ListRowsFor(surfaceHeight, seen, current int) int

ListRowsFor is ListRows with the two cases the high-water mark gets wrong.

The mark exists so that refining a query does not resize the box under the user's hands, and that is right while the list is answering. It is not right once it has stopped:

  • a query that matches nothing gets a one-row list. The mark had a box that grew to fifty hits still reserving a dozen rows under the words "No matches", which reads as broken rather than steady, and nothing is being refined at that point — the query has stopped matching.
  • a list showing fewer rows than the ordinary floor keeps the floor and no more. One hit in a fourteen-row box is thirteen blank rows; one hit in an eight-row box is the same box an unasked finder draws, so nothing has jittered and nothing is being reserved for results that are not coming.

current is how many rows the list is showing. A caller in a state that has not asked anything yet — no query, or a scan still running — passes MinListRows rather than zero: an empty box is not a dead end, and a box that opens one row tall and grows is the jitter this all exists to avoid.

func PreferredListRows added in v1.0.0

func PreferredListRows(surfaceHeight int) int

PreferredListRows is the list length a content-sized modal aims for on a surface this tall: enough to be worth opening, never so much that a picker with three hits reserves most of a large pane. It deliberately does not depend on how many rows there are to show — a box that grows as results land breathes under the user's hands.

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 ComboFilterFunc added in v1.0.0

type ComboFilterFunc func(query string, item DropdownItem) bool

ComboFilterFunc reports whether item matches the current query.

type ComboOption added in v1.0.0

type ComboOption func(*comboSection)

ComboOption configures a Combo section.

func WithComboFilter added in v1.0.0

func WithComboFilter(fn ComboFilterFunc) ComboOption

WithComboFilter replaces the default case-insensitive substring filter.

func WithComboMaxVisible added in v1.0.0

func WithComboMaxVisible(n int) ComboOption

WithComboMaxVisible sets how many overlay rows are shown (default 8).

func WithComboSubmitOnEnter added in v1.0.0

func WithComboSubmitOnEnter(submit bool) ComboOption

WithComboSubmitOnEnter submits the modal primary action after Enter commits the highlight (default true).

func WithOpenOnFocus added in v1.0.0

func WithOpenOnFocus(open bool) ComboOption

WithOpenOnFocus opens the overlay when the field gains focus (default true).

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 DropdownItem struct {
	ID    string
	Label string
	Value string // written into the input on commit; empty means Label
	Desc  string
	Data  any
}

DropdownItem is one row in a Combo overlay.

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
	MouseOnly bool   // Hit-tested but omitted from the Tab / focus order
}

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
	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.

func WithPerItemFocus

func WithPerItemFocus() ListOption

WithPerItemFocus makes the list register each item as a separate focusable for Tab navigation. This overrides the default single-focus behavior when you want Tab to cycle through individual items.

func WithSingleFocus

func WithSingleFocus() ListOption

WithSingleFocus makes the list register as a single focusable unit for Tab navigation. When focused, j/k or up/down change selection within the list without Tab-cycling through each item. This is useful for lists that are part of a larger form where Tab should skip between sections. Note: This is now the default behavior. This option is kept for backward compatibility.

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.KeyPressMsg) (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) HoveredID

func (m *Modal) HoveredID() string

HoveredID returns the currently hovered element ID.

func (*Modal) Invalidate added in v1.0.0

func (m *Modal) Invalidate()

Invalidate marks the cached layout bounds as untrustworthy. Call it whenever the modal's content changes outside a render (for example when an async load replaces the text a Custom section draws). Until the next Render, boundary queries answer "unknown" rather than guessing.

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) ScrollBy

func (m *Modal) ScrollBy(delta int)

ScrollBy adjusts the scroll offset by delta lines (positive = down, negative = up). Movement is clamped through the last render's bounds; before the first trustworthy render the offset is clamped again in buildLayout.

func (*Modal) ScrollToBottom

func (m *Modal) ScrollToBottom()

ScrollToBottom scrolls to the bottom of the content. The offset is clamped to the actual max in buildLayout.

func (*Modal) ScrollToTop

func (m *Modal) ScrollToTop()

ScrollToTop scrolls to the top of the content.

func (*Modal) SetFocus

func (m *Modal) SetFocus(id string)

SetFocus sets focus to a specific element by ID.

func (*Modal) WheelAtBoundary added in v1.0.0

func (m *Modal) WheelAtBoundary(msg tea.MouseWheelMsg, h *mouse.Handler) bool

WheelAtBoundary reports whether this wheel event is certainly a no-op for the modal, using only the geometry and scroll bounds produced by the most recent Render. It never rebuilds or mutates visible content.

True means "certain no-op": the event can be dropped before Update and View. False means the surface can move, or that the answer is unknown - callers must forward the event. The query answers unknown before the first render and after Invalidate, and answers true for wheel over the backdrop or over non-scrollable modal chrome, because an open modal absorbs those events without changing state. When the pointer is over a section that owns its own scroll state (see ScrollOwnerSection), that section answers instead.

type Option

type Option func(*Modal)

Option is a functional option for configuring a Modal.

func WithCloseOnBackdropClick

func WithCloseOnBackdropClick(close bool) Option

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

func WithCustomFooter

func WithCustomFooter(footer string) Option

WithCustomFooter sets a fixed footer line rendered outside the scroll viewport.

func WithHints

func WithHints(show bool) Option

WithHints enables the keyboard hint line at the bottom.

func WithMargin added in v1.0.0

func WithMargin(x, y int) Option

WithMargin sets how much of the surface the modal leaves clear around itself. The default keeps the box off the edge of a screen; a modal that is meant to own its surface — a pane too small to show anything useful behind the modal — passes 0, 0 and is then rendered at exactly the surface's size.

func WithPrimaryAction

func WithPrimaryAction(actionID string) Option

WithPrimaryAction sets the action ID returned when input submits implicitly.

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 Overlay added in v1.0.0

type Overlay struct {
	Content    string
	OffsetX    int
	OffsetY    int // preferred top relative to the section (typically just below it)
	Focusables []FocusableInfo
}

Overlay is drawn over later sections and does not count toward modal height. Focusables are relative to the overlay's top-left, not the section.

type RenderedSection

type RenderedSection struct {
	Content    string          // Rendered string content
	Focusables []FocusableInfo // Focusable elements with hit region info
	Overlay    *Overlay        // Optional floating layer; does not affect section height
}

RenderedSection is the result of rendering a section.

type ScrollOwnerSection added in v1.0.0

type ScrollOwnerSection interface {
	Section

	// OwnsScrollRegion reports whether the given mouse hit region ID belongs to
	// this section's scrollable area.
	OwnsScrollRegion(regionID string) bool

	// ScrollAtBoundary reports whether delta lines (negative up, positive down)
	// cannot move this section's own scroll state.
	ScrollAtBoundary(delta int) bool
}

ScrollOwnerSection is implemented by sections that own their own scroll state (a document viewport, a nested list) rather than moving the modal body's offset. When the pointer is over a region such a section claims, Modal.WheelAtBoundary delegates the answer to it.

Both methods must be read-only: they may not rebuild or mutate content. ScrollAtBoundary follows the same semantics as Modal.WheelAtBoundary - true only when applying delta is certainly a no-op, false for movable or unknown.

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 Checkbox

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

Checkbox creates a checkbox section.

func CheckboxDisplay

func CheckboxDisplay(label string, checked *bool, hint string) Section

CheckboxDisplay creates a non-focusable checkbox display. The hint shows the keyboard shortcut to toggle (e.g., "ctrl+a").

func Combo added in v1.0.0

func Combo(id string, input *textinput.Model, items []DropdownItem, selected *int, opts ...ComboOption) Section

Combo creates a text field whose filtered list floats over later sections. selected is an index into items (the same convention as List). Typing moves it to the top match's items index, not 0 unless that item is first.

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 ScrollingCustom added in v1.0.0

func ScrollingCustom(renderFn CustomRenderFunc, updateFn CustomUpdateFunc, ownsRegion func(regionID string) bool, atBoundary func(delta int) bool) Section

ScrollingCustom creates a Custom section that owns its own scroll state and can answer wheel-boundary questions for the regions it claims. ownsRegion receives a mouse hit region ID; atBoundary must be read-only and may return true only when delta is certainly a no-op. Either callback may be nil, in which case the section never claims the wheel.

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 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 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