@signaldb/svelte 2.0.0-beta.6 → 2.0.0-beta.7

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 (89) hide show
  1. package/dist/base/core/src/AsyncDataAdapter.d.ts +64 -0
  2. package/dist/base/core/src/AsyncDataAdapter.js +450 -0
  3. package/dist/base/core/src/AutoFetchDataAdapter.d.ts +112 -0
  4. package/dist/base/core/src/AutoFetchDataAdapter.js +652 -0
  5. package/dist/base/core/src/Collection/Cursor.d.ts +113 -0
  6. package/dist/base/core/src/Collection/Cursor.js +293 -0
  7. package/dist/base/core/src/Collection/Observer.d.ts +64 -0
  8. package/dist/base/core/src/Collection/Observer.js +181 -0
  9. package/dist/base/core/src/Collection/index.d.ts +294 -0
  10. package/dist/base/core/src/Collection/index.js +580 -0
  11. package/dist/base/core/src/Collection/types.d.ts +28 -0
  12. package/dist/base/core/src/Collection/types.js +2 -0
  13. package/dist/base/core/src/DataAdapter.d.ts +35 -0
  14. package/dist/base/core/src/DataAdapter.js +2 -0
  15. package/dist/base/core/src/DefaultDataAdapter.d.ts +35 -0
  16. package/dist/base/core/src/DefaultDataAdapter.js +398 -0
  17. package/dist/base/core/src/WorkerDataAdapter.d.ts +25 -0
  18. package/dist/base/core/src/WorkerDataAdapter.js +211 -0
  19. package/dist/base/core/src/WorkerDataAdapterHost.d.ts +62 -0
  20. package/dist/base/core/src/WorkerDataAdapterHost.js +409 -0
  21. package/dist/base/core/src/createIndex.d.ts +7 -0
  22. package/dist/base/core/src/createIndex.js +120 -0
  23. package/dist/base/core/src/createIndexProvider.d.ts +8 -0
  24. package/dist/base/core/src/createIndexProvider.js +11 -0
  25. package/dist/base/core/src/createReactivityAdapter.d.ts +8 -0
  26. package/dist/base/core/src/createReactivityAdapter.js +11 -0
  27. package/dist/base/core/src/createStorageAdapter.d.ts +9 -0
  28. package/dist/base/core/src/createStorageAdapter.js +11 -0
  29. package/dist/base/core/src/getIndexInfo.d.ts +39 -0
  30. package/dist/base/core/src/getIndexInfo.js +176 -0
  31. package/dist/base/core/src/index.d.ts +22 -0
  32. package/dist/base/core/src/index.js +39 -0
  33. package/dist/base/core/src/types/Dependency.d.ts +4 -0
  34. package/dist/base/core/src/types/Dependency.js +2 -0
  35. package/dist/base/core/src/types/IndexProvider.d.ts +26 -0
  36. package/dist/base/core/src/types/IndexProvider.js +2 -0
  37. package/dist/base/core/src/types/Modifier.d.ts +46 -0
  38. package/dist/base/core/src/types/Modifier.js +3 -0
  39. package/dist/base/core/src/types/ReactivityAdapter.d.ts +6 -0
  40. package/dist/base/core/src/types/ReactivityAdapter.js +2 -0
  41. package/dist/base/core/src/types/Selector.d.ts +46 -0
  42. package/dist/base/core/src/types/Selector.js +3 -0
  43. package/dist/base/core/src/types/Signal.d.ts +4 -0
  44. package/dist/base/core/src/types/Signal.js +2 -0
  45. package/dist/base/core/src/types/StorageAdapter.d.ts +20 -0
  46. package/dist/base/core/src/types/StorageAdapter.js +2 -0
  47. package/dist/base/core/src/utils/EventEmitter.d.ts +71 -0
  48. package/dist/base/core/src/utils/EventEmitter.js +144 -0
  49. package/dist/base/core/src/utils/batchOnNextTick.d.ts +16 -0
  50. package/dist/base/core/src/utils/batchOnNextTick.js +72 -0
  51. package/dist/base/core/src/utils/compact.d.ts +9 -0
  52. package/dist/base/core/src/utils/compact.js +21 -0
  53. package/dist/base/core/src/utils/createSignal.d.ts +14 -0
  54. package/dist/base/core/src/utils/createSignal.js +38 -0
  55. package/dist/base/core/src/utils/deepClone.d.ts +17 -0
  56. package/dist/base/core/src/utils/deepClone.js +68 -0
  57. package/dist/base/core/src/utils/get.d.ts +9 -0
  58. package/dist/base/core/src/utils/get.js +27 -0
  59. package/dist/base/core/src/utils/getMatchingKeys.d.ts +19 -0
  60. package/dist/base/core/src/utils/getMatchingKeys.js +49 -0
  61. package/dist/base/core/src/utils/intersection.d.ts +9 -0
  62. package/dist/base/core/src/utils/intersection.js +16 -0
  63. package/dist/base/core/src/utils/isEqual.d.ts +14 -0
  64. package/dist/base/core/src/utils/isEqual.js +43 -0
  65. package/dist/base/core/src/utils/isFieldExpression.d.ts +11 -0
  66. package/dist/base/core/src/utils/isFieldExpression.js +52 -0
  67. package/dist/base/core/src/utils/match.d.ts +12 -0
  68. package/dist/base/core/src/utils/match.js +16 -0
  69. package/dist/base/core/src/utils/modify.d.ts +14 -0
  70. package/dist/base/core/src/utils/modify.js +29 -0
  71. package/dist/base/core/src/utils/project.d.ts +15 -0
  72. package/dist/base/core/src/utils/project.js +43 -0
  73. package/dist/base/core/src/utils/queryId.d.ts +9 -0
  74. package/dist/base/core/src/utils/queryId.js +30 -0
  75. package/dist/base/core/src/utils/randomId.d.ts +7 -0
  76. package/dist/base/core/src/utils/randomId.js +12 -0
  77. package/dist/base/core/src/utils/reactiveOrAsync.d.ts +59 -0
  78. package/dist/base/core/src/utils/reactiveOrAsync.js +93 -0
  79. package/dist/base/core/src/utils/serializeValue.d.ts +12 -0
  80. package/dist/base/core/src/utils/serializeValue.js +27 -0
  81. package/dist/base/core/src/utils/set.d.ts +13 -0
  82. package/dist/base/core/src/utils/set.js +43 -0
  83. package/dist/base/core/src/utils/sortItems.d.ts +12 -0
  84. package/dist/base/core/src/utils/sortItems.js +23 -0
  85. package/dist/base/core/src/utils/uniqueBy.d.ts +10 -0
  86. package/dist/base/core/src/utils/uniqueBy.js +19 -0
  87. package/dist/reactivity-adapters/svelte/index.svelte.d.ts +10 -0
  88. package/dist/reactivity-adapters/svelte/index.svelte.js +36 -0
  89. package/package.json +3 -3
@@ -0,0 +1,113 @@
1
+ import type ReactivityAdapter from '../types/ReactivityAdapter';
2
+ import type { BaseItem, FindOptions, Transform } from './types';
3
+ import type { ObserveCallbacks } from './Observer';
4
+ /**
5
+ * Checks if the current scope is reactive, considering the provided reactivity adapter.
6
+ * @param reactivity - The reactivity adapter or a boolean indicating whether reactivity is enabled.
7
+ * @returns A boolean indicating if the current scope is reactive.
8
+ */
9
+ export declare function isInReactiveScope(reactivity: ReactivityAdapter | undefined | false): boolean;
10
+ export interface CursorOptions<T extends BaseItem, U = T, Async extends boolean = false> extends FindOptions<T, Async> {
11
+ transform?: Transform<T, U>;
12
+ bindEvents?: (requery: () => void) => () => void;
13
+ }
14
+ /**
15
+ * Represents a cursor for querying and observing a filtered, sorted, and transformed
16
+ * subset of items from a collection. Supports reactivity and field tracking.
17
+ * @template T - The type of the items in the collection.
18
+ * @template U - The transformed item type after applying transform (default is T).
19
+ */
20
+ export default class Cursor<T extends BaseItem, U = T, Async extends boolean = false> {
21
+ private observer;
22
+ private getItems;
23
+ private options;
24
+ private onCleanupCallbacks;
25
+ /**
26
+ * Creates a new instance of the `Cursor` class.
27
+ * Provides utilities for querying, observing, and transforming items from a collection.
28
+ * @template T - The type of the items in the collection.
29
+ * @template U - The transformed item type after applying transformations (default is T).
30
+ * @param getItems - A function that retrieves the filtered list of items.
31
+ * @param options - Optional configuration for the cursor.
32
+ * @param options.transform - A transformation function to apply to each item when retrieving them.
33
+ * @param options.bindEvents - A function to bind reactivity events for the cursor, which should return a cleanup function.
34
+ * @param options.fields - A projection object defining which fields of the item should be included or excluded.
35
+ * @param options.sort - A sort specifier to determine the order of the items.
36
+ * @param options.skip - The number of items to skip from the beginning of the result set.
37
+ * @param options.limit - The maximum number of items to return in the result set.
38
+ * @param options.reactive - A reactivity adapter to enable observing changes in the cursor's result set.
39
+ * @param options.fieldTracking - A boolean to enable fine-grained field tracking for reactivity.
40
+ * @param options.transformAll - A function that will be able to solve the n+1 problem
41
+ */
42
+ constructor(getItems: Async extends true ? () => Promise<T[]> : () => T[], options?: CursorOptions<T, U, Async>);
43
+ private addGetters;
44
+ private transform;
45
+ private depend;
46
+ private ensureObserver;
47
+ private observeRawChanges;
48
+ /**
49
+ * Cleans up all resources associated with the cursor, such as reactive bindings
50
+ * and event listeners. This method should be called when the cursor is no longer needed
51
+ * to prevent memory leaks.
52
+ */
53
+ cleanup(): void;
54
+ /**
55
+ * Registers a cleanup callback to be executed when the `cleanup` method is called.
56
+ * Useful for managing resources and ensuring proper cleanup of bindings or listeners.
57
+ * @param callback - A function to be executed during cleanup.
58
+ */
59
+ onCleanup(callback: () => void): void;
60
+ /**
61
+ * Iterates over each item in the cursor's result set, applying the provided callback
62
+ * function to each transformed item.
63
+ * ⚡️ this function is reactive!
64
+ * @param callback - A function to execute for each item in the result set.
65
+ * @param callback.item - The transformed item.
66
+ * @returns A promise that resolves when all items have been processed, or void if not in async mode.
67
+ */
68
+ forEach(callback: (item: U) => void): Async extends true ? Promise<void> : void;
69
+ /**
70
+ * Creates a new array populated with the results of applying the provided callback
71
+ * function to each transformed item in the cursor's result set.
72
+ * ⚡️ this function is reactive!
73
+ * @template V - The type of the items in the resulting array.
74
+ * @param callback - A function to execute for each item in the result set.
75
+ * @param callback.item - The transformed item.
76
+ * @returns An array of results after applying the callback to each item.
77
+ */
78
+ map<V>(callback: (item: U) => V): Async extends true ? Promise<V[]> : V[];
79
+ /**
80
+ * Fetches all transformed items from the cursor's result set as an array.
81
+ * Automatically applies filtering, sorting, and limiting as per the cursor's options.
82
+ * ⚡️ this function is reactive!
83
+ * @returns An array of transformed items in the result set.
84
+ */
85
+ fetch(): Async extends true ? Promise<U[]> : U[];
86
+ /**
87
+ * Counts the total number of items in the cursor's result set after applying
88
+ * filtering and other criteria.
89
+ * ⚡️ this function is reactive!
90
+ * @returns The total number of items in the result set.
91
+ */
92
+ count(): Async extends true ? Promise<number> : number;
93
+ /**
94
+ * Observes changes to the cursor's result set and triggers the specified callbacks
95
+ * when items are added, removed, or updated. Supports reactivity and transformation.
96
+ * @param callbacks - An object containing the callback functions to handle different change events.
97
+ * @param callbacks.added - Triggered when an item is added to the result set.
98
+ * @param callbacks.removed - Triggered when an item is removed from the result set.
99
+ * @param callbacks.changed - Triggered when an item in the result set is modified.
100
+ * @param callbacks.addedBefore - Triggered when an item is added before another item in the result set.
101
+ * @param callbacks.movedBefore - Triggered when an item is moved before another item in the result set.
102
+ * @param callbacks.changedField - Triggered when a specific field of an item changes.
103
+ * @param skipInitial - A boolean indicating whether to skip the initial notification of the current result set.
104
+ * @returns A function to stop observing changes.
105
+ */
106
+ observeChanges(callbacks: ObserveCallbacks<T>, skipInitial?: boolean): () => void;
107
+ /**
108
+ * Forces the cursor to re-evaluate its result set by re-fetching items
109
+ * from the collection. This is useful when the underlying data or query
110
+ * criteria have changed, and you want to ensure the cursor reflects the latest state.
111
+ */
112
+ requery(): void;
113
+ }
@@ -0,0 +1,293 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.isInReactiveScope = isInReactiveScope;
7
+ const Observer_1 = __importDefault(require("./Observer"));
8
+ /**
9
+ * Checks if the current scope is reactive, considering the provided reactivity adapter.
10
+ * @param reactivity - The reactivity adapter or a boolean indicating whether reactivity is enabled.
11
+ * @returns A boolean indicating if the current scope is reactive.
12
+ */
13
+ function isInReactiveScope(reactivity) {
14
+ if (!reactivity)
15
+ return false; // if reactivity is disabled we don't need to check
16
+ if (!reactivity.isInScope)
17
+ return true; // if reactivity is enabled and no isInScope method is provided we assume it is in scope
18
+ return reactivity.isInScope(); // if reactivity is enabled and isInScope method is provided we check if it is in scope
19
+ }
20
+ /**
21
+ * Represents a cursor for querying and observing a filtered, sorted, and transformed
22
+ * subset of items from a collection. Supports reactivity and field tracking.
23
+ * @template T - The type of the items in the collection.
24
+ * @template U - The transformed item type after applying transform (default is T).
25
+ */
26
+ class Cursor {
27
+ observer;
28
+ getItems;
29
+ options;
30
+ onCleanupCallbacks = [];
31
+ /**
32
+ * Creates a new instance of the `Cursor` class.
33
+ * Provides utilities for querying, observing, and transforming items from a collection.
34
+ * @template T - The type of the items in the collection.
35
+ * @template U - The transformed item type after applying transformations (default is T).
36
+ * @param getItems - A function that retrieves the filtered list of items.
37
+ * @param options - Optional configuration for the cursor.
38
+ * @param options.transform - A transformation function to apply to each item when retrieving them.
39
+ * @param options.bindEvents - A function to bind reactivity events for the cursor, which should return a cleanup function.
40
+ * @param options.fields - A projection object defining which fields of the item should be included or excluded.
41
+ * @param options.sort - A sort specifier to determine the order of the items.
42
+ * @param options.skip - The number of items to skip from the beginning of the result set.
43
+ * @param options.limit - The maximum number of items to return in the result set.
44
+ * @param options.reactive - A reactivity adapter to enable observing changes in the cursor's result set.
45
+ * @param options.fieldTracking - A boolean to enable fine-grained field tracking for reactivity.
46
+ * @param options.transformAll - A function that will be able to solve the n+1 problem
47
+ */
48
+ constructor(getItems, options) {
49
+ this.getItems = getItems;
50
+ this.options = options || {};
51
+ }
52
+ addGetters(item) {
53
+ if (!isInReactiveScope(this.options.reactive))
54
+ return item;
55
+ const depend = this.depend.bind(this);
56
+ return Object.entries(item).reduce((memo, [key, value]) => {
57
+ Object.defineProperty(memo, key, {
58
+ get() {
59
+ depend({
60
+ changedField: notify => (changedItem, changedFieldName) => {
61
+ if (changedFieldName !== key || changedItem.id !== item.id)
62
+ return;
63
+ notify();
64
+ },
65
+ });
66
+ return value;
67
+ },
68
+ enumerable: true,
69
+ configurable: true,
70
+ });
71
+ return memo;
72
+ }, {});
73
+ }
74
+ transform(rawItem) {
75
+ const item = this.options.fieldTracking
76
+ ? this.addGetters(rawItem)
77
+ : rawItem;
78
+ if (!this.options.transform)
79
+ return item;
80
+ return this.options.transform(item);
81
+ }
82
+ depend(changeEvents) {
83
+ if (this.options?.async)
84
+ return;
85
+ if (!isInReactiveScope(this.options.reactive)) {
86
+ // eslint-disable-next-line no-console
87
+ console.warn('Cursor.depend() called outside of a reactive scope without async option; consider using { async: true } or wrapping in a reactive scope');
88
+ }
89
+ if (!this.options.reactive)
90
+ return;
91
+ const signal = this.options.reactive.create();
92
+ signal.depend();
93
+ const notify = () => signal.notify();
94
+ /**
95
+ * Builds a notifier function for the specified event.
96
+ * @template Event - The type of the event.
97
+ * @param event - The event for which to build the notifier.
98
+ * @returns A function that handles the event and triggers the appropriate notifications.
99
+ */
100
+ function buildNotifier(event) {
101
+ const eventHandler = changeEvents[event];
102
+ return (...args) => {
103
+ // if the event is just turned on with true, we can notify directly
104
+ if (eventHandler === true) {
105
+ notify();
106
+ return;
107
+ }
108
+ // if the event is something else than true or a function, we don't care about it
109
+ if (typeof eventHandler !== 'function')
110
+ return;
111
+ // if the event is a function, we call it with the notify function
112
+ eventHandler(notify)(...args);
113
+ };
114
+ }
115
+ const stop = this.observeRawChanges({
116
+ added: buildNotifier('added'),
117
+ addedBefore: buildNotifier('addedBefore'),
118
+ changed: buildNotifier('changed'),
119
+ changedField: buildNotifier('changedField'),
120
+ movedBefore: buildNotifier('movedBefore'),
121
+ removed: buildNotifier('removed'),
122
+ }, true);
123
+ if (this.options.reactive.onDispose) {
124
+ this.options.reactive.onDispose(() => stop(), signal);
125
+ }
126
+ this.onCleanup(stop);
127
+ }
128
+ ensureObserver() {
129
+ if (!this.observer) {
130
+ const observer = new Observer_1.default(() => {
131
+ const requery = () => {
132
+ observer.runChecks(this.getItems);
133
+ };
134
+ const cleanup = this.options.bindEvents && this.options.bindEvents(requery);
135
+ return () => {
136
+ if (cleanup)
137
+ cleanup();
138
+ };
139
+ });
140
+ this.onCleanup(() => observer.stop());
141
+ this.observer = observer;
142
+ }
143
+ return this.observer;
144
+ }
145
+ observeRawChanges(callbacks, skipInitial = false) {
146
+ const observer = this.ensureObserver();
147
+ observer.addCallbacks(callbacks, skipInitial);
148
+ observer.runChecks(this.getItems);
149
+ return () => {
150
+ observer.removeCallbacks(callbacks);
151
+ if (!observer.isEmpty())
152
+ return;
153
+ // remove observer if it's empty
154
+ observer.stop();
155
+ this.observer = undefined;
156
+ };
157
+ }
158
+ /**
159
+ * Cleans up all resources associated with the cursor, such as reactive bindings
160
+ * and event listeners. This method should be called when the cursor is no longer needed
161
+ * to prevent memory leaks.
162
+ */
163
+ cleanup() {
164
+ this.onCleanupCallbacks.forEach((callback) => {
165
+ callback();
166
+ });
167
+ this.onCleanupCallbacks = [];
168
+ }
169
+ /**
170
+ * Registers a cleanup callback to be executed when the `cleanup` method is called.
171
+ * Useful for managing resources and ensuring proper cleanup of bindings or listeners.
172
+ * @param callback - A function to be executed during cleanup.
173
+ */
174
+ onCleanup(callback) {
175
+ this.onCleanupCallbacks.push(callback);
176
+ }
177
+ /**
178
+ * Iterates over each item in the cursor's result set, applying the provided callback
179
+ * function to each transformed item.
180
+ * ⚡️ this function is reactive!
181
+ * @param callback - A function to execute for each item in the result set.
182
+ * @param callback.item - The transformed item.
183
+ * @returns A promise that resolves when all items have been processed, or void if not in async mode.
184
+ */
185
+ forEach(callback) {
186
+ this.depend({
187
+ addedBefore: true,
188
+ removed: true,
189
+ movedBefore: true,
190
+ ...this.options.fieldTracking ? {} : { changed: true },
191
+ });
192
+ const executeForEach = (items) => {
193
+ items.forEach((item) => {
194
+ callback(this.transform(item));
195
+ });
196
+ };
197
+ const result = this.getItems();
198
+ if (result instanceof Promise) {
199
+ return result.then(executeForEach);
200
+ }
201
+ else {
202
+ executeForEach(result);
203
+ return undefined;
204
+ }
205
+ }
206
+ /**
207
+ * Creates a new array populated with the results of applying the provided callback
208
+ * function to each transformed item in the cursor's result set.
209
+ * ⚡️ this function is reactive!
210
+ * @template V - The type of the items in the resulting array.
211
+ * @param callback - A function to execute for each item in the result set.
212
+ * @param callback.item - The transformed item.
213
+ * @returns An array of results after applying the callback to each item.
214
+ */
215
+ map(callback) {
216
+ const results = [];
217
+ const maybePromise = this.forEach((item) => {
218
+ results.push(callback(item));
219
+ });
220
+ if (maybePromise instanceof Promise) {
221
+ return maybePromise.then(() => results);
222
+ }
223
+ return results;
224
+ }
225
+ /**
226
+ * Fetches all transformed items from the cursor's result set as an array.
227
+ * Automatically applies filtering, sorting, and limiting as per the cursor's options.
228
+ * ⚡️ this function is reactive!
229
+ * @returns An array of transformed items in the result set.
230
+ */
231
+ fetch() {
232
+ return this.map(item => item);
233
+ }
234
+ /**
235
+ * Counts the total number of items in the cursor's result set after applying
236
+ * filtering and other criteria.
237
+ * ⚡️ this function is reactive!
238
+ * @returns The total number of items in the result set.
239
+ */
240
+ count() {
241
+ this.depend({
242
+ added: true,
243
+ removed: true,
244
+ });
245
+ const maybePromise = this.getItems();
246
+ return (maybePromise instanceof Promise
247
+ ? maybePromise.then(items => items.length)
248
+ : maybePromise.length);
249
+ }
250
+ /**
251
+ * Observes changes to the cursor's result set and triggers the specified callbacks
252
+ * when items are added, removed, or updated. Supports reactivity and transformation.
253
+ * @param callbacks - An object containing the callback functions to handle different change events.
254
+ * @param callbacks.added - Triggered when an item is added to the result set.
255
+ * @param callbacks.removed - Triggered when an item is removed from the result set.
256
+ * @param callbacks.changed - Triggered when an item in the result set is modified.
257
+ * @param callbacks.addedBefore - Triggered when an item is added before another item in the result set.
258
+ * @param callbacks.movedBefore - Triggered when an item is moved before another item in the result set.
259
+ * @param callbacks.changedField - Triggered when a specific field of an item changes.
260
+ * @param skipInitial - A boolean indicating whether to skip the initial notification of the current result set.
261
+ * @returns A function to stop observing changes.
262
+ */
263
+ observeChanges(callbacks, skipInitial = false) {
264
+ return this.observeRawChanges(Object
265
+ .entries(callbacks)
266
+ .reduce((memo, [callbackName, callback]) => {
267
+ if (!callback)
268
+ return memo;
269
+ return {
270
+ ...memo,
271
+ [callbackName]: (item, before) => {
272
+ const transformedValue = this.transform(item);
273
+ const hasBeforeParameter = before !== undefined;
274
+ const transformedBeforeValue = hasBeforeParameter && before
275
+ ? this.transform(before)
276
+ : null;
277
+ return callback(transformedValue, ...hasBeforeParameter ? [transformedBeforeValue] : []);
278
+ },
279
+ };
280
+ }, {}), skipInitial);
281
+ }
282
+ /**
283
+ * Forces the cursor to re-evaluate its result set by re-fetching items
284
+ * from the collection. This is useful when the underlying data or query
285
+ * criteria have changed, and you want to ensure the cursor reflects the latest state.
286
+ */
287
+ requery() {
288
+ if (!this.observer)
289
+ return;
290
+ this.observer.runChecks(this.getItems);
291
+ }
292
+ }
293
+ exports.default = Cursor;
@@ -0,0 +1,64 @@
1
+ type AddedCallback<T> = (item: T) => void;
2
+ type AddedBeforeCallback<T> = (item: T, before: T) => void;
3
+ type ChangedCallback<T> = (item: T) => void;
4
+ type ChangedFieldCallback<T> = <Field extends keyof T>(item: T, field: Field, oldValue: T[Field], newValue: T[Field]) => void;
5
+ type MovedBeforeCallback<T> = (item: T, before: T) => void;
6
+ type RemovedCallback<T> = (item: T) => void;
7
+ export interface ObserveCallbacks<T> {
8
+ added?: AddedCallback<T>;
9
+ addedBefore?: AddedBeforeCallback<T>;
10
+ changed?: ChangedCallback<T>;
11
+ changedField?: ChangedFieldCallback<T>;
12
+ movedBefore?: MovedBeforeCallback<T>;
13
+ removed?: RemovedCallback<T>;
14
+ }
15
+ /**
16
+ * Represents an observer that tracks changes in a collection of items and triggers
17
+ * callbacks for various events such as addition, removal, and modification of items.
18
+ * @template T - The type of the items being observed, which must include an `id` field.
19
+ */
20
+ export default class Observer<T extends {
21
+ id: any;
22
+ }> {
23
+ private previousItems;
24
+ private callbacks;
25
+ private unbindEvents;
26
+ /**
27
+ * Creates a new instance of the `Observer` class.
28
+ * Sets up event bindings and initializes the callbacks for tracking changes in a collection.
29
+ * @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
30
+ */
31
+ constructor(bindEvents: () => () => void);
32
+ private call;
33
+ private hasCallbacks;
34
+ /**
35
+ * Determines if the observer has no active callbacks registered for any events.
36
+ * @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
37
+ */
38
+ isEmpty(): boolean;
39
+ /**
40
+ * Compares the previous state of items with the new state and triggers the appropriate callbacks
41
+ * for events such as added, removed, changed, or moved items.
42
+ * @param getItems - A function that returns a promise resolving to the new items or the items themselves.
43
+ */
44
+ runChecks(getItems: () => Promise<T[]> | T[]): void;
45
+ private checkItems;
46
+ private stopped;
47
+ /**
48
+ * Stops the observer by unbinding all events and cleaning up resources.
49
+ * Safe to call multiple times - will only unbind once.
50
+ */
51
+ stop(): void;
52
+ /**
53
+ * Registers callbacks for specific events to observe changes in the collection.
54
+ * @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
55
+ * @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
56
+ */
57
+ addCallbacks(callbacks: ObserveCallbacks<T>, skipInitial?: boolean): void;
58
+ /**
59
+ * Removes the specified callbacks for specific events, unregistering them from the observer.
60
+ * @param callbacks - An object containing the callbacks to be removed for various events.
61
+ */
62
+ removeCallbacks(callbacks: ObserveCallbacks<T>): void;
63
+ }
64
+ export {};
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const isEqual_1 = __importDefault(require("../utils/isEqual"));
7
+ const uniqueBy_1 = __importDefault(require("../utils/uniqueBy"));
8
+ /**
9
+ * Represents an observer that tracks changes in a collection of items and triggers
10
+ * callbacks for various events such as addition, removal, and modification of items.
11
+ * @template T - The type of the items being observed, which must include an `id` field.
12
+ */
13
+ class Observer {
14
+ previousItems = [];
15
+ callbacks;
16
+ unbindEvents;
17
+ /**
18
+ * Creates a new instance of the `Observer` class.
19
+ * Sets up event bindings and initializes the callbacks for tracking changes in a collection.
20
+ * @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
21
+ */
22
+ constructor(bindEvents) {
23
+ this.callbacks = {
24
+ added: [],
25
+ addedBefore: [],
26
+ changed: [],
27
+ changedField: [],
28
+ movedBefore: [],
29
+ removed: [],
30
+ };
31
+ this.unbindEvents = bindEvents();
32
+ }
33
+ call(event, ...args) {
34
+ this.callbacks[event].forEach(({ callback, options }) => {
35
+ // execute only if it's not initial call or if initial call should not be skipped
36
+ if (!options.skipInitial || !options.isInitial) {
37
+ callback(...args);
38
+ }
39
+ });
40
+ }
41
+ hasCallbacks(events) {
42
+ return events.some(event => this.callbacks[event].length > 0);
43
+ }
44
+ /**
45
+ * Determines if the observer has no active callbacks registered for any events.
46
+ * @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
47
+ */
48
+ isEmpty() {
49
+ return !this.hasCallbacks([
50
+ 'added',
51
+ 'addedBefore',
52
+ 'changed',
53
+ 'changedField',
54
+ 'movedBefore',
55
+ 'removed',
56
+ ]);
57
+ }
58
+ /**
59
+ * Compares the previous state of items with the new state and triggers the appropriate callbacks
60
+ * for events such as added, removed, changed, or moved items.
61
+ * @param getItems - A function that returns a promise resolving to the new items or the items themselves.
62
+ */
63
+ runChecks(getItems) {
64
+ const result = getItems();
65
+ if (result instanceof Promise) {
66
+ result
67
+ .then(newItems => this.checkItems(newItems))
68
+ .catch((error) => {
69
+ // eslint-disable-next-line no-console
70
+ console.error('Error while asynchronously querying items', error);
71
+ });
72
+ }
73
+ else {
74
+ this.checkItems(result);
75
+ }
76
+ }
77
+ checkItems(newItems) {
78
+ const oldItemsMap = new Map(this.previousItems.map((item, index) => [
79
+ item.id,
80
+ { item, index, beforeItem: this.previousItems[index + 1] || null },
81
+ ]));
82
+ const newItemsMap = new Map(newItems.map((item, index) => [
83
+ item.id,
84
+ { item, index, beforeItem: newItems[index + 1] || null },
85
+ ]));
86
+ if (this.hasCallbacks(['changed', 'changedField', 'movedBefore', 'removed'])) {
87
+ // Check for removed or changed items
88
+ oldItemsMap.forEach(({ item: oldItem, index, beforeItem: oldBeforeItem }) => {
89
+ const newItem = newItemsMap.get(oldItem.id);
90
+ if (newItem) {
91
+ if (this.hasCallbacks(['changed', 'changedField']) // If the item exists but has changed, call 'changed' callback
92
+ && !(0, isEqual_1.default)(newItem.item, oldItem)) {
93
+ this.call('changed', newItem.item);
94
+ if (this.hasCallbacks(['changedField'])) {
95
+ // check for changed fields and call 'changedField' callback
96
+ const keys = (0, uniqueBy_1.default)([
97
+ ...Object.keys(newItem.item),
98
+ ...Object.keys(oldItem),
99
+ ], value => value);
100
+ keys.forEach((key) => {
101
+ if ((0, isEqual_1.default)(newItem.item[key], oldItem[key]))
102
+ return;
103
+ this.call('changedField', newItem.item, key, oldItem[key], newItem.item[key]);
104
+ });
105
+ }
106
+ }
107
+ // If the item's beforeItem has changed, call 'movedBefore' callback
108
+ if (newItem.index !== index && newItem.beforeItem?.id !== oldBeforeItem?.id) {
109
+ this.call('movedBefore', newItem.item, newItem.beforeItem);
110
+ }
111
+ }
112
+ else {
113
+ // If the item no longer exists, call 'removed' callback
114
+ this.call('removed', oldItem);
115
+ }
116
+ });
117
+ }
118
+ if (this.hasCallbacks(['added', 'addedBefore'])) {
119
+ // Check for added items
120
+ newItems.forEach((newItem, index) => {
121
+ const oldItem = oldItemsMap.get(newItem.id);
122
+ if (oldItem)
123
+ return;
124
+ // If the item is newly added, call 'added' and 'addedBefore' callbacks
125
+ this.call('added', newItem);
126
+ this.call('addedBefore', newItem, newItems[index + 1] || null);
127
+ });
128
+ }
129
+ // Store new items as previous items for next check
130
+ this.previousItems = newItems;
131
+ Object.keys(this.callbacks).forEach((key) => {
132
+ const event = key;
133
+ const callbacks = this.callbacks[event];
134
+ this.callbacks[event] = callbacks.map(callback => ({
135
+ ...callback,
136
+ options: {
137
+ ...callback.options,
138
+ isInitial: false,
139
+ },
140
+ }));
141
+ });
142
+ }
143
+ stopped = false;
144
+ /**
145
+ * Stops the observer by unbinding all events and cleaning up resources.
146
+ * Safe to call multiple times - will only unbind once.
147
+ */
148
+ stop() {
149
+ if (this.stopped)
150
+ return;
151
+ this.stopped = true;
152
+ this.unbindEvents();
153
+ }
154
+ /**
155
+ * Registers callbacks for specific events to observe changes in the collection.
156
+ * @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
157
+ * @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
158
+ */
159
+ addCallbacks(callbacks, skipInitial = false) {
160
+ Object.keys(callbacks).forEach((key) => {
161
+ const typedKey = key;
162
+ this.callbacks[typedKey].push({
163
+ callback: callbacks[typedKey],
164
+ options: { skipInitial, isInitial: true },
165
+ });
166
+ });
167
+ }
168
+ /**
169
+ * Removes the specified callbacks for specific events, unregistering them from the observer.
170
+ * @param callbacks - An object containing the callbacks to be removed for various events.
171
+ */
172
+ removeCallbacks(callbacks) {
173
+ Object.keys(callbacks).forEach((key) => {
174
+ const typedKey = key;
175
+ const index = this.callbacks[typedKey]
176
+ .findIndex(({ callback }) => callback === callbacks[typedKey]);
177
+ this.callbacks[typedKey].splice(index, 1);
178
+ });
179
+ }
180
+ }
181
+ exports.default = Observer;