nodra

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 3 Imported by: 0

README

Nodra

Website Go Reference Latest version Go version GitHub stars License X GitHub Sponsors

Nodra is a concurrency-safe reactive state store for Go desktop applications. It provides Zustand-like ergonomics for MyGo apps while keeping state independent from the renderer and persistence backend.

简体中文 · 日本語 · 한국어 · Español

Install

go get github.com/yldm-tech/nodra@latest

The core package is github.com/yldm-tech/nodra. The optional inspector is github.com/yldm-tech/nodra/devtools, the optional bridge to web pages is github.com/yldm-tech/nodra/bridge, and the Edit menu integration for native UI is github.com/yldm-tech/nodra/nativeui.

Quick start

package main

import (
	"fmt"

	"github.com/yldm-tech/nodra"
)

type State struct{ Count int }

func main() {
	store := nodra.New(State{})
	defer store.Close()

	stop := store.Subscribe(func(s nodra.Snapshot[State]) {
		fmt.Println(s.Value.Count)
	})
	defer stop()

	_ = store.Update(func(s *State) { s.Count++ })
}

Core capabilities

  • Versioned Store[T] with synchronous subscriptions, bounded watches and read-only views.
  • Derived state, selectors, projections, field bindings and atomic transactions.
  • Undo/redo history with grouping, filtering and payload budgets.
  • JSON, versioned migration, encrypted, backup, journaled and conflict-checked persistence.
  • Debounced, cancelable and queued async actions with progress, retries and metrics.
  • Scope for ownership and shutdown ordering.
  • Optional MyGo invalidation helpers and a local authenticated DevTools inspector.
  • A bridge that lets the web pages of a MyGo app follow a Store and change it through registered actions.
  • Undo and Redo of the window's keys and Edit menu acting on a History, for MyGo native UI.

MyGo

stop := nodra.InvalidateSelector(store, window, func(s State) int {
	return s.Count
})
defer stop()

The integration targets MyGo v0.7.4. Keep temporary widget state in the view owner and commit only the edited field to the shared Store. See examples/mygo for a minimal native window.

history := nodra.Track(store, 100)
nativeui.InvalidateHistory(history, window) // redraw when Undo or Redo becomes possible

func (app *App) view(c *ui.Context) {
	nativeui.UndoShortcuts(c, app.history) // Cmd+Z, Shift+Cmd+Z and the Edit menu
	// ...
}

The optional nativeui subpackage makes the window's Undo and Redo act on a History: the keys, and with MyGo 0.7.4 on macOS the Edit menu items, which are enabled only while history can act. A focused text input keeps its own undo. It is separate from the core so apps without native UI do not link MyGo's ui package.

Services and CLIs that share Stores but never open a window can build with -tags nodra_nomygo. It leaves out the *mygo.Window helpers (InvalidateTarget stays) so MyGo is not linked, and a CGO_ENABLED=0 Linux build is then a static executable. The tag applies to the whole build: nativeui, or any library that calls those helpers, does not compile with it, and bridge links MyGo again. See docs/support.md.

Web pages

b := bridge.New(bridge.Options{})
stop, err := bridge.ExposeProjection(b, "counter", store, func(s State) PageState { return PageState{Count: s.Count} })
stopAdd, err := bridge.Handle(b, "counter/add", func(ctx context.Context, by int) error {
	return store.Update(func(s *State) { s.Count += by })
})
b.Bind() // before App.Run
import { dispatch, remoteState } from "./nodra.js";

const counter = remoteState("counter"); // subscribe and getSnapshot fit useSyncExternalStore
await dispatch("counter/add", 1);

The optional bridge subpackage makes a Store the one source of truth for native windows and web pages alike. Pages see only what the projection returns, receive a frame when it changes (coalesced into the latest only once about 1 MiB of frames waits for a slow page), and change state only through the actions Go registers. The JavaScript client in bridge/client has no dependencies. See docs/bridge.md and examples/web.

Persistence

persistence := nodra.NewPersistence(store, nodra.FileStorage{Path: "state.json", Backup: true}, nodra.JSONCodec[State]{})
// A missing file is a first start. Stop on any other load error: autosave would overwrite the file.
if err := persistence.Load(ctx); err != nil && !errors.Is(err, fs.ErrNotExist) {
	return err
}
writer, err := persistence.AutoSaveAsync(ctx, nodra.AsyncOptions{Debounce: 100 * time.Millisecond})
if err != nil {
	return err
}
defer func() {
	if err := writer.Close(shutdownCtx); err != nil {
		// The store still owns the data: retry with persistence.Save using a fresh context, or report the error.
		log.Printf("save state: %v", err)
	}
}()

Use VersionedJSONCodec, AESGCMCodec, Journal, Durable and WithConflictDetection when the application needs migrations, encryption or stronger file recovery guarantees. Details are in docs/architecture.md.

Complete example

examples/workbench is the full Nodra + MyGo desktop project. It combines cloned state, local drafts, validated backup persistence, debounced and cancelable async search, async saves, scoped shutdown, native invalidation, English/Simplified Chinese localization and optional DevTools.

go run ./examples/workbench
go run ./examples/workbench -devtools

The smaller examples cover one integration at a time:

DevTools

inspector := devtools.New(devtools.Options{})
defer inspector.Close()
stop, err := devtools.Attach(inspector, "state", store.ReadOnly())
if err != nil {
	panic(err)
}
defer stop()
url, _ := inspector.Listen()
fmt.Println(url)

DevTools is read-only by default. AllowRestore explicitly enables typed JSON editing and snapshot restoration. See docs/devtools.md for redaction, limits, remote read-only mode and the JSON compatibility contract.

Documentation

Verification

go test ./...
go test -race ./...
go vet ./...
golangci-lint run ./...
go run golang.org/x/vuln/cmd/govulncheck@latest ./...

Nodra is one Go module: github.com/yldm-tech/nodra. The project requires Go 1.27.3 or newer and uses MyGo v0.7.4 for native integration.

Documentation

Overview

Package nodra is a concurrency-safe reactive state store for Go desktop applications.

The root package is the stable public API; implementation details are kept in internal/core. The public method index and ownership/error contracts are in docs/public-api.md, and the v1 support matrix is in docs/support.md. Go doc does not list the methods of a type alias, so the root package shows none of the methods of the types it re-exports from internal/core. This package comment therefore keeps the method index of every re-exported type here too; the error types add only Error and Unwrap.

Stores

Start with New, Create or NewWithClone. New and Create copy values shallowly; NewWithClone isolates mutable references with a clone function. Store provides Get, State, Snapshot, Version, ReadOnly, Set, Update, UpdateErr, Patch, Reset, Transaction, Batch, BatchErr, Watch, Subscribe, SubscribeWith, SubscribeSnapshot, SubscribeMutations, Do, Action, SubscribeActions, SubscribeActionHooks, SubscribeActionTrace, TaskSnapshot, ActiveTasks, ID, Done and Close. ReadOnly exposes the observation-only surface: ReadOnly provides Get, State, Snapshot, Version, ID, Done, Subscribe, SubscribeWith, SubscribeSnapshot, SubscribeMutations, SubscribeActions, SubscribeActionTrace, TaskSnapshot, ActiveTasks and Watch.

Define and DefineWithClone create named store factories: Definition.New returns a store with independent state and Definition.ID returns its id. BindField binds an editor to one field through Field.Get, Field.Set and Field.Edit. Atomic2, AtomicGroup and AtomicUpdate commit several stores as one visibility boundary.

Derived values

Derive, DeriveProjection and Combine return memoized Derived values, and Derived provides Get, Snapshot, Subscribe, SubscribeSnapshot, Done and Close; Done is closed when the value is closed. Select, SubscribeSelector, SubscribeSelectorWith, SubscribeProjection and SubscribeProjectionWith read or observe projections.

History

Track and TrackWith record undo and redo. History provides Undo, Redo, CanUndo, CanRedo, BeginGroup, Status and Close. CanUndo and CanRedo are false while a group is open, and closing the tracked Store does not close its History.

Persistence

NewPersistence and NewPersistenceWithOptions combine a Storage such as FileStorage or CheckedFileStorage with a Codec such as JSONCodec, VersionedJSONCodec or AESGCMCodec. FileStorage provides Load, LoadBackup, Save and WithConflictDetection, which returns a CheckedFileStorage; CheckedFileStorage provides Load, LoadBackup and Save and rejects a save over content another writer changed. The codecs provide JSONCodec.Encode and Decode, VersionedJSONCodec.Encode and Decode, and AESGCMCodec.Encode and Decode. NewMemoryKeyProvider supplies AESGCMCodec keys for tests and local applications, and MemoryKeyProvider provides Add, SetCurrent, Current and Get to add keys, rotate the key for new writes and read keys. Persistence provides Load, LoadBackup, LoadWithRecovery, Save, AutoSave, AutoSaveWithErrors and AutoSaveAsync. AutoSaveAsync returns an AsyncPersistence, and AsyncPersistence provides Flush, Errors, Status and Close.

Async work

NewAsyncAction and NewAsyncActionWithOptions create an AsyncAction, and AsyncAction provides Run, Status, Metrics, ExportMetrics, SubscribeMetrics and Close. Run returns a Task, and Task provides Wait, Cancel, Done and Status. NewScope creates a Scope that owns subscriptions, persistence writers and actions, and Scope provides Context, Observe, Defer, Done and Close.

MyGo

MyGo redraws use Invalidate, InvalidateTarget, InvalidateSelector, InvalidateSelectorWith, InvalidateProjection and InvalidateProjectionWith. Programs that never use a MyGo window can build with the nodra_nomygo tag, which leaves out the helpers that take a *mygo.Window so MyGo is not linked; InvalidateTarget stays available.

Index

Constants

View Source
const (
	LatestWins ActionPolicy = core.LatestWins
	QueueAll   ActionPolicy = core.QueueAll

	TaskQueued     TaskPhase = core.TaskQueued
	TaskRunning    TaskPhase = core.TaskRunning
	TaskSucceeded  TaskPhase = core.TaskSucceeded
	TaskCanceled   TaskPhase = core.TaskCanceled
	TaskSuperseded TaskPhase = core.TaskSuperseded
	TaskFailed     TaskPhase = core.TaskFailed

	MutationDirect      MutationType = core.MutationDirect
	MutationPatch       MutationType = core.MutationPatch
	MutationAction      MutationType = core.MutationAction
	MutationReset       MutationType = core.MutationReset
	MutationTransaction MutationType = core.MutationTransaction
)

Variables

View Source
var (
	ErrNoUndo              = core.ErrNoUndo
	ErrNoRedo              = core.ErrNoRedo
	ErrSuperseded          = core.ErrSuperseded
	ErrInvalidAction       = core.ErrInvalidAction
	ErrQueueFull           = core.ErrQueueFull
	ErrUnsupportedVersion  = core.ErrUnsupportedVersion
	ErrMissingMigration    = core.ErrMissingMigration
	ErrClosed              = core.ErrClosed
	ErrFileConflict        = core.ErrFileConflict
	ErrHistoryBatch        = core.ErrHistoryBatch
	ErrHistoryGroup        = core.ErrHistoryGroup
	ErrInvalidBinding      = core.ErrInvalidBinding
	ErrInvalidHistory      = core.ErrInvalidHistory
	ErrInvalidKey          = core.ErrInvalidKey
	ErrInvalidPersistence  = core.ErrInvalidPersistence
	ErrNoBackup            = core.ErrNoBackup
	ErrPersistenceRecovery = core.ErrPersistenceRecovery
)

Functions

func Atomic2 added in v0.9.0

func Atomic2[A, B any](first *Store[A], second *Store[B], fn func(*A, *B) error) error

Atomic2 commits two different stores as one visibility boundary. Both candidates are prepared while both store locks are held; a callback error or panic leaves both stores unchanged, with preparation panics returned as PanicError. Readers and ordinary writers wait until both values are committed. Notifications run after the boundary is released, so listeners may safely reenter either store. A notification panic propagates unchanged without rolling back the committed stores. fn must not call Store methods; mutate only the provided pointers.

func AtomicGroup added in v0.9.0

func AtomicGroup(ops ...AtomicOp) error

AtomicGroup commits any number of AtomicUpdate operations as one visibility boundary. Every callback is prepared while all participating store locks are held; an error or panic leaves every store unchanged, with preparation panics returned as PanicError, and a store that appears twice is rejected. Lock order is stable across calls, so groups built in opposite order cannot deadlock. Notifications run after all locks are released and may safely reenter their stores. A notification panic propagates unchanged without rolling back the committed stores.

func Invalidate added in v0.2.0

func Invalidate[T any](source Observable[T], window *mygo.Window) func()

Invalidate requests a new frame of window's native Content whenever source publishes a snapshot. The request is made on the writing goroutine and Window.Invalidate posts it to MyGo's main thread. The subscription stops when the window closes; the returned function stops it earlier and is safe to call repeatedly. Nil inputs and destroyed windows subscribe to nothing. A callback already running when stopped may still request a frame.

func InvalidateProjection added in v0.6.0

func InvalidateProjection[T, V any](source Reader[T], window *mygo.Window, project func(T) V) func()

InvalidateProjection is Invalidate that requests a frame only when an owned projection changes, without cloning the entire source. project follows SubscribeProjectionWith's ownership rules. The window owns the subscription lifetime.

func InvalidateProjectionWith added in v0.6.0

func InvalidateProjectionWith[T, V any](source Reader[T], window *mygo.Window, project func(T) V, options SelectorOptions[V]) func()

InvalidateProjectionWith is InvalidateProjection with custom equality and optional immediate invalidation from options. Nil inputs and destroyed windows subscribe to nothing. As with Invalidate, the subscription stops when the window closes, the returned function is idempotent, and stopping does not wait for callbacks already running.

func InvalidateSelector added in v0.5.0

func InvalidateSelector[T, V any](source Observable[T], window *mygo.Window, selector func(T) V) func()

InvalidateSelector is Invalidate that requests a frame only when the selected value changes, using SubscribeSelector's equality. selector runs on writer goroutines and must be safe for concurrent calls; selected reference values follow the store's ownership policy. The subscription stops when the window closes or the returned function is called.

func InvalidateSelectorWith added in v0.5.0

func InvalidateSelectorWith[T, V any](source Observable[T], window *mygo.Window, selector func(T) V, options SelectorOptions[V]) func()

InvalidateSelectorWith is InvalidateSelector with custom equality and optional immediate invalidation from options. Nil inputs and destroyed windows subscribe to nothing. As with Invalidate, stopping does not wait for callbacks already running.

func InvalidateTarget added in v0.9.0

func InvalidateTarget[T any](source Observable[T], target InvalidationTarget) func()

InvalidateTarget requests a redraw from any InvalidationTarget whenever source publishes. Nil and typed-nil targets are ignored. It accepts read-only and derived sources without depending on a UI toolkit. The caller owns the target lifecycle: unlike Invalidate it does not watch for a window closing, so call the returned stop function when the target is no longer valid.

func SubscribeProjection added in v0.6.0

func SubscribeProjection[T, V any](source Reader[T], project func(T) V, fn func(V)) func()

SubscribeProjection is SubscribeSelector over a borrowed projection and follows SubscribeProjectionWith's ownership rules.

func SubscribeProjectionWith added in v0.6.0

func SubscribeProjectionWith[T, V any](source Reader[T], project func(T) V, fn func(current, previous V), options SelectorOptions[V]) func()

SubscribeProjectionWith is an opt-in selector that borrows immutable source snapshots instead of cloning the entire store per notification. project must be pure and safe for concurrent calls, must not retain or mutate source references, and must return independently owned projections. fn must treat the current and previous projections as immutable. Equality, initialization and callback ordering match SubscribeSelectorWith.

func SubscribeSelector

func SubscribeSelector[T, S any](source Observable[T], selector func(T) S, fn func(S)) func()

SubscribeSelector calls fn with the selected value each time it changes, using the default equality of SubscribeSelectorWith. It returns an idempotent unsubscribe function; nil inputs subscribe to nothing.

func SubscribeSelectorWith

func SubscribeSelectorWith[T, V any](source Observable[T], selector func(T) V, fn func(current, previous V), options SelectorOptions[V]) func()

SubscribeSelectorWith calls fn with the current and previous selected values each time the selection changes. options.Equals replaces the default equality, which uses == for comparable values and reflect.DeepEqual otherwise, and options.Immediate also calls fn once with the initial selection. It catches up after registration and ignores obsolete computations. selector, equality and fn run on writer goroutines and may overlap, as with Store.Subscribe. It returns an idempotent unsubscribe function; nil inputs subscribe to nothing.

Types

type AESGCMCodec added in v0.9.0

type AESGCMCodec[T any] = core.AESGCMCodec[T]

AESGCMCodec encrypts another codec's bytes with authenticated AES-GCM.

type ActionEvent

type ActionEvent = core.ActionEvent

type ActionHooks

type ActionHooks = core.ActionHooks

type ActionMetrics added in v0.9.0

type ActionMetrics = core.ActionMetrics

type ActionOptions added in v0.6.0

type ActionOptions[I any] = core.ActionOptions[I]

type ActionPolicy added in v0.6.0

type ActionPolicy = core.ActionPolicy

type ActionTrace added in v0.6.0

type ActionTrace = core.ActionTrace

type AsyncAction added in v0.6.0

type AsyncAction[T, I, R any] = core.AsyncAction[T, I, R]

func NewAsyncAction added in v0.6.0

func NewAsyncAction[T, I, R any](store *Store[T], name string, work func(context.Context, I, func(float64)) (R, error), apply func(*T, R) error) (*AsyncAction[T, I, R], error)

NewAsyncAction creates a cancelable action on store with the default LatestWins policy and one shared key. Each Run calls work outside every lock with its context and a progress callback, then apply commits the result to the latest store candidate; canceled and superseded results never commit, and panics in work or apply become task errors. It returns ErrInvalidAction when store, work or apply is nil. Closing store cancels the action's runs; Close rejects new runs, cancels accepted work and waits within its context.

func NewAsyncActionWithOptions added in v0.6.0

func NewAsyncActionWithOptions[T, I, R any](store *Store[T], name string, work func(context.Context, I, func(float64)) (R, error), apply func(*T, R) error, options ActionOptions[I]) (*AsyncAction[T, I, R], error)

NewAsyncActionWithOptions is NewAsyncAction with the scheduling, debounce and retry policy in options. It returns ErrInvalidAction for negative limits or durations, an unknown policy, a positive Debounce with QueueAll, or retries that are not declared Idempotent.

type AsyncOptions added in v0.3.0

type AsyncOptions = core.AsyncOptions

type AsyncPersistence added in v0.3.0

type AsyncPersistence[T any] = core.AsyncPersistence[T]

type AsyncState added in v0.6.0

type AsyncState = core.AsyncState

type AtomicOp added in v0.9.0

type AtomicOp = core.AtomicOp

func AtomicUpdate added in v0.9.0

func AtomicUpdate[T any](store *Store[T], fn func(*T) error) AtomicOp

AtomicUpdate prepares one store update for AtomicGroup. fn sees a private candidate and may return an error to abort the whole group. It must not call Store methods; mutate only the provided pointer.

type CheckedFileStorage added in v0.7.0

type CheckedFileStorage = core.CheckedFileStorage

type Codec

type Codec[T any] = core.Codec[T]

type Definition

type Definition[T any] = core.Definition[T]

func Define

func Define[T any](id string, initial func() T) *Definition[T]

Define creates a named store factory. Each Definition.New call runs initial and returns a store with independent state and the definition's ID; a nil initial yields the zero value. The stores copy values shallowly as with New, so initial must return fresh maps, slices and pointers for the instances to stay independent. Use DefineWithClone for isolated mutable state.

func DefineWithClone added in v0.3.0

func DefineWithClone[T any](id string, initial func() T, clone func(T) T) *Definition[T]

DefineWithClone creates a named store factory whose stores follow NewWithClone's isolation policy with clone.

type Derived

type Derived[T, V any] = core.Derived[T, V]

func Combine added in v0.7.0

func Combine[A, B, V any](first Observable[A], second Observable[B], project func(A, B) V, equals func(V, V) bool) *Derived[Pair[A, B], V]

Combine derives a value from two stores or derived values. Independent writes are eventually consistent, while Atomic2 and AtomicGroup notifications are settled through the derived graph before downstream callbacks run. Old source versions and obsolete computations cannot replace newer ones. project and equals must be pure and safe for concurrent calls, and source references must stay immutable. Close the returned value to detach both sources.

func Derive

func Derive[T, V any](source Observable[T], selector func(T) V, equals func(V, V) bool) *Derived[T, V]

Derive returns a memoized value that selector computes from source. It recomputes when source publishes and notifies its listeners only when the selected value changes according to equals; a nil equals treats every recomputation as a change. selector and equals must be pure and safe for concurrent calls, and returned reference values and listener arguments are read-only. An invalid source or a nil selector returns a closed value. Close the returned value when its owner is done.

func DeriveProjection added in v0.6.0

func DeriveProjection[T, V any](source Reader[T], project func(T) V, equals func(V, V) bool) *Derived[T, V]

DeriveProjection is Derive over a borrowed projection: it memoizes an owned projection without cloning the whole source. project follows SubscribeProjectionWith's ownership rules, and returned reference values and listener arguments are read-only. Close the returned value when its owner is done.

type Field added in v0.7.0

type Field[T, V any] = core.Field[T, V]

func BindField added in v0.7.0

func BindField[T, V any](store *Store[T], read func(T) V, write func(*T, V) error) (Field[T, V], error)

BindField binds an immediate editor to one field of store's state. read selects the field from the store's current value, and write applies a new value to the latest store candidate, so unrelated concurrent changes survive; an error from write rejects the value and leaves the store unchanged. It returns ErrInvalidBinding when store, read or write is nil. read and write follow the store's ownership policy; keep form drafts separate when edits need an explicit Save or Cancel.

type FileConflictError added in v0.7.0

type FileConflictError = core.FileConflictError

type FileFingerprint added in v0.7.0

type FileFingerprint = core.FileFingerprint

type FileStorage

type FileStorage = core.FileStorage

type History

type History[T any] = core.History[T]

func Track

func Track[T any](store *Store[T], limit int) *History[T]

Track starts recording changes to store for undo and redo, keeping at most limit undo entries; values below one disable recording. It is TrackWith with only Limit set. Closing store does not close History, and closing the History releases its subscription without closing the store, so close History when the store's owner is done with it.

func TrackWith added in v0.6.0

func TrackWith[T any](store *Store[T], options HistoryOptions[T]) *History[T]

TrackWith is Track with HistoryOptions for filtering, restoring and payload budgets. A negative MaxBytes, or a positive MaxBytes without Size, panics with ErrInvalidHistory. A nil store or a Limit below one returns a closed History that records nothing. Closing store does not close History: Undo and Redo then return ErrClosed and keep their stacks, CanUndo, CanRedo and Status keep reporting those stacks, and Status stays open, so close History when the store's owner is done with it.

type HistoryOptions added in v0.6.0

type HistoryOptions[T any] = core.HistoryOptions[T]

type HistoryState added in v0.7.0

type HistoryState = core.HistoryState

type InvalidationTarget added in v0.9.0

type InvalidationTarget = core.InvalidationTarget

type JSONCodec

type JSONCodec[T any] = core.JSONCodec[T]

type JSONMigration added in v0.3.0

type JSONMigration = core.JSONMigration

type KeyProvider added in v0.9.0

type KeyProvider = core.KeyProvider

type LoadError added in v0.6.0

type LoadError = core.LoadError

type MemoryKeyProvider added in v0.9.0

type MemoryKeyProvider = core.MemoryKeyProvider

func NewMemoryKeyProvider added in v0.9.0

func NewMemoryKeyProvider(id string, key []byte) (*MemoryKeyProvider, error)

NewMemoryKeyProvider returns a concurrency-safe in-memory KeyProvider whose current key is key under id, for tests and local applications. It copies key and returns ErrInvalidKey when id is empty or key is not a valid AES key. Production applications should implement KeyProvider over their OS keychain or secret manager.

type MetricsSink added in v0.9.0

type MetricsSink = core.MetricsSink

type Mutation

type Mutation[T any] = core.Mutation[T]

type MutationType

type MutationType = core.MutationType

type Observable added in v0.7.0

type Observable[T any] = core.Observable[T]

type Pair added in v0.7.0

type Pair[A, B any] = core.Pair[A, B]

type PanicError added in v0.6.0

type PanicError = core.PanicError

type Persistence

type Persistence[T any] = core.Persistence[T]

Persistence connects a Store to a byte Storage and Codec.

func NewPersistence

func NewPersistence[T any](store *Store[T], storage Storage, codec Codec[T]) *Persistence[T]

NewPersistence connects store to storage and codec. Persistence is explicit: call Load at startup, then Save after successful actions or start AutoSave, AutoSaveWithErrors or AutoSaveAsync. Save calls on one instance are serialized, but separate instances sharing a storage destination are not coordinated, so use one instance per destination. A nil store, storage or codec makes Load, Save and AutoSaveAsync return ErrInvalidPersistence.

func NewPersistenceWithOptions added in v0.6.0

func NewPersistenceWithOptions[T any](store *Store[T], storage Storage, codec Codec[T], options PersistenceOptions[T]) *Persistence[T]

NewPersistenceWithOptions is NewPersistence with options. options.Validate checks decoded state before Load replaces the store value and saved state before it is written; it must be pure and safe for concurrent calls, and must not mutate its input.

type PersistenceOptions added in v0.6.0

type PersistenceOptions[T any] = core.PersistenceOptions[T]

type PersistenceState added in v0.7.0

type PersistenceState = core.PersistenceState

type ReadOnly added in v0.6.0

type ReadOnly[T any] = core.ReadOnly[T]

type Reader added in v0.6.0

type Reader[T any] = core.Reader[T]

type RecoveryError added in v0.9.0

type RecoveryError = core.RecoveryError

type RetryOptions added in v0.9.0

type RetryOptions = core.RetryOptions

type Scope added in v0.6.0

type Scope = core.Scope

func NewScope added in v0.6.0

func NewScope() *Scope

NewScope returns an open Scope. Close cancels Context, stops observations, then runs deferred drains in reverse registration order: register stores first, persistence second and actions last so work finishes before persistence drains and stores close.

type SelectorOptions

type SelectorOptions[V any] = core.SelectorOptions[V]

type Snapshot

type Snapshot[T any] = core.Snapshot[T]

func Select added in v0.6.0

func Select[T, V any](source Reader[T], project func(T) V) Snapshot[V]

Select reads an owned projection and the source version without cloning the whole store. project borrows read-only state under the read lock: it must not mutate or retain source references, reenter the store, or block. Return scalars or copy every mutable reference into the projection, for example with slices.Clone.

type Storage

type Storage = core.Storage

type Store

type Store[T any] = core.Store[T]

Store owns versioned state and synchronously publishes snapshots to its observers. See Store methods in docs/public-api.md when the Go documentation renderer omits methods for this root-package alias.

func Create

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

Create is the Pinia/Zustand-style name for New and follows New's shallow ownership policy.

func New

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

New creates an open store at version zero that holds initial. New copies values shallowly: maps, slices and pointers reachable from initial, from values passed to Set and from values returned by Get, Snapshot and callbacks stay shared with the store. Do not mutate that data outside an update callback, copy it before writing inside one, and do not keep a mutable alias of a value passed to New or Set; rollback and Reset cannot undo an in-place mutation through a shared reference. Use NewWithClone for isolated mutable state.

func NewWithClone added in v0.3.0

func NewWithClone[T any](initial T, clone func(T) T) *Store[T]

NewWithClone creates a store that isolates owned state, snapshots, subscriber values and rollback with clone. clone must copy all mutable references, be safe for concurrent calls, and must not reenter the store. A nil clone preserves New's behavior.

type SubscribeOptions

type SubscribeOptions[T any] = core.SubscribeOptions[T]

type Task added in v0.6.0

type Task = core.Task

type TaskMetrics added in v0.7.0

type TaskMetrics = core.TaskMetrics

type TaskPhase added in v0.6.0

type TaskPhase = core.TaskPhase

type TaskSnapshot added in v0.6.0

type TaskSnapshot = core.TaskSnapshot

type VersionedJSONCodec added in v0.3.0

type VersionedJSONCodec[T any] = core.VersionedJSONCodec[T]

Directories

Path Synopsis
Package bridge exposes Nodra state to the web pages of a MyGo app, so a Store in Go stays the one source of truth for windows of native UI and web pages alike.
Package bridge exposes Nodra state to the web pages of a MyGo app, so a Store in Go stays the one source of truth for windows of native UI and web pages alike.
Package devtools provides an opt-in local inspector for Nodra stores.
Package devtools provides an opt-in local inspector for Nodra stores.
examples
basic command
devtools command
Command devtools runs a counter with a live local inspector.
Command devtools runs a counter with a live local inspector.
mygo command
Example mygo demonstrates two native windows sharing business state with independent redraw subscriptions, and the Edit menu's Undo and Redo acting on the state's history.
Example mygo demonstrates two native windows sharing business state with independent redraw subscriptions, and the Edit menu's Undo and Redo acting on the state's history.
persistent command
Command persistent demonstrates cloned state, schema migration and write-behind persistence.
Command persistent demonstrates cloned state, schema migration and write-behind persistence.
web command
Example web shows one Store behind a window of native UI and a window of a web page: both read the same count, and either changes it.
Example web shows one Store behind a window of native UI and a window of a web page: both read the same count, and either changes it.
workbench command
Command workbench searches real local file names and edits persisted settings.
Command workbench searches real local file names and edits persisted settings.
internal
core
Package nodra is a state library for MyGo apps: concurrency-safe reactive stores whose snapshots drive native MyGo views.
Package nodra is a state library for MyGo apps: concurrency-safe reactive stores whose snapshots drive native MyGo views.
Package nativeui connects Nodra to MyGo's native UI beyond redrawing: the Edit menu's Undo and Redo, and their shortcuts, act on a History.
Package nativeui connects Nodra to MyGo's native UI beyond redrawing: the Edit menu's Undo and Redo, and their shortcuts, act on a History.

Jump to

Keyboard shortcuts

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