@aerogel/reactivity 0.0.0-stage → 0.0.0

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 (71) hide show
  1. package/dist/composables/computedModel.d.ts +3 -0
  2. package/dist/composables/computedModel.js +57 -0
  3. package/dist/composables/computedModel.js.map +1 -0
  4. package/dist/composables/computedModelAttribute.d.ts +4 -0
  5. package/dist/composables/computedModelAttribute.js +28 -0
  6. package/dist/composables/computedModelAttribute.js.map +1 -0
  7. package/dist/composables/computedModels.d.ts +10 -0
  8. package/dist/composables/computedModels.js +152 -0
  9. package/dist/composables/computedModels.js.map +1 -0
  10. package/dist/composables/index.d.ts +7 -0
  11. package/dist/composables/useModelEvent.d.ts +3 -0
  12. package/dist/composables/useModelEvent.js +9 -0
  13. package/dist/composables/useModelEvent.js.map +1 -0
  14. package/dist/composables/useModels.d.ts +13 -0
  15. package/dist/composables/useModels.js +48 -0
  16. package/dist/composables/useModels.js.map +1 -0
  17. package/dist/composables/useSingletonModel.d.ts +11 -0
  18. package/dist/composables/useSingletonModel.js +14 -0
  19. package/dist/composables/useSingletonModel.js.map +1 -0
  20. package/dist/index.d.ts +12 -0
  21. package/dist/index.js +10 -0
  22. package/dist/internals/config.js +11 -0
  23. package/dist/internals/config.js.map +1 -0
  24. package/dist/internals/errors.js +9 -0
  25. package/dist/internals/errors.js.map +1 -0
  26. package/dist/internals/flags.js +6 -0
  27. package/dist/internals/flags.js.map +1 -0
  28. package/dist/internals/tracking.d.ts +6 -0
  29. package/dist/internals/tracking.js +224 -0
  30. package/dist/internals/tracking.js.map +1 -0
  31. package/dist/lib/config.d.ts +16 -0
  32. package/dist/lib/config.js +14 -0
  33. package/dist/lib/config.js.map +1 -0
  34. package/dist/lib/index.d.ts +4 -0
  35. package/dist/lib/tracking.d.ts +21 -0
  36. package/dist/lib/tracking.js +42 -0
  37. package/dist/lib/tracking.js.map +1 -0
  38. package/package.json +42 -5
  39. package/src/composables/computedModel.ts +86 -0
  40. package/src/composables/computedModelAttribute.ts +40 -0
  41. package/src/composables/computedModels.ts +322 -0
  42. package/src/composables/index.ts +6 -0
  43. package/src/composables/useModelEvent.ts +12 -0
  44. package/src/composables/useModels.ts +76 -0
  45. package/src/composables/useSingletonModel.ts +23 -0
  46. package/src/index.ts +2 -0
  47. package/src/internals/config.ts +12 -0
  48. package/src/internals/errors.ts +10 -0
  49. package/src/internals/flags.ts +3 -0
  50. package/src/internals/tracking.ts +360 -0
  51. package/src/lib/config.ts +28 -0
  52. package/src/lib/index.ts +2 -0
  53. package/src/lib/tracking.ts +86 -0
  54. package/src/testing/TestingComputedModelsCache.ts +20 -0
  55. package/src/testing/setup.ts +33 -0
  56. package/src/testing/stubs/models/Book.schema.ts +13 -0
  57. package/src/testing/stubs/models/Book.ts +3 -0
  58. package/src/testing/stubs/models/Chapter.schema.ts +14 -0
  59. package/src/testing/stubs/models/Chapter.ts +3 -0
  60. package/src/testing/stubs/models/Item.schema.ts +14 -0
  61. package/src/testing/stubs/models/Item.ts +3 -0
  62. package/src/testing/stubs/models/Post.schema.ts +11 -0
  63. package/src/testing/stubs/models/Post.ts +3 -0
  64. package/src/testing/stubs/models/Shelf.schema.ts +13 -0
  65. package/src/testing/stubs/models/Shelf.ts +3 -0
  66. package/src/testing/stubs/models/Task.schema.ts +12 -0
  67. package/src/testing/stubs/models/Task.ts +3 -0
  68. package/src/testing/stubs/models/User.schema.ts +9 -0
  69. package/src/testing/stubs/models/User.ts +3 -0
  70. package/src/testing/stubs/models/registry.d.ts +19 -0
  71. package/README.md +0 -3
@@ -0,0 +1,322 @@
1
+ import { config } from '@aerogel/reactivity/internals/config';
2
+ import { reportDevelopmentError } from '@aerogel/reactivity/internals/errors';
3
+ import {
4
+ getTrackedModelsData,
5
+ listenToModelChanges,
6
+ onTrackedModelsCleared,
7
+ } from '@aerogel/reactivity/internals/tracking';
8
+ import type { ComputedModelsCache } from '@aerogel/reactivity/lib/config';
9
+ import { debounce, fail, isArray, isInstanceOf, isNullable, isPlainObject, tap, throttle } from '@noeldemartin/utils';
10
+ import { Model, hydrateModel } from 'soukai-bis';
11
+ import type { ComputedAttribute, ModelConstructor, SerializedModel } from 'soukai-bis';
12
+ import {
13
+ ReactiveEffect,
14
+ computed,
15
+ customRef,
16
+ getCurrentScope,
17
+ onScopeDispose,
18
+ shallowReactive,
19
+ shallowRef,
20
+ toRaw,
21
+ watch,
22
+ watchEffect,
23
+ } from 'vue';
24
+ import type { ComputedRef, Ref } from 'vue';
25
+
26
+ const SERIALIZED_MODEL_KEY = '@model';
27
+
28
+ function isSerializedModelReference(value: unknown): value is { [SERIALIZED_MODEL_KEY]: SerializedModel } {
29
+ return isPlainObject(value) && SERIALIZED_MODEL_KEY in value;
30
+ }
31
+
32
+ function isModel(value: unknown): value is Model {
33
+ return isInstanceOf(value, Model);
34
+ }
35
+
36
+ function mapNestedValues<TLeaf>(
37
+ value: unknown,
38
+ isLeaf: (value: unknown) => value is TLeaf,
39
+ callback: (leaf: TLeaf) => unknown,
40
+ filter: (leaf: TLeaf) => boolean = () => true,
41
+ ): unknown {
42
+ const isIncluded = (item: unknown) => !isLeaf(item) || filter(item);
43
+ const mapItem = (item: unknown) => mapNestedValues(item, isLeaf, callback, filter);
44
+
45
+ if (isLeaf(value)) {
46
+ return callback(value);
47
+ }
48
+
49
+ if (isArray(value)) {
50
+ return value.filter(isIncluded).map(mapItem);
51
+ }
52
+
53
+ if (isPlainObject(value)) {
54
+ return Object.fromEntries(
55
+ Object.entries(value)
56
+ .filter(([, item]) => isIncluded(item))
57
+ .map(([key, item]) => [key, mapItem(item)]),
58
+ );
59
+ }
60
+
61
+ return value;
62
+ }
63
+
64
+ function mapModels(value: unknown): Map<string, Model> {
65
+ const map = new Map<string, Model>();
66
+
67
+ mapNestedValues(value, isModel, (model) => model.url && map.set(model.url, model));
68
+
69
+ return map;
70
+ }
71
+
72
+ function watchComputedAttributes(modelClass: ModelConstructor, attributes: string[], callback: () => void) {
73
+ const modelAttributes = attributes.filter((attribute) => modelClass.hasComputedAttribute(attribute));
74
+
75
+ if (modelAttributes.length === 0) {
76
+ return;
77
+ }
78
+
79
+ const modelData = getTrackedModelsData(modelClass);
80
+ const subscriptions = new Map<Model, () => void>();
81
+
82
+ watchEffect(() => {
83
+ const watchedModels = new Set<Model>(modelData.modelsArray.value);
84
+
85
+ for (const [model, unsubscribe] of subscriptions.entries()) {
86
+ if (watchedModels.has(model)) {
87
+ continue;
88
+ }
89
+
90
+ unsubscribe();
91
+ subscriptions.delete(model);
92
+ }
93
+
94
+ modelData.modelsArray.value.forEach((model) => {
95
+ if (subscriptions.has(model)) {
96
+ return;
97
+ }
98
+
99
+ const unsubscribes = modelAttributes.map((attribute) => {
100
+ const computedAttribute = toRaw(model).getComputedAttribute(attribute);
101
+
102
+ return computedAttribute.subscribe(callback);
103
+ });
104
+
105
+ subscriptions.set(model, () => unsubscribes.forEach((unsubscribe) => unsubscribe()));
106
+ });
107
+ });
108
+
109
+ getCurrentScope() && onScopeDispose(() => subscriptions.forEach((unsubscribe) => unsubscribe()));
110
+ }
111
+
112
+ function shallowComputedModels<T>(
113
+ modelClasses: ModelConstructor[],
114
+ compute: () => T,
115
+ options: ComputedModelsOptions = {},
116
+ ): ComputedRef<T> {
117
+ const watchedAttributes = options.watchComputedAttributes ?? [];
118
+ const unknownAttribute = watchedAttributes.find(
119
+ (attribute) => !modelClasses.some((modelClass) => modelClass.hasComputedAttribute(attribute)),
120
+ );
121
+
122
+ if (unknownAttribute) {
123
+ throw new Error(`Computed attribute '${unknownAttribute}' is not defined in any of the watched models.`);
124
+ }
125
+
126
+ return customRef((track, trigger) => {
127
+ let value: T;
128
+ let dirty = true;
129
+ const invalidate = () => dirty || ((dirty = true), trigger());
130
+ const invalidateComputedAttributes = throttle(invalidate);
131
+ const computeEffect = new ReactiveEffect(compute);
132
+ const listeners: Array<() => void> = modelClasses.flatMap((modelClass) =>
133
+ listenToModelChanges(modelClass, invalidate),
134
+ );
135
+
136
+ computeEffect.scheduler = invalidate;
137
+
138
+ modelClasses.forEach((modelClass) =>
139
+ watchComputedAttributes(modelClass, watchedAttributes, invalidateComputedAttributes),
140
+ );
141
+ getCurrentScope() && onScopeDispose(() => listeners.forEach((stop) => stop()));
142
+
143
+ return {
144
+ get: () => {
145
+ if (dirty) {
146
+ value = computeEffect.run();
147
+ dirty = false;
148
+ }
149
+
150
+ track();
151
+
152
+ return value;
153
+ },
154
+
155
+ // oxlint-disable-next-line no-console
156
+ set: () => console.warn('Computed models ref was not set (it is immutable).'),
157
+ };
158
+ }) as ComputedRef<T>;
159
+ }
160
+
161
+ function reactiveComputedModels<T>(
162
+ modelClasses: ModelConstructor[],
163
+ compute: () => T,
164
+ options: ComputedModelsOptions = {},
165
+ ): ComputedRef<T> {
166
+ let reactiveModelsMap = new Map<string, Model>();
167
+ const cachedValue = shallowRef<{ value: T } | null>(null);
168
+ const shallowModels = shallowComputedModels(modelClasses, compute, options);
169
+ const reactiveModels = computed(() => {
170
+ const value = shallowModels.value;
171
+
172
+ return tap(
173
+ toReactiveModels(isNullable(value) && cachedValue.value ? cachedValue.value.value : value, options),
174
+ (models) => (reactiveModelsMap = mapModels(models)),
175
+ );
176
+ });
177
+
178
+ const listeners = modelClasses.map((modelClass) =>
179
+ modelClass.on('modified', ({ model: updatedModel, field }) => {
180
+ if (!updatedModel.url) {
181
+ return;
182
+ }
183
+
184
+ Object.assign(reactiveModelsMap.get(updatedModel.url) ?? {}, {
185
+ [field]: updatedModel.getAttribute(field),
186
+ });
187
+ }),
188
+ );
189
+
190
+ getCurrentScope() && onScopeDispose(() => listeners.forEach((stop) => stop()));
191
+
192
+ if (options.cacheKey) {
193
+ const cache = config.computedModelsCache ?? fail<ComputedModelsCache>('Computed models cache is missing');
194
+
195
+ void restoreCachedValue<T>(cache, options.cacheKey).then((value) => value && (cachedValue.value ??= value));
196
+
197
+ watchCachedValue(cache, options.cacheKey, reactiveModels, shallowModels, cachedValue);
198
+ }
199
+
200
+ return reactiveModels;
201
+ }
202
+
203
+ async function restoreCachedValue<T>(cache: ComputedModelsCache, key: string): Promise<{ value: T } | null> {
204
+ try {
205
+ const cached = await cache.get(key);
206
+
207
+ if (cached === undefined) {
208
+ return null;
209
+ }
210
+
211
+ return { value: (await hydrateCachedValue(cached)) as T };
212
+ } catch (error) {
213
+ reportDevelopmentError(error, `Failed restoring cached value '${key}'`);
214
+
215
+ return null;
216
+ }
217
+ }
218
+
219
+ async function hydrateCachedModel(serializedModel: SerializedModel): Promise<Model> {
220
+ const model = await hydrateModel(serializedModel);
221
+
222
+ if (!model.hasUrl()) {
223
+ return model;
224
+ }
225
+
226
+ const trackedModelsData = getTrackedModelsData(model.static());
227
+ const trackedModel = trackedModelsData.modelsMap.values().find(({ url }) => url === model.url);
228
+
229
+ if (trackedModel) {
230
+ return trackedModel;
231
+ }
232
+
233
+ if (!trackedModelsData.loaded.value) {
234
+ trackedModelsData.modelsMap.add(model);
235
+ }
236
+
237
+ return model;
238
+ }
239
+
240
+ async function hydrateCachedValue(value: unknown): Promise<unknown> {
241
+ const hydratingModels: Promise<[object, Model]>[] = [];
242
+
243
+ mapNestedValues(value, isSerializedModelReference, (reference) =>
244
+ hydratingModels.push(hydrateCachedModel(reference[SERIALIZED_MODEL_KEY]).then((model) => [reference, model])),
245
+ );
246
+
247
+ const models = new Map(await Promise.all(hydratingModels));
248
+
249
+ return mapNestedValues(value, isSerializedModelReference, (reference) => models.get(reference));
250
+ }
251
+
252
+ function serializeCachedValue(value: unknown): unknown {
253
+ return mapNestedValues(value, isModel, (model) => ({ [SERIALIZED_MODEL_KEY]: toRaw(model).serialize() }));
254
+ }
255
+
256
+ function watchCachedValue(
257
+ cache: ComputedModelsCache,
258
+ key: string,
259
+ reactiveModels: ComputedRef<unknown>,
260
+ shallowModels: ComputedRef<unknown>,
261
+ cachedValue: Ref<{ value: unknown } | null>,
262
+ ): void {
263
+ const stopListeners = onTrackedModelsCleared(() => {
264
+ saveValue.cancel();
265
+
266
+ cachedValue.value = null;
267
+ });
268
+ const saveValue = debounce(async (value: unknown) => {
269
+ try {
270
+ await cache.set(key, serializeCachedValue(value));
271
+ } catch (error) {
272
+ reportDevelopmentError(error, `Failed caching value '${key}'`);
273
+ }
274
+ }, 500);
275
+
276
+ watch(reactiveModels, (value) => {
277
+ if (isNullable(shallowModels.value)) {
278
+ return;
279
+ }
280
+
281
+ cachedValue.value = { value };
282
+
283
+ saveValue(value);
284
+ });
285
+
286
+ getCurrentScope() && onScopeDispose(stopListeners);
287
+ }
288
+
289
+ function toReactiveModels<T>(value: T, options: ComputedModelsOptions = {}): T {
290
+ return mapNestedValues(
291
+ value,
292
+ isModel,
293
+ shallowReactive,
294
+ options.includeSoftDeleted ? undefined : (model) => !model.isSoftDeleted(),
295
+ ) as T;
296
+ }
297
+
298
+ export type ComputedAttributeName<T extends ModelConstructor> =
299
+ T extends ModelConstructor<infer TModel>
300
+ ? {
301
+ [K in keyof TModel]: TModel[K] extends ComputedAttribute ? K : never;
302
+ }[keyof TModel] &
303
+ string
304
+ : never;
305
+
306
+ export interface ComputedModelsOptions<TAttribute extends string = string> {
307
+ watchComputedAttributes?: TAttribute[];
308
+ cacheKey?: string;
309
+ includeSoftDeleted?: boolean;
310
+ }
311
+
312
+ export function computedModels<T, TModelClass extends ModelConstructor = ModelConstructor>(
313
+ modelClasses: TModelClass | TModelClass[],
314
+ compute: () => T,
315
+ options: ComputedModelsOptions<
316
+ ModelConstructor extends TModelClass ? string : ComputedAttributeName<TModelClass>
317
+ > = {},
318
+ ): ComputedRef<T> {
319
+ // TODO This implementation is probably very inefficient and needs to be improved for better performance with large
320
+ // collections. There are also more details in the unit tests for this function.
321
+ return reactiveComputedModels(isArray(modelClasses) ? modelClasses : [modelClasses], compute, options);
322
+ }
@@ -0,0 +1,6 @@
1
+ export * from './computedModel';
2
+ export * from './computedModelAttribute';
3
+ export * from './computedModels';
4
+ export * from './useModelEvent';
5
+ export * from './useModels';
6
+ export * from './useSingletonModel';
@@ -0,0 +1,12 @@
1
+ import type { Model, ModelConstructor, ModelInstanceEvent, ModelListener } from 'soukai-bis';
2
+ import { getCurrentScope, onScopeDispose } from 'vue';
3
+
4
+ export function useModelEvent<TModel extends Model, TEvent extends ModelInstanceEvent>(
5
+ modelClass: ModelConstructor<TModel>,
6
+ event: TEvent,
7
+ listener: ModelListener<TModel, TEvent>,
8
+ ): void {
9
+ const cleanUp = modelClass.on(event, listener);
10
+
11
+ getCurrentScope() && onScopeDispose(cleanUp);
12
+ }
@@ -0,0 +1,76 @@
1
+ import { computedModels } from '@aerogel/reactivity/composables/computedModels';
2
+ import { config } from '@aerogel/reactivity/internals/config';
3
+ import { getTrackedModelsData } from '@aerogel/reactivity/internals/tracking';
4
+ import type { Model, ModelConstructor, ModelWithUrl } from 'soukai-bis';
5
+ import { computed, readonly, ref, shallowRef, toValue, watch, watchEffect } from 'vue';
6
+ import type { ComputedRef, MaybeRef, Ref } from 'vue';
7
+
8
+ export interface UseModelsResult<T extends Model> {
9
+ models: ComputedRef<ModelWithUrl<T>[]>;
10
+ loading: ComputedRef<boolean>;
11
+ refreshing: Readonly<Ref<boolean>>;
12
+ }
13
+
14
+ export function useModels<T extends Model>(
15
+ modelClass: ModelConstructor<T>,
16
+ options: { includeSoftDeleted?: boolean; depth?: number; only?: MaybeRef<string[]> } = {},
17
+ ): UseModelsResult<T> {
18
+ let lastLoadId = 0;
19
+ const hasUrls = options.only !== undefined;
20
+ const urlsLoading = ref(false);
21
+ const models = shallowRef([]) as Ref<ModelWithUrl<T>[]>;
22
+ const modelData = getTrackedModelsData<T>(modelClass, { load: !hasUrls, depth: options.depth });
23
+
24
+ watch(
25
+ () => toValue(options.only),
26
+ (urls) => {
27
+ if (!urls) {
28
+ return;
29
+ }
30
+
31
+ const loadId = ++lastLoadId;
32
+
33
+ if (urls.length === 0) {
34
+ urlsLoading.value = false;
35
+
36
+ return;
37
+ }
38
+
39
+ urlsLoading.value = true;
40
+
41
+ modelData
42
+ .load(urls)
43
+ .catch((error) => config.reportError(error))
44
+ .finally(() => {
45
+ if (loadId !== lastLoadId) {
46
+ return;
47
+ }
48
+
49
+ urlsLoading.value = false;
50
+ });
51
+ },
52
+ { immediate: true, deep: true, flush: 'sync' },
53
+ );
54
+
55
+ watchEffect(() => {
56
+ if (!hasUrls) {
57
+ models.value = modelData.modelsArray.value;
58
+
59
+ return;
60
+ }
61
+
62
+ const urlsSet = new Set(toValue(options.only));
63
+
64
+ models.value = modelData.modelsArray.value.filter((model) => urlsSet.has(model.url));
65
+ });
66
+
67
+ return {
68
+ models: computedModels(modelClass, () => models.value, { includeSoftDeleted: options.includeSoftDeleted }),
69
+ loading: hasUrls
70
+ ? computed(() => urlsLoading.value)
71
+ : computed(() => modelData.loading.value && !modelData.loaded.value),
72
+ refreshing: hasUrls
73
+ ? computed(() => urlsLoading.value || modelData.loading.value)
74
+ : readonly(modelData.loading),
75
+ };
76
+ }
@@ -0,0 +1,23 @@
1
+ import { computedModel } from '@aerogel/reactivity/composables/computedModel';
2
+ import { useModels } from '@aerogel/reactivity/composables/useModels';
3
+ import type { Model, ModelConstructor, ModelWithUrl } from 'soukai-bis';
4
+ import type { ComputedRef, Ref } from 'vue';
5
+
6
+ export interface UseSingletonModelResult<T extends Model> {
7
+ model: Readonly<Ref<ModelWithUrl<T> | null>>;
8
+ loading: ComputedRef<boolean>;
9
+ refreshing: Readonly<Ref<boolean>>;
10
+ }
11
+
12
+ export function useSingletonModel<T extends Model>(
13
+ modelClass: ModelConstructor<T>,
14
+ options: { includeSoftDeleted?: boolean } = {},
15
+ ): UseSingletonModelResult<T> {
16
+ const { models, loading, refreshing } = useModels(modelClass, options);
17
+
18
+ return {
19
+ model: computedModel(() => models.value[0] ?? null),
20
+ loading,
21
+ refreshing,
22
+ };
23
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './composables';
2
+ export * from './lib';
@@ -0,0 +1,12 @@
1
+ import type { ComputedModelsCache, ModelsWorkerLoader } from '@aerogel/reactivity/lib/config';
2
+
3
+ export const config = {
4
+ reportError(error: unknown): unknown {
5
+ // oxlint-disable-next-line no-console
6
+ console.error(error);
7
+
8
+ return;
9
+ },
10
+ computedModelsCache: null as ComputedModelsCache | null,
11
+ createModelsWorkerLoader: null as (() => ModelsWorkerLoader) | null,
12
+ };
@@ -0,0 +1,10 @@
1
+ import { isDevelopment } from '@noeldemartin/utils';
2
+
3
+ export function reportDevelopmentError(error: unknown, message: string): void {
4
+ if (!isDevelopment()) {
5
+ return;
6
+ }
7
+
8
+ // oxlint-disable-next-line no-console
9
+ console.warn(message, error);
10
+ }
@@ -0,0 +1,3 @@
1
+ // Copied from Vue's ReactivityFlags.
2
+ export const IS_REACTIVE = '__v_isReactive';
3
+ export const RAW = '__v_raw';