@mmstack/primitives 19.2.3 → 20.0.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.
@@ -1,20 +0,0 @@
1
- import { Signal } from '@angular/core';
2
- /**
3
- * A specialized Signal that tracks network status.
4
- * It's a boolean signal with an attached `since` signal.
5
- */
6
- export type NetworkStatusSignal = Signal<boolean> & {
7
- /** A signal tracking the timestamp of the last status change. */
8
- readonly since: Signal<Date>;
9
- };
10
- /**
11
- * Creates a read-only signal that tracks the browser's online status.
12
- *
13
- * The main signal returns a boolean (`true` for online, `false` for offline).
14
- * An additional `since` signal is attached, tracking when the status last changed.
15
- * It's SSR-safe and automatically cleans up its event listeners.
16
- *
17
- * @param debugName Optional debug name for the signal.
18
- * @returns A `NetworkStatusSignal` instance.
19
- */
20
- export declare function networkStatus(debugName?: string): NetworkStatusSignal;
@@ -1,38 +0,0 @@
1
- import { Signal } from '@angular/core';
2
- /**
3
- * Creates a read-only signal that tracks the page's visibility state.
4
- *
5
- * It uses the browser's Page Visibility API to reactively report if the
6
- * current document is `'visible'`, `'hidden'`, or in another state.
7
- * The primitive is SSR-safe and automatically cleans up its event listeners
8
- * when the creating context is destroyed.
9
- *
10
- * @param debugName Optional debug name for the signal.
11
- * @returns A read-only `Signal<DocumentVisibilityState>`. On the server,
12
- * it returns a static signal with a value of `'visible'`.
13
- *
14
- * @example
15
- * ```ts
16
- * import { Component, effect } from '@angular/core';
17
- * import { pageVisibility } from '@mmstack/primitives';
18
- *
19
- * @Component({
20
- * selector: 'app-visibility-tracker',
21
- * template: `<p>Page is currently: {{ visibilityState() }}</p>`
22
- * })
23
- * export class VisibilityTrackerComponent {
24
- * readonly visibilityState = pageVisibility();
25
- *
26
- * constructor() {
27
- * effect(() => {
28
- * if (this.visibilityState() === 'hidden') {
29
- * console.log('Page is hidden, pausing expensive animations...');
30
- * } else {
31
- * console.log('Page is visible, resuming activity.');
32
- * }
33
- * });
34
- * }
35
- * }
36
- * ```
37
- */
38
- export declare function pageVisibility(debugName?: string): Signal<DocumentVisibilityState>;
@@ -1,84 +0,0 @@
1
- import { ElementRef, // Used for SSR fallback
2
- type Signal } from '@angular/core';
3
- /**
4
- * Represents the scroll position.
5
- */
6
- export type ScrollPosition = {
7
- /** The horizontal scroll position (pixels from the left). */
8
- readonly x: number;
9
- /** The vertical scroll position (pixels from the top). */
10
- readonly y: number;
11
- };
12
- /**
13
- * Options for configuring the `scrollPosition` sensor.
14
- */
15
- export type ScrollPositionOptions = {
16
- /**
17
- * The target to listen for scroll events on.
18
- * Can be `window` (for page scroll) or an `HTMLElement`/`ElementRef<HTMLElement>`.
19
- * @default window
20
- */
21
- target?: Window | HTMLElement | ElementRef<HTMLElement>;
22
- /**
23
- * Optional delay in milliseconds to throttle the updates.
24
- * Scroll events can fire very rapidly.
25
- * @default 100 // A common default for scroll throttling
26
- */
27
- throttle?: number;
28
- /** Optional debug name for the internal signal. */
29
- debugName?: string;
30
- };
31
- /**
32
- * A specialized Signal that tracks scroll position.
33
- * It's a throttled signal of the scroll coordinates with an attached `unthrottled` signal.
34
- */
35
- export type ScrollPositionSignal = Signal<ScrollPosition> & {
36
- /** A signal providing the raw, unthrottled scroll position. */
37
- readonly unthrottled: Signal<ScrollPosition>;
38
- };
39
- /**
40
- * Creates a read-only signal that tracks the scroll position (x, y) of the window
41
- * or a specified HTML element.
42
- *
43
- * Updates are throttled by default to optimize performance. An `unthrottled`
44
- * property is available on the returned signal for direct access to raw updates.
45
- * The primitive is SSR-safe and automatically cleans up its event listeners.
46
- *
47
- * @param options Optional configuration for the scroll sensor.
48
- * @returns A `ScrollPositionSignal`. On the server, it returns a static
49
- * signal with `{ x: 0, y: 0 }`.
50
- *
51
- * @example
52
- * ```ts
53
- * import { Component, effect, ElementRef, viewChild } from '@angular/core';
54
- * import { scrollPosition } from '@mmstack/primitives';
55
- *
56
- * @Component({
57
- * selector: 'app-scroll-tracker',
58
- * template: `
59
- * <p>Window Scroll: X: {{ windowScroll().x }}, Y: {{ windowScroll().y }}</p>
60
- * <div #scrollableDiv style="height: 200px; width: 200px; overflow: auto; border: 1px solid black;">
61
- * <div style="height: 400px; width: 400px;">Scroll me!</div>
62
- * </div>
63
- * @if (divScroll()) {
64
- * <p>Div Scroll: X: {{ divScroll().x }}, Y: {{ divScroll().y }}</p>
65
- * }
66
- * `
67
- * })
68
- * export class ScrollTrackerComponent {
69
- * readonly windowScroll = scrollPosition(); // Defaults to window
70
- * readonly scrollableDiv = viewChild<ElementRef<HTMLDivElement>>('scrollableDiv');
71
- * readonly divScroll = scrollPosition({ target: this.scrollableDiv() }); // Example with element target
72
- *
73
- * constructor() {
74
- * effect(() => {
75
- * console.log('Window scrolled to:', this.windowScroll());
76
- * if (this.divScroll()) {
77
- * console.log('Div scrolled to:', this.divScroll());
78
- * }
79
- * });
80
- * }
81
- * }
82
- * ```
83
- */
84
- export declare function scrollPosition(opt?: ScrollPositionOptions): ScrollPositionSignal;
@@ -1,76 +0,0 @@
1
- import { Signal } from '@angular/core';
2
- import { MousePositionOptions, MousePositionSignal } from './mouse-position';
3
- import { NetworkStatusSignal } from './network-status';
4
- import { ScrollPositionOptions, ScrollPositionSignal } from './scroll-position';
5
- import { WindowSizeOptions, WindowSizeSignal } from './window-size';
6
- /**
7
- * Creates a sensor signal that tracks the mouse cursor's position.
8
- * @param type Must be `'mousePosition'`.
9
- * @param options Optional configuration for the mouse position sensor.
10
- * @returns A `MousePositionSignal` that tracks mouse coordinates and provides an unthrottled version.
11
- * @see {mousePosition} for detailed documentation and examples.
12
- * @example const pos = sensor('mousePosition', { coordinateSpace: 'page', throttle: 50 });
13
- */
14
- export declare function sensor(type: 'mousePosition', options?: MousePositionOptions): MousePositionSignal;
15
- /**
16
- * Creates a sensor signal that tracks the browser's online/offline status.
17
- * @param type Must be `'networkStatus'`.
18
- * @param options Optional configuration, currently only `debugName`.
19
- * @returns A `NetworkStatusSignal` which is a boolean indicating online status, with an attached `since` signal.
20
- * @see {networkStatus} for detailed documentation and examples.
21
- * @example const onlineStatus = sensor('networkStatus');
22
- */
23
- export declare function sensor(type: 'networkStatus', options?: {
24
- debugName?: string;
25
- }): NetworkStatusSignal;
26
- /**
27
- * Creates a sensor signal that tracks the page's visibility state (e.g., 'visible', 'hidden').
28
- * @param type Must be `'pageVisibility'`.
29
- * @param options Optional configuration, currently only `debugName`.
30
- * @returns A `Signal<DocumentVisibilityState>` indicating the page's current visibility.
31
- * @see {pageVisibility} for detailed documentation and examples.
32
- * @example const visibility = sensor('pageVisibility');
33
- */
34
- export declare function sensor(type: 'pageVisibility', options?: {
35
- debugName?: string;
36
- }): Signal<DocumentVisibilityState>;
37
- /**
38
- * Creates a sensor signal that tracks the user's OS/browser preference for a dark color scheme.
39
- * @param type Must be `'dark-mode'`.
40
- * @param options Optional configuration, currently only `debugName`.
41
- * @returns A `Signal<boolean>` which is `true` if a dark theme is preferred.
42
- * @see {prefersDarkMode} for detailed documentation and examples.
43
- * @example const isDarkMode = sensor('dark-mode');
44
- */
45
- export declare function sensor(type: 'dark-mode', options?: {
46
- debugName?: string;
47
- }): Signal<boolean>;
48
- /**
49
- * Creates a sensor signal that tracks the user's OS/browser preference for reduced motion.
50
- * @param type Must be `'reduced-motion'`.
51
- * @param options Optional configuration, currently only `debugName`.
52
- * @returns A `Signal<boolean>` which is `true` if reduced motion is preferred.
53
- * @see {prefersReducedMotion} for detailed documentation and examples.
54
- * @example const wantsReducedMotion = sensor('reduced-motion');
55
- */
56
- export declare function sensor(type: 'reduced-motion', options?: {
57
- debugName?: string;
58
- }): Signal<boolean>;
59
- /**
60
- * Creates a sensor signal that tracks the browser window's inner dimensions (width and height).
61
- * @param type Must be `'windowSize'`.
62
- * @param options Optional configuration for the window size sensor, including `throttle` and `debugName`.
63
- * @returns A `WindowSizeSignal` that tracks window dimensions and provides an unthrottled version.
64
- * @see {windowSize} for detailed documentation and examples.
65
- * @example const size = sensor('windowSize', { throttle: 200 });
66
- */
67
- export declare function sensor(type: 'windowSize', options?: WindowSizeOptions): WindowSizeSignal;
68
- /**
69
- * Creates a sensor signal that tracks the scroll position (x, y) of the window or a specified element.
70
- * @param type Must be `'scrollPosition'`.
71
- * @param options Optional configuration for the scroll position sensor, including `target`, `throttle`, and `debugName`.
72
- * @returns A `ScrollPositionSignal` that tracks scroll coordinates and provides an unthrottled version.
73
- * @see {scrollPosition} for detailed documentation and examples.
74
- * @example const pageScroll = sensor('scrollPosition', { throttle: 150 });
75
- */
76
- export declare function sensor(type: 'scrollPosition', options?: ScrollPositionOptions): ScrollPositionSignal;
@@ -1,75 +0,0 @@
1
- import { Signal } from '@angular/core';
2
- /**
3
- * Represents the dimensions of the window.
4
- */
5
- export type WindowSize = {
6
- /** The current inner width of the window in pixels. */
7
- readonly width: number;
8
- /** The current inner height of the window in pixels. */
9
- readonly height: number;
10
- };
11
- /**
12
- * Options for configuring the `mousePosition` sensor.
13
- */
14
- export type WindowSizeOptions = {
15
- /**
16
- * Optional debug name for the internal signal.
17
- */
18
- debugName?: string;
19
- /**
20
- * Optional delay in milliseconds to throttle the updates.
21
- * @default 100
22
- */
23
- throttle?: number;
24
- };
25
- /**
26
- * A specialized Signal that tracks window size.
27
- * It's a throttled signal of the window.innerHeight/innerWidth properties
28
- * with an attached `unthrottled` signal.
29
- */
30
- export type WindowSizeSignal = Signal<WindowSize> & {
31
- /** A signal providing the raw, unthrottled window size. */
32
- readonly unthrottled: Signal<WindowSize>;
33
- };
34
- /**
35
- * Creates a read-only signal that tracks the browser window's inner dimensions (width and height).
36
- *
37
- * Updates are throttled by default (100ms) to optimize performance during resize events.
38
- * An `unthrottled` property is available on the returned signal for direct access to raw updates.
39
- * The primitive is SSR-safe (returns a default size on the server) and automatically
40
- * cleans up its event listeners.
41
- *
42
- * @param opt Optional configuration, including `throttle` (ms) and `debugName`.
43
- * @returns A `WindowSizeSignal` (a `Signal<WindowSize>` with an `unthrottled` property).
44
- *
45
- * @example
46
- * ```ts
47
- * import { Component, effect } from '@angular/core';
48
- * import { windowSize } from '@mmstack/primitives';
49
- *
50
- * @Component({
51
- * selector: 'app-responsive-header',
52
- * template: `
53
- * <header>
54
- * Current Window Size: {{ size().width }}px x {{ size().height }}px
55
- * @if (isMobile()) {
56
- * <p>Mobile Menu</p>
57
- * } @else {
58
- * <p>Desktop Menu</p>
59
- * }
60
- * </header>
61
- * `
62
- * })
63
- * export class ResponsiveHeaderComponent {
64
- * readonly size = windowSize();
65
- * readonly isMobile = computed(() => this.size().width < 768);
66
- *
67
- * constructor() {
68
- * effect(() => {
69
- * console.log('Window resized to:', this.size());
70
- * });
71
- * }
72
- * }
73
- * ```
74
- */
75
- export declare function windowSize(opt?: WindowSizeOptions): WindowSizeSignal;
package/lib/stored.d.ts DELETED
@@ -1,136 +0,0 @@
1
- import { Signal, type CreateSignalOptions, type WritableSignal } from '@angular/core';
2
- /**
3
- * Interface for storage mechanisms compatible with the `stored` signal.
4
- * Matches the essential parts of the `Storage` interface (`localStorage`, `sessionStorage`).
5
- */
6
- type Store = {
7
- /** Retrieves an item from storage for a given key. */
8
- getItem: (key: string) => string | null;
9
- /** Sets an item in storage for a given key. */
10
- setItem: (key: string, value: string) => void;
11
- /** Removes an item from storage for a given key. */
12
- removeItem: (key: string) => void;
13
- };
14
- /**
15
- * Options for creating a signal synchronized with persistent storage using `stored()`.
16
- * Extends Angular's `CreateSignalOptions`.
17
- *
18
- * @template T The type of value held by the signal.
19
- */
20
- export type CreateStoredOptions<T> = CreateSignalOptions<T> & {
21
- /**
22
- * The key used to identify the item in storage.
23
- * Can be a static string or a function/signal returning a string for dynamic keys
24
- * (e.g., based on user ID or other application state).
25
- */
26
- key: string | (() => string);
27
- /**
28
- * Optional custom storage implementation (e.g., `sessionStorage` or a custom adapter).
29
- * Must conform to the `Store` interface (`getItem`, `setItem`, `removeItem`).
30
- * Defaults to `localStorage` in browser environments and a no-op store on the server.
31
- */
32
- store?: Store;
33
- /**
34
- * Optional function to serialize the value (type `T`) into a string before storing.
35
- * Defaults to `JSON.stringify`.
36
- * @param {T} value The value to serialize.
37
- * @returns {string} The serialized string representation.
38
- */
39
- serialize?: (value: T) => string;
40
- /**
41
- * Optional function to deserialize the string retrieved from storage back into the value (type `T`).
42
- * Defaults to `JSON.parse`.
43
- * @param {string} value The string retrieved from storage.
44
- * @returns {T} The deserialized value.
45
- */
46
- deserialize?: (value: string) => T;
47
- /**
48
- * If `true`, the signal will attempt to synchronize its state across multiple browser tabs
49
- * using the `storage` event. Changes made in one tab (set, update, clear) will be
50
- * reflected in other tabs using the same storage key.
51
- * Requires a browser environment. Defaults to `false`.
52
- */
53
- syncTabs?: boolean;
54
- /**
55
- * Optional parameter to specify how key changes should be handled, load is the default.
56
- * - `load`: The signal will load the value from storage when the key changes & replace the signal's value.
57
- * - `store`: The signal will store the current value to the new key when the key changes.
58
- */
59
- onKeyChange?: 'load' | 'store';
60
- /**
61
- * If 'true', the signal will remove the old key from storage when the key changes, defaults to `false`.
62
- */
63
- cleanupOldKey?: boolean;
64
- };
65
- /**
66
- * A specialized `WritableSignal` returned by the `stored()` function.
67
- * It synchronizes its value with persistent storage and provides additional methods.
68
- *
69
- * @template T The type of value held by the signal (matches the fallback type).
70
- */
71
- export type StoredSignal<T> = WritableSignal<T> & {
72
- /**
73
- * Removes the item associated with the signal's key from the configured storage.
74
- * After clearing, reading the signal will return the fallback value until it's set again.
75
- */
76
- clear: () => void;
77
- /**
78
- * A `Signal<string>` containing the current storage key being used by this stored signal.
79
- * This is particularly useful if the key was configured dynamically. You can read or react
80
- * to this signal to know the active key.
81
- */
82
- key: Signal<string>;
83
- };
84
- /**
85
- * Creates a `WritableSignal` whose state is automatically synchronized with persistent storage
86
- * (like `localStorage` or `sessionStorage`).
87
- *
88
- * It handles Server-Side Rendering (SSR) gracefully, allows dynamic storage keys,
89
- * custom serialization/deserialization, custom storage providers, and optional
90
- * synchronization across browser tabs.
91
- *
92
- * @template T The type of value held by the signal and stored (after serialization).
93
- * @param fallback The default value of type `T` to use when no value is found in storage
94
- * or when deserialization fails. The signal's value will never be `null` or `undefined`
95
- * publicly, it will always revert to this fallback.
96
- * @param options Configuration options (`CreateStoredOptions<T>`). Requires at least the `key`.
97
- * @returns A `StoredSignal<T>` instance. This signal behaves like a standard `WritableSignal<T>`,
98
- * but its value is persisted. It includes a `.clear()` method to remove the item from storage
99
- * and a `.key` signal providing the current storage key.
100
- *
101
- * @remarks
102
- * - **Persistence:** The signal automatically saves its value to storage whenever the signal's
103
- * value or its configured `key` changes. This is managed internally using `effect`.
104
- * - **SSR Safety:** Detects server environments and uses a no-op storage, preventing errors.
105
- * - **Error Handling:** Catches and logs errors during serialization/deserialization in dev mode.
106
- * - **Tab Sync:** If `syncTabs` is true, listens to `storage` events to keep the signal value
107
- * consistent across browser tabs using the same key. Cleanup is handled automatically
108
- * using `DestroyRef`.
109
- * - **Removal:** Use the `.clear()` method on the returned signal to remove the item from storage.
110
- * Setting the signal to the fallback value will store the fallback value, not remove the item.
111
- *
112
- * @example
113
- * ```ts
114
- * import { Component, effect, signal } from '@angular/core';
115
- * import { stored } from '@mmstack/primitives'; // Adjust import path
116
- *
117
- * @Component({
118
- * selector: 'app-settings',
119
- * standalone: true,
120
- * template: `
121
- * Theme:
122
- * <select [ngModel]="theme()" (ngModelChange)="theme.set($event)">
123
- * <option value="light">Light</option>
124
- * <option value="dark">Dark</option>
125
- * </select>
126
- * <button (click)="theme.clear()">Clear Theme Setting</button>
127
- * <p>Storage Key Used: {{ theme.key() }}</p>
128
- * ` // Requires FormsModule for ngModel
129
- * })
130
- * export class SettingsComponent {
131
- * theme = stored<'light' | 'dark'>('light', { key: 'app-theme', syncTabs: true });
132
- * }
133
- * ```
134
- */
135
- export declare function stored<T>(fallback: T, { key, store: providedStore, serialize, deserialize, syncTabs, equal, onKeyChange, cleanupOldKey, ...rest }: CreateStoredOptions<T>): StoredSignal<T>;
136
- export {};
@@ -1,75 +0,0 @@
1
- import { type CreateSignalOptions, DestroyRef, type WritableSignal } from '@angular/core';
2
- import { DebouncedSignal } from './debounced';
3
- /**
4
- * Options for creating a throttled writable signal.
5
- * Extends Angular's `CreateSignalOptions` with a throttle time setting.
6
- *
7
- * @template T The type of value held by the signal.
8
- */
9
- export type CreateThrottledOptions<T> = CreateSignalOptions<T> & {
10
- /**
11
- * The throttle delay in milliseconds. The minimum time
12
- * in milliseconds that must pass between updates to the throttled signal's value.
13
- */
14
- ms?: number;
15
- /**
16
- * Optional `DestroyRef` to clean up the throttle timer when the signal is destroyed.
17
- * If provided, the timer will be cleared when the signal is destroyed.
18
- * If the signal is called within a reactive context a DestroyRef is injected automatically.
19
- * If it is not provided or injected, the timer will not be cleared automatically...which is usually fine :)
20
- */
21
- destroyRef?: DestroyRef;
22
- };
23
- /**
24
- * A specialized `WritableSignal` whose publicly readable value updates are throttled.
25
- *
26
- * It provides access to the underlying, non-throttled signal via the `original` property.
27
- *
28
- * @template T The type of value held by the signal.
29
- * @see {DebouncedSignal} as the output type has the same structure.
30
- */
31
- export type ThrottledSignal<T> = DebouncedSignal<T>;
32
- /**
33
- * A convenience function that creates and throttles a new `WritableSignal` in one step.
34
- *
35
- * @see {throttle} for the core implementation details.
36
- *
37
- * @template T The type of value the signal holds.
38
- * @param initial The initial value of the signal.
39
- * @param opt Options for signal creation, including throttle time `ms`.
40
- * @returns A `ThrottledSignal<T>` instance.
41
- *
42
- * @example
43
- * const query = throttled('', { ms: 500 });
44
- * effect(() => console.log('Throttled Query:', query()));
45
- *
46
- * query.set('a');
47
- * query.set('b');
48
- * query.set('c');
49
- * // With a trailing-edge throttle, the final value 'c' would be set
50
- * // after the 500ms cooldown.
51
- */
52
- export declare function throttled<T>(initial: T, opt?: CreateThrottledOptions<T>): DebouncedSignal<T>;
53
- /**
54
- * Wraps an existing `WritableSignal` to create a new one whose readable value is throttled.
55
- *
56
- * This implementation avoids using `effect` by pairing a trigger signal with an `untracked`
57
- * read of the source signal to control when the throttled value is re-evaluated.
58
- *
59
- * @template T The type of value the signal holds.
60
- * @param source The source `WritableSignal` to wrap. Writes are applied to this signal immediately.
61
- * @param opt Options for throttling, including throttle time `ms` and an optional `DestroyRef`.
62
- * @returns A new `ThrottledSignal<T>` whose read value is throttled. The `.original` property
63
- * of the returned signal is a reference back to the provided `source` signal.
64
- *
65
- * @example
66
- * const query = throttled('', { ms: 500 });
67
- * effect(() => console.log('Throttled Query:', query()));
68
- *
69
- * query.set('a');
70
- * query.set('b');
71
- * query.set('c');
72
- * // With a trailing-edge throttle, the final value 'c' would be set
73
- * // after the 500ms cooldown.
74
- */
75
- export declare function throttle<T>(source: WritableSignal<T>, opt?: CreateThrottledOptions<T>): ThrottledSignal<T>;
@@ -1,30 +0,0 @@
1
- import { Signal, WritableSignal } from '@angular/core';
2
- /**
3
- * Converts a read-only `Signal` into a `WritableSignal` by providing custom `set` and, optionally, `update` functions.
4
- * This can be useful for creating controlled write access to a signal that is otherwise read-only.
5
- *
6
- * @typeParam T - The type of value held by the signal.
7
- *
8
- * @param signal - The read-only `Signal` to be made writable.
9
- * @param set - A function that will be used to set the signal's value. This function *must* handle
10
- * the actual update mechanism (e.g., updating a backing store, emitting an event, etc.).
11
- * @param update - (Optional) A function that will be used to update the signal's value based on its
12
- * previous value. If not provided, a default `update` implementation is used that
13
- * calls the provided `set` function with the result of the updater function. The
14
- * default implementation uses `untracked` to avoid creating unnecessary dependencies
15
- * within the updater function.
16
- *
17
- * @returns A `WritableSignal` that uses the provided `set` and `update` functions. The `asReadonly`
18
- * method of the returned signal will still return the original read-only signal.
19
- *
20
- * @example
21
- * // Basic usage: Making a read-only signal writable with a custom set function.
22
- * const originalValue = signal({a: 0});
23
- * const readOnlySignal = computed(() => originalValue().a);
24
- * const writableSignal = toWritable(readOnlySignal, (newValue) => {
25
- * originalValue.update((prev) => { ...prev, a: newValue });
26
- * });
27
- *
28
- * writableSignal.set(5); // sets value of originalValue.a to 5 & triggers all signals
29
- */
30
- export declare function toWritable<T>(signal: Signal<T>, set: (value: T) => void, update?: (updater: (value: T) => T) => void): WritableSignal<T>;
package/lib/until.d.ts DELETED
@@ -1,51 +0,0 @@
1
- import { DestroyRef, Injector, Signal } from '@angular/core';
2
- export type UntilOptions = {
3
- /**
4
- * Optional timeout in milliseconds. If the condition is not met
5
- * within this period, the promise will reject.
6
- */
7
- timeout?: number;
8
- /**
9
- * Optional DestroyRef. If provided and the component/context is destroyed
10
- * before the condition is met or timeout occurs, the promise will reject.
11
- * If not provided, it will attempt to inject one if called in an injection context.
12
- */
13
- destroyRef?: DestroyRef;
14
- injector?: Injector;
15
- };
16
- /**
17
- * Creates a Promise that resolves when a signal's value satisfies a given predicate.
18
- *
19
- * This is useful for imperatively waiting for a reactive state to change,
20
- * for example, in tests or to orchestrate complex asynchronous operations.
21
- *
22
- * @template T The type of the signal's value.
23
- * @param sourceSignal The signal to observe.
24
- * @param predicate A function that takes the signal's value and returns `true` if the condition is met.
25
- * @param options Optional configuration for timeout and explicit destruction.
26
- * @returns A Promise that resolves with the signal's value when the predicate is true,
27
- * or rejects on timeout or context destruction.
28
- *
29
- * @example
30
- * ```ts
31
- * const count = signal(0);
32
- *
33
- * async function waitForCount() {
34
- * console.log('Waiting for count to be >= 3...');
35
- * try {
36
- * const finalCount = await until(count, c => c >= 3, { timeout: 5000 });
37
- * console.log(`Count reached: ${finalCount}`);
38
- * } catch (e: any) { // Ensure 'e' is typed if you access properties like e.message
39
- * console.error(e.message); // e.g., "until: Timeout after 5000ms."
40
- * }
41
- * }
42
- *
43
- * // Simulate updates
44
- * setTimeout(() => count.set(1), 500);
45
- * setTimeout(() => count.set(2), 1000);
46
- * setTimeout(() => count.set(3), 1500);
47
- *
48
- * waitForCount();
49
- * ```
50
- */
51
- export declare function until<T>(sourceSignal: Signal<T>, predicate: (value: T) => boolean, options?: UntilOptions): Promise<T>;