@mmstack/primitives 19.0.5 → 19.1.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/LICENSE +21 -21
- package/README.md +239 -229
- package/fesm2022/mmstack-primitives.mjs +122 -53
- package/fesm2022/mmstack-primitives.mjs.map +1 -1
- package/index.d.ts +1 -0
- package/lib/debounced.d.ts +47 -34
- package/lib/with-history.d.ts +14 -0
- package/package.json +6 -6
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025-present Miha Mulec
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-present Miha J. Mulec
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,229 +1,239 @@
|
|
|
1
|
-
# @mmstack/primitives
|
|
2
|
-
|
|
3
|
-
A collection of utility functions and primitives designed to enhance development with Angular Signals, providing helpful patterns and inspired by features from other reactive libraries. All value helpers also use pure derivations (no effects/RxJS).
|
|
4
|
-
|
|
5
|
-
[](https://badge.fury.io/js/%40mmstack%2Fprimitives)
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
- `
|
|
19
|
-
- `
|
|
20
|
-
- `
|
|
21
|
-
- `
|
|
22
|
-
- `
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
import {
|
|
33
|
-
import {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
```
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
```
|
|
1
|
+
# @mmstack/primitives
|
|
2
|
+
|
|
3
|
+
A collection of utility functions and primitives designed to enhance development with Angular Signals, providing helpful patterns and inspired by features from other reactive libraries. All value helpers also use pure derivations (no effects/RxJS).
|
|
4
|
+
|
|
5
|
+
[](https://badge.fury.io/js/%40mmstack%2Fprimitives)
|
|
6
|
+
[](https://github.com/mihajm/mmstack/blob/master/packages/primitives/LICENSE)
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @mmstack/primitives
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Primitives
|
|
15
|
+
|
|
16
|
+
This library provides the following primitives:
|
|
17
|
+
|
|
18
|
+
- `debounced` - Creates a writable signal whose value updates are debounced after set/update.
|
|
19
|
+
- `mutable` - A signal variant allowing in-place mutations while triggering updates.
|
|
20
|
+
- `stored` - Creates a signal synchronized with persistent storage (e.g., localStorage).
|
|
21
|
+
- `mapArray` - Maps a reactive array efficently into an array of stable derivations.
|
|
22
|
+
- `toWritable` - Converts a read-only signal to writable using custom write logic.
|
|
23
|
+
- `derived` - Creates a signal with two-way binding to a source signal.
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
### debounced
|
|
28
|
+
|
|
29
|
+
Creates a WritableSignal where the propagation of its value (after calls to .set() or .update()) is delayed. The publicly readable signal value updates only after a specified time (ms) has passed without further set/update calls. It also includes an .original property, which is a Signal reflecting the value immediately after set/update is called.
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
import { Component, signal, effect } from '@angular/core';
|
|
33
|
+
import { debounced, debounce } from '@mmstack/primitives';
|
|
34
|
+
import { FormsModule } from '@angular/forms';
|
|
35
|
+
|
|
36
|
+
@Component({
|
|
37
|
+
selector: 'app-debounced',
|
|
38
|
+
template: `<input [(ngModel)]="searchTerm" />`,
|
|
39
|
+
})
|
|
40
|
+
export class SearchComponent {
|
|
41
|
+
searchTerm = debounced('', { ms: 300 }); // Debounce for 300ms
|
|
42
|
+
|
|
43
|
+
constructor() {
|
|
44
|
+
effect(() => {
|
|
45
|
+
// Runs 300ms after the user stops typing
|
|
46
|
+
console.log('Perform search for:', this.searchTerm());
|
|
47
|
+
});
|
|
48
|
+
effect(() => {
|
|
49
|
+
// Runs immediately on input change
|
|
50
|
+
console.log('Input value:', this.searchTerm.original());
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
You can also debounce an existing signal:
|
|
57
|
+
|
|
58
|
+
```typescript
|
|
59
|
+
import { debounce } from '@mmstack/primitives';
|
|
60
|
+
|
|
61
|
+
const query = signal('');
|
|
62
|
+
const debouncedQuery = debounce(query, { ms: 300 });
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### mutable
|
|
66
|
+
|
|
67
|
+
Creates a MutableSignal, a signal variant designed for scenarios where you want to perform in-place mutations on objects or arrays held within the signal, while still ensuring Angular's change detection is correctly triggered. It provides .mutate() and .inline() methods alongside the standard .set() and .update(). Please note that any computeds, which resolve non-primitive values from a mutable require equals to be set to false.
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
import { Component, computed, effect } from '@angular/core';
|
|
71
|
+
import { mutable } from '@mmstack/primitives';
|
|
72
|
+
import { FormsModule } from '@angular/forms';
|
|
73
|
+
|
|
74
|
+
@Component({
|
|
75
|
+
selector: 'app-mutable',
|
|
76
|
+
template: ` <button (click)="incrementAge()">inc</button> `,
|
|
77
|
+
})
|
|
78
|
+
export class SearchComponent {
|
|
79
|
+
user = mutable({ name: { first: 'John', last: 'Doe' }, age: 30 });
|
|
80
|
+
|
|
81
|
+
constructor() {
|
|
82
|
+
effect(() => {
|
|
83
|
+
// Runs every time user is mutated
|
|
84
|
+
console.log(this.user());
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const age = computed(() => this.user().age);
|
|
88
|
+
|
|
89
|
+
effect(() => {
|
|
90
|
+
// Runs every time age changes
|
|
91
|
+
console.log(age());
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
const name = computed(() => this.user().name);
|
|
95
|
+
effect(() => {
|
|
96
|
+
// Doesnt run if user changes, unless name is destructured
|
|
97
|
+
console.log(name());
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const name2 = computed(() => this.user().name, {
|
|
101
|
+
equal: () => false,
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
effect(() => {
|
|
105
|
+
// Runs every time user changes (even if name did not change)
|
|
106
|
+
console.log(name2());
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
incrementAge() {
|
|
111
|
+
user.mutate((prev) => {
|
|
112
|
+
prev.age++;
|
|
113
|
+
return prev;
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
incrementInline() {
|
|
118
|
+
user.inline((prev) => {
|
|
119
|
+
prev.age++;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### stored
|
|
126
|
+
|
|
127
|
+
Creates a WritableSignal whose state is automatically synchronized with persistent storage (like localStorage or sessionStorage), providing a fallback value when no data is found or fails to parse.
|
|
128
|
+
|
|
129
|
+
It handles Server-Side Rendering (SSR) gracefully, allows dynamic storage keys, custom serialization/deserialization, custom storage providers, and optional synchronization across browser tabs via the storage event. It returns a StoredSignal<T> which includes a .clear() method and a reactive .key signal.
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
import { Component, effect, signal } from '@angular/core';
|
|
133
|
+
import { stored } from '@mmstack/primitives';
|
|
134
|
+
// import { FormsModule } from '@angular/forms'; // Needed for ngModel
|
|
135
|
+
|
|
136
|
+
@Component({
|
|
137
|
+
selector: 'app-theme-selector',
|
|
138
|
+
standalone: true,
|
|
139
|
+
// imports: [FormsModule], // Import if using ngModel
|
|
140
|
+
template: `
|
|
141
|
+
Theme:
|
|
142
|
+
<select [value]="theme()" (change)="theme.set($event.target.value)">
|
|
143
|
+
<option value="light">Light</option>
|
|
144
|
+
<option value="dark">Dark</option>
|
|
145
|
+
<option value="system">System</option>
|
|
146
|
+
</select>
|
|
147
|
+
<button (click)="theme.clear()">Reset Theme</button>
|
|
148
|
+
<p>Using storage key: {{ theme.key() }}</p>
|
|
149
|
+
`,
|
|
150
|
+
})
|
|
151
|
+
export class ThemeSelectorComponent {
|
|
152
|
+
// Persist theme preference in localStorage, default to 'system'
|
|
153
|
+
theme = stored<'light' | 'dark' | 'system'>('system', {
|
|
154
|
+
key: 'user-theme',
|
|
155
|
+
syncTabs: true, // Sync theme choice across tabs
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
constructor() {
|
|
159
|
+
effect(() => {
|
|
160
|
+
console.log(`Theme set to: ${this.theme()}`);
|
|
161
|
+
// Logic to apply theme (e.g., add class to body)
|
|
162
|
+
document.body.className = `theme-${this.theme()}`;
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### mapArray
|
|
169
|
+
|
|
170
|
+
Reactive map helper that stabilizes a source array Signal by length. It provides stability by giving the mapping function a stable Signal<T> for each item based on its index. Sub signals are not re-created, rather they propagate value updates through. This is particularly useful for rendering lists (@for) as it minimizes DOM changes when array items change identity but represent the same conceptual entity.
|
|
171
|
+
|
|
172
|
+
```typescript
|
|
173
|
+
import { Component, signal } from '@angular/core';
|
|
174
|
+
import { mapArray } from '@mmstack/primitives';
|
|
175
|
+
|
|
176
|
+
@Component({
|
|
177
|
+
selector: 'app-map-demo',
|
|
178
|
+
template: `
|
|
179
|
+
<ul>
|
|
180
|
+
@for (item of displayItems(); track item) {
|
|
181
|
+
<li>{{ item() }}</li>
|
|
182
|
+
}
|
|
183
|
+
</ul>
|
|
184
|
+
<button (click)="addItem()">Add</button>
|
|
185
|
+
<button (click)="updateFirst()">Update First</button>
|
|
186
|
+
`,
|
|
187
|
+
})
|
|
188
|
+
export class ListComponent {
|
|
189
|
+
sourceItems = signal([
|
|
190
|
+
{ id: 1, name: 'A' },
|
|
191
|
+
{ id: 2, name: 'B' },
|
|
192
|
+
]);
|
|
193
|
+
|
|
194
|
+
readonly displayItems = mapArray(this.sourceItems, (child, index) => computed(() => `Item ${index}: ${child().name}`));
|
|
195
|
+
|
|
196
|
+
addItem() {
|
|
197
|
+
this.sourceItems.update((items) => [...items, { id: Date.now(), name: String.fromCharCode(67 + items.length - 2) }]);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
updateFirst() {
|
|
201
|
+
this.sourceItems.update((items) => {
|
|
202
|
+
items[0] = { ...items[0], name: items[0].name + '+' };
|
|
203
|
+
return [...items]; // New array, but mapArray keeps stable signals
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### toWritable
|
|
210
|
+
|
|
211
|
+
A utility function that converts a read-only Signal into a WritableSignal by allowing you to provide custom implementations for the .set() and .update() methods. This is useful for creating controlled write access to signals that are naturally read-only (like those created by computed). This is used under the hood in derived.
|
|
212
|
+
|
|
213
|
+
```typescript
|
|
214
|
+
import { Component, signal, effect } from '@angular/core';
|
|
215
|
+
import { toWritable } from '@mmstack/primitives';
|
|
216
|
+
|
|
217
|
+
const user = signal({ name: 'John' });
|
|
218
|
+
|
|
219
|
+
const name = toWritable(
|
|
220
|
+
computed(() => user().name),
|
|
221
|
+
(name) => user.update((prev) => ({ ...prev, name })),
|
|
222
|
+
); // WritableSignal<string> bound to user signal
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### derived
|
|
226
|
+
|
|
227
|
+
Creates a WritableSignal that represents a part of another source WritableSignal (e.g., an object property or an array element), enabling two-way data binding. Changes to the source update the derived signal, and changes to the derived signal (via .set() or .update()) update the source signal accordingly.
|
|
228
|
+
|
|
229
|
+
```typescript
|
|
230
|
+
const user = signal({ name: 'John' });
|
|
231
|
+
|
|
232
|
+
const name = derived(user, 'name'); // WritableSignal<string>, which updates user signal & reacts to changes in the name property
|
|
233
|
+
|
|
234
|
+
// Full syntax example
|
|
235
|
+
const name2 = derived(user, {
|
|
236
|
+
from: (u) => u.name,
|
|
237
|
+
onChange: (name) => user.update((prev) => ({ ...prev, name })),
|
|
238
|
+
});
|
|
239
|
+
```
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { untracked, signal, computed, isSignal, linkedSignal,
|
|
1
|
+
import { untracked, signal, inject, DestroyRef, computed, isSignal, linkedSignal, PLATFORM_ID, isDevMode, effect } from '@angular/core';
|
|
2
2
|
import { isPlatformServer } from '@angular/common';
|
|
3
|
+
import { SIGNAL } from '@angular/core/primitives/signals';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Converts a read-only `Signal` into a `WritableSignal` by providing custom `set` and, optionally, `update` functions.
|
|
@@ -38,87 +39,100 @@ function toWritable(signal, set, update) {
|
|
|
38
39
|
}
|
|
39
40
|
|
|
40
41
|
/**
|
|
41
|
-
*
|
|
42
|
-
* a specified debounce period (`ms`) has passed since the last call to its
|
|
43
|
-
* `.set()` or `.update()` method.
|
|
42
|
+
* A convenience function that creates and debounces a new `WritableSignal` in one step.
|
|
44
43
|
*
|
|
45
|
-
*
|
|
46
|
-
* signals and a custom `equal` function to delay value propagation based on a timer.
|
|
44
|
+
* @see {debounce} for the core implementation details.
|
|
47
45
|
*
|
|
48
46
|
* @template T The type of value the signal holds.
|
|
49
47
|
* @param initial The initial value of the signal.
|
|
50
|
-
* @param opt Options for signal creation, including
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
* @
|
|
54
|
-
*
|
|
48
|
+
* @param opt Options for signal creation, including debounce time `ms`.
|
|
49
|
+
* @returns A `DebouncedSignal<T>` instance.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* // The existing example remains perfect here.
|
|
53
|
+
* const query = debounced('', { ms: 500 });
|
|
54
|
+
* effect(() => console.log('Debounced Query:', query()));
|
|
55
|
+
* query.set('abc');
|
|
56
|
+
* // ...500ms later...
|
|
57
|
+
* // Output: Debounced Query: abc
|
|
58
|
+
*/
|
|
59
|
+
function debounced(initial, opt) {
|
|
60
|
+
return debounce(signal(initial, opt), opt);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Wraps an existing `WritableSignal` to create a new one whose readable value is debounced.
|
|
64
|
+
*
|
|
65
|
+
* This implementation avoids using `effect` by pairing a trigger signal with an `untracked`
|
|
66
|
+
* read of the source signal to control when the debounced value is re-evaluated.
|
|
67
|
+
*
|
|
68
|
+
* @template T The type of value the signal holds.
|
|
69
|
+
* @param source The source `WritableSignal` to wrap. Writes are applied to this signal immediately.
|
|
70
|
+
* @param opt Options for debouncing, including debounce time `ms` and an optional `DestroyRef`.
|
|
71
|
+
* @returns A new `DebouncedSignal<T>` whose read value is debounced. The `.original` property
|
|
72
|
+
* of the returned signal is a reference back to the provided `source` signal.
|
|
55
73
|
*
|
|
56
74
|
* @example
|
|
57
75
|
* ```ts
|
|
58
|
-
* import { effect } from '@angular/core';
|
|
76
|
+
* import { signal, effect } from '@angular/core';
|
|
59
77
|
*
|
|
60
|
-
* // Create a
|
|
61
|
-
* const
|
|
78
|
+
* // 1. Create a standard source signal.
|
|
79
|
+
* const sourceQuery = signal('');
|
|
80
|
+
*
|
|
81
|
+
* // 2. Create a debounced version of it.
|
|
82
|
+
* const debouncedQuery = debounce(sourceQuery, { ms: 500 });
|
|
62
83
|
*
|
|
84
|
+
* // This effect tracks the original signal and runs immediately.
|
|
63
85
|
* effect(() => {
|
|
64
|
-
*
|
|
65
|
-
* console.log('Debounced Query:', query());
|
|
86
|
+
* console.log('Original Query:', debouncedQuery.original());
|
|
66
87
|
* });
|
|
67
88
|
*
|
|
89
|
+
* // This effect tracks the debounced signal and runs after the delay.
|
|
68
90
|
* effect(() => {
|
|
69
|
-
*
|
|
70
|
-
* console.log('Original Query:', query.original());
|
|
91
|
+
* console.log('Debounced Query:', debouncedQuery());
|
|
71
92
|
* });
|
|
72
93
|
*
|
|
73
94
|
* console.log('Setting query to "a"');
|
|
74
|
-
*
|
|
95
|
+
* debouncedQuery.set('a');
|
|
75
96
|
* // Output: Original Query: a
|
|
76
97
|
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
* query.set('ab');
|
|
80
|
-
* // Output: Original Query: ab
|
|
81
|
-
* }, 200); // Before debounce timeout
|
|
82
|
-
*
|
|
83
|
-
* setTimeout(() => {
|
|
84
|
-
* console.log('Setting query to "abc"');
|
|
85
|
-
* query.set('abc');
|
|
86
|
-
* // Output: Original Query: abc
|
|
87
|
-
* }, 400); // Before debounce timeout
|
|
88
|
-
*
|
|
89
|
-
* // ~500ms after the *last* set (at 400ms), the debounced effect runs:
|
|
90
|
-
* // Output (at ~900ms): Debounced Query: abc
|
|
98
|
+
* // ...500ms later...
|
|
99
|
+
* // Output: Debounced Query: a
|
|
91
100
|
* ```
|
|
92
101
|
*/
|
|
93
|
-
function
|
|
94
|
-
const
|
|
95
|
-
const ms = opt.ms ?? 0;
|
|
102
|
+
function debounce(source, opt) {
|
|
103
|
+
const ms = opt?.ms ?? 0;
|
|
96
104
|
const trigger = signal(false);
|
|
97
105
|
let timeout;
|
|
98
|
-
|
|
106
|
+
try {
|
|
107
|
+
const destroyRef = opt?.destroyRef ?? inject(DestroyRef, { optional: true });
|
|
108
|
+
destroyRef?.onDestroy(() => {
|
|
109
|
+
if (timeout)
|
|
110
|
+
clearTimeout(timeout);
|
|
111
|
+
timeout = undefined;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
// not in injection context & no destroyRef provided opting out of cleanup
|
|
116
|
+
}
|
|
117
|
+
const triggerFn = (afterClean) => {
|
|
99
118
|
if (timeout)
|
|
100
119
|
clearTimeout(timeout);
|
|
101
|
-
|
|
120
|
+
afterClean();
|
|
102
121
|
timeout = setTimeout(() => {
|
|
103
122
|
trigger.update((c) => !c);
|
|
104
123
|
}, ms);
|
|
105
124
|
};
|
|
125
|
+
const set = (value) => {
|
|
126
|
+
triggerFn(() => source.set(value));
|
|
127
|
+
};
|
|
106
128
|
const update = (fn) => {
|
|
107
|
-
|
|
108
|
-
clearTimeout(timeout);
|
|
109
|
-
internal.update(fn);
|
|
110
|
-
timeout = setTimeout(() => {
|
|
111
|
-
trigger.update((c) => !c);
|
|
112
|
-
}, ms);
|
|
129
|
+
triggerFn(() => source.update(fn));
|
|
113
130
|
};
|
|
114
|
-
const
|
|
115
|
-
trigger
|
|
116
|
-
|
|
117
|
-
}),
|
|
118
|
-
|
|
119
|
-
});
|
|
120
|
-
const writable = toWritable(computed(() => stable().value, opt), set, update);
|
|
121
|
-
writable.original = internal;
|
|
131
|
+
const writable = toWritable(computed(() => {
|
|
132
|
+
trigger();
|
|
133
|
+
return untracked(source);
|
|
134
|
+
}, opt), set, update);
|
|
135
|
+
writable.original = source;
|
|
122
136
|
return writable;
|
|
123
137
|
}
|
|
124
138
|
|
|
@@ -446,9 +460,64 @@ function stored(fallback, { key, store: providedStore, serialize = JSON.stringif
|
|
|
446
460
|
return writable;
|
|
447
461
|
}
|
|
448
462
|
|
|
463
|
+
function withHistory(source, opt) {
|
|
464
|
+
const { equal = Object.is, debugName } = source[SIGNAL];
|
|
465
|
+
const maxSize = opt?.maxSize ?? Infinity;
|
|
466
|
+
const history = mutable([], opt);
|
|
467
|
+
const redoArray = mutable([]);
|
|
468
|
+
const set = (value) => {
|
|
469
|
+
const current = untracked(source);
|
|
470
|
+
if (equal(value, current))
|
|
471
|
+
return;
|
|
472
|
+
source.set(value);
|
|
473
|
+
history.mutate((c) => {
|
|
474
|
+
if (c.length >= maxSize) {
|
|
475
|
+
c = c.slice(Math.floor(maxSize / 2));
|
|
476
|
+
}
|
|
477
|
+
c.push(current);
|
|
478
|
+
return c;
|
|
479
|
+
});
|
|
480
|
+
redoArray.set([]);
|
|
481
|
+
};
|
|
482
|
+
const update = (updater) => {
|
|
483
|
+
set(updater(untracked(source)));
|
|
484
|
+
};
|
|
485
|
+
const internal = toWritable(computed(() => source(), {
|
|
486
|
+
equal,
|
|
487
|
+
debugName,
|
|
488
|
+
}), set, update);
|
|
489
|
+
internal.history = history;
|
|
490
|
+
internal.undo = () => {
|
|
491
|
+
const last = untracked(history);
|
|
492
|
+
if (last.length === 0)
|
|
493
|
+
return;
|
|
494
|
+
const prev = last.at(-1);
|
|
495
|
+
const cur = untracked(source);
|
|
496
|
+
history.inline((c) => c.pop());
|
|
497
|
+
redoArray.inline((c) => c.push(cur));
|
|
498
|
+
source.set(prev);
|
|
499
|
+
};
|
|
500
|
+
internal.redo = () => {
|
|
501
|
+
const last = untracked(redoArray);
|
|
502
|
+
if (last.length === 0)
|
|
503
|
+
return;
|
|
504
|
+
const prev = last.at(-1);
|
|
505
|
+
redoArray.inline((c) => c.pop());
|
|
506
|
+
set(prev);
|
|
507
|
+
};
|
|
508
|
+
internal.clear = () => {
|
|
509
|
+
history.set([]);
|
|
510
|
+
redoArray.set([]);
|
|
511
|
+
};
|
|
512
|
+
internal.canUndo = computed(() => history().length > 0);
|
|
513
|
+
internal.canRedo = computed(() => redoArray().length > 0);
|
|
514
|
+
internal.canClear = computed(() => internal.canUndo() || internal.canRedo());
|
|
515
|
+
return internal;
|
|
516
|
+
}
|
|
517
|
+
|
|
449
518
|
/**
|
|
450
519
|
* Generated bundle index. Do not edit.
|
|
451
520
|
*/
|
|
452
521
|
|
|
453
|
-
export { debounced, derived, isDerivation, isMutable, mapArray, mutable, stored, toFakeDerivation, toFakeSignalDerivation, toWritable };
|
|
522
|
+
export { debounce, debounced, derived, isDerivation, isMutable, mapArray, mutable, stored, toFakeDerivation, toFakeSignalDerivation, toWritable, withHistory };
|
|
454
523
|
//# sourceMappingURL=mmstack-primitives.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mmstack-primitives.mjs","sources":["../../../../packages/primitives/src/lib/to-writable.ts","../../../../packages/primitives/src/lib/debounced.ts","../../../../packages/primitives/src/lib/derived.ts","../../../../packages/primitives/src/lib/map-array.ts","../../../../packages/primitives/src/lib/mutable.ts","../../../../packages/primitives/src/lib/stored.ts","../../../../packages/primitives/src/mmstack-primitives.ts"],"sourcesContent":["import { Signal, untracked, WritableSignal } from '@angular/core';\n\n/**\n * Converts a read-only `Signal` into a `WritableSignal` by providing custom `set` and, optionally, `update` functions.\n * This can be useful for creating controlled write access to a signal that is otherwise read-only.\n *\n * @typeParam T - The type of value held by the signal.\n *\n * @param signal - The read-only `Signal` to be made writable.\n * @param set - A function that will be used to set the signal's value. This function *must* handle\n * the actual update mechanism (e.g., updating a backing store, emitting an event, etc.).\n * @param update - (Optional) A function that will be used to update the signal's value based on its\n * previous value. If not provided, a default `update` implementation is used that\n * calls the provided `set` function with the result of the updater function. The\n * default implementation uses `untracked` to avoid creating unnecessary dependencies\n * within the updater function.\n *\n * @returns A `WritableSignal` that uses the provided `set` and `update` functions. The `asReadonly`\n * method of the returned signal will still return the original read-only signal.\n *\n * @example\n * // Basic usage: Making a read-only signal writable with a custom set function.\n * const originalValue = signal({a: 0});\n * const readOnlySignal = computed(() => originalValue().a);\n * const writableSignal = toWritable(readOnlySignal, (newValue) => {\n * originalValue.update((prev) => { ...prev, a: newValue });\n * });\n *\n * writableSignal.set(5); // sets value of originalValue.a to 5 & triggers all signals\n */\nexport function toWritable<T>(\n signal: Signal<T>,\n set: (value: T) => void,\n update?: (updater: (value: T) => T) => void,\n): WritableSignal<T> {\n const internal = signal as WritableSignal<T>;\n internal.asReadonly = () => signal;\n internal.set = set;\n internal.update = update ?? ((updater) => set(updater(untracked(internal))));\n\n return internal;\n}\n","import {\n computed,\n type CreateSignalOptions,\n type Signal,\n signal,\n type WritableSignal,\n} from '@angular/core';\nimport { toWritable } from './to-writable';\n\n/**\n * Options for creating a debounced writable signal.\n * Extends Angular's `CreateSignalOptions` with a debounce time setting.\n *\n * @template T The type of value held by the signal.\n */\nexport type CreateDebouncedOptions<T> = CreateSignalOptions<T> & {\n /**\n * The debounce delay in milliseconds. Specifies how long to wait after the\n * last `set` or `update` call before the debounced signal reflects the new value.\n */\n ms?: number;\n};\n\n/**\n * A specialized `WritableSignal` whose publicly readable value updates are debounced.\n *\n * It provides access to the underlying, non-debounced signal via the `original` property.\n *\n * @template T The type of value held by the signal.\n */\nexport type DebouncedSignal<T> = WritableSignal<T> & {\n /**\n * A reference to the original, inner `WritableSignal`.\n * This signal's value is updated *immediately* upon calls to `set` or `update`\n * on the parent `DebouncedSignal`. Useful for accessing the latest value\n * without the debounce delay.\n */\n original: Signal<T>;\n};\n\n/**\n * Creates a `WritableSignal` whose publicly readable value is updated only after\n * a specified debounce period (`ms`) has passed since the last call to its\n * `.set()` or `.update()` method.\n *\n * This implementation avoids using `effect` by leveraging intermediate `computed`\n * signals and a custom `equal` function to delay value propagation based on a timer.\n *\n * @template T The type of value the signal holds.\n * @param initial The initial value of the signal.\n * @param opt Options for signal creation, including:\n * - `ms`: The debounce time in milliseconds. Defaults to 0 if omitted (no debounce).\n * - Other `CreateSignalOptions` (like `equal`) are passed to underlying signals.\n * @returns A `DebouncedSignal<T>` instance. Its readable value updates are debounced,\n * and it includes an `.original` property providing immediate access to the latest set value.\n *\n * @example\n * ```ts\n * import { effect } from '@angular/core';\n *\n * // Create a debounced signal with a 500ms delay\n * const query = debounced('', { ms: 500 });\n *\n * effect(() => {\n * // This effect runs 500ms after the last change to 'query'\n * console.log('Debounced Query:', query());\n * });\n *\n * effect(() => {\n * // This effect runs immediately when 'query.original' changes\n * console.log('Original Query:', query.original());\n * });\n *\n * console.log('Setting query to \"a\"');\n * query.set('a');\n * // Output: Original Query: a\n *\n * setTimeout(() => {\n * console.log('Setting query to \"ab\"');\n * query.set('ab');\n * // Output: Original Query: ab\n * }, 200); // Before debounce timeout\n *\n * setTimeout(() => {\n * console.log('Setting query to \"abc\"');\n * query.set('abc');\n * // Output: Original Query: abc\n * }, 400); // Before debounce timeout\n *\n * // ~500ms after the *last* set (at 400ms), the debounced effect runs:\n * // Output (at ~900ms): Debounced Query: abc\n * ```\n */\nexport function debounced<T>(\n initial: T,\n opt: CreateDebouncedOptions<T>,\n): DebouncedSignal<T> {\n const internal = signal(initial, opt);\n const ms = opt.ms ?? 0;\n\n const trigger = signal(false);\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const set = (value: T) => {\n if (timeout) clearTimeout(timeout);\n internal.set(value);\n\n timeout = setTimeout(() => {\n trigger.update((c) => !c);\n }, ms);\n };\n\n const update = (fn: (prev: T) => T) => {\n if (timeout) clearTimeout(timeout);\n internal.update(fn);\n\n timeout = setTimeout(() => {\n trigger.update((c) => !c);\n }, ms);\n };\n\n const stable = computed(\n () => ({\n trigger: trigger(),\n value: internal(),\n }),\n {\n equal: (a, b) => a.trigger === b.trigger,\n },\n );\n\n const writable = toWritable(\n computed(() => stable().value, opt),\n set,\n update,\n ) as DebouncedSignal<T>;\n writable.original = internal;\n\n return writable;\n}\n","import {\n computed,\n CreateSignalOptions,\n signal,\n untracked,\n type WritableSignal,\n} from '@angular/core';\nimport type { UnknownObject } from '@mmstack/object';\nimport { toWritable } from './to-writable';\n\n/**\n * Options for creating a derived signal using the full `derived` function signature.\n * @typeParam T - The type of the source signal's value (parent).\n * @typeParam U - The type of the derived signal's value (child).\n */\ntype CreateDerivedOptions<T, U> = CreateSignalOptions<U> & {\n /**\n * A function that extracts the derived value (`U`) from the source signal's value (`T`).\n */\n from: (v: T) => U;\n /**\n * A function that updates the source signal's value (`T`) when the derived signal's value (`U`) changes.\n * This establishes the two-way binding.\n */\n onChange: (newValue: U) => void;\n};\n\n/**\n * A `WritableSignal` that derives its value from another `WritableSignal` (the \"source\" signal).\n * It provides two-way binding: changes to the source signal update the derived signal, and\n * changes to the derived signal update the source signal.\n *\n * @typeParam T - The type of the source signal's value (parent).\n * @typeParam U - The type of the derived signal's value (child).\n */\nexport type DerivedSignal<T, U> = WritableSignal<U> & {\n /**\n * The function used to derive the derived signal's value from the source signal's value.\n * This is primarily for internal use and introspection.\n */\n from: (v: T) => U;\n};\n\n/**\n * Creates a `DerivedSignal` that derives its value from another `WritableSignal` (the source signal).\n * This overload provides the most flexibility, allowing you to specify custom `from` and `onChange` functions.\n *\n * @typeParam T - The type of the source signal's value.\n * @typeParam U - The type of the derived signal's value.\n * @param source - The source `WritableSignal`.\n * @param options - An object containing the `from` and `onChange` functions, and optional signal options.\n * @returns A `DerivedSignal` instance.\n *\n * @example\n * const user = signal({ name: 'John', age: 30 });\n * const name = derived(user, {\n * from: (u) => u.name,\n * onChange: (newName) => user.update((u) => ({ ...u, name: newName })),\n * });\n */\nexport function derived<T, U>(\n source: WritableSignal<T>,\n opt: CreateDerivedOptions<T, U>,\n): DerivedSignal<T, U>;\n\n/**\n * Creates a `DerivedSignal` that derives a property from an object held by the source signal.\n * This overload simplifies creating derived signals for object properties.\n *\n * @typeParam T - The type of the source signal's value (must be an object).\n * @typeParam TKey - The key of the property to derive.\n * @param source - The source `WritableSignal` (holding an object).\n * @param key - The key of the property to derive.\n * @param options - Optional signal options for the derived signal.\n * @returns A `DerivedSignal` instance.\n *\n * @example\n * const user = signal({ name: 'John', age: 30 });\n * const name = derived(user, 'name');\n */\nexport function derived<T extends UnknownObject, TKey extends keyof T>(\n source: WritableSignal<T>,\n key: TKey,\n opt?: CreateSignalOptions<T[TKey]>,\n): DerivedSignal<T, T[TKey]>;\n\n/**\n * Creates a `DerivedSignal` from an array, and derives an element by index.\n *\n * @typeParam T - The type of the source signal's value (must be an array).\n * @param source - The source `WritableSignal` (holding an array).\n * @param index - The index of the element to derive.\n * @param options - Optional signal options for the derived signal.\n * @returns A `DerivedSignal` instance.\n *\n * @example\n * const numbers = signal([1, 2, 3]);\n * const secondNumber = derived(numbers, 1); // secondNumber() === 2\n * secondNumber.set(5); // numbers() === [1, 5, 3]\n */\nexport function derived<T extends any[]>(\n source: WritableSignal<T>,\n index: number,\n opt?: CreateSignalOptions<T[number]>,\n): DerivedSignal<T, T[number]>;\n\nexport function derived<T, U>(\n source: WritableSignal<T>,\n optOrKey: CreateDerivedOptions<T, U> | keyof T,\n opt?: CreateSignalOptions<U>,\n): DerivedSignal<T, U> {\n const isArray =\n Array.isArray(untracked(source)) && typeof optOrKey === 'number';\n\n const from =\n typeof optOrKey === 'object' ? optOrKey.from : (v: T) => v[optOrKey] as U;\n const onChange =\n typeof optOrKey === 'object'\n ? optOrKey.onChange\n : isArray\n ? (next: U) => {\n source.update(\n (cur) =>\n (cur as unknown as any[]).map((v, i) =>\n i === optOrKey ? next : v,\n ) as T,\n );\n }\n : (next: U) => {\n source.update((cur) => ({ ...cur, [optOrKey]: next }));\n };\n\n const rest = typeof optOrKey === 'object' ? optOrKey : opt;\n\n const sig = toWritable<U>(\n computed(() => from(source()), rest),\n (newVal) => onChange(newVal),\n ) as DerivedSignal<T, U>;\n\n sig.from = from;\n\n return sig;\n}\n\n/**\n * Creates a \"fake\" `DerivedSignal` from a simple value. This is useful for creating\n * `FormControlSignal` instances that are not directly derived from another signal.\n * The returned signal's `from` function will always return the initial value.\n *\n * @typeParam T - This type parameter is not used in the implementation but is kept for type compatibility with `DerivedSignal`.\n * @typeParam U - The type of the signal's value.\n * @param initial - The initial value of the signal.\n * @returns A `DerivedSignal` instance.\n * @internal\n */\nexport function toFakeDerivation<T, U>(initial: U): DerivedSignal<T, U> {\n const sig = signal(initial) as DerivedSignal<T, U>;\n sig.from = () => initial;\n\n return sig;\n}\n\n/**\n * Creates a \"fake\" `DerivedSignal` from an existing `WritableSignal`. This is useful\n * for treating a regular `WritableSignal` as a `DerivedSignal` without changing its behavior.\n * The returned signal's `from` function returns the current value of signal, using `untracked`.\n *\n * @typeParam T - This type parameter is not used in the implementation but is kept for type compatibility with `DerivedSignal`.\n * @typeParam U - The type of the signal's value.\n * @param initial - The existing `WritableSignal`.\n * @returns A `DerivedSignal` instance.\n * @internal\n */\nexport function toFakeSignalDerivation<T, U>(\n initial: WritableSignal<U>,\n): DerivedSignal<T, U> {\n const sig = initial as DerivedSignal<T, U>;\n sig.from = () => untracked(initial);\n return sig;\n}\n\n/**\n * Type guard function to check if a given `WritableSignal` is a `DerivedSignal`.\n *\n * @typeParam T - The type of the source signal's value (optional, defaults to `any`).\n * @typeParam U - The type of the derived signal's value (optional, defaults to `any`).\n * @param sig - The `WritableSignal` to check.\n * @returns `true` if the signal is a `DerivedSignal`, `false` otherwise.\n */\nexport function isDerivation<T, U>(\n sig: WritableSignal<U>,\n): sig is DerivedSignal<T, U> {\n return 'from' in sig;\n}\n","import {\n computed,\n type CreateSignalOptions,\n isSignal,\n linkedSignal,\n type Signal,\n} from '@angular/core';\n\n/**\n * Reactively maps items from a source array (or signal of an array) using a provided mapping function.\n *\n * This function serves a similar purpose to SolidJS's `mapArray` by providing stability\n * for mapped items. It receives a source function returning an array (or a Signal<T[]>)\n * and a mapping function.\n *\n * For each item in the source array, it creates a stable `computed` signal representing\n * that item's value at its current index. This stable signal (`Signal<T>`) is passed\n * to the mapping function. This ensures that downstream computations or components\n * depending on the mapped result only re-render or re-calculate for the specific items\n * that have changed, or when items are added/removed, rather than re-evaluating everything\n * when the source array reference changes but items remain the same.\n *\n * It efficiently handles changes in the source array's length by reusing existing mapped\n * results when possible, slicing when the array shrinks, and appending new mapped items\n * when it grows.\n *\n * @template T The type of items in the source array.\n * @template U The type of items in the resulting mapped array.\n *\n * @param source A function returning the source array `T[]`, or a `Signal<T[]>` itself.\n * The `mapArray` function will reactively update based on changes to this source.\n * @param map The mapping function. It is called for each item in the source array.\n * It receives:\n * - `value`: A stable `Signal<T>` representing the item at the current index.\n * Use this signal within your mapping logic if you need reactivity\n * tied to the specific item's value changes.\n * - `index`: The number index of the item in the array.\n * It should return the mapped value `U`.\n * @param [opt] Optional `CreateSignalOptions<T>`. These options are passed directly\n * to the `computed` signal created for each individual item (`Signal<T>`).\n * This allows specifying options like a custom `equal` function for item comparison.\n *\n * @returns A `Signal<U[]>` containing the mapped array. This signal updates whenever\n * the source array changes (either length or the values of its items).\n *\n * @example\n * ```ts\n * const sourceItems = signal([\n * { id: 1, name: 'Apple' },\n * { id: 2, name: 'Banana' }\n * ]);\n *\n * const mappedItems = mapArray(\n * sourceItems,\n * (itemSignal, index) => {\n * // itemSignal is stable for a given item based on its index.\n * // We create a computed here to react to changes in the item's name.\n * return computed(() => `${index}: ${itemSignal().name.toUpperCase()}`);\n * },\n * // Example optional options (e.g., custom equality for item signals)\n * { equal: (a, b) => a.id === b.id && a.name === b.name }\n * );\n * ```\n */\nexport function mapArray<T, U>(\n source: () => T[],\n map: (value: Signal<T>, index: number) => U,\n opt?: CreateSignalOptions<T>,\n): Signal<U[]> {\n const data = isSignal(source) ? source : computed(source);\n const len = computed(() => data().length);\n\n return linkedSignal<number, U[]>({\n source: () => len(),\n computation: (len, prev) => {\n if (!prev)\n return Array.from({ length: len }, (_, i) =>\n map(\n computed(() => source()[i], opt),\n i,\n ),\n );\n\n if (len === prev.value.length) return prev.value;\n\n if (len < prev.value.length) {\n return prev.value.slice(0, len);\n } else {\n const next = [...prev.value];\n for (let i = prev.value.length; i < len; i++) {\n next[i] = map(\n computed(() => source()[i], opt),\n i,\n );\n }\n return next;\n }\n },\n equal: (a, b) => a.length === b.length,\n });\n}\n","import {\r\n signal,\r\n type CreateSignalOptions,\r\n type ValueEqualityFn,\r\n type WritableSignal,\r\n} from '@angular/core';\r\n\r\nconst { is } = Object;\r\n\r\n/**\r\n * A `MutableSignal` is a special type of `WritableSignal` that allows for in-place mutation of its value.\r\n * In addition to the standard `set` and `update` methods, it provides a `mutate` method. This is useful\r\n * for performance optimization when dealing with complex objects or arrays, as it avoids unnecessary\r\n * object copying.\r\n *\r\n * @typeParam T - The type of value held by the signal.\r\n */\r\nexport type MutableSignal<T> = WritableSignal<T> & {\r\n /**\r\n * Mutates the signal's value in-place. This is similar to `update`, but it's optimized for\r\n * scenarios where you want to modify the existing object directly rather than creating a new one.\r\n *\r\n * @param updater - A function that takes the current value as input and modifies it directly.\r\n *\r\n * @example\r\n * const myArray = mutable([1, 2, 3]);\r\n * myArray.mutate((arr) => {\r\n * arr.push(4);\r\n * return arr;\r\n * }); // myArray() now returns [1, 2, 3, 4]\r\n */\r\n mutate: WritableSignal<T>['update'];\r\n\r\n /**\r\n * Mutates the signal's value in-place, similar to `mutate`, but with a void-returning value in updater\r\n * function. This further emphasizes that the mutation is happening inline, improving readability\r\n * in some cases.\r\n * @param updater - Function to change to the current value\r\n * @example\r\n * const myObject = mutable({ a: 1, b: 2 });\r\n * myObject.inline((obj) => (obj.a = 3)); // myObject() now returns { a: 3, b: 2 }\r\n */\r\n inline: (updater: (value: T) => void) => void;\r\n};\r\n\r\n/**\r\n * Creates a `MutableSignal`. This function overloads the standard `signal` function to provide\r\n * the additional `mutate` and `inline` methods.\r\n *\r\n * @typeParam T - The type of value held by the signal.\r\n *\r\n * @param initial - The initial value of the signal. If no initial value is provided, it defaults to `undefined`.\r\n * @param options - Optional. An object containing signal options, including a custom equality function (`equal`).\r\n *\r\n * @returns A `MutableSignal` instance.\r\n *\r\n * @example\r\n * // Create a mutable signal with an initial value:\r\n * const mySignal = mutable({ count: 0 }) // MutableSignal<{ count: number }>;\r\n *\r\n * // Create a mutable signal with no initial value (starts as undefined):\r\n * const = mutable<number>(); // MutableSignal<number | undefined>\r\n *\r\n * // Create a mutable signal with a custom equality function:\r\n * const myCustomSignal = mutable({ a: 1 }, { equal: (a, b) => a.a === b.a });\r\n */\r\nexport function mutable<T>(): MutableSignal<T | undefined>;\r\nexport function mutable<T>(initial: T): MutableSignal<T>;\r\nexport function mutable<T>(\r\n initial: T,\r\n opt?: CreateSignalOptions<T>,\r\n): MutableSignal<T>;\r\n\r\nexport function mutable<T>(\r\n initial?: T,\r\n opt?: CreateSignalOptions<T>,\r\n): MutableSignal<T> {\r\n const baseEqual = opt?.equal ?? is;\r\n let trigger = false;\r\n\r\n const equal: ValueEqualityFn<T | undefined> = (a, b) => {\r\n if (trigger) return false;\r\n return baseEqual(a, b);\r\n };\r\n\r\n const sig = signal<T | undefined>(initial, {\r\n ...opt,\r\n equal,\r\n }) as MutableSignal<T>;\r\n\r\n const internalUpdate = sig.update;\r\n\r\n sig.mutate = (updater) => {\r\n trigger = true;\r\n internalUpdate(updater);\r\n trigger = false;\r\n };\r\n\r\n sig.inline = (updater) => {\r\n sig.mutate((prev) => {\r\n updater(prev);\r\n return prev;\r\n });\r\n };\r\n\r\n return sig;\r\n}\r\n\r\n/**\r\n * Type guard function to check if a given `WritableSignal` is a `MutableSignal`. This is useful\r\n * for situations where you need to conditionally use the `mutate` or `inline` methods.\r\n *\r\n * @typeParam T - The type of the signal's value (optional, defaults to `any`).\r\n * @param value - The `WritableSignal` to check.\r\n * @returns `true` if the signal is a `MutableSignal`, `false` otherwise.\r\n *\r\n * @example\r\n * const mySignal = signal(0);\r\n * const myMutableSignal = mutable(0);\r\n *\r\n * if (isMutable(mySignal)) {\r\n * mySignal.mutate(x => x + 1); // This would cause a type error, as mySignal is not a MutableSignal.\r\n * }\r\n *\r\n * if (isMutable(myMutableSignal)) {\r\n * myMutableSignal.mutate(x => x + 1); // This is safe.\r\n * }\r\n */\r\nexport function isMutable<T = any>(\r\n value: WritableSignal<T>,\r\n): value is MutableSignal<T> {\r\n return 'mutate' in value && typeof value.mutate === 'function';\r\n}\r\n","import { isPlatformServer } from '@angular/common';\nimport {\n computed,\n DestroyRef,\n effect,\n inject,\n isDevMode,\n isSignal,\n PLATFORM_ID,\n Signal,\n signal,\n untracked,\n type CreateSignalOptions,\n type WritableSignal,\n} from '@angular/core';\nimport { toWritable } from './to-writable';\n\n/**\n * Interface for storage mechanisms compatible with the `stored` signal.\n * Matches the essential parts of the `Storage` interface (`localStorage`, `sessionStorage`).\n */\ntype Store = {\n /** Retrieves an item from storage for a given key. */\n getItem: (key: string) => string | null;\n /** Sets an item in storage for a given key. */\n setItem: (key: string, value: string) => void;\n /** Removes an item from storage for a given key. */\n removeItem: (key: string) => void;\n};\n\n// Internal dummy store for server-side rendering\nconst noopStore: Store = {\n getItem: () => null,\n setItem: () => {\n /* noop */\n },\n removeItem: () => {\n /* noop */\n },\n};\n\n/**\n * Options for creating a signal synchronized with persistent storage using `stored()`.\n * Extends Angular's `CreateSignalOptions`.\n *\n * @template T The type of value held by the signal.\n */\nexport type CreateStoredOptions<T> = CreateSignalOptions<T> & {\n /**\n * The key used to identify the item in storage.\n * Can be a static string or a function/signal returning a string for dynamic keys\n * (e.g., based on user ID or other application state).\n */\n key: string | (() => string);\n /**\n * Optional custom storage implementation (e.g., `sessionStorage` or a custom adapter).\n * Must conform to the `Store` interface (`getItem`, `setItem`, `removeItem`).\n * Defaults to `localStorage` in browser environments and a no-op store on the server.\n */\n store?: Store;\n /**\n * Optional function to serialize the value (type `T`) into a string before storing.\n * Defaults to `JSON.stringify`.\n * @param {T} value The value to serialize.\n * @returns {string} The serialized string representation.\n */\n serialize?: (value: T) => string;\n /**\n * Optional function to deserialize the string retrieved from storage back into the value (type `T`).\n * Defaults to `JSON.parse`.\n * @param {string} value The string retrieved from storage.\n * @returns {T} The deserialized value.\n */\n deserialize?: (value: string) => T;\n /**\n * If `true`, the signal will attempt to synchronize its state across multiple browser tabs\n * using the `storage` event. Changes made in one tab (set, update, clear) will be\n * reflected in other tabs using the same storage key.\n * Requires a browser environment. Defaults to `false`.\n */\n syncTabs?: boolean;\n};\n\n/**\n * A specialized `WritableSignal` returned by the `stored()` function.\n * It synchronizes its value with persistent storage and provides additional methods.\n *\n * @template T The type of value held by the signal (matches the fallback type).\n */\nexport type StoredSignal<T> = WritableSignal<T> & {\n /**\n * Removes the item associated with the signal's key from the configured storage.\n * After clearing, reading the signal will return the fallback value until it's set again.\n */\n clear: () => void;\n /**\n * A `Signal<string>` containing the current storage key being used by this stored signal.\n * This is particularly useful if the key was configured dynamically. You can read or react\n * to this signal to know the active key.\n */\n key: Signal<string>;\n};\n\n/**\n * Creates a `WritableSignal` whose state is automatically synchronized with persistent storage\n * (like `localStorage` or `sessionStorage`).\n *\n * It handles Server-Side Rendering (SSR) gracefully, allows dynamic storage keys,\n * custom serialization/deserialization, custom storage providers, and optional\n * synchronization across browser tabs.\n *\n * @template T The type of value held by the signal and stored (after serialization).\n * @param fallback The default value of type `T` to use when no value is found in storage\n * or when deserialization fails. The signal's value will never be `null` or `undefined`\n * publicly, it will always revert to this fallback.\n * @param options Configuration options (`CreateStoredOptions<T>`). Requires at least the `key`.\n * @returns A `StoredSignal<T>` instance. This signal behaves like a standard `WritableSignal<T>`,\n * but its value is persisted. It includes a `.clear()` method to remove the item from storage\n * and a `.key` signal providing the current storage key.\n *\n * @remarks\n * - **Persistence:** The signal automatically saves its value to storage whenever the signal's\n * value or its configured `key` changes. This is managed internally using `effect`.\n * - **SSR Safety:** Detects server environments and uses a no-op storage, preventing errors.\n * - **Error Handling:** Catches and logs errors during serialization/deserialization in dev mode.\n * - **Tab Sync:** If `syncTabs` is true, listens to `storage` events to keep the signal value\n * consistent across browser tabs using the same key. Cleanup is handled automatically\n * using `DestroyRef`.\n * - **Removal:** Use the `.clear()` method on the returned signal to remove the item from storage.\n * Setting the signal to the fallback value will store the fallback value, not remove the item.\n *\n * @example\n * ```ts\n * import { Component, effect, signal } from '@angular/core';\n * import { stored } from '@mmstack/primitives'; // Adjust import path\n *\n * @Component({\n * selector: 'app-settings',\n * standalone: true,\n * template: `\n * Theme:\n * <select [ngModel]=\"theme()\" (ngModelChange)=\"theme.set($event)\">\n * <option value=\"light\">Light</option>\n * <option value=\"dark\">Dark</option>\n * </select>\n * <button (click)=\"theme.clear()\">Clear Theme Setting</button>\n * <p>Storage Key Used: {{ theme.key() }}</p>\n * ` // Requires FormsModule for ngModel\n * })\n * export class SettingsComponent {\n * theme = stored<'light' | 'dark'>('light', { key: 'app-theme', syncTabs: true });\n * }\n * ```\n */\nexport function stored<T>(\n fallback: T,\n {\n key,\n store: providedStore,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n syncTabs = false,\n equal = Object.is,\n ...rest\n }: CreateStoredOptions<T>,\n): StoredSignal<T> {\n const isServer = isPlatformServer(inject(PLATFORM_ID));\n\n const fallbackStore = isServer ? noopStore : localStorage;\n const store = providedStore ?? fallbackStore;\n\n const keySig =\n typeof key === 'string'\n ? computed(() => key)\n : isSignal(key)\n ? key\n : computed(key);\n\n const getValue = (key: string): T | null => {\n const found = store.getItem(key);\n if (found === null) return null;\n try {\n return deserialize(found);\n } catch (err) {\n if (isDevMode())\n console.error(`Failed to parse stored value for key \"${key}\":`, err);\n return null;\n }\n };\n\n const storeValue = (key: string, value: T | null) => {\n try {\n if (value === null) return store.removeItem(key);\n const serialized = serialize(value);\n store.setItem(key, serialized);\n } catch (err) {\n if (isDevMode())\n console.error(`Failed to store value for key \"${key}\":`, err);\n }\n };\n\n const opt = {\n ...rest,\n equal,\n };\n\n const internal = signal(getValue(untracked(keySig)), {\n ...opt,\n equal: (a, b) => {\n if (a === null && b === null) return true;\n if (a === null || b === null) return false;\n return equal(a, b);\n },\n });\n\n effect(() => storeValue(keySig(), internal()));\n\n if (syncTabs && !isServer) {\n const destroyRef = inject(DestroyRef);\n const sync = (e: StorageEvent) => {\n if (e.key !== untracked(keySig)) return;\n\n if (e.newValue === null) internal.set(null);\n else internal.set(getValue(e.key));\n };\n\n window.addEventListener('storage', sync);\n\n destroyRef.onDestroy(() => window.removeEventListener('storage', sync));\n }\n\n const writable = toWritable<T>(\n computed(() => internal() ?? fallback, opt),\n internal.set,\n ) as StoredSignal<T>;\n\n writable.clear = () => {\n internal.set(null);\n };\n writable.key = keySig;\n return writable;\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BG;SACa,UAAU,CACxB,MAAiB,EACjB,GAAuB,EACvB,MAA2C,EAAA;IAE3C,MAAM,QAAQ,GAAG,MAA2B;AAC5C,IAAA,QAAQ,CAAC,UAAU,GAAG,MAAM,MAAM;AAClC,IAAA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"file":"mmstack-primitives.mjs","sources":["../../../../packages/primitives/src/lib/to-writable.ts","../../../../packages/primitives/src/lib/debounced.ts","../../../../packages/primitives/src/lib/derived.ts","../../../../packages/primitives/src/lib/map-array.ts","../../../../packages/primitives/src/lib/mutable.ts","../../../../packages/primitives/src/lib/stored.ts","../../../../packages/primitives/src/lib/with-history.ts","../../../../packages/primitives/src/mmstack-primitives.ts"],"sourcesContent":["import { Signal, untracked, WritableSignal } from '@angular/core';\r\n\r\n/**\r\n * Converts a read-only `Signal` into a `WritableSignal` by providing custom `set` and, optionally, `update` functions.\r\n * This can be useful for creating controlled write access to a signal that is otherwise read-only.\r\n *\r\n * @typeParam T - The type of value held by the signal.\r\n *\r\n * @param signal - The read-only `Signal` to be made writable.\r\n * @param set - A function that will be used to set the signal's value. This function *must* handle\r\n * the actual update mechanism (e.g., updating a backing store, emitting an event, etc.).\r\n * @param update - (Optional) A function that will be used to update the signal's value based on its\r\n * previous value. If not provided, a default `update` implementation is used that\r\n * calls the provided `set` function with the result of the updater function. The\r\n * default implementation uses `untracked` to avoid creating unnecessary dependencies\r\n * within the updater function.\r\n *\r\n * @returns A `WritableSignal` that uses the provided `set` and `update` functions. The `asReadonly`\r\n * method of the returned signal will still return the original read-only signal.\r\n *\r\n * @example\r\n * // Basic usage: Making a read-only signal writable with a custom set function.\r\n * const originalValue = signal({a: 0});\r\n * const readOnlySignal = computed(() => originalValue().a);\r\n * const writableSignal = toWritable(readOnlySignal, (newValue) => {\r\n * originalValue.update((prev) => { ...prev, a: newValue });\r\n * });\r\n *\r\n * writableSignal.set(5); // sets value of originalValue.a to 5 & triggers all signals\r\n */\r\nexport function toWritable<T>(\r\n signal: Signal<T>,\r\n set: (value: T) => void,\r\n update?: (updater: (value: T) => T) => void,\r\n): WritableSignal<T> {\r\n const internal = signal as WritableSignal<T>;\r\n internal.asReadonly = () => signal;\r\n internal.set = set;\r\n internal.update = update ?? ((updater) => set(updater(untracked(internal))));\r\n\r\n return internal;\r\n}\r\n","import {\r\n computed,\r\n type CreateSignalOptions,\r\n DestroyRef,\r\n inject,\r\n type Signal,\r\n signal,\r\n untracked,\r\n type WritableSignal,\r\n} from '@angular/core';\r\nimport { toWritable } from './to-writable';\r\n\r\n/**\r\n * Options for creating a debounced writable signal.\r\n * Extends Angular's `CreateSignalOptions` with a debounce time setting.\r\n *\r\n * @template T The type of value held by the signal.\r\n */\r\nexport type CreateDebouncedOptions<T> = CreateSignalOptions<T> & {\r\n /**\r\n * The debounce delay in milliseconds. Specifies how long to wait after the\r\n * last `set` or `update` call before the debounced signal reflects the new value.\r\n */\r\n ms?: number;\r\n /**\r\n * Optional `DestroyRef` to clean up the debounce timer when the signal is destroyed.\r\n * If provided, the timer will be cleared when the signal is destroyed.\r\n * If the signal is called within a reactive context a DestroyRef is injected automatically.\r\n * If it is not provided or injected, the timer will not be cleared automatically...which is usually fine :)\r\n */\r\n destroyRef?: DestroyRef;\r\n};\r\n\r\n/**\r\n * A specialized `WritableSignal` whose publicly readable value updates are debounced.\r\n *\r\n * It provides access to the underlying, non-debounced signal via the `original` property.\r\n *\r\n * @template T The type of value held by the signal.\r\n */\r\nexport type DebouncedSignal<T> = WritableSignal<T> & {\r\n /**\r\n * A reference to the original, inner `WritableSignal`.\r\n * This signal's value is updated *immediately* upon calls to `set` or `update`\r\n * on the parent `DebouncedSignal`. Useful for accessing the latest value\r\n * without the debounce delay.\r\n */\r\n original: Signal<T>;\r\n};\r\n\r\n/**\r\n * A convenience function that creates and debounces a new `WritableSignal` in one step.\r\n *\r\n * @see {debounce} for the core implementation details.\r\n *\r\n * @template T The type of value the signal holds.\r\n * @param initial The initial value of the signal.\r\n * @param opt Options for signal creation, including debounce time `ms`.\r\n * @returns A `DebouncedSignal<T>` instance.\r\n *\r\n * @example\r\n * // The existing example remains perfect here.\r\n * const query = debounced('', { ms: 500 });\r\n * effect(() => console.log('Debounced Query:', query()));\r\n * query.set('abc');\r\n * // ...500ms later...\r\n * // Output: Debounced Query: abc\r\n */\r\nexport function debounced<T>(\r\n initial: T,\r\n opt?: CreateDebouncedOptions<T>,\r\n): DebouncedSignal<T> {\r\n return debounce(signal(initial, opt), opt);\r\n}\r\n\r\n/**\r\n * Wraps an existing `WritableSignal` to create a new one whose readable value is debounced.\r\n *\r\n * This implementation avoids using `effect` by pairing a trigger signal with an `untracked`\r\n * read of the source signal to control when the debounced value is re-evaluated.\r\n *\r\n * @template T The type of value the signal holds.\r\n * @param source The source `WritableSignal` to wrap. Writes are applied to this signal immediately.\r\n * @param opt Options for debouncing, including debounce time `ms` and an optional `DestroyRef`.\r\n * @returns A new `DebouncedSignal<T>` whose read value is debounced. The `.original` property\r\n * of the returned signal is a reference back to the provided `source` signal.\r\n *\r\n * @example\r\n * ```ts\r\n * import { signal, effect } from '@angular/core';\r\n *\r\n * // 1. Create a standard source signal.\r\n * const sourceQuery = signal('');\r\n *\r\n * // 2. Create a debounced version of it.\r\n * const debouncedQuery = debounce(sourceQuery, { ms: 500 });\r\n *\r\n * // This effect tracks the original signal and runs immediately.\r\n * effect(() => {\r\n * console.log('Original Query:', debouncedQuery.original());\r\n * });\r\n *\r\n * // This effect tracks the debounced signal and runs after the delay.\r\n * effect(() => {\r\n * console.log('Debounced Query:', debouncedQuery());\r\n * });\r\n *\r\n * console.log('Setting query to \"a\"');\r\n * debouncedQuery.set('a');\r\n * // Output: Original Query: a\r\n *\r\n * // ...500ms later...\r\n * // Output: Debounced Query: a\r\n * ```\r\n */\r\nexport function debounce<T>(\r\n source: WritableSignal<T>,\r\n opt?: CreateDebouncedOptions<T>,\r\n): DebouncedSignal<T> {\r\n const ms = opt?.ms ?? 0;\r\n\r\n const trigger = signal(false);\r\n\r\n let timeout: ReturnType<typeof setTimeout> | undefined;\r\n\r\n try {\r\n const destroyRef =\r\n opt?.destroyRef ?? inject(DestroyRef, { optional: true });\r\n\r\n destroyRef?.onDestroy(() => {\r\n if (timeout) clearTimeout(timeout);\r\n timeout = undefined;\r\n });\r\n } catch {\r\n // not in injection context & no destroyRef provided opting out of cleanup\r\n }\r\n\r\n const triggerFn = (afterClean: () => void) => {\r\n if (timeout) clearTimeout(timeout);\r\n afterClean();\r\n timeout = setTimeout(() => {\r\n trigger.update((c) => !c);\r\n }, ms);\r\n };\r\n\r\n const set = (value: T) => {\r\n triggerFn(() => source.set(value));\r\n };\r\n\r\n const update = (fn: (prev: T) => T) => {\r\n triggerFn(() => source.update(fn));\r\n };\r\n\r\n const writable = toWritable(\r\n computed(() => {\r\n trigger();\r\n return untracked(source);\r\n }, opt),\r\n set,\r\n update,\r\n ) as DebouncedSignal<T>;\r\n writable.original = source;\r\n\r\n return writable;\r\n}\r\n","import {\r\n computed,\r\n CreateSignalOptions,\r\n signal,\r\n untracked,\r\n type WritableSignal,\r\n} from '@angular/core';\r\nimport type { UnknownObject } from '@mmstack/object';\r\nimport { toWritable } from './to-writable';\r\n\r\n/**\r\n * Options for creating a derived signal using the full `derived` function signature.\r\n * @typeParam T - The type of the source signal's value (parent).\r\n * @typeParam U - The type of the derived signal's value (child).\r\n */\r\ntype CreateDerivedOptions<T, U> = CreateSignalOptions<U> & {\r\n /**\r\n * A function that extracts the derived value (`U`) from the source signal's value (`T`).\r\n */\r\n from: (v: T) => U;\r\n /**\r\n * A function that updates the source signal's value (`T`) when the derived signal's value (`U`) changes.\r\n * This establishes the two-way binding.\r\n */\r\n onChange: (newValue: U) => void;\r\n};\r\n\r\n/**\r\n * A `WritableSignal` that derives its value from another `WritableSignal` (the \"source\" signal).\r\n * It provides two-way binding: changes to the source signal update the derived signal, and\r\n * changes to the derived signal update the source signal.\r\n *\r\n * @typeParam T - The type of the source signal's value (parent).\r\n * @typeParam U - The type of the derived signal's value (child).\r\n */\r\nexport type DerivedSignal<T, U> = WritableSignal<U> & {\r\n /**\r\n * The function used to derive the derived signal's value from the source signal's value.\r\n * This is primarily for internal use and introspection.\r\n */\r\n from: (v: T) => U;\r\n};\r\n\r\n/**\r\n * Creates a `DerivedSignal` that derives its value from another `WritableSignal` (the source signal).\r\n * This overload provides the most flexibility, allowing you to specify custom `from` and `onChange` functions.\r\n *\r\n * @typeParam T - The type of the source signal's value.\r\n * @typeParam U - The type of the derived signal's value.\r\n * @param source - The source `WritableSignal`.\r\n * @param options - An object containing the `from` and `onChange` functions, and optional signal options.\r\n * @returns A `DerivedSignal` instance.\r\n *\r\n * @example\r\n * const user = signal({ name: 'John', age: 30 });\r\n * const name = derived(user, {\r\n * from: (u) => u.name,\r\n * onChange: (newName) => user.update((u) => ({ ...u, name: newName })),\r\n * });\r\n */\r\nexport function derived<T, U>(\r\n source: WritableSignal<T>,\r\n opt: CreateDerivedOptions<T, U>,\r\n): DerivedSignal<T, U>;\r\n\r\n/**\r\n * Creates a `DerivedSignal` that derives a property from an object held by the source signal.\r\n * This overload simplifies creating derived signals for object properties.\r\n *\r\n * @typeParam T - The type of the source signal's value (must be an object).\r\n * @typeParam TKey - The key of the property to derive.\r\n * @param source - The source `WritableSignal` (holding an object).\r\n * @param key - The key of the property to derive.\r\n * @param options - Optional signal options for the derived signal.\r\n * @returns A `DerivedSignal` instance.\r\n *\r\n * @example\r\n * const user = signal({ name: 'John', age: 30 });\r\n * const name = derived(user, 'name');\r\n */\r\nexport function derived<T extends UnknownObject, TKey extends keyof T>(\r\n source: WritableSignal<T>,\r\n key: TKey,\r\n opt?: CreateSignalOptions<T[TKey]>,\r\n): DerivedSignal<T, T[TKey]>;\r\n\r\n/**\r\n * Creates a `DerivedSignal` from an array, and derives an element by index.\r\n *\r\n * @typeParam T - The type of the source signal's value (must be an array).\r\n * @param source - The source `WritableSignal` (holding an array).\r\n * @param index - The index of the element to derive.\r\n * @param options - Optional signal options for the derived signal.\r\n * @returns A `DerivedSignal` instance.\r\n *\r\n * @example\r\n * const numbers = signal([1, 2, 3]);\r\n * const secondNumber = derived(numbers, 1); // secondNumber() === 2\r\n * secondNumber.set(5); // numbers() === [1, 5, 3]\r\n */\r\nexport function derived<T extends any[]>(\r\n source: WritableSignal<T>,\r\n index: number,\r\n opt?: CreateSignalOptions<T[number]>,\r\n): DerivedSignal<T, T[number]>;\r\n\r\nexport function derived<T, U>(\r\n source: WritableSignal<T>,\r\n optOrKey: CreateDerivedOptions<T, U> | keyof T,\r\n opt?: CreateSignalOptions<U>,\r\n): DerivedSignal<T, U> {\r\n const isArray =\r\n Array.isArray(untracked(source)) && typeof optOrKey === 'number';\r\n\r\n const from =\r\n typeof optOrKey === 'object' ? optOrKey.from : (v: T) => v[optOrKey] as U;\r\n const onChange =\r\n typeof optOrKey === 'object'\r\n ? optOrKey.onChange\r\n : isArray\r\n ? (next: U) => {\r\n source.update(\r\n (cur) =>\r\n (cur as unknown as any[]).map((v, i) =>\r\n i === optOrKey ? next : v,\r\n ) as T,\r\n );\r\n }\r\n : (next: U) => {\r\n source.update((cur) => ({ ...cur, [optOrKey]: next }));\r\n };\r\n\r\n const rest = typeof optOrKey === 'object' ? optOrKey : opt;\r\n\r\n const sig = toWritable<U>(\r\n computed(() => from(source()), rest),\r\n (newVal) => onChange(newVal),\r\n ) as DerivedSignal<T, U>;\r\n\r\n sig.from = from;\r\n\r\n return sig;\r\n}\r\n\r\n/**\r\n * Creates a \"fake\" `DerivedSignal` from a simple value. This is useful for creating\r\n * `FormControlSignal` instances that are not directly derived from another signal.\r\n * The returned signal's `from` function will always return the initial value.\r\n *\r\n * @typeParam T - This type parameter is not used in the implementation but is kept for type compatibility with `DerivedSignal`.\r\n * @typeParam U - The type of the signal's value.\r\n * @param initial - The initial value of the signal.\r\n * @returns A `DerivedSignal` instance.\r\n * @internal\r\n */\r\nexport function toFakeDerivation<T, U>(initial: U): DerivedSignal<T, U> {\r\n const sig = signal(initial) as DerivedSignal<T, U>;\r\n sig.from = () => initial;\r\n\r\n return sig;\r\n}\r\n\r\n/**\r\n * Creates a \"fake\" `DerivedSignal` from an existing `WritableSignal`. This is useful\r\n * for treating a regular `WritableSignal` as a `DerivedSignal` without changing its behavior.\r\n * The returned signal's `from` function returns the current value of signal, using `untracked`.\r\n *\r\n * @typeParam T - This type parameter is not used in the implementation but is kept for type compatibility with `DerivedSignal`.\r\n * @typeParam U - The type of the signal's value.\r\n * @param initial - The existing `WritableSignal`.\r\n * @returns A `DerivedSignal` instance.\r\n * @internal\r\n */\r\nexport function toFakeSignalDerivation<T, U>(\r\n initial: WritableSignal<U>,\r\n): DerivedSignal<T, U> {\r\n const sig = initial as DerivedSignal<T, U>;\r\n sig.from = () => untracked(initial);\r\n return sig;\r\n}\r\n\r\n/**\r\n * Type guard function to check if a given `WritableSignal` is a `DerivedSignal`.\r\n *\r\n * @typeParam T - The type of the source signal's value (optional, defaults to `any`).\r\n * @typeParam U - The type of the derived signal's value (optional, defaults to `any`).\r\n * @param sig - The `WritableSignal` to check.\r\n * @returns `true` if the signal is a `DerivedSignal`, `false` otherwise.\r\n */\r\nexport function isDerivation<T, U>(\r\n sig: WritableSignal<U>,\r\n): sig is DerivedSignal<T, U> {\r\n return 'from' in sig;\r\n}\r\n","import {\r\n computed,\r\n type CreateSignalOptions,\r\n isSignal,\r\n linkedSignal,\r\n type Signal,\r\n} from '@angular/core';\r\n\r\n/**\r\n * Reactively maps items from a source array (or signal of an array) using a provided mapping function.\r\n *\r\n * This function serves a similar purpose to SolidJS's `mapArray` by providing stability\r\n * for mapped items. It receives a source function returning an array (or a Signal<T[]>)\r\n * and a mapping function.\r\n *\r\n * For each item in the source array, it creates a stable `computed` signal representing\r\n * that item's value at its current index. This stable signal (`Signal<T>`) is passed\r\n * to the mapping function. This ensures that downstream computations or components\r\n * depending on the mapped result only re-render or re-calculate for the specific items\r\n * that have changed, or when items are added/removed, rather than re-evaluating everything\r\n * when the source array reference changes but items remain the same.\r\n *\r\n * It efficiently handles changes in the source array's length by reusing existing mapped\r\n * results when possible, slicing when the array shrinks, and appending new mapped items\r\n * when it grows.\r\n *\r\n * @template T The type of items in the source array.\r\n * @template U The type of items in the resulting mapped array.\r\n *\r\n * @param source A function returning the source array `T[]`, or a `Signal<T[]>` itself.\r\n * The `mapArray` function will reactively update based on changes to this source.\r\n * @param map The mapping function. It is called for each item in the source array.\r\n * It receives:\r\n * - `value`: A stable `Signal<T>` representing the item at the current index.\r\n * Use this signal within your mapping logic if you need reactivity\r\n * tied to the specific item's value changes.\r\n * - `index`: The number index of the item in the array.\r\n * It should return the mapped value `U`.\r\n * @param [opt] Optional `CreateSignalOptions<T>`. These options are passed directly\r\n * to the `computed` signal created for each individual item (`Signal<T>`).\r\n * This allows specifying options like a custom `equal` function for item comparison.\r\n *\r\n * @returns A `Signal<U[]>` containing the mapped array. This signal updates whenever\r\n * the source array changes (either length or the values of its items).\r\n *\r\n * @example\r\n * ```ts\r\n * const sourceItems = signal([\r\n * { id: 1, name: 'Apple' },\r\n * { id: 2, name: 'Banana' }\r\n * ]);\r\n *\r\n * const mappedItems = mapArray(\r\n * sourceItems,\r\n * (itemSignal, index) => {\r\n * // itemSignal is stable for a given item based on its index.\r\n * // We create a computed here to react to changes in the item's name.\r\n * return computed(() => `${index}: ${itemSignal().name.toUpperCase()}`);\r\n * },\r\n * // Example optional options (e.g., custom equality for item signals)\r\n * { equal: (a, b) => a.id === b.id && a.name === b.name }\r\n * );\r\n * ```\r\n */\r\nexport function mapArray<T, U>(\r\n source: () => T[],\r\n map: (value: Signal<T>, index: number) => U,\r\n opt?: CreateSignalOptions<T>,\r\n): Signal<U[]> {\r\n const data = isSignal(source) ? source : computed(source);\r\n const len = computed(() => data().length);\r\n\r\n return linkedSignal<number, U[]>({\r\n source: () => len(),\r\n computation: (len, prev) => {\r\n if (!prev)\r\n return Array.from({ length: len }, (_, i) =>\r\n map(\r\n computed(() => source()[i], opt),\r\n i,\r\n ),\r\n );\r\n\r\n if (len === prev.value.length) return prev.value;\r\n\r\n if (len < prev.value.length) {\r\n return prev.value.slice(0, len);\r\n } else {\r\n const next = [...prev.value];\r\n for (let i = prev.value.length; i < len; i++) {\r\n next[i] = map(\r\n computed(() => source()[i], opt),\r\n i,\r\n );\r\n }\r\n return next;\r\n }\r\n },\r\n equal: (a, b) => a.length === b.length,\r\n });\r\n}\r\n","import {\r\n signal,\r\n type CreateSignalOptions,\r\n type ValueEqualityFn,\r\n type WritableSignal,\r\n} from '@angular/core';\r\n\r\nconst { is } = Object;\r\n\r\n/**\r\n * A `MutableSignal` is a special type of `WritableSignal` that allows for in-place mutation of its value.\r\n * In addition to the standard `set` and `update` methods, it provides a `mutate` method. This is useful\r\n * for performance optimization when dealing with complex objects or arrays, as it avoids unnecessary\r\n * object copying.\r\n *\r\n * @typeParam T - The type of value held by the signal.\r\n */\r\nexport type MutableSignal<T> = WritableSignal<T> & {\r\n /**\r\n * Mutates the signal's value in-place. This is similar to `update`, but it's optimized for\r\n * scenarios where you want to modify the existing object directly rather than creating a new one.\r\n *\r\n * @param updater - A function that takes the current value as input and modifies it directly.\r\n *\r\n * @example\r\n * const myArray = mutable([1, 2, 3]);\r\n * myArray.mutate((arr) => {\r\n * arr.push(4);\r\n * return arr;\r\n * }); // myArray() now returns [1, 2, 3, 4]\r\n */\r\n mutate: WritableSignal<T>['update'];\r\n\r\n /**\r\n * Mutates the signal's value in-place, similar to `mutate`, but with a void-returning value in updater\r\n * function. This further emphasizes that the mutation is happening inline, improving readability\r\n * in some cases.\r\n * @param updater - Function to change to the current value\r\n * @example\r\n * const myObject = mutable({ a: 1, b: 2 });\r\n * myObject.inline((obj) => (obj.a = 3)); // myObject() now returns { a: 3, b: 2 }\r\n */\r\n inline: (updater: (value: T) => void) => void;\r\n};\r\n\r\n/**\r\n * Creates a `MutableSignal`. This function overloads the standard `signal` function to provide\r\n * the additional `mutate` and `inline` methods.\r\n *\r\n * @typeParam T - The type of value held by the signal.\r\n *\r\n * @param initial - The initial value of the signal. If no initial value is provided, it defaults to `undefined`.\r\n * @param options - Optional. An object containing signal options, including a custom equality function (`equal`).\r\n *\r\n * @returns A `MutableSignal` instance.\r\n *\r\n * @example\r\n * // Create a mutable signal with an initial value:\r\n * const mySignal = mutable({ count: 0 }) // MutableSignal<{ count: number }>;\r\n *\r\n * // Create a mutable signal with no initial value (starts as undefined):\r\n * const = mutable<number>(); // MutableSignal<number | undefined>\r\n *\r\n * // Create a mutable signal with a custom equality function:\r\n * const myCustomSignal = mutable({ a: 1 }, { equal: (a, b) => a.a === b.a });\r\n */\r\nexport function mutable<T>(): MutableSignal<T | undefined>;\r\nexport function mutable<T>(initial: T): MutableSignal<T>;\r\nexport function mutable<T>(\r\n initial: T,\r\n opt?: CreateSignalOptions<T>,\r\n): MutableSignal<T>;\r\n\r\nexport function mutable<T>(\r\n initial?: T,\r\n opt?: CreateSignalOptions<T>,\r\n): MutableSignal<T> {\r\n const baseEqual = opt?.equal ?? is;\r\n let trigger = false;\r\n\r\n const equal: ValueEqualityFn<T | undefined> = (a, b) => {\r\n if (trigger) return false;\r\n return baseEqual(a, b);\r\n };\r\n\r\n const sig = signal<T | undefined>(initial, {\r\n ...opt,\r\n equal,\r\n }) as MutableSignal<T>;\r\n\r\n const internalUpdate = sig.update;\r\n\r\n sig.mutate = (updater) => {\r\n trigger = true;\r\n internalUpdate(updater);\r\n trigger = false;\r\n };\r\n\r\n sig.inline = (updater) => {\r\n sig.mutate((prev) => {\r\n updater(prev);\r\n return prev;\r\n });\r\n };\r\n\r\n return sig;\r\n}\r\n\r\n/**\r\n * Type guard function to check if a given `WritableSignal` is a `MutableSignal`. This is useful\r\n * for situations where you need to conditionally use the `mutate` or `inline` methods.\r\n *\r\n * @typeParam T - The type of the signal's value (optional, defaults to `any`).\r\n * @param value - The `WritableSignal` to check.\r\n * @returns `true` if the signal is a `MutableSignal`, `false` otherwise.\r\n *\r\n * @example\r\n * const mySignal = signal(0);\r\n * const myMutableSignal = mutable(0);\r\n *\r\n * if (isMutable(mySignal)) {\r\n * mySignal.mutate(x => x + 1); // This would cause a type error, as mySignal is not a MutableSignal.\r\n * }\r\n *\r\n * if (isMutable(myMutableSignal)) {\r\n * myMutableSignal.mutate(x => x + 1); // This is safe.\r\n * }\r\n */\r\nexport function isMutable<T = any>(\r\n value: WritableSignal<T>,\r\n): value is MutableSignal<T> {\r\n return 'mutate' in value && typeof value.mutate === 'function';\r\n}\r\n","import { isPlatformServer } from '@angular/common';\r\nimport {\r\n computed,\r\n DestroyRef,\r\n effect,\r\n inject,\r\n isDevMode,\r\n isSignal,\r\n PLATFORM_ID,\r\n Signal,\r\n signal,\r\n untracked,\r\n type CreateSignalOptions,\r\n type WritableSignal,\r\n} from '@angular/core';\r\nimport { toWritable } from './to-writable';\r\n\r\n/**\r\n * Interface for storage mechanisms compatible with the `stored` signal.\r\n * Matches the essential parts of the `Storage` interface (`localStorage`, `sessionStorage`).\r\n */\r\ntype Store = {\r\n /** Retrieves an item from storage for a given key. */\r\n getItem: (key: string) => string | null;\r\n /** Sets an item in storage for a given key. */\r\n setItem: (key: string, value: string) => void;\r\n /** Removes an item from storage for a given key. */\r\n removeItem: (key: string) => void;\r\n};\r\n\r\n// Internal dummy store for server-side rendering\r\nconst noopStore: Store = {\r\n getItem: () => null,\r\n setItem: () => {\r\n /* noop */\r\n },\r\n removeItem: () => {\r\n /* noop */\r\n },\r\n};\r\n\r\n/**\r\n * Options for creating a signal synchronized with persistent storage using `stored()`.\r\n * Extends Angular's `CreateSignalOptions`.\r\n *\r\n * @template T The type of value held by the signal.\r\n */\r\nexport type CreateStoredOptions<T> = CreateSignalOptions<T> & {\r\n /**\r\n * The key used to identify the item in storage.\r\n * Can be a static string or a function/signal returning a string for dynamic keys\r\n * (e.g., based on user ID or other application state).\r\n */\r\n key: string | (() => string);\r\n /**\r\n * Optional custom storage implementation (e.g., `sessionStorage` or a custom adapter).\r\n * Must conform to the `Store` interface (`getItem`, `setItem`, `removeItem`).\r\n * Defaults to `localStorage` in browser environments and a no-op store on the server.\r\n */\r\n store?: Store;\r\n /**\r\n * Optional function to serialize the value (type `T`) into a string before storing.\r\n * Defaults to `JSON.stringify`.\r\n * @param {T} value The value to serialize.\r\n * @returns {string} The serialized string representation.\r\n */\r\n serialize?: (value: T) => string;\r\n /**\r\n * Optional function to deserialize the string retrieved from storage back into the value (type `T`).\r\n * Defaults to `JSON.parse`.\r\n * @param {string} value The string retrieved from storage.\r\n * @returns {T} The deserialized value.\r\n */\r\n deserialize?: (value: string) => T;\r\n /**\r\n * If `true`, the signal will attempt to synchronize its state across multiple browser tabs\r\n * using the `storage` event. Changes made in one tab (set, update, clear) will be\r\n * reflected in other tabs using the same storage key.\r\n * Requires a browser environment. Defaults to `false`.\r\n */\r\n syncTabs?: boolean;\r\n};\r\n\r\n/**\r\n * A specialized `WritableSignal` returned by the `stored()` function.\r\n * It synchronizes its value with persistent storage and provides additional methods.\r\n *\r\n * @template T The type of value held by the signal (matches the fallback type).\r\n */\r\nexport type StoredSignal<T> = WritableSignal<T> & {\r\n /**\r\n * Removes the item associated with the signal's key from the configured storage.\r\n * After clearing, reading the signal will return the fallback value until it's set again.\r\n */\r\n clear: () => void;\r\n /**\r\n * A `Signal<string>` containing the current storage key being used by this stored signal.\r\n * This is particularly useful if the key was configured dynamically. You can read or react\r\n * to this signal to know the active key.\r\n */\r\n key: Signal<string>;\r\n};\r\n\r\n/**\r\n * Creates a `WritableSignal` whose state is automatically synchronized with persistent storage\r\n * (like `localStorage` or `sessionStorage`).\r\n *\r\n * It handles Server-Side Rendering (SSR) gracefully, allows dynamic storage keys,\r\n * custom serialization/deserialization, custom storage providers, and optional\r\n * synchronization across browser tabs.\r\n *\r\n * @template T The type of value held by the signal and stored (after serialization).\r\n * @param fallback The default value of type `T` to use when no value is found in storage\r\n * or when deserialization fails. The signal's value will never be `null` or `undefined`\r\n * publicly, it will always revert to this fallback.\r\n * @param options Configuration options (`CreateStoredOptions<T>`). Requires at least the `key`.\r\n * @returns A `StoredSignal<T>` instance. This signal behaves like a standard `WritableSignal<T>`,\r\n * but its value is persisted. It includes a `.clear()` method to remove the item from storage\r\n * and a `.key` signal providing the current storage key.\r\n *\r\n * @remarks\r\n * - **Persistence:** The signal automatically saves its value to storage whenever the signal's\r\n * value or its configured `key` changes. This is managed internally using `effect`.\r\n * - **SSR Safety:** Detects server environments and uses a no-op storage, preventing errors.\r\n * - **Error Handling:** Catches and logs errors during serialization/deserialization in dev mode.\r\n * - **Tab Sync:** If `syncTabs` is true, listens to `storage` events to keep the signal value\r\n * consistent across browser tabs using the same key. Cleanup is handled automatically\r\n * using `DestroyRef`.\r\n * - **Removal:** Use the `.clear()` method on the returned signal to remove the item from storage.\r\n * Setting the signal to the fallback value will store the fallback value, not remove the item.\r\n *\r\n * @example\r\n * ```ts\r\n * import { Component, effect, signal } from '@angular/core';\r\n * import { stored } from '@mmstack/primitives'; // Adjust import path\r\n *\r\n * @Component({\r\n * selector: 'app-settings',\r\n * standalone: true,\r\n * template: `\r\n * Theme:\r\n * <select [ngModel]=\"theme()\" (ngModelChange)=\"theme.set($event)\">\r\n * <option value=\"light\">Light</option>\r\n * <option value=\"dark\">Dark</option>\r\n * </select>\r\n * <button (click)=\"theme.clear()\">Clear Theme Setting</button>\r\n * <p>Storage Key Used: {{ theme.key() }}</p>\r\n * ` // Requires FormsModule for ngModel\r\n * })\r\n * export class SettingsComponent {\r\n * theme = stored<'light' | 'dark'>('light', { key: 'app-theme', syncTabs: true });\r\n * }\r\n * ```\r\n */\r\nexport function stored<T>(\r\n fallback: T,\r\n {\r\n key,\r\n store: providedStore,\r\n serialize = JSON.stringify,\r\n deserialize = JSON.parse,\r\n syncTabs = false,\r\n equal = Object.is,\r\n ...rest\r\n }: CreateStoredOptions<T>,\r\n): StoredSignal<T> {\r\n const isServer = isPlatformServer(inject(PLATFORM_ID));\r\n\r\n const fallbackStore = isServer ? noopStore : localStorage;\r\n const store = providedStore ?? fallbackStore;\r\n\r\n const keySig =\r\n typeof key === 'string'\r\n ? computed(() => key)\r\n : isSignal(key)\r\n ? key\r\n : computed(key);\r\n\r\n const getValue = (key: string): T | null => {\r\n const found = store.getItem(key);\r\n if (found === null) return null;\r\n try {\r\n return deserialize(found);\r\n } catch (err) {\r\n if (isDevMode())\r\n console.error(`Failed to parse stored value for key \"${key}\":`, err);\r\n return null;\r\n }\r\n };\r\n\r\n const storeValue = (key: string, value: T | null) => {\r\n try {\r\n if (value === null) return store.removeItem(key);\r\n const serialized = serialize(value);\r\n store.setItem(key, serialized);\r\n } catch (err) {\r\n if (isDevMode())\r\n console.error(`Failed to store value for key \"${key}\":`, err);\r\n }\r\n };\r\n\r\n const opt = {\r\n ...rest,\r\n equal,\r\n };\r\n\r\n const internal = signal(getValue(untracked(keySig)), {\r\n ...opt,\r\n equal: (a, b) => {\r\n if (a === null && b === null) return true;\r\n if (a === null || b === null) return false;\r\n return equal(a, b);\r\n },\r\n });\r\n\r\n effect(() => storeValue(keySig(), internal()));\r\n\r\n if (syncTabs && !isServer) {\r\n const destroyRef = inject(DestroyRef);\r\n const sync = (e: StorageEvent) => {\r\n if (e.key !== untracked(keySig)) return;\r\n\r\n if (e.newValue === null) internal.set(null);\r\n else internal.set(getValue(e.key));\r\n };\r\n\r\n window.addEventListener('storage', sync);\r\n\r\n destroyRef.onDestroy(() => window.removeEventListener('storage', sync));\r\n }\r\n\r\n const writable = toWritable<T>(\r\n computed(() => internal() ?? fallback, opt),\r\n internal.set,\r\n ) as StoredSignal<T>;\r\n\r\n writable.clear = () => {\r\n internal.set(null);\r\n };\r\n writable.key = keySig;\r\n return writable;\r\n}\r\n","import {\r\n computed,\r\n type CreateSignalOptions,\r\n type Signal,\r\n untracked,\r\n type ValueEqualityFn,\r\n type WritableSignal,\r\n} from '@angular/core';\r\nimport { SIGNAL } from '@angular/core/primitives/signals';\r\nimport { mutable } from './mutable';\r\nimport { toWritable } from './to-writable';\r\n\r\nexport type SignalWithHistory<T> = WritableSignal<T> & {\r\n history: Signal<T[]>;\r\n undo: () => void;\r\n redo: () => void;\r\n canRedo: Signal<boolean>;\r\n canUndo: Signal<boolean>;\r\n clear: () => void;\r\n canClear: Signal<boolean>;\r\n};\r\n\r\nexport type CreateHistoryOptions<T> = Omit<\r\n CreateSignalOptions<T[]>,\r\n 'equal'\r\n> & {\r\n maxSize?: number;\r\n};\r\n\r\nexport function withHistory<T>(\r\n source: WritableSignal<T>,\r\n opt?: CreateHistoryOptions<T>,\r\n): SignalWithHistory<T> {\r\n const { equal = Object.is, debugName } = source[SIGNAL] as {\r\n equal?: ValueEqualityFn<T>;\r\n debugName?: string;\r\n };\r\n\r\n const maxSize = opt?.maxSize ?? Infinity;\r\n\r\n const history = mutable<T[]>([], opt);\r\n\r\n const redoArray = mutable<T[]>([]);\r\n\r\n const set = (value: T) => {\r\n const current = untracked(source);\r\n if (equal(value, current)) return;\r\n\r\n source.set(value);\r\n\r\n history.mutate((c) => {\r\n if (c.length >= maxSize) {\r\n c = c.slice(Math.floor(maxSize / 2));\r\n }\r\n c.push(current);\r\n return c;\r\n });\r\n redoArray.set([]);\r\n };\r\n\r\n const update = (updater: (prev: T) => T) => {\r\n set(updater(untracked(source)));\r\n };\r\n\r\n const internal = toWritable(\r\n computed(() => source(), {\r\n equal,\r\n debugName,\r\n }),\r\n set,\r\n update,\r\n ) as SignalWithHistory<T>;\r\n internal.history = history;\r\n\r\n internal.undo = () => {\r\n const last = untracked(history);\r\n if (last.length === 0) return;\r\n\r\n const prev = last.at(-1)!;\r\n const cur = untracked(source);\r\n\r\n history.inline((c) => c.pop());\r\n redoArray.inline((c) => c.push(cur));\r\n\r\n source.set(prev);\r\n };\r\n\r\n internal.redo = () => {\r\n const last = untracked(redoArray);\r\n if (last.length === 0) return;\r\n\r\n const prev = last.at(-1)!;\r\n\r\n redoArray.inline((c) => c.pop());\r\n\r\n set(prev);\r\n };\r\n\r\n internal.clear = () => {\r\n history.set([]);\r\n redoArray.set([]);\r\n };\r\n\r\n internal.canUndo = computed(() => history().length > 0);\r\n internal.canRedo = computed(() => redoArray().length > 0);\r\n internal.canClear = computed(() => internal.canUndo() || internal.canRedo());\r\n\r\n return internal;\r\n}\r\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BG;SACa,UAAU,CACxB,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AQ,CAAC,OAAO,GAAG,QAAQ,CAAC,MAAM,OAAO,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;AACvD,IAAA,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC,MAAM,SAAS,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;AACzD,IAAA,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAC,MAAM,QAAQ,CAAC,OAAO,EAAE,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;AAE5E,IAAA,OAAO,QAAQ;AACjB;;AC5GA;;AAEG;;;;"}
|
package/index.d.ts
CHANGED
package/lib/debounced.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type CreateSignalOptions, type Signal, type WritableSignal } from '@angular/core';
|
|
1
|
+
import { type CreateSignalOptions, DestroyRef, type Signal, type WritableSignal } from '@angular/core';
|
|
2
2
|
/**
|
|
3
3
|
* Options for creating a debounced writable signal.
|
|
4
4
|
* Extends Angular's `CreateSignalOptions` with a debounce time setting.
|
|
@@ -11,6 +11,13 @@ export type CreateDebouncedOptions<T> = CreateSignalOptions<T> & {
|
|
|
11
11
|
* last `set` or `update` call before the debounced signal reflects the new value.
|
|
12
12
|
*/
|
|
13
13
|
ms?: number;
|
|
14
|
+
/**
|
|
15
|
+
* Optional `DestroyRef` to clean up the debounce timer when the signal is destroyed.
|
|
16
|
+
* If provided, the timer will be cleared when the signal is destroyed.
|
|
17
|
+
* If the signal is called within a reactive context a DestroyRef is injected automatically.
|
|
18
|
+
* If it is not provided or injected, the timer will not be cleared automatically...which is usually fine :)
|
|
19
|
+
*/
|
|
20
|
+
destroyRef?: DestroyRef;
|
|
14
21
|
};
|
|
15
22
|
/**
|
|
16
23
|
* A specialized `WritableSignal` whose publicly readable value updates are debounced.
|
|
@@ -29,56 +36,62 @@ export type DebouncedSignal<T> = WritableSignal<T> & {
|
|
|
29
36
|
original: Signal<T>;
|
|
30
37
|
};
|
|
31
38
|
/**
|
|
32
|
-
*
|
|
33
|
-
* a specified debounce period (`ms`) has passed since the last call to its
|
|
34
|
-
* `.set()` or `.update()` method.
|
|
39
|
+
* A convenience function that creates and debounces a new `WritableSignal` in one step.
|
|
35
40
|
*
|
|
36
|
-
*
|
|
37
|
-
* signals and a custom `equal` function to delay value propagation based on a timer.
|
|
41
|
+
* @see {debounce} for the core implementation details.
|
|
38
42
|
*
|
|
39
43
|
* @template T The type of value the signal holds.
|
|
40
44
|
* @param initial The initial value of the signal.
|
|
41
|
-
* @param opt Options for signal creation, including
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* @
|
|
45
|
-
*
|
|
45
|
+
* @param opt Options for signal creation, including debounce time `ms`.
|
|
46
|
+
* @returns A `DebouncedSignal<T>` instance.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* // The existing example remains perfect here.
|
|
50
|
+
* const query = debounced('', { ms: 500 });
|
|
51
|
+
* effect(() => console.log('Debounced Query:', query()));
|
|
52
|
+
* query.set('abc');
|
|
53
|
+
* // ...500ms later...
|
|
54
|
+
* // Output: Debounced Query: abc
|
|
55
|
+
*/
|
|
56
|
+
export declare function debounced<T>(initial: T, opt?: CreateDebouncedOptions<T>): DebouncedSignal<T>;
|
|
57
|
+
/**
|
|
58
|
+
* Wraps an existing `WritableSignal` to create a new one whose readable value is debounced.
|
|
59
|
+
*
|
|
60
|
+
* This implementation avoids using `effect` by pairing a trigger signal with an `untracked`
|
|
61
|
+
* read of the source signal to control when the debounced value is re-evaluated.
|
|
62
|
+
*
|
|
63
|
+
* @template T The type of value the signal holds.
|
|
64
|
+
* @param source The source `WritableSignal` to wrap. Writes are applied to this signal immediately.
|
|
65
|
+
* @param opt Options for debouncing, including debounce time `ms` and an optional `DestroyRef`.
|
|
66
|
+
* @returns A new `DebouncedSignal<T>` whose read value is debounced. The `.original` property
|
|
67
|
+
* of the returned signal is a reference back to the provided `source` signal.
|
|
46
68
|
*
|
|
47
69
|
* @example
|
|
48
70
|
* ```ts
|
|
49
|
-
* import { effect } from '@angular/core';
|
|
71
|
+
* import { signal, effect } from '@angular/core';
|
|
50
72
|
*
|
|
51
|
-
* // Create a
|
|
52
|
-
* const
|
|
73
|
+
* // 1. Create a standard source signal.
|
|
74
|
+
* const sourceQuery = signal('');
|
|
53
75
|
*
|
|
76
|
+
* // 2. Create a debounced version of it.
|
|
77
|
+
* const debouncedQuery = debounce(sourceQuery, { ms: 500 });
|
|
78
|
+
*
|
|
79
|
+
* // This effect tracks the original signal and runs immediately.
|
|
54
80
|
* effect(() => {
|
|
55
|
-
*
|
|
56
|
-
* console.log('Debounced Query:', query());
|
|
81
|
+
* console.log('Original Query:', debouncedQuery.original());
|
|
57
82
|
* });
|
|
58
83
|
*
|
|
84
|
+
* // This effect tracks the debounced signal and runs after the delay.
|
|
59
85
|
* effect(() => {
|
|
60
|
-
*
|
|
61
|
-
* console.log('Original Query:', query.original());
|
|
86
|
+
* console.log('Debounced Query:', debouncedQuery());
|
|
62
87
|
* });
|
|
63
88
|
*
|
|
64
89
|
* console.log('Setting query to "a"');
|
|
65
|
-
*
|
|
90
|
+
* debouncedQuery.set('a');
|
|
66
91
|
* // Output: Original Query: a
|
|
67
92
|
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
* query.set('ab');
|
|
71
|
-
* // Output: Original Query: ab
|
|
72
|
-
* }, 200); // Before debounce timeout
|
|
73
|
-
*
|
|
74
|
-
* setTimeout(() => {
|
|
75
|
-
* console.log('Setting query to "abc"');
|
|
76
|
-
* query.set('abc');
|
|
77
|
-
* // Output: Original Query: abc
|
|
78
|
-
* }, 400); // Before debounce timeout
|
|
79
|
-
*
|
|
80
|
-
* // ~500ms after the *last* set (at 400ms), the debounced effect runs:
|
|
81
|
-
* // Output (at ~900ms): Debounced Query: abc
|
|
93
|
+
* // ...500ms later...
|
|
94
|
+
* // Output: Debounced Query: a
|
|
82
95
|
* ```
|
|
83
96
|
*/
|
|
84
|
-
export declare function
|
|
97
|
+
export declare function debounce<T>(source: WritableSignal<T>, opt?: CreateDebouncedOptions<T>): DebouncedSignal<T>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type CreateSignalOptions, type Signal, type WritableSignal } from '@angular/core';
|
|
2
|
+
export type SignalWithHistory<T> = WritableSignal<T> & {
|
|
3
|
+
history: Signal<T[]>;
|
|
4
|
+
undo: () => void;
|
|
5
|
+
redo: () => void;
|
|
6
|
+
canRedo: Signal<boolean>;
|
|
7
|
+
canUndo: Signal<boolean>;
|
|
8
|
+
clear: () => void;
|
|
9
|
+
canClear: Signal<boolean>;
|
|
10
|
+
};
|
|
11
|
+
export type CreateHistoryOptions<T> = Omit<CreateSignalOptions<T[]>, 'equal'> & {
|
|
12
|
+
maxSize?: number;
|
|
13
|
+
};
|
|
14
|
+
export declare function withHistory<T>(source: WritableSignal<T>, opt?: CreateHistoryOptions<T>): SignalWithHistory<T>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mmstack/primitives",
|
|
3
|
-
"version": "19.
|
|
3
|
+
"version": "19.1.1",
|
|
4
4
|
"keywords": [
|
|
5
5
|
"angular",
|
|
6
6
|
"signals",
|
|
@@ -14,10 +14,13 @@
|
|
|
14
14
|
"url": "https://github.com/mihajm/mmstack"
|
|
15
15
|
},
|
|
16
16
|
"homepage": "https://github.com/mihajm/mmstack/blob/master/packages/primitives",
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@mmstack/object": "^19.1.0",
|
|
19
|
+
"tslib": "^2.3.0"
|
|
20
|
+
},
|
|
17
21
|
"peerDependencies": {
|
|
18
22
|
"@angular/core": "~19.2.3",
|
|
19
|
-
"@angular/common": "~19.2.3"
|
|
20
|
-
"@mmstack/object": "~19.0.0"
|
|
23
|
+
"@angular/common": "~19.2.3"
|
|
21
24
|
},
|
|
22
25
|
"sideEffects": false,
|
|
23
26
|
"module": "fesm2022/mmstack-primitives.mjs",
|
|
@@ -30,8 +33,5 @@
|
|
|
30
33
|
"types": "./index.d.ts",
|
|
31
34
|
"default": "./fesm2022/mmstack-primitives.mjs"
|
|
32
35
|
}
|
|
33
|
-
},
|
|
34
|
-
"dependencies": {
|
|
35
|
-
"tslib": "^2.3.0"
|
|
36
36
|
}
|
|
37
37
|
}
|