@angular-architects/ngrx-toolkit 20.0.0 → 20.0.2

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.
Files changed (84) hide show
  1. package/eslint.config.cjs +43 -0
  2. package/jest.config.ts +22 -0
  3. package/ng-package.json +7 -0
  4. package/package.json +4 -21
  5. package/project.json +37 -0
  6. package/redux-connector/docs/README.md +131 -0
  7. package/redux-connector/index.ts +6 -0
  8. package/redux-connector/ng-package.json +5 -0
  9. package/redux-connector/src/lib/create-redux.ts +102 -0
  10. package/redux-connector/src/lib/model.ts +89 -0
  11. package/redux-connector/src/lib/rxjs-interop/redux-method.ts +66 -0
  12. package/redux-connector/src/lib/signal-redux-store.ts +59 -0
  13. package/redux-connector/src/lib/util.ts +22 -0
  14. package/src/index.ts +43 -0
  15. package/src/lib/assertions/assertions.ts +9 -0
  16. package/src/lib/devtools/features/with-disabled-name-indicies.ts +31 -0
  17. package/src/lib/devtools/features/with-glitch-tracking.ts +35 -0
  18. package/src/lib/devtools/features/with-mapper.ts +34 -0
  19. package/src/lib/devtools/internal/current-action-names.ts +1 -0
  20. package/src/lib/devtools/internal/default-tracker.ts +60 -0
  21. package/src/lib/devtools/internal/devtools-feature.ts +37 -0
  22. package/src/lib/devtools/internal/devtools-syncer.service.ts +202 -0
  23. package/src/lib/devtools/internal/glitch-tracker.service.ts +61 -0
  24. package/src/lib/devtools/internal/models.ts +29 -0
  25. package/src/lib/devtools/provide-devtools-config.ts +32 -0
  26. package/src/lib/devtools/rename-devtools-name.ts +21 -0
  27. package/src/lib/devtools/tests/action-name.spec.ts +48 -0
  28. package/src/lib/devtools/tests/basic.spec.ts +111 -0
  29. package/src/lib/devtools/tests/connecting.spec.ts +37 -0
  30. package/src/lib/devtools/tests/helpers.spec.ts +43 -0
  31. package/src/lib/devtools/tests/naming.spec.ts +216 -0
  32. package/src/lib/devtools/tests/provide-devtools-config.spec.ts +25 -0
  33. package/src/lib/devtools/tests/types.spec.ts +19 -0
  34. package/src/lib/devtools/tests/update-state.spec.ts +29 -0
  35. package/src/lib/devtools/tests/with-devtools.spec.ts +5 -0
  36. package/src/lib/devtools/tests/with-glitch-tracking.spec.ts +272 -0
  37. package/src/lib/devtools/tests/with-mapper.spec.ts +69 -0
  38. package/src/lib/devtools/update-state.ts +38 -0
  39. package/src/lib/devtools/with-dev-tools-stub.ts +6 -0
  40. package/src/lib/devtools/with-devtools.ts +81 -0
  41. package/src/lib/immutable-state/deep-freeze.ts +43 -0
  42. package/src/lib/immutable-state/is-dev-mode.ts +6 -0
  43. package/src/lib/immutable-state/tests/with-immutable-state.spec.ts +278 -0
  44. package/src/lib/immutable-state/with-immutable-state.ts +150 -0
  45. package/src/lib/shared/prettify.ts +3 -0
  46. package/src/lib/shared/signal-store-models.ts +30 -0
  47. package/src/lib/shared/throw-if-null.ts +7 -0
  48. package/src/lib/storage-sync/features/with-indexed-db.ts +81 -0
  49. package/src/lib/storage-sync/features/with-local-storage.ts +58 -0
  50. package/src/lib/storage-sync/internal/indexeddb.service.ts +124 -0
  51. package/src/lib/storage-sync/internal/local-storage.service.ts +19 -0
  52. package/src/lib/storage-sync/internal/models.ts +62 -0
  53. package/src/lib/storage-sync/internal/session-storage.service.ts +18 -0
  54. package/src/lib/storage-sync/tests/indexeddb.service.spec.ts +99 -0
  55. package/src/lib/storage-sync/tests/with-storage-async.spec.ts +305 -0
  56. package/src/lib/storage-sync/tests/with-storage-sync.spec.ts +273 -0
  57. package/src/lib/storage-sync/with-storage-sync.ts +236 -0
  58. package/src/lib/with-call-state.spec.ts +42 -0
  59. package/src/lib/with-call-state.ts +195 -0
  60. package/src/lib/with-conditional.spec.ts +125 -0
  61. package/src/lib/with-conditional.ts +74 -0
  62. package/src/lib/with-data-service.spec.ts +564 -0
  63. package/src/lib/with-data-service.ts +433 -0
  64. package/src/lib/with-feature-factory.spec.ts +69 -0
  65. package/src/lib/with-feature-factory.ts +56 -0
  66. package/src/lib/with-pagination.spec.ts +135 -0
  67. package/src/lib/with-pagination.ts +373 -0
  68. package/src/lib/with-redux.spec.ts +258 -0
  69. package/src/lib/with-redux.ts +387 -0
  70. package/src/lib/with-reset.spec.ts +112 -0
  71. package/src/lib/with-reset.ts +62 -0
  72. package/src/lib/with-undo-redo.spec.ts +274 -0
  73. package/src/lib/with-undo-redo.ts +200 -0
  74. package/src/test-setup.ts +6 -0
  75. package/tsconfig.json +29 -0
  76. package/tsconfig.lib.json +17 -0
  77. package/tsconfig.lib.prod.json +9 -0
  78. package/tsconfig.spec.json +17 -0
  79. package/fesm2022/angular-architects-ngrx-toolkit-redux-connector.mjs +0 -119
  80. package/fesm2022/angular-architects-ngrx-toolkit-redux-connector.mjs.map +0 -1
  81. package/fesm2022/angular-architects-ngrx-toolkit.mjs +0 -1780
  82. package/fesm2022/angular-architects-ngrx-toolkit.mjs.map +0 -1
  83. package/index.d.ts +0 -938
  84. package/redux-connector/index.d.ts +0 -59
@@ -1,1780 +0,0 @@
1
- import * as i0 from '@angular/core';
2
- import { Injectable, InjectionToken, signal, effect, inject, PLATFORM_ID, computed, isSignal, untracked, isDevMode as isDevMode$1 } from '@angular/core';
3
- import { watchState, getState, signalStoreFeature, withMethods, withHooks, patchState as patchState$1, withState, withComputed, withProps } from '@ngrx/signals';
4
- import { isPlatformBrowser, isPlatformServer } from '@angular/common';
5
- import { Subject } from 'rxjs';
6
- import { removeEntity, setAllEntities, updateEntity, addEntity } from '@ngrx/signals/entities';
7
-
8
- const DEVTOOLS_FEATURE = Symbol('DEVTOOLS_FEATURE');
9
- function createDevtoolsFeature(options) {
10
- return {
11
- [DEVTOOLS_FEATURE]: true,
12
- ...options,
13
- };
14
- }
15
-
16
- /**
17
- * If multiple instances of the same SignalStore class
18
- * exist, their devtool names are indexed.
19
- *
20
- * For example:
21
- *
22
- * ```typescript
23
- * const Store = signalStore(
24
- * withDevtools('flights')
25
- * )
26
- *
27
- * const store1 = new Store(); // will show up as 'flights'
28
- * const store2 = new Store(); // will show up as 'flights-1'
29
- * ```
30
- *
31
- * With adding `withDisabledNameIndices` to the store:
32
- * ```typescript
33
- * const Store = signalStore(
34
- * withDevtools('flights', withDisabledNameIndices())
35
- * )
36
- *
37
- * const store1 = new Store(); // will show up as 'flights'
38
- * const store2 = new Store(); //💥 throws an error
39
- * ```
40
- *
41
- */
42
- function withDisabledNameIndices() {
43
- return createDevtoolsFeature({ indexNames: false });
44
- }
45
-
46
- function throwIfNull(obj) {
47
- if (obj === null || obj === undefined) {
48
- throw new Error('');
49
- }
50
- return obj;
51
- }
52
-
53
- /**
54
- * Internal Service used by {@link withGlitchTracking}. It does not rely
55
- * on `effect` as {@link DefaultTracker} does but uses the NgRx function
56
- * `watchState` to track all state changes.
57
- */
58
- class GlitchTrackerService {
59
- #stores = {};
60
- #callback;
61
- get stores() {
62
- return Object.entries(this.#stores).reduce((acc, [id, { store }]) => {
63
- acc[id] = store;
64
- return acc;
65
- }, {});
66
- }
67
- onChange(callback) {
68
- this.#callback = callback;
69
- }
70
- removeStore(id) {
71
- this.#stores = Object.entries(this.#stores).reduce((newStore, [storeId, value]) => {
72
- if (storeId !== id) {
73
- newStore[storeId] = value;
74
- }
75
- else {
76
- value.destroyWatcher();
77
- }
78
- return newStore;
79
- }, {});
80
- throwIfNull(this.#callback)({});
81
- }
82
- track(id, store) {
83
- const watcher = watchState(store, (state) => {
84
- throwIfNull(this.#callback)({ [id]: state });
85
- });
86
- this.#stores[id] = { destroyWatcher: watcher.destroy, store };
87
- }
88
- notifyRenamedStore(id) {
89
- if (Object.keys(this.#stores).includes(id) && this.#callback) {
90
- this.#callback({ [id]: getState(this.#stores[id].store) });
91
- }
92
- }
93
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: GlitchTrackerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
94
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: GlitchTrackerService, providedIn: 'root' }); }
95
- }
96
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: GlitchTrackerService, decorators: [{
97
- type: Injectable,
98
- args: [{ providedIn: 'root' }]
99
- }] });
100
-
101
- /**
102
- * It tracks all state changes of the State, including intermediary updates
103
- * that are typically suppressed by Angular's glitch-free mechanism.
104
- *
105
- * This feature is especially useful for debugging.
106
- *
107
- * Example:
108
- *
109
- * ```typescript
110
- * const Store = signalStore(
111
- * { providedIn: 'root' },
112
- * withState({ count: 0 }),
113
- * withDevtools('counter', withGlitchTracking()),
114
- * withMethods((store) => ({
115
- * increase: () =>
116
- * patchState(store, (value) => ({ count: value.count + 1 })),
117
- * }))
118
- * );
119
- *
120
- * // would show up in the DevTools with value 0
121
- * const store = inject(Store);
122
- *
123
- * store.increase(); // would show up in the DevTools with value 1
124
- * store.increase(); // would show up in the DevTools with value 2
125
- * store.increase(); // would show up in the DevTools with value 3
126
- * ```
127
- *
128
- * Without `withGlitchTracking`, the DevTools would only show the final value of 3.
129
- */
130
- function withGlitchTracking() {
131
- return createDevtoolsFeature({ tracker: GlitchTrackerService });
132
- }
133
-
134
- /**
135
- * Allows you to define a function to map the state.
136
- *
137
- * It is needed for huge states, that slows down the Devtools and where
138
- * you don't need to see the whole state or other reasons.
139
- *
140
- * Example:
141
- *
142
- * ```typescript
143
- * const initialState = {
144
- * id: 1,
145
- * email: 'john.list@host.com',
146
- * name: 'John List',
147
- * enteredPassword: ''
148
- * }
149
- *
150
- * const Store = signalStore(
151
- * withState(initialState),
152
- * withDevtools(
153
- * 'user',
154
- * withMapper(state => ({...state, enteredPassword: '***' }))
155
- * )
156
- * )
157
- * ```
158
- *
159
- * @param map function which maps the state
160
- */
161
- function withMapper(map) {
162
- return createDevtoolsFeature({ map: map });
163
- }
164
-
165
- /**
166
- * Provides the configuration options for connecting to the Redux DevTools Extension.
167
- */
168
- function provideDevtoolsConfig(config) {
169
- return {
170
- provide: REDUX_DEVTOOLS_CONFIG,
171
- useValue: config,
172
- };
173
- }
174
- /**
175
- * Injection token for the configuration options for connecting to the Redux DevTools Extension.
176
- */
177
- const REDUX_DEVTOOLS_CONFIG = new InjectionToken('ReduxDevtoolsConfig');
178
-
179
- class DefaultTracker {
180
- #stores = signal({}, ...(ngDevMode ? [{ debugName: "#stores" }] : []));
181
- get stores() {
182
- return this.#stores();
183
- }
184
- #trackCallback;
185
- #trackingEffect = effect(() => {
186
- if (this.#trackCallback === undefined) {
187
- throw new Error('no callback function defined');
188
- }
189
- const stores = this.#stores();
190
- const fullState = Object.entries(stores).reduce((acc, [id, store]) => {
191
- return { ...acc, [id]: getState(store) };
192
- }, {});
193
- this.#trackCallback(fullState);
194
- }, ...(ngDevMode ? [{ debugName: "#trackingEffect" }] : []));
195
- track(id, store) {
196
- this.#stores.update((value) => ({
197
- ...value,
198
- [id]: store,
199
- }));
200
- }
201
- onChange(callback) {
202
- this.#trackCallback = callback;
203
- }
204
- removeStore(id) {
205
- this.#stores.update((stores) => Object.entries(stores).reduce((newStore, [storeId, state]) => {
206
- if (storeId !== id) {
207
- newStore[storeId] = state;
208
- }
209
- return newStore;
210
- }, {}));
211
- }
212
- notifyRenamedStore(id) {
213
- if (this.#stores()[id]) {
214
- this.#stores.update((stores) => {
215
- return { ...stores };
216
- });
217
- }
218
- }
219
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: DefaultTracker, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
220
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: DefaultTracker, providedIn: 'root' }); }
221
- }
222
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: DefaultTracker, decorators: [{
223
- type: Injectable,
224
- args: [{ providedIn: 'root' }]
225
- }] });
226
-
227
- const currentActionNames = new Set();
228
-
229
- const dummyConnection = {
230
- send: () => void true,
231
- };
232
- /**
233
- * A service provided by the root injector is
234
- * required because the synchronization runs
235
- * globally.
236
- *
237
- * The SignalStore could be provided in a component.
238
- * If the effect starts in the injection
239
- * context of the SignalStore, the complete sync
240
- * process would shut down once the component gets
241
- * destroyed.
242
- */
243
- class DevtoolsSyncer {
244
- /**
245
- * Stores all SignalStores that are connected to the
246
- * DevTools along their options, names and id.
247
- */
248
- #stores = {};
249
- #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
250
- #trackers = [];
251
- #devtoolsConfig = {
252
- name: 'NgRx SignalStore',
253
- ...inject(REDUX_DEVTOOLS_CONFIG, { optional: true }),
254
- };
255
- /**
256
- * Maintains the current states of all stores to avoid conflicts
257
- * between glitch-free and glitched trackers when used simultaneously.
258
- *
259
- * The challenge lies in ensuring that glitched trackers do not
260
- * interfere with the synchronization process of glitch-free trackers.
261
- * Specifically, glitched trackers could cause the synchronization to
262
- * read the current state of stores managed by glitch-free trackers.
263
- *
264
- * Therefore, the synchronization process doesn't read the state from
265
- * each store, but relies on #currentState.
266
- *
267
- * Please note, that here the key is the name and not the id.
268
- */
269
- #currentState = {};
270
- #currentId = 1;
271
- #connection = this.#isBrowser
272
- ? window.__REDUX_DEVTOOLS_EXTENSION__
273
- ? window.__REDUX_DEVTOOLS_EXTENSION__.connect(this.#devtoolsConfig)
274
- : dummyConnection
275
- : dummyConnection;
276
- constructor() {
277
- if (!this.#isBrowser) {
278
- return;
279
- }
280
- }
281
- ngOnDestroy() {
282
- currentActionNames.clear();
283
- }
284
- syncToDevTools(changedStatePerId) {
285
- const mappedChangedStatePerName = Object.entries(changedStatePerId).reduce((acc, [id, store]) => {
286
- const { options, name } = this.#stores[id];
287
- acc[name] = options.map(store);
288
- return acc;
289
- }, {});
290
- this.#currentState = {
291
- ...this.#currentState,
292
- ...mappedChangedStatePerName,
293
- };
294
- const names = Array.from(currentActionNames);
295
- const type = names.length ? names.join(', ') : 'Store Update';
296
- currentActionNames.clear();
297
- this.#connection.send({ type }, this.#currentState);
298
- }
299
- getNextId() {
300
- return String(this.#currentId++);
301
- }
302
- /**
303
- * Consumer provides the id. That is because we can only start
304
- * tracking the store in the init hook.
305
- * Unfortunately, methods for renaming having the final id
306
- * need to be defined already before.
307
- * That's why `withDevtools` requests first the id and
308
- * then registers itself later.
309
- */
310
- addStore(id, name, store, options) {
311
- let storeName = name;
312
- const names = Object.values(this.#stores).map((store) => store.name);
313
- if (names.includes(storeName)) {
314
- // const { options } = throwIfNull(
315
- // Object.values(this.#stores).find((store) => store.name === storeName)
316
- // );
317
- if (!options.indexNames) {
318
- throw new Error(`An instance of the store ${storeName} already exists. \
319
- Enable automatic indexing via withDevTools('${storeName}', { indexNames: true }), or rename it upon instantiation.`);
320
- }
321
- }
322
- for (let i = 1; names.includes(storeName); i++) {
323
- storeName = `${name}-${i}`;
324
- }
325
- this.#stores[id] = { name: storeName, options };
326
- const tracker = options.tracker;
327
- if (!this.#trackers.includes(tracker)) {
328
- this.#trackers.push(tracker);
329
- }
330
- tracker.onChange((changedState) => this.syncToDevTools(changedState));
331
- tracker.track(id, store);
332
- }
333
- removeStore(id) {
334
- const name = this.#stores[id].name;
335
- this.#stores = Object.entries(this.#stores).reduce((newStore, [storeId, value]) => {
336
- if (storeId !== id) {
337
- newStore[storeId] = value;
338
- }
339
- return newStore;
340
- }, {});
341
- this.#currentState = Object.entries(this.#currentState).reduce((newState, [storeName, state]) => {
342
- if (storeName !== name) {
343
- newState[name] = state;
344
- }
345
- return newState;
346
- }, {});
347
- for (const tracker of this.#trackers) {
348
- tracker.removeStore(id);
349
- }
350
- }
351
- renameStore(oldName, newName) {
352
- const storeNames = Object.values(this.#stores).map((store) => store.name);
353
- const id = throwIfNull(Object.keys(this.#stores).find((id) => this.#stores[id].name === oldName));
354
- if (storeNames.includes(newName)) {
355
- throw new Error(`NgRx Toolkit/DevTools: cannot rename from ${oldName} to ${newName}. ${newName} is already assigned to another SignalStore instance.`);
356
- }
357
- this.#stores = Object.entries(this.#stores).reduce((newStore, [id, value]) => {
358
- if (value.name === oldName) {
359
- newStore[id] = { ...value, name: newName };
360
- }
361
- else {
362
- newStore[id] = value;
363
- }
364
- return newStore;
365
- }, {});
366
- // we don't rename in #currentState but wait for tracker to notify
367
- // us with a changed state that contains that name.
368
- this.#currentState = Object.entries(this.#currentState).reduce((newState, [storeName, state]) => {
369
- if (storeName !== oldName) {
370
- newState[storeName] = state;
371
- }
372
- return newState;
373
- }, {});
374
- this.#trackers.forEach((tracker) => tracker.notifyRenamedStore(id));
375
- }
376
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: DevtoolsSyncer, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
377
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: DevtoolsSyncer, providedIn: 'root' }); }
378
- }
379
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: DevtoolsSyncer, decorators: [{
380
- type: Injectable,
381
- args: [{ providedIn: 'root' }]
382
- }], ctorParameters: () => [] });
383
-
384
- const renameDevtoolsMethodName = '___renameDevtoolsName';
385
- const uniqueDevtoolsId = '___uniqueDevtoolsId';
386
- const EXISTING_NAMES = new InjectionToken('Array contain existing names for the signal stores', { factory: () => [], providedIn: 'root' });
387
- /**
388
- * Adds this store as a feature state to the Redux DevTools.
389
- *
390
- * By default, the action name is 'Store Update'. You can
391
- * change that via the {@link updateState} method, which has as second
392
- * parameter the action name.
393
- *
394
- * The standalone function {@link renameDevtoolsName} can rename
395
- * the store name.
396
- *
397
- * @param name name of the store as it should appear in the DevTools
398
- * @param features features to extend or modify the behavior of the Devtools
399
- */
400
- function withDevtools(name, ...features) {
401
- return signalStoreFeature(withMethods(() => {
402
- const syncer = inject(DevtoolsSyncer);
403
- const id = syncer.getNextId();
404
- // TODO: use withProps and symbols
405
- return {
406
- [renameDevtoolsMethodName]: (newName) => {
407
- syncer.renameStore(name, newName);
408
- },
409
- [uniqueDevtoolsId]: () => id,
410
- };
411
- }), withHooks((store) => {
412
- const syncer = inject(DevtoolsSyncer);
413
- const id = String(store[uniqueDevtoolsId]());
414
- return {
415
- onInit() {
416
- const id = String(store[uniqueDevtoolsId]());
417
- const finalOptions = {
418
- indexNames: !features.some((f) => f.indexNames === false),
419
- map: features.find((f) => f.map)?.map ?? ((state) => state),
420
- tracker: inject(features.find((f) => f.tracker)?.tracker || DefaultTracker),
421
- };
422
- syncer.addStore(id, name, store, finalOptions);
423
- },
424
- onDestroy() {
425
- syncer.removeStore(id);
426
- },
427
- };
428
- }));
429
- }
430
-
431
- /**
432
- * Renames the name of a store how it appears in the Devtools.
433
- * @param store instance of the SignalStore
434
- * @param newName new name for the Devtools
435
- */
436
- function renameDevtoolsName(store, newName) {
437
- const renameMethod = store[renameDevtoolsMethodName];
438
- if (!renameMethod) {
439
- throw new Error("Devtools extensions haven't been added to this store.");
440
- }
441
- renameMethod(newName);
442
- }
443
-
444
- /**
445
- * @deprecated Has been renamed to `updateState`
446
- */
447
- const patchState = (state, action, ...rest) => {
448
- updateState(state, action, ...rest);
449
- };
450
- /**
451
- * Wrapper of `patchState` for DevTools integration. Next to updating the state,
452
- * it also sends the action to the DevTools.
453
- * @param stateSource state of Signal Store
454
- * @param action name of action how it will show in DevTools
455
- * @param updaters updater functions or objects
456
- */
457
- function updateState(stateSource, action, ...updaters) {
458
- currentActionNames.add(action);
459
- return patchState$1(stateSource, ...updaters);
460
- }
461
-
462
- /**
463
- * Stub for DevTools integration. Can be used to disable DevTools in production.
464
- */
465
- const withDevToolsStub = () => (store) => store;
466
-
467
- function assertActionFnSpecs(obj) {
468
- if (!obj || typeof obj !== 'object') {
469
- throw new Error('%o is not an Action Specification');
470
- }
471
- }
472
-
473
- function payload() {
474
- return {};
475
- }
476
- const noPayload = {};
477
- /**
478
- * Creates a reducer function to separate the reducer logic into another file.
479
- *
480
- * ```typescript
481
- * interface FlightState {
482
- * flights: Flight[];
483
- * effect1: boolean;
484
- * effect2: boolean;
485
- * }
486
- *
487
- * const initialState: FlightState = {
488
- * flights: [],
489
- * effect1: false,
490
- * effect2: false,
491
- * };
492
- *
493
- * const actions = {
494
- * init: noPayload,
495
- * updateEffect1: payload<{ value: boolean }>(),
496
- * updateEffect2: payload<{ value: boolean }>(),
497
- * };
498
- *
499
- * const reducer = createReducer<FlightState, typeof actions>((actions, on) => {
500
- * on(actions.updateEffect1, (state, { value }) => {
501
- * patchState(state, { effect1: value });
502
- * });
503
- *
504
- * on(actions.updateEffect2, (state, { value }) => {
505
- * patchState(state, { effect2: value });
506
- * });
507
- * });
508
- *
509
- * signalStore(
510
- * withState(initialState),
511
- * withRedux({
512
- * actions,
513
- * reducer,
514
- * })
515
- * );
516
- * ```
517
- * @param reducerFactory
518
- */
519
- function createReducer(reducerFactory) {
520
- return reducerFactory;
521
- }
522
- /**
523
- * @deprecated Use NgRx's `@ngrx/signals/events` starting in 19.2
524
- *
525
- * Creates the effects function to separate the effects logic into another file.
526
- *
527
- * ```typescript
528
- * interface FlightState {
529
- * flights: Flight[];
530
- * effect1: boolean;
531
- * effect2: boolean;
532
- * }
533
- *
534
- * const initialState: FlightState = {
535
- * flights: [],
536
- * effect1: false,
537
- * effect2: false,
538
- * };
539
- *
540
- * const actions = {
541
- * init: noPayload,
542
- * updateEffect1: payload<{ value: boolean }>(),
543
- * updateEffect2: payload<{ value: boolean }>(),
544
- * };
545
- *
546
- * const effects = createEffects(actions, (actions, create) => {
547
- * return {
548
- * init1$: create(actions.init).pipe(
549
- * map(() => actions.updateEffect1({ value: true }))
550
- * ),
551
- * init2$: create(actions.init).pipe(
552
- * map(() => actions.updateEffect2({ value: true }))
553
- * ),
554
- * };
555
- * });
556
- *
557
- * signalStore(
558
- * withState(initialState),
559
- * withRedux({
560
- * actions,
561
- * effects,
562
- * })
563
- * );
564
- * ```
565
- * @param actions
566
- * @param effectsFactory
567
- */
568
- function createEffects(actions, effectsFactory) {
569
- return effectsFactory;
570
- }
571
- function createActionFns(actionFnSpecs, reducerRegistry, effectsRegistry, state) {
572
- const actionFns = {};
573
- for (const type in actionFnSpecs) {
574
- const actionFn = (payload) => {
575
- const fullPayload = { ...payload, type };
576
- const reducer = reducerRegistry[type];
577
- if (reducer) {
578
- reducer(state, fullPayload);
579
- }
580
- const effectSubjects = effectsRegistry[type];
581
- if (effectSubjects?.length) {
582
- for (const effectSubject of effectSubjects) {
583
- effectSubject.next(fullPayload);
584
- }
585
- }
586
- return fullPayload;
587
- };
588
- actionFn.type = type.toString();
589
- actionFns[type] = actionFn;
590
- }
591
- return actionFns;
592
- }
593
- function createPublicAndAllActionsFns(actionFnSpecs, reducerRegistry, effectsRegistry, state) {
594
- if ('public' in actionFnSpecs || 'private' in actionFnSpecs) {
595
- const privates = actionFnSpecs['private'] || {};
596
- const publics = actionFnSpecs['public'] || {};
597
- assertActionFnSpecs(privates);
598
- assertActionFnSpecs(publics);
599
- const privateActionFns = createActionFns(privates, reducerRegistry, effectsRegistry, state);
600
- const publicActionFns = createActionFns(publics, reducerRegistry, effectsRegistry, state);
601
- return {
602
- all: { ...privateActionFns, ...publicActionFns },
603
- publics: publicActionFns,
604
- };
605
- }
606
- const actionFns = createActionFns(actionFnSpecs, reducerRegistry, effectsRegistry, state);
607
- return { all: actionFns, publics: actionFns };
608
- }
609
- function fillReducerRegistry(reducer, actionFns, reducerRegistry) {
610
- function on(action, reducerFn) {
611
- reducerRegistry[action.type] = reducerFn;
612
- }
613
- reducer(actionFns, on);
614
- return reducerRegistry;
615
- }
616
- function fillEffects(effects, actionFns, effectsRegistry = {}) {
617
- function create(action) {
618
- const subject = new Subject();
619
- if (!(action.type in effectsRegistry)) {
620
- effectsRegistry[action.type] = [];
621
- }
622
- effectsRegistry[action.type].push(subject);
623
- return subject.asObservable();
624
- }
625
- const effectObservables = effects(actionFns, create);
626
- return Object.values(effectObservables);
627
- }
628
- function startSubscriptions(observables) {
629
- return observables.map((observable) => observable.subscribe());
630
- }
631
- function processRedux(actionFnSpecs, reducer, effects, store) {
632
- const reducerRegistry = {};
633
- const effectsRegistry = {};
634
- const actionsMap = createPublicAndAllActionsFns(actionFnSpecs, reducerRegistry, effectsRegistry, store);
635
- const actionFns = actionsMap.all;
636
- const publicActionsFns = actionsMap.publics;
637
- fillReducerRegistry(reducer, actionFns, reducerRegistry);
638
- const effectObservables = fillEffects(effects, actionFns, effectsRegistry);
639
- const subscriptions = startSubscriptions(effectObservables);
640
- return {
641
- methods: publicActionsFns,
642
- subscriptions: subscriptions,
643
- };
644
- }
645
- /**
646
- * @param redux redux
647
- *
648
- * properties do not start with `with` since they are not extension functions on their own.
649
- *
650
- * no dependency to NgRx
651
- *
652
- * actions are passed to reducer and effects, but it is also possible to use other actions.
653
- * effects provide forAction and do not return anything. that is important because effects should stay inaccessible
654
- */
655
- function withRedux(redux) {
656
- return (store) => {
657
- const { methods } = processRedux(redux.actions, redux.reducer, redux.effects, store);
658
- return {
659
- ...store,
660
- methods: { ...store.methods, ...methods },
661
- };
662
- };
663
- }
664
-
665
- function deriveCallStateKeys(collection) {
666
- return {
667
- callStateKey: collection ? `${collection}CallState` : 'callState',
668
- loadingKey: collection ? `${collection}Loading` : 'loading',
669
- loadedKey: collection ? `${collection}Loaded` : 'loaded',
670
- errorKey: collection ? `${collection}Error` : 'error',
671
- };
672
- }
673
- function getCallStateKeys(config) {
674
- const prop = config?.collection;
675
- return deriveCallStateKeys(prop);
676
- }
677
- function getCollectionArray(config) {
678
- return 'collections' in config
679
- ? config.collections
680
- : 'collection' in config && config.collection
681
- ? [config.collection]
682
- : undefined;
683
- }
684
- function withCallState(config) {
685
- return signalStoreFeature(withState(() => {
686
- if (!config) {
687
- return { callState: 'init' };
688
- }
689
- const collections = getCollectionArray(config);
690
- if (collections) {
691
- return collections.reduce((acc, cur) => ({
692
- ...acc,
693
- ...{ [cur ? `${cur}CallState` : 'callState']: 'init' },
694
- }), {});
695
- }
696
- return { callState: 'init' };
697
- }), withComputed((state) => {
698
- if (config) {
699
- const collections = getCollectionArray(config);
700
- if (collections) {
701
- return collections.reduce((acc, cur) => {
702
- const { callStateKey, errorKey, loadedKey, loadingKey } = deriveCallStateKeys(cur);
703
- const callState = state[callStateKey];
704
- return {
705
- ...acc,
706
- [loadingKey]: computed(() => callState() === 'loading'),
707
- [loadedKey]: computed(() => callState() === 'loaded'),
708
- [errorKey]: computed(() => {
709
- const v = callState();
710
- return typeof v === 'object' ? v.error : null;
711
- }),
712
- };
713
- }, {});
714
- }
715
- }
716
- const { callStateKey, errorKey, loadedKey, loadingKey } = deriveCallStateKeys();
717
- const callState = state[callStateKey];
718
- return {
719
- [loadingKey]: computed(() => callState() === 'loading'),
720
- [loadedKey]: computed(() => callState() === 'loaded'),
721
- [errorKey]: computed(() => {
722
- const v = callState();
723
- return typeof v === 'object' ? v.error : null;
724
- }),
725
- };
726
- }));
727
- }
728
- function setLoading(prop) {
729
- if (prop) {
730
- return { [`${prop}CallState`]: 'loading' };
731
- }
732
- return { callState: 'loading' };
733
- }
734
- function setLoaded(prop) {
735
- if (prop) {
736
- return { [`${prop}CallState`]: 'loaded' };
737
- }
738
- else {
739
- return { callState: 'loaded' };
740
- }
741
- }
742
- function setError(error, prop) {
743
- let errorMessage;
744
- if (!error) {
745
- errorMessage = '';
746
- }
747
- else if (typeof error === 'object' && 'message' in error) {
748
- errorMessage = String(error.message);
749
- }
750
- else {
751
- errorMessage = String(error);
752
- }
753
- if (prop) {
754
- return {
755
- [`${prop}CallState`]: { error: errorMessage },
756
- };
757
- }
758
- else {
759
- return { callState: { error: errorMessage } };
760
- }
761
- }
762
-
763
- function capitalize(str) {
764
- return str ? str[0].toUpperCase() + str.substring(1) : str;
765
- }
766
- function getDataServiceKeys(options) {
767
- const filterKey = options.collection
768
- ? `${options.collection}Filter`
769
- : 'filter';
770
- const selectedIdsKey = options.collection
771
- ? `selected${capitalize(options.collection)}Ids`
772
- : 'selectedIds';
773
- const selectedEntitiesKey = options.collection
774
- ? `selected${capitalize(options.collection)}Entities`
775
- : 'selectedEntities';
776
- const updateFilterKey = options.collection
777
- ? `update${capitalize(options.collection)}Filter`
778
- : 'updateFilter';
779
- const updateSelectedKey = options.collection
780
- ? `updateSelected${capitalize(options.collection)}Entities`
781
- : 'updateSelected';
782
- const loadKey = options.collection
783
- ? `load${capitalize(options.collection)}Entities`
784
- : 'load';
785
- const currentKey = options.collection
786
- ? `current${capitalize(options.collection)}`
787
- : 'current';
788
- const loadByIdKey = options.collection
789
- ? `load${capitalize(options.collection)}ById`
790
- : 'loadById';
791
- const setCurrentKey = options.collection
792
- ? `setCurrent${capitalize(options.collection)}`
793
- : 'setCurrent';
794
- const createKey = options.collection
795
- ? `create${capitalize(options.collection)}`
796
- : 'create';
797
- const updateKey = options.collection
798
- ? `update${capitalize(options.collection)}`
799
- : 'update';
800
- const updateAllKey = options.collection
801
- ? `updateAll${capitalize(options.collection)}`
802
- : 'updateAll';
803
- const deleteKey = options.collection
804
- ? `delete${capitalize(options.collection)}`
805
- : 'delete';
806
- // TODO: Take these from @ngrx/signals/entities, when they are exported
807
- const entitiesKey = options.collection
808
- ? `${options.collection}Entities`
809
- : 'entities';
810
- const entityMapKey = options.collection
811
- ? `${options.collection}EntityMap`
812
- : 'entityMap';
813
- const idsKey = options.collection ? `${options.collection}Ids` : 'ids';
814
- return {
815
- filterKey,
816
- selectedIdsKey,
817
- selectedEntitiesKey,
818
- updateFilterKey,
819
- updateSelectedKey,
820
- loadKey,
821
- entitiesKey,
822
- entityMapKey,
823
- idsKey,
824
- currentKey,
825
- loadByIdKey,
826
- setCurrentKey,
827
- createKey,
828
- updateKey,
829
- updateAllKey,
830
- deleteKey,
831
- };
832
- }
833
- function withDataService(options) {
834
- const { dataServiceType, filter, collection: prefix } = options;
835
- const { entitiesKey, filterKey, loadKey, selectedEntitiesKey, selectedIdsKey, updateFilterKey, updateSelectedKey, currentKey, createKey, updateKey, updateAllKey, deleteKey, loadByIdKey, setCurrentKey, } = getDataServiceKeys(options);
836
- const { callStateKey } = getCallStateKeys({ collection: prefix });
837
- return signalStoreFeature(withState(() => ({
838
- [filterKey]: filter,
839
- [selectedIdsKey]: {},
840
- [currentKey]: undefined,
841
- })), withComputed((store) => {
842
- const entities = store[entitiesKey];
843
- const selectedIds = store[selectedIdsKey];
844
- return {
845
- [selectedEntitiesKey]: computed(() => entities().filter((e) => selectedIds()[e.id])),
846
- };
847
- }), withMethods((store) => {
848
- const dataService = inject(dataServiceType);
849
- return {
850
- [updateFilterKey]: (filter) => {
851
- patchState$1(store, { [filterKey]: filter });
852
- },
853
- [updateSelectedKey]: (id, selected) => {
854
- patchState$1(store, (state) => ({
855
- [selectedIdsKey]: {
856
- ...state[selectedIdsKey],
857
- [id]: selected,
858
- },
859
- }));
860
- },
861
- [loadKey]: async () => {
862
- const filter = store[filterKey];
863
- (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
864
- try {
865
- const result = await dataService.load(filter());
866
- patchState$1(store, prefix
867
- ? setAllEntities(result, { collection: prefix })
868
- : setAllEntities(result));
869
- (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
870
- }
871
- catch (e) {
872
- (() => store[callStateKey] &&
873
- patchState$1(store, setError(e, prefix)))();
874
- throw e;
875
- }
876
- },
877
- [loadByIdKey]: async (id) => {
878
- (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
879
- try {
880
- const current = await dataService.loadById(id);
881
- (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
882
- patchState$1(store, { [currentKey]: current });
883
- }
884
- catch (e) {
885
- (() => store[callStateKey] &&
886
- patchState$1(store, setError(e, prefix)))();
887
- throw e;
888
- }
889
- },
890
- [setCurrentKey]: (current) => {
891
- patchState$1(store, { [currentKey]: current });
892
- },
893
- [createKey]: async (entity) => {
894
- patchState$1(store, { [currentKey]: entity });
895
- (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
896
- try {
897
- const created = await dataService.create(entity);
898
- patchState$1(store, { [currentKey]: created });
899
- patchState$1(store, prefix
900
- ? addEntity(created, { collection: prefix })
901
- : addEntity(created));
902
- (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
903
- }
904
- catch (e) {
905
- (() => store[callStateKey] &&
906
- patchState$1(store, setError(e, prefix)))();
907
- throw e;
908
- }
909
- },
910
- [updateKey]: async (entity) => {
911
- patchState$1(store, { [currentKey]: entity });
912
- (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
913
- try {
914
- const updated = await dataService.update(entity);
915
- patchState$1(store, { [currentKey]: updated });
916
- const updateArg = {
917
- id: updated.id,
918
- changes: updated,
919
- };
920
- const updater = (collection) => updateEntity(updateArg, { collection });
921
- patchState$1(store, prefix ? updater(prefix) : updateEntity(updateArg));
922
- (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
923
- }
924
- catch (e) {
925
- (() => store[callStateKey] &&
926
- patchState$1(store, setError(e, prefix)))();
927
- throw e;
928
- }
929
- },
930
- [updateAllKey]: async (entities) => {
931
- (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
932
- try {
933
- const result = await dataService.updateAll(entities);
934
- patchState$1(store, prefix
935
- ? setAllEntities(result, { collection: prefix })
936
- : setAllEntities(result));
937
- (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
938
- }
939
- catch (e) {
940
- (() => store[callStateKey] &&
941
- patchState$1(store, setError(e, prefix)))();
942
- throw e;
943
- }
944
- },
945
- [deleteKey]: async (entity) => {
946
- patchState$1(store, { [currentKey]: entity });
947
- (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
948
- try {
949
- await dataService.delete(entity);
950
- patchState$1(store, { [currentKey]: undefined });
951
- patchState$1(store, prefix
952
- ? removeEntity(entity.id, { collection: prefix })
953
- : removeEntity(entity.id));
954
- (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
955
- }
956
- catch (e) {
957
- (() => store[callStateKey] &&
958
- patchState$1(store, setError(e, prefix)))();
959
- throw e;
960
- }
961
- },
962
- };
963
- }));
964
- }
965
-
966
- /** With pagination comes in two flavors the first one is local pagination or in memory pagination. For example we have 2000 items which we want
967
- * to display in a table and the response payload is small enough to be stored in the memory. But we can not display all 2000 items at once
968
- * so we need to paginate the data. The second flavor is server side pagination where the response payload is too large to be stored in the memory
969
- * and we need to fetch the data from the server in chunks. In the second case we 'could' also cache the data in the memory but that could lead to
970
- * other problems like memory leaks and stale data. So we will not cache the data in the memory in the second case.
971
- * This feature implements the local pagination.
972
- */
973
- function withPagination(options) {
974
- const { pageKey, pageSizeKey, entitiesKey, selectedPageEntitiesKey, totalCountKey, pageCountKey, pageNavigationArrayMaxKey, pageNavigationArrayKey, hasNextPageKey, hasPreviousPageKey, } = createPaginationKeys(options);
975
- return signalStoreFeature(withState({
976
- [pageKey]: 0,
977
- [pageSizeKey]: 10,
978
- [pageNavigationArrayMaxKey]: 7,
979
- }), withComputed((store) => {
980
- const entities = store[entitiesKey];
981
- const page = store[pageKey];
982
- const pageSize = store[pageSizeKey];
983
- const pageNavigationArrayMax = store[pageNavigationArrayMaxKey];
984
- return {
985
- // The derived enitites which are displayed on the current page
986
- [selectedPageEntitiesKey]: computed(() => {
987
- const pageSizeValue = pageSize();
988
- const pageValue = page();
989
- return entities().slice(pageValue * pageSizeValue, (pageValue + 1) * pageSizeValue);
990
- }),
991
- [totalCountKey]: computed(() => entities().length),
992
- [pageCountKey]: computed(() => {
993
- const totalCountValue = entities().length;
994
- const pageSizeValue = pageSize();
995
- if (totalCountValue === 0) {
996
- return 0;
997
- }
998
- return Math.ceil(totalCountValue / pageSizeValue);
999
- }),
1000
- [pageNavigationArrayKey]: computed(() => createPageArray(page(), pageSize(), entities().length, pageNavigationArrayMax())),
1001
- [hasNextPageKey]: computed(() => {
1002
- return page() < pageSize();
1003
- }),
1004
- [hasPreviousPageKey]: computed(() => {
1005
- return page() > 1;
1006
- }),
1007
- };
1008
- }));
1009
- }
1010
- function gotoPage(page, options) {
1011
- const { pageKey } = createPaginationKeys(options);
1012
- return {
1013
- [pageKey]: page,
1014
- };
1015
- }
1016
- function setPageSize(pageSize, options) {
1017
- const { pageSizeKey } = createPaginationKeys(options);
1018
- return {
1019
- [pageSizeKey]: pageSize,
1020
- };
1021
- }
1022
- function nextPage(options) {
1023
- const { pageKey } = createPaginationKeys(options);
1024
- return (state) => {
1025
- const currentPage = state[pageKey];
1026
- return { [pageKey]: currentPage + 1 };
1027
- };
1028
- }
1029
- function previousPage(options) {
1030
- const { pageKey } = createPaginationKeys(options);
1031
- return (state) => {
1032
- const currentPage = state[pageKey];
1033
- return { [pageKey]: currentPage - 1 };
1034
- };
1035
- }
1036
- function firstPage(options) {
1037
- const { pageKey } = createPaginationKeys(options);
1038
- return { [pageKey]: 0 };
1039
- }
1040
- function setMaxPageNavigationArrayItems(maxPageNavigationArrayItems, options) {
1041
- const { pageNavigationArrayMaxKey } = createPaginationKeys(options);
1042
- return {
1043
- [pageNavigationArrayMaxKey]: maxPageNavigationArrayItems,
1044
- };
1045
- }
1046
- function createPaginationKeys(options) {
1047
- const entitiesKey = options?.collection
1048
- ? `${options.collection}Entities`
1049
- : 'entities';
1050
- const selectedPageEntitiesKey = options?.collection
1051
- ? `selectedPage${capitalize(options?.collection)}Entities`
1052
- : 'selectedPageEntities';
1053
- const pageKey = options?.collection
1054
- ? `${options.collection}CurrentPage`
1055
- : 'currentPage';
1056
- const pageSizeKey = options?.collection
1057
- ? `${options.collection}PageSize`
1058
- : 'pageSize';
1059
- const totalCountKey = options?.collection
1060
- ? `${options.collection}TotalCount`
1061
- : 'totalCount';
1062
- const pageCountKey = options?.collection
1063
- ? `${options.collection}PageCount`
1064
- : 'pageCount';
1065
- const pageNavigationArrayMaxKey = options?.collection
1066
- ? `${options.collection}PageNavigationArrayMax`
1067
- : 'pageNavigationArrayMax';
1068
- const pageNavigationArrayKey = options?.collection
1069
- ? `${options.collection}PageNavigationArray`
1070
- : 'pageNavigationArray';
1071
- const hasNextPageKey = options?.collection
1072
- ? `hasNext${capitalize(options.collection)}Page`
1073
- : 'hasNextPage';
1074
- const hasPreviousPageKey = options?.collection
1075
- ? `hasPrevious${capitalize(options.collection)}Page`
1076
- : 'hasPreviousPage';
1077
- return {
1078
- pageKey,
1079
- pageSizeKey,
1080
- entitiesKey,
1081
- selectedPageEntitiesKey,
1082
- totalCountKey,
1083
- pageCountKey,
1084
- pageNavigationArrayKey,
1085
- pageNavigationArrayMaxKey,
1086
- hasNextPageKey,
1087
- hasPreviousPageKey,
1088
- };
1089
- }
1090
- function createPageArray(currentPage, itemsPerPage, totalItems, paginationRange) {
1091
- // Convert paginationRange to number in case it's a string
1092
- paginationRange = +paginationRange;
1093
- // Calculate total number of pages
1094
- const totalPages = Math.max(Math.ceil(totalItems / itemsPerPage), 1);
1095
- const halfWay = Math.ceil(paginationRange / 2);
1096
- const isStart = currentPage <= halfWay;
1097
- const isEnd = totalPages - halfWay < currentPage;
1098
- const isMiddle = !isStart && !isEnd;
1099
- const ellipsesNeeded = paginationRange < totalPages;
1100
- const pages = [];
1101
- for (let i = 1; i <= totalPages && i <= paginationRange; i++) {
1102
- let pageNumber = i;
1103
- if (i === paginationRange) {
1104
- pageNumber = totalPages;
1105
- }
1106
- else if (ellipsesNeeded) {
1107
- if (isEnd) {
1108
- pageNumber = totalPages - paginationRange + i;
1109
- }
1110
- else if (isMiddle) {
1111
- pageNumber = currentPage - halfWay + i;
1112
- }
1113
- }
1114
- const openingEllipsesNeeded = i === 2 && (isMiddle || isEnd);
1115
- const closingEllipsesNeeded = i === paginationRange - 1 && (isMiddle || isStart);
1116
- const label = ellipsesNeeded && (openingEllipsesNeeded || closingEllipsesNeeded)
1117
- ? '...'
1118
- : pageNumber;
1119
- pages.push({ label, value: pageNumber });
1120
- }
1121
- return pages;
1122
- }
1123
-
1124
- /**
1125
- * Adds a `resetState` method to the store, which resets the state
1126
- * to the initial state.
1127
- *
1128
- * If you want to set a custom initial state, you can use {@link setResetState}.
1129
- */
1130
- function withReset() {
1131
- return signalStoreFeature(withProps(() => ({ _resetState: { value: {} } })), withMethods((store) => {
1132
- // workaround to TS excessive property check
1133
- const methods = {
1134
- resetState() {
1135
- patchState$1(store, store._resetState.value);
1136
- },
1137
- __setResetState__(state) {
1138
- store._resetState.value = state;
1139
- },
1140
- };
1141
- return methods;
1142
- }), withHooks((store) => ({
1143
- onInit() {
1144
- store._resetState.value = getState(store);
1145
- },
1146
- })));
1147
- }
1148
- /**
1149
- * Sets the reset state of the store to the given state.
1150
- *
1151
- * Throws an error if the store is not configured with {@link withReset}.
1152
- * @param store the instance of a SignalStore
1153
- * @param state the state to set as the reset state
1154
- */
1155
- function setResetState(store, state) {
1156
- if (!('__setResetState__' in store)) {
1157
- throw new Error('Cannot set reset state, since store is not configured with withReset()');
1158
- }
1159
- store.__setResetState__(state);
1160
- }
1161
-
1162
- const defaultOptions = {
1163
- maxStackSize: 100,
1164
- keys: [],
1165
- skip: 0,
1166
- };
1167
- function getUndoRedoKeys(collections) {
1168
- if (collections) {
1169
- return collections.flatMap((c) => [
1170
- `${c}EntityMap`,
1171
- `${c}Ids`,
1172
- `selected${capitalize(c)}Ids`,
1173
- `${c}Filter`,
1174
- ]);
1175
- }
1176
- return ['entityMap', 'ids', 'selectedIds', 'filter'];
1177
- }
1178
- function withUndoRedo(options) {
1179
- let previous = null;
1180
- let skipOnce = false;
1181
- const normalized = {
1182
- ...defaultOptions,
1183
- ...options,
1184
- };
1185
- //
1186
- // Design Decision: This feature has its own
1187
- // internal state.
1188
- //
1189
- const undoStack = [];
1190
- const redoStack = [];
1191
- const canUndo = signal(false, ...(ngDevMode ? [{ debugName: "canUndo" }] : []));
1192
- const canRedo = signal(false, ...(ngDevMode ? [{ debugName: "canRedo" }] : []));
1193
- const updateInternal = () => {
1194
- canUndo.set(undoStack.length !== 0);
1195
- canRedo.set(redoStack.length !== 0);
1196
- };
1197
- const keys = [...getUndoRedoKeys(normalized.collections), ...normalized.keys];
1198
- return signalStoreFeature(withComputed(() => ({
1199
- canUndo: canUndo.asReadonly(),
1200
- canRedo: canRedo.asReadonly(),
1201
- })), withMethods((store) => ({
1202
- undo() {
1203
- const item = undoStack.pop();
1204
- if (item && previous) {
1205
- redoStack.push(previous);
1206
- }
1207
- if (item) {
1208
- skipOnce = true;
1209
- patchState$1(store, item);
1210
- previous = item;
1211
- }
1212
- updateInternal();
1213
- },
1214
- redo() {
1215
- const item = redoStack.pop();
1216
- if (item && previous) {
1217
- undoStack.push(previous);
1218
- }
1219
- if (item) {
1220
- skipOnce = true;
1221
- patchState$1(store, item);
1222
- previous = item;
1223
- }
1224
- updateInternal();
1225
- },
1226
- clearStack() {
1227
- undoStack.splice(0);
1228
- redoStack.splice(0);
1229
- previous = null;
1230
- updateInternal();
1231
- },
1232
- })), withHooks({
1233
- onInit(store) {
1234
- effect(() => {
1235
- const cand = keys.reduce((acc, key) => {
1236
- const s = store[key];
1237
- if (s && isSignal(s)) {
1238
- return {
1239
- ...acc,
1240
- [key]: s(),
1241
- };
1242
- }
1243
- return acc;
1244
- }, {});
1245
- if (normalized.skip > 0) {
1246
- normalized.skip--;
1247
- return;
1248
- }
1249
- if (skipOnce) {
1250
- skipOnce = false;
1251
- return;
1252
- }
1253
- //
1254
- // Deep Comparison to prevent duplicated entries
1255
- // on the stack. This can e.g. happen after an undo
1256
- // if the component sends back the undone filter
1257
- // to the store.
1258
- //
1259
- if (JSON.stringify(cand) === JSON.stringify(previous)) {
1260
- return;
1261
- }
1262
- // Clear redoStack after recorded action
1263
- redoStack.splice(0);
1264
- if (previous) {
1265
- undoStack.push(previous);
1266
- }
1267
- if (redoStack.length > normalized.maxStackSize) {
1268
- undoStack.unshift();
1269
- }
1270
- previous = cand;
1271
- // Don't propogate current reactive context
1272
- untracked(() => updateInternal());
1273
- });
1274
- },
1275
- }));
1276
- }
1277
-
1278
- /**
1279
- * Deep freezes a state object along its properties with primitive values
1280
- * on the first level.
1281
- *
1282
- * The reason for this is that the final state is a merge of all
1283
- * root properties of all states, i.e. `withState`,....
1284
- *
1285
- * Since the root object will not be part of the state (shadow clone),
1286
- * we are not freezing it.
1287
- */
1288
- function deepFreeze(target,
1289
- // if empty all properties will be frozen
1290
- propertyNamesToBeFrozen,
1291
- // also means that we are on the first level
1292
- isRoot = true) {
1293
- const runPropertyNameCheck = propertyNamesToBeFrozen.length > 0;
1294
- for (const key of Reflect.ownKeys(target)) {
1295
- if (runPropertyNameCheck && !propertyNamesToBeFrozen.includes(key)) {
1296
- continue;
1297
- }
1298
- const propValue = target[key];
1299
- if (isRecordLike(propValue) && !Object.isFrozen(propValue)) {
1300
- Object.freeze(propValue);
1301
- deepFreeze(propValue, [], false);
1302
- }
1303
- else if (isRoot) {
1304
- Object.defineProperty(target, key, {
1305
- value: propValue,
1306
- writable: false,
1307
- configurable: false,
1308
- });
1309
- }
1310
- }
1311
- }
1312
- function isRecordLike(target) {
1313
- return typeof target === 'object' && target !== null;
1314
- }
1315
-
1316
- // necessary wrapper function to test prod mode
1317
- function isDevMode() {
1318
- return isDevMode$1();
1319
- }
1320
-
1321
- function withImmutableState(stateOrFactory, options) {
1322
- const immutableState = typeof stateOrFactory === 'function' ? stateOrFactory() : stateOrFactory;
1323
- const stateKeys = Reflect.ownKeys(immutableState);
1324
- const applyFreezing = isDevMode() || options?.enableInProduction === true;
1325
- return signalStoreFeature(withState(immutableState), withHooks((store) => ({
1326
- onInit() {
1327
- if (!applyFreezing) {
1328
- return;
1329
- }
1330
- /**
1331
- * `immutableState` will be initially frozen. That is because
1332
- * of potential mutations outside the SignalStore
1333
- *
1334
- * ```ts
1335
- * const initialState = {user: {id: 1}};
1336
- * signalStore(withImmutableState(initialState));
1337
- *
1338
- * initialState.user.id = 2; // must throw immutability
1339
- * ```
1340
- */
1341
- deepFreeze(getState(store), stateKeys);
1342
- watchState(store, (state) => {
1343
- deepFreeze(state, stateKeys);
1344
- });
1345
- },
1346
- })));
1347
- }
1348
-
1349
- const keyPath = 'ngrxToolkitKeyPath';
1350
- const dbName = 'ngrxToolkitDb';
1351
- const storeName = 'ngrxToolkitStore';
1352
- const VERSION = 1;
1353
- class IndexedDBService {
1354
- /**
1355
- * write to indexedDB
1356
- * @param key
1357
- * @param data
1358
- */
1359
- async setItem(key, data) {
1360
- const db = await this.openDB();
1361
- const tx = db.transaction(storeName, 'readwrite');
1362
- const store = tx.objectStore(storeName);
1363
- store.put({
1364
- [keyPath]: key,
1365
- value: data,
1366
- });
1367
- return new Promise((resolve, reject) => {
1368
- tx.oncomplete = () => {
1369
- db.close();
1370
- resolve();
1371
- };
1372
- tx.onerror = () => {
1373
- db.close();
1374
- reject();
1375
- };
1376
- });
1377
- }
1378
- /**
1379
- * read from indexedDB
1380
- * @param key
1381
- */
1382
- async getItem(key) {
1383
- const db = await this.openDB();
1384
- const tx = db.transaction(storeName, 'readonly');
1385
- const store = tx.objectStore(storeName);
1386
- const request = store.get(key);
1387
- return new Promise((resolve, reject) => {
1388
- request.onsuccess = () => {
1389
- db.close();
1390
- // localStorage(sessionStorage) returns null if the key does not exist
1391
- // Similarly, indexedDB should return null
1392
- if (request.result === undefined) {
1393
- resolve(null);
1394
- }
1395
- resolve(request.result?.['value']);
1396
- };
1397
- request.onerror = () => {
1398
- db.close();
1399
- reject();
1400
- };
1401
- });
1402
- }
1403
- /**
1404
- * delete indexedDB
1405
- * @param key
1406
- */
1407
- async clear(key) {
1408
- const db = await this.openDB();
1409
- const tx = db.transaction(storeName, 'readwrite');
1410
- const store = tx.objectStore(storeName);
1411
- const request = store.delete(key);
1412
- return new Promise((resolve, reject) => {
1413
- request.onsuccess = () => {
1414
- db.close();
1415
- resolve();
1416
- };
1417
- request.onerror = () => {
1418
- db.close();
1419
- reject();
1420
- };
1421
- });
1422
- }
1423
- /**
1424
- * open indexedDB
1425
- */
1426
- async openDB() {
1427
- return new Promise((resolve, reject) => {
1428
- const request = indexedDB.open(dbName, VERSION);
1429
- request.onupgradeneeded = () => {
1430
- const db = request.result;
1431
- if (!db.objectStoreNames.contains(storeName)) {
1432
- db.createObjectStore(storeName, { keyPath });
1433
- }
1434
- };
1435
- request.onsuccess = () => {
1436
- resolve(request.result);
1437
- };
1438
- request.onerror = () => {
1439
- reject(request.error);
1440
- };
1441
- });
1442
- }
1443
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: IndexedDBService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1444
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: IndexedDBService, providedIn: 'root' }); }
1445
- }
1446
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: IndexedDBService, decorators: [{
1447
- type: Injectable,
1448
- args: [{ providedIn: 'root' }]
1449
- }] });
1450
-
1451
- const SYNC_STATUS = Symbol('SYNC_STATUS');
1452
-
1453
- function withIndexedDB() {
1454
- function factory({ key, parse, select, stringify }, store, useStubs) {
1455
- if (useStubs) {
1456
- return {
1457
- clearStorage: () => Promise.resolve(),
1458
- readFromStorage: () => Promise.resolve(),
1459
- writeToStorage: () => Promise.resolve(),
1460
- };
1461
- }
1462
- const indexeddbService = inject(IndexedDBService);
1463
- function warnOnSyncing(mode) {
1464
- if (store[SYNC_STATUS]() === 'syncing') {
1465
- const prettyMode = mode === 'read' ? 'Reading' : 'Writing';
1466
- console.warn(`${prettyMode} to Store (${key}) happened during an ongoing synchronization process.`, 'Please ensure that the store is not in syncing state via `store.whenSynced()`.', 'Alternatively, you can disable the autoSync by passing `autoSync: false` in the config.');
1467
- }
1468
- }
1469
- return {
1470
- /**
1471
- * Removes the item stored in storage.
1472
- */
1473
- async clearStorage() {
1474
- warnOnSyncing('write');
1475
- store[SYNC_STATUS].set('syncing');
1476
- patchState$1(store, {});
1477
- await indexeddbService.clear(key);
1478
- store[SYNC_STATUS].set('synced');
1479
- },
1480
- /**
1481
- * Reads item from storage and patches the state.
1482
- */
1483
- async readFromStorage() {
1484
- warnOnSyncing('read');
1485
- store[SYNC_STATUS].set('syncing');
1486
- const stateString = await indexeddbService.getItem(key);
1487
- if (stateString) {
1488
- patchState$1(store, parse(stateString));
1489
- }
1490
- store[SYNC_STATUS].set('synced');
1491
- },
1492
- /**
1493
- * Writes selected portion to storage.
1494
- */
1495
- async writeToStorage() {
1496
- warnOnSyncing('write');
1497
- store[SYNC_STATUS].set('syncing');
1498
- const slicedState = select(getState(store));
1499
- await indexeddbService.setItem(key, stringify(slicedState));
1500
- store[SYNC_STATUS].set('synced');
1501
- },
1502
- };
1503
- }
1504
- factory.type = 'async';
1505
- return factory;
1506
- }
1507
-
1508
- class LocalStorageService {
1509
- getItem(key) {
1510
- return localStorage.getItem(key);
1511
- }
1512
- setItem(key, data) {
1513
- return localStorage.setItem(key, data);
1514
- }
1515
- clear(key) {
1516
- return localStorage.removeItem(key);
1517
- }
1518
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: LocalStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1519
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: LocalStorageService, providedIn: 'root' }); }
1520
- }
1521
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: LocalStorageService, decorators: [{
1522
- type: Injectable,
1523
- args: [{
1524
- providedIn: 'root',
1525
- }]
1526
- }] });
1527
-
1528
- class SessionStorageService {
1529
- getItem(key) {
1530
- return sessionStorage.getItem(key);
1531
- }
1532
- setItem(key, data) {
1533
- return sessionStorage.setItem(key, data);
1534
- }
1535
- clear(key) {
1536
- return sessionStorage.removeItem(key);
1537
- }
1538
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: SessionStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1539
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: SessionStorageService, providedIn: 'root' }); }
1540
- }
1541
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: SessionStorageService, decorators: [{
1542
- type: Injectable,
1543
- args: [{
1544
- providedIn: 'root',
1545
- }]
1546
- }] });
1547
-
1548
- function withLocalStorage() {
1549
- return createSyncMethods(LocalStorageService);
1550
- }
1551
- function withSessionStorage() {
1552
- return createSyncMethods(SessionStorageService);
1553
- }
1554
- function createSyncMethods(Storage) {
1555
- function factory({ key, parse, select, stringify }, store, useStubs) {
1556
- if (useStubs) {
1557
- return {
1558
- clearStorage: () => undefined,
1559
- readFromStorage: () => undefined,
1560
- writeToStorage: () => undefined,
1561
- };
1562
- }
1563
- const storage = inject(Storage);
1564
- return {
1565
- clearStorage() {
1566
- storage.clear(key);
1567
- },
1568
- readFromStorage() {
1569
- const stateString = storage.getItem(key);
1570
- if (stateString) {
1571
- patchState$1(store, parse(stateString));
1572
- }
1573
- },
1574
- writeToStorage() {
1575
- const slicedState = select(getState(store));
1576
- storage.setItem(key, stringify(slicedState));
1577
- },
1578
- };
1579
- }
1580
- factory.type = 'sync';
1581
- return factory;
1582
- }
1583
-
1584
- function withStorageSync(configOrKey, storageStrategy) {
1585
- if (typeof configOrKey !== 'string' &&
1586
- configOrKey.storage &&
1587
- storageStrategy) {
1588
- throw new Error('You can either pass a storage strategy or a config with storage, but not both.');
1589
- }
1590
- const config = {
1591
- autoSync: true,
1592
- select: (state) => state,
1593
- parse: JSON.parse,
1594
- stringify: JSON.stringify,
1595
- storage: () => localStorage,
1596
- ...(typeof configOrKey === 'string' ? { key: configOrKey } : configOrKey),
1597
- };
1598
- const factory = storageStrategy ??
1599
- (config.storage() === localStorage
1600
- ? withLocalStorage()
1601
- : withSessionStorage());
1602
- if (factory.type === 'sync') {
1603
- return createSyncStorageSync(factory, config);
1604
- }
1605
- else {
1606
- return createAsyncStorageSync(factory, config);
1607
- }
1608
- }
1609
- function createSyncStorageSync(factory, config) {
1610
- return signalStoreFeature(withMethods((store, platformId = inject(PLATFORM_ID)) => {
1611
- return factory(config, store, isPlatformServer(platformId));
1612
- }), withHooks({
1613
- onInit(store, platformId = inject(PLATFORM_ID)) {
1614
- if (isPlatformServer(platformId)) {
1615
- return;
1616
- }
1617
- if (config.autoSync) {
1618
- store.readFromStorage();
1619
- watchState(store, () => store.writeToStorage());
1620
- }
1621
- },
1622
- }));
1623
- }
1624
- function createAsyncStorageSync(factory, config) {
1625
- return signalStoreFeature(withProps(() => {
1626
- const props = {
1627
- /*
1628
- // we need to have that as property (and not state)
1629
- // Otherwise the state watcher fires when updating the sync status
1630
- */
1631
- [SYNC_STATUS]: signal('idle'),
1632
- };
1633
- const resolves = [];
1634
- effect(() => {
1635
- const syncStatus = props[SYNC_STATUS]();
1636
- if (syncStatus === 'synced') {
1637
- resolves.forEach((resolve) => resolve());
1638
- resolves.splice(0, resolves.length);
1639
- }
1640
- });
1641
- return {
1642
- ...props,
1643
- isSynced: computed(() => props[SYNC_STATUS]() === 'synced'),
1644
- whenSynced: () => new Promise((resolve) => {
1645
- if (props[SYNC_STATUS]() === 'synced') {
1646
- resolve();
1647
- }
1648
- else {
1649
- resolves.push(resolve);
1650
- }
1651
- }),
1652
- };
1653
- }), withMethods((store, platformId = inject(PLATFORM_ID)) => {
1654
- return factory(config, store, isPlatformServer(platformId));
1655
- }), withHooks({
1656
- async onInit(store, platformId = inject(PLATFORM_ID)) {
1657
- if (isPlatformServer(platformId)) {
1658
- return;
1659
- }
1660
- const initialState = JSON.stringify(getState(store));
1661
- if (config.autoSync) {
1662
- let startWatching = false;
1663
- watchState(store, () => {
1664
- if (!startWatching) {
1665
- const currentState = JSON.stringify(getState(store));
1666
- // Necessary because getState returns always a new object
1667
- if (currentState === initialState) {
1668
- return;
1669
- }
1670
- console.warn(`Writing to Store (${config.key}) happened before the state was initially read from storage.`, 'Please ensure that the store is not in syncing state via `store.whenSynced()` before writing to the state.', 'Alternatively, you can disable autoSync by passing `autoSync: false` in the config.');
1671
- return;
1672
- }
1673
- return store.writeToStorage();
1674
- });
1675
- await store.readFromStorage();
1676
- startWatching = true;
1677
- }
1678
- },
1679
- }));
1680
- }
1681
-
1682
- /**
1683
- * `withConditional` activates a feature based on a given condition.
1684
- *
1685
- * **Use Cases**
1686
- * - Conditionally activate features based on the **store state** or other criteria.
1687
- * - Choose between **two different implementations** of a feature.
1688
- *
1689
- * **Type Constraints**
1690
- * Both features must have **exactly the same state, props, and methods**.
1691
- * Otherwise, a type error will occur.
1692
- *
1693
- *
1694
- * **Usage**
1695
- *
1696
- * ```typescript
1697
- * const withUser = signalStoreFeature(
1698
- * withState({ id: 1, name: 'Konrad' }),
1699
- * withHooks(store => ({
1700
- * onInit() {
1701
- * // user loading logic
1702
- * }
1703
- * }))
1704
- * );
1705
- *
1706
- * function withFakeUser() {
1707
- * return signalStoreFeature(
1708
- * withState({ id: 0, name: 'anonymous' })
1709
- * );
1710
- * }
1711
- *
1712
- * signalStore(
1713
- * withMethods(() => ({
1714
- * useRealUser: () => true
1715
- * })),
1716
- * withConditional((store) => store.useRealUser(), withUser, withFakeUser)
1717
- * )
1718
- * ```
1719
- *
1720
- * @param condition - A function that determines which feature to activate based on the store state.
1721
- * @param featureIfTrue - The feature to activate if the condition evaluates to `true`.
1722
- * @param featureIfFalse - The feature to activate if the condition evaluates to `false`.
1723
- * @returns A `SignalStoreFeature` that applies the selected feature based on the condition.
1724
- */
1725
- function withConditional(condition, featureIfTrue, featureIfFalse) {
1726
- return (store) => {
1727
- const conditionStore = {
1728
- ...store['stateSignals'],
1729
- ...store['props'],
1730
- ...store['methods'],
1731
- };
1732
- return condition(conditionStore)
1733
- ? featureIfTrue(store)
1734
- : featureIfFalse(store);
1735
- };
1736
- }
1737
- const emptyFeature = signalStoreFeature(withState({}));
1738
-
1739
- /**
1740
- * @deprecated Use `import { withFeature } from '@ngrx/signals'` instead, starting with `ngrx/signals` 19.1: https://ngrx.io/guide/signals/signal-store/custom-store-features#connecting-a-custom-feature-with-the-store
1741
- *
1742
- * Allows to pass properties, methods, or signals from a SignalStore
1743
- * to a feature.
1744
- *
1745
- * Typically, a `signalStoreFeature` can have input constraints on
1746
- *
1747
- * ```typescript
1748
- * function withSum(a: Signal<number>, b: Signal<number>) {
1749
- * return signalStoreFeature(
1750
- * withComputed(() => ({
1751
- * sum: computed(() => a() + b())
1752
- * }))
1753
- * );
1754
- * }
1755
- *
1756
- * signalStore(
1757
- * withState({ a: 1, b: 2 }),
1758
- * withFeatureFactory((store) => withSum(store.a, store.b))
1759
- * );
1760
- * ```
1761
- * @param factoryFn
1762
- */
1763
- function withFeatureFactory(factoryFn) {
1764
- return (store) => {
1765
- const storeForFactory = {
1766
- ...store['stateSignals'],
1767
- ...store['props'],
1768
- ...store['methods'],
1769
- };
1770
- const feature = factoryFn(storeForFactory);
1771
- return feature(store);
1772
- };
1773
- }
1774
-
1775
- /**
1776
- * Generated bundle index. Do not edit.
1777
- */
1778
-
1779
- export { capitalize, createEffects, createPageArray, createReducer, deriveCallStateKeys, emptyFeature, firstPage, getCallStateKeys, getCollectionArray, getDataServiceKeys, getUndoRedoKeys, gotoPage, nextPage, noPayload, patchState, payload, previousPage, provideDevtoolsConfig, renameDevtoolsName, setError, setLoaded, setLoading, setMaxPageNavigationArrayItems, setPageSize, setResetState, updateState, withCallState, withConditional, withDataService, withDevToolsStub, withDevtools, withDisabledNameIndices, withFeatureFactory, withGlitchTracking, withImmutableState, withIndexedDB, withIndexedDB as withIndexeddb, withLocalStorage, withMapper, withPagination, withRedux, withReset, withSessionStorage, withStorageSync, withUndoRedo };
1780
- //# sourceMappingURL=angular-architects-ngrx-toolkit.mjs.map