@mmstack/primitives 20.4.7 → 20.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/index.d.ts CHANGED
@@ -1,4 +1,40 @@
1
- import { CreateSignalOptions, DestroyRef, WritableSignal, Signal, ElementRef, EffectCleanupRegisterFn, CreateEffectOptions, Injector, ValueEqualityFn } from '@angular/core';
1
+ import { ValueEqualityFn, Injector, Signal, CreateSignalOptions, DestroyRef, WritableSignal, EffectRef, EffectCleanupRegisterFn, CreateEffectOptions, ElementRef } from '@angular/core';
2
+
3
+ type CreateChunkedOptions<T> = {
4
+ /**
5
+ * The number of items to process in each chunk.
6
+ * @default 50
7
+ */
8
+ chunkSize?: number;
9
+ /**
10
+ * The delay between processing each chunk. Can be a number (milliseconds) or 'frame' to use `requestAnimationFrame`.
11
+ * @default 'frame'
12
+ */
13
+ delay?: number | 'frame' | 'microtask';
14
+ /**
15
+ * A custom equality function to determine if the processed chunk has changed. This can help prevent unnecessary updates if the chunk content is the same as the previous one.
16
+ */
17
+ equal?: ValueEqualityFn<T[]>;
18
+ /**
19
+ * An optional `Injector` to use for the internal effect. This allows the effect to have access to dependency injection if needed.
20
+ */
21
+ injector?: Injector;
22
+ };
23
+ /**
24
+ * Creates a new `Signal` that processes an array of items in time-sliced chunks. This is useful for handling large lists without blocking the main thread.
25
+ *
26
+ * The returned signal will initially contain the first `chunkSize` items from the source array. It will then schedule updates to include additional chunks of items based on the specified `duration`.
27
+ *
28
+ * @template T The type of items in the array.
29
+ * @param source A `Signal` or a function that returns an array of items to be processed in chunks.
30
+ * @param options Configuration options for chunk size, delay duration, equality function, and injector.
31
+ * @returns A `Signal` that emits the current chunk of items being processed.
32
+ *
33
+ * @example
34
+ * const largeList = signal(Array.from({ length: 1000 }, (_, i) => i));
35
+ * const chunkedList = chunked(largeList, { chunkSize: 100, duration: 100 });
36
+ */
37
+ declare function chunked<T>(source: Signal<T[]> | (() => T[]), options?: CreateChunkedOptions<T>): Signal<T[]>;
2
38
 
3
39
  /**
4
40
  * Options for creating a debounced writable signal.
@@ -192,7 +228,6 @@ declare function mutable<T>(initial: T, opt?: CreateSignalOptions<T>): MutableSi
192
228
  */
193
229
  declare function isMutable<T = any>(value: WritableSignal<T>): value is MutableSignal<T>;
194
230
 
195
- type UnknownObject = Record<PropertyKey, unknown>;
196
231
  /**
197
232
  * Options for creating a derived signal using the full `derived` function signature.
198
233
  * @typeParam T - The type of the source signal's value (parent).
@@ -271,31 +306,32 @@ declare function derived<T, U>(source: WritableSignal<T>, opt: CreateDerivedOpti
271
306
  * console.log(user().name); // Outputs: Jane
272
307
  * ```
273
308
  */
274
- declare function derived<T extends UnknownObject, TKey extends keyof T>(source: WritableSignal<T>, key: TKey, opt?: CreateSignalOptions<T[TKey]>): DerivedSignal<T, T[TKey]>;
309
+ declare function derived<T extends object, TKey extends keyof T>(source: MutableSignal<T>, key: TKey, opt?: CreateSignalOptions<T[TKey]>): DerivedSignal<T, T[TKey]> & MutableSignal<T[TKey]>;
275
310
  /**
276
- * Creates a `DerivedSignal` from an array, deriving an element by its index.
277
- * This overload is a convenient shorthand for accessing array elements.
311
+ * Creates a `DerivedSignal` that derives a property from an object held by the source signal.
312
+ * This overload is a convenient shorthand for accessing object properties.
278
313
  *
279
- * @typeParam T The type of the source signal's value (must be an array).
280
- * @param source The source `WritableSignal` (holding an array).
281
- * @param index The index of the element to derive.
314
+ * @typeParam T The type of the source signal's value (must be an object).
315
+ * @typeParam TKey The key of the property to derive.
316
+ * @param source The source `WritableSignal` (holding an object).
317
+ * @param key The key of the property to derive.
282
318
  * @param options Optional signal options for the derived signal.
283
319
  * @returns A `DerivedSignal` instance.
284
320
  *
285
321
  * @example
286
322
  * ```ts
287
- * const numbers = signal([1, 2, 3]);
288
- * const secondNumber = derived(numbers, 1);
323
+ * const user = signal({ name: 'John', age: 30 });
324
+ * const name = derived(user, 'name');
289
325
  *
290
- * console.log(secondNumber()); // Outputs: 2
326
+ * console.log(name()); // Outputs: John
291
327
  *
292
328
  * // Update the derived signal, which also updates the source
293
- * secondNumber.set(5);
329
+ * name.set('Jane');
294
330
  *
295
- * console.log(numbers()); // Outputs: [1, 5, 3]
331
+ * console.log(user().name); // Outputs: Jane
296
332
  * ```
297
333
  */
298
- declare function derived<T extends any[]>(source: WritableSignal<T>, index: number, opt?: CreateSignalOptions<T[number]>): DerivedSignal<T, T[number]>;
334
+ declare function derived<T extends object, TKey extends keyof T>(source: WritableSignal<T>, key: TKey, opt?: CreateSignalOptions<T[TKey]>): DerivedSignal<T, T[TKey]>;
299
335
  /**
300
336
  * Creates a `DerivedSignal` that derives its value from another `MutableSignal`.
301
337
  * Use mutuable signals with caution, but very useful for deeply nested structures.
@@ -319,6 +355,30 @@ declare function derived<T extends any[]>(source: WritableSignal<T>, index: numb
319
355
  * ```
320
356
  */
321
357
  declare function derived<T, U>(source: MutableSignal<T>, optOrKey: CreateDerivedOptions<T, U> | keyof T, opt?: CreateSignalOptions<U>): DerivedSignal<T, U> & MutableSignal<U>;
358
+ /**
359
+ * Creates a `DerivedSignal` from an array, deriving an element by its index.
360
+ * This overload is a convenient shorthand for accessing array elements.
361
+ *
362
+ * @typeParam T The type of the source signal's value (must be an array).
363
+ * @param source The source `WritableSignal` (holding an array).
364
+ * @param index The index of the element to derive.
365
+ * @param options Optional signal options for the derived signal.
366
+ * @returns A `DerivedSignal` instance.
367
+ *
368
+ * @example
369
+ * ```ts
370
+ * const numbers = signal([1, 2, 3]);
371
+ * const secondNumber = derived(numbers, 1);
372
+ *
373
+ * console.log(secondNumber()); // Outputs: 2
374
+ *
375
+ * // Update the derived signal, which also updates the source
376
+ * secondNumber.set(5);
377
+ *
378
+ * console.log(numbers()); // Outputs: [1, 5, 3]
379
+ * ```
380
+ */
381
+ declare function derived<T extends any[]>(source: WritableSignal<T>, index: number, opt?: CreateSignalOptions<T[number]>): DerivedSignal<T, T[number]>;
322
382
  /**
323
383
  * Creates a "fake" `DerivedSignal` from a simple value. This is useful for creating
324
384
  * `FormControlSignal` instances that are not directly derived from another signal.
@@ -353,71 +413,87 @@ declare function toFakeSignalDerivation<T, U>(initial: WritableSignal<U>): Deriv
353
413
  */
354
414
  declare function isDerivation<T, U>(sig: WritableSignal<U>): sig is DerivedSignal<T, U>;
355
415
 
356
- /**
357
- * Options for configuring the `elementVisibility` sensor, extending
358
- * standard `IntersectionObserverInit` options.
359
- */
360
- type ElementVisibilityOptions = IntersectionObserverInit & {
361
- /** Optional debug name for the internal signal. */
362
- debugName?: string;
363
- };
364
- type ElementVisibilitySignal = Signal<IntersectionObserverEntry | undefined> & {
365
- readonly visible: Signal<boolean>;
416
+ type Frame = {
417
+ injector: Injector;
418
+ parent: Frame | null;
419
+ children: Set<EffectRef>;
366
420
  };
421
+
367
422
  /**
368
- * Creates a read-only signal that tracks the intersection status of a target DOM element
369
- * with the viewport or a specified root element, using the `IntersectionObserver` API.
423
+ * Creates an effect that can be nested, similar to SolidJS's `createEffect`.
370
424
  *
371
- * It can observe a static `ElementRef`/`Element` or a `Signal` that resolves to one,
372
- * allowing for dynamic targets.
425
+ * This primitive enables true hierarchical reactivity. A `nestedEffect` created
426
+ * within another `nestedEffect` is automatically destroyed and recreated when
427
+ * the parent re-runs.
373
428
  *
374
- * @param target The DOM element (or `ElementRef`, or a `Signal` resolving to one) to observe.
375
- * If the signal resolves to `null`, observation stops.
376
- * @param options Optional `IntersectionObserverInit` options (e.g., `root`, `rootMargin`, `threshold`)
377
- * and an optional `debugName`.
378
- * @returns A `Signal<IntersectionObserverEntry | undefined>`. It emits `undefined` initially,
379
- * on the server, or if the target is `null`. Otherwise, it emits the latest
380
- * `IntersectionObserverEntry`. Consumers can derive a boolean `isVisible` from
381
- * this entry's `isIntersecting` property.
429
+ * It automatically handles injector propagation and lifetime management, allowing
430
+ * you to create fine-grained, conditional side-effects that only track
431
+ * dependencies when they are "live".
432
+ *
433
+ * @param effectFn The side-effect function, which receives a cleanup register function.
434
+ * @param options (Optional) Angular's `CreateEffectOptions`.
435
+ * @returns An `EffectRef` for the created effect.
382
436
  *
383
437
  * @example
384
438
  * ```ts
385
- * import { Component, effect, ElementRef, viewChild } from '@angular/core';
386
- * import { elementVisibility } from '@mmstack/primitives';
387
- * import { computed } from '@angular/core'; // For derived boolean
388
- *
389
- * @Component({
390
- * selector: 'app-lazy-image',
391
- * template: `
392
- * <div #imageContainer style="height: 200px; border: 1px dashed grey;">
393
- * @if (isVisible()) {
394
- * <img src="your-image-url.jpg" alt="Lazy loaded image" />
395
- * <p>Image is VISIBLE!</p>
396
- * } @else {
397
- * <p>Scroll down to see the image...</p>
398
- * }
399
- * </div>
400
- * `
401
- * })
402
- * export class LazyImageComponent {
403
- * readonly imageContainer = viewChild.required<ElementRef<HTMLDivElement>>('imageContainer');
404
- *
405
- * // Observe the element, get the full IntersectionObserverEntry
406
- * readonly intersectionEntry = elementVisibility(this.imageContainer);
439
+ * // Assume `coldGuard` changes rarely, but `hotSignal` changes often.
440
+ * const coldGuard = signal(false);
441
+ * const hotSignal = signal(0);
407
442
  *
408
- * // Derive a simple boolean for visibility
409
- * readonly isVisible = computed(() => this.intersectionEntry()?.isIntersecting ?? false);
443
+ * nestedEffect(() => {
444
+ * // This outer effect only tracks `coldGuard`.
445
+ * if (coldGuard()) {
410
446
  *
411
- * constructor() {
412
- * effect(() => {
413
- * console.log('Intersection Entry:', this.intersectionEntry());
414
- * console.log('Is Visible:', this.isVisible());
447
+ * // This inner effect is CREATED when coldGuard is true
448
+ * // and DESTROYED when it becomes false.
449
+ * nestedEffect(() => {
450
+ * // It only tracks `hotSignal` while it exists.
451
+ * console.log('Hot signal is:', hotSignal());
415
452
  * });
416
453
  * }
417
- * }
454
+ * // If `coldGuard` is false, this outer effect does not track `hotSignal`.
455
+ * });
456
+ * ```
457
+ * @example
458
+ * ```ts
459
+ * const users = signal([
460
+ * { id: 1, name: 'Alice' },
461
+ * { id: 2, name: 'Bob' }
462
+ * ]);
463
+ *
464
+ * // The fine-grained mapped list
465
+ * const mappedUsers = mapArray(
466
+ * users,
467
+ * (userSignal, index) => {
468
+ * // 1. Create a fine-grained SIDE EFFECT for *this item*
469
+ * // This effect's lifetime is now tied to this specific item. created once on init of this index.
470
+ * const effectRef = nestedEffect(() => {
471
+ * // This only runs if *this* userSignal changes,
472
+ * // not if the whole list changes.
473
+ * console.log(`User ${index} updated:`, userSignal().name);
474
+ * });
475
+ *
476
+ * // 2. Return the data AND the cleanup logic
477
+ * return {
478
+ * // The mapped data
479
+ * label: computed(() => `User: ${userSignal().name}`),
480
+ *
481
+ * // The cleanup function
482
+ * destroyEffect: () => effectRef.destroy()
483
+ * };
484
+ * },
485
+ * {
486
+ * // 3. Tell mapArray HOW to clean up when an item is removed, this needs to be manual as it's not a nestedEffect itself
487
+ * onDestroy: (mappedItem) => {
488
+ * mappedItem.destroyEffect();
489
+ * }
490
+ * }
491
+ * );
418
492
  * ```
419
493
  */
420
- declare function elementVisibility(target?: ElementRef<Element> | Element | Signal<ElementRef<Element> | Element | null>, opt?: ElementVisibilityOptions): ElementVisibilitySignal;
494
+ declare function nestedEffect(effectFn: (registerCleanup: EffectCleanupRegisterFn) => void, options?: CreateEffectOptions & {
495
+ bindToFrame?: (parent: Frame | null) => Frame | null;
496
+ }): EffectRef;
421
497
 
422
498
  /**
423
499
  * Reactively maps items from a source array to a new array, creating stable signals for each item.
@@ -449,7 +525,7 @@ declare function elementVisibility(target?: ElementRef<Element> | Element | Sign
449
525
  * ]);
450
526
  *
451
527
  * // The `itemSignal` is writable because `sourceItems` is a WritableSignal.
452
- * const mappedItems = mapArray(sourceItems, (itemSignal, index) => ({
528
+ * const mappedItems = indexArray(sourceItems, (itemSignal, index) => ({
453
529
  * label: computed(() => `${index}: ${itemSignal().name.toUpperCase()}`),
454
530
  * setName: (newName: string) => itemSignal.update(item => ({ ...item, name: newName }))
455
531
  * }));
@@ -458,91 +534,60 @@ declare function elementVisibility(target?: ElementRef<Element> | Element | Sign
458
534
  * mappedItems()[0].setName('Avocado');
459
535
  * // sourceItems() is now: [{ id: 1, name: 'Avocado' }, { id: 2, name: 'Banana' }]
460
536
  */
461
- declare function mapArray<T, U>(source: MutableSignal<T[]>, map: (value: MutableSignal<T>, index: number) => U, options?: CreateSignalOptions<T> & {
537
+ declare function indexArray<T, U>(source: MutableSignal<T[]>, map: (value: MutableSignal<T>, index: number) => U, options?: CreateSignalOptions<T> & {
462
538
  onDestroy?: (value: U) => void;
463
539
  }): Signal<U[]>;
464
- declare function mapArray<T, U>(source: WritableSignal<T[]>, map: (value: WritableSignal<T>, index: number) => U, options?: CreateSignalOptions<T> & {
540
+ declare function indexArray<T, U>(source: WritableSignal<T[]>, map: (value: WritableSignal<T>, index: number) => U, options?: CreateSignalOptions<T> & {
465
541
  onDestroy?: (value: U) => void;
466
542
  }): Signal<U[]>;
467
- declare function mapArray<T, U>(source: Signal<T[]> | (() => T[]), map: (value: Signal<T>, index: number) => U, options?: CreateSignalOptions<T> & {
543
+ declare function indexArray<T, U>(source: Signal<T[]> | (() => T[]), map: (value: Signal<T>, index: number) => U, options?: CreateSignalOptions<T> & {
468
544
  onDestroy?: (value: U) => void;
469
545
  }): Signal<U[]>;
546
+ /**
547
+ * @deprecated use indexArray instead
548
+ */
549
+ declare const mapArray: typeof indexArray;
470
550
 
471
551
  /**
472
- * Creates an effect that can be nested, similar to SolidJS's `createEffect`.
473
- *
474
- * This primitive enables true hierarchical reactivity. A `nestedEffect` created
475
- * within another `nestedEffect` is automatically destroyed and recreated when
476
- * the parent re-runs.
552
+ * Reactively maps items from a source array to a new array by value (identity).
477
553
  *
478
- * It automatically handles injector propagation and lifetime management, allowing
479
- * you to create fine-grained, conditional side-effects that only track
480
- * dependencies when they are "live".
554
+ * similar to `Array.prototype.map`, but:
555
+ * 1. The `mapFn` receives the `index` as a Signal.
556
+ * 2. If an item in the `source` array moves to a new position, the *result* of the map function is reused and moved.
557
+ * The `index` signal is updated to the new index.
558
+ * 3. The `mapFn` is only run for *new* items.
481
559
  *
482
- * @param effectFn The side-effect function, which receives a cleanup register function.
483
- * @param options (Optional) Angular's `CreateEffectOptions`.
484
- * @returns An `EffectRef` for the created effect.
560
+ * This is useful for building efficient lists where DOM nodes or heavy instances should be reused
561
+ * when the list is reordered.
485
562
  *
486
- * @example
487
- * ```ts
488
- * // Assume `coldGuard` changes rarely, but `hotSignal` changes often.
489
- * const coldGuard = signal(false);
490
- * const hotSignal = signal(0);
491
- *
492
- * nestedEffect(() => {
493
- * // This outer effect only tracks `coldGuard`.
494
- * if (coldGuard()) {
495
- *
496
- * // This inner effect is CREATED when coldGuard is true
497
- * // and DESTROYED when it becomes false.
498
- * nestedEffect(() => {
499
- * // It only tracks `hotSignal` while it exists.
500
- * console.log('Hot signal is:', hotSignal());
501
- * });
502
- * }
503
- * // If `coldGuard` is false, this outer effect does not track `hotSignal`.
504
- * });
505
- * ```
506
- * @example
507
- * ```ts
508
- * const users = signal([
509
- { id: 1, name: 'Alice' },
510
- { id: 2, name: 'Bob' }
511
- ]);
512
-
513
- // The fine-grained mapped list
514
- const mappedUsers = mapArray(
515
- users,
516
- (userSignal, index) => {
517
- // 1. Create a fine-grained SIDE EFFECT for *this item*
518
- // This effect's lifetime is now tied to this specific item. created once on init of this index.
519
- const effectRef = nestedEffect(() => {
520
- // This only runs if *this* userSignal changes,
521
- // not if the whole list changes.
522
- console.log(`User ${index} updated:`, userSignal().name);
523
- });
524
-
525
- // 2. Return the data AND the cleanup logic
526
- return {
527
- // The mapped data
528
- label: computed(() => `User: ${userSignal().name}`),
529
-
530
- // The cleanup function
531
- destroyEffect: () => effectRef.destroy()
532
- };
533
- },
534
- {
535
- // 3. Tell mapArray HOW to clean up when an item is removed, this needs to be manual as it's not a nestedEffect itself
536
- onDestroy: (mappedItem) => {
537
- mappedItem.destroyEffect();
538
- }
539
- }
540
- );
541
- * ```
563
+ * @param source A `Signal<T[]>` or a function returning `T[]`.
564
+ * @param mapFn The mapping function. Receives the item and its index as a Signal.
565
+ * @param options Optional configuration:
566
+ * - `onDestroy`: A callback invoked when a mapped item is removed from the array.
567
+ * @returns A `Signal<U[]>` containing the mapped array.
542
568
  */
543
- declare function nestedEffect(effectFn: (registerCleanup: EffectCleanupRegisterFn) => void, options?: CreateEffectOptions): {
544
- destroy: () => void;
569
+ declare function keyArray<T, U, K>(source: Signal<T[]> | (() => T[]), mapFn: (v: T, i: Signal<number>) => U, options?: {
570
+ onDestroy?: (value: U) => void;
571
+ /**
572
+ * Optional function to use a custom key for item comparison.
573
+ * Use this if you want to reuse mapped items based on a property (like an ID)
574
+ * even if the item reference changes.
575
+ */
576
+ key?: (item: T) => K;
577
+ }): Signal<U[]>;
578
+
579
+ type MappedObject<T extends object, U> = {
580
+ [K in keyof T]: U;
545
581
  };
582
+ declare function mapObject<T extends object, U>(source: MutableSignal<T>, mapFn: <K extends keyof T>(key: K, value: MutableSignal<T[K]>) => U, options?: {
583
+ onDestroy?: (value: U) => void;
584
+ }): Signal<MappedObject<T, U>>;
585
+ declare function mapObject<T extends object, U>(source: WritableSignal<T>, mapFn: <K extends keyof T>(key: K, value: WritableSignal<T[K]>) => U, options?: {
586
+ onDestroy?: (value: U) => void;
587
+ }): Signal<MappedObject<T, U>>;
588
+ declare function mapObject<T extends object, U>(source: (() => T) | Signal<T>, mapFn: <K extends keyof T>(key: K, value: Signal<T[K]>) => U, options?: {
589
+ onDestroy?: (value: U) => void;
590
+ }): Signal<MappedObject<T, U>>;
546
591
 
547
592
  /**
548
593
  * A pure, synchronous transform from I -> O.
@@ -640,6 +685,107 @@ declare function pipeable<TSig extends Signal<any>>(signal: TSig): PipeableSigna
640
685
  */
641
686
  declare function piped<T>(initial: T, opt?: CreateSignalOptions<T>): PipeableSignal<T, WritableSignal<T>>;
642
687
 
688
+ /**
689
+ * Represents the size of an element.
690
+ */
691
+ interface ElementSize {
692
+ width: number;
693
+ height: number;
694
+ }
695
+ /**
696
+ * Options for configuring the `elementSize` sensor.
697
+ */
698
+ type ElementSizeOptions = ResizeObserverOptions & {
699
+ /** Optional debug name for the internal signal. */
700
+ debugName?: string;
701
+ };
702
+ type ElementSizeSignal = Signal<ElementSize | undefined>;
703
+ /**
704
+ * Creates a read-only signal that tracks the size of a target DOM element.
705
+ *
706
+ * By default, it observes the `border-box` size to align with `getBoundingClientRect()`,
707
+ * which is used to provide a synchronous initial value if possible.
708
+ *
709
+ * @param target The DOM element (or `ElementRef`, or a `Signal` resolving to one) to observe.
710
+ * @param options Optional configuration including `box` (defaults to 'border-box') and `debugName`.
711
+ * @returns A `Signal<ElementSize | undefined>`.
712
+ *
713
+ * @example
714
+ * ```ts
715
+ * const size = elementSize(elementRef);
716
+ * effect(() => {
717
+ * console.log('Size:', size()?.width, size()?.height);
718
+ * });
719
+ * ```
720
+ */
721
+ declare function elementSize(target?: ElementRef<Element> | Element | Signal<ElementRef<Element> | Element | null>, opt?: ElementSizeOptions): ElementSizeSignal;
722
+
723
+ /**
724
+ * Options for configuring the `elementVisibility` sensor, extending
725
+ * standard `IntersectionObserverInit` options.
726
+ */
727
+ type ElementVisibilityOptions = IntersectionObserverInit & {
728
+ /** Optional debug name for the internal signal. */
729
+ debugName?: string;
730
+ };
731
+ type ElementVisibilitySignal = Signal<IntersectionObserverEntry | undefined> & {
732
+ readonly visible: Signal<boolean>;
733
+ };
734
+ /**
735
+ * Creates a read-only signal that tracks the intersection status of a target DOM element
736
+ * with the viewport or a specified root element, using the `IntersectionObserver` API.
737
+ *
738
+ * It can observe a static `ElementRef`/`Element` or a `Signal` that resolves to one,
739
+ * allowing for dynamic targets.
740
+ *
741
+ * @param target The DOM element (or `ElementRef`, or a `Signal` resolving to one) to observe.
742
+ * If the signal resolves to `null`, observation stops.
743
+ * @param options Optional `IntersectionObserverInit` options (e.g., `root`, `rootMargin`, `threshold`)
744
+ * and an optional `debugName`.
745
+ * @returns A `Signal<IntersectionObserverEntry | undefined>`. It emits `undefined` initially,
746
+ * on the server, or if the target is `null`. Otherwise, it emits the latest
747
+ * `IntersectionObserverEntry`. Consumers can derive a boolean `isVisible` from
748
+ * this entry's `isIntersecting` property.
749
+ *
750
+ * @example
751
+ * ```ts
752
+ * import { Component, effect, ElementRef, viewChild } from '@angular/core';
753
+ * import { elementVisibility } from '@mmstack/primitives';
754
+ * import { computed } from '@angular/core'; // For derived boolean
755
+ *
756
+ * @Component({
757
+ * selector: 'app-lazy-image',
758
+ * template: `
759
+ * <div #imageContainer style="height: 200px; border: 1px dashed grey;">
760
+ * @if (isVisible()) {
761
+ * <img src="your-image-url.jpg" alt="Lazy loaded image" />
762
+ * <p>Image is VISIBLE!</p>
763
+ * } @else {
764
+ * <p>Scroll down to see the image...</p>
765
+ * }
766
+ * </div>
767
+ * `
768
+ * })
769
+ * export class LazyImageComponent {
770
+ * readonly imageContainer = viewChild.required<ElementRef<HTMLDivElement>>('imageContainer');
771
+ *
772
+ * // Observe the element, get the full IntersectionObserverEntry
773
+ * readonly intersectionEntry = elementVisibility(this.imageContainer);
774
+ *
775
+ * // Derive a simple boolean for visibility
776
+ * readonly isVisible = computed(() => this.intersectionEntry()?.isIntersecting ?? false);
777
+ *
778
+ * constructor() {
779
+ * effect(() => {
780
+ * console.log('Intersection Entry:', this.intersectionEntry());
781
+ * console.log('Is Visible:', this.isVisible());
782
+ * });
783
+ * }
784
+ * }
785
+ * ```
786
+ */
787
+ declare function elementVisibility(target?: ElementRef<Element> | Element | Signal<ElementRef<Element> | Element | null>, opt?: ElementVisibilityOptions): ElementVisibilitySignal;
788
+
643
789
  /**
644
790
  * Creates a read-only signal that reactively tracks whether a CSS media query
645
791
  * string currently matches.
@@ -1029,6 +1175,81 @@ type WindowSizeSignal = Signal<WindowSize> & {
1029
1175
  */
1030
1176
  declare function windowSize(opt?: WindowSizeOptions): WindowSizeSignal;
1031
1177
 
1178
+ type SensorTypedOptions = {
1179
+ elementVisibility: {
1180
+ opt: ElementVisibilityOptions & {
1181
+ target?: ElementRef<Element> | Element | Signal<ElementRef<Element> | Element | null>;
1182
+ };
1183
+ returnType: ElementVisibilitySignal;
1184
+ };
1185
+ elementSize: {
1186
+ opt: ElementSizeOptions & {
1187
+ target?: ElementRef<Element> | Element | Signal<ElementRef<Element> | Element | null>;
1188
+ };
1189
+ returnType: ElementSizeSignal;
1190
+ };
1191
+ mousePosition: {
1192
+ opt: MousePositionOptions;
1193
+ returnType: MousePositionSignal;
1194
+ };
1195
+ networkStatus: {
1196
+ opt: {
1197
+ debugName?: string;
1198
+ };
1199
+ returnType: NetworkStatusSignal;
1200
+ };
1201
+ pageVisibility: {
1202
+ opt: {
1203
+ debugName?: string;
1204
+ };
1205
+ returnType: Signal<DocumentVisibilityState>;
1206
+ };
1207
+ darkMode: {
1208
+ opt: {
1209
+ debugName?: string;
1210
+ };
1211
+ returnType: Signal<boolean>;
1212
+ };
1213
+ reducedMotion: {
1214
+ opt: {
1215
+ debugName?: string;
1216
+ };
1217
+ returnType: Signal<boolean>;
1218
+ };
1219
+ scrollPosition: {
1220
+ opt: ScrollPositionOptions;
1221
+ returnType: ScrollPositionSignal;
1222
+ };
1223
+ windowSize: {
1224
+ opt: WindowSizeOptions;
1225
+ returnType: WindowSizeSignal;
1226
+ };
1227
+ mediaQuery: {
1228
+ opt: {
1229
+ query: string;
1230
+ debugName?: string;
1231
+ };
1232
+ returnType: Signal<boolean>;
1233
+ };
1234
+ };
1235
+ /**
1236
+ * Creates a sensor signal that the elements visiblity within the viewport
1237
+ * @param type Must be `'elementVisibility'`.
1238
+ * @param options Optional configuration IntersectionObserver & target.
1239
+ * @returns A `ElementVisibilitySignal` that tracks whether the Element is intersected.
1240
+ * @see {elementVisibility} for detailed documentation and examples.
1241
+ * @example const pos = sensor('elementVisibility');
1242
+ */
1243
+ declare function sensor(type: 'elementVisibility', options?: SensorTypedOptions['elementVisibility']['opt']): ElementVisibilitySignal;
1244
+ /**
1245
+ * Creates a sensor signal that tracks the element's size dimensions.
1246
+ * @param type Must be `'elementSize'`.
1247
+ * @param options Optional configuration ResizeObserver & target.
1248
+ * @returns A `ElementSizeSignal` that tracks the element's size ({ width, height }).
1249
+ * @see {elementSize} for detailed documentation and examples.
1250
+ * @example const size = sensor('elementSize');
1251
+ */
1252
+ declare function sensor(type: 'elementSize', options?: SensorTypedOptions['elementSize']['opt']): ElementSizeSignal;
1032
1253
  /**
1033
1254
  * Creates a sensor signal that tracks the mouse cursor's position.
1034
1255
  * @param type Must be `'mousePosition'`.
@@ -1037,7 +1258,7 @@ declare function windowSize(opt?: WindowSizeOptions): WindowSizeSignal;
1037
1258
  * @see {mousePosition} for detailed documentation and examples.
1038
1259
  * @example const pos = sensor('mousePosition', { coordinateSpace: 'page', throttle: 50 });
1039
1260
  */
1040
- declare function sensor(type: 'mousePosition', options?: MousePositionOptions): MousePositionSignal;
1261
+ declare function sensor(type: 'mousePosition', options?: SensorTypedOptions['mousePosition']['opt']): MousePositionSignal;
1041
1262
  /**
1042
1263
  * Creates a sensor signal that tracks the browser's online/offline status.
1043
1264
  * @param type Must be `'networkStatus'`.
@@ -1046,9 +1267,7 @@ declare function sensor(type: 'mousePosition', options?: MousePositionOptions):
1046
1267
  * @see {networkStatus} for detailed documentation and examples.
1047
1268
  * @example const onlineStatus = sensor('networkStatus');
1048
1269
  */
1049
- declare function sensor(type: 'networkStatus', options?: {
1050
- debugName?: string;
1051
- }): NetworkStatusSignal;
1270
+ declare function sensor(type: 'networkStatus', options?: SensorTypedOptions['networkStatus']['opt']): NetworkStatusSignal;
1052
1271
  /**
1053
1272
  * Creates a sensor signal that tracks the page's visibility state (e.g., 'visible', 'hidden').
1054
1273
  * @param type Must be `'pageVisibility'`.
@@ -1057,31 +1276,34 @@ declare function sensor(type: 'networkStatus', options?: {
1057
1276
  * @see {pageVisibility} for detailed documentation and examples.
1058
1277
  * @example const visibility = sensor('pageVisibility');
1059
1278
  */
1060
- declare function sensor(type: 'pageVisibility', options?: {
1061
- debugName?: string;
1062
- }): Signal<DocumentVisibilityState>;
1279
+ declare function sensor(type: 'pageVisibility', options?: SensorTypedOptions['pageVisibility']['opt']): Signal<DocumentVisibilityState>;
1063
1280
  /**
1064
1281
  * Creates a sensor signal that tracks the user's OS/browser preference for a dark color scheme.
1065
- * @param type Must be `'dark-mode'`.
1282
+ * @param type Must be `'darkMode'`.
1066
1283
  * @param options Optional configuration, currently only `debugName`.
1067
1284
  * @returns A `Signal<boolean>` which is `true` if a dark theme is preferred.
1068
1285
  * @see {prefersDarkMode} for detailed documentation and examples.
1069
1286
  * @example const isDarkMode = sensor('dark-mode');
1070
1287
  */
1071
- declare function sensor(type: 'dark-mode', options?: {
1072
- debugName?: string;
1073
- }): Signal<boolean>;
1288
+ declare function sensor(type: 'darkMode' | 'dark-mode', options?: SensorTypedOptions['darkMode']['opt']): Signal<boolean>;
1074
1289
  /**
1075
1290
  * Creates a sensor signal that tracks the user's OS/browser preference for reduced motion.
1076
- * @param type Must be `'reduced-motion'`.
1291
+ * @param type Must be `'reducedMotion'`.
1077
1292
  * @param options Optional configuration, currently only `debugName`.
1078
1293
  * @returns A `Signal<boolean>` which is `true` if reduced motion is preferred.
1079
1294
  * @see {prefersReducedMotion} for detailed documentation and examples.
1080
1295
  * @example const wantsReducedMotion = sensor('reduced-motion');
1081
1296
  */
1082
- declare function sensor(type: 'reduced-motion', options?: {
1083
- debugName?: string;
1084
- }): Signal<boolean>;
1297
+ declare function sensor(type: 'reducedMotion' | 'reduced-motion', options?: SensorTypedOptions['reducedMotion']['opt']): Signal<boolean>;
1298
+ /**
1299
+ * Creates a sensor signal that tracks the provided media query.
1300
+ * @param type Must be `'mediaQuery'`.
1301
+ * @param options Optional configuration for the media query sensor, including `query` and `debugName`.
1302
+ * @returns A `Signal<boolean>` which is `true` if the media query currently matches.
1303
+ * @see {mediaQuery} for detailed documentation and examples.
1304
+ * @example const isDesktop = sensor('mediaQuery', { query: '(min-width: 1024px)' });
1305
+ */
1306
+ declare function sensor(type: 'mediaQuery', options?: SensorTypedOptions['mediaQuery']['opt']): Signal<boolean>;
1085
1307
  /**
1086
1308
  * Creates a sensor signal that tracks the browser window's inner dimensions (width and height).
1087
1309
  * @param type Must be `'windowSize'`.
@@ -1090,7 +1312,7 @@ declare function sensor(type: 'reduced-motion', options?: {
1090
1312
  * @see {windowSize} for detailed documentation and examples.
1091
1313
  * @example const size = sensor('windowSize', { throttle: 200 });
1092
1314
  */
1093
- declare function sensor(type: 'windowSize', options?: WindowSizeOptions): WindowSizeSignal;
1315
+ declare function sensor(type: 'windowSize', options?: SensorTypedOptions['windowSize']['opt']): WindowSizeSignal;
1094
1316
  /**
1095
1317
  * Creates a sensor signal that tracks the scroll position (x, y) of the window or a specified element.
1096
1318
  * @param type Must be `'scrollPosition'`.
@@ -1099,7 +1321,70 @@ declare function sensor(type: 'windowSize', options?: WindowSizeOptions): Window
1099
1321
  * @see {scrollPosition} for detailed documentation and examples.
1100
1322
  * @example const pageScroll = sensor('scrollPosition', { throttle: 150 });
1101
1323
  */
1102
- declare function sensor(type: 'scrollPosition', options?: ScrollPositionOptions): ScrollPositionSignal;
1324
+ declare function sensor(type: 'scrollPosition', options?: SensorTypedOptions['scrollPosition']['opt']): ScrollPositionSignal;
1325
+ type SensorsOptions<TKey extends keyof SensorTypedOptions> = {
1326
+ [K in TKey]: SensorTypedOptions[K]['opt'];
1327
+ };
1328
+ type Sensors<TKey extends keyof SensorTypedOptions> = {
1329
+ [K in TKey]: SensorTypedOptions[K]['returnType'];
1330
+ };
1331
+ declare function sensors<const TType extends keyof SensorTypedOptions>(track: TType[], opt?: SensorsOptions<TType>): Sensors<TType>;
1332
+
1333
+ type BaseType = string | number | boolean | symbol | undefined | null | Function | Date | RegExp;
1334
+ type Key = string | number;
1335
+ type AnyRecord = Record<Key, any>;
1336
+ /**
1337
+ * @internal
1338
+ * Validates whether a value is a Signal Store.
1339
+ */
1340
+ declare function isStore<T>(value: unknown): value is SignalStore<T>;
1341
+ type SignalArrayStore<T extends any[]> = Signal<T> & {
1342
+ readonly [index: number]: SignalStore<T[number]>;
1343
+ readonly length: Signal<number>;
1344
+ [Symbol.iterator](): Iterator<SignalStore<T[number]>>;
1345
+ };
1346
+ type WritableArrayStore<T extends any[]> = WritableSignal<T> & {
1347
+ readonly asReadonlyStore: () => SignalArrayStore<T>;
1348
+ readonly [index: number]: WritableSignalStore<T[number]>;
1349
+ readonly length: Signal<number>;
1350
+ [Symbol.iterator](): Iterator<WritableSignalStore<T[number]>>;
1351
+ };
1352
+ type MutableArrayStore<T extends any[]> = MutableSignal<T> & {
1353
+ readonly asReadonlyStore: () => SignalArrayStore<T>;
1354
+ readonly [index: number]: MutableSignalStore<T[number]>;
1355
+ readonly length: Signal<number>;
1356
+ [Symbol.iterator](): Iterator<MutableSignalStore<T[number]>>;
1357
+ };
1358
+ type SignalStore<T> = Signal<T> & (NonNullable<T> extends BaseType ? unknown : NonNullable<T> extends Array<any> ? SignalArrayStore<NonNullable<T>> : Readonly<{
1359
+ [K in keyof Required<T>]: SignalStore<NonNullable<T>[K]>;
1360
+ }>);
1361
+ type WritableSignalStore<T> = WritableSignal<T> & {
1362
+ readonly asReadonlyStore: () => SignalStore<T>;
1363
+ } & (NonNullable<T> extends BaseType ? unknown : NonNullable<T> extends Array<any> ? WritableArrayStore<NonNullable<T>> : Readonly<{
1364
+ [K in keyof Required<T>]: WritableSignalStore<NonNullable<T>[K]>;
1365
+ }>);
1366
+ type MutableSignalStore<T> = MutableSignal<T> & {
1367
+ readonly asReadonlyStore: () => SignalStore<T>;
1368
+ } & (NonNullable<T> extends BaseType ? unknown : NonNullable<T> extends Array<any> ? MutableArrayStore<NonNullable<T>> : Readonly<{
1369
+ [K in keyof Required<T>]: MutableSignalStore<NonNullable<T>[K]>;
1370
+ }>);
1371
+ declare function toStore<T extends AnyRecord>(source: MutableSignal<T>, injector?: Injector): MutableSignalStore<T>;
1372
+ declare function toStore<T extends AnyRecord>(source: WritableSignal<T>, injector?: Injector): WritableSignalStore<T>;
1373
+ declare function toStore<T extends AnyRecord>(source: Signal<T>, injector?: Injector): SignalStore<T>;
1374
+ /**
1375
+ * Creates a WritableSignalStore from a value.
1376
+ * @see {@link toStore}
1377
+ */
1378
+ declare function store<T extends AnyRecord>(value: T, opt?: CreateSignalOptions<T> & {
1379
+ injector?: Injector;
1380
+ }): WritableSignalStore<T>;
1381
+ /**
1382
+ * Creates a MutableSignalStore from a value.
1383
+ * @see {@link toStore}
1384
+ */
1385
+ declare function mutableStore<T extends AnyRecord>(value: T, opt?: CreateSignalOptions<T> & {
1386
+ injector?: Injector;
1387
+ }): MutableSignalStore<T>;
1103
1388
 
1104
1389
  /**
1105
1390
  * Interface for storage mechanisms compatible with the `stored` signal.
@@ -1163,6 +1448,10 @@ type CreateStoredOptions<T> = CreateSignalOptions<T> & {
1163
1448
  * If 'true', the signal will remove the old key from storage when the key changes, defaults to `false`.
1164
1449
  */
1165
1450
  cleanupOldKey?: boolean;
1451
+ /**
1452
+ * Optional validator, which is called on load of value. Store will be set to fallback if value is false
1453
+ */
1454
+ validate?: (value: T) => boolean;
1166
1455
  };
1167
1456
  /**
1168
1457
  * A specialized `WritableSignal` returned by the `stored()` function.
@@ -1234,7 +1523,7 @@ type StoredSignal<T> = WritableSignal<T> & {
1234
1523
  * }
1235
1524
  * ```
1236
1525
  */
1237
- declare function stored<T>(fallback: T, { key, store: providedStore, serialize, deserialize, syncTabs, equal, onKeyChange, cleanupOldKey, ...rest }: CreateStoredOptions<T>): StoredSignal<T>;
1526
+ declare function stored<T>(fallback: T, { key, store: providedStore, serialize, deserialize, syncTabs, equal, onKeyChange, cleanupOldKey, validate, ...rest }: CreateStoredOptions<T>): StoredSignal<T>;
1238
1527
 
1239
1528
  type SyncSignalOptions = {
1240
1529
  id?: string;
@@ -1380,7 +1669,14 @@ declare function throttle<T>(source: WritableSignal<T>, opt?: CreateThrottledOpt
1380
1669
  *
1381
1670
  * writableSignal.set(5); // sets value of originalValue.a to 5 & triggers all signals
1382
1671
  */
1383
- declare function toWritable<T>(signal: Signal<T>, set: (value: T) => void, update?: (updater: (value: T) => T) => void): WritableSignal<T>;
1672
+ declare function toWritable<T>(source: Signal<T>, set: (value: T) => void, update?: (updater: (value: T) => T) => void, opt?: CreateSignalOptions<T> & {
1673
+ /**
1674
+ * If `true` (the default), the returned signal will be a computed signal that depends on the source signal.
1675
+ * If `false`, the returned signal will be a direct wrapper around the source signal without creating a new computed signal.
1676
+ * @default true
1677
+ */
1678
+ pure?: boolean;
1679
+ }): WritableSignal<T>;
1384
1680
 
1385
1681
  type UntilOptions = {
1386
1682
  /**
@@ -1532,5 +1828,5 @@ type CreateHistoryOptions<T> = Omit<CreateSignalOptions<T[]>, 'equal'> & {
1532
1828
  */
1533
1829
  declare function withHistory<T>(source: WritableSignal<T>, opt?: CreateHistoryOptions<T>): SignalWithHistory<T>;
1534
1830
 
1535
- export { combineWith, debounce, debounced, derived, distinct, elementVisibility, filter, isDerivation, isMutable, map, mapArray, mediaQuery, mousePosition, mutable, nestedEffect, networkStatus, pageVisibility, pipeable, piped, prefersDarkMode, prefersReducedMotion, scrollPosition, select, sensor, stored, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toWritable, until, windowSize, withHistory };
1536
- export type { CreateDebouncedOptions, CreateHistoryOptions, CreateStoredOptions, CreateThrottledOptions, DebouncedSignal, DerivedSignal, ElementVisibilityOptions, ElementVisibilitySignal, MousePositionOptions, MousePositionSignal, MutableSignal, NetworkStatusSignal, PipeableSignal, ScrollPosition, ScrollPositionOptions, ScrollPositionSignal, SignalWithHistory, StoredSignal, ThrottledSignal, UntilOptions, WindowSize, WindowSizeOptions, WindowSizeSignal };
1831
+ export { chunked, combineWith, debounce, debounced, derived, distinct, elementSize, elementVisibility, filter, indexArray, isDerivation, isMutable, isStore, keyArray, map, mapArray, mapObject, mediaQuery, mousePosition, mutable, mutableStore, nestedEffect, networkStatus, pageVisibility, pipeable, piped, prefersDarkMode, prefersReducedMotion, scrollPosition, select, sensor, sensors, store, stored, tabSync, tap, throttle, throttled, toFakeDerivation, toFakeSignalDerivation, toStore, toWritable, until, windowSize, withHistory };
1832
+ export type { CreateChunkedOptions, CreateDebouncedOptions, CreateHistoryOptions, CreateStoredOptions, CreateThrottledOptions, DebouncedSignal, DerivedSignal, ElementSize, ElementSizeOptions, ElementSizeSignal, ElementVisibilityOptions, ElementVisibilitySignal, MousePositionOptions, MousePositionSignal, MutableSignal, MutableSignalStore, NetworkStatusSignal, PipeableSignal, ScrollPosition, ScrollPositionOptions, ScrollPositionSignal, SignalStore, SignalWithHistory, StoredSignal, ThrottledSignal, UntilOptions, WindowSize, WindowSizeOptions, WindowSizeSignal, WritableSignalStore };