@mmstack/primitives 21.5.0 → 21.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -1
- package/fesm2022/mmstack-primitives.mjs +206 -24
- package/fesm2022/mmstack-primitives.mjs.map +1 -1
- package/package.json +1 -1
- package/types/mmstack-primitives.d.ts +112 -3
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ npm install @mmstack/primitives
|
|
|
17
17
|
|
|
18
18
|
- [Writable signal variants](#writable-signal-variants) — `mutable`, `derived`, `store` / `mutableStore`, `forkStore`, `toWritable`
|
|
19
19
|
- [Timing & propagation](#timing--propagation) — `debounced`, `throttled`, `until`
|
|
20
|
-
- [Reactive collections](#reactive-collections) — `indexArray`, `keyArray`, `mapObject`
|
|
20
|
+
- [Reactive collections](#reactive-collections) — `indexArray`, `keyArray`, `mapObject`, `projection`
|
|
21
21
|
- [Effects](#effects) — `nestedEffect`
|
|
22
22
|
- [Concurrency & transitions](#concurrency--transitions) — `keepPrevious`, keep-alive (`MmActivity`), `pausable*` / `providePausableOptions`, Suspense (`mm-suspense`), hold-and-swap (`*mmTransition`), per-element morphs (`mmViewTransitionName`), async derivations (`latest` / `use`), `deferredValue`, `startTransition` / `startTransaction`, `holdUntilReady`
|
|
23
23
|
- [History & persistence](#history--persistence) — `withHistory`, `stored`, `tabSync`, `opLog`
|
|
@@ -303,6 +303,32 @@ const controls = mapObject(
|
|
|
303
303
|
);
|
|
304
304
|
```
|
|
305
305
|
|
|
306
|
+
### `projection`
|
|
307
|
+
|
|
308
|
+
A derived **store**, the store-shaped counterpart to `computed`. Where `derived` slices one value out of a source and `indexArray` / `keyArray` map a list, `projection` derives a whole store subtree from a computation. `fn` receives a mutable draft seeded with the current value and either mutates it or returns new data; the result is reconciled against the previous value so unchanged object subtrees keep their reference and keyed array items keep their identity across recomputes. Reading through the returned store is per-leaf, so a `computed` over one field only recomputes when that field actually changes, even though the whole projection re-ran.
|
|
309
|
+
|
|
310
|
+
```typescript
|
|
311
|
+
import { projection } from '@mmstack/primitives';
|
|
312
|
+
|
|
313
|
+
const users = signal<User[]>([]);
|
|
314
|
+
|
|
315
|
+
// return form: derive a filtered collection, reconciled by id
|
|
316
|
+
const active = projection<User[]>(() => users().filter((u) => u.active), [], {
|
|
317
|
+
key: 'id',
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
// mutate form: update fields on the draft
|
|
321
|
+
const summary = projection<{ total: number; active: number }>(
|
|
322
|
+
(draft) => {
|
|
323
|
+
draft.total = users().length;
|
|
324
|
+
draft.active = users().filter((u) => u.active).length;
|
|
325
|
+
},
|
|
326
|
+
{ total: 0, active: 0 },
|
|
327
|
+
);
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
Recompute is pull-based, exactly like `computed`: memoized, re-run on the first read after a dependency changes, coherent immediately after a write (no waiting on an effect flush), and skipped entirely while nobody reads. `fn` must be pure since it runs inside the reactive computation. Prefer `computed` for a plain value, and reach for `projection` when you want the per-property tracking of a store on top of a derivation. The standalone `reconcile(prev, next, key)` is exported too, for producing a reference-stable value by hand. Values must be structured-clonable (the draft is a clone of the current value). With an explicit store context (`createStoreContext()`) a projection is injector-free, so it also runs on a worker host.
|
|
331
|
+
|
|
306
332
|
## Effects
|
|
307
333
|
|
|
308
334
|
### `nestedEffect`
|
|
@@ -681,6 +707,7 @@ log.latest(); // Signal<OpBatch | null> — lossy sampling (devtools-style)
|
|
|
681
707
|
state.user.name.set('Bea');
|
|
682
708
|
// → { origin, version, ops: [{ kind: 'set', path: ['user','name'], next: 'Bea', prev: 'Ann' }] }
|
|
683
709
|
|
|
710
|
+
log.flush(); // synchronously emit any pending change now, instead of waiting for the tick. idempotent, no-op when clean.
|
|
684
711
|
log.apply(remoteBatch); // applies ops in ONE commit AND advances the diff baseline —
|
|
685
712
|
// so applying a remote batch emits no echo batch (sync loops terminate by construction)
|
|
686
713
|
invertBatch(batch); // prev-based inverse — undo is a data transform
|
|
@@ -688,6 +715,8 @@ invertBatch(batch); // prev-based inverse — undo is a data transform
|
|
|
688
715
|
|
|
689
716
|
Batching is per tick (two writes to one leaf in a tick emit one composed op), `prev` is always carried in-memory (structural sharing makes it free — wire serializers decide whether to keep it), arrays diff per-index at equal lengths and as whole-array ops on length change, and a `forkStore`'s `commit()` lands as a single batch — fork *is* the transaction primitive. Mutable stores are unsupported (in-place mutation defeats ref-identity diffing; dev warn). This is the substrate for worker mirrors, tab/mesh sync, persistence journals, and undo — one protocol, many consumers.
|
|
690
717
|
|
|
718
|
+
An `opLog` can also run with no Angular injector, which is what lets the graph mirror into a Web Worker. Pass `driver: microtaskOpLogDriver()` to drive emission off the microtask queue instead of an `effect()`, and build the store with `createStoreContext()` (a self-contained proxy cache) so `store` and `opLog` work in a worker or a plain Node process. The pure helpers `applyOps(root, ops)` and `diffOps(prev, next)` apply and produce batches without owning a log. [`@mmstack/worker`](https://www.npmjs.com/package/@mmstack/worker) is built directly on these seams.
|
|
719
|
+
|
|
691
720
|
## Performance helpers
|
|
692
721
|
|
|
693
722
|
### `chunked`
|
|
@@ -4263,7 +4263,11 @@ function buildChildNode(target, prop, isMutableSource, options) {
|
|
|
4263
4263
|
function toStore(source, { injector, vivify = false, noUnionLeaves = false, ...rest } = {}) {
|
|
4264
4264
|
if (isStore(source))
|
|
4265
4265
|
return source;
|
|
4266
|
-
if
|
|
4266
|
+
// injector is needed ONLY to resolve the two proxy-globals tokens; if a caller supplies the
|
|
4267
|
+
// globals directly (createStoreContext — the worker-side seam with no DI), skip inject entirely
|
|
4268
|
+
const sharedGlobals = rest[STORE_SHARED_GLOBALS];
|
|
4269
|
+
const hasSharedGlobals = !!(sharedGlobals?.cache && sharedGlobals?.registry);
|
|
4270
|
+
if (!injector && !hasSharedGlobals)
|
|
4267
4271
|
injector = inject(Injector);
|
|
4268
4272
|
const writableSource = isWritableSignal(source)
|
|
4269
4273
|
? source
|
|
@@ -4281,13 +4285,18 @@ function toStore(source, { injector, vivify = false, noUnionLeaves = false, ...r
|
|
|
4281
4285
|
return 'primitive';
|
|
4282
4286
|
}, ...(ngDevMode ? [{ debugName: "kind" }] : /* istanbul ignore next */ []));
|
|
4283
4287
|
const STORE_OPTIONS = {
|
|
4284
|
-
|
|
4288
|
+
// may be undefined in worker/DI-less mode; unused downstream once globals are resolved
|
|
4289
|
+
// (children thread the resolved globals via STORE_SHARED_OPTIONS, derived needs no injector)
|
|
4290
|
+
injector: injector,
|
|
4285
4291
|
vivify,
|
|
4286
4292
|
noUnionLeaves,
|
|
4287
4293
|
[STORE_SHARED_GLOBALS]: {
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
|
|
4294
|
+
// the `injector!` reads run only when a global is absent, which (per hasSharedGlobals) means
|
|
4295
|
+
// an injector was resolved above
|
|
4296
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
4297
|
+
cache: sharedGlobals?.cache ?? injector.get(PROXY_CACHE_TOKEN),
|
|
4298
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
4299
|
+
registry: sharedGlobals?.registry ?? injector.get(PROXY_CLEANUP_TOKEN),
|
|
4291
4300
|
},
|
|
4292
4301
|
};
|
|
4293
4302
|
// built lazily so non-array nodes never allocate it
|
|
@@ -4359,7 +4368,14 @@ function toStore(source, { injector, vivify = false, noUnionLeaves = false, ...r
|
|
|
4359
4368
|
return () => {
|
|
4360
4369
|
if (!isWritableSource)
|
|
4361
4370
|
return s;
|
|
4362
|
-
return untracked(() => toStore(source.asReadonly(), {
|
|
4371
|
+
return untracked(() => toStore(source.asReadonly(), {
|
|
4372
|
+
injector,
|
|
4373
|
+
vivify,
|
|
4374
|
+
noUnionLeaves,
|
|
4375
|
+
// forward the resolved globals — re-resolving from the injector both re-injects
|
|
4376
|
+
// needlessly and breaks in DI-less (worker) mode where injector is undefined
|
|
4377
|
+
[STORE_SHARED_GLOBALS]: STORE_OPTIONS[STORE_SHARED_GLOBALS],
|
|
4378
|
+
}));
|
|
4363
4379
|
};
|
|
4364
4380
|
const k = untracked(kind);
|
|
4365
4381
|
if (prop === 'extend' && k !== 'array')
|
|
@@ -4524,6 +4540,40 @@ function mutableStore(value, opt) {
|
|
|
4524
4540
|
...opt,
|
|
4525
4541
|
});
|
|
4526
4542
|
}
|
|
4543
|
+
/**
|
|
4544
|
+
* Builds a DI-less store context — the shared proxy-cache and cleanup registry that {@link toStore}
|
|
4545
|
+
* normally resolves from the injector — so a `store`/`toStore`/`opLog` graph can run with NO Angular
|
|
4546
|
+
* injection context. Spread the result into the options:
|
|
4547
|
+
*
|
|
4548
|
+
* ```ts
|
|
4549
|
+
* import { microtaskOpLogDriver } from '@mmstack/worker/host';
|
|
4550
|
+
* const ctx = createStoreContext();
|
|
4551
|
+
* const s = store({ todos: [] }, ctx);
|
|
4552
|
+
* const log = opLog(s, { driver: microtaskOpLogDriver(), origin: 'worker' }); // no injector anywhere
|
|
4553
|
+
* ```
|
|
4554
|
+
*
|
|
4555
|
+
* **This is a worker-only fallback — do NOT use it on the main thread.** DI is the default and
|
|
4556
|
+
* correct path in an app: the injector scopes the proxy-cache/cleanup singletons per app instance,
|
|
4557
|
+
* which on the SERVER keeps one request's store identity from bleeding into another's (the exact
|
|
4558
|
+
* hazard a module-scope singleton would reintroduce). A Web Worker is safe because it is a single
|
|
4559
|
+
* store graph per thread and never runs during SSR (spawn is a `PLATFORM_ID === 'server'` no-op),
|
|
4560
|
+
* so there is no cross-request scope to contaminate. Never hoist a `createStoreContext()` to module
|
|
4561
|
+
* scope on a shared/main thread.
|
|
4562
|
+
*
|
|
4563
|
+
* **Share ONE context across every store in a worker** — the same way `providedIn: 'root'` shares
|
|
4564
|
+
* one cache across all of an app's stores. `@mmstack/worker/host` memoizes this per worker
|
|
4565
|
+
* (`workerStoreContext()`); reach for `createStoreContext()` directly only in a bare
|
|
4566
|
+
* (non-worker-host) DI-less setup, and hold the single instance yourself.
|
|
4567
|
+
*/
|
|
4568
|
+
function createStoreContext() {
|
|
4569
|
+
const cache = new WeakMap();
|
|
4570
|
+
const registry = new FinalizationRegistry(({ target, prop }) => {
|
|
4571
|
+
const entry = cache.get(target);
|
|
4572
|
+
if (entry)
|
|
4573
|
+
entry.delete(prop);
|
|
4574
|
+
});
|
|
4575
|
+
return { [STORE_SHARED_GLOBALS]: { cache, registry } };
|
|
4576
|
+
}
|
|
4527
4577
|
|
|
4528
4578
|
function isPlainRecord(value) {
|
|
4529
4579
|
if (value === null || typeof value !== 'object')
|
|
@@ -4603,7 +4653,7 @@ function generateOrigin() {
|
|
|
4603
4653
|
return globalThis.crypto.randomUUID();
|
|
4604
4654
|
return Math.random().toString(36).substring(2);
|
|
4605
4655
|
}
|
|
4606
|
-
const isPlainArray = (v) => Array.isArray(v) && !isOpaque(v);
|
|
4656
|
+
const isPlainArray$1 = (v) => Array.isArray(v) && !isOpaque(v);
|
|
4607
4657
|
/**
|
|
4608
4658
|
* Reference-identity-pruned structural diff — the same short-circuit discipline as `merge3`:
|
|
4609
4659
|
* an untouched subtree kept its reference (the store's copy-on-write contract), so the walk
|
|
@@ -4628,7 +4678,7 @@ function diffNode(prev, next, path, ops) {
|
|
|
4628
4678
|
}
|
|
4629
4679
|
return;
|
|
4630
4680
|
}
|
|
4631
|
-
if (isPlainArray(prev) && isPlainArray(next)) {
|
|
4681
|
+
if (isPlainArray$1(prev) && isPlainArray$1(next)) {
|
|
4632
4682
|
// same length → per-index descent (matches `arr[i].x.set(...)` writes); a length
|
|
4633
4683
|
// change is a whole unit — index attribution lies under insert/remove/reorder
|
|
4634
4684
|
if (prev.length === next.length) {
|
|
@@ -4645,7 +4695,7 @@ function diffNode(prev, next, path, ops) {
|
|
|
4645
4695
|
/** Immutably applies one op along its path, vivifying missing containers `'auto'`-style. */
|
|
4646
4696
|
function applyAt(container, path, idx, op) {
|
|
4647
4697
|
const seg = path[idx];
|
|
4648
|
-
const base = isPlainArray(container)
|
|
4698
|
+
const base = isPlainArray$1(container)
|
|
4649
4699
|
? container.slice()
|
|
4650
4700
|
: isRecord(container)
|
|
4651
4701
|
? { ...container }
|
|
@@ -4665,6 +4715,37 @@ function applyAt(container, path, idx, op) {
|
|
|
4665
4715
|
base[seg] = applyAt(base[seg], path, idx + 1, op);
|
|
4666
4716
|
return base;
|
|
4667
4717
|
}
|
|
4718
|
+
/**
|
|
4719
|
+
* Pure, store-free application of ops onto a plain root value, returning the next immutable root
|
|
4720
|
+
* (structural-sharing along op paths, missing containers vivified `'auto'`-style). This is the
|
|
4721
|
+
* same transform {@link OpLog.apply} runs, extracted so a replica can fold a received batch into
|
|
4722
|
+
* a value WITHOUT owning a diffing {@link opLog} — e.g. the worker-graph read-replica seam.
|
|
4723
|
+
* Accepts a batch or a bare op list.
|
|
4724
|
+
*/
|
|
4725
|
+
function applyOps(root, ops) {
|
|
4726
|
+
const list = Array.isArray(ops) ? ops : ops.ops;
|
|
4727
|
+
let next = root;
|
|
4728
|
+
for (const op of list) {
|
|
4729
|
+
if (op.path.length === 0) {
|
|
4730
|
+
if (op.kind === 'set')
|
|
4731
|
+
next = op.next;
|
|
4732
|
+
continue; // a root delete is meaningless — ignore (mirrors OpLog.apply)
|
|
4733
|
+
}
|
|
4734
|
+
next = applyAt(next, op.path, 0, op);
|
|
4735
|
+
}
|
|
4736
|
+
return next;
|
|
4737
|
+
}
|
|
4738
|
+
/**
|
|
4739
|
+
* Pure reference-pruned structural diff of two roots into minimal ops (the emission core of
|
|
4740
|
+
* {@link opLog}, exported so code outside a log can produce a batch — e.g. diffing a scratch
|
|
4741
|
+
* draft against a replica's current value to route a write to its owner). Trusts the
|
|
4742
|
+
* copy-on-write contract: an untouched subtree that kept its reference is skipped.
|
|
4743
|
+
*/
|
|
4744
|
+
function diffOps(prev, next) {
|
|
4745
|
+
const ops = [];
|
|
4746
|
+
diffNode(prev, next, [], ops);
|
|
4747
|
+
return ops;
|
|
4748
|
+
}
|
|
4668
4749
|
/**
|
|
4669
4750
|
* Inverts a batch for undo: reversed order, `set`↔its own inverse (an add — a `set` with no
|
|
4670
4751
|
* `prev` — inverts to a `delete`; a `delete` inverts to a `set` restoring `prev`). Feed the
|
|
@@ -4677,14 +4758,24 @@ function invertBatch(batch) {
|
|
|
4677
4758
|
for (let i = ops.length - 1; i >= 0; i--) {
|
|
4678
4759
|
const op = ops[i];
|
|
4679
4760
|
if (op.kind === 'delete') {
|
|
4680
|
-
inverted.push({
|
|
4761
|
+
inverted.push({
|
|
4762
|
+
kind: 'set',
|
|
4763
|
+
path: op.path,
|
|
4764
|
+
next: op.prev,
|
|
4765
|
+
prev: undefined,
|
|
4766
|
+
});
|
|
4681
4767
|
continue;
|
|
4682
4768
|
}
|
|
4683
4769
|
if (!Object.hasOwn(op, 'prev')) {
|
|
4684
4770
|
inverted.push({ kind: 'delete', path: op.path, prev: op.next });
|
|
4685
4771
|
}
|
|
4686
4772
|
else {
|
|
4687
|
-
inverted.push({
|
|
4773
|
+
inverted.push({
|
|
4774
|
+
kind: 'set',
|
|
4775
|
+
path: op.path,
|
|
4776
|
+
next: op.prev,
|
|
4777
|
+
prev: op.next,
|
|
4778
|
+
});
|
|
4688
4779
|
}
|
|
4689
4780
|
}
|
|
4690
4781
|
return inverted;
|
|
@@ -4713,7 +4804,6 @@ function invertBatch(batch) {
|
|
|
4713
4804
|
* ```
|
|
4714
4805
|
*/
|
|
4715
4806
|
function opLog(source, opt) {
|
|
4716
|
-
const injector = opt?.injector ?? inject(Injector);
|
|
4717
4807
|
const origin = opt?.origin ?? generateOrigin();
|
|
4718
4808
|
// a store proxy's `has` trap answers for the VALUE's keys, so `isMutable`'s `'mutate' in`
|
|
4719
4809
|
// probe can't see the brand — ask the store's own kind symbol first
|
|
@@ -4744,16 +4834,24 @@ function opLog(source, opt) {
|
|
|
4744
4834
|
for (const cb of [...subscribers])
|
|
4745
4835
|
cb(batch);
|
|
4746
4836
|
};
|
|
4747
|
-
const
|
|
4837
|
+
const run = () => {
|
|
4748
4838
|
source(); // track every commit…
|
|
4749
4839
|
untracked(flush); // …and emit the delta since the last flush
|
|
4750
|
-
}
|
|
4840
|
+
};
|
|
4841
|
+
// default driver is an Angular effect (needs an injector); a supplied driver runs injector-free
|
|
4842
|
+
// (the worker-side seam, e.g. microtaskOpLogDriver from @mmstack/worker/host)
|
|
4843
|
+
const ref = opt?.driver
|
|
4844
|
+
? opt.driver(run)
|
|
4845
|
+
: effect(run, { injector: opt?.injector ?? inject(Injector) });
|
|
4751
4846
|
return {
|
|
4752
4847
|
latest: latest.asReadonly(),
|
|
4753
4848
|
subscribe: (cb) => {
|
|
4754
4849
|
subscribers.add(cb);
|
|
4755
4850
|
return () => subscribers.delete(cb);
|
|
4756
4851
|
},
|
|
4852
|
+
// the emission core, callable on demand — reads the source untracked, so it never disturbs the
|
|
4853
|
+
// driver's subscription; a subsequent scheduled run just finds the baseline already advanced
|
|
4854
|
+
flush: () => flush(),
|
|
4757
4855
|
apply: (batchOrOps) => {
|
|
4758
4856
|
const ops = Array.isArray(batchOrOps)
|
|
4759
4857
|
? batchOrOps
|
|
@@ -4762,15 +4860,7 @@ function opLog(source, opt) {
|
|
|
4762
4860
|
return;
|
|
4763
4861
|
// pending local writes must emit BEFORE the baseline advances past them
|
|
4764
4862
|
flush();
|
|
4765
|
-
|
|
4766
|
-
for (const op of ops) {
|
|
4767
|
-
if (op.path.length === 0) {
|
|
4768
|
-
if (op.kind === 'set')
|
|
4769
|
-
root = op.next;
|
|
4770
|
-
continue; // a root delete is meaningless — ignore
|
|
4771
|
-
}
|
|
4772
|
-
root = applyAt(root, op.path, 0, op);
|
|
4773
|
-
}
|
|
4863
|
+
const root = applyOps(untracked(source), ops); // one atomic root, structural-shared
|
|
4774
4864
|
source.set(root);
|
|
4775
4865
|
prevRoot = root; // baseline advance: an applied batch never echoes
|
|
4776
4866
|
},
|
|
@@ -4782,6 +4872,98 @@ function opLog(source, opt) {
|
|
|
4782
4872
|
};
|
|
4783
4873
|
}
|
|
4784
4874
|
|
|
4875
|
+
const isPlainArray = (v) => Array.isArray(v) && !isOpaque(v);
|
|
4876
|
+
function keyOf(item, key) {
|
|
4877
|
+
if (typeof key === 'function')
|
|
4878
|
+
return key(item);
|
|
4879
|
+
return isRecord(item) ? item[key] : item;
|
|
4880
|
+
}
|
|
4881
|
+
/**
|
|
4882
|
+
* Produces a value equal to `next` but sharing as much of `prev`'s reference structure as possible:
|
|
4883
|
+
* an object subtree that did not change keeps its `prev` reference, and array items are matched by
|
|
4884
|
+
* `key` so a surviving item keeps its identity across a reorder/insert/remove (only added items are
|
|
4885
|
+
* new, only removed items are dropped). This is what lets a derived store recompute without tearing
|
|
4886
|
+
* down every downstream `computed` that reads an unchanged part of it.
|
|
4887
|
+
*/
|
|
4888
|
+
function reconcile(prev, next, key = 'id') {
|
|
4889
|
+
return reconcileValue(prev, next, key);
|
|
4890
|
+
}
|
|
4891
|
+
function reconcileValue(prev, next, key) {
|
|
4892
|
+
if (Object.is(prev, next))
|
|
4893
|
+
return prev;
|
|
4894
|
+
if (isPlainArray(prev) && isPlainArray(next)) {
|
|
4895
|
+
const byKey = new Map();
|
|
4896
|
+
for (const item of prev)
|
|
4897
|
+
byKey.set(keyOf(item, key), item);
|
|
4898
|
+
let changed = prev.length !== next.length;
|
|
4899
|
+
const out = next.map((item, i) => {
|
|
4900
|
+
const match = byKey.get(keyOf(item, key));
|
|
4901
|
+
const rv = match !== undefined ? reconcileValue(match, item, key) : item;
|
|
4902
|
+
if (rv !== prev[i])
|
|
4903
|
+
changed = true;
|
|
4904
|
+
return rv;
|
|
4905
|
+
});
|
|
4906
|
+
return changed ? out : prev;
|
|
4907
|
+
}
|
|
4908
|
+
if (isRecord(prev) && isRecord(next)) {
|
|
4909
|
+
const nextKeys = Object.keys(next);
|
|
4910
|
+
let changed = Object.keys(prev).length !== nextKeys.length;
|
|
4911
|
+
const out = {};
|
|
4912
|
+
for (const k of nextKeys) {
|
|
4913
|
+
const rv = Object.hasOwn(prev, k)
|
|
4914
|
+
? reconcileValue(prev[k], next[k], key)
|
|
4915
|
+
: next[k];
|
|
4916
|
+
out[k] = rv;
|
|
4917
|
+
if (rv !== prev[k])
|
|
4918
|
+
changed = true;
|
|
4919
|
+
}
|
|
4920
|
+
return changed ? out : prev;
|
|
4921
|
+
}
|
|
4922
|
+
return next;
|
|
4923
|
+
}
|
|
4924
|
+
/**
|
|
4925
|
+
* A derived STORE, the store-shaped counterpart to `computed`. `fn` receives a mutable draft seeded
|
|
4926
|
+
* with the current value and either mutates it in place or returns a new value; whichever it does,
|
|
4927
|
+
* the result is reconciled against the previous value (see {@link reconcile}) so unchanged subtrees
|
|
4928
|
+
* keep reference identity and keyed array items keep their proxy identity. Reading through the
|
|
4929
|
+
* returned store is fine-grained: a `computed` over one field only recomputes when that field
|
|
4930
|
+
* actually changes, even though the whole projection re-ran.
|
|
4931
|
+
*
|
|
4932
|
+
* Recompute is pull-based, exactly like `computed`: the projection is memoized and re-runs on the
|
|
4933
|
+
* first read after a signal `fn` depends on changes, so reads are always coherent (no waiting on an
|
|
4934
|
+
* effect flush) and nothing recomputes while nobody reads. `fn` must be pure, it runs inside the
|
|
4935
|
+
* reactive computation. Prefer `computed` for a plain value; reach for `projection` when you want
|
|
4936
|
+
* the per-property tracking of a store on top of a derivation.
|
|
4937
|
+
*
|
|
4938
|
+
* ```ts
|
|
4939
|
+
* const active = projection<User[]>(() => users().filter((u) => u.active), [], { key: 'id' });
|
|
4940
|
+
* // active[0].name(); — surviving users keep identity across recomputes
|
|
4941
|
+
* ```
|
|
4942
|
+
*
|
|
4943
|
+
* Needs an injection context (or an explicit `injector`) for the store layer's cleanup on the main
|
|
4944
|
+
* thread; with an explicit store context (`createStoreContext()`) it is injector-free, so it also
|
|
4945
|
+
* runs on a worker host.
|
|
4946
|
+
*
|
|
4947
|
+
* @param fn receives the current draft; mutate it, or return new data.
|
|
4948
|
+
* @param seed the initial value, held before the first run.
|
|
4949
|
+
*/
|
|
4950
|
+
function projection(fn, seed, opt) {
|
|
4951
|
+
const { key = 'id', ...storeOpt } = opt ?? {};
|
|
4952
|
+
// linkedSignal rather than an effect-driven signal: the computation runs in the tracked
|
|
4953
|
+
// context (fn's reads are dependencies) and `previous` hands back the last emitted value for
|
|
4954
|
+
// the reconcile, so the projection is glitch-free, lazy, and needs no effect scheduler.
|
|
4955
|
+
const root = linkedSignal({ ...(ngDevMode ? { debugName: "root" } : /* istanbul ignore next */ {}), source: () => undefined,
|
|
4956
|
+
computation: (_, previous) => {
|
|
4957
|
+
const base = previous ? previous.value : seed;
|
|
4958
|
+
// a plain mutable scratch seeded with the current value; fn mutates it or returns new data
|
|
4959
|
+
const draft = structuredClone(base);
|
|
4960
|
+
const returned = fn(draft);
|
|
4961
|
+
const next = (returned === undefined ? draft : returned);
|
|
4962
|
+
return reconcile(base, next, key);
|
|
4963
|
+
} });
|
|
4964
|
+
return toStore(root, storeOpt).asReadonlyStore();
|
|
4965
|
+
}
|
|
4966
|
+
|
|
4785
4967
|
/**
|
|
4786
4968
|
* @internal The plain-`effect` sibling of the public {@link pausableEffect} (which is built on
|
|
4787
4969
|
* `nestedEffect`). For infra utilities that own a single top-level effect/subscription and don't
|
|
@@ -5307,5 +5489,5 @@ function withHistory(sourceOrValue, opt) {
|
|
|
5307
5489
|
* Generated bundle index. Do not edit.
|
|
5308
5490
|
*/
|
|
5309
5491
|
|
|
5310
|
-
export { MmActivity, MmTransition, MmViewTransitionName, PAUSABLE_OPTIONS, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, batteryStatus, bridgeScopeToPendingTasks, chunked, clipboard, combineWith, createAttributedPending, createForwardingScope, createTransaction, createTransitionScope, debounce, debounced, deferredValue, derived, distinct, elementSize, elementVisibility, extendStore, filter, filterWith, focusWithin, forkStore, geolocation, getTransitionScope, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, invertBatch, isDerivation, isLeaf, isMutable, isOpaque, isStore, keepPrevious, keyArray, latest, map, mapArray, mapObject, mediaQuery, merge3, mousePosition, mutable, mutableStore, nestedEffect, networkStatus, opLog, opaque, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, pipeable, piped, pointerDrag, pooled, pooledArray, pooledMap, pooledSet, prefersDarkMode, prefersReducedMotion, provideForwardingTransitionScope, providePausableOptions, providePaused, provideTransitionScope, registerResource, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, stored, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, until, use, windowSize, withHistory };
|
|
5492
|
+
export { MmActivity, MmTransition, MmViewTransitionName, PAUSABLE_OPTIONS, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, applyOps, batteryStatus, bridgeScopeToPendingTasks, chunked, clipboard, combineWith, createAttributedPending, createForwardingScope, createStoreContext, createTransaction, createTransitionScope, debounce, debounced, deferredValue, derived, diffOps, distinct, elementSize, elementVisibility, extendStore, filter, filterWith, focusWithin, forkStore, geolocation, getTransitionScope, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, invertBatch, isDerivation, isLeaf, isMutable, isOpaque, isStore, keepPrevious, keyArray, latest, map, mapArray, mapObject, mediaQuery, merge3, mousePosition, mutable, mutableStore, nestedEffect, networkStatus, opLog, opaque, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, pipeable, piped, pointerDrag, pooled, pooledArray, pooledMap, pooledSet, prefersDarkMode, prefersReducedMotion, projection, provideForwardingTransitionScope, providePausableOptions, providePaused, provideTransitionScope, reconcile, registerResource, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, stored, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, until, use, windowSize, withHistory };
|
|
5311
5493
|
//# sourceMappingURL=mmstack-primitives.mjs.map
|