core

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2025 License: MIT Imports: 19 Imported by: 0

README

go-clack/core

Clack contains low-level primitives for implementing your own command-line applications.

Currently exposes Prompt as well as:

  • TextPrompt
  • PasswordPrompt
  • PathPrompt
  • ConfirmPrompt
  • SelectPrompt
  • MultiSelectPrompt
  • GroupMultiSelectPrompt
  • SelectPathPrompt
  • MultiSelectPathPrompt
  • SelectKeyPrompt

Each Prompt accepts a Render function.

p := core.NewTextPrompt(core.TextPromptParams{
  Render: func(p *core.TextPrompt) string {
    return fmt.Sprintf("What's your name?\n%s", p.ValueWithCursor)
  },
})

name, err := p.Run()
if (err != nil) {
  // Handle prompt's cancellation
  os.Exit(0)
}

Get Started

To start using go-clack/core, follow these steps:

1. Install the Package

First, add the go-clack/core package to your Go project:

go get github.com/orochaa/go-clack/core
2. Create a Prompt

To create and run a simple text prompt, you can use the following code:

// main.go
package main

import (
  "fmt"
  "os"
  "github.com/orochaa/go-clack/core"
)

func main() {
  p := core.NewTextPrompt(core.TextPromptParams{
    Render: func(p *core.TextPrompt) string {
    return fmt.Sprintf("What's your name?\n%s", p.ValueWithCursor())
    },
  })

  name, err := p.Run()
  if err != nil {
      fmt.Println("Prompt was canceled.")
      os.Exit(0)
  }

  fmt.Printf("Hello, %s!\n", name)
}
3. Run Your Application

Compile and run your application:

go run main.go

This will present a text prompt asking for the user's name. The input will be captured and printed back as a greeting.

Explore More

The go-clack/core package provides various other prompts for different types of user inputs, such as password inputs, file path selections, confirmations, and more. Explore the available prompts and customize their behavior using the Render function, or create a brand new one extending the core Prompt.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCancelPrompt error = errors.New("prompt canceled")
)

Functions

func NewActionHandler

func NewActionHandler(listeners map[Action]func(), defaultListener func(key *Key)) (actionHandler func(key *Key))

NewActionHandler creates a closure that handles key events and maps them to actions. It uses the global aliases map to determine the action for a given key and invokes the corresponding listener. If no listener is found for the action, the default listener is invoked.

Parameters:

  • listeners (map[Action]func()): A map of actions to their corresponding listener functions.
  • defaultListener (func(key *Key)): A default listener function to invoke if no action-specific listener is found.

Returns:

  • actionHandler (func(key *Key)): A action handler that handles key events and invokes the appropriate listener.

func UpdateSettings

func UpdateSettings(settings Settings)

UpdateSettings updates the global Settings for the application.

func WrapRender

func WrapRender[T any, TPrompt any](p TPrompt, render func(p TPrompt) string) func(_ *Prompt[T]) string

WrapRender wraps a render function for a specific prompt type (TPrompt) into a function compatible with the Prompt[T] type. It allows custom rendering logic to be applied to a prompt.

Parameters:

  • p (TPrompt): The prompt instance to be passed to the render function.
  • render (func(p TPrompt) string): The custom render function that generates the prompt's frame.

Returns:

  • func(_ *Prompt[T]) string: A function that can be used as the render function for a Prompt[T].

func WrapValidate

func WrapValidate[TValue any](validate func(value TValue) error, isRequired *bool, errMsg string) func(value TValue) error

WrapValidate wraps a validation function and combines it with a required flag and custom error message. It ensures that the value is validated against the provided rules and returns an error if validation fails.

Parameters:

  • validate (func(value TValue) error): The custom validation function to apply to the value.
  • isRequired (*bool): A pointer to a boolean indicating whether the value is required.
  • errMsg (string): The error message to return if the value is required but not provided or invalid.

Returns:

  • func(value TValue) error: A function that validates the value and returns an error if validation fails.

Types

type Action

type Action int

Action represents an action that can be performed in the application.

const (
	UpAction Action = iota
	DownAction
	LeftAction
	RightAction
	HomeAction
	EndAction
	SpaceAction
	SubmitAction
	CancelAction
)

type ConfirmPrompt

type ConfirmPrompt struct {
	Prompt[bool]
	Active   string
	Inactive string
}

func NewConfirmPrompt

func NewConfirmPrompt(params ConfirmPromptParams) *ConfirmPrompt

NewConfirmPrompt initializes and returns a new instance of ConfirmPrompt.

The user can toggle between the two options using arrow keys. The prompt returns the selected value if the user confirms their choice. If the user cancels the prompt, it returns an error. If an error occurs during the prompt, it also returns an error.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • Active (string): The label displayed when the prompt is in the "active" (true) state (default: "yes").
  • Inactive (string): The label displayed when the prompt is in the "inactive" (false) state (default: "no").
  • InitialValue (bool): The initial value of the prompt (default: false).
  • Render (func(p *MultiSelectPathPrompt) string): A custom render function for the prompt (default: nil).

Returns:

  • *ConfirmPrompt: A pointer to the newly created ConfirmPrompt instance.

type ConfirmPromptParams

type ConfirmPromptParams struct {
	Context      context.Context
	Input        *os.File
	Output       *os.File
	Active       string
	Inactive     string
	InitialValue bool
	Render       func(p *ConfirmPrompt) string
}

type Event

type Event int

Event represents the type of events that can occur.

const (
	// KeyEvent is emitted after each user's input
	KeyEvent Event = iota
	// ValidateEvent is emitted when the input is being validated
	ValidateEvent
	// ErrorEvent is emitted if an error occurs during the validation process
	ErrorEvent
	// FinalizeEvent is emitted on user's submit or cancel, and before rendering the related state
	FinalizeEvent
	// CancelEvent is emitted after the user cancels the prompt, and after rendering the cancel state
	CancelEvent
	// SubmitEvent is emitted after the user submits the input, and after rendering the submit state
	SubmitEvent
)

type EventListener

type EventListener func(args ...any)

type FileSystem

type FileSystem interface {
	Getwd() (string, error)
	ReadDir(name string) ([]os.DirEntry, error)
	UserHomeDir() (string, error)
}

type FormatLineOptions

type FormatLineOptions struct {
	Start string
	End   string
	Sides string
	Style func(line string) string
}

type FormatLinesOptions

type FormatLinesOptions struct {
	FirstLine FormatLineOptions
	NewLine   FormatLineOptions
	LastLine  FormatLineOptions
	Default   FormatLineOptions
	MinWidth  int
	MaxWidth  int
}

type GroupMultiSelectOption

type GroupMultiSelectOption[TValue comparable] struct {
	MultiSelectOption[TValue]
	IsGroup bool
	Options []*GroupMultiSelectOption[TValue]
}

type GroupMultiSelectPrompt

type GroupMultiSelectPrompt[TValue comparable] struct {
	Prompt[[]TValue]
	Options        []*GroupMultiSelectOption[TValue]
	DisabledGroups bool
	Required       bool
}

func NewGroupMultiSelectPrompt

func NewGroupMultiSelectPrompt[TValue comparable](params GroupMultiSelectPromptParams[TValue]) *GroupMultiSelectPrompt[TValue]

NewGroupMultiSelectPrompt initializes and returns a new instance of GroupMultiSelectPrompt.

The user can navigate between options using arrow keys. The user can select multiple options using space key. The prompt returns the values of the selected options. If the user cancels the prompt, it returns an error. If an error occurs during the prompt, it also returns an error.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • Options (map[string][]MultiSelectOption[TValue]): A map of grouped options for the prompt (default: nil.
  • InitialValue ([]TValue): The initial selected values (default: nil.
  • DisabledGroups (bool): Whether groups are disabled for selection (default: false).
  • Required (bool): Whether the prompt requires at least one selection (default: false).
  • Validate (func(value []TValue) error): Custom validation function for the prompt (default: nil).
  • Render (func(p *GroupMultiSelectPrompt[TValue]) string): Custom render function for the prompt (default: nil).

Returns:

  • *GroupMultiSelectPrompt[TValue]: A new instance of GroupMultiSelectPrompt.

func (*GroupMultiSelectPrompt[TValue]) IsGroupSelected

func (p *GroupMultiSelectPrompt[TValue]) IsGroupSelected(group *GroupMultiSelectOption[TValue]) bool

IsGroupSelected checks if all options within a group are selected. If groups are disabled, it always returns false.

Parameters:

  • group (*GroupMultiSelectOption[TValue]): The group to check for selection.

Returns:

  • bool: True if all options in the group are selected, false otherwise.

type GroupMultiSelectPromptParams

type GroupMultiSelectPromptParams[TValue comparable] struct {
	Context        context.Context
	Input          *os.File
	Output         *os.File
	Options        map[string][]MultiSelectOption[TValue]
	InitialValue   []TValue
	DisabledGroups bool
	Required       bool
	Validate       func(value []TValue) error
	Render         func(p *GroupMultiSelectPrompt[TValue]) string
}

type Key

type Key struct {
	Name  KeyName
	Char  string
	Shift bool
	Ctrl  bool
}

type KeyName

type KeyName string
const (
	UpKey        KeyName = "Up"
	DownKey      KeyName = "Down"
	LeftKey      KeyName = "Left"
	RightKey     KeyName = "Right"
	HomeKey      KeyName = "Home"
	EndKey       KeyName = "End"
	SpaceKey     KeyName = "Space"
	EnterKey     KeyName = "Enter"
	CancelKey    KeyName = "Cancel"
	TabKey       KeyName = "Tab"
	BackspaceKey KeyName = "Backspace"
	EscapeKey    KeyName = "Escape"
)

type LineOption

type LineOption int
const (
	FirstLine LineOption = iota
	NewLine
	LastLine
)

type MultiSelectOption

type MultiSelectOption[TValue comparable] struct {
	Label      string
	Value      TValue
	IsSelected bool
}

type MultiSelectPathPrompt

type MultiSelectPathPrompt struct {
	Prompt[[]string]
	Root          *PathNode
	CurrentOption *PathNode
	OnlyShowDir   bool
	Filter        bool
	Search        string
	Required      bool
	FileSystem    FileSystem
}

func NewMultiSelectPathPrompt

func NewMultiSelectPathPrompt(params MultiSelectPathPromptParams) *MultiSelectPathPrompt

NewMultiSelectPathPrompt initializes and returns a new instance of MultiSelectPathPrompt.

The user can navigate through directories and files using arrow keys. The user can select multiple options using space key. The prompt returns the path of the selected options. If the user cancels the prompt, it returns an error. If an error occurs during the prompt, it also returns an error.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • InitialValue ([]string): Initial selected paths (default: nil).
  • InitialPath (string): The initial directory path to start from (default: current working directory).
  • OnlyShowDir (bool): Whether to only show directories (default: false).
  • Required (bool): Whether at least one option must be selected (default: false).
  • Filter (bool): Whether to enable filtering of options (default: false).
  • FileSystem (FileSystem): The file system implementation to use (default: OSFileSystem).
  • Validate (func(value []string) error): Custom validation function (default: nil).
  • Render (func(p *MultiSelectPathPrompt) string): Custom render function (default: nil).

Returns:

  • *MultiSelectPathPrompt: A new instance of MultiSelectPathPrompt.

func (*MultiSelectPathPrompt) Options

func (p *MultiSelectPathPrompt) Options() []*PathNode

Options returns a list of filtered PathNode options based on the current layer and search term.

Returns:

  • []*PathNode: A slice of PathNode objects representing the available options.

type MultiSelectPathPromptParams

type MultiSelectPathPromptParams struct {
	Context      context.Context
	Input        *os.File
	Output       *os.File
	InitialValue []string
	InitialPath  string
	OnlyShowDir  bool
	Required     bool
	Filter       bool
	FileSystem   FileSystem
	Validate     func(value []string) error
	Render       func(p *MultiSelectPathPrompt) string
}

type MultiSelectPrompt

type MultiSelectPrompt[TValue comparable] struct {
	Prompt[[]TValue]

	Options  []*MultiSelectOption[TValue]
	Search   string
	Filter   bool
	Required bool
	// contains filtered or unexported fields
}

func NewMultiSelectPrompt

func NewMultiSelectPrompt[TValue comparable](params MultiSelectPromptParams[TValue]) *MultiSelectPrompt[TValue]

NewMultiSelectPrompt initializes and returns a new instance of MultiSelectPrompt.

The user can navigate through options using arrow keys. The user can select multiple options using space key. The prompt returns the value of the selected options. If the user cancels the prompt, it returns an error. If an error occurs during the prompt, it also returns an error.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • Options ([]*MultiSelectOption[TValue]): A list of options for the prompt (default: nil.
  • InitialValue ([]TValue): The initial selected values (default: nil.
  • Filter (bool): Whether to enable filtering of options (default: false).
  • Required (bool): Whether the prompt requires at least one selection (default: false).
  • Validate (func(value []TValue) error): Custom validation function for the prompt (default: nil).
  • Render (func(p *MultiSelectPrompt[TValue]) string): Custom render function for the prompt (default: nil).

Returns:

  • *MultiSelectPrompt[TValue]: A new instance of MultiSelectPrompt.

type MultiSelectPromptParams

type MultiSelectPromptParams[TValue comparable] struct {
	Context      context.Context
	Input        *os.File
	Output       *os.File
	Options      []*MultiSelectOption[TValue]
	InitialValue []TValue
	Filter       bool
	Required     bool
	Validate     func(value []TValue) error
	Render       func(p *MultiSelectPrompt[TValue]) string
}

type PasswordPrompt

type PasswordPrompt struct {
	Prompt[string]
	Required bool
}

func NewPasswordPrompt

func NewPasswordPrompt(params PasswordPromptParams) *PasswordPrompt

NewPasswordPrompt initializes and returns a new instance of PasswordPrompt.

The user can input a password. The password is masked by asterisks ("*"). The prompt returns the password without the mask. If the user cancels the prompt, it returns an error. If an error occurs during the prompt, it also returns an error.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • InitialValue (string): The initial value of the password input (default: "").
  • Required (bool): Whether the password input is required (default: false).
  • Validate (func(value string) error): Custom validation function for the password (default: nil).
  • Render (func(p *PasswordPrompt) string): Custom render function for the prompt (default: nil).

Returns:

  • *PasswordPrompt: A new instance of PasswordPrompt.

func (*PasswordPrompt) ValueWithMask

func (p *PasswordPrompt) ValueWithMask() string

ValueWithMask returns the current password value masked with asterisks (*). This is useful for displaying the password in a secure manner.

Returns:

  • string: The masked password value.

func (*PasswordPrompt) ValueWithMaskAndCursor

func (p *PasswordPrompt) ValueWithMaskAndCursor() string

ValueWithMaskAndCursor returns the current password value masked with asterisks (*) and includes a cursor indicator. The cursor is represented by an inverse character at the current cursor position.

Returns:

  • string: The masked password value with the cursor indicator.

type PasswordPromptParams

type PasswordPromptParams struct {
	Context      context.Context
	Input        *os.File
	Output       *os.File
	InitialValue string
	Required     bool
	Validate     func(value string) error
	Render       func(p *PasswordPrompt) string
}

type PathNode

type PathNode struct {
	Index  int
	Depth  int
	Path   string
	Name   string
	Parent *PathNode

	IsDir    bool
	IsOpen   bool
	Children []*PathNode

	IsSelected bool

	FileSystem  FileSystem
	OnlyShowDir bool
}

func NewPathNode

func NewPathNode(rootPath string, options PathNodeOptions) *PathNode

NewPathNode initializes a new PathNode with the provided root path and options. It sets up the root node, configures the file system, and opens the node to populate its children.

Parameters:

  • rootPath (string): The root path for the node.
  • options (PathNodeOptions): Configuration options for the node.
  • OnlyShowDir (bool): Whether to only show directories (default: false).
  • FileSystem (FileSystem): The file system implementation to use (default: OSFileSystem).

Returns:

  • *PathNode: A new instance of PathNode.

func (*PathNode) Close

func (p *PathNode) Close()

Close closes the current PathNode by clearing its children and marking it as closed.

func (*PathNode) FilteredFlat

func (p *PathNode) FilteredFlat(search string, currentNode *PathNode) []*PathNode

FilteredFlat returns a filtered and flattened list of nodes based on the provided search term. If the search term is empty or invalid, it returns the full flattened list.

Parameters:

  • search (string): The search term to filter nodes by.
  • currentNode (*PathNode): The current node to filter relative to.

Returns:

  • []*PathNode: A slice of filtered nodes.

func (*PathNode) FilteredLayer

func (p *PathNode) FilteredLayer(search string) []*PathNode

FilteredLayer returns a filtered list of nodes in the current layer based on the provided search term. If the search term is empty or invalid, it returns the full layer.

Parameters:

  • search (string): The search term to filter nodes by.

Returns:

  • []*PathNode: A slice of filtered nodes in the current layer.

func (*PathNode) FirstChild

func (p *PathNode) FirstChild() *PathNode

FirstChild returns the first child of the current node. If the node has no children, it returns nil.

Returns:

  • *PathNode: The first child node.

func (*PathNode) Flat

func (p *PathNode) Flat() []*PathNode

Flat returns a flattened list of all nodes in the tree, starting from the current node.

Returns:

  • []*PathNode: A slice of all nodes in the tree.

func (*PathNode) IndexOf

func (p *PathNode) IndexOf(node *PathNode, options []*PathNode) int

IndexOf returns the index of a given node in the provided options slice. If the node is not found, it returns -1.

Parameters:

  • node (*PathNode): The node to find the index of.
  • options ([]*PathNode): The slice of nodes to search in.

Returns:

  • int: The index of the node, or -1 if not found.

func (*PathNode) IsEqual

func (p *PathNode) IsEqual(node *PathNode) bool

IsEqual checks if the current node is equal to another node based on their paths.

Parameters:

  • node (*PathNode): The node to compare with.

Returns:

  • bool: True if the nodes are equal, false otherwise.

func (*PathNode) IsRoot

func (p *PathNode) IsRoot() bool

IsRoot checks if the current node is the root node. It returns true if the node has no parent, false otherwise.

Returns:

  • bool: True if the node is the root, false otherwise.

func (*PathNode) LastChild

func (p *PathNode) LastChild() *PathNode

LastChild returns the last child of the current node. If the node has no children, it returns nil.

Returns:

  • *PathNode: The last child node.

func (*PathNode) Layer

func (p *PathNode) Layer() []*PathNode

Layer returns the children of the current node's parent, representing the current layer in the tree.

Returns:

  • []*PathNode: A slice of nodes in the current layer.

func (*PathNode) NextChild

func (p *PathNode) NextChild(index int) *PathNode

NextChild returns the next child relative to the provided index. If the index is out of bounds, it wraps around to the first child.

Parameters:

  • index (int): The index of the current child.

Returns:

  • *PathNode: The next child node

func (*PathNode) Open

func (p *PathNode) Open()

Open opens the current PathNode, reads its directory entries, and populates its children. If the node is not a directory or is already open, this function does nothing.

func (*PathNode) PrevChild

func (p *PathNode) PrevChild(index int) *PathNode

PrevChild returns the previous child relative to the provided index. If the index is out of bounds, it wraps around to the last child.

Parameters:

  • index (int): The index of the current child.

Returns:

  • *PathNode: The previous child node.

func (*PathNode) TraverseNodes

func (p *PathNode) TraverseNodes(visit func(node *PathNode))

TraverseNodes traverses the node and its children, applying the provided visit function to each node.

Parameters:

  • visit (func(node *PathNode)): A function to apply to each node during traversal.

type PathNodeOptions

type PathNodeOptions struct {
	OnlyShowDir bool
	FileSystem  FileSystem
}

type PathPrompt

type PathPrompt struct {
	Prompt[string]
	OnlyShowDir bool
	Required    bool
	Hint        string
	HintOptions []string
	HintIndex   int
	FileSystem  FileSystem
}

func NewPathPrompt

func NewPathPrompt(params PathPromptParams) *PathPrompt

NewPathPrompt initializes and returns a new instance of PathPrompt.

The user can input a path. The prompt has built-in autosuggestion and autocomplete features. The prompt returns the path. If the user cancels the prompt, it returns an error. If an error occurs during the prompt, it also returns an error.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • InitialValue (string): The initial value of the path input (default: current working directory).
  • OnlyShowDir (bool): Whether to only show directories (default: false).
  • Required (bool): Whether the path input is required (default: false).
  • FileSystem (FileSystem): The file system implementation to use (default: OSFileSystem).
  • Validate (func(value string) error): Custom validation function for the path (default: nil).
  • Render (func(p *PathPrompt) string): Custom render function for the prompt (default: nil).

Returns:

  • *PathPrompt: A new instance of PathPrompt.

func (*PathPrompt) ValueWithCursor

func (p *PathPrompt) ValueWithCursor() string

ValueWithCursor returns the current path value with a cursor indicator. The cursor is represented by an inverse character at the current cursor position. If the cursor is at the end of the value, the hint is displayed.

Returns:

  • string: The path value with the cursor indicator and hint.

type PathPromptParams

type PathPromptParams struct {
	Context      context.Context
	Input        *os.File
	Output       *os.File
	InitialValue string
	OnlyShowDir  bool
	Required     bool
	FileSystem   FileSystem
	Validate     func(value string) error
	Render       func(p *PathPrompt) string
}

type Prompt

type Prompt[TValue any] struct {
	State       State
	Error       string
	Value       TValue
	CursorIndex int

	Validate           func(value TValue) error
	ValidationDuration time.Duration
	IsValidating       bool

	Render func(p *Prompt[TValue]) string
	Frame  string
	// contains filtered or unexported fields
}

func NewPrompt

func NewPrompt[TValue any](params PromptParams[TValue]) *Prompt[TValue]

NewPrompt initializes a new Prompt with the provided parameters.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • InitialValue (TValue): The initial value of the prompt (default: zero value of TValue).
  • CursorIndex (int): The initial cursor position in the input (default: 0).
  • Validate (func(value TValue) error): Custom validation function for the input (default: nil).
  • Render (func(p *Prompt[TValue]) string): Custom render function for the prompt (default: nil).

Returns:

  • *Prompt[TValue]: A new instance of Prompt.

func (*Prompt[TValue]) DiffLines

func (p *Prompt[TValue]) DiffLines(oldFrame, newFrame string) []int

DiffLines calculates the difference between an old and a new frame.

func (*Prompt[TValue]) Emit

func (p *Prompt[TValue]) Emit(event Event, args ...any)

Emit triggers the specified event with the given arguments.

func (*Prompt[TValue]) FormatLines

func (p *Prompt[TValue]) FormatLines(lines []string, options FormatLinesOptions) string

FormatLines applies styles to multiple lines based on their type and the provided options.

func (*Prompt[TValue]) LimitLines

func (p *Prompt[TValue]) LimitLines(lines []string, usedLines int) string

LimitLines limits the number of lines to fit within the terminal size.

func (*Prompt[TValue]) Off

func (p *Prompt[TValue]) Off(event Event, listener EventListener)

Off removes a listener for the specified event.

func (*Prompt[TValue]) On

func (p *Prompt[TValue]) On(event Event, listener EventListener)

On registers a listener for the specified event.

func (*Prompt[TValue]) Once

func (p *Prompt[TValue]) Once(event Event, listener EventListener)

Once registers a one-time listener for the specified event.

func (*Prompt[TValue]) ParseKey

func (p *Prompt[TValue]) ParseKey(r rune) *Key

ParseKey parses a rune into a Key.

func (*Prompt[TValue]) PressKey

func (p *Prompt[TValue]) PressKey(key *Key)

PressKey handles key press events and updates the state of the prompt.

func (*Prompt[TValue]) Run

func (p *Prompt[TValue]) Run() (TValue, error)

Run runs the prompt and processes input.

func (*Prompt[TValue]) Size

func (p *Prompt[TValue]) Size() (width int, height int, err error)

Size retrieves the width and height of the terminal output.

func (*Prompt[TValue]) TrackKeyValue

func (p *Prompt[TValue]) TrackKeyValue(key *Key, value string, cursorIndex int) (newValue string, newCursorIndex int)

TrackKeyValue updates the string value and cursor position based on key presses.

type PromptParams

type PromptParams[TValue any] struct {
	Context      context.Context
	Input        *os.File
	Output       *os.File
	InitialValue TValue
	CursorIndex  int
	Validate     func(value TValue) error
	Render       func(p *Prompt[TValue]) string
}

type SelectKeyOption

type SelectKeyOption[TValue any] struct {
	Label string
	Value TValue
	Key   string
}

type SelectKeyPrompt

type SelectKeyPrompt[TValue any] struct {
	Prompt[TValue]
	Options []*SelectKeyOption[TValue]
}

func NewSelectKeyPrompt

func NewSelectKeyPrompt[TValue any](params SelectKeyPromptParams[TValue]) *SelectKeyPrompt[TValue]

The user can select an option by clicking on the related key. The prompt returns the value of the selected option. If the user cancels the prompt, it returns an error. If an error occurs during the prompt, it also returns an error.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • Options ([]*SelectKeyOption[TValue]): A list of options for the prompt (default: nil).
  • Render (func(p *SelectKeyPrompt[TValue]) string): Custom render function for the prompt (default: nil).

Returns:

  • *SelectKeyPrompt[TValue]: A new instance of SelectKeyPrompt.

type SelectKeyPromptParams

type SelectKeyPromptParams[TValue any] struct {
	Context context.Context
	Input   *os.File
	Output  *os.File
	Options []*SelectKeyOption[TValue]
	Render  func(p *SelectKeyPrompt[TValue]) string
}

type SelectOption

type SelectOption[TValue comparable] struct {
	Label string
	Value TValue
}

type SelectPathPrompt

type SelectPathPrompt struct {
	Prompt[string]
	Root          *PathNode
	CurrentLayer  []*PathNode
	CurrentOption *PathNode
	OnlyShowDir   bool
	Search        string
	Filter        bool
	FileSystem    FileSystem
}

func NewSelectPathPrompt

func NewSelectPathPrompt(params SelectPathPromptParams) *SelectPathPrompt

NewSelectPathPrompt initializes and returns a new instance of SelectPathPrompt.

The user can navigate through directories and files using arrow keys. The user can select an option using enter key. The prompt returns the path of the selected option. If the user cancels the prompt, it returns an error. If an error occurs during the prompt, it also returns an error.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • InitialValue (string): The initial path value (default: current working directory).
  • OnlyShowDir (bool): Whether to only show directories (default: false).
  • Filter (bool): Whether to enable filtering of options (default: false).
  • FileSystem (FileSystem): The file system implementation to use (default: OSFileSystem).
  • Render (func(p *SelectPathPrompt) string): Custom render function for the prompt (default: nil).

Returns:

  • *SelectPathPrompt: A new instance of SelectPathPrompt.

func (*SelectPathPrompt) Options

func (p *SelectPathPrompt) Options() []*PathNode

Options returns a list of filtered and flattened PathNode options based on the current search term and selected node.

Returns:

  • []*PathNode: A slice of PathNode objects representing the available options.

type SelectPathPromptParams

type SelectPathPromptParams struct {
	Context      context.Context
	Input        *os.File
	Output       *os.File
	InitialValue string
	OnlyShowDir  bool
	Filter       bool
	FileSystem   FileSystem
	Render       func(p *SelectPathPrompt) string
}

type SelectPrompt

type SelectPrompt[TValue comparable] struct {
	Prompt[TValue]

	Options  []*SelectOption[TValue]
	Search   string
	Filter   bool
	Required bool
	// contains filtered or unexported fields
}

func NewSelectPrompt

func NewSelectPrompt[TValue comparable](params SelectPromptParams[TValue]) *SelectPrompt[TValue]

NewSelectPrompt initializes and returns a new instance of SelectPrompt.

The user can navigate through options using arrow keys. The user can select an option using enter key. The prompt returns the value of the selected option. If the user cancels the prompt, it returns an error. If an error occurs during the prompt, it also returns an error.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • InitialValue (TValue): The initial value of the prompt (default: zero value of TValue).
  • Options ([]*SelectOption[TValue]): A list of options for the prompt (default: nil).
  • Filter (bool): Whether to enable filtering of options (default: false).
  • Required (bool): Whether the prompt requires a selection (default: false).
  • Render (func(p *SelectPrompt[TValue]) string): Custom render function for the prompt (default: nil).

Returns:

  • *SelectPrompt[TValue]: A new instance of SelectPrompt.

type SelectPromptParams

type SelectPromptParams[TValue comparable] struct {
	Context      context.Context
	Input        *os.File
	Output       *os.File
	InitialValue TValue
	Options      []*SelectOption[TValue]
	Filter       bool
	Required     bool
	Render       func(p *SelectPrompt[TValue]) string
}

type Settings

type Settings struct {
	// Aliases is a map of custom key bindings for actions.
	// If a key binding already exists in the aliases map, it is not overwritten.
	Aliases map[KeyName]Action
}

Settings defines user-configurable settings for the application.

type State

type State int
const (
	// InitialState is the initial state of the prompt
	InitialState State = iota
	// ActiveState is set after the user's first action
	ActiveState
	// ValidateState is set after 400ms of validation (e.g., checking user input)
	ValidateState
	// ErrorState is set if there is an error during validation
	ErrorState
	// CancelState is set after the user cancels the prompt
	CancelState
	// SubmitState is set after the user submits the input
	SubmitState
)

type TextPrompt

type TextPrompt struct {
	Prompt[string]
	Placeholder string
	Required    bool
}

func NewTextPrompt

func NewTextPrompt(params TextPromptParams) *TextPrompt

NewTextPrompt initializes and returns a new instance of TextPrompt.

The user can input a value. The prompt returns the value. If the user cancels the prompt, it returns an error. If an error occurs during the prompt, it also returns an error.

Parameters:

  • Context (context.Context): The context for the prompt (default: context.Background).
  • Input (*os.File): The input stream for the prompt (default: OSFileSystem).
  • Output (*os.File): The output stream for the prompt (default: OSFileSystem).
  • InitialValue (string): The initial value of the text input (default: "").
  • Placeholder (string): The placeholder text to display when the input is empty (default: "").
  • Required (bool): Whether the text input is required (default: false).
  • Validate (func(value string) error): Custom validation function for the input (default: nil).
  • Render (func(p *TextPrompt) string): Custom render function for the prompt (default: nil).

Returns:

  • *TextPrompt: A new instance of TextPrompt.

func (*TextPrompt) ValueWithCursor

func (p *TextPrompt) ValueWithCursor() string

ValueWithCursor returns the current input value with a cursor indicator. The cursor is represented by an inverse character at the current cursor position. If the cursor is at the end of the value, it is displayed as a block character.

Returns:

  • string: The input value with the cursor indicator.

type TextPromptParams

type TextPromptParams struct {
	Context      context.Context
	Input        *os.File
	Output       *os.File
	InitialValue string
	Placeholder  string
	Required     bool
	Validate     func(value string) error
	Render       func(p *TextPrompt) string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳