@mmstack/primitives 21.0.28 → 21.1.0
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 +229 -1
- package/fesm2022/mmstack-primitives.mjs +733 -71
- package/fesm2022/mmstack-primitives.mjs.map +1 -1
- package/package.json +1 -1
- package/types/mmstack-primitives.d.ts +451 -11
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as i0 from '@angular/core';
|
|
2
|
-
import { isDevMode, inject, Injector, untracked, effect, DestroyRef, linkedSignal, computed, signal, isWritableSignal as isWritableSignal$
|
|
2
|
+
import { isDevMode, inject, Injector, untracked, effect, DestroyRef, linkedSignal, InjectionToken, TemplateRef, ViewContainerRef, input, computed, Directive, signal, PLATFORM_ID, runInInjectionContext, afterNextRender, Component, isWritableSignal as isWritableSignal$2, isSignal, ElementRef, Injectable } from '@angular/core';
|
|
3
3
|
import { isPlatformServer } from '@angular/common';
|
|
4
4
|
import { SIGNAL } from '@angular/core/primitives/signals';
|
|
5
5
|
|
|
@@ -212,6 +212,555 @@ function chunked(source, options) {
|
|
|
212
212
|
return internal.asReadonly();
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
+
/**
|
|
216
|
+
* Whether the subtree a resource/component lives in is currently PAUSED, for Activity / keep-alive.
|
|
217
|
+
* Provided by an Activity boundary (`MmActivity`, or the app-builder's per-branch injector) and read
|
|
218
|
+
* — only at instantiation — by anything that should pause its background work while paused (a resource
|
|
219
|
+
* returning its `paused` token, a `<video>` pausing playback, the pausable primitives, …). Absent
|
|
220
|
+
* unless an Activity boundary provides one — read it via `injectPaused()`, which falls back to a
|
|
221
|
+
* never-paused signal, so code that isn't inside an Activity boundary is unaffected.
|
|
222
|
+
*/
|
|
223
|
+
const PAUSED_CONTEXT = new InjectionToken('@mmstack/primitives:paused-context');
|
|
224
|
+
/**
|
|
225
|
+
* Keep-alive (the Angular analog of React's `<Activity>` / Vue's `<keep-alive>`): the wrapped
|
|
226
|
+
* subtree is mounted ONCE and kept — when `[mmActivity]` is false it's hidden (`display:none`) and
|
|
227
|
+
* its change detection is paused, preserving state (scroll, inputs, a video's position, loaded
|
|
228
|
+
* data); when true it's shown and CD resumes. It is never destroyed until the directive is.
|
|
229
|
+
*
|
|
230
|
+
* It also provides {@link PAUSED_CONTEXT} to the content (= the negation of `visible`), so descendants
|
|
231
|
+
* can pause *effect-driven* or *Observable* work while hidden (CD-detach alone pauses pull-based/template work, not
|
|
232
|
+
* effects/polling). If you're using the pausable primitives this is done automatically
|
|
233
|
+
*
|
|
234
|
+
* ```html
|
|
235
|
+
* <section *mmActivity="tab() === 'editor'"> ...heavy stateful editor... </section>
|
|
236
|
+
* ```
|
|
237
|
+
*/
|
|
238
|
+
class MmActivity {
|
|
239
|
+
tpl = inject(TemplateRef);
|
|
240
|
+
vcr = inject(ViewContainerRef);
|
|
241
|
+
parent = inject(Injector);
|
|
242
|
+
/** When false, keep the content mounted but hidden + CD-detached. */
|
|
243
|
+
visible = input.required({ ...(ngDevMode ? { debugName: "visible" } : /* istanbul ignore next */ {}), alias: 'mmActivity' });
|
|
244
|
+
/** Paused == not visible — handed to the kept subtree as PAUSED_CONTEXT. */
|
|
245
|
+
paused = computed(() => !this.visible(), ...(ngDevMode ? [{ debugName: "paused" }] : /* istanbul ignore next */ []));
|
|
246
|
+
view = null;
|
|
247
|
+
constructor() {
|
|
248
|
+
effect(() => {
|
|
249
|
+
const visible = this.visible();
|
|
250
|
+
untracked(() => this.apply(visible));
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
apply(visible) {
|
|
254
|
+
if (!this.view) {
|
|
255
|
+
// Created once, kept for the directive's lifetime. The content gets PAUSED_CONTEXT = !visible,
|
|
256
|
+
// so resources/components inside can pause their effect-driven work while hidden.
|
|
257
|
+
this.view = this.vcr.createEmbeddedView(this.tpl, {}, {
|
|
258
|
+
injector: Injector.create({
|
|
259
|
+
parent: this.parent,
|
|
260
|
+
providers: [providePaused(this.paused)],
|
|
261
|
+
}),
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
for (const node of this.view.rootNodes) {
|
|
265
|
+
if (node instanceof HTMLElement)
|
|
266
|
+
node.style.display = visible ? '' : 'none';
|
|
267
|
+
}
|
|
268
|
+
if (visible)
|
|
269
|
+
this.view.reattach();
|
|
270
|
+
else
|
|
271
|
+
this.view.detach();
|
|
272
|
+
}
|
|
273
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.12", ngImport: i0, type: MmActivity, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
274
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.12", type: MmActivity, isStandalone: true, selector: "[mmActivity]", inputs: { visible: { classPropertyName: "visible", publicName: "mmActivity", isSignal: true, isRequired: true, transformFunction: null } }, ngImport: i0 });
|
|
275
|
+
}
|
|
276
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.12", ngImport: i0, type: MmActivity, decorators: [{
|
|
277
|
+
type: Directive,
|
|
278
|
+
args: [{
|
|
279
|
+
selector: '[mmActivity]',
|
|
280
|
+
}]
|
|
281
|
+
}], ctorParameters: () => [], propDecorators: { visible: [{ type: i0.Input, args: [{ isSignal: true, alias: "mmActivity", required: true }] }] } });
|
|
282
|
+
// Shared never-paused signal returned outside a boundary / on the server (SSR renders the full tree,
|
|
283
|
+
// nothing is paused). Readonly so a consumer can't cast-and-`.set()` the shared default for everyone.
|
|
284
|
+
const NEVER_PAUSED = signal(false).asReadonly();
|
|
285
|
+
/**
|
|
286
|
+
* Inject the nearest paused-state signal — `true` while the surrounding subtree is paused (hidden by
|
|
287
|
+
* an Activity boundary). Defaults to a never-paused signal, so callers outside an Activity are
|
|
288
|
+
* unaffected; on the server it is always never-paused, so server-side work (e.g. connector fetches)
|
|
289
|
+
* isn't suppressed. This is the public way to read pause state; the underlying token is intentionally
|
|
290
|
+
* not exported.
|
|
291
|
+
*/
|
|
292
|
+
function injectPaused() {
|
|
293
|
+
if (isPlatformServer(inject(PLATFORM_ID, { optional: true }) ?? 'browser'))
|
|
294
|
+
return NEVER_PAUSED;
|
|
295
|
+
return inject(PAUSED_CONTEXT, { optional: true }) ?? NEVER_PAUSED;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Build a provider that supplies a paused-state signal to a subtree — the public way to set up an
|
|
299
|
+
* Activity-style pause boundary (used by `MmActivity` and the app-builder's per-branch injectors).
|
|
300
|
+
*/
|
|
301
|
+
function providePaused(source) {
|
|
302
|
+
return { provide: PAUSED_CONTEXT, useValue: source };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Structural hold-and-swap as a signal. Given a `target` (the desired value — e.g. the
|
|
307
|
+
* subtree/def/key you want to show) and a `ready` predicate, returns a signal that keeps
|
|
308
|
+
* yielding its PREVIOUS value until `ready()` is true, then swaps to the current target.
|
|
309
|
+
*
|
|
310
|
+
* This is the structural counterpart to `keepPrevious`/`commit`: where those hold a *value*
|
|
311
|
+
* through a reload, this holds a *structure* through a swap. The caller mounts the incoming
|
|
312
|
+
* structure off to the side (so its resources can settle and flip `ready`), keeps showing the
|
|
313
|
+
* held previous structure meanwhile, and lets the old one go once `ready` releases the swap.
|
|
314
|
+
*
|
|
315
|
+
* The very first value passes straight through (nothing to hold yet).
|
|
316
|
+
*/
|
|
317
|
+
function holdUntilReady(target, ready) {
|
|
318
|
+
return linkedSignal({
|
|
319
|
+
source: () => ({ t: target(), ready: ready() }),
|
|
320
|
+
computation: (curr, prev) => (prev === undefined || curr.ready ? curr.t : prev.value),
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Resolve a {@link PauseOption} into a pause predicate, or `null` meaning "do not pause".
|
|
326
|
+
* `null` tells the caller to return the bare primitive — no wrapper is created.
|
|
327
|
+
*
|
|
328
|
+
* - omitted/`true` → the ambient {@link PAUSED_CONTEXT} if an Activity boundary provides one (via
|
|
329
|
+
* `opt.injector` or the current injection context), else `null` (the bare primitive, no allocation).
|
|
330
|
+
* The default, because an explicit `pausable*` call wants to be pausable. An explicit `pause: true`
|
|
331
|
+
* with no boundary dev-warns; the omitted default stays quiet. SSR → `null`.
|
|
332
|
+
* - a function → returned as-is (covers `Signal<boolean>`; usable outside an injection context).
|
|
333
|
+
* SSR → `null` here too, detected via `opt.injector` if given, else a `globalThis.window` probe.
|
|
334
|
+
* - `false` → `null` (the explicit opt-out).
|
|
335
|
+
*
|
|
336
|
+
* Encapsulating this here keeps every pausable primitive's branching identical and in one place.
|
|
337
|
+
*/
|
|
338
|
+
function resolvePause(opt) {
|
|
339
|
+
const explicit = opt?.pause; // distinguish explicit `true` from the omitted default
|
|
340
|
+
const pause = explicit ?? true; // explicit pausable* calls default to pausing
|
|
341
|
+
if (pause === false)
|
|
342
|
+
return null;
|
|
343
|
+
const run = (fn) => opt?.injector ? runInInjectionContext(opt.injector, fn) : fn();
|
|
344
|
+
const onServer = () => typeof pause === 'function' && !opt?.injector
|
|
345
|
+
? typeof globalThis.window === 'undefined'
|
|
346
|
+
: run(() => isPlatformServer(inject(PLATFORM_ID, { optional: true }) ?? 'browser'));
|
|
347
|
+
if (typeof pause === 'function')
|
|
348
|
+
return onServer() ? null : pause;
|
|
349
|
+
if (onServer())
|
|
350
|
+
return null;
|
|
351
|
+
const paused = run(() => inject(PAUSED_CONTEXT, { optional: true }));
|
|
352
|
+
if (!paused) {
|
|
353
|
+
if (explicit === true && isDevMode())
|
|
354
|
+
console.warn('[pausable] `pause: true` but no PAUSED_CONTEXT in scope — not pausing. Provide one via an ' +
|
|
355
|
+
'Activity boundary (`MmActivity` / `providePaused`), or pass a predicate / `pause: false`.');
|
|
356
|
+
return null;
|
|
357
|
+
}
|
|
358
|
+
return paused;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Like {@link nestedEffect}, but pausable. While paused the effect does NOT run its body — and,
|
|
362
|
+
* crucially, it reads the pause predicate FIRST, so while paused its dependency set collapses to just
|
|
363
|
+
* the predicate (no churn from the real deps); on resume it re-runs and re-tracks. With no `pause`
|
|
364
|
+
* option it defaults to the ambient `PAUSED_CONTEXT`; `pause: false` makes it a plain `nestedEffect`
|
|
365
|
+
* with zero added overhead.
|
|
366
|
+
*/
|
|
367
|
+
function pausableEffect(effectFn, options) {
|
|
368
|
+
const paused = resolvePause(options);
|
|
369
|
+
if (!paused)
|
|
370
|
+
return nestedEffect(effectFn, options);
|
|
371
|
+
return nestedEffect((registerCleanup) => {
|
|
372
|
+
if (paused())
|
|
373
|
+
return; // read FIRST → while paused, deps collapse to just the predicate
|
|
374
|
+
effectFn(registerCleanup);
|
|
375
|
+
}, options);
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Like `signal`, but pausable. While paused, READS hold the last value; writes still land on the
|
|
379
|
+
* underlying signal and surface on resume. Built on the `keepPrevious`/`hold` shape — a
|
|
380
|
+
* `linkedSignal` gated on the pause predicate, with `set`/`update`/`asReadonly` forwarded to the
|
|
381
|
+
* source signal. With no `pause` option it defaults to the ambient `PAUSED_CONTEXT`; `pause: false`
|
|
382
|
+
* makes it a plain `signal` — no `linkedSignal` is created.
|
|
383
|
+
*
|
|
384
|
+
* NOTE: while paused, `set(x)` followed by a read returns the *held* (pre-pause) value, not `x` — the
|
|
385
|
+
* write lands on the source and surfaces on resume. That is the "freeze the displayed value while
|
|
386
|
+
* hidden" semantics; do not rely on read-after-write while paused.
|
|
387
|
+
*/
|
|
388
|
+
function pausableSignal(initialValue, options) {
|
|
389
|
+
const paused = resolvePause(options);
|
|
390
|
+
const src = signal(initialValue, options);
|
|
391
|
+
if (!paused)
|
|
392
|
+
return src;
|
|
393
|
+
const read = linkedSignal({ ...(ngDevMode ? { debugName: "read" } : /* istanbul ignore next */ {}), source: () => ({ v: src(), paused: paused() }),
|
|
394
|
+
computation: (curr, prev) => prev !== undefined && curr.paused ? prev.value : curr.v,
|
|
395
|
+
equal: options?.equal });
|
|
396
|
+
read.set = src.set;
|
|
397
|
+
read.update = src.update;
|
|
398
|
+
read.asReadonly = src.asReadonly;
|
|
399
|
+
return read;
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Like `computed`, but pausable. While paused it holds its last value AND does not recompute: the
|
|
403
|
+
* computation's dependencies are not read while paused, so a dependency change can't trigger work —
|
|
404
|
+
* on resume it recomputes and re-tracks. The very first read always computes, to seed a value. With
|
|
405
|
+
* no `pause` option it defaults to the ambient `PAUSED_CONTEXT`; `pause: false` makes it a plain
|
|
406
|
+
* `computed`.
|
|
407
|
+
*/
|
|
408
|
+
function pausableComputed(computation, options) {
|
|
409
|
+
const paused = resolvePause(options);
|
|
410
|
+
if (!paused)
|
|
411
|
+
return computed(computation, options);
|
|
412
|
+
const HELD = Symbol('paused-hold');
|
|
413
|
+
const ls = linkedSignal({ ...(ngDevMode ? { debugName: "ls" } : /* istanbul ignore next */ {}), source: () => (paused() ? HELD : computation()),
|
|
414
|
+
computation: (next, prev) => next !== HELD ? next : prev !== undefined ? prev.value : computation(),
|
|
415
|
+
equal: options?.equal });
|
|
416
|
+
return ls.asReadonly();
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const { is } = Object;
|
|
420
|
+
function mutable(initial, opt) {
|
|
421
|
+
const baseEqual = opt?.equal ?? is;
|
|
422
|
+
let cnt = 0;
|
|
423
|
+
const equal = (a, b) => {
|
|
424
|
+
if (cnt > 0)
|
|
425
|
+
return false;
|
|
426
|
+
return baseEqual(a, b);
|
|
427
|
+
};
|
|
428
|
+
const sig = signal(initial, {
|
|
429
|
+
...opt,
|
|
430
|
+
equal,
|
|
431
|
+
});
|
|
432
|
+
const internalUpdate = sig.update;
|
|
433
|
+
sig.mutate = (updater) => {
|
|
434
|
+
cnt++;
|
|
435
|
+
internalUpdate(updater);
|
|
436
|
+
cnt--;
|
|
437
|
+
};
|
|
438
|
+
sig.inline = (updater) => {
|
|
439
|
+
sig.mutate((prev) => {
|
|
440
|
+
updater(prev);
|
|
441
|
+
return prev;
|
|
442
|
+
});
|
|
443
|
+
};
|
|
444
|
+
return sig;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Type guard function to check if a given `WritableSignal` is a `MutableSignal`. This is useful
|
|
448
|
+
* for situations where you need to conditionally use the `mutate` or `inline` methods.
|
|
449
|
+
*
|
|
450
|
+
* @typeParam T - The type of the signal's value (optional, defaults to `any`).
|
|
451
|
+
* @param value - The `WritableSignal` to check.
|
|
452
|
+
* @returns `true` if the signal is a `MutableSignal`, `false` otherwise.
|
|
453
|
+
*
|
|
454
|
+
* @example
|
|
455
|
+
* const mySignal = signal(0);
|
|
456
|
+
* const myMutableSignal = mutable(0);
|
|
457
|
+
*
|
|
458
|
+
* if (isMutable(mySignal)) {
|
|
459
|
+
* mySignal.mutate(x => x + 1); // This would cause a type error, as mySignal is not a MutableSignal.
|
|
460
|
+
* }
|
|
461
|
+
*
|
|
462
|
+
* if (isMutable(myMutableSignal)) {
|
|
463
|
+
* myMutableSignal.mutate(x => x + 1); // This is safe.
|
|
464
|
+
* }
|
|
465
|
+
*/
|
|
466
|
+
function isMutable(value) {
|
|
467
|
+
return 'mutate' in value && typeof value.mutate === 'function';
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function createTransitionScope() {
|
|
471
|
+
const list = mutable([]);
|
|
472
|
+
const pending = computed(() => list().some(({ ref }) => {
|
|
473
|
+
const s = ref.status();
|
|
474
|
+
return s === 'loading' || s === 'reloading';
|
|
475
|
+
}), ...(ngDevMode ? [{ debugName: "pending" }] : /* istanbul ignore next */ []));
|
|
476
|
+
const holdCount = signal(0, ...(ngDevMode ? [{ debugName: "holdCount" }] : /* istanbul ignore next */ []));
|
|
477
|
+
const holding = computed(() => holdCount() > 0, ...(ngDevMode ? [{ debugName: "holding" }] : /* istanbul ignore next */ []));
|
|
478
|
+
return {
|
|
479
|
+
resources: computed(() => list().map((e) => e.ref)),
|
|
480
|
+
pending,
|
|
481
|
+
suspended: (type) => list().some(({ ref, suspends }) => suspends && (type === 'loading' ? ref.isLoading() : !ref.hasValue())),
|
|
482
|
+
add: (ref, opt) => untracked(() => list.inline((c) => c.push({ ref, suspends: opt?.suspends ?? true }))),
|
|
483
|
+
remove: (ref) => untracked(() => list.inline((c) => {
|
|
484
|
+
const i = c.findIndex((e) => e.ref === ref);
|
|
485
|
+
if (i !== -1)
|
|
486
|
+
c.splice(i, 1);
|
|
487
|
+
})),
|
|
488
|
+
commit: (value) => linkedSignal({
|
|
489
|
+
source: () => ({ v: value(), settled: !pending() }),
|
|
490
|
+
computation: (curr, prev) => curr.settled || prev === undefined ? curr.v : prev.value,
|
|
491
|
+
}),
|
|
492
|
+
holding,
|
|
493
|
+
beginHold: () => untracked(() => holdCount.update((c) => c + 1)),
|
|
494
|
+
endHold: () => untracked(() => holdCount.update((c) => (c > 0 ? c - 1 : 0))),
|
|
495
|
+
hold: (value) => linkedSignal({
|
|
496
|
+
source: () => ({ v: value(), held: holding() }),
|
|
497
|
+
computation: (curr, prev) => prev !== undefined && curr.held ? prev.value : curr.v,
|
|
498
|
+
}),
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
function createNoopScope() {
|
|
502
|
+
return {
|
|
503
|
+
resources: computed(() => []),
|
|
504
|
+
pending: computed(() => false),
|
|
505
|
+
suspended: () => false,
|
|
506
|
+
add: () => {
|
|
507
|
+
// noop
|
|
508
|
+
},
|
|
509
|
+
remove: () => {
|
|
510
|
+
// noop
|
|
511
|
+
},
|
|
512
|
+
commit: (value) => value,
|
|
513
|
+
holding: computed(() => false),
|
|
514
|
+
beginHold: () => {
|
|
515
|
+
// noop
|
|
516
|
+
},
|
|
517
|
+
endHold: () => {
|
|
518
|
+
// noop
|
|
519
|
+
},
|
|
520
|
+
hold: (value) => value,
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
const TRANSITION_SCOPE = new InjectionToken('@mmstack/resource:transition-scope');
|
|
524
|
+
/** Provide a fresh transition scope at a boundary so its subtree's resources are tracked independently. */
|
|
525
|
+
function provideTransitionScope() {
|
|
526
|
+
return { provide: TRANSITION_SCOPE, useFactory: createTransitionScope };
|
|
527
|
+
}
|
|
528
|
+
function injectTransitionScope() {
|
|
529
|
+
const scope = inject(TRANSITION_SCOPE, { optional: true });
|
|
530
|
+
if (!scope) {
|
|
531
|
+
if (isDevMode())
|
|
532
|
+
console.warn('[mmstack/resource] No transition scope in context — registration/tracking here is a no-op. ' +
|
|
533
|
+
'Use a <mm-suspense> boundary or provideTransitionScope() in an ancestor.');
|
|
534
|
+
return createNoopScope();
|
|
535
|
+
}
|
|
536
|
+
return scope;
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Returns a register function bound to the nearest transition scope: it adds a resource
|
|
540
|
+
* to the scope and removes it when the caller's injection context is destroyed. Pass any
|
|
541
|
+
* `ResourceRef` (a query, mutation, or plain Angular resource) through it.
|
|
542
|
+
*/
|
|
543
|
+
function injectRegisterResource() {
|
|
544
|
+
const scope = injectTransitionScope();
|
|
545
|
+
const destroyRef = inject(DestroyRef);
|
|
546
|
+
return (res, opt) => {
|
|
547
|
+
scope.add(res, opt);
|
|
548
|
+
destroyRef.onDestroy(() => scope.remove(res));
|
|
549
|
+
return res;
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
/** Convenience: register a resource with the nearest transition scope. Must run in an injection context. */
|
|
553
|
+
function registerResource(res, opt) {
|
|
554
|
+
return injectRegisterResource()(res, opt);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Returns a `startTransition(fn)` bound to the nearest transition scope. `fn` runs its state
|
|
559
|
+
* mutations (which commit immediately); any resource that reloads as a result holds its value
|
|
560
|
+
* (when `coordinate`/`commit`-wrapped) and reveals together once everything settles. The
|
|
561
|
+
* returned handle exposes a unified `pending` + `done` for the whole operation — for imperative
|
|
562
|
+
* coordination (disable a control, await completion) on top of the declarative hold-and-commit.
|
|
563
|
+
*
|
|
564
|
+
* Must be called in an injection context. This is the *async* generalization (Tier 2): it adds
|
|
565
|
+
* no rendering cost and needs no fork — holding direct/sync readers is a separate, deferred tier.
|
|
566
|
+
*/
|
|
567
|
+
function injectStartTransition() {
|
|
568
|
+
const scope = injectTransitionScope();
|
|
569
|
+
const injector = inject(Injector);
|
|
570
|
+
return (fn) => {
|
|
571
|
+
untracked(fn);
|
|
572
|
+
let sawPending = false;
|
|
573
|
+
const done = new Promise((resolve) => {
|
|
574
|
+
const watcher = effect(() => {
|
|
575
|
+
const p = scope.pending();
|
|
576
|
+
if (p)
|
|
577
|
+
sawPending = true;
|
|
578
|
+
// settle: requests went in flight and then drained
|
|
579
|
+
if (sawPending && !p) {
|
|
580
|
+
watcher.destroy();
|
|
581
|
+
resolve();
|
|
582
|
+
}
|
|
583
|
+
}, { ...(ngDevMode ? { debugName: "watcher" } : /* istanbul ignore next */ {}), injector });
|
|
584
|
+
// no-async fallback: once the reactive system has processed the writes (afterNextRender),
|
|
585
|
+
// if nothing ever went in flight, the transition is already complete.
|
|
586
|
+
afterNextRender(() => {
|
|
587
|
+
if (!sawPending && !untracked(scope.pending)) {
|
|
588
|
+
watcher.destroy();
|
|
589
|
+
resolve();
|
|
590
|
+
}
|
|
591
|
+
}, { injector });
|
|
592
|
+
});
|
|
593
|
+
return { pending: scope.pending, done };
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* Shared **suspense** (readiness) boundary behaviour: reads the *nearest* transition scope and exposes
|
|
599
|
+
* its `pending`/`suspended` state. This is the readiness gate — distinct from the hold-stale *swap*
|
|
600
|
+
* primitives (`TransitionRouterOutlet`, `ab-transition`), which are the actual "transitions". The two
|
|
601
|
+
* concrete components below differ only by whether they provide their own scope, so the logic (and
|
|
602
|
+
* template) live here once.
|
|
603
|
+
*
|
|
604
|
+
* - **First load** (`suspended()`): no value yet → show the `[placeholder]` fallback.
|
|
605
|
+
* - **Reload** (`pending()` but a value is held via `keepPrevious`): keep the real content mounted and
|
|
606
|
+
* surface a busy indicator (`aria-busy`, and an optional `[busy]` slot) instead of flashing back to
|
|
607
|
+
* the placeholder.
|
|
608
|
+
*
|
|
609
|
+
* `type` selects what "not ready" means: `'value'` (default) suspends only until a first value lands
|
|
610
|
+
* then holds through reloads; `'loading'` suspends on every in-flight load (strict suspense).
|
|
611
|
+
*/
|
|
612
|
+
class SuspenseBoundaryBase {
|
|
613
|
+
scope = injectTransitionScope();
|
|
614
|
+
/** What counts as "not ready" for the first-load placeholder. Defaults to value-presence. */
|
|
615
|
+
type = input('value', ...(ngDevMode ? [{ debugName: "type" }] : /* istanbul ignore next */ []));
|
|
616
|
+
pending = this.scope.pending;
|
|
617
|
+
suspended = computed(() => this.scope.suspended(this.type()), ...(ngDevMode ? [{ debugName: "suspended" }] : /* istanbul ignore next */ []));
|
|
618
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.12", ngImport: i0, type: SuspenseBoundaryBase, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
619
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.12", type: SuspenseBoundaryBase, isStandalone: true, inputs: { type: { classPropertyName: "type", publicName: "type", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0 });
|
|
620
|
+
}
|
|
621
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.12", ngImport: i0, type: SuspenseBoundaryBase, decorators: [{
|
|
622
|
+
type: Directive
|
|
623
|
+
}], propDecorators: { type: [{ type: i0.Input, args: [{ isSignal: true, alias: "type", required: false }] }] } });
|
|
624
|
+
const SUSPENSE_TEMPLATE = `
|
|
625
|
+
@if (suspended()) {
|
|
626
|
+
<ng-content select="[placeholder]"><span>Loading…</span></ng-content>
|
|
627
|
+
} @else {
|
|
628
|
+
@if (pending()) {
|
|
629
|
+
<ng-content select="[busy]" />
|
|
630
|
+
}
|
|
631
|
+
<ng-content />
|
|
632
|
+
}
|
|
633
|
+
`;
|
|
634
|
+
// `display: contents` so the boundary adds no box of its own.
|
|
635
|
+
const SUSPENSE_STYLES = `
|
|
636
|
+
:host {
|
|
637
|
+
display: contents;
|
|
638
|
+
}
|
|
639
|
+
`;
|
|
640
|
+
const SUSPENSE_HOST = {
|
|
641
|
+
'[attr.aria-busy]': 'pending() ? true : null',
|
|
642
|
+
};
|
|
643
|
+
/**
|
|
644
|
+
* Standalone suspense boundary — **provides its own scope**, so dropping a `<mm-suspense>` anywhere
|
|
645
|
+
* just works: the resources created in its subtree register into it without any extra
|
|
646
|
+
* `provideTransitionScope()`. The common case.
|
|
647
|
+
*/
|
|
648
|
+
class SuspenseBoundary extends SuspenseBoundaryBase {
|
|
649
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.12", ngImport: i0, type: SuspenseBoundary, deps: null, target: i0.ɵɵFactoryTarget.Component });
|
|
650
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.12", type: SuspenseBoundary, isStandalone: true, selector: "mm-suspense", host: { properties: { "attr.aria-busy": "pending() ? true : null" } }, providers: [provideTransitionScope()], usesInheritance: true, ngImport: i0, template: "\n @if (suspended()) {\n <ng-content select=\"[placeholder]\"><span>Loading\u2026</span></ng-content>\n } @else {\n @if (pending()) {\n <ng-content select=\"[busy]\" />\n }\n <ng-content />\n }\n", isInline: true, styles: [":host{display:contents}\n"] });
|
|
651
|
+
}
|
|
652
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.12", ngImport: i0, type: SuspenseBoundary, decorators: [{
|
|
653
|
+
type: Component,
|
|
654
|
+
args: [{ selector: 'mm-suspense', template: SUSPENSE_TEMPLATE, host: SUSPENSE_HOST, providers: [provideTransitionScope()], styles: [":host{display:contents}\n"] }]
|
|
655
|
+
}] });
|
|
656
|
+
/**
|
|
657
|
+
* Unscoped suspense boundary — **reads the ambient scope** instead of providing one. For cases where
|
|
658
|
+
* the resources to coordinate are registered *above* the boundary (e.g. an app-builder page whose
|
|
659
|
+
* manifests/connectors register at a higher injector), so the boundary observes that outer scope
|
|
660
|
+
* rather than opening a fresh one. Pair with a `provideTransitionScope()` (or another boundary) in an
|
|
661
|
+
* ancestor.
|
|
662
|
+
*/
|
|
663
|
+
class UnscopedSuspenseBoundary extends SuspenseBoundaryBase {
|
|
664
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.12", ngImport: i0, type: UnscopedSuspenseBoundary, deps: null, target: i0.ɵɵFactoryTarget.Component });
|
|
665
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.12", type: UnscopedSuspenseBoundary, isStandalone: true, selector: "mm-unscoped-suspense", host: { properties: { "attr.aria-busy": "pending() ? true : null" } }, usesInheritance: true, ngImport: i0, template: "\n @if (suspended()) {\n <ng-content select=\"[placeholder]\"><span>Loading\u2026</span></ng-content>\n } @else {\n @if (pending()) {\n <ng-content select=\"[busy]\" />\n }\n <ng-content />\n }\n", isInline: true, styles: [":host{display:contents}\n"] });
|
|
666
|
+
}
|
|
667
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.12", ngImport: i0, type: UnscopedSuspenseBoundary, decorators: [{
|
|
668
|
+
type: Component,
|
|
669
|
+
args: [{ selector: 'mm-unscoped-suspense', template: SUSPENSE_TEMPLATE, host: SUSPENSE_HOST, styles: [":host{display:contents}\n"] }]
|
|
670
|
+
}] });
|
|
671
|
+
|
|
672
|
+
function createTransaction() {
|
|
673
|
+
const log = new Map();
|
|
674
|
+
return {
|
|
675
|
+
record: (sig) => {
|
|
676
|
+
if (!log.has(sig))
|
|
677
|
+
log.set(sig, untracked(sig));
|
|
678
|
+
},
|
|
679
|
+
restore: () => untracked(() => {
|
|
680
|
+
for (const [sig, old] of log)
|
|
681
|
+
sig.set(old);
|
|
682
|
+
log.clear();
|
|
683
|
+
}),
|
|
684
|
+
clear: () => log.clear(),
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
// The currently-active transaction, set only for the synchronous duration of a `startTransaction`
|
|
688
|
+
// body (so stateful actions running inside it can record their writes). Module-level + sync
|
|
689
|
+
// set/reset is the honest shape: a transaction is call-scoped, not structural-per-injector.
|
|
690
|
+
let active = null;
|
|
691
|
+
/** The transaction in effect right now, or `null`. Stateful actions consult this to record undo. */
|
|
692
|
+
function activeTransaction() {
|
|
693
|
+
return active;
|
|
694
|
+
}
|
|
695
|
+
function runInTransaction(txn, fn) {
|
|
696
|
+
const prev = active;
|
|
697
|
+
active = txn;
|
|
698
|
+
try {
|
|
699
|
+
untracked(fn);
|
|
700
|
+
}
|
|
701
|
+
finally {
|
|
702
|
+
active = prev;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Returns a `startTransaction(fn)` bound to the nearest transition scope — the Tier 3 sibling of
|
|
707
|
+
* `injectStartTransition`. It HOLDS the scope's synchronous display reads from before `fn` runs
|
|
708
|
+
* (so a state write inside `fn` doesn't flash through), records those writes in an undo log, then:
|
|
709
|
+
* - on settle (the scope's resources go in flight and drain) → release the hold + keep the writes;
|
|
710
|
+
* - on `abort()` → roll the writes back and release the hold.
|
|
711
|
+
*
|
|
712
|
+
* The writes land on LIVE state immediately (so derived variables and connector requests see the
|
|
713
|
+
* new values and refetch); only the *display* is held, via `scope.hold`. Must run in an injection
|
|
714
|
+
* context.
|
|
715
|
+
*/
|
|
716
|
+
function injectStartTransaction() {
|
|
717
|
+
const scope = injectTransitionScope();
|
|
718
|
+
const injector = inject(Injector);
|
|
719
|
+
return (fn) => {
|
|
720
|
+
const txn = createTransaction();
|
|
721
|
+
// Hold BEFORE the writes, so the display freezes at pre-transaction values.
|
|
722
|
+
scope.beginHold();
|
|
723
|
+
let finished = false;
|
|
724
|
+
let watcher;
|
|
725
|
+
const finish = (restore) => {
|
|
726
|
+
if (finished)
|
|
727
|
+
return;
|
|
728
|
+
finished = true;
|
|
729
|
+
watcher?.destroy();
|
|
730
|
+
if (restore)
|
|
731
|
+
txn.restore();
|
|
732
|
+
else
|
|
733
|
+
txn.clear();
|
|
734
|
+
scope.endHold();
|
|
735
|
+
};
|
|
736
|
+
runInTransaction(txn, fn);
|
|
737
|
+
let sawPending = false;
|
|
738
|
+
const done = new Promise((resolve) => {
|
|
739
|
+
watcher = effect(() => {
|
|
740
|
+
const p = scope.pending();
|
|
741
|
+
if (p)
|
|
742
|
+
sawPending = true;
|
|
743
|
+
if (sawPending && !p) {
|
|
744
|
+
finish(false);
|
|
745
|
+
resolve();
|
|
746
|
+
}
|
|
747
|
+
}, { injector });
|
|
748
|
+
// no-async fallback: if nothing ever went in flight, settle once the writes are processed.
|
|
749
|
+
afterNextRender(() => {
|
|
750
|
+
if (!sawPending && !untracked(scope.pending)) {
|
|
751
|
+
finish(false);
|
|
752
|
+
resolve();
|
|
753
|
+
}
|
|
754
|
+
}, { injector });
|
|
755
|
+
});
|
|
756
|
+
return {
|
|
757
|
+
pending: scope.pending,
|
|
758
|
+
done,
|
|
759
|
+
abort: () => finish(true),
|
|
760
|
+
};
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
|
|
215
764
|
/**
|
|
216
765
|
* Converts a read-only `Signal` into a `WritableSignal` by providing custom `set` and, optionally, `update` functions.
|
|
217
766
|
* This can be useful for creating controlled write access to a signal that is otherwise read-only.
|
|
@@ -346,57 +895,6 @@ function debounce(source, opt) {
|
|
|
346
895
|
return writable;
|
|
347
896
|
}
|
|
348
897
|
|
|
349
|
-
const { is } = Object;
|
|
350
|
-
function mutable(initial, opt) {
|
|
351
|
-
const baseEqual = opt?.equal ?? is;
|
|
352
|
-
let cnt = 0;
|
|
353
|
-
const equal = (a, b) => {
|
|
354
|
-
if (cnt > 0)
|
|
355
|
-
return false;
|
|
356
|
-
return baseEqual(a, b);
|
|
357
|
-
};
|
|
358
|
-
const sig = signal(initial, {
|
|
359
|
-
...opt,
|
|
360
|
-
equal,
|
|
361
|
-
});
|
|
362
|
-
const internalUpdate = sig.update;
|
|
363
|
-
sig.mutate = (updater) => {
|
|
364
|
-
cnt++;
|
|
365
|
-
internalUpdate(updater);
|
|
366
|
-
cnt--;
|
|
367
|
-
};
|
|
368
|
-
sig.inline = (updater) => {
|
|
369
|
-
sig.mutate((prev) => {
|
|
370
|
-
updater(prev);
|
|
371
|
-
return prev;
|
|
372
|
-
});
|
|
373
|
-
};
|
|
374
|
-
return sig;
|
|
375
|
-
}
|
|
376
|
-
/**
|
|
377
|
-
* Type guard function to check if a given `WritableSignal` is a `MutableSignal`. This is useful
|
|
378
|
-
* for situations where you need to conditionally use the `mutate` or `inline` methods.
|
|
379
|
-
*
|
|
380
|
-
* @typeParam T - The type of the signal's value (optional, defaults to `any`).
|
|
381
|
-
* @param value - The `WritableSignal` to check.
|
|
382
|
-
* @returns `true` if the signal is a `MutableSignal`, `false` otherwise.
|
|
383
|
-
*
|
|
384
|
-
* @example
|
|
385
|
-
* const mySignal = signal(0);
|
|
386
|
-
* const myMutableSignal = mutable(0);
|
|
387
|
-
*
|
|
388
|
-
* if (isMutable(mySignal)) {
|
|
389
|
-
* mySignal.mutate(x => x + 1); // This would cause a type error, as mySignal is not a MutableSignal.
|
|
390
|
-
* }
|
|
391
|
-
*
|
|
392
|
-
* if (isMutable(myMutableSignal)) {
|
|
393
|
-
* myMutableSignal.mutate(x => x + 1); // This is safe.
|
|
394
|
-
* }
|
|
395
|
-
*/
|
|
396
|
-
function isMutable(value) {
|
|
397
|
-
return 'mutate' in value && typeof value.mutate === 'function';
|
|
398
|
-
}
|
|
399
|
-
|
|
400
898
|
/**
|
|
401
899
|
* @internal
|
|
402
900
|
* Type guard for an array-index-like property key: a non-empty string that parses to a finite
|
|
@@ -620,8 +1118,27 @@ function isDerivation(sig) {
|
|
|
620
1118
|
return 'from' in sig;
|
|
621
1119
|
}
|
|
622
1120
|
|
|
623
|
-
function
|
|
624
|
-
|
|
1121
|
+
function keepPrevious(src, opt) {
|
|
1122
|
+
const persisted = linkedSignal({ ...(ngDevMode ? { debugName: "persisted" } : /* istanbul ignore next */ {}), ...opt,
|
|
1123
|
+
source: () => src(),
|
|
1124
|
+
computation: (next, prev) => next === undefined && prev !== undefined ? prev.value : next });
|
|
1125
|
+
if (isWritableSignal$2(src)) {
|
|
1126
|
+
persisted.set = src.set;
|
|
1127
|
+
persisted.update = src.update;
|
|
1128
|
+
persisted.asReadonly = src.asReadonly;
|
|
1129
|
+
if (isMutable(src)) {
|
|
1130
|
+
persisted.mutate = src.mutate;
|
|
1131
|
+
persisted.inline = src.inline;
|
|
1132
|
+
}
|
|
1133
|
+
if (isDerivation(src)) {
|
|
1134
|
+
persisted.from = src.from;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
return persisted;
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
function isWritableSignal$1(value) {
|
|
1141
|
+
return isWritableSignal$2(value);
|
|
625
1142
|
}
|
|
626
1143
|
/**
|
|
627
1144
|
* @internal
|
|
@@ -630,7 +1147,7 @@ function isWritableSignal(value) {
|
|
|
630
1147
|
* @returns
|
|
631
1148
|
*/
|
|
632
1149
|
function createSetter(source) {
|
|
633
|
-
if (!isWritableSignal(source))
|
|
1150
|
+
if (!isWritableSignal$1(source))
|
|
634
1151
|
return () => {
|
|
635
1152
|
// noop;
|
|
636
1153
|
};
|
|
@@ -663,12 +1180,12 @@ function indexArray(source, map, opt = {}) {
|
|
|
663
1180
|
const data = isSignal(source) ? source : computed(source);
|
|
664
1181
|
const len = computed(() => data().length, ...(ngDevMode ? [{ debugName: "len" }] : /* istanbul ignore next */ []));
|
|
665
1182
|
const setter = createSetter(data);
|
|
666
|
-
const writableData = isWritableSignal(data)
|
|
1183
|
+
const writableData = isWritableSignal$1(data)
|
|
667
1184
|
? data
|
|
668
1185
|
: toWritable(data, () => {
|
|
669
1186
|
// noop
|
|
670
1187
|
});
|
|
671
|
-
if (isWritableSignal(data) && isMutable(data) && !opt.equal) {
|
|
1188
|
+
if (isWritableSignal$1(data) && isMutable(data) && !opt.equal) {
|
|
672
1189
|
opt.equal = (a, b) => {
|
|
673
1190
|
if (typeof a !== typeof b)
|
|
674
1191
|
return false;
|
|
@@ -878,7 +1395,7 @@ function pooledKeys(src) {
|
|
|
878
1395
|
}
|
|
879
1396
|
function mapObject(source, mapFn, options = {}) {
|
|
880
1397
|
const src = isSignal(source) ? source : computed(source);
|
|
881
|
-
const writable = (isWritableSignal(src)
|
|
1398
|
+
const writable = (isWritableSignal$1(src)
|
|
882
1399
|
? src
|
|
883
1400
|
: toWritable(src, () => {
|
|
884
1401
|
// noop
|
|
@@ -2399,6 +2916,9 @@ function signalFromEvent(target, eventName, initial, projectOrOpt, maybeOpt) {
|
|
|
2399
2916
|
return untracked(() => state.asReadonly());
|
|
2400
2917
|
}
|
|
2401
2918
|
|
|
2919
|
+
function isWritableSignal(value) {
|
|
2920
|
+
return isWritableSignal$2(value);
|
|
2921
|
+
}
|
|
2402
2922
|
/**
|
|
2403
2923
|
* Runtime marker + compile-time brand for an opaque value. A `const`-declared `Symbol`
|
|
2404
2924
|
* has a `unique symbol` type, so the same symbol serves as both the property key written
|
|
@@ -2440,6 +2960,82 @@ function isOpaque(value) {
|
|
|
2440
2960
|
value !== null &&
|
|
2441
2961
|
value[OPAQUE] === true);
|
|
2442
2962
|
}
|
|
2963
|
+
/**
|
|
2964
|
+
* @internal Runtime brand carrying a store node's lazily-built leaf probe. Exported (like
|
|
2965
|
+
* {@link OPAQUE}) only so the `{ readonly [LEAF]: () => boolean }` brand on the store types is
|
|
2966
|
+
* nameable in the emitted declarations — not part of the supported surface; use {@link isLeaf}.
|
|
2967
|
+
*/
|
|
2968
|
+
const LEAF = Symbol('@mmstack/primitives::store/LEAF');
|
|
2969
|
+
/**
|
|
2970
|
+
* @internal Whether a value is a terminal leaf: a concrete non-record/non-array value always is;
|
|
2971
|
+
* `null`/`undefined` is a leaf only when vivification is disabled (with vivify on it can still
|
|
2972
|
+
* materialize a container, so it stays a descendable substore).
|
|
2973
|
+
*/
|
|
2974
|
+
function isLeafValue(value, vivifyEnabled) {
|
|
2975
|
+
if (value == null)
|
|
2976
|
+
return !vivifyEnabled;
|
|
2977
|
+
if (isOpaque(value))
|
|
2978
|
+
return true; // opaque always wins — even arrays
|
|
2979
|
+
return !Array.isArray(value) && !isRecord(value);
|
|
2980
|
+
}
|
|
2981
|
+
/**
|
|
2982
|
+
* @internal Constant leaf probes for nodes whose leaf-ness is statically known, so the reactive
|
|
2983
|
+
* `computed` can be skipped entirely.
|
|
2984
|
+
*/
|
|
2985
|
+
function alwaysTrue() {
|
|
2986
|
+
return true;
|
|
2987
|
+
}
|
|
2988
|
+
function alwaysFalse() {
|
|
2989
|
+
return false;
|
|
2990
|
+
}
|
|
2991
|
+
/**
|
|
2992
|
+
* @internal Attaches a lazy, memoized leaf probe to a store node. The probe (`() => boolean`)
|
|
2993
|
+
* closes over the node's value signal and its (stable) vivify setting, building the backing
|
|
2994
|
+
* `computed` on first call so leaf-ness tracks the live value reactively without taxing every
|
|
2995
|
+
* node access. Idempotent.
|
|
2996
|
+
*/
|
|
2997
|
+
function markAsLeaf(sig, value, vivifyEnabled, noUnionLeaves) {
|
|
2998
|
+
if (typeof sig[LEAF] !== 'function') {
|
|
2999
|
+
let memo;
|
|
3000
|
+
const probe = () => {
|
|
3001
|
+
if (memo)
|
|
3002
|
+
return memo();
|
|
3003
|
+
const v = untracked(value);
|
|
3004
|
+
memo =
|
|
3005
|
+
isOpaque(v) || (v == null && !vivifyEnabled) || noUnionLeaves
|
|
3006
|
+
? isLeafValue(v, vivifyEnabled)
|
|
3007
|
+
? alwaysTrue
|
|
3008
|
+
: alwaysFalse
|
|
3009
|
+
: computed(() => isLeafValue(value(), vivifyEnabled));
|
|
3010
|
+
return memo();
|
|
3011
|
+
};
|
|
3012
|
+
Object.defineProperty(sig, LEAF, {
|
|
3013
|
+
value: probe,
|
|
3014
|
+
enumerable: false,
|
|
3015
|
+
configurable: true,
|
|
3016
|
+
});
|
|
3017
|
+
}
|
|
3018
|
+
return sig;
|
|
3019
|
+
}
|
|
3020
|
+
/**
|
|
3021
|
+
* Reports whether a store node is currently a **leaf** — a terminal value the store does not
|
|
3022
|
+
* descend into (a primitive, `Date`, `RegExp`, {@link opaque} object, class instance, or a
|
|
3023
|
+
* `null`/`undefined` hole when vivification is off) rather than a record/array substore.
|
|
3024
|
+
*
|
|
3025
|
+
* Leaf-ness reflects the node's **live** value: the probe is reactive and memoized, so calling
|
|
3026
|
+
* `isLeaf` inside a `computed`/`effect` re-evaluates when the node's shape changes.
|
|
3027
|
+
*
|
|
3028
|
+
* @internal Exposed for advanced/niche interop only — not part of the supported public surface
|
|
3029
|
+
* and may change without a major version bump.
|
|
3030
|
+
*
|
|
3031
|
+
* @example
|
|
3032
|
+
* const s = store({ name: 'Ada', address: { city: 'London' } });
|
|
3033
|
+
* isLeaf(s.name); // true
|
|
3034
|
+
* isLeaf(s.address); // false — a substore
|
|
3035
|
+
*/
|
|
3036
|
+
function isLeaf(value) {
|
|
3037
|
+
return isStore(value) && value[LEAF]?.() === true;
|
|
3038
|
+
}
|
|
2443
3039
|
const IS_STORE = Symbol('@mmstack/primitives::store/IS_STORE');
|
|
2444
3040
|
const SCOPE_PARENT = Symbol('@mmstack/primitives::store/SCOPE_PARENT');
|
|
2445
3041
|
/**
|
|
@@ -2502,7 +3098,7 @@ function hasOwnKey(value, key) {
|
|
|
2502
3098
|
* @internal
|
|
2503
3099
|
* Makes an array store
|
|
2504
3100
|
*/
|
|
2505
|
-
function toArrayStore(source, injector, vivify) {
|
|
3101
|
+
function toArrayStore(source, injector, vivify, noUnionLeaves = false) {
|
|
2506
3102
|
if (isStore(source))
|
|
2507
3103
|
return source;
|
|
2508
3104
|
const isMutableSource = isMutable(source);
|
|
@@ -2612,9 +3208,10 @@ function toArrayStore(source, injector, vivify) {
|
|
|
2612
3208
|
});
|
|
2613
3209
|
const childSample = untracked(computation);
|
|
2614
3210
|
const childVivify = resolveVivify(childSample, vivify);
|
|
2615
|
-
const proxy = Array.isArray(childSample)
|
|
2616
|
-
? toArrayStore(computation, injector, childVivify)
|
|
2617
|
-
: toStore(computation, injector, childVivify);
|
|
3211
|
+
const proxy = Array.isArray(childSample) && !isOpaque(childSample)
|
|
3212
|
+
? toArrayStore(computation, injector, childVivify, noUnionLeaves)
|
|
3213
|
+
: toStore(computation, injector, childVivify, noUnionLeaves);
|
|
3214
|
+
markAsLeaf(proxy, computation, childVivify !== false, noUnionLeaves);
|
|
2618
3215
|
const ref = new WeakRef(proxy);
|
|
2619
3216
|
storeCache.set(idx, ref);
|
|
2620
3217
|
PROXY_CLEANUP.register(proxy, { target, prop: idx }, ref);
|
|
@@ -2631,7 +3228,7 @@ function toArrayStore(source, injector, vivify) {
|
|
|
2631
3228
|
* const state = store({ user: { name: 'John' } });
|
|
2632
3229
|
* const nameSignal = state.user.name; // WritableSignal<string>
|
|
2633
3230
|
*/
|
|
2634
|
-
function toStore(source, injector, vivify = false) {
|
|
3231
|
+
function toStore(source, injector, vivify = false, noUnionLeaves = false) {
|
|
2635
3232
|
if (isStore(source))
|
|
2636
3233
|
return source;
|
|
2637
3234
|
if (!injector)
|
|
@@ -2672,7 +3269,7 @@ function toStore(source, injector, vivify = false) {
|
|
|
2672
3269
|
return () => {
|
|
2673
3270
|
if (!isWritableSource)
|
|
2674
3271
|
return s;
|
|
2675
|
-
return untracked(() => toStore(source.asReadonly(), injector, vivify));
|
|
3272
|
+
return untracked(() => toStore(source.asReadonly(), injector, vivify, noUnionLeaves));
|
|
2676
3273
|
};
|
|
2677
3274
|
if (prop === 'extend')
|
|
2678
3275
|
return (seed) => scopedStore(s, seed, isMutableSource
|
|
@@ -2725,9 +3322,10 @@ function toStore(source, injector, vivify = false) {
|
|
|
2725
3322
|
});
|
|
2726
3323
|
const childSample = untracked(computation);
|
|
2727
3324
|
const childVivify = resolveVivify(childSample, vivify);
|
|
2728
|
-
const proxy = Array.isArray(childSample)
|
|
2729
|
-
? toArrayStore(computation, injector, childVivify)
|
|
2730
|
-
: toStore(computation, injector, childVivify);
|
|
3325
|
+
const proxy = Array.isArray(childSample) && !isOpaque(childSample)
|
|
3326
|
+
? toArrayStore(computation, injector, childVivify, noUnionLeaves)
|
|
3327
|
+
: toStore(computation, injector, childVivify, noUnionLeaves);
|
|
3328
|
+
markAsLeaf(proxy, computation, childVivify !== false, noUnionLeaves);
|
|
2731
3329
|
const ref = new WeakRef(proxy);
|
|
2732
3330
|
storeCache.set(prop, ref);
|
|
2733
3331
|
PROXY_CLEANUP.register(proxy, { target, prop }, ref);
|
|
@@ -2771,7 +3369,9 @@ function scopedStore(parent, seed, kind, injector) {
|
|
|
2771
3369
|
layer[key].set(next[key]);
|
|
2772
3370
|
}
|
|
2773
3371
|
};
|
|
2774
|
-
const base = toWritable(view, kind === 'readonly' ? () => undefined : splitSet, undefined, {
|
|
3372
|
+
const base = toWritable(view, kind === 'readonly' ? () => undefined : splitSet, undefined, {
|
|
3373
|
+
pure: false,
|
|
3374
|
+
});
|
|
2775
3375
|
if (kind === 'mutable') {
|
|
2776
3376
|
base.mutate = (updater) => splitSet(updater(untracked(view)));
|
|
2777
3377
|
base.inline = (updater) => base.mutate((prev) => {
|
|
@@ -2820,14 +3420,76 @@ function scopedStore(parent, seed, kind, injector) {
|
|
|
2820
3420
|
* @see {@link toStore}
|
|
2821
3421
|
*/
|
|
2822
3422
|
function store(value, opt) {
|
|
2823
|
-
return toStore(signal(value, opt), opt?.injector, opt?.vivify ?? false);
|
|
3423
|
+
return toStore(signal(value, opt), opt?.injector, opt?.vivify ?? false, opt?.noUnionLeaves ?? false);
|
|
2824
3424
|
}
|
|
2825
3425
|
/**
|
|
2826
3426
|
* Creates a MutableSignalStore from a value.
|
|
2827
3427
|
* @see {@link toStore}
|
|
2828
3428
|
*/
|
|
2829
3429
|
function mutableStore(value, opt) {
|
|
2830
|
-
return toStore(mutable(value, opt), opt?.injector, opt?.vivify ?? false);
|
|
3430
|
+
return toStore(mutable(value, opt), opt?.injector, opt?.vivify ?? false, opt?.noUnionLeaves ?? false);
|
|
3431
|
+
}
|
|
3432
|
+
|
|
3433
|
+
function isPlainRecord(value) {
|
|
3434
|
+
if (value === null || typeof value !== 'object')
|
|
3435
|
+
return false;
|
|
3436
|
+
const proto = Object.getPrototypeOf(value);
|
|
3437
|
+
return proto === Object.prototype || proto === null;
|
|
3438
|
+
}
|
|
3439
|
+
/**
|
|
3440
|
+
* Per-path 3-way merge. Reference-equality short-circuits do the work: a subtree the fork never
|
|
3441
|
+
* touched satisfies `mine === ancestor` (structural sharing keeps its identity) → take the live
|
|
3442
|
+
* base; a subtree the base never changed satisfies `theirs === ancestor` → keep the fork's. So it
|
|
3443
|
+
* only deep-walks paths that BOTH sides changed, and on a leaf/array conflict the fork wins.
|
|
3444
|
+
* Arrays are treated atomically (no positional merge — index shifts make that unsafe); supply a
|
|
3445
|
+
* {@link ReconcileFn} for array-aware merging.
|
|
3446
|
+
*
|
|
3447
|
+
* CONTRACT: "unchanged" is detected by REFERENCE identity, not deep equality. `mine` must be a
|
|
3448
|
+
* copy-on-write derivative of `ancestor` — i.e. untouched nodes keep their reference — which the
|
|
3449
|
+
* fork guarantees because writes flow through `toStore` (it rebuilds only the edited path and
|
|
3450
|
+
* shares everything else). Feed it a structurally-equal-but-fresh-reference node for an untouched
|
|
3451
|
+
* path and it will treat that node as edited (recursion/leaf-value checks usually still reconcile,
|
|
3452
|
+
* but a fresh-ref clean node vs a base type-change resolves to the fork's stale value). Primitive
|
|
3453
|
+
* leaves compare by value, so equal primitives are correctly seen as unchanged.
|
|
3454
|
+
*/
|
|
3455
|
+
function merge3(ancestor, mine, theirs) {
|
|
3456
|
+
if (Object.is(mine, theirs) || Object.is(mine, ancestor))
|
|
3457
|
+
return theirs; // unedited → live base
|
|
3458
|
+
if (Object.is(theirs, ancestor))
|
|
3459
|
+
return mine; // base unchanged here → keep the fork's edit
|
|
3460
|
+
if (isPlainRecord(mine) && isPlainRecord(theirs) && isPlainRecord(ancestor)) {
|
|
3461
|
+
const out = { ...theirs };
|
|
3462
|
+
for (const key of new Set([...Object.keys(mine), ...Object.keys(theirs)])) {
|
|
3463
|
+
out[key] = merge3(ancestor[key], mine[key], theirs[key]);
|
|
3464
|
+
}
|
|
3465
|
+
return out;
|
|
3466
|
+
}
|
|
3467
|
+
return mine; // leaf / array / type-mismatch conflict → local wins
|
|
3468
|
+
}
|
|
3469
|
+
function forkStore(base, opt) {
|
|
3470
|
+
// A mutable base mutates in place, so its value reference is stable across changes — which defeats merge3's identity-based change detection
|
|
3471
|
+
const mutableBase = typeof base.mutate === 'function';
|
|
3472
|
+
let strategy = opt?.strategy ?? (mutableBase ? 'coarse' : 'fine');
|
|
3473
|
+
if (mutableBase && strategy === 'fine') {
|
|
3474
|
+
if (isDevMode())
|
|
3475
|
+
console.warn("[fork] strategy 'fine' relies on reference-identity change detection, but the base is a " +
|
|
3476
|
+
"mutable store (in-place mutation keeps the same reference) — falling back to 'coarse'.");
|
|
3477
|
+
strategy = 'coarse';
|
|
3478
|
+
}
|
|
3479
|
+
const reconcile = strategy === 'coarse'
|
|
3480
|
+
? (_ancestor, _mine, theirs) => theirs // re-link to the new base (whole-value reset)
|
|
3481
|
+
: strategy === 'fine'
|
|
3482
|
+
? merge3
|
|
3483
|
+
: strategy;
|
|
3484
|
+
const merge = reconcile;
|
|
3485
|
+
const staged = linkedSignal({ ...(ngDevMode ? { debugName: "staged" } : /* istanbul ignore next */ {}), source: () => base(),
|
|
3486
|
+
computation: (theirs, prev) => prev === undefined ? theirs : merge(prev.source, prev.value, theirs) });
|
|
3487
|
+
const store = toStore(staged, opt?.injector, opt?.vivify, opt?.noUnionLeaves);
|
|
3488
|
+
return {
|
|
3489
|
+
store,
|
|
3490
|
+
commit: () => base.set(untracked(staged)),
|
|
3491
|
+
discard: () => staged.set(untracked(base)),
|
|
3492
|
+
};
|
|
2831
3493
|
}
|
|
2832
3494
|
|
|
2833
3495
|
// Internal dummy store for server-side rendering
|
|
@@ -3304,5 +3966,5 @@ function withHistory(sourceOrValue, opt) {
|
|
|
3304
3966
|
* Generated bundle index. Do not edit.
|
|
3305
3967
|
*/
|
|
3306
3968
|
|
|
3307
|
-
export { batteryStatus, chunked, clipboard, combineWith, debounce, debounced, derived, distinct, elementSize, elementVisibility, filter, filterWith, focusWithin, geolocation, idle, indexArray, isDerivation, isMutable, isOpaque, isStore, keyArray, map, mapArray, mapObject, mediaQuery, mousePosition, mutable, mutableStore, nestedEffect, networkStatus, opaque, orientation, pageVisibility, pairwise, pipeable, piped, pooled, pooledArray, pooledMap, pooledSet, prefersDarkMode, prefersReducedMotion, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, stored, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, until, windowSize, withHistory };
|
|
3969
|
+
export { MmActivity, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, batteryStatus, chunked, clipboard, combineWith, createTransaction, createTransitionScope, debounce, debounced, derived, distinct, elementSize, elementVisibility, filter, filterWith, focusWithin, forkStore, geolocation, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, isDerivation, isLeaf, isMutable, isOpaque, isStore, keepPrevious, keyArray, map, mapArray, mapObject, mediaQuery, merge3, mousePosition, mutable, mutableStore, nestedEffect, networkStatus, opaque, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, pipeable, piped, pooled, pooledArray, pooledMap, pooledSet, prefersDarkMode, prefersReducedMotion, providePaused, provideTransitionScope, registerResource, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, stored, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, until, windowSize, withHistory };
|
|
3308
3970
|
//# sourceMappingURL=mmstack-primitives.mjs.map
|