state

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package state provides minimal reactive primitives for terminal UIs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Batch

func Batch(fn func())

Batch defers subscriber notifications until fn completes.

func Debounce

func Debounce(duration time.Duration, fn func()) func()

Debounce returns a function that delays calling fn until after the specified duration has elapsed since the last invocation. Each call resets the timer. Useful for search-as-you-type, resize handlers, and similar scenarios where only the final event in a burst matters.

func EqualComparable

func EqualComparable[T comparable](a, b T) bool

EqualComparable compares comparable values with ==.

func Throttle

func Throttle(duration time.Duration, fn func()) func()

Throttle returns a function that calls fn at most once per duration. The first call executes immediately; subsequent calls within the duration window are silently dropped. After the duration elapses, the next call will execute immediately again.

Types

type AsyncScheduler

type AsyncScheduler struct{}

AsyncScheduler runs callbacks in a new goroutine.

func (AsyncScheduler) Schedule

func (AsyncScheduler) Schedule(fn func())

Schedule dispatches fn asynchronously.

type Computed

type Computed[T any] struct {
	// contains filtered or unexported fields
}

Computed derives its value from other reactive sources and automatically recalculates when dependencies change. Read with Get; subscribe with Subscribe.

func NewComputed

func NewComputed[T any](compute func() T, deps ...Subscribable) *Computed[T]

NewComputed creates a derived value from dependencies. If no deps are provided, dependencies are detected automatically by tracking signal reads.

func NewComputedWithScheduler

func NewComputedWithScheduler[T any](scheduler Scheduler, compute func() T, deps ...Subscribable) *Computed[T]

NewComputedWithScheduler creates a derived value and schedules recomputes. If no deps are provided, dependencies are detected automatically.

func (*Computed[T]) Get

func (c *Computed[T]) Get() T

Get returns the current computed value.

func (*Computed[T]) SetEqualFunc

func (c *Computed[T]) SetEqualFunc(fn EqualFunc[T])

SetEqualFunc configures the equality check used to suppress redundant updates.

func (*Computed[T]) Stop

func (c *Computed[T]) Stop()

Stop unsubscribes from dependency updates.

func (*Computed[T]) Subscribe

func (c *Computed[T]) Subscribe(fn func()) func()

Subscribe registers a listener for change notifications.

func (*Computed[T]) SubscribeWithScheduler

func (c *Computed[T]) SubscribeWithScheduler(scheduler Scheduler, fn func()) func()

SubscribeWithScheduler registers a listener using a scheduler. If scheduler is nil, callbacks run synchronously.

type Effect

type Effect func()

Effect runs side effects when dependencies change.

type EffectHandle

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

EffectHandle manages an effect's lifecycle.

func NewEffect

func NewEffect(fn Effect, deps ...Signalish) *EffectHandle

NewEffect creates an effect that runs when deps change.

func NewEffectWithScheduler

func NewEffectWithScheduler(scheduler Scheduler, fn Effect, deps ...Signalish) *EffectHandle

NewEffectWithScheduler creates an effect with a scheduler.

func (*EffectHandle) Dispose

func (e *EffectHandle) Dispose()

Dispose stops the effect and unsubscribes from dependencies.

func (*EffectHandle) Trigger

func (e *EffectHandle) Trigger()

Trigger runs the effect once.

type EqualFunc

type EqualFunc[T any] func(a, b T) bool

EqualFunc compares two values for equality.

type History

type History[T any] struct {
	// contains filtered or unexported fields
}

History provides generic undo/redo with branching history support.

func NewHistory

func NewHistory[T any](initial T, opts ...HistoryOption) *History[T]

NewHistory creates a new history with an initial state.

func (*History[T]) CanRedo

func (h *History[T]) CanRedo() bool

CanRedo returns true if redo is possible.

func (*History[T]) CanUndo

func (h *History[T]) CanUndo() bool

CanUndo returns true if undo is possible.

func (*History[T]) Clear

func (h *History[T]) Clear()

Clear resets history to the initial state only.

func (*History[T]) Current

func (h *History[T]) Current() T

Current returns the current state.

func (*History[T]) Push

func (h *History[T]) Push(state T)

Push records a new state, clearing the redo stack.

func (*History[T]) PushGrouped

func (h *History[T]) PushGrouped(state T)

PushGrouped groups with recent pushes if within the group window.

func (*History[T]) Redo

func (h *History[T]) Redo() (T, bool)

Redo moves forward one state and returns the new current state. Returns false if no redo is available.

func (*History[T]) RedoDepth

func (h *History[T]) RedoDepth() int

RedoDepth returns the number of redo steps available.

func (*History[T]) RestoreSnapshot

func (h *History[T]) RestoreSnapshot(snap Snapshot[T])

RestoreSnapshot restores history from a snapshot.

func (*History[T]) SetSizeFunc

func (h *History[T]) SetSizeFunc(fn func(T) int64)

SetSizeFunc sets a custom function to calculate the size of a state. This is used for memory limit enforcement.

func (*History[T]) Subscribe

func (h *History[T]) Subscribe(fn func()) func()

Subscribe registers a listener for history changes. Returns an unsubscribe function.

func (*History[T]) TakeSnapshot

func (h *History[T]) TakeSnapshot() Snapshot[T]

TakeSnapshot returns a linear snapshot of states from root to current. Useful for serialization.

func (*History[T]) Undo

func (h *History[T]) Undo() (T, bool)

Undo moves back one state and returns the new current state. Returns false if already at root.

func (*History[T]) UndoDepth

func (h *History[T]) UndoDepth() int

UndoDepth returns the number of undo steps available.

type HistoryOption

type HistoryOption func(*historyConfig)

HistoryOption configures a History instance.

func WithGroupWindow

func WithGroupWindow(d time.Duration) HistoryOption

WithGroupWindow sets the time window for grouping operations. Operations within this window will be merged into a single undo step.

func WithMaxBytes

func WithMaxBytes(n int64) HistoryOption

WithMaxBytes sets the memory limit for history (0 = unlimited).

func WithMaxDepth

func WithMaxDepth(n int) HistoryOption

WithMaxDepth sets the maximum number of undo steps (0 = unlimited).

type Queue

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

Queue batches callbacks for explicit flushing.

func NewQueue

func NewQueue() *Queue

NewQueue creates an empty queue.

func (*Queue) Flush

func (q *Queue) Flush() int

Flush executes queued callbacks and returns the count.

func (*Queue) Schedule

func (q *Queue) Schedule(fn func())

Schedule enqueues a callback for later flushing.

type Readable

type Readable[T any] interface {
	Get() T
	Subscribe(fn func()) func()
	SubscribeWithScheduler(scheduler Scheduler, fn func()) func()
}

Readable exposes read-only access to a reactive value. Both Signal and Computed satisfy this interface.

type Resource

type Resource[T any] struct {
	Data    T
	Loading bool
	Error   error
	// contains filtered or unexported fields
}

Resource represents asynchronously loaded data with status.

func NewResource

func NewResource[T any](fetcher func() (T, error), deps ...Signalish) *Resource[T]

NewResource creates a resource that refetches when deps change.

func NewResourceWithScheduler

func NewResourceWithScheduler[T any](scheduler Scheduler, fetcher func() (T, error), deps ...Signalish) *Resource[T]

NewResourceWithScheduler creates a resource with dependency scheduling.

func (*Resource[T]) Dispose

func (r *Resource[T]) Dispose()

Dispose unsubscribes from dependencies.

func (*Resource[T]) Get

func (r *Resource[T]) Get() Resource[T]

Get returns a snapshot of the resource state.

func (*Resource[T]) Refetch

func (r *Resource[T]) Refetch()

Refetch triggers a new fetch cycle.

func (*Resource[T]) Subscribe

func (r *Resource[T]) Subscribe(fn func()) func()

Subscribe registers a listener for state changes.

func (*Resource[T]) SubscribeWithScheduler

func (r *Resource[T]) SubscribeWithScheduler(scheduler Scheduler, fn func()) func()

SubscribeWithScheduler registers a listener using a scheduler.

type Scheduler

type Scheduler interface {
	Schedule(fn func())
}

Scheduler dispatches subscription callbacks.

var DirectScheduler Scheduler = SchedulerFunc(func(fn func()) {
	if fn != nil {
		fn()
	}
})

DirectScheduler runs callbacks immediately in the caller goroutine.

type SchedulerFunc

type SchedulerFunc func(func())

SchedulerFunc adapts a function into a Scheduler.

func (SchedulerFunc) Schedule

func (f SchedulerFunc) Schedule(fn func())

Schedule dispatches fn using the wrapped function.

type Signal

type Signal[T any] struct {
	// contains filtered or unexported fields
}

Signal holds a mutable value and notifies subscribers when it changes. It is the core reactive primitive -- use Get to read, Set to write. Redundant Set calls (same value) are suppressed via equality checking.

func DebouncedSignal

func DebouncedSignal[T any](source *Signal[T], delay time.Duration) *Signal[T]

DebouncedSignal creates a new signal that follows the source signal but only updates after the source value has been stable for the given delay. This is useful for debouncing user input before triggering expensive operations like search queries or validation.

The returned signal starts with the current value of source.

func NewSignal

func NewSignal[T any](initial T) *Signal[T]

NewSignal creates a new signal with an initial value. Automatically configures appropriate equality checking:

  • comparable types (int, string, etc.) use ==
  • complex types use reflect.DeepEqual

func (*Signal[T]) Get

func (s *Signal[T]) Get() T

Get returns the current value.

func (*Signal[T]) Set

func (s *Signal[T]) Set(value T) bool

Set updates the value and notifies subscribers if it changed.

func (*Signal[T]) SetEqualFunc

func (s *Signal[T]) SetEqualFunc(fn EqualFunc[T])

SetEqualFunc configures the equality check used to suppress redundant updates.

func (*Signal[T]) Subscribe

func (s *Signal[T]) Subscribe(fn func()) func()

Subscribe registers a listener for change notifications.

func (*Signal[T]) SubscribeWithScheduler

func (s *Signal[T]) SubscribeWithScheduler(scheduler Scheduler, fn func()) func()

SubscribeWithScheduler registers a listener using a scheduler. If scheduler is nil, callbacks run synchronously.

func (*Signal[T]) Update

func (s *Signal[T]) Update(fn func(T) T) bool

Update replaces the value using fn. fn runs outside the signal lock; Update is not atomic across goroutines.

type Signalish

type Signalish = Subscribable

Signalish describes a reactive dependency.

type Snapshot

type Snapshot[T any] struct {
	States  []T
	Current int
}

Snapshot represents a serializable state of the history.

type Subscribable

type Subscribable interface {
	Subscribe(fn func()) func()
}

Subscribable is implemented by any reactive value that supports change notifications. Subscribe returns an unsubscribe function. Both Signal and Computed implement this interface.

type Subscriptions

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

Subscriptions tracks and clears multiple unsubscribe callbacks.

func NewSubscriptions

func NewSubscriptions(scheduler Scheduler) *Subscriptions

NewSubscriptions creates a Subscriptions with a default scheduler.

func (*Subscriptions) Add

func (s *Subscriptions) Add(unsub func())

Add registers an unsubscribe callback.

func (*Subscriptions) Clear

func (s *Subscriptions) Clear()

Clear unsubscribes all tracked callbacks.

func (*Subscriptions) Observe

func (s *Subscriptions) Observe(sub Subscribable, fn func())

Observe registers a listener using the default scheduler.

func (*Subscriptions) Scheduler

func (s *Subscriptions) Scheduler() Scheduler

Scheduler returns the default scheduler.

func (*Subscriptions) SetScheduler

func (s *Subscriptions) SetScheduler(scheduler Scheduler)

SetScheduler updates the default scheduler.

func (*Subscriptions) Subscribe

func (s *Subscriptions) Subscribe(sub Subscribable, fn func())

Subscribe registers a listener and tracks the unsubscribe.

func (*Subscriptions) SubscribeWithScheduler

func (s *Subscriptions) SubscribeWithScheduler(sub Subscribable, scheduler Scheduler, fn func())

SubscribeWithScheduler registers a listener using a scheduler and tracks it.

type Writable

type Writable[T any] interface {
	Readable[T]
	Set(value T) bool
	Update(fn func(T) T) bool
}

Writable exposes read/write access to a reactive value. Signal satisfies this interface; Computed does not (it is read-only).

Jump to

Keyboard shortcuts

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