kites

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 9 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

📦 Kites

Kites is a lightweight, thread-safe external state store for global state management outside of the Virtual DOM (VDOM) tree, inspired by libraries like Zustand and Redux. It uses the State-Method + Higher-Order Action pattern directly on *kites.Store[T], integrates with Kitex via selector-based hooks (kites.Use, kites.UseContext), and ships with a Redux/Zustand-style DevTools inspector (extras/kites/kitesdt) featuring automatic action names, field-level diffs, and time-travel debugging.

✨ Features

  • 🔒 Fully Thread-Safe: Safe for concurrent updates and reads using sync.RWMutex with copy-on-write draft isolation for slices, maps, and pointers.
  • 🛑 Deadlock Protection: Listener notifications are dispatched outside of the write lock to prevent deadlocks when updating state inside subscriber callbacks.
  • 🎯 Selector-Based Re-rendering: Components only subscribe to and re-render on changes to specific slices of the state. If the selected state hasn't changed, the component bails out of re-rendering.
  • ⚡ State-Method + Higher-Order Actions: Define pointer-receiver mutation methods directly on your state struct T, pass Go method expressions ((*AppState).Increment) to store.Update, store.Action, kites.Bind, and kites.Action, and compose multiple mutators in a single atomic Update.
  • 🧪 Scoped DI & Parallel Testing: Create typed store contexts with kites.NewContext(initialState) and mount isolated *kites.Store[T] instances per VDOM subtree via Provider, enabling t.Parallel() tests and action-only consumers (ctx.Action(...), ctx.Store()).
  • 🔍 Redux/Zustand DevTools (kitesdt): Automatically captures action names (e.g. "Increment", "AddCount", "Reset"), renders an action timeline with Diff / State / Raw tabs, and provides a time-travel scrubber.

🚀 Getting Started

1. Define State with Selector & Action Methods

Keep your state T as pure serializable data. Define read-only selectors as value-receiver methods (func (s AppState) ...) and mutating actions as pointer-receiver methods (func (s *AppState) ...):

package store

import "github.com/masterkeysrd/kite/extras/kites"

type AppState struct {
	Counter int
	Theme   string
}

// Value-receiver methods = Read-only Selectors (func(AppState) U)
func (s AppState) SelectCounter() int         { return s.Counter }
func (s AppState) IsAbove(threshold int) bool { return s.Counter > threshold }

// Pointer-receiver methods = Mutating Actions (func(*AppState))
func (s *AppState) Increment()     { s.Counter++ }
func (s *AppState) ResetCounter()  { s.Counter = 0 }
func (s *AppState) AddCount(n int) { s.Counter += n }

var AppCtx = kites.NewContext(AppState{
	Counter: 0,
	Theme:   "dark",
})
2. Connect Store to Components with Selectors & Actions

Pass value-receiver method expressions (or kites.Select for parameterized selectors) to kites.UseContext / kites.Use, and pass pointer-receiver method expressions (or kites.Bind) to ctx.Action / store.Action:

package store

import (
	"github.com/masterkeysrd/kite/extras/kites"
	"github.com/masterkeysrd/kite/extras/kitex"
	"github.com/masterkeysrd/kite/style"
)

var CounterDisplay = kitex.FC("CounterDisplay", func(_ kitex.NoProps) kitex.Node {
	// Component ONLY re-renders when Counter changes; Theme updates are ignored.
	count := kites.UseContext(AppCtx, AppState.SelectCounter)
	aboveTen := kites.UseContext(AppCtx, kites.Select(AppState.IsAbove, 10))

	return kitex.Box.Style(
		style.S().Padding(1),
		kitex.Span.Style(style.S().Bold(true), kitex.Textf("Counter: %d (above 10: %t)", count, aboveTen)),
	)
})

var Controls = kitex.FC("Controls", func(_ kitex.NoProps) kitex.Node {
	// Action-only: ctx.Action / ctx.Store() do NOT subscribe to state mutations.
	addCount := kites.Action(AppCtx.Store(), (*AppState).AddCount)

	return kitex.Box(kitex.BoxProps{},
		kitex.Button(kitex.ButtonProps{
			OnPress: AppCtx.Action((*AppState).Increment),
		}, kitex.Text("Increment")),
		kitex.Button(kitex.ButtonProps{
			OnPress: AppCtx.Action(kites.Bind((*AppState).AddCount, 10)),
		}, kitex.Text("+10")),
		kitex.Button(kitex.ButtonProps{
			OnPress: func() { addCount(5) },
		}, kitex.Text("+5")),
	)
})
3. Batching Multiple Mutators Atomically

Update accepts variadic func(*T) mutators, applying them sequentially under a single lock and a single copy-on-write clone, then notifying subscribers once:

appStore.Update(
	(*AppState).ResetCounter,
	(*AppState).Increment,
)
// DevTools records action: "ResetCounter + Increment"
4. DevTools Integration (extras/kites/kitesdt)

Register your store with kitesdt.Track and attach the extension to Kite's inspector:

kitesdt.Track("AppStore", AppCtx.Default())

if insp, err := devtools.Install(eng, devtools.Options{}); err == nil {
	kitexdt.Register(insp)
	kitesdt.Register(insp)
}

kitesdt automatically records action names (Increment, AddCount, Reset, SetState), previous/next snapshots for field-level Diff inspection, State / Raw tabs, and a time-travel scrubber with Jump / Reset / Commit & Clear.

5. Direct & Selector Subscriptions (Outside UI)
unsubscribe := appStore.Subscribe(func(newVal, oldVal AppState) {
	fmt.Printf("State updated from %+v to %+v\n", oldVal, newVal)
})
defer unsubscribe()

unsubCounter := kites.SubscribeSelector(appStore, func(s AppState) int {
	return s.Counter
}, func(newCount, oldCount int) {
	fmt.Printf("Counter changed: %d -> %d\n", oldCount, newCount)
})
defer unsubCounter()

💡 Good Practices

  1. Keep State T Pure Data with Pointer-Receiver Methods Keep your state T as pure serializable data and define actions as pointer-receiver methods (func (s *AppState) Increment()).

    Warning: Avoid placing func() fields inside state struct T when relying on automatic equality checks, as functions break Go's comparable constraint.

  2. Use kites.NewContext & Provider Instead of Hardcoded Singletons Prefer kites.NewContext(initialState) over referencing package-level store singletons directly inside components. Wrapping parallel tests with AppCtx.Provider(kites.Create(testState), ...) gives each test an isolated *kites.Store[T] so t.Parallel() works safely, and action-only components calling AppCtx.Action(...) or AppCtx.Store() never re-render when state mutates.

  3. Select the Narrowest Slice Prefer kites.Use(store, selector) or kites.UseContext(ctx, selector) over store.Use() / ctx.Use() in leaf components so unrelated field updates bail out before re-rendering.

  4. Choose the Right Mutation API

    • store.Update(mutators ...func(*T)): In-place mutations on a single isolated copy-on-write draft; supports method expressions and kites.Bind.
    • store.Action(mutators ...func(*T)) func(): Zero-argument handler wrapper for UI callbacks (OnPress).
    • kites.Bind(method, arg) func(*T): Curries a 1-argument func(*T, A) method with arg while preserving the method name for DevTools.
    • kites.Action(store, method) func(A): Returns a typed callable func(A) bound to store.
    • store.Set(func(T) T): Functional value transform returning the next state.
    • store.SetState(T): Direct full-state replacement (automatically cloned for isolation).
    • store.Reset(): Restores the initial state snapshot captured at Create time and notifies subscribers.
    • Never mutate snapshots returned by Get() or Use()—always mutate inside Update or Set.
  5. Parallel & Async Testing

    • Mount an isolated store per parallel test with ctx.Provider(kites.Create(initial), ...).
    • Use store.Reset() for cleanup in sequential tests.
    • Use kites.WaitFor(ctx, store, predicate) instead of time.Sleep when waiting for background goroutines to reach an expected state.

🛠 API Reference

Store & Higher-Order Actions
  • Create[T](initial T) *Store[T]: Instantiates a new store and saves an isolated copy of initial.
  • Store.Use() T: Subscribes the current functional component to the entire state T and returns the current snapshot.
  • Store.Initial() T: Returns a safe snapshot of the initial state configured at Create time.
  • Store.Get() T: Returns the current state snapshot.
  • Store.Set(updater func(T) T): Updates the state thread-safely using an isolated copy-on-write draft and notifies subscribers after unlocking.
  • Store.Update(mutators ...func(*T)): Applies one or more mutators sequentially to an isolated copy-on-write draft under a single lock and notifies subscribers once.
  • Store.Action(mutators ...func(*T)) func(): Returns func() { s.Update(mutators...) }.
  • Bind[T, A](method func(*T, A), arg A) func(*T): Curries method with arg into a func(*T) mutator while preserving method's name for DevTools.
  • Action[T, A](s *Store[T], method func(*T, A)) func(A): Returns func(arg A) { s.Update(Bind(method, arg)) }.
  • Store.SetState(next T): Replaces the store's state directly with an isolated copy of next and notifies subscribers.
  • Store.Reset(): Restores the store to a fresh clone of its initial state and notifies subscribers.
  • Store.Subscribe(listener func(newVal T, oldVal T)) func(): Subscribes to store changes. Returns an unsubscribe function.
  • Store.SubscribeAction(listener func(action string, newVal, oldVal T)) func(): Subscribes with automatic action name metadata.
Hooks

Go 1.27+ Roadmap Note: Once Kite upgrades to Go 1.27 (following the Go 1.28 release), where generic methods on structs are supported, selector-based Use and UseWith will also be exposed directly as generic methods on *Store[T] and *Context[T].

  • Use[T, U](s *Store[T], selector func(T) U) U: Connects *Store[T] to a functional component using a thread-safe useSyncExternalStore bridge, automatically bailing out when the selected value has not changed.
  • UseWith[T, U](s *Store[T], selector func(T) U, isEqual func(a, b U) bool) U: Connects *Store[T] to a functional component with a custom equality function isEqual.
  • Select[T, A, U](selector func(T, A) U, arg A) func(T) U: Curries a 1-argument value-receiver selector method func(T, A) U with arg into a func(T) U selector.
Scoped Context
  • NewContext[T](initialState T) *Context[T]: Creates a context initialized with a default *Store[T] holding initialState.
  • Context.Provider(store *Store[T], children ...kitex.Node) kitex.Node: Mounts an isolated *Store[T] instance for a VDOM subtree.
  • Context.Store() *Store[T]: Retrieves the active *Store[T] from the nearest Provider (or the default store) without subscribing to state changes.
  • Context.Default() *Store[T]: Returns the default store created by NewContext.
  • Context.Use() T: Subscribes to the entire state of ctx.Store().
  • Context.Action(mutators ...func(*T)) func(): Calls ctx.Store().Action(mutators...).
  • UseContext[T, U](ctx *Context[T], selector func(T) U) U: Selects a slice U from ctx.Store() and subscribes the component to changes in that slice.
  • UseContextWith[T, U](ctx *Context[T], selector func(T) U, isEqual func(a, b U) bool) U: Same as UseContext with a custom isEqual comparator.
Subscriptions & Testing Helpers
  • SubscribeSelector[T, U](s *Store[T], selector func(T) U, listener func(newVal, oldVal U)) func(): Subscribes outside components and invokes listener only when the selected slice changes.
  • SubscribeSelectorWith[T, U](s *Store[T], selector func(T) U, isEqual func(a, b U) bool, listener func(newVal, oldVal U)) func(): Same as SubscribeSelector with a custom isEqual comparator.
  • WaitFor[T](ctx context.Context, s *Store[T], predicate func(T) bool) (T, error): Blocks until predicate(state) is true or ctx is canceled, returning the matching snapshot or ctx.Err().
DevTools (extras/kites/kitesdt)
  • kitesdt.Track[T](name string, store *kites.Store[T]): Registers a store for inspection and action-timeline recording.
  • kitesdt.Untrack[T](store *kites.Store[T]): Detaches a store from the DevTools registry.
  • kitesdt.Register(insp *inspector.Inspector): Mounts the kites extension tab onto Kite's DevTools inspector.

Documentation

Overview

Package kites implements a lightweight, thread-safe external state store (similar to Zustand or Redux) for global state management outside of the VDOM tree.

It follows the State-Method + Higher-Order Action pattern on *Store[T]: state structs define pointer-receiver mutation methods (func (s *State) Inc()), which are passed as method expressions to Store.Update, Store.Action, Bind, and Action. Stores support copy-on-write isolation for mutable slices/maps, scoped dependency injection and parallel test isolation through Context[T] and Provider, selector-filtered non-UI subscriptions via SubscribeSelector, deterministic async waiting via WaitFor, and automatic action-name tracking for DevTools (extras/kites/kitesdt). It integrates with the kitex framework through Use, UseWith, UseContext, and Store.Use.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Action

func Action[T any, A any](s *Store[T], method func(*T, A)) func(A)

Action curries a 1-argument state method func(*T, A) against store s, returning a callable func(A) that calls s.Update(Bind(method, arg)) and preserves the method name in DevTools.

func Bind

func Bind[T any, A any](method func(*T, A), arg A) func(*T)

Bind curries a 1-argument state method func(*T, A) (or helper function) with arg into a func(*T) mutator while preserving the original method name for DevTools tracking.

func CleanState

func CleanState(val any) any

CleanState recursively converts an arbitrary Go value into a JSON-serializable representation, stripping non-serializable chan/unsafe.Pointer fields and representing non-nil functions as "ƒ () {}".

func Select

func Select[T any, A any, U any](selector func(T, A) U, arg A) func(T) U

Select curries a 1-argument value-receiver selector method func(T, A) U with arg into a standard func(T) U selector for Use, UseContext, and SubscribeSelector.

func SubscribeSelector

func SubscribeSelector[T any, U any](s *Store[T], selector func(T) U, listener func(newVal, oldVal U)) func()

SubscribeSelector subscribes to a specific slice of the store selected by selector. The listener is invoked only when the selected slice changes according to default equality (== for comparable types, reflect.DeepEqual otherwise). Returns an unsubscribe function.

func SubscribeSelectorWith

func SubscribeSelectorWith[T any, U any](s *Store[T], selector func(T) U, isEqual func(a, b U) bool, listener func(newVal, oldVal U)) func()

SubscribeSelectorWith subscribes to a specific slice of the store using a custom equality function isEqual.

func Use

func Use[T any, U any](s *Store[T], selector func(T) U) U

Use integrates the external *kites.Store with the kitex VDOM tree. It retrieves the current slice of the store using the provided selector, and subscribes to store changes using a thread-safe external-store bridge (modeled after React's useSyncExternalStore).

Selectors can be inline closures or value-receiver method expressions on T (e.g. AppState.SelectCounter, or parameterized via kites.Select(AppState.ItemByID, id)). Selector outputs may be comparable primitives, structs, slices, or maps. If the selected slice has not changed between updates, Use bails out without marking the component dirty or scheduling a VDOM re-render.

Note (Go 1.27+ roadmap): Once Kite upgrades to Go 1.27 (when Go 1.28 is released) where generic methods are supported, selector-based Use and UseWith will also be exposed directly as generic methods on *Store[T] and *Context[T].

func UseContext

func UseContext[T any, U any](ctx *Context[T], selector func(T) U) U

UseContext selects a slice U from the store in ctx and subscribes the component to changes in that slice.

func UseContextWith

func UseContextWith[T any, U any](ctx *Context[T], selector func(T) U, isEqual func(a, b U) bool) U

UseContextWith selects a slice U from the store in ctx using a custom equality comparator isEqual.

func UseWith

func UseWith[T any, U any](s *Store[T], selector func(T) U, isEqual func(a, b U) bool) U

UseWith integrates the external *kites.Store with the kitex VDOM tree using a custom equality function isEqual to determine whether the selected slice changed.

func WaitFor

func WaitFor[T any](ctx context.Context, s *Store[T], predicate func(T) bool) (T, error)

WaitFor blocks until predicate(state) returns true for the store's current or future state, or until ctx is canceled. It returns the matching state snapshot or ctx.Err().

Types

type Context

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

Context holds a scoped *Store[T] for dependency injection and parallel test isolation via Provider.

func NewContext

func NewContext[T any](initialState T) *Context[T]

NewContext creates a store Context initialized with a default store holding initialState.

func (*Context[T]) Action

func (c *Context[T]) Action(mutators ...func(*T)) func()

Action returns a zero-argument callback that invokes Update(mutators...) on the active store in ctx.

func (*Context[T]) Default

func (c *Context[T]) Default() *Store[T]

Default returns the default store created by NewContext.

func (*Context[T]) Provider

func (c *Context[T]) Provider(store *Store[T], children ...kitex.Node) kitex.Node

Provider mounts an isolated *Store[T] instance for the given VDOM subtree.

func (*Context[T]) Store

func (c *Context[T]) Store() *Store[T]

Store retrieves the active *Store[T] from the nearest enclosing Provider, or the default store if none is mounted. Calling Store() inside a component does not subscribe to state updates, making it ideal for action-only components.

func (*Context[T]) Use

func (c *Context[T]) Use() T

Use subscribes the current functional component to the entire state of the active store in ctx.

type InspectableStore

type InspectableStore interface {
	SubscriberCount() int
	Reset()
	InspectTypeName() string
	InspectState() any
	InspectInitial() any
	SetStateAny(state any) error
	SubscribeAny(listener func(newVal, oldVal any)) func()
	SubscribeActionAny(listener func(action string, newVal, oldVal any)) func()
}

InspectableStore is implemented by *Store[T]. It exposes type-erased inspection, subscription, reset, and time-travel restore hooks for DevTools integrations such as kitesdt.

type Store

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

Store holds the state of type T and manages subscribers to changes. It is fully thread-safe and can be used both inside and outside the kitex VDOM tree.

func Create

func Create[T any](initial T) *Store[T]

Create initializes a new Store with the given initial state.

func (*Store[T]) Action

func (s *Store[T]) Action(mutators ...func(*T)) func()

Action returns a zero-argument callback that invokes s.Update(mutators...). This enables passing Go method expressions on *T directly to UI event handlers:

OnPress: store.Action((*AppState).Increment)
OnPress: store.Action(kites.Bind((*AppState).AddCount, 10))

func (*Store[T]) Get

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

Get returns the current state snapshot.

func (*Store[T]) Initial

func (s *Store[T]) Initial() T

Initial returns a snapshot of the store's initial state.

func (*Store[T]) InspectInitial

func (s *Store[T]) InspectInitial() any

InspectInitial returns a JSON-safe snapshot of the store's initial state.

func (*Store[T]) InspectState

func (s *Store[T]) InspectState() any

InspectState returns a JSON-safe snapshot of the current store state.

func (*Store[T]) InspectTypeName

func (s *Store[T]) InspectTypeName() string

InspectTypeName returns the Go type name of the store's state type T.

func (*Store[T]) Reset

func (s *Store[T]) Reset()

Reset restores the store's state to a fresh copy of its initial state and notifies subscribers.

func (*Store[T]) Set

func (s *Store[T]) Set(updater func(T) T)

Set updates the state using the provided updater function. It passes an isolated copy-on-write draft of the current state to updater under a write lock so that in-place mutations to slices, maps, or data pointers inside updater never race with concurrent readers (such as the UI drawing thread) or corrupt previous snapshots. Subscribers are notified after unlocking.

func (*Store[T]) SetState

func (s *Store[T]) SetState(next T)

SetState replaces the store's state with next and notifies subscribers.

func (*Store[T]) SetStateAny

func (s *Store[T]) SetStateAny(val any) error

SetStateAny replaces the store's state with a dynamically typed snapshot of type T.

func (*Store[T]) Subscribe

func (s *Store[T]) Subscribe(listener func(newVal T, oldVal T)) func()

Subscribe registers a listener callback to be invoked when the state changes. It returns an unsubscribe function that removes the listener.

func (*Store[T]) SubscribeAction

func (s *Store[T]) SubscribeAction(listener func(action string, newVal T, oldVal T)) func()

SubscribeAction registers a listener callback invoked with the resolved action name and state transition snapshots whenever the store mutates.

func (*Store[T]) SubscribeActionAny

func (s *Store[T]) SubscribeActionAny(listener func(action string, newVal, oldVal any)) func()

SubscribeActionAny registers a type-erased listener notified with the resolved action name and state snapshots on every mutation.

func (*Store[T]) SubscribeAny

func (s *Store[T]) SubscribeAny(listener func(newVal, oldVal any)) func()

SubscribeAny registers a type-erased listener notified on state transitions. When the state type contains mutable reference types, isolated clones are passed to the listener so stored snapshots remain safe for time-travel restoration.

func (*Store[T]) SubscriberCount

func (s *Store[T]) SubscriberCount() int

SubscriberCount returns the number of active subscribers attached to the store.

func (*Store[T]) Update

func (s *Store[T]) Update(mutators ...func(*T))

Update mutates the state in place using one or more pointer mutators applied sequentially to a single isolated copy-on-write draft under a single lock, commits the result, and notifies subscribers once.

Action names are automatically extracted from the passed method expressions, bound mutators (via Bind), or named helper functions for DevTools tracking.

func (*Store[T]) Use

func (s *Store[T]) Use() T

Use subscribes the current functional component to the entire state of s and returns the current snapshot.

type StoreHistorySnapshot

type StoreHistorySnapshot struct {
	Seq       uint64 `json:"seq"`
	Timestamp string `json:"timestamp"`
	Action    string `json:"action"`
	State     any    `json:"state"`
	PrevState any    `json:"prevState,omitempty"`
}

StoreHistorySnapshot represents a single recorded state transition in a store's timeline.

type StoreSnapshot

type StoreSnapshot struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	TypeName    string                 `json:"typeName"`
	State       any                    `json:"state"`
	Initial     any                    `json:"initial"`
	Subscribers int                    `json:"subscribers"`
	UpdatedAt   string                 `json:"updatedAt,omitempty"`
	History     []StoreHistorySnapshot `json:"history,omitempty"`
}

StoreSnapshot is a JSON-serializable snapshot of a tracked kites store and its bounded mutation history for DevTools inspection.

Directories

Path Synopsis
Package kitesdt provides the DevTools integration bridge and time-travel debugger mini-plugin for kites global state stores.
Package kitesdt provides the DevTools integration bridge and time-travel debugger mini-plugin for kites global state stores.

Jump to

Keyboard shortcuts

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