@dirtytalk/structural
v0.2.0
Published
Path-based dirty-tracking instantiation of @dirtytalk/engine, for state containers and structural data.
Maintainers
Readme
@dirtytalk/structural
Path-based dirty-tracking instantiation of @dirtytalk/engine, for state containers and structural data.
Why this exists
Both state containers and UI renderers ask the same question after a mutation: what changed, who cares, and when do we tell them? For structural data (objects and arrays whose consumers read named paths through them) the answer here is a set of interned path IDs.
A consumer says which paths it reads (consume + setPaths, usually fed by trackRender). Each
mutation diffs the old and new state along the watched paths only, skipping subtrees whose
reference is unchanged. One flush per scheduler tick calls the consumers it woke with the set of
changed path ids. The cost of a change follows what consumers read and how many of them it wakes,
not the size of the state or one walk per consumer.
What's in the box
StructuralStore<S>: a ready-to-use container with publicset,patchandupdate. The quick way to use the package without subclassing.StructuralContainer<S>: the abstract base class. Holds state, indexes consumers by the paths they watch, and provides the protected mutatorsemit,patchandupdatefor subclasses to build methods on.Consumer: the handlecontainer.consume(cb)returns:setPaths(paths),dispose().PathInterner: string-to-ID interning. One per container class by default, one per store.PathSet: aSet<PathId>or theALL_PATHSsentinel, withPathSetSpace, theSpace<PathSet>the container hands to the engine'sDirtyChannel.trackRender: Proxy-based path recorder. Wraps state, records every field access as an internedPathId, and returns the access set alongside the proxied value. Optionally accepts aProxyCacheto reuse proxies across renders, see Cross-render proxy reuse below.ProxyCache: opt-in, caller-owned cache that letstrackRenderskip re-allocating aProxyfor array items (or any nested value) that didn't change between renders.getAt: reads a value at a dotted path string.- React adapter at
@dirtytalk/structural/react:useStructural(container), built onuseSyncExternalStore. @dirtytalk/structural/testing:setTrackTrace, a hook that observes tracking decisions.
Install
pnpm add @dirtytalk/structural @dirtytalk/engine@dirtytalk/engine is a runtime dependency. Both packages are versioned together in this
monorepo; installing structural without engine would produce a missing peer at runtime.
Quick example: core (no React)
import { SyncScheduler } from '@dirtytalk/engine';
import { StructuralStore } from '@dirtytalk/structural';
const store = new StructuralStore(
{ count: 0, label: 'counter' },
{ scheduler: new SyncScheduler() },
);
const unsubscribe = store.subscribe((dirty) => {
console.log('state:', store.state, 'dirty:', dirty);
});
store.patch({ count: 1 });
// => state: { count: 1, label: 'counter' } dirty: Set { <root id> }
unsubscribe();subscribe(cb) listens to every change. To wake only when specific paths change, register a
consumer and tell it what it reads:
const consumer = store.consume(() => console.log('count changed'));
consumer.setPaths(new Set([store.interner.intern('count')]));
store.patch({ label: 'renamed' }); // does not wake the consumer
store.patch({ count: 2 }); // wakes it
consumer.dispose();dirty holds the ids of the changed paths among those any consumer watches. When no watched path
changed it holds only the root id (interner.rootId(), which lookup decodes to ''). In the
first example nothing watches a specific path, so the callback receives the root id alone.
To keep mutation inside the class, subclass StructuralContainer and expose methods that call
the protected emit, patch and update:
import { StructuralContainer } from '@dirtytalk/structural';
class Counter extends StructuralContainer<{ count: number }> {
constructor() {
super({ count: 0 });
}
increment() {
this.patch({ count: this.state.count + 1 });
}
}Quick example: React
import { useStructural } from '@dirtytalk/structural/react';
const counter = new Counter();
function CounterDisplay() {
const [state, container] = useStructural(counter);
// Only the paths read inside this render are recorded.
// Reading state.count watches "count". A patch to another key will not
// re-render this component.
return <button onClick={() => container.increment()}>{state.count}</button>;
}On each render, useStructural wraps state in a recording Proxy and, after commit, passes the
accessed paths to its consumer with setPaths. If props or context change what fields are read,
the watched paths update on the next commit. No selector declaration is required.
API surface: public exports
| Export | Role |
| --------------------------------- | --------------------------------------------------------------------- |
| StructuralStore<S> | Concrete container with public set, patch, update |
| StructuralContainer<S> | Base class: state, consumers, protected emit/patch/update |
| Consumer | { paths, setPaths(paths), dispose() }, from container.consume(cb) |
| PathInterner | Interning: intern(path): PathId, lookup(id): string, size |
| PathSet | Set<PathId> \| typeof ALL_PATHS |
| PathSetSpace | Space<PathSet> implementation for the engine |
| ALL_PATHS | Interest value: wake on every change |
| pathSetUnion | Pure union of two PathSet values |
| pathSetEquals | Equality check for two PathSet values |
| trackRender | (state, interner, proxyCache?) => { value, paths, disarm } |
| ProxyCache | Opt-in cache: reuses proxies across trackRender calls |
| raw, untracked | (v) => v: unwrap a tracked proxy to its raw target |
| getAt | (obj, dottedPath) => unknown |
| useStructural (react subpath) | (container) => [state, container] |
| setTrackTrace (testing) | (hook \| null) => void: observe tracking decisions |
Container members: state, interner, consume(cb), subscribe(cb), flush(),
consumers(), consumerCount (includes subscribe listeners) and dispose().
Options: scheduler, interner, equality (keyed by exact dotted path; a key containing . or
\ is written escaped), and onError (receives errors thrown by consumer callbacks).
Mutation semantics
emit(next)replaces the state. A no-op whenObject.is(state, next).patch(partial)isemit(deepMerge(state, partial)). Plain-object branches merge recursively. Arrays, class instances,Map,Set,Dateand primitives replace the slot. A patch cannot remove a key:undefinedis stored as a value. Useemitorupdateto remove one.update(fn)isemit(fn(state)).- With no consumers a mutation only replaces the state: no diff, no flush.
Tracking hazards
trackRender returns a recording proxy; values read off it are themselves
proxies. Two situations need raw() to unwrap them:
- Identity
===callbacks. Comparing a value read from the proxy against a raw object reference (directly, or via an identity-search likeArray.prototype.includes) fails because the value is wrapped. Compareraw(value) === rawRef. - Derived-array / escaped proxy. A proxy (or a sub-proxy inside a derived
array such as a
.filterresult) that escapes the render frame keeps recording into a stalepathsset and breaks reference identity against the underlying state. Callraw()on anything stored or handed to code that expects the raw object.
Supported state
Tracking assumes plain data: plain objects and arrays with string keys and
ordinary enumerable, writable properties. Frozen state (for example immer output) is tracked like
mutable state. Non-plain values (Map, Date, class instances) are leaves compared by
reference. Not tracked: symbol keys,
descriptor-only changes (same value, different flags), an own key starting to
shadow an inherited one with an equal value, own properties shadowing array
methods, and non-enumerable properties, which patch drops without a mark.
Cross-render proxy reuse (ProxyCache)
By default, trackRender allocates a brand-new Proxy for every object it touches, every single
call. For a component that maps over a large array (items.map(item => <Row key={item.id} .../>)),
that means a full re-render pays O(array length) proxy allocations even when almost every item is
the exact same object reference as last render, e.g. reordering two rows in a 1000-row list still
allocates ~1000 proxies for a change that only touched 2. ProxyCache, passed as trackRender's
optional third argument, fixes this: a (target, prefix) pair unchanged since the caller's last
trackRender call reuses the same Proxy object instead of allocating a new one.
import { trackRender, ProxyCache } from '@dirtytalk/structural';
// Scoped per call-site, e.g. one per component instance, created once and
// reused across that component's renders (a React `useRef(new ProxyCache())`
// is the typical home for it).
const proxyCache = new ProxyCache();
function renderList(state: { items: Item[] }) {
const { value, paths, disarm } = trackRender(state, interner, proxyCache);
// ...read value.items, etc...
disarm();
}Key properties:
- Keyed by
(target, prefix), not target alone. The same object read at two different paths in one render (aliasing) still gets two independent proxies, exactly as the no-cache behavior guarantees. Only a genuine repeat read at the same path across calls is reused. This is also why reordering an item to a brand-new index it has never occupied before still allocates a fresh proxy for it: the(target, prefix)pair is new, so there's nothing to reuse. The win is proportional to how many items keep their index across a render, which is exactly the common case (a two-item swap in a 1000-item list reuses 998 proxies and allocates 2). - Scope one
ProxyCacheper call-site, never globally or per-container. An entry holds exactly one live "session" (the render'spaths/armedstate) at a time; sharing a cache across two independently-timed callers would let one caller's render silently repoint an entry the other caller is still reading from. If a consumer tracks more than one independent thing per render (e.g. a primary state plus a separate dependency), give each its ownProxyCache. - No explicit eviction needed. The cache is
WeakMap-keyed by the target object, so entries for objects no longer referenced anywhere else are collected normally. disarm(),raw()/untracked(), and removal all keep working unchanged. A reused proxy still unwraps to the same raw target viaraw()regardless of how many renders old it is, anddisarm()still freezes exactly the entries touched by the render that called it.
What it is not
- No auto-tracked computed values. There is no
computed(() => a + b)with a hidden dependency graph. Build derived values above this layer. - No effect system with cleanups.
subscribereturns an unsubscribe function and aConsumerhasdispose(); those are the cleanup primitives. - No scheduler opinions. The scheduler is injected through the container options. The engine
provides
SyncScheduler,ManualScheduler,MicrotaskScheduler, andRAFScheduler; choose what fits your context. This package does not force one. - No mutation primitive. All updates go through
emit,patch, orupdate: immutable replacement only. In-place mutation ofstatebypasses change tracking silently. On aStructuralContainerthose three areprotected, so callers go through the methods a subclass exposes;StructuralStoreexposesset,patchandupdatepublicly. - No virtual DOM. The React adapter triggers re-renders via
useSyncExternalStore; the actual reconciliation is React's job.
License
MIT, see LICENSE.
