Documentation
¶
Overview ¶
Package modal provides declarative modal dialog components with automatic hit region management, focus handling, scrolling, and keyboard/mouse interaction.
Index ¶
- Constants
- func ContentBoxWidth(surfaceWidth int) int
- func ListRows(surfaceHeight, seen int) int
- func ListRowsFor(surfaceHeight, seen, current int) int
- func PreferredListRows(surfaceHeight int) int
- type BtnOption
- type ButtonDef
- type ComboFilterFunc
- type ComboOption
- type CustomRenderFunc
- type CustomUpdateFunc
- type DropdownItem
- type FocusableInfo
- type InputOption
- type ListItem
- type ListOption
- type Modal
- func (m *Modal) AddSection(s Section) *Modal
- func (m *Modal) FocusedID() string
- func (m *Modal) HandleKey(msg tea.KeyPressMsg) (action string, cmd tea.Cmd)
- func (m *Modal) HandleMouse(msg tea.MouseMsg, handler *mouse.Handler) string
- func (m *Modal) HoveredID() string
- func (m *Modal) Invalidate()
- func (m *Modal) Render(screenW, screenH int, handler *mouse.Handler) string
- func (m *Modal) Reset()
- func (m *Modal) ScrollBy(delta int)
- func (m *Modal) ScrollToBottom()
- func (m *Modal) ScrollToTop()
- func (m *Modal) SetFocus(id string)
- func (m *Modal) WheelAtBoundary(msg tea.MouseWheelMsg, h *mouse.Handler) bool
- type Option
- func WithCloseOnBackdropClick(close bool) Option
- func WithCustomFooter(footer string) Option
- func WithHintText(text string) Option
- func WithHints(show bool) Option
- func WithInitialFocus(id string) Option
- func WithMargin(x, y int) Option
- func WithPrimaryAction(actionID string) Option
- func WithVariant(v Variant) Option
- func WithWidth(w int) Option
- type Overlay
- type RenderedSection
- type ScrollOwnerSection
- type Section
- func Buttons(btns ...ButtonDef) Section
- func Checkbox(id, label string, checked *bool) Section
- func CheckboxDisplay(label string, checked *bool, hint string) Section
- func Combo(id string, input *textinput.Model, items []DropdownItem, selected *int, ...) Section
- func Custom(renderFn CustomRenderFunc, updateFn CustomUpdateFunc) Section
- func Input(id string, model *textinput.Model, opts ...InputOption) Section
- func InputWithLabel(id, label string, model *textinput.Model, opts ...InputOption) Section
- func List(id string, items []ListItem, selectedIdx *int, opts ...ListOption) Section
- func ScrollingCustom(renderFn CustomRenderFunc, updateFn CustomUpdateFunc, ...) Section
- func Spacer() Section
- func Text(s string) Section
- func Textarea(id string, model *textarea.Model, height int, opts ...TextareaOption) Section
- func TextareaWithLabel(id, label string, model *textarea.Model, height int, opts ...TextareaOption) Section
- func When(condition func() bool, section Section) Section
- type TextareaOption
- type Variant
Constants ¶
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
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
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
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
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 BtnDisabled ¶ added in v1.3.0
func BtnDisabled() BtnOption
BtnDisabled marks the button unavailable: muted, unfocusable, and inert to both Enter and a click.
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
// Disabled buttons are drawn muted, are skipped by focus, and never
// return their action. A refusal the user can see beats a click that
// quietly does nothing.
Disabled bool
}
ButtonDef defines a button in a button row.
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 ¶
CustomUpdateFunc is the signature for custom section update functions.
type DropdownItem ¶ added in v1.0.0
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 ¶
type Modal struct {
// contains filtered or unexported fields
}
Modal represents a declarative modal dialog with automatic hit region management.
func (*Modal) AddSection ¶
AddSection adds a section to the modal. Returns the modal for chaining.
func (*Modal) HandleKey ¶
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 ¶
HandleMouse processes mouse input. Returns the action ID if a clickable element was clicked, empty string otherwise.
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 ¶
Render renders the modal and registers hit regions. Returns the styled modal content string.
func (*Modal) ScrollBy ¶
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) WheelAtBoundary ¶ added in v1.0.0
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 ¶
WithCloseOnBackdropClick controls whether clicking the backdrop dismisses the modal. Defaults to true.
func WithCustomFooter ¶
WithCustomFooter sets a fixed footer line rendered outside the scroll viewport.
func WithHintText ¶ added in v1.3.0
WithHintText replaces the default keyboard hint line. Use it where one of the default verbs is a lie — a modal whose Enter is a no-op should not advertise "Enter to confirm". Implies WithHints(true).
func WithInitialFocus ¶ added in v1.2.2
WithInitialFocus sets the element ID that receives focus on first render.
func WithMargin ¶ added in v1.0.0
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 ¶
WithPrimaryAction sets the action ID returned when input submits implicitly.
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 CheckboxDisplay ¶
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 TextareaWithLabel ¶
func TextareaWithLabel(id, label string, model *textarea.Model, height int, opts ...TextareaOption) Section
TextareaWithLabel creates a textarea section with a label.
type TextareaOption ¶
type TextareaOption func(*textareaSection)
TextareaOption is a functional option for Textarea sections.