@mmstack/primitives 22.8.3 → 22.9.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.
@@ -2041,7 +2041,9 @@ function effectiveKeys(arr, getKey, report) {
2041
2041
  * when the list is reordered.
2042
2042
  *
2043
2043
  * @param source A `Signal<T[]>` or a function returning `T[]`.
2044
- * @param mapFn The mapping function. Receives the item and its index as a Signal.
2044
+ * @param mapFn The mapping function. Receives the item, its index as a Signal, and the
2045
+ * entry's key (the effective ordinal key when `duplicateKeys` is enabled, otherwise
2046
+ * the raw key) — stable for the lifetime of the mapped entry.
2045
2047
  * @param options Optional configuration:
2046
2048
  * - `onDestroy`: A callback invoked when a mapped item is removed from the array.
2047
2049
  * - `key`: A custom key extractor for identity matching (e.g. `(item) => item.id`)
@@ -2119,7 +2121,7 @@ function keyArray(source, mapFn, options = {}) {
2119
2121
  const indexSignal = signal(j, /* @ts-ignore */
2120
2122
  ...(ngDevMode ? [{ debugName: "indexSignal" }] : /* istanbul ignore next */ []));
2121
2123
  newIndexes[j] = indexSignal;
2122
- newMapped[j] = mapFn(item, indexSignal);
2124
+ newMapped[j] = mapFn(item, indexSignal, newKeys ? newKeys[j] : getKey(item));
2123
2125
  }
2124
2126
  }
2125
2127
  else {
@@ -2173,7 +2175,7 @@ function keyArray(source, mapFn, options = {}) {
2173
2175
  const indexSignal = signal(j, /* @ts-ignore */
2174
2176
  ...(ngDevMode ? [{ debugName: "indexSignal" }] : /* istanbul ignore next */ []));
2175
2177
  newIndexes[j] = indexSignal;
2176
- newMapped[j] = mapFn(newItems[j], indexSignal);
2178
+ newMapped[j] = mapFn(newItems[j], indexSignal, kNew(j));
2177
2179
  }
2178
2180
  }
2179
2181
  items.length = newLen;
@@ -6865,6 +6867,9 @@ function stored(fallback, { key, store: providedStore, serialize = JSON.stringif
6865
6867
  writable.key = keySig;
6866
6868
  return writable;
6867
6869
  }
6870
+ function isStored(value) {
6871
+ return 'clear' in value && typeof value.clear === 'function' && 'key' in value;
6872
+ }
6868
6873
 
6869
6874
  /** Op-mode sync for a writable store: hello exchange, then live envelopes. */
6870
6875
  function storeTabSync(sig, opt, bus, injector) {
@@ -7102,6 +7107,125 @@ function tabSync(sig, opt) {
7102
7107
  return sig;
7103
7108
  }
7104
7109
 
7110
+ /**
7111
+ * Wraps any member of the writable-signal family so that every synchronous write
7112
+ * first records an ambient "cause" (via the caller-provided `capture` function)
7113
+ * and then delegates to the original write, preserving the wrapped signal's exact
7114
+ * write semantics. The recorded cause is exposed through a plain {@link Traced.causedBy}
7115
+ * read, letting a downstream consumer attribute a change to whatever caused it —
7116
+ * without any dependency on a particular telemetry system.
7117
+ *
7118
+ * Capture is **synchronous-only** and last-writer-wins: the cause is whatever
7119
+ * `capture()` returns during the `set`/`update`/`mutate`/`inline` call. A write
7120
+ * performed after an `await` (once the ambient cause has been cleared) records
7121
+ * `undefined`; a write while `capture()` returns `undefined` clears the cause.
7122
+ * `causedBy()` is a plain read, not a signal — reading it never subscribes, and
7123
+ * a cause-only change (a write with a different cause but no dependent-visible
7124
+ * value change) never invalidates a consumer.
7125
+ *
7126
+ * The traced twin behaves like the original except for `causedBy`: it carries the
7127
+ * wrapped signal's surface — `asReadonly`, the `mutate`/`inline` methods of a
7128
+ * mutable, and the `from` of a derived — and the underlying write semantics survive
7129
+ * (a traced `derived` still writes through to its source; a traced `toWritable` still
7130
+ * runs its custom `set`). Reads through the twin stay tracked — consumers subscribe
7131
+ * exactly as they would to the source.
7132
+ *
7133
+ * @typeParam S - The wrapped writable-signal type.
7134
+ * @typeParam C - The type of the captured cause.
7135
+ *
7136
+ * @param sig - The writable signal to trace. Any family member is accepted
7137
+ * (`signal`, `mutable`, `derived`, `toWritable`, `stored`, ...).
7138
+ * @param capture - A function invoked synchronously at the start of every write.
7139
+ * Its return value becomes the current cause; returning `undefined`
7140
+ * clears it.
7141
+ * @param opt - Optional configuration.
7142
+ * @param opt.pure - If `true` (the default), the returned twin is a **new** signal
7143
+ * that reads through to `sig`; `sig` itself is left untouched, so
7144
+ * tracing a shared signal never makes the original writable or
7145
+ * alters its behaviour.
7146
+ *
7147
+ * CAUTION: with `pure: false` the write methods are patched
7148
+ * directly onto the `sig` object you passed in — every other
7149
+ * holder of that signal now records causes on write. Only use it
7150
+ * with a signal you created and own exclusively.
7151
+ *
7152
+ * @returns A {@link Traced} twin of `sig` exposing `causedBy()`.
7153
+ *
7154
+ * @example
7155
+ * // A refetch attributing itself to whatever wrote the query.
7156
+ * let activeCause: string | undefined;
7157
+ * const query = traced(signal(''), () => activeCause);
7158
+ *
7159
+ * activeCause = 'user-typed';
7160
+ * query.set('hello');
7161
+ * query.causedBy(); // 'user-typed'
7162
+ *
7163
+ * @example
7164
+ * // Tracing a shared, read-only-exposed signal without making it writable.
7165
+ * const shared = signal(0);
7166
+ * const twin = traced(shared, () => currentInteraction());
7167
+ * twin === shared; // false — the original is untouched
7168
+ */
7169
+ function traced(sig, capture, opt) {
7170
+ const twin = (opt?.pure === false ? sig : facadeOf(sig));
7171
+ let cause;
7172
+ const setOriginal = sig.set.bind(sig);
7173
+ twin.set = (value) => {
7174
+ cause = capture();
7175
+ setOriginal(value);
7176
+ };
7177
+ const updateOriginal = sig.update.bind(sig);
7178
+ twin.update = (updater) => {
7179
+ cause = capture();
7180
+ updateOriginal(updater);
7181
+ };
7182
+ if (isMutable(sig)) {
7183
+ const source = sig;
7184
+ const mutableTwin = twin;
7185
+ const mutateOriginal = source.mutate.bind(source);
7186
+ mutableTwin.mutate = (updater) => {
7187
+ cause = capture();
7188
+ mutateOriginal(updater);
7189
+ };
7190
+ const inlineOriginal = source.inline.bind(source);
7191
+ mutableTwin.inline = (updater) => {
7192
+ cause = capture();
7193
+ inlineOriginal(updater);
7194
+ };
7195
+ }
7196
+ if (isStored(sig)) {
7197
+ const source = sig;
7198
+ const storedTwin = twin;
7199
+ const clearOriginal = source.clear.bind(source);
7200
+ storedTwin.clear = () => {
7201
+ cause = capture();
7202
+ clearOriginal();
7203
+ };
7204
+ }
7205
+ twin.causedBy = () => cause;
7206
+ return twin;
7207
+ }
7208
+ /**
7209
+ * Builds a read-through facade over `sig`: a fresh signal whose reads track `sig`,
7210
+ * carrying `sig`'s non-write surface (`asReadonly`, and `from` on a derived signal)
7211
+ * by explicit delegation. The write methods are attached by {@link traced}. The
7212
+ * facade's `equal` always reports "changed", so it forwards every notification `sig`
7213
+ * emits — including the same-reference `mutate`/`inline` force-notifies that a default
7214
+ * `computed` would swallow (see `mutable`'s docs). The change decision is thereby
7215
+ * delegated entirely to `sig`.
7216
+ */
7217
+ function facadeOf(sig) {
7218
+ const facade = computed(sig, { equal: () => false });
7219
+ facade.asReadonly = sig.asReadonly.bind(sig);
7220
+ if (isDerivation(sig)) {
7221
+ facade.from = sig.from;
7222
+ }
7223
+ if (isStored(sig)) {
7224
+ facade.key = sig.key;
7225
+ }
7226
+ return facade;
7227
+ }
7228
+
7105
7229
  function until(sourceSignal, predicate, options = {}) {
7106
7230
  return new Promise((resolve, reject) => {
7107
7231
  let effectRef;
@@ -7302,5 +7426,5 @@ function withHistory(sourceOrValue, opt) {
7302
7426
  * Generated bundle index. Do not edit.
7303
7427
  */
7304
7428
 
7305
- export { CONCURRENCY_INSTRUMENTATION, MmActivity, MmTransition, MmViewTransitionName, OP_PROTO_VERSION, PAUSABLE_OPTIONS, PERSISTED_STORE_OPTIONS, POS_SEGMENT, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, applyOps, batteryStatus, bridgeScopeToPendingTasks, chunked, clipboard, combineWith, compareHlc, compareSiblings, compareTotal, createAttributedPending, createConvergingApply, createForwardingScope, createHlcClock, createStoreContext, createTransaction, createTransitionScope, debounce, debounced, defaultFold, deferredValue, derived, diffOps, distinct, elementSize, elementVisibility, extendStore, filter, filterWith, focusWithin, forkStore, geolocation, getTransitionScope, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, insertElement, invertBatch, isConflicted, isDerivation, isLeaf, isMutable, isOpaque, isStore, keepPrevious, keyArray, keyedArray, latest, lww, map, mapArray, mapObject, mediaQuery, merge3, mergeThree, mousePosition, moveElement, mutable, mutableStore, nestedEffect, networkStatus, opLog, opSync, opaque, orderedEntries, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, perfCustomTracks, persist, persistedStore, pipeable, piped, pointerDrag, policyStrategy, pooled, pooledArray, pooledMap, pooledSet, posBetween, prefersDarkMode, prefersReducedMotion, preserve, projection, provideConcurrencyInstrumentation, provideForwardingTransitionScope, providePausableOptions, providePaused, providePersistedStoreOptions, provideTransitionScope, rebalanceContainer, rebaseOps, reconcile, registerResource, removeElement, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, storeHistory, stored, syncedFork, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, until, use, validateEnvelope, windowSize, withHistory };
7429
+ export { CONCURRENCY_INSTRUMENTATION, MmActivity, MmTransition, MmViewTransitionName, OP_PROTO_VERSION, PAUSABLE_OPTIONS, PERSISTED_STORE_OPTIONS, POS_SEGMENT, SuspenseBoundary, SuspenseBoundaryBase, UnscopedSuspenseBoundary, activeTransaction, applyOps, batteryStatus, bridgeScopeToPendingTasks, chunked, clipboard, combineWith, compareHlc, compareSiblings, compareTotal, createAttributedPending, createConvergingApply, createForwardingScope, createHlcClock, createStoreContext, createTransaction, createTransitionScope, debounce, debounced, defaultFold, deferredValue, derived, diffOps, distinct, elementSize, elementVisibility, extendStore, filter, filterWith, focusWithin, forkStore, geolocation, getTransitionScope, holdUntilReady, idle, indexArray, injectPaused, injectRegisterResource, injectStartTransaction, injectStartTransition, injectTransitionScope, insertElement, invertBatch, isConflicted, isDerivation, isLeaf, isMutable, isOpaque, isStore, isStored, keepPrevious, keyArray, keyedArray, latest, lww, map, mapArray, mapObject, mediaQuery, merge3, mergeThree, mousePosition, moveElement, mutable, mutableStore, nestedEffect, networkStatus, opLog, opSync, opaque, orderedEntries, orientation, pageVisibility, pairwise, pausableComputed, pausableEffect, pausableSignal, perfCustomTracks, persist, persistedStore, pipeable, piped, pointerDrag, policyStrategy, pooled, pooledArray, pooledMap, pooledSet, posBetween, prefersDarkMode, prefersReducedMotion, preserve, projection, provideConcurrencyInstrumentation, provideForwardingTransitionScope, providePausableOptions, providePaused, providePersistedStoreOptions, provideTransitionScope, rebalanceContainer, rebaseOps, reconcile, registerResource, removeElement, resolvePause, scan, scrollPosition, select, sensor, sensors, signalFromEvent, startWith, store, storeHistory, stored, syncedFork, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, traced, until, use, validateEnvelope, windowSize, withHistory };
7306
7430
  //# sourceMappingURL=mmstack-primitives.mjs.map