@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.
- package/dist/composables/computedModel.d.ts +3 -0
- package/dist/composables/computedModel.js +57 -0
- package/dist/composables/computedModel.js.map +1 -0
- package/dist/composables/computedModelAttribute.d.ts +4 -0
- package/dist/composables/computedModelAttribute.js +28 -0
- package/dist/composables/computedModelAttribute.js.map +1 -0
- package/dist/composables/computedModels.d.ts +10 -0
- package/dist/composables/computedModels.js +152 -0
- package/dist/composables/computedModels.js.map +1 -0
- package/dist/composables/index.d.ts +7 -0
- package/dist/composables/useModelEvent.d.ts +3 -0
- package/dist/composables/useModelEvent.js +9 -0
- package/dist/composables/useModelEvent.js.map +1 -0
- package/dist/composables/useModels.d.ts +13 -0
- package/dist/composables/useModels.js +48 -0
- package/dist/composables/useModels.js.map +1 -0
- package/dist/composables/useSingletonModel.d.ts +11 -0
- package/dist/composables/useSingletonModel.js +14 -0
- package/dist/composables/useSingletonModel.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +10 -0
- package/dist/internals/config.js +11 -0
- package/dist/internals/config.js.map +1 -0
- package/dist/internals/errors.js +9 -0
- package/dist/internals/errors.js.map +1 -0
- package/dist/internals/flags.js +6 -0
- package/dist/internals/flags.js.map +1 -0
- package/dist/internals/tracking.d.ts +6 -0
- package/dist/internals/tracking.js +224 -0
- package/dist/internals/tracking.js.map +1 -0
- package/dist/lib/config.d.ts +16 -0
- package/dist/lib/config.js +14 -0
- package/dist/lib/config.js.map +1 -0
- package/dist/lib/index.d.ts +4 -0
- package/dist/lib/tracking.d.ts +21 -0
- package/dist/lib/tracking.js +42 -0
- package/dist/lib/tracking.js.map +1 -0
- package/package.json +42 -5
- package/src/composables/computedModel.ts +86 -0
- package/src/composables/computedModelAttribute.ts +40 -0
- package/src/composables/computedModels.ts +322 -0
- package/src/composables/index.ts +6 -0
- package/src/composables/useModelEvent.ts +12 -0
- package/src/composables/useModels.ts +76 -0
- package/src/composables/useSingletonModel.ts +23 -0
- package/src/index.ts +2 -0
- package/src/internals/config.ts +12 -0
- package/src/internals/errors.ts +10 -0
- package/src/internals/flags.ts +3 -0
- package/src/internals/tracking.ts +360 -0
- package/src/lib/config.ts +28 -0
- package/src/lib/index.ts +2 -0
- package/src/lib/tracking.ts +86 -0
- package/src/testing/TestingComputedModelsCache.ts +20 -0
- package/src/testing/setup.ts +33 -0
- package/src/testing/stubs/models/Book.schema.ts +13 -0
- package/src/testing/stubs/models/Book.ts +3 -0
- package/src/testing/stubs/models/Chapter.schema.ts +14 -0
- package/src/testing/stubs/models/Chapter.ts +3 -0
- package/src/testing/stubs/models/Item.schema.ts +14 -0
- package/src/testing/stubs/models/Item.ts +3 -0
- package/src/testing/stubs/models/Post.schema.ts +11 -0
- package/src/testing/stubs/models/Post.ts +3 -0
- package/src/testing/stubs/models/Shelf.schema.ts +13 -0
- package/src/testing/stubs/models/Shelf.ts +3 -0
- package/src/testing/stubs/models/Task.schema.ts +12 -0
- package/src/testing/stubs/models/Task.ts +3 -0
- package/src/testing/stubs/models/User.schema.ts +9 -0
- package/src/testing/stubs/models/User.ts +3 -0
- package/src/testing/stubs/models/registry.d.ts +19 -0
- package/README.md +0 -3
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import "../internals/flags.js";
|
|
2
|
+
import { listenToModelChanges } from "../internals/tracking.js";
|
|
3
|
+
import { isInstanceOf, tap, throttle } from "@noeldemartin/utils";
|
|
4
|
+
import { Model, getRelatedClasses } from "soukai-bis";
|
|
5
|
+
import { customRef, getCurrentScope, onScopeDispose, toRaw, watchEffect } from "vue";
|
|
6
|
+
// src/composables/computedModel.ts
|
|
7
|
+
function createModelProxy(model, track, trigger) {
|
|
8
|
+
return new Proxy(model, {
|
|
9
|
+
get(target, prop, receiver) {
|
|
10
|
+
if (prop === "__v_raw") return target;
|
|
11
|
+
if (prop === "__v_isReactive") return true;
|
|
12
|
+
track();
|
|
13
|
+
return Reflect.get(target, prop, receiver);
|
|
14
|
+
},
|
|
15
|
+
set(target, prop, val, receiver) {
|
|
16
|
+
const result = Reflect.set(target, prop, val, receiver);
|
|
17
|
+
trigger();
|
|
18
|
+
return result;
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
function computedModel(compute) {
|
|
23
|
+
return customRef((track, trigger) => {
|
|
24
|
+
let value;
|
|
25
|
+
let rawValue;
|
|
26
|
+
let proxy = null;
|
|
27
|
+
const listeners = [];
|
|
28
|
+
const onModelUpdated = throttle(trigger);
|
|
29
|
+
const stopListeners = () => {
|
|
30
|
+
listeners.forEach((stop) => stop());
|
|
31
|
+
listeners.splice(0, listeners.length);
|
|
32
|
+
};
|
|
33
|
+
getCurrentScope() && onScopeDispose(stopListeners);
|
|
34
|
+
watchEffect(() => {
|
|
35
|
+
const newValue = toRaw(compute());
|
|
36
|
+
if (rawValue instanceof Model && (!isInstanceOf(newValue, Model) || newValue.static() !== rawValue.static())) stopListeners();
|
|
37
|
+
if (newValue instanceof Model) {
|
|
38
|
+
if (newValue !== rawValue) proxy = createModelProxy(newValue, track, trigger);
|
|
39
|
+
value = proxy;
|
|
40
|
+
} else {
|
|
41
|
+
value = newValue;
|
|
42
|
+
proxy = null;
|
|
43
|
+
}
|
|
44
|
+
rawValue = newValue;
|
|
45
|
+
trigger();
|
|
46
|
+
if (!isInstanceOf(rawValue, Model) || listeners.length) return;
|
|
47
|
+
for (const modelClass of getRelatedClasses(rawValue.static())) listeners.push(...listenToModelChanges(modelClass, onModelUpdated));
|
|
48
|
+
});
|
|
49
|
+
return {
|
|
50
|
+
get: () => tap(value, () => track()),
|
|
51
|
+
set: () => console.warn("Computed model ref was not set (it is immutable).")
|
|
52
|
+
};
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
export { computedModel };
|
|
56
|
+
|
|
57
|
+
//# sourceMappingURL=computedModel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"computedModel.js","names":[],"sources":["../../src/composables/computedModel.ts"],"sourcesContent":["import { IS_REACTIVE, RAW } from '@aerogel/reactivity/internals/flags';\nimport { listenToModelChanges } from '@aerogel/reactivity/internals/tracking';\nimport { isInstanceOf, tap, throttle } from '@noeldemartin/utils';\nimport { Model, getRelatedClasses } from 'soukai-bis';\nimport { customRef, getCurrentScope, onScopeDispose, toRaw, watchEffect } from 'vue';\nimport type { Ref } from 'vue';\n\nfunction createModelProxy<T extends object>(model: T, track: () => void, trigger: () => void): T {\n return new Proxy(model, {\n get(target, prop, receiver) {\n if (prop === RAW) {\n return target;\n }\n\n if (prop === IS_REACTIVE) {\n return true;\n }\n\n track();\n return Reflect.get(target, prop, receiver);\n },\n set(target, prop, val, receiver) {\n const result = Reflect.set(target, prop, val, receiver);\n\n trigger();\n\n return result;\n },\n });\n}\n\nexport function computedModel<T>(compute: () => T): Readonly<Ref<T>> {\n return customRef((track, trigger) => {\n let value: T;\n let rawValue: T;\n let proxy: T | null = null;\n const listeners: Array<() => void> = [];\n const onModelUpdated = throttle(trigger);\n const stopListeners = () => {\n listeners.forEach((stop) => stop());\n listeners.splice(0, listeners.length);\n };\n\n getCurrentScope() && onScopeDispose(stopListeners);\n watchEffect(() => {\n const newValue = toRaw(compute());\n\n if (\n rawValue instanceof Model &&\n (!isInstanceOf(newValue, Model) || newValue.static() !== rawValue.static())\n ) {\n stopListeners();\n }\n\n if (newValue instanceof Model) {\n if (newValue !== rawValue) {\n proxy = createModelProxy(newValue, track, trigger) as T;\n }\n\n value = proxy as T;\n } else {\n value = newValue;\n proxy = null;\n }\n\n rawValue = newValue;\n\n trigger();\n\n if (!isInstanceOf(rawValue, Model) || listeners.length) {\n return;\n }\n\n for (const modelClass of getRelatedClasses(rawValue.static())) {\n listeners.push(...listenToModelChanges(modelClass, onModelUpdated));\n }\n });\n\n return {\n get: () => tap(value, () => track()),\n\n // oxlint-disable-next-line no-console\n set: () => console.warn('Computed model ref was not set (it is immutable).'),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,QAAQ,KAAK,mDAAmD;EAC/E;CACJ,CAAC;AACL"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { ComputedAttribute, Model } from "soukai-bis";
|
|
2
|
+
import { MaybeRefOrGetter, Ref } from "vue";
|
|
3
|
+
export declare function computedModelAttribute<TModel extends Model, TAttribute extends string & keyof TModel>(model: MaybeRefOrGetter<TModel | null | undefined>, attribute: TAttribute): TModel[TAttribute] extends ComputedAttribute<infer T> ? Readonly<Ref<T | undefined>> : never;
|
|
4
|
+
//# sourceMappingURL=computedModelAttribute.d.ts.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { fail } from "@noeldemartin/utils";
|
|
2
|
+
import { customRef, onScopeDispose, toRaw, toValue, watchEffect } from "vue";
|
|
3
|
+
// src/composables/computedModelAttribute.ts
|
|
4
|
+
function computedModelAttribute(model, attribute) {
|
|
5
|
+
return customRef((track, trigger) => {
|
|
6
|
+
let computedAttribute;
|
|
7
|
+
let unsubscribe;
|
|
8
|
+
watchEffect(() => {
|
|
9
|
+
const currentModel = toValue(model);
|
|
10
|
+
const currentComputedAttribute = currentModel && toRaw(currentModel).getComputedAttribute(attribute);
|
|
11
|
+
if (currentComputedAttribute === computedAttribute) return;
|
|
12
|
+
unsubscribe?.();
|
|
13
|
+
computedAttribute = currentComputedAttribute;
|
|
14
|
+
unsubscribe = computedAttribute?.subscribe(() => trigger());
|
|
15
|
+
});
|
|
16
|
+
onScopeDispose(() => unsubscribe?.());
|
|
17
|
+
return {
|
|
18
|
+
get: () => {
|
|
19
|
+
track();
|
|
20
|
+
return computedAttribute?.value;
|
|
21
|
+
},
|
|
22
|
+
set: () => fail("Computed model attribute ref is read-only")
|
|
23
|
+
};
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
export { computedModelAttribute };
|
|
27
|
+
|
|
28
|
+
//# sourceMappingURL=computedModelAttribute.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"computedModelAttribute.js","names":[],"sources":["../../src/composables/computedModelAttribute.ts"],"sourcesContent":["import { fail } from '@noeldemartin/utils';\nimport type { Nullable } from '@noeldemartin/utils';\nimport type { ComputedAttribute, Model } from 'soukai-bis';\nimport { customRef, onScopeDispose, toRaw, toValue, watchEffect } from 'vue';\nimport type { MaybeRefOrGetter, Ref } from 'vue';\n\nexport function computedModelAttribute<TModel extends Model, TAttribute extends string & keyof TModel>(\n model: MaybeRefOrGetter<TModel | null | undefined>,\n attribute: TAttribute,\n): TModel[TAttribute] extends ComputedAttribute<infer T> ? Readonly<Ref<T | undefined>> : never {\n return customRef((track, trigger) => {\n let computedAttribute: Nullable<ComputedAttribute>;\n let unsubscribe: Nullable<() => void>;\n\n watchEffect(() => {\n const currentModel = toValue(model);\n const currentComputedAttribute = currentModel && toRaw(currentModel).getComputedAttribute(attribute);\n\n if (currentComputedAttribute === computedAttribute) {\n return;\n }\n\n unsubscribe?.();\n\n computedAttribute = currentComputedAttribute;\n unsubscribe = computedAttribute?.subscribe(() => trigger());\n });\n\n onScopeDispose(() => unsubscribe?.());\n\n return {\n get: () => {\n track();\n\n return computedAttribute?.value;\n },\n set: () => fail('Computed model attribute ref is read-only'),\n };\n }) as TModel[TAttribute] extends ComputedAttribute<infer T> ? Readonly<Ref<T | undefined>> : never;\n}\n"],"mappings":";;;AAMA,SAAgB,uBACZ,OACA,WAC4F;CAC5F,OAAO,WAAW,OAAO,YAAY;EACjC,IAAI;EACJ,IAAI;EAEJ,kBAAkB;GACd,MAAM,eAAe,QAAQ,KAAK;GAClC,MAAM,2BAA2B,gBAAgB,MAAM,YAAY,CAAC,CAAC,qBAAqB,SAAS;GAEnG,IAAI,6BAA6B,mBAC7B;GAGJ,cAAc;GAEd,oBAAoB;GACpB,cAAc,mBAAmB,gBAAgB,QAAQ,CAAC;EAC9D,CAAC;EAED,qBAAqB,cAAc,CAAC;EAEpC,OAAO;GACH,WAAW;IACP,MAAM;IAEN,OAAO,mBAAmB;GAC9B;GACA,WAAW,KAAK,2CAA2C;EAC/D;CACJ,CAAC;AACL"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { ComputedAttribute, ModelConstructor } from "soukai-bis";
|
|
2
|
+
import { ComputedRef } from "vue";
|
|
3
|
+
export type ComputedAttributeName<T extends ModelConstructor> = T extends ModelConstructor<infer TModel> ? { [K in keyof TModel]: TModel[K] extends ComputedAttribute ? K : never; }[keyof TModel] & string : never;
|
|
4
|
+
export interface ComputedModelsOptions<TAttribute extends string = string> {
|
|
5
|
+
watchComputedAttributes?: TAttribute[];
|
|
6
|
+
cacheKey?: string;
|
|
7
|
+
includeSoftDeleted?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare function computedModels<T, TModelClass extends ModelConstructor = ModelConstructor>(modelClasses: TModelClass | TModelClass[], compute: () => T, options?: ComputedModelsOptions<ModelConstructor extends TModelClass ? string : ComputedAttributeName<TModelClass>>): ComputedRef<T>;
|
|
10
|
+
//# sourceMappingURL=computedModels.d.ts.map
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { config } from "../internals/config.js";
|
|
2
|
+
import { reportDevelopmentError } from "../internals/errors.js";
|
|
3
|
+
import { getTrackedModelsData, listenToModelChanges, onTrackedModelsCleared } from "../internals/tracking.js";
|
|
4
|
+
import { debounce, fail, isArray, isInstanceOf, isNullable, isPlainObject, tap, throttle } from "@noeldemartin/utils";
|
|
5
|
+
import { Model, hydrateModel } from "soukai-bis";
|
|
6
|
+
import { ReactiveEffect, computed, customRef, getCurrentScope, onScopeDispose, shallowReactive, shallowRef, toRaw, watch, watchEffect } from "vue";
|
|
7
|
+
// src/composables/computedModels.ts
|
|
8
|
+
const SERIALIZED_MODEL_KEY = "@model";
|
|
9
|
+
function isSerializedModelReference(value) {
|
|
10
|
+
return isPlainObject(value) && SERIALIZED_MODEL_KEY in value;
|
|
11
|
+
}
|
|
12
|
+
function isModel(value) {
|
|
13
|
+
return isInstanceOf(value, Model);
|
|
14
|
+
}
|
|
15
|
+
function mapNestedValues(value, isLeaf, callback, filter = () => true) {
|
|
16
|
+
const isIncluded = (item) => !isLeaf(item) || filter(item);
|
|
17
|
+
const mapItem = (item) => mapNestedValues(item, isLeaf, callback, filter);
|
|
18
|
+
if (isLeaf(value)) return callback(value);
|
|
19
|
+
if (isArray(value)) return value.filter(isIncluded).map(mapItem);
|
|
20
|
+
if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).filter(([, item]) => isIncluded(item)).map(([key, item]) => [key, mapItem(item)]));
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
function mapModels(value) {
|
|
24
|
+
const map = /* @__PURE__ */ new Map();
|
|
25
|
+
mapNestedValues(value, isModel, (model) => model.url && map.set(model.url, model));
|
|
26
|
+
return map;
|
|
27
|
+
}
|
|
28
|
+
function watchComputedAttributes(modelClass, attributes, callback) {
|
|
29
|
+
const modelAttributes = attributes.filter((attribute) => modelClass.hasComputedAttribute(attribute));
|
|
30
|
+
if (modelAttributes.length === 0) return;
|
|
31
|
+
const modelData = getTrackedModelsData(modelClass);
|
|
32
|
+
const subscriptions = /* @__PURE__ */ new Map();
|
|
33
|
+
watchEffect(() => {
|
|
34
|
+
const watchedModels = new Set(modelData.modelsArray.value);
|
|
35
|
+
for (const [model, unsubscribe] of subscriptions.entries()) {
|
|
36
|
+
if (watchedModels.has(model)) continue;
|
|
37
|
+
unsubscribe();
|
|
38
|
+
subscriptions.delete(model);
|
|
39
|
+
}
|
|
40
|
+
modelData.modelsArray.value.forEach((model) => {
|
|
41
|
+
if (subscriptions.has(model)) return;
|
|
42
|
+
const unsubscribes = modelAttributes.map((attribute) => {
|
|
43
|
+
return toRaw(model).getComputedAttribute(attribute).subscribe(callback);
|
|
44
|
+
});
|
|
45
|
+
subscriptions.set(model, () => unsubscribes.forEach((unsubscribe) => unsubscribe()));
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
getCurrentScope() && onScopeDispose(() => subscriptions.forEach((unsubscribe) => unsubscribe()));
|
|
49
|
+
}
|
|
50
|
+
function shallowComputedModels(modelClasses, compute, options = {}) {
|
|
51
|
+
const watchedAttributes = options.watchComputedAttributes ?? [];
|
|
52
|
+
const unknownAttribute = watchedAttributes.find((attribute) => !modelClasses.some((modelClass) => modelClass.hasComputedAttribute(attribute)));
|
|
53
|
+
if (unknownAttribute) throw new Error(`Computed attribute '${unknownAttribute}' is not defined in any of the watched models.`);
|
|
54
|
+
return customRef((track, trigger) => {
|
|
55
|
+
let value;
|
|
56
|
+
let dirty = true;
|
|
57
|
+
const invalidate = () => dirty || (dirty = true, trigger());
|
|
58
|
+
const invalidateComputedAttributes = throttle(invalidate);
|
|
59
|
+
const computeEffect = new ReactiveEffect(compute);
|
|
60
|
+
const listeners = modelClasses.flatMap((modelClass) => listenToModelChanges(modelClass, invalidate));
|
|
61
|
+
computeEffect.scheduler = invalidate;
|
|
62
|
+
modelClasses.forEach((modelClass) => watchComputedAttributes(modelClass, watchedAttributes, invalidateComputedAttributes));
|
|
63
|
+
getCurrentScope() && onScopeDispose(() => listeners.forEach((stop) => stop()));
|
|
64
|
+
return {
|
|
65
|
+
get: () => {
|
|
66
|
+
if (dirty) {
|
|
67
|
+
value = computeEffect.run();
|
|
68
|
+
dirty = false;
|
|
69
|
+
}
|
|
70
|
+
track();
|
|
71
|
+
return value;
|
|
72
|
+
},
|
|
73
|
+
set: () => console.warn("Computed models ref was not set (it is immutable).")
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
function reactiveComputedModels(modelClasses, compute, options = {}) {
|
|
78
|
+
let reactiveModelsMap = /* @__PURE__ */ new Map();
|
|
79
|
+
const cachedValue = shallowRef(null);
|
|
80
|
+
const shallowModels = shallowComputedModels(modelClasses, compute, options);
|
|
81
|
+
const reactiveModels = computed(() => {
|
|
82
|
+
const value = shallowModels.value;
|
|
83
|
+
return tap(toReactiveModels(isNullable(value) && cachedValue.value ? cachedValue.value.value : value, options), (models) => reactiveModelsMap = mapModels(models));
|
|
84
|
+
});
|
|
85
|
+
const listeners = modelClasses.map((modelClass) => modelClass.on("modified", ({ model: updatedModel, field }) => {
|
|
86
|
+
if (!updatedModel.url) return;
|
|
87
|
+
Object.assign(reactiveModelsMap.get(updatedModel.url) ?? {}, { [field]: updatedModel.getAttribute(field) });
|
|
88
|
+
}));
|
|
89
|
+
getCurrentScope() && onScopeDispose(() => listeners.forEach((stop) => stop()));
|
|
90
|
+
if (options.cacheKey) {
|
|
91
|
+
const cache = config.computedModelsCache ?? fail("Computed models cache is missing");
|
|
92
|
+
restoreCachedValue(cache, options.cacheKey).then((value) => value && (cachedValue.value ??= value));
|
|
93
|
+
watchCachedValue(cache, options.cacheKey, reactiveModels, shallowModels, cachedValue);
|
|
94
|
+
}
|
|
95
|
+
return reactiveModels;
|
|
96
|
+
}
|
|
97
|
+
async function restoreCachedValue(cache, key) {
|
|
98
|
+
try {
|
|
99
|
+
const cached = await cache.get(key);
|
|
100
|
+
if (cached === void 0) return null;
|
|
101
|
+
return { value: await hydrateCachedValue(cached) };
|
|
102
|
+
} catch (error) {
|
|
103
|
+
reportDevelopmentError(error, `Failed restoring cached value '${key}'`);
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async function hydrateCachedModel(serializedModel) {
|
|
108
|
+
const model = await hydrateModel(serializedModel);
|
|
109
|
+
if (!model.hasUrl()) return model;
|
|
110
|
+
const trackedModelsData = getTrackedModelsData(model.static());
|
|
111
|
+
const trackedModel = trackedModelsData.modelsMap.values().find(({ url }) => url === model.url);
|
|
112
|
+
if (trackedModel) return trackedModel;
|
|
113
|
+
if (!trackedModelsData.loaded.value) trackedModelsData.modelsMap.add(model);
|
|
114
|
+
return model;
|
|
115
|
+
}
|
|
116
|
+
async function hydrateCachedValue(value) {
|
|
117
|
+
const hydratingModels = [];
|
|
118
|
+
mapNestedValues(value, isSerializedModelReference, (reference) => hydratingModels.push(hydrateCachedModel(reference[SERIALIZED_MODEL_KEY]).then((model) => [reference, model])));
|
|
119
|
+
const models = new Map(await Promise.all(hydratingModels));
|
|
120
|
+
return mapNestedValues(value, isSerializedModelReference, (reference) => models.get(reference));
|
|
121
|
+
}
|
|
122
|
+
function serializeCachedValue(value) {
|
|
123
|
+
return mapNestedValues(value, isModel, (model) => ({ [SERIALIZED_MODEL_KEY]: toRaw(model).serialize() }));
|
|
124
|
+
}
|
|
125
|
+
function watchCachedValue(cache, key, reactiveModels, shallowModels, cachedValue) {
|
|
126
|
+
const stopListeners = onTrackedModelsCleared(() => {
|
|
127
|
+
saveValue.cancel();
|
|
128
|
+
cachedValue.value = null;
|
|
129
|
+
});
|
|
130
|
+
const saveValue = debounce(async (value) => {
|
|
131
|
+
try {
|
|
132
|
+
await cache.set(key, serializeCachedValue(value));
|
|
133
|
+
} catch (error) {
|
|
134
|
+
reportDevelopmentError(error, `Failed caching value '${key}'`);
|
|
135
|
+
}
|
|
136
|
+
}, 500);
|
|
137
|
+
watch(reactiveModels, (value) => {
|
|
138
|
+
if (isNullable(shallowModels.value)) return;
|
|
139
|
+
cachedValue.value = { value };
|
|
140
|
+
saveValue(value);
|
|
141
|
+
});
|
|
142
|
+
getCurrentScope() && onScopeDispose(stopListeners);
|
|
143
|
+
}
|
|
144
|
+
function toReactiveModels(value, options = {}) {
|
|
145
|
+
return mapNestedValues(value, isModel, shallowReactive, options.includeSoftDeleted ? void 0 : (model) => !model.isSoftDeleted());
|
|
146
|
+
}
|
|
147
|
+
function computedModels(modelClasses, compute, options = {}) {
|
|
148
|
+
return reactiveComputedModels(isArray(modelClasses) ? modelClasses : [modelClasses], compute, options);
|
|
149
|
+
}
|
|
150
|
+
export { computedModels };
|
|
151
|
+
|
|
152
|
+
//# sourceMappingURL=computedModels.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"computedModels.js","names":[],"sources":["../../src/composables/computedModels.ts"],"sourcesContent":["import { config } from '@aerogel/reactivity/internals/config';\nimport { reportDevelopmentError } from '@aerogel/reactivity/internals/errors';\nimport {\n getTrackedModelsData,\n listenToModelChanges,\n onTrackedModelsCleared,\n} from '@aerogel/reactivity/internals/tracking';\nimport type { ComputedModelsCache } from '@aerogel/reactivity/lib/config';\nimport { debounce, fail, isArray, isInstanceOf, isNullable, isPlainObject, tap, throttle } from '@noeldemartin/utils';\nimport { Model, hydrateModel } from 'soukai-bis';\nimport type { ComputedAttribute, ModelConstructor, SerializedModel } from 'soukai-bis';\nimport {\n ReactiveEffect,\n computed,\n customRef,\n getCurrentScope,\n onScopeDispose,\n shallowReactive,\n shallowRef,\n toRaw,\n watch,\n watchEffect,\n} from 'vue';\nimport type { ComputedRef, Ref } from 'vue';\n\nconst SERIALIZED_MODEL_KEY = '@model';\n\nfunction isSerializedModelReference(value: unknown): value is { [SERIALIZED_MODEL_KEY]: SerializedModel } {\n return isPlainObject(value) && SERIALIZED_MODEL_KEY in value;\n}\n\nfunction isModel(value: unknown): value is Model {\n return isInstanceOf(value, Model);\n}\n\nfunction mapNestedValues<TLeaf>(\n value: unknown,\n isLeaf: (value: unknown) => value is TLeaf,\n callback: (leaf: TLeaf) => unknown,\n filter: (leaf: TLeaf) => boolean = () => true,\n): unknown {\n const isIncluded = (item: unknown) => !isLeaf(item) || filter(item);\n const mapItem = (item: unknown) => mapNestedValues(item, isLeaf, callback, filter);\n\n if (isLeaf(value)) {\n return callback(value);\n }\n\n if (isArray(value)) {\n return value.filter(isIncluded).map(mapItem);\n }\n\n if (isPlainObject(value)) {\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, item]) => isIncluded(item))\n .map(([key, item]) => [key, mapItem(item)]),\n );\n }\n\n return value;\n}\n\nfunction mapModels(value: unknown): Map<string, Model> {\n const map = new Map<string, Model>();\n\n mapNestedValues(value, isModel, (model) => model.url && map.set(model.url, model));\n\n return map;\n}\n\nfunction watchComputedAttributes(modelClass: ModelConstructor, attributes: string[], callback: () => void) {\n const modelAttributes = attributes.filter((attribute) => modelClass.hasComputedAttribute(attribute));\n\n if (modelAttributes.length === 0) {\n return;\n }\n\n const modelData = getTrackedModelsData(modelClass);\n const subscriptions = new Map<Model, () => void>();\n\n watchEffect(() => {\n const watchedModels = new Set<Model>(modelData.modelsArray.value);\n\n for (const [model, unsubscribe] of subscriptions.entries()) {\n if (watchedModels.has(model)) {\n continue;\n }\n\n unsubscribe();\n subscriptions.delete(model);\n }\n\n modelData.modelsArray.value.forEach((model) => {\n if (subscriptions.has(model)) {\n return;\n }\n\n const unsubscribes = modelAttributes.map((attribute) => {\n const computedAttribute = toRaw(model).getComputedAttribute(attribute);\n\n return computedAttribute.subscribe(callback);\n });\n\n subscriptions.set(model, () => unsubscribes.forEach((unsubscribe) => unsubscribe()));\n });\n });\n\n getCurrentScope() && onScopeDispose(() => subscriptions.forEach((unsubscribe) => unsubscribe()));\n}\n\nfunction shallowComputedModels<T>(\n modelClasses: ModelConstructor[],\n compute: () => T,\n options: ComputedModelsOptions = {},\n): ComputedRef<T> {\n const watchedAttributes = options.watchComputedAttributes ?? [];\n const unknownAttribute = watchedAttributes.find(\n (attribute) => !modelClasses.some((modelClass) => modelClass.hasComputedAttribute(attribute)),\n );\n\n if (unknownAttribute) {\n throw new Error(`Computed attribute '${unknownAttribute}' is not defined in any of the watched models.`);\n }\n\n return customRef((track, trigger) => {\n let value: T;\n let dirty = true;\n const invalidate = () => dirty || ((dirty = true), trigger());\n const invalidateComputedAttributes = throttle(invalidate);\n const computeEffect = new ReactiveEffect(compute);\n const listeners: Array<() => void> = modelClasses.flatMap((modelClass) =>\n listenToModelChanges(modelClass, invalidate),\n );\n\n computeEffect.scheduler = invalidate;\n\n modelClasses.forEach((modelClass) =>\n watchComputedAttributes(modelClass, watchedAttributes, invalidateComputedAttributes),\n );\n getCurrentScope() && onScopeDispose(() => listeners.forEach((stop) => stop()));\n\n return {\n get: () => {\n if (dirty) {\n value = computeEffect.run();\n dirty = false;\n }\n\n track();\n\n return value;\n },\n\n // oxlint-disable-next-line no-console\n set: () => console.warn('Computed models ref was not set (it is immutable).'),\n };\n }) as ComputedRef<T>;\n}\n\nfunction reactiveComputedModels<T>(\n modelClasses: ModelConstructor[],\n compute: () => T,\n options: ComputedModelsOptions = {},\n): ComputedRef<T> {\n let reactiveModelsMap = new Map<string, Model>();\n const cachedValue = shallowRef<{ value: T } | null>(null);\n const shallowModels = shallowComputedModels(modelClasses, compute, options);\n const reactiveModels = computed(() => {\n const value = shallowModels.value;\n\n return tap(\n toReactiveModels(isNullable(value) && cachedValue.value ? cachedValue.value.value : value, options),\n (models) => (reactiveModelsMap = mapModels(models)),\n );\n });\n\n const listeners = modelClasses.map((modelClass) =>\n modelClass.on('modified', ({ model: updatedModel, field }) => {\n if (!updatedModel.url) {\n return;\n }\n\n Object.assign(reactiveModelsMap.get(updatedModel.url) ?? {}, {\n [field]: updatedModel.getAttribute(field),\n });\n }),\n );\n\n getCurrentScope() && onScopeDispose(() => listeners.forEach((stop) => stop()));\n\n if (options.cacheKey) {\n const cache = config.computedModelsCache ?? fail<ComputedModelsCache>('Computed models cache is missing');\n\n void restoreCachedValue<T>(cache, options.cacheKey).then((value) => value && (cachedValue.value ??= value));\n\n watchCachedValue(cache, options.cacheKey, reactiveModels, shallowModels, cachedValue);\n }\n\n return reactiveModels;\n}\n\nasync function restoreCachedValue<T>(cache: ComputedModelsCache, key: string): Promise<{ value: T } | null> {\n try {\n const cached = await cache.get(key);\n\n if (cached === undefined) {\n return null;\n }\n\n return { value: (await hydrateCachedValue(cached)) as T };\n } catch (error) {\n reportDevelopmentError(error, `Failed restoring cached value '${key}'`);\n\n return null;\n }\n}\n\nasync function hydrateCachedModel(serializedModel: SerializedModel): Promise<Model> {\n const model = await hydrateModel(serializedModel);\n\n if (!model.hasUrl()) {\n return model;\n }\n\n const trackedModelsData = getTrackedModelsData(model.static());\n const trackedModel = trackedModelsData.modelsMap.values().find(({ url }) => url === model.url);\n\n if (trackedModel) {\n return trackedModel;\n }\n\n if (!trackedModelsData.loaded.value) {\n trackedModelsData.modelsMap.add(model);\n }\n\n return model;\n}\n\nasync function hydrateCachedValue(value: unknown): Promise<unknown> {\n const hydratingModels: Promise<[object, Model]>[] = [];\n\n mapNestedValues(value, isSerializedModelReference, (reference) =>\n hydratingModels.push(hydrateCachedModel(reference[SERIALIZED_MODEL_KEY]).then((model) => [reference, model])),\n );\n\n const models = new Map(await Promise.all(hydratingModels));\n\n return mapNestedValues(value, isSerializedModelReference, (reference) => models.get(reference));\n}\n\nfunction serializeCachedValue(value: unknown): unknown {\n return mapNestedValues(value, isModel, (model) => ({ [SERIALIZED_MODEL_KEY]: toRaw(model).serialize() }));\n}\n\nfunction watchCachedValue(\n cache: ComputedModelsCache,\n key: string,\n reactiveModels: ComputedRef<unknown>,\n shallowModels: ComputedRef<unknown>,\n cachedValue: Ref<{ value: unknown } | null>,\n): void {\n const stopListeners = onTrackedModelsCleared(() => {\n saveValue.cancel();\n\n cachedValue.value = null;\n });\n const saveValue = debounce(async (value: unknown) => {\n try {\n await cache.set(key, serializeCachedValue(value));\n } catch (error) {\n reportDevelopmentError(error, `Failed caching value '${key}'`);\n }\n }, 500);\n\n watch(reactiveModels, (value) => {\n if (isNullable(shallowModels.value)) {\n return;\n }\n\n cachedValue.value = { value };\n\n saveValue(value);\n });\n\n getCurrentScope() && onScopeDispose(stopListeners);\n}\n\nfunction toReactiveModels<T>(value: T, options: ComputedModelsOptions = {}): T {\n return mapNestedValues(\n value,\n isModel,\n shallowReactive,\n options.includeSoftDeleted ? undefined : (model) => !model.isSoftDeleted(),\n ) as T;\n}\n\nexport type ComputedAttributeName<T extends ModelConstructor> =\n T extends ModelConstructor<infer TModel>\n ? {\n [K in keyof TModel]: TModel[K] extends ComputedAttribute ? K : never;\n }[keyof TModel] &\n string\n : never;\n\nexport interface ComputedModelsOptions<TAttribute extends string = string> {\n watchComputedAttributes?: TAttribute[];\n cacheKey?: string;\n includeSoftDeleted?: boolean;\n}\n\nexport function computedModels<T, TModelClass extends ModelConstructor = ModelConstructor>(\n modelClasses: TModelClass | TModelClass[],\n compute: () => T,\n options: ComputedModelsOptions<\n ModelConstructor extends TModelClass ? string : ComputedAttributeName<TModelClass>\n > = {},\n): ComputedRef<T> {\n // TODO This implementation is probably very inefficient and needs to be improved for better performance with large\n // collections. There are also more details in the unit tests for this function.\n return reactiveComputedModels(isArray(modelClasses) ? modelClasses : [modelClasses], compute, options);\n}\n"],"mappings":";;;;;;;AAyBA,MAAM,uBAAuB;AAE7B,SAAS,2BAA2B,OAAsE;CACtG,OAAO,cAAc,KAAK,KAAK,wBAAwB;AAC3D;AAEA,SAAS,QAAQ,OAAgC;CAC7C,OAAO,aAAa,OAAO,KAAK;AACpC;AAEA,SAAS,gBACL,OACA,QACA,UACA,eAAyC,MAClC;CACP,MAAM,cAAc,SAAkB,CAAC,OAAO,IAAI,KAAK,OAAO,IAAI;CAClE,MAAM,WAAW,SAAkB,gBAAgB,MAAM,QAAQ,UAAU,MAAM;CAEjF,IAAI,OAAO,KAAK,GACZ,OAAO,SAAS,KAAK;CAGzB,IAAI,QAAQ,KAAK,GACb,OAAO,MAAM,OAAO,UAAU,CAAC,CAAC,IAAI,OAAO;CAG/C,IAAI,cAAc,KAAK,GACnB,OAAO,OAAO,YACV,OAAO,QAAQ,KAAK,CAAC,CAChB,QAAQ,GAAG,UAAU,WAAW,IAAI,CAAC,CAAC,CACtC,KAAK,CAAC,KAAK,UAAU,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,CAClD;CAGJ,OAAO;AACX;AAEA,SAAS,UAAU,OAAoC;CACnD,MAAM,sBAAM,IAAI,IAAmB;CAEnC,gBAAgB,OAAO,UAAU,UAAU,MAAM,OAAO,IAAI,IAAI,MAAM,KAAK,KAAK,CAAC;CAEjF,OAAO;AACX;AAEA,SAAS,wBAAwB,YAA8B,YAAsB,UAAsB;CACvG,MAAM,kBAAkB,WAAW,QAAQ,cAAc,WAAW,qBAAqB,SAAS,CAAC;CAEnG,IAAI,gBAAgB,WAAW,GAC3B;CAGJ,MAAM,YAAY,qBAAqB,UAAU;CACjD,MAAM,g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c,KAAK,GAC9B;EAGJ,YAAY,QAAQ,EAAE,MAAM;EAE5B,UAAU,KAAK;CACnB,CAAC;CAED,gBAAgB,KAAK,eAAe,aAAa;AACrD;AAEA,SAAS,iBAAoB,OAAU,UAAiC,CAAC,GAAM;CAC3E,OAAO,gBACH,OACA,SACA,iBACA,QAAQ,qBAAqB,KAAA,KAAa,UAAU,CAAC,MAAM,cAAc,CAC7E;AACJ;AAgBA,SAAgB,eACZ,cACA,SACA,UAEI,CAAC,GACS;CAGd,OAAO,uBAAuB,QAAQ,YAAY,IAAI,eAAe,CAAC,YAAY,GAAG,SAAS,OAAO;AACzG"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { computedModel } from "./computedModel.js";
|
|
2
|
+
import { computedModelAttribute } from "./computedModelAttribute.js";
|
|
3
|
+
import { ComputedAttributeName, ComputedModelsOptions, computedModels } from "./computedModels.js";
|
|
4
|
+
import { useModelEvent } from "./useModelEvent.js";
|
|
5
|
+
import { UseModelsResult, useModels } from "./useModels.js";
|
|
6
|
+
import { UseSingletonModelResult, useSingletonModel } from "./useSingletonModel.js";
|
|
7
|
+
export { ComputedAttributeName, ComputedModelsOptions, UseModelsResult, UseSingletonModelResult, computedModel, computedModelAttribute, computedModels, useModelEvent, useModels, useSingletonModel };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { Model, ModelConstructor, ModelInstanceEvent, ModelListener } from "soukai-bis";
|
|
2
|
+
export declare function useModelEvent<TModel extends Model, TEvent extends ModelInstanceEvent>(modelClass: ModelConstructor<TModel>, event: TEvent, listener: ModelListener<TModel, TEvent>): void;
|
|
3
|
+
//# sourceMappingURL=useModelEvent.d.ts.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { getCurrentScope, onScopeDispose } from "vue";
|
|
2
|
+
// src/composables/useModelEvent.ts
|
|
3
|
+
function useModelEvent(modelClass, event, listener) {
|
|
4
|
+
const cleanUp = modelClass.on(event, listener);
|
|
5
|
+
getCurrentScope() && onScopeDispose(cleanUp);
|
|
6
|
+
}
|
|
7
|
+
export { useModelEvent };
|
|
8
|
+
|
|
9
|
+
//# sourceMappingURL=useModelEvent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useModelEvent.js","names":[],"sources":["../../src/composables/useModelEvent.ts"],"sourcesContent":["import type { Model, ModelConstructor, ModelInstanceEvent, ModelListener } from 'soukai-bis';\nimport { getCurrentScope, onScopeDispose } from 'vue';\n\nexport function useModelEvent<TModel extends Model, TEvent extends ModelInstanceEvent>(\n modelClass: ModelConstructor<TModel>,\n event: TEvent,\n listener: ModelListener<TModel, TEvent>,\n): void {\n const cleanUp = modelClass.on(event, listener);\n\n getCurrentScope() && onScopeDispose(cleanUp);\n}\n"],"mappings":";;AAGA,SAAgB,cACZ,YACA,OACA,UACI;CACJ,MAAM,UAAU,WAAW,GAAG,OAAO,QAAQ;CAE7C,gBAAgB,KAAK,eAAe,OAAO;AAC/C"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Model, ModelConstructor, ModelWithUrl } from "soukai-bis";
|
|
2
|
+
import { ComputedRef, MaybeRef, Ref } from "vue";
|
|
3
|
+
export interface UseModelsResult<T extends Model> {
|
|
4
|
+
models: ComputedRef<ModelWithUrl<T>[]>;
|
|
5
|
+
loading: ComputedRef<boolean>;
|
|
6
|
+
refreshing: Readonly<Ref<boolean>>;
|
|
7
|
+
}
|
|
8
|
+
export declare function useModels<T extends Model>(modelClass: ModelConstructor<T>, options?: {
|
|
9
|
+
includeSoftDeleted?: boolean;
|
|
10
|
+
depth?: number;
|
|
11
|
+
only?: MaybeRef<string[]>;
|
|
12
|
+
}): UseModelsResult<T>;
|
|
13
|
+
//# sourceMappingURL=useModels.d.ts.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { computedModels } from "./computedModels.js";
|
|
2
|
+
import { config } from "../internals/config.js";
|
|
3
|
+
import { getTrackedModelsData } from "../internals/tracking.js";
|
|
4
|
+
import { computed, readonly, ref, shallowRef, toValue, watch, watchEffect } from "vue";
|
|
5
|
+
// src/composables/useModels.ts
|
|
6
|
+
function useModels(modelClass, options = {}) {
|
|
7
|
+
let lastLoadId = 0;
|
|
8
|
+
const hasUrls = options.only !== void 0;
|
|
9
|
+
const urlsLoading = ref(false);
|
|
10
|
+
const models = shallowRef([]);
|
|
11
|
+
const modelData = getTrackedModelsData(modelClass, {
|
|
12
|
+
load: !hasUrls,
|
|
13
|
+
depth: options.depth
|
|
14
|
+
});
|
|
15
|
+
watch(() => toValue(options.only), (urls) => {
|
|
16
|
+
if (!urls) return;
|
|
17
|
+
const loadId = ++lastLoadId;
|
|
18
|
+
if (urls.length === 0) {
|
|
19
|
+
urlsLoading.value = false;
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
urlsLoading.value = true;
|
|
23
|
+
modelData.load(urls).catch((error) => config.reportError(error)).finally(() => {
|
|
24
|
+
if (loadId !== lastLoadId) return;
|
|
25
|
+
urlsLoading.value = false;
|
|
26
|
+
});
|
|
27
|
+
}, {
|
|
28
|
+
immediate: true,
|
|
29
|
+
deep: true,
|
|
30
|
+
flush: "sync"
|
|
31
|
+
});
|
|
32
|
+
watchEffect(() => {
|
|
33
|
+
if (!hasUrls) {
|
|
34
|
+
models.value = modelData.modelsArray.value;
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const urlsSet = new Set(toValue(options.only));
|
|
38
|
+
models.value = modelData.modelsArray.value.filter((model) => urlsSet.has(model.url));
|
|
39
|
+
});
|
|
40
|
+
return {
|
|
41
|
+
models: computedModels(modelClass, () => models.value, { includeSoftDeleted: options.includeSoftDeleted }),
|
|
42
|
+
loading: hasUrls ? computed(() => urlsLoading.value) : computed(() => modelData.loading.value && !modelData.loaded.value),
|
|
43
|
+
refreshing: hasUrls ? computed(() => urlsLoading.value || modelData.loading.value) : readonly(modelData.loading)
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export { useModels };
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=useModels.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useModels.js","names":[],"sources":["../../src/composables/useModels.ts"],"sourcesContent":["import { computedModels } from '@aerogel/reactivity/composables/computedModels';\nimport { config } from '@aerogel/reactivity/internals/config';\nimport { getTrackedModelsData } from '@aerogel/reactivity/internals/tracking';\nimport type { Model, ModelConstructor, ModelWithUrl } from 'soukai-bis';\nimport { computed, readonly, ref, shallowRef, toValue, watch, watchEffect } from 'vue';\nimport type { ComputedRef, MaybeRef, Ref } from 'vue';\n\nexport interface UseModelsResult<T extends Model> {\n models: ComputedRef<ModelWithUrl<T>[]>;\n loading: ComputedRef<boolean>;\n refreshing: Readonly<Ref<boolean>>;\n}\n\nexport function useModels<T extends Model>(\n modelClass: ModelConstructor<T>,\n options: { includeSoftDeleted?: boolean; depth?: number; only?: MaybeRef<string[]> } = {},\n): UseModelsResult<T> {\n let lastLoadId = 0;\n const hasUrls = options.only !== undefined;\n const urlsLoading = ref(false);\n const models = shallowRef([]) as Ref<ModelWithUrl<T>[]>;\n const modelData = getTrackedModelsData<T>(modelClass, { load: !hasUrls, depth: options.depth });\n\n watch(\n () => toValue(options.only),\n (urls) => {\n if (!urls) {\n return;\n }\n\n const loadId = ++lastLoadId;\n\n if (urls.length === 0) {\n urlsLoading.value = false;\n\n return;\n }\n\n urlsLoading.value = true;\n\n modelData\n .load(urls)\n .catch((error) => config.reportError(error))\n .finally(() => {\n if (loadId !== lastLoadId) {\n return;\n }\n\n urlsLoading.value = false;\n });\n },\n { immediate: true, deep: true, flush: 'sync' },\n );\n\n watchEffect(() => {\n if (!hasUrls) {\n models.value = modelData.modelsArray.value;\n\n return;\n }\n\n const urlsSet = new Set(toValue(options.only));\n\n models.value = modelData.modelsArray.value.filter((model) => urlsSet.has(model.url));\n });\n\n return {\n models: computedModels(modelClass, () => models.value, { includeSoftDeleted: options.includeSoftDeleted }),\n loading: hasUrls\n ? computed(() => urlsLoading.value)\n : computed(() => modelData.loading.value && !modelData.loaded.value),\n refreshing: hasUrls\n ? computed(() => urlsLoading.value || modelData.loading.value)\n : readonly(modelData.loading),\n };\n}\n"],"mappings":";;;;;AAaA,SAAgB,UACZ,YACA,UAAuF,CAAC,GACtE;CAClB,IAAI,aAAa;CACjB,MAAM,UAAU,QAAQ,SAAS,KAAA;CACjC,MAAM,cAAc,IAAI,KAAK;CAC7B,MAAM,SAAS,WAAW,CAAC,CAAC;CAC5B,MAAM,YAAY,qBAAwB,YAAY;EAAE,MAAM,CAAC;EAAS,OAAO,QAAQ;CAAM,CAAC;CAE9F,YACU,QAAQ,QAAQ,IAAI,IACzB,SAAS;EACN,IAAI,CAAC,MACD;EAGJ,MAAM,SAAS,EAAE;EAEjB,IAAI,KAAK,WAAW,GAAG;GACnB,YAAY,QAAQ;GAEpB;EACJ;EAEA,YAAY,QAAQ;EAEpB,UACK,KAAK,IAAI,CAAC,CACV,OAAO,UAAU,OAAO,YAAY,KAAK,CAAC,CAAC,CAC3C,cAAc;GACX,IAAI,WAAW,YACX;GAGJ,YAAY,QAAQ;EACxB,CAAC;CACT,GACA;EAAE,WAAW;EAAM,MAAM;EAAM,OAAO;CAAO,CACjD;CAEA,kBAAkB;EACd,IAAI,CAAC,SAAS;GACV,OAAO,QAAQ,UAAU,YAAY;GAErC;EACJ;EAEA,MAAM,UAAU,IAAI,IAAI,QAAQ,QAAQ,IAAI,CAAC;EAE7C,OAAO,QAAQ,UAAU,YAAY,MAAM,QAAQ,UAAU,QAAQ,IAAI,MAAM,GAAG,CAAC;CACvF,CAAC;CAED,OAAO;EACH,QAAQ,eAAe,kBAAkB,OAAO,OAAO,EAAE,oBAAoB,QAAQ,mBAAmB,CAAC;EACzG,SAAS,UACH,eAAe,YAAY,KAAK,IAChC,eAAe,UAAU,QAAQ,SAAS,CAAC,UAAU,OAAO,KAAK;EACvE,YAAY,UACN,eAAe,YAAY,SAAS,UAAU,QAAQ,KAAK,IAC3D,SAAS,UAAU,OAAO;CACpC;AACJ"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Model, ModelConstructor, ModelWithUrl } from "soukai-bis";
|
|
2
|
+
import { ComputedRef, Ref } from "vue";
|
|
3
|
+
export interface UseSingletonModelResult<T extends Model> {
|
|
4
|
+
model: Readonly<Ref<ModelWithUrl<T> | null>>;
|
|
5
|
+
loading: ComputedRef<boolean>;
|
|
6
|
+
refreshing: Readonly<Ref<boolean>>;
|
|
7
|
+
}
|
|
8
|
+
export declare function useSingletonModel<T extends Model>(modelClass: ModelConstructor<T>, options?: {
|
|
9
|
+
includeSoftDeleted?: boolean;
|
|
10
|
+
}): UseSingletonModelResult<T>;
|
|
11
|
+
//# sourceMappingURL=useSingletonModel.d.ts.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { computedModel } from "./computedModel.js";
|
|
2
|
+
import { useModels } from "./useModels.js";
|
|
3
|
+
// src/composables/useSingletonModel.ts
|
|
4
|
+
function useSingletonModel(modelClass, options = {}) {
|
|
5
|
+
const { models, loading, refreshing } = useModels(modelClass, options);
|
|
6
|
+
return {
|
|
7
|
+
model: computedModel(() => models.value[0] ?? null),
|
|
8
|
+
loading,
|
|
9
|
+
refreshing
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export { useSingletonModel };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=useSingletonModel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useSingletonModel.js","names":[],"sources":["../../src/composables/useSingletonModel.ts"],"sourcesContent":["import { computedModel } from '@aerogel/reactivity/composables/computedModel';\nimport { useModels } from '@aerogel/reactivity/composables/useModels';\nimport type { Model, ModelConstructor, ModelWithUrl } from 'soukai-bis';\nimport type { ComputedRef, Ref } from 'vue';\n\nexport interface UseSingletonModelResult<T extends Model> {\n model: Readonly<Ref<ModelWithUrl<T> | null>>;\n loading: ComputedRef<boolean>;\n refreshing: Readonly<Ref<boolean>>;\n}\n\nexport function useSingletonModel<T extends Model>(\n modelClass: ModelConstructor<T>,\n options: { includeSoftDeleted?: boolean } = {},\n): UseSingletonModelResult<T> {\n const { models, loading, refreshing } = useModels(modelClass, options);\n\n return {\n model: computedModel(() => models.value[0] ?? null),\n loading,\n refreshing,\n };\n}\n"],"mappings":";;;AAWA,SAAgB,kBACZ,YACA,UAA4C,CAAC,GACnB;CAC1B,MAAM,EAAE,QAAQ,SAAS,eAAe,UAAU,YAAY,OAAO;CAErE,OAAO;EACH,OAAO,oBAAoB,OAAO,MAAM,MAAM,IAAI;EAClD;EACA;CACJ;AACJ"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { computedModel } from "./composables/computedModel.js";
|
|
2
|
+
import { computedModelAttribute } from "./composables/computedModelAttribute.js";
|
|
3
|
+
import { ComputedAttributeName, ComputedModelsOptions, computedModels } from "./composables/computedModels.js";
|
|
4
|
+
import { useModelEvent } from "./composables/useModelEvent.js";
|
|
5
|
+
import { UseModelsResult, useModels } from "./composables/useModels.js";
|
|
6
|
+
import { UseSingletonModelResult, useSingletonModel } from "./composables/useSingletonModel.js";
|
|
7
|
+
import "./composables/index.js";
|
|
8
|
+
import { ComputedModelsCache, ModelsWorkerLoader, setComputedModelsCache, setErrorReporter, setModelsWorkerLoader } from "./lib/config.js";
|
|
9
|
+
import { clearTrackedModels, resetModelsState } from "./internals/tracking.js";
|
|
10
|
+
import { TrackOptions, findTrackedModel, getTrackedModels, getTrackedSingletonModel, loadTrackedModels, loadTrackedSingletonModel, refreshTrackedModels, setTrackedModelsDiscoveryUrls, trackModels } from "./lib/tracking.js";
|
|
11
|
+
import "./lib/index.js";
|
|
12
|
+
export { ComputedAttributeName, ComputedModelsCache, ComputedModelsOptions, ModelsWorkerLoader, TrackOptions, UseModelsResult, UseSingletonModelResult, clearTrackedModels, computedModel, computedModelAttribute, computedModels, findTrackedModel, getTrackedModels, getTrackedSingletonModel, loadTrackedModels, loadTrackedSingletonModel, refreshTrackedModels, resetModelsState, setComputedModelsCache, setErrorReporter, setModelsWorkerLoader, setTrackedModelsDiscoveryUrls, trackModels, useModelEvent, useModels, useSingletonModel };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { clearTrackedModels, resetModelsState } from "./internals/tracking.js";
|
|
2
|
+
import { computedModel } from "./composables/computedModel.js";
|
|
3
|
+
import { computedModelAttribute } from "./composables/computedModelAttribute.js";
|
|
4
|
+
import { computedModels } from "./composables/computedModels.js";
|
|
5
|
+
import { useModelEvent } from "./composables/useModelEvent.js";
|
|
6
|
+
import { useModels } from "./composables/useModels.js";
|
|
7
|
+
import { useSingletonModel } from "./composables/useSingletonModel.js";
|
|
8
|
+
import { setComputedModelsCache, setErrorReporter, setModelsWorkerLoader } from "./lib/config.js";
|
|
9
|
+
import { findTrackedModel, getTrackedModels, getTrackedSingletonModel, loadTrackedModels, loadTrackedSingletonModel, refreshTrackedModels, setTrackedModelsDiscoveryUrls, trackModels } from "./lib/tracking.js";
|
|
10
|
+
export { clearTrackedModels, computedModel, computedModelAttribute, computedModels, findTrackedModel, getTrackedModels, getTrackedSingletonModel, loadTrackedModels, loadTrackedSingletonModel, refreshTrackedModels, resetModelsState, setComputedModelsCache, setErrorReporter, setModelsWorkerLoader, setTrackedModelsDiscoveryUrls, trackModels, useModelEvent, useModels, useSingletonModel };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../../src/internals/config.ts"],"sourcesContent":["import type { ComputedModelsCache, ModelsWorkerLoader } from '@aerogel/reactivity/lib/config';\n\nexport const config = {\n reportError(error: unknown): unknown {\n // oxlint-disable-next-line no-console\n console.error(error);\n\n return;\n },\n computedModelsCache: null as ComputedModelsCache | null,\n createModelsWorkerLoader: null as (() => ModelsWorkerLoader) | null,\n};\n"],"mappings":";AAEA,MAAa,SAAS;CAClB,YAAY,OAAyB;EAEjC,QAAQ,MAAM,KAAK;CAGvB;CACA,qBAAqB;CACrB,0BAA0B;AAC9B"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { isDevelopment } from "@noeldemartin/utils";
|
|
2
|
+
// src/internals/errors.ts
|
|
3
|
+
function reportDevelopmentError(error, message) {
|
|
4
|
+
if (!isDevelopment()) return;
|
|
5
|
+
console.warn(message, error);
|
|
6
|
+
}
|
|
7
|
+
export { reportDevelopmentError };
|
|
8
|
+
|
|
9
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../../src/internals/errors.ts"],"sourcesContent":["import { isDevelopment } from '@noeldemartin/utils';\n\nexport function reportDevelopmentError(error: unknown, message: string): void {\n if (!isDevelopment()) {\n return;\n }\n\n // oxlint-disable-next-line no-console\n console.warn(message, error);\n}\n"],"mappings":";;AAEA,SAAgB,uBAAuB,OAAgB,SAAuB;CAC1E,IAAI,CAAC,cAAc,GACf;CAIJ,QAAQ,KAAK,SAAS,KAAK;AAC/B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flags.js","names":[],"sources":["../../src/internals/flags.ts"],"sourcesContent":["// Copied from Vue's ReactivityFlags.\nexport const IS_REACTIVE = '__v_isReactive';\nexport const RAW = '__v_raw';\n"],"mappings":";AACA,MAAa,cAAc;AAC3B,MAAa,MAAM"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import "@noeldemartin/utils/vue";
|
|
2
|
+
import { Model, ModelConstructor, ModelWithUrl } from "soukai-bis";
|
|
3
|
+
import { ComputedRef, Ref } from "vue";
|
|
4
|
+
export declare function clearTrackedModels(): void;
|
|
5
|
+
export declare function resetModelsState(): void;
|
|
6
|
+
//# sourceMappingURL=tracking.d.ts.map
|