formfx

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package formfx provides interactive, terminal-based form controls with multipath API support.

FormFX follows the TFX multipath pattern (see MULTIPATH.md):

  • EXPRESS: Confirm() / Input() / Select() // Zero-config, quick usage
  • INSTANTIATED: Confirm(config) / Input(config) // Config struct for control
  • DSL: New().Method().Method().Show() // Chained builder pattern

Interactive features (arrow keys, WASD navigation) are powered by RunFX for robust terminal management and graceful fallback in non-TTY environments.

Basic usage:

// Express: Zero-config
result, err := formfx.Confirm("Are you sure?")

// Instantiated: Config struct
cfg := formfx.ConfirmConfig{Label: "Proceed?", Default: true}
result, err := formfx.Confirm(cfg)

// DSL: Chained builder
result, err := formfx.NewConfirm().
	Label("Proceed with deployment?").
	Default(true).
	Show()

All prompts return (value, error) and handle context cancellation gracefully. In non-TTY environments, prompts fall back to simple text input.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrConfigNotSet is returned when a configuration is not set.
	ErrConfigNotSet = errors.New("formfx: configuration not set")
	// ErrOutOfBounds is retained for compatibility with older prompt flows.
	ErrOutOfBounds = errors.New("formfx: index out of bounds")
	// ErrInvalidOption is returned when an option is invalid.
	ErrInvalidOption = errors.New("formfx: invalid option")
	// ErrInvalidKeyHandler is returned when a key handler is not set.
	ErrInvalidKeyHandler = errors.New("formfx: key handler not set")
	// ErrInvalidRenderer is returned when a renderer is not set.
	ErrInvalidRenderer = errors.New("formfx: renderer not set")
	// ErrCanceled is retained for compatibility with older prompt flows.
	ErrCanceled = errors.New("formfx: operation canceled")
	// ErrInvalidConfigType is returned when the provided configuration type is not supported.
	ErrInvalidConfigType = errors.New("formfx: invalid configuration type")
	// ErrInvalidPromptType is retained for compatibility with older prompt flows.
	ErrInvalidPromptType = errors.New("formfx: invalid prompt type")
)

Functions

func DisableEcho

func DisableEcho() error

DisableEcho disables terminal echo.

func EnableEcho

func EnableEcho() error

EnableEcho enables terminal echo.

func HorizontalKeyHandler

func HorizontalKeyHandler(p *Prompt, key runfx.Key) bool

func TextInputKeyHandler

func TextInputKeyHandler(p *InputPrompt, key runfx.Key) bool

TextInputKeyHandler proporciona un manejo de teclado básico para la edición de texto.

func VerticalKeyHandler

func VerticalKeyHandler(p *Prompt, key runfx.Key) bool

VerticalKeyHandler handles vertical navigation in a prompt.

Types

type ConfirmBuilder

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

func NewConfirmBuilder

func NewConfirmBuilder(label string, defaultValue bool) *ConfirmBuilder

NewConfirmBuilder is a non standard way to create a ConfirmPrompt. Its experimental and it's intended for builder patterns.

func (*ConfirmBuilder) Build

func (b *ConfirmBuilder) Build() (*ConfirmPrompt, error)

Build constructs the ConfirmPrompt with the provided configuration.

func (*ConfirmBuilder) DefaultValue

func (b *ConfirmBuilder) DefaultValue(defaultValue bool) *ConfirmBuilder

DefaultValue sets the default selection for the ConfirmPrompt.

func (*ConfirmBuilder) KeyHandler

func (b *ConfirmBuilder) KeyHandler(handler KeyHandlerFunc) *ConfirmBuilder

KeyHandler sets a custom key handler for the ConfirmPrompt.

func (*ConfirmBuilder) Label

func (b *ConfirmBuilder) Label(label string) *ConfirmBuilder

Label sets the label for the ConfirmPrompt.

func (*ConfirmBuilder) Renderer

func (b *ConfirmBuilder) Renderer(renderer ConfirmRenderer) *ConfirmBuilder

Renderer sets a custom renderer for the ConfirmPrompt.

type ConfirmConfig

type ConfirmConfig struct {
	Label        string          // The question to ask.
	DefaultValue bool            // Default selection (true for Yes, false for No).
	KeyHandler   KeyHandlerFunc  // Custom key handling logic.
	Renderer     ConfirmRenderer // Custom renderer for visualization.
}

ConfirmConfig holds the configuration for ConfirmPrompt.

func DefaultConfirmConfig

func DefaultConfirmConfig() *ConfirmConfig

DefaultConfirmConfig returns a default configuration for ConfirmPrompt.

type ConfirmPrompt

type ConfirmPrompt struct {
	Label string
	// contains filtered or unexported fields
}

ConfirmPrompt is a high-level UI component for a binary choice (Yes/No). It uses a primitive Prompt internally to manage state.

func Confirm

func Confirm(args ...any) (*ConfirmPrompt, error)

Confirm creates a new ConfirmPrompt with the given label and default selection. It defaults to "Yes" if defaultValue is true, otherwise "No".

func NewConfirmPrompt

func NewConfirmPrompt(cfg *ConfirmConfig) (*ConfirmPrompt, error)

NewConfirmPrompt creates a new Confirm component. `label` is the question to ask. `defaultValue` sets the initial selection (0 for Yes, false for No). It panics if the defaultValue is not a boolean.

func (*ConfirmPrompt) Canceled

func (c *ConfirmPrompt) Canceled() <-chan struct{}

Canceled returns a channel that will be closed if the user cancels the operation.

func (*ConfirmPrompt) Done

func (c *ConfirmPrompt) Done() <-chan int

Done returns a channel that will receive the result index when the user confirms. The caller is responsible for translating the index (0 for Yes, 1 for No).

func (*ConfirmPrompt) OnKey

func (c *ConfirmPrompt) OnKey(key runfx.Key) bool

OnKey implements the runfx.Interactive interface by delegating the call to the primitive prompt.

func (*ConfirmPrompt) OnResize

func (c *ConfirmPrompt) OnResize(cols, rows int)

OnResize implements the runfx.Visual interface.

func (*ConfirmPrompt) Render

func (c *ConfirmPrompt) Render() []byte

Render implements the runfx.Visual interface. ConfirmPrompt is responsible for translating the state of the internal prompt to a "Yes/No" visual representation.

func (*ConfirmPrompt) SetRenderer

func (c *ConfirmPrompt) SetRenderer(r ConfirmRenderer)

SetRenderer allows changing the renderer of ConfirmPrompt.

type ConfirmRenderer

type ConfirmRenderer interface {
	Render(c *ConfirmPrompt) []byte
}

ConfirmRenderer is the interface that defines how a ConfirmPrompt component should be rendered.

type DefaultConfirmRenderer

type DefaultConfirmRenderer struct{}

DefaultConfirmRenderer is the standard implementation that draws "[Yes] / No".

func (*DefaultConfirmRenderer) Render

func (r *DefaultConfirmRenderer) Render(c *ConfirmPrompt) []byte

Render translates the state of ConfirmPrompt to a visual representation.

type DefaultSecretRenderer

type DefaultSecretRenderer struct{}

DefaultSecretRenderer es la implementación estándar.

func (*DefaultSecretRenderer) Render

func (r *DefaultSecretRenderer) Render(s *SecretPrompt) []byte

type DefaultSelectRenderer

type DefaultSelectRenderer struct{}

DefaultSelectRenderer is the standard implementation.

func (*DefaultSelectRenderer) Render

func (r *DefaultSelectRenderer) Render(s *SelectPrompt) []byte

type InputPrompt

type InputPrompt struct {
	Value     []rune // Usamos runas para un manejo correcto de caracteres multibyte.
	CursorPos int    // Posición del cursor dentro del slice de runas.

	Done     chan string // Devuelve el valor final como un string.
	Canceled chan struct{}
	// contains filtered or unexported fields
}

InputPrompt es un componente primitivo que gestiona el estado de una entrada de texto. Es agnóstico a su representación visual (texto plano, contraseña, etc.).

func NewInputPrompt

func NewInputPrompt(defaultValue string) *InputPrompt

NewInputPrompt crea una nueva instancia de un InputPrompt primitivo.

func (*InputPrompt) OnKey

func (p *InputPrompt) OnKey(key runfx.Key) bool

func (*InputPrompt) OnResize

func (p *InputPrompt) OnResize(cols, rows int)

func (*InputPrompt) Render

func (p *InputPrompt) Render() []byte

func (*InputPrompt) SetKeyHandler

func (p *InputPrompt) SetKeyHandler(h TextKeyHandlerFunc)

SetKeyHandler permite inyectar una lógica de teclado personalizada.

type IsTTYFunc

type IsTTYFunc func(w io.Writer) bool

IsTTYFunc is a function type for checking if a writer is a TTY.

IsTTY is a variable that holds the current IsTTYFunc implementation.

type KeyHandlerFunc

type KeyHandlerFunc func(p *Prompt, key runfx.Key) bool

KeyHandlerFunc defines the signature for injectable keyboard logic. Returns true if the loop should stop.

type Prompt

type Prompt struct {
	NumOptions    int // The number of options available in the prompt.
	SelectedIndex int // Exported so custom KeyHandlers can manipulate it.

	Done     chan int
	Canceled chan struct{}
	// contains filtered or unexported fields
}

Prompt is the low-level component. It is the central piece that is manipulated. It no longer contains a copy of the configuration.

func NewPrompt

func NewPrompt(numOptions int, defaultIndex int) (*Prompt, error)

NewPrompt creates a new Prompt with the given number of options and default index.

func (*Prompt) OnKey

func (p *Prompt) OnKey(key runfx.Key) bool

OnKey implements the runfx.Interactive interface and delegates to the injected logic.

func (*Prompt) OnResize

func (p *Prompt) OnResize(cols, rows int)

func (*Prompt) Render

func (p *Prompt) Render() []byte

These methods are required by the runfx.Visual interface.

func (*Prompt) SetKeyHandler

func (p *Prompt) SetKeyHandler(handler KeyHandlerFunc)

SetKeyHandler allows setting a custom key handler for the prompt.

type PromptConfig

type PromptConfig struct {
	NumOptions    int // The number of options available in the prompt.
	SelectedIndex int // Exported so custom KeyHandlers can manipulate it.
	// contains filtered or unexported fields
}

PromptConfig defines the configuration for the Prompt component.

func DefaultConfig

func DefaultConfig() PromptConfig

type Reader

type Reader interface {
	ReadLine(ctx context.Context) (string, error)
}

Reader is an interface for reading input.

type SecretConfig

type SecretConfig struct {
	Label    string
	Confirm  bool
	Mask     rune // El carácter a usar para enmascarar la entrada.
	Renderer SecretRenderer
}

SecretConfig contiene la configuración declarativa para un SecretPrompt.

func DefaultSecretConfig

func DefaultSecretConfig() SecretConfig

DefaultSecretConfig devuelve la configuración por defecto.

type SecretPrompt

type SecretPrompt struct {
	Label   string
	Confirm bool
	Mask    rune
	// contains filtered or unexported fields
}

SecretPrompt es un componente de UI para la entrada de texto secreto.

func NewSecretPrompt

func NewSecretPrompt(cfg SecretConfig) (*SecretPrompt, error)

NewSecretPrompt es el constructor explícito y fuertemente tipado.

func Secret

func Secret(opts ...any) (*SecretPrompt, error)

Secret es la función de conveniencia de alto nivel.

func (*SecretPrompt) Canceled

func (s *SecretPrompt) Canceled() <-chan struct{}

func (*SecretPrompt) Done

func (s *SecretPrompt) Done() <-chan string

func (*SecretPrompt) OnKey

func (s *SecretPrompt) OnKey(key runfx.Key) bool

func (*SecretPrompt) OnResize

func (s *SecretPrompt) OnResize(cols, rows int)

func (*SecretPrompt) Render

func (s *SecretPrompt) Render() []byte

type SecretRenderer

type SecretRenderer interface {
	Render(s *SecretPrompt) []byte
}

SecretRenderer define la interfaz para renderizar un componente SecretPrompt.

type SelectBuilder

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

SelectBuilder provides the DSL path.

func NewSelectBuilder

func NewSelectBuilder() *SelectBuilder

NewSelectBuilder is the entry point for the DSL path.

func (*SelectBuilder) Build

func (b *SelectBuilder) Build() (*SelectPrompt, error)

Build constructs the SelectPrompt with the provided configuration.

func (*SelectBuilder) Label

func (b *SelectBuilder) Label(label string) *SelectBuilder

Label sets the prompt label.

func (*SelectBuilder) Options

func (b *SelectBuilder) Options(options []string) *SelectBuilder

Options sets the selection options.

func (*SelectBuilder) SelectedIndex

func (b *SelectBuilder) SelectedIndex(index int) *SelectBuilder

SelectedIndex sets the default selection index.

type SelectConfig

type SelectConfig struct {
	Label         string
	Options       []string
	SelectedIndex int
	KeyHandler    KeyHandlerFunc
	Renderer      SelectRenderer
}

SelectConfig contains the declarative configuration for a SelectPrompt.

func DefaultSelectConfig

func DefaultSelectConfig() SelectConfig

DefaultSelectConfig returns the default configuration for a SelectPrompt.

type SelectPrompt

type SelectPrompt struct {
	Label   string
	Options []string
	// contains filtered or unexported fields
}

SelectPrompt is a UI component for selecting from a list of options.

func NewSelectPrompt

func NewSelectPrompt(cfg SelectConfig) (*SelectPrompt, error)

NewSelectPrompt is the explicit and strongly-typed constructor.

func Select

func Select(opts ...any) (*SelectPrompt, error)

Select is the high-level convenience function.

func (*SelectPrompt) Canceled

func (s *SelectPrompt) Canceled() <-chan struct{}

func (*SelectPrompt) Done

func (s *SelectPrompt) Done() <-chan int

func (*SelectPrompt) OnKey

func (s *SelectPrompt) OnKey(key runfx.Key) bool

func (*SelectPrompt) OnResize

func (s *SelectPrompt) OnResize(cols, rows int)

func (*SelectPrompt) Render

func (s *SelectPrompt) Render() []byte

func (*SelectPrompt) SetOptions

func (s *SelectPrompt) SetOptions(options []string) error

SetOptions allows dynamically changing the component's options. Recreates the internal prompt to maintain state consistency.

func (*SelectPrompt) SetRenderer

func (s *SelectPrompt) SetRenderer(r SelectRenderer)

type SelectRenderer

type SelectRenderer interface {
	Render(s *SelectPrompt) []byte
}

SelectRenderer defines the interface for rendering a SelectPrompt component.

type StdinReader

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

StdinReader implements Reader for os.Stdin.

func NewStdinReader

func NewStdinReader(r io.Reader) *StdinReader

NewStdinReader creates a new StdinReader.

func (*StdinReader) ReadLine

func (r *StdinReader) ReadLine(ctx context.Context) (string, error)

ReadLine reads a line from stdin, supporting context for timeouts/cancellation.

type StdoutWriter

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

StdoutWriter implements Writer for os.Stdout.

func NewStdoutWriter

func NewStdoutWriter(w io.Writer) *StdoutWriter

NewStdoutWriter creates a new StdoutWriter.

func (*StdoutWriter) Flush

func (w *StdoutWriter) Flush()

Flush flushes the writer (no-op for now).

func (*StdoutWriter) Write

func (w *StdoutWriter) Write(p []byte) (n int, err error)

Write writes bytes to stdout.

func (*StdoutWriter) WriteString

func (w *StdoutWriter) WriteString(s string) (n int, err error)

WriteString writes a string to stdout.

type TextKeyHandlerFunc

type TextKeyHandlerFunc func(p *InputPrompt, key runfx.Key) bool

type Writer

type Writer interface {
	Write(p []byte) (n int, err error)
	WriteString(s string) (n int, err error)
	Flush()
}

Writer is an interface for writing output.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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