bubbletree

package module
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2026 License: ISC Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ErrCmd

func ErrCmd(err error) tea.Cmd

ErrCmd returns a model-global message when an error occured.

func ModelFinishedCmd

func ModelFinishedCmd(id string) tea.Cmd

ModelFinishedCmd returns a model-global message when the model has completed its its shutdown sequence.

func SetDisabledCmd

func SetDisabledCmd(ids []string) tea.Cmd

SetDisabledCmd returns a model-global message to set the targeted models instances as disabled.

func SetFocusCmd

func SetFocusCmd(id string) tea.Cmd

SetFocusCmd returns a model-global message when component focus needs to change to a specific model instance.

func ShutDownCmd

func ShutDownCmd(ids []string) tea.Cmd

ShutDownCmd returns a model-global message when the system is requested to shut down. This is typically sent by the root model following an fatal error or when the user wants to close the application. Model instances should cleanup and move into an FinishedState upon receiving this message.

Types

type AppModel added in v1.5.0

type AppModel interface {
	// BranchModel embeds the branch model interface that an App Model should
	// implement first.
	BranchModel

	// AppView is a App Model special routine allowing the bridge between the
	// RootNode instance, implementing the bubble tea Model, and the bubbletree
	// Core Application (App Model). Particularly, when the root model is aware
	// of a descendant model producing an error, it is able to pass down the
	// error information so that the Core Application may display the last View
	// (with the passed down error) before the program exits. In other words,
	// the AppView method isn't simply calling the regular View method only when
	// the application is quitting.
	AppView(quitting bool, err error) string

	// QuittingView is a App Model special routine that is allowed to display
	// the last window before the programs exits.
	QuittingView(err error) string
}

AppModel defines a Core Application model in the bubbletree framework. This single instance model is the only one being directly connected to the RootModel instance of the system (defined to work directly in the bubble tea context, rather than bubbletree). It essentially is a BranchModel with the addition of the AppView method which facilitates the program quitting event. When the root model detects that the program is quitting (with errors or not), is passes this information to AppView() so that the Core Application may display the last window before quitting.

type AppOption added in v1.5.0

type AppOption func(*DefaultAppModel)

AppOption is used to set options on the app model.

func WithConfigViper added in v1.1.0

func WithConfigViper(viper *viper.Viper) AppOption

WithConfigViper sets the active viper config to use in the model.

func WithLogger added in v1.1.0

func WithLogger(logger *slog.Logger) AppOption

WithLogger sets the logger to use for model logging.

func WithProgname added in v1.5.0

func WithProgname(progname string) AppOption

WithProgname passes the base program name.

func WithProgver added in v1.5.0

func WithProgver(progver string) AppOption

WithProgver passes the base program version.

func WithReconfigure added in v1.1.0

func WithReconfigure(force bool) AppOption

WithReconfigure ignores a complete config file and brings up the user input form, enabling configuration changes.

func WithSpewConfigState added in v1.1.0

func WithSpewConfigState(spewcfg *spew.ConfigState) AppOption

WithSpewConfigState sets spew utility configuration state instance to a specified one.

func WithTheme added in v1.3.0

func WithTheme(theme Themer) AppOption

WithTheme sets the theme for the entire application tree.

type AppOpts added in v1.5.0

type AppOpts struct {
	OptProgname    string
	OptProgver     string
	OptLogger      *slog.Logger
	OptConfigViper *viper.Viper
	OptSpewcfg     *spew.ConfigState
	OptReconf      bool
	OptTheme       Themer // Optional theme for UI styling
}

AppOpts describes general configurations or states of the root model for the application.

type BranchModel

type BranchModel interface {
	// CommonModel embeds the common model interface that a branch model should
	// implement first.
	CommonModel

	// Update is responsible for accepting a tea message passed down from the
	// parent model and updating the model data when appropriate.
	Update(msg tea.Msg) (BranchModel, tea.Cmd)

	// UpdateNodeModels is responsible to call the Update method on all child models
	// that the current model has registered. It also gathers the child models new
	// commands generated and returns them alongside the updated branch model.
	UpdateNodeModels(msg tea.Msg) tea.Cmd
}

BranchModel defines a branch (inner) node in the bubbletree framework. These models have child models that are used to divide the logic of the model. This is useful for the implementation of large modules or for models defining user interfaces comprising of many components. A branch model node has tasks similar to the root model although it doesn't communicate directly with the bubble tea framework. It is responsible to instantiate and register its direct children and run the Init/Update/View methods of its children and passing the results back up the tree.

type CommonModel

type CommonModel interface {
	Init() tea.Cmd
	View(w, h int) string
	GetViewHeader(w, h int) string
	GetViewFooter(w, h int) string
	CancelContext()
	GetModelID() string
	GetState() State
	IsActive() bool
	IsInactive() bool
	IsShuttingDown() bool
	IsFinished() bool
	GetProperties() Properties
	IsDisabled() bool
	IsFocused() bool
}

CommonModel is an interface defining the routine requirements for each models used in the bubbletree framework. With each components (bubbles in bubbletea framework parlance) implementing the interface, it is easy and predictable to define how all parts of the bubbletree system work together with the other model types defined as: root, branch and leaf. Most models implementations will not only satisfy this iterface but will also implement either a leaf, a branch or the one-per-application root model.

type DefaultAppModel added in v1.5.0

type DefaultAppModel struct {
	// Include all common fields and methods of the default BranchModel
	// interface implementation.
	DefaultBranchModel

	// Options passed in by the main program.
	AppOpts

	// Real-time screen dimensions (updated by tea.WindowSizeMsg).
	Screen

	// Update + View execution performance.
	Timing
}

DefaultAppModel implements default methods for the AppModel interface. It can be used as a base implementation when no specific code is required. The implementor of the AppModel interface may overwrite the default behavior of the model by reimplementing desired methods.

func (DefaultAppModel) AppView added in v1.5.0

func (m DefaultAppModel) AppView(quitting bool, err error) string

AppView is the default implementation of the AppModel interface.

func (DefaultAppModel) QuittingView added in v1.5.0

func (m DefaultAppModel) QuittingView(err error) string

QuittingView is the default implementation of the AppModel interface.

type DefaultBranchModel

type DefaultBranchModel struct {
	// Include all common fields and methods of the default CommonModel
	// interface implementation.
	DefaultCommonModel

	// The <ModelID, *Model> map of all registered descendant models.
	Models *sync.Map
}

DefaultBranchModel implements default methods for the BranchModel interface. It can be used as a base implementation when no specific code is required. The implementor of the BranchModel interface may overwrite the default behavior of the model by reimplementing desired methods.

func (DefaultBranchModel) LinkNewModel

func (m DefaultBranchModel) LinkNewModel(model CommonModel, modelID *string)

LinkNewModel takes a new descendant model and updates the model ID saved by the model for later reference in addition to adding that new model to a map of descendant models.

func (DefaultBranchModel) MustGetModel

func (m DefaultBranchModel) MustGetModel(modelID string) CommonModel

MustGetModel returns a model identified by the parameter modelID from the linked model sync.Map. The function will panic if the model cannot be found or if the found object doesn't implement the 'CommonModel' interface.

func (DefaultBranchModel) Update

func (m DefaultBranchModel) Update(msg tea.Msg) (BranchModel, tea.Cmd)

Update is the default implementation of the BranchModel interface. It is the update logic in reaction to the new message passed as parameter. The updated copy of the model is returned along with optional new tea commands. Note that a model can implement its own handling of specific messages and then call this general session message handling code, in combination, via an embeded DefaultBranchModel instead of completely overwriting the method.

func (DefaultBranchModel) UpdateNodeModel added in v1.2.0

func (m DefaultBranchModel) UpdateNodeModel(model CommonModel, msg tea.Msg) tea.Cmd

UpdateNodeModel runs the Update() method on a specified model with the passed in message. The descendant returned tea.Cmd is relayed to the caller.

func (DefaultBranchModel) UpdateNodeModels

func (m DefaultBranchModel) UpdateNodeModels(msg tea.Msg) tea.Cmd

UpdateNodeModels is the default implementation of the BranchModel interface.

type DefaultCommonModel

type DefaultCommonModel struct {
	// The unique ID for this instance: e.g., 'config00', 'config01'...
	ID string

	// The current model's instance State.
	State State

	// Whether or not this model is currently in focus/active.
	Properties Properties

	// The initial viper Viper passed along.
	Viper *viper.Viper

	// slog Logger to use throughout the model.
	Logger *slog.Logger

	// The model context needed to notify long running goroutines.
	Ctx context.Context

	// The cancel func associated with the above context.
	Cancel context.CancelFunc

	// Optional theme for UI styling. Can be nil if application doesn't use theming.
	Theme Themer
}

DefaultCommonModel defines data that are common use amongst all instantiated models.

func (DefaultCommonModel) CancelContext

func (m DefaultCommonModel) CancelContext()

CancelContext is the default implementation of the CommonModel interface. It is used to explicitely cancel the model's instance context.

func (DefaultCommonModel) GetModelID

func (m DefaultCommonModel) GetModelID() string

GetModelID is the default implementation of the CommonModel interface. It is an identification helper routine. Calling it will return the name of the model as identified internally. This ID can be combined with an arbitrary prefix to uniquely identify a specific model instance out of others created from the same model.

func (DefaultCommonModel) GetProperties

func (m DefaultCommonModel) GetProperties() Properties

GetProperties is the default implementation of the CommonModel interface. It returns the model's instance current property set.

func (DefaultCommonModel) GetState

func (m DefaultCommonModel) GetState() State

GetState is the default implementation of the CommonModel interface. It returns the model's current state. For now, it informs whether the model is doing work (ActiveState), whether it hasn't started yet (InactiveState), that it is shutting down (ShuttingDownState) or terminated with all resources freed (FinishedState).

func (DefaultCommonModel) GetTheme added in v1.3.0

func (m DefaultCommonModel) GetTheme() Themer

GetTheme returns the theme if set, otherwise returns the default minimal theme. This ensures models always have access to a valid theme for rendering.

func (DefaultCommonModel) GetViewFooter

func (m DefaultCommonModel) GetViewFooter(w, h int) string

GetViewFooter is the default implementation of the CommonModel interface. It returns the view portion that should be displayed in the app's footer section of the final composed UI window. This should be a short string or a unicode icon.

func (DefaultCommonModel) GetViewHeader

func (m DefaultCommonModel) GetViewHeader(w, h int) string

GetViewHeader is the default implementation of the CommonModel interface. It returns the view portion that should be displayed in the app's header section of the final composed UI window. This should be a short string or a unicode icon.

func (DefaultCommonModel) Init

func (m DefaultCommonModel) Init() tea.Cmd

Init is the default implementation of the CommonModel interface. It sends a kick-off tea command for the model when needed.

func (DefaultCommonModel) IsActive

func (m DefaultCommonModel) IsActive() bool

IsActive is the default implementation of the CommonModel interface. It returns whether the model's instance is currently in "Active" state.

func (DefaultCommonModel) IsDisabled

func (m DefaultCommonModel) IsDisabled() bool

IsDisabled is the default implementation of the CommonModel interface. It returns whether the model's instance has the "Disabled" property set. Disabled models will not respond to loop events and is a useful state to debug the rest of the system without the disabled model(s).

func (DefaultCommonModel) IsFinished

func (m DefaultCommonModel) IsFinished() bool

IsFinished is the default implementation of the CommonModel interface. It returns whether the model's instance has completed its shutdown actions and all long running goroutines, if any, have returned from the receiving the context cancellation signal.

func (DefaultCommonModel) IsFocused

func (m DefaultCommonModel) IsFocused() bool

IsFocused is the default implementation of the CommonModel interface. It returns whether the model's instance has the "Focused" property set. The focused model instance may use this as a signal to activate itself and generate non-empty views.

func (DefaultCommonModel) IsInactive

func (m DefaultCommonModel) IsInactive() bool

IsInactive is the default implementation of the CommonModel interface. It returns whether the model's instance is currently in "Inactive" state.

func (DefaultCommonModel) IsShuttingDown

func (m DefaultCommonModel) IsShuttingDown() bool

IsShuttingDown is the default implementation of the CommonModel interface. It returns whether the model's instance has acknowledged the ShuttingDownMsg. The model should have initiated it own shutdown actions by cleaning up resources and canceling contexts when required.

func (DefaultCommonModel) LogAction

func (m DefaultCommonModel) LogAction(msg any, action string)

LogAction sends a standardized log entry after a new queued tea.Cmd.

func (DefaultCommonModel) LogNotice

func (m DefaultCommonModel) LogNotice(msg any, notice string)

LogNotice sends a standardized log entry of a notification.

func (DefaultCommonModel) LogPropertyChange

func (m DefaultCommonModel) LogPropertyChange(msg any, old, new Properties)

LogPropertyChange sends a standardized log entry after a model property change.

func (DefaultCommonModel) LogStateChange

func (m DefaultCommonModel) LogStateChange(msg any)

LogStateChange sends a standardized log entry after a model state change.

func (DefaultCommonModel) View

func (m DefaultCommonModel) View(w, h int) string

View is the default implementation of the CommonModel interface. It is the model rendering routine that creates the output reflecting the current state of the model data. This rendered string is passed back up the tree to the root model for final window composition. The w and h parameters sets the model's virtual view window size. This could be the same as the actual terminal window size if the root model communicates it as being the case.

type DefaultLeafModel

type DefaultLeafModel struct {
	// Include all common fields and methods of the default CommonModel
	// interface implementation.
	DefaultCommonModel
}

DefaultLeafModel implements default methods for the LeafModel interface. It can be used as a base implementation when no specific code is required. The implementor of the LeafModel interface may overwrite the default behavior of the model by reimplementing desired methods.

func (DefaultLeafModel) Update

func (m DefaultLeafModel) Update(msg tea.Msg) (LeafModel, tea.Cmd)

Update is the default implementation of the LeafModel interface. It is the update logic in reaction to the new message passed as parameter. The updated copy of the model is returned along with optional new tea commands. Note that a model can implement its own handling of specific messages and then call this general session message handling code, in combination, via an embeded DefaultLeafModel instead of completely overwriting the method.

type DefaultRootModel

type DefaultRootModel struct {
	// The directly linked main application model.
	CoreApp AppModel

	// Ending program cleanup happened, bubble tea is quitting.
	Quitting bool

	// The last error recorded in the model.
	Err error
}

DefaultRootModel implements default methods for the RootModel interface. It can be used as a base implementation when no specific code is required. The implementor of the RootModel interface may overwrite the default behavior of the model by reimplementing desired methods.

func (DefaultRootModel) Init

func (m DefaultRootModel) Init() tea.Cmd

Init is the default implementation of the RootModel interface.

func (DefaultRootModel) LastError

func (m DefaultRootModel) LastError() error

LastError returns the last error recorded by the root model.

func (DefaultRootModel) Update

func (m DefaultRootModel) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update is the default implementation of the RootModel interface.

func (DefaultRootModel) View

func (m DefaultRootModel) View() string

View is the default implementation of the RootModel interface.

type ErrMsg

type ErrMsg struct{ Err error }

ErrMsg is a model-global message sent when an error occured while running the model.

func (ErrMsg) Error

func (e ErrMsg) Error() string

type LeafModel

type LeafModel interface {
	// CommonModel embeds the common model interface that a leaf model should
	// implement first.
	CommonModel

	// Update is responsible for accepting a tea message passed down from the
	// parent model and updating the model data when appropriate.
	Update(msg tea.Msg) (LeafModel, tea.Cmd)
}

LeafModel defines a leaf (outer) node in the bubbletree framework. These models don't have child nodes, implementing all the logic within the bounds of a single model. Its Init/Update/View methods are called by its parent branch model. LeafModels act like a regular bubble tea "bubble".

type ModelFinishedMsg

type ModelFinishedMsg struct{ ModelID string }

ModelFinishedMsg is a model-global message sent when the model has completed its shutdown sequence: its goroutines returned, and its resources are fully freed.

func (ModelFinishedMsg) IsRecipient

func (msg ModelFinishedMsg) IsRecipient(id string) bool

IsRecipient returns whether the message is destined to the specified model instance.

type OptionalStyleProvider added in v1.3.0

type OptionalStyleProvider interface {
	GetButtonStyle() lipgloss.Style
	GetCardStyle() lipgloss.Style
	GetTabStyle() lipgloss.Style
	GetWinbarStyle() lipgloss.Style
}

OptionalStyleProvider is an optional interface for themes that provide additional component styles. Applications can type-assert to check if their theme supports these extensions.

type Properties

type Properties int
const (
	Disabled Properties = 1 << iota
	Focused
)

The possible bubble tree model properties

func (*Properties) SetDisabled

func (p *Properties) SetDisabled() (old, new Properties)

SetDisabled sets the Disabled model property.

func (*Properties) SetFocused

func (p *Properties) SetFocused() (old, new Properties)

SetFocused sets the Focused model property.

func (Properties) String

func (p Properties) String() string

func (*Properties) UnsetDisabled

func (p *Properties) UnsetDisabled() (old, new Properties)

UnsetDisabled unsets the Disabled model property.

func (*Properties) UnsetFocused

func (p *Properties) UnsetFocused() (old, new Properties)

UnsetFocused unsets the Focused model property.

type RootModel

type RootModel interface {
	// tea.Model is the Charmbracelet bubble tea main Init/Update/View interface
	// that connects the program to the bubble tea framework.
	tea.Model

	// LastError returns the last error saved in the model instance.
	LastError() error
}

RootModel defines the root node of the bubbletree framework. Only one model should implement this interface in a program. Only this model has its Init, Update, and View methods called directly by bubble tea. In bubbletree, the root model instantiates and registers its direct descendants and is responsible for calling Init/Update/View as appropriate. The idea is that tea.Msgs are propagated down the model tree. Those messages will generate new tea.Cmds from all the tree components, which will be flowing back up to the root model. Those tree gathered commands are returned to bubble tea for processing. Similarly, at View execution time, the root model will have all the nodes from the tree run their View() method and the result will be aggregated by the root model View() method for final UI composition.

func New added in v1.5.0

func New(app AppModel) RootModel

New returns a new DefaultRootModel instance.

type Screen added in v1.5.0

type Screen struct {
	Width  int
	Height int
}

Screen holds the current state details of the terminal window.

type SetDisabledMsg

type SetDisabledMsg struct{ ModelIDs []string }

SetDisabledMsg is a model-global message sent to request that models instances listed have the "Disabled" properties set.

func (SetDisabledMsg) IsRecipient

func (msg SetDisabledMsg) IsRecipient(id string) bool

IsRecipient returns whether the message is destined to the specified model instance.

type SetFocusMsg

type SetFocusMsg struct{ ModelID string }

SetFocusMsg is a model-global message sent to request a change of model instance focus. The message includes the Model ID that needs focus. Target models should set the Focused property on the model and act approprietely.

func (SetFocusMsg) IsRecipient

func (msg SetFocusMsg) IsRecipient(id string) bool

IsRecipient returns whether the message is destined to the specified model instance.

type ShutDownMsg

type ShutDownMsg struct{ ModelIDs []string }

ShutDownMsg is a model-global message used to request that the list of specified model instances enter their shutdown sequence. This allows time for graceful cleanup before tea.Quit get called at a later time or when a model instance self terminate.

func (ShutDownMsg) IsRecipient

func (msg ShutDownMsg) IsRecipient(id string) bool

IsRecipient returns whether the message is destined to the specified model instance.

type State

type State int
const (
	InactiveState State = iota
	ActiveState
	ShuttingDownState
	FinishedState
)

The possible bubble tree model states

func (State) String

func (s State) String() string

type Themer added in v1.3.0

type Themer interface {
	// Core color accessors - every theme must provide these base colors
	GetPrimaryColor() lipgloss.Color
	GetSecondaryColor() lipgloss.Color
	GetSuccessColor() lipgloss.Color
	GetErrorColor() lipgloss.Color
	GetTextColor() lipgloss.Color       // Text color for content on main background
	GetBackgroundColor() lipgloss.Color // Main background color
	GetAccentTextColor() lipgloss.Color // Text color for content on colored surfaces (buttons, badges, etc.)

	// Base style accessors - minimal set for framework components
	GetBaseStyle() lipgloss.Style   // Default text style
	GetHeaderStyle() lipgloss.Style // For headers/titles
	GetErrorStyle() lipgloss.Style  // For error messages

	// Render helpers - convenience methods
	RenderNormalText(string) string
	RenderHeaderText(string) string
	RenderErrorText(string) string
	RenderPrimaryText(string) string
	RenderSecondaryText(string) string
}

Themer is the minimal interface that any theme implementation must satisfy. Applications using bubbletree can provide their own implementations with additional methods and styling capabilities beyond this base interface.

func DefaultMinimalTheme added in v1.3.0

func DefaultMinimalTheme() Themer

DefaultMinimalTheme returns a minimal theme implementation using basic ANSI colors. This theme is used as a fallback when no theme is provided to the application.

type Timing added in v1.5.0

type Timing struct {
	UpdateRuntime time.Duration
	ViewRuntime   time.Duration
}

Timing holds information about the update and view execution performance in terms of elapsed time.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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