@tanstack/vue-db 0.3.4 → 0.3.5
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.
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const vue = require("vue");
|
|
4
4
|
const db = require("@tanstack/db");
|
|
5
|
+
function snapshotRows(data) {
|
|
6
|
+
if (Array.isArray(data)) return [...data];
|
|
7
|
+
return data === void 0 ? [] : [data];
|
|
8
|
+
}
|
|
5
9
|
function useLiveQuery(configOrQueryOrCollection, deps = []) {
|
|
6
10
|
const collection = vue.computed(() => {
|
|
7
11
|
let unwrappedParam = configOrQueryOrCollection;
|
|
@@ -65,7 +69,7 @@ Or switch to syncMode "eager" if you want all data to sync automatically.`
|
|
|
65
69
|
status.value = snapshot.status;
|
|
66
70
|
persistedStatus.value = snapshot.persistedStatus;
|
|
67
71
|
persistedError.value = snapshot.persistedError;
|
|
68
|
-
internalData.value =
|
|
72
|
+
internalData.value = snapshotRows(snapshot.data);
|
|
69
73
|
};
|
|
70
74
|
vue.watchEffect((onInvalidate) => {
|
|
71
75
|
const currentCollection = collection.value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLiveQuery.cjs","sources":["../../src/useLiveQuery.ts"],"sourcesContent":["import {\n computed,\n getCurrentInstance,\n onUnmounted,\n reactive,\n ref,\n shallowRef,\n toValue,\n watchEffect,\n} from 'vue'\nimport {\n BaseQueryBuilder,\n createLiveQueryCollection,\n createLiveQueryObserver,\n getPublicCollection,\n isCollection,\n isSingleResultCollection,\n resolveLiveQueryValue,\n} from '@tanstack/db'\nimport type {\n ChangeMessage,\n Collection,\n CollectionStatus,\n Context,\n GetResult,\n InferResultType,\n InitialQueryBuilder,\n LiveQueryCollectionConfig,\n LiveQueryObserver,\n LiveQueryPersistedStatus,\n NonSingleResult,\n QueryBuilder,\n SingleResult,\n} from '@tanstack/db'\nimport type { ComputedRef, MaybeRefOrGetter } from 'vue'\n\n/**\n * Return type for useLiveQuery hook\n * @property state - Reactive Map of query results (key → item)\n * @property data - Reactive array of query results in order, or single result for findOne queries\n * @property collection - The underlying query collection instance\n * @property status - Current query status\n * @property isLoading - True while initial query data is loading\n * @property isReady - True when query has received first data and is ready\n * @property isIdle - True when query hasn't started yet\n * @property isError - True when query encountered an error\n * @property isCleanedUp - True when query has been cleaned up\n */\nexport interface UseLiveQueryReturn<TContext extends Context> {\n state: ComputedRef<Map<string | number, GetResult<TContext>>>\n data: ComputedRef<InferResultType<TContext>>\n collection: ComputedRef<Collection<GetResult<TContext>, string | number, {}>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\ntype InferConditionalResultType<TContext extends Context> =\n TContext extends SingleResult\n ? InferResultType<TContext> | []\n : InferResultType<TContext>\n\nexport type ConditionalUseLiveQueryReturn<TContext extends Context> = Omit<\n UseLiveQueryReturn<TContext>,\n `data` | `collection` | `status`\n> & {\n data: ComputedRef<InferConditionalResultType<TContext>>\n collection: ComputedRef<Collection<\n GetResult<TContext>,\n string | number,\n {}\n > | null>\n status: ComputedRef<CollectionStatus | `disabled`>\n}\n\nexport interface UseLiveQueryReturnWithCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<Array<T>>\n collection: ComputedRef<Collection<T, TKey, TUtils>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\nexport interface UseLiveQueryReturnWithSingleResultCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<T | undefined>\n collection: ComputedRef<Collection<T, TKey, TUtils> & SingleResult>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\n/**\n * Create a live query using a query function\n * @param queryFn - Query function that defines what data to fetch\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic query with object syntax\n * const { data, isLoading } = useLiveQuery((q) =>\n * q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.completed, false))\n * .select(({ todos }) => ({ id: todos.id, text: todos.text }))\n * )\n *\n * @example\n * // With reactive dependencies\n * const minPriority = ref(5)\n * const { data, state } = useLiveQuery(\n * (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => gt(todos.priority, minPriority.value)),\n * [minPriority] // Re-run when minPriority changes\n * )\n *\n * @example\n * // Join pattern\n * const { data } = useLiveQuery((q) =>\n * q.from({ issues: issueCollection })\n * .join({ persons: personCollection }, ({ issues, persons }) =>\n * eq(issues.userId, persons.id)\n * )\n * .select(({ issues, persons }) => ({\n * id: issues.id,\n * title: issues.title,\n * userName: persons.name\n * }))\n * )\n *\n * @example\n * // Handle loading and error states in template\n * const { data, isLoading, isError, status } = useLiveQuery((q) =>\n * q.from({ todos: todoCollection })\n * )\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error: {{ status }}</div>\n * // <ul v-else>\n * // <li v-for=\"todo in data\" :key=\"todo.id\">{{ todo.text }}</li>\n * // </ul>\n */\n// Overload 1: Accept query function that always returns QueryBuilder\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n// Overload 1b: Accept query function that can return undefined/null\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (\n q: InitialQueryBuilder,\n ) => QueryBuilder<TContext> | undefined | null,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): ConditionalUseLiveQueryReturn<TContext>\n\n/**\n * Create a live query using configuration object\n * @param config - Configuration object with query and options\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic config object usage\n * const { data, status } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection }),\n * gcTime: 60000\n * })\n *\n * @example\n * // With reactive dependencies\n * const filter = ref('active')\n * const { data, isReady } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.status, filter.value))\n * }, [filter])\n *\n * @example\n * // Handle all states uniformly\n * const { data, isLoading, isReady, isError } = useLiveQuery({\n * query: (q) => q.from({ items: itemCollection })\n * })\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Something went wrong</div>\n * // <div v-else-if=\"!isReady\">Preparing...</div>\n * // <div v-else>{{ data.length }} items loaded</div>\n */\n// Overload 2: Accept config object\nexport function useLiveQuery<TContext extends Context>(\n config: LiveQueryCollectionConfig<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n/**\n * Subscribe to an existing query collection (can be reactive)\n * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a ref)\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Using pre-created query collection\n * const myLiveQuery = createLiveQueryCollection((q) =>\n * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))\n * )\n * const { data, collection } = useLiveQuery(myLiveQuery)\n *\n * @example\n * // Reactive query collection reference\n * const selectedQuery = ref(todosQuery)\n * const { data, collection } = useLiveQuery(selectedQuery)\n *\n * // Switch queries reactively\n * selectedQuery.value = archiveQuery\n *\n * @example\n * // Access query collection methods directly\n * const { data, collection, isReady } = useLiveQuery(existingQuery)\n *\n * // Use underlying collection for mutations\n * const handleToggle = (id) => {\n * collection.value.update(id, draft => { draft.completed = !draft.completed })\n * }\n *\n * @example\n * // Handle states consistently\n * const { data, isLoading, isError } = useLiveQuery(sharedQuery)\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error loading data</div>\n * // <div v-else>\n * // <Item v-for=\"item in data\" :key=\"item.id\" v-bind=\"item\" />\n * // </div>\n */\n// Overload 3: Accept pre-created live query collection (can be reactive) - non-single result\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & NonSingleResult\n >,\n): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>\n\n// Overload 4: Accept pre-created live query collection with singleResult: true\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & SingleResult\n >,\n): UseLiveQueryReturnWithSingleResultCollection<TResult, TKey, TUtils>\n\n// Implementation\nexport function useLiveQuery(\n configOrQueryOrCollection: any,\n deps: Array<MaybeRefOrGetter<unknown>> = [],\n): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {\n const collection = computed(() => {\n // First check if the original parameter might be a ref/getter\n // by seeing if toValue returns something different than the original\n // NOTE: Don't call toValue on functions - toValue treats functions as getters and calls them!\n let unwrappedParam = configOrQueryOrCollection\n if (typeof configOrQueryOrCollection !== `function`) {\n try {\n const potentiallyUnwrapped = toValue(configOrQueryOrCollection)\n if (potentiallyUnwrapped !== configOrQueryOrCollection) {\n unwrappedParam = potentiallyUnwrapped\n }\n } catch {\n // If toValue fails, use original parameter\n unwrappedParam = configOrQueryOrCollection\n }\n }\n\n // Check if it's already a collection\n const inputIsCollection = isCollection(unwrappedParam)\n\n if (inputIsCollection) {\n // Warn when passing a collection directly with on-demand sync mode\n // In on-demand mode, data is only loaded when queries with predicates request it\n // Passing the collection directly doesn't provide any predicates, so no data loads\n const syncMode = (unwrappedParam as { config?: { syncMode?: string } })\n .config?.syncMode\n if (syncMode === `on-demand`) {\n console.warn(\n `[useLiveQuery] Warning: Passing a collection with syncMode \"on-demand\" directly to useLiveQuery ` +\n `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\\n\\n` +\n `Instead, use a query builder function:\\n` +\n ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\\n\\n` +\n `Or switch to syncMode \"eager\" if you want all data to sync automatically.`,\n )\n }\n // It's already a collection, ensure sync is started for Vue hooks\n // Only start sync if the collection is in idle state\n if (unwrappedParam.status === `idle`) {\n unwrappedParam.startSyncImmediate()\n }\n return unwrappedParam\n }\n\n // Reference deps to make computed reactive to them\n deps.forEach((dep) => toValue(dep))\n\n // Ensure we always start sync for Vue hooks\n if (typeof unwrappedParam === `function`) {\n // A query function returning null or undefined disables the query.\n return resolveLiveQueryValue(\n unwrappedParam(new BaseQueryBuilder() as InitialQueryBuilder),\n )\n } else {\n return createLiveQueryCollection({\n ...unwrappedParam,\n startSync: true,\n })\n }\n })\n\n // Reactive state that gets updated granularly through change events\n const state = reactive(new Map<string | number, any>())\n\n // Reactive data array that maintains sorted order\n const internalData = ref<Array<any>>([])\n\n // Computed wrapper for the data to match expected return type\n // Returns single item for singleResult collections, array otherwise\n const data = computed(() => {\n const currentCollection = collection.value\n if (!currentCollection) {\n return internalData.value\n }\n return isSingleResultCollection(currentCollection)\n ? internalData.value[0]\n : internalData.value\n })\n\n // Track collection status reactively\n const status = ref(\n collection.value ? collection.value.status : (`disabled` as const),\n )\n const persistedStatus = ref<LiveQueryPersistedStatus>(`unavailable`)\n const persistedError = shallowRef<unknown>(undefined)\n\n // The shared observer owns subscription, the ready-race, and status; Vue\n // materializes into its own reactive map (granular) + ordered array.\n let currentObserver: LiveQueryObserver<any, any> | null = null\n\n const syncFromObserver = (observer: LiveQueryObserver<any, any>) => {\n const snapshot = observer.getSnapshot()\n status.value = snapshot.status as CollectionStatus\n persistedStatus.value = snapshot.persistedStatus\n persistedError.value = snapshot.persistedError\n internalData.value = Array.from(snapshot.state?.values() ?? [])\n }\n\n // Watch for collection changes and subscribe to updates\n watchEffect((onInvalidate) => {\n const currentCollection = collection.value\n\n // Tear down any previous observer.\n currentObserver?.dispose()\n currentObserver = null\n\n // Handle null collection (disabled query)\n if (!currentCollection) {\n status.value = `disabled` as const\n persistedStatus.value = `unavailable`\n persistedError.value = undefined\n state.clear()\n internalData.value = []\n return\n }\n\n const observer = createLiveQueryObserver(currentCollection)\n currentObserver = observer\n\n // Initial rows arrive as the observer's first delta (includeInitialState);\n // apply them and every subsequent delta granularly to the reactive map.\n state.clear()\n\n const unsubscribe = observer.subscribe(\n (changes: Array<ChangeMessage<any>> | undefined) => {\n if (changes) {\n for (const change of changes) {\n switch (change.type) {\n case `insert`:\n case `update`:\n state.set(change.key, change.value)\n break\n case `delete`:\n state.delete(change.key)\n break\n }\n }\n } else {\n // Cleanup and other status-only publications carry no row deltas.\n // Rebuild the keyed view so it cannot diverge from ordered data.\n state.clear()\n for (const [key, value] of observer.getSnapshot().state ?? []) {\n state.set(key, value)\n }\n }\n syncFromObserver(observer)\n },\n )\n syncFromObserver(observer)\n\n // Cleanup when effect is invalidated\n onInvalidate(() => {\n unsubscribe()\n observer.dispose()\n currentObserver = null\n })\n })\n\n // Cleanup on unmount (only if we're in a component context)\n const instance = getCurrentInstance()\n if (instance) {\n onUnmounted(() => currentObserver?.dispose())\n }\n\n return {\n state: computed(() => state),\n data,\n collection: computed(() => getPublicCollection(collection.value)),\n status: computed(() => status.value),\n isLoading: computed(() => status.value === `loading`),\n isReady: computed(\n () => status.value === `ready` || status.value === `disabled`,\n ),\n persistedStatus: computed(() => persistedStatus.value),\n isPersistedReady: computed(() => persistedStatus.value === `ready`),\n persistedError: computed(() => persistedError.value),\n isIdle: computed(() => status.value === `idle`),\n isError: computed(() => status.value === `error`),\n isCleanedUp: computed(() => status.value === `cleaned-up`),\n }\n}\n"],"names":["computed","toValue","isCollection","resolveLiveQueryValue","BaseQueryBuilder","createLiveQueryCollection","reactive","ref","isSingleResultCollection","shallowRef","watchEffect","createLiveQueryObserver","getCurrentInstance","onUnmounted","getPublicCollection"],"mappings":";;;;AA0RO,SAAS,aACd,2BACA,OAAyC,IACkC;AAC3E,QAAM,aAAaA,IAAAA,SAAS,MAAM;AAIhC,QAAI,iBAAiB;AACrB,QAAI,OAAO,8BAA8B,YAAY;AACnD,UAAI;AACF,cAAM,uBAAuBC,IAAAA,QAAQ,yBAAyB;AAC9D,YAAI,yBAAyB,2BAA2B;AACtD,2BAAiB;AAAA,QACnB;AAAA,MACF,QAAQ;AAEN,yBAAiB;AAAA,MACnB;AAAA,IACF;AAGA,UAAM,oBAAoBC,GAAAA,aAAa,cAAc;AAErD,QAAI,mBAAmB;AAIrB,YAAM,WAAY,eACf,QAAQ;AACX,UAAI,aAAa,aAAa;AAC5B,gBAAQ;AAAA,UACN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAAA;AAAA,MAMJ;AAGA,UAAI,eAAe,WAAW,QAAQ;AACpC,uBAAe,mBAAA;AAAA,MACjB;AACA,aAAO;AAAA,IACT;AAGA,SAAK,QAAQ,CAAC,QAAQD,IAAAA,QAAQ,GAAG,CAAC;AAGlC,QAAI,OAAO,mBAAmB,YAAY;AAExC,aAAOE,GAAAA;AAAAA,QACL,eAAe,IAAIC,GAAAA,iBAAA,CAAyC;AAAA,MAAA;AAAA,IA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AO;AAAA,IAChD,aAAaA,IAAAA,SAAS,MAAM,OAAO,UAAU,YAAY;AAAA,EAAA;AAE7D;;"}
|
|
1
|
+
{"version":3,"file":"useLiveQuery.cjs","sources":["../../src/useLiveQuery.ts"],"sourcesContent":["import {\n computed,\n getCurrentInstance,\n onUnmounted,\n reactive,\n ref,\n shallowRef,\n toValue,\n watchEffect,\n} from 'vue'\nimport {\n BaseQueryBuilder,\n createLiveQueryCollection,\n createLiveQueryObserver,\n getPublicCollection,\n isCollection,\n isSingleResultCollection,\n resolveLiveQueryValue,\n} from '@tanstack/db'\nimport type {\n ChangeMessage,\n Collection,\n CollectionStatus,\n Context,\n GetResult,\n InferResultType,\n InitialQueryBuilder,\n LiveQueryCollectionConfig,\n LiveQueryObserver,\n LiveQueryPersistedStatus,\n NonSingleResult,\n QueryBuilder,\n SingleResult,\n} from '@tanstack/db'\nimport type { ComputedRef, MaybeRefOrGetter } from 'vue'\n\n/** Copy a snapshot's ordered rows; a single-result query's `data` is one row. */\nfunction snapshotRows(data: unknown): Array<any> {\n if (Array.isArray(data)) return [...data]\n return data === undefined ? [] : [data]\n}\n\n/**\n * Return type for useLiveQuery hook\n * @property state - Reactive Map of query results (key → item)\n * @property data - Reactive array of query results in order, or single result for findOne queries\n * @property collection - The underlying query collection instance\n * @property status - Current query status\n * @property isLoading - True while initial query data is loading\n * @property isReady - True when query has received first data and is ready\n * @property isIdle - True when query hasn't started yet\n * @property isError - True when query encountered an error\n * @property isCleanedUp - True when query has been cleaned up\n */\nexport interface UseLiveQueryReturn<TContext extends Context> {\n state: ComputedRef<Map<string | number, GetResult<TContext>>>\n data: ComputedRef<InferResultType<TContext>>\n collection: ComputedRef<Collection<GetResult<TContext>, string | number, {}>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\ntype InferConditionalResultType<TContext extends Context> =\n TContext extends SingleResult\n ? InferResultType<TContext> | []\n : InferResultType<TContext>\n\nexport type ConditionalUseLiveQueryReturn<TContext extends Context> = Omit<\n UseLiveQueryReturn<TContext>,\n `data` | `collection` | `status`\n> & {\n data: ComputedRef<InferConditionalResultType<TContext>>\n collection: ComputedRef<Collection<\n GetResult<TContext>,\n string | number,\n {}\n > | null>\n status: ComputedRef<CollectionStatus | `disabled`>\n}\n\nexport interface UseLiveQueryReturnWithCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<Array<T>>\n collection: ComputedRef<Collection<T, TKey, TUtils>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\nexport interface UseLiveQueryReturnWithSingleResultCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<T | undefined>\n collection: ComputedRef<Collection<T, TKey, TUtils> & SingleResult>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\n/**\n * Create a live query using a query function\n * @param queryFn - Query function that defines what data to fetch\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic query with object syntax\n * const { data, isLoading } = useLiveQuery((q) =>\n * q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.completed, false))\n * .select(({ todos }) => ({ id: todos.id, text: todos.text }))\n * )\n *\n * @example\n * // With reactive dependencies\n * const minPriority = ref(5)\n * const { data, state } = useLiveQuery(\n * (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => gt(todos.priority, minPriority.value)),\n * [minPriority] // Re-run when minPriority changes\n * )\n *\n * @example\n * // Join pattern\n * const { data } = useLiveQuery((q) =>\n * q.from({ issues: issueCollection })\n * .join({ persons: personCollection }, ({ issues, persons }) =>\n * eq(issues.userId, persons.id)\n * )\n * .select(({ issues, persons }) => ({\n * id: issues.id,\n * title: issues.title,\n * userName: persons.name\n * }))\n * )\n *\n * @example\n * // Handle loading and error states in template\n * const { data, isLoading, isError, status } = useLiveQuery((q) =>\n * q.from({ todos: todoCollection })\n * )\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error: {{ status }}</div>\n * // <ul v-else>\n * // <li v-for=\"todo in data\" :key=\"todo.id\">{{ todo.text }}</li>\n * // </ul>\n */\n// Overload 1: Accept query function that always returns QueryBuilder\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n// Overload 1b: Accept query function that can return undefined/null\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (\n q: InitialQueryBuilder,\n ) => QueryBuilder<TContext> | undefined | null,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): ConditionalUseLiveQueryReturn<TContext>\n\n/**\n * Create a live query using configuration object\n * @param config - Configuration object with query and options\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic config object usage\n * const { data, status } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection }),\n * gcTime: 60000\n * })\n *\n * @example\n * // With reactive dependencies\n * const filter = ref('active')\n * const { data, isReady } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.status, filter.value))\n * }, [filter])\n *\n * @example\n * // Handle all states uniformly\n * const { data, isLoading, isReady, isError } = useLiveQuery({\n * query: (q) => q.from({ items: itemCollection })\n * })\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Something went wrong</div>\n * // <div v-else-if=\"!isReady\">Preparing...</div>\n * // <div v-else>{{ data.length }} items loaded</div>\n */\n// Overload 2: Accept config object\nexport function useLiveQuery<TContext extends Context>(\n config: LiveQueryCollectionConfig<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n/**\n * Subscribe to an existing query collection (can be reactive)\n * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a ref)\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Using pre-created query collection\n * const myLiveQuery = createLiveQueryCollection((q) =>\n * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))\n * )\n * const { data, collection } = useLiveQuery(myLiveQuery)\n *\n * @example\n * // Reactive query collection reference\n * const selectedQuery = ref(todosQuery)\n * const { data, collection } = useLiveQuery(selectedQuery)\n *\n * // Switch queries reactively\n * selectedQuery.value = archiveQuery\n *\n * @example\n * // Access query collection methods directly\n * const { data, collection, isReady } = useLiveQuery(existingQuery)\n *\n * // Use underlying collection for mutations\n * const handleToggle = (id) => {\n * collection.value.update(id, draft => { draft.completed = !draft.completed })\n * }\n *\n * @example\n * // Handle states consistently\n * const { data, isLoading, isError } = useLiveQuery(sharedQuery)\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error loading data</div>\n * // <div v-else>\n * // <Item v-for=\"item in data\" :key=\"item.id\" v-bind=\"item\" />\n * // </div>\n */\n// Overload 3: Accept pre-created live query collection (can be reactive) - non-single result\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & NonSingleResult\n >,\n): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>\n\n// Overload 4: Accept pre-created live query collection with singleResult: true\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & SingleResult\n >,\n): UseLiveQueryReturnWithSingleResultCollection<TResult, TKey, TUtils>\n\n// Implementation\nexport function useLiveQuery(\n configOrQueryOrCollection: any,\n deps: Array<MaybeRefOrGetter<unknown>> = [],\n): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {\n const collection = computed(() => {\n // First check if the original parameter might be a ref/getter\n // by seeing if toValue returns something different than the original\n // NOTE: Don't call toValue on functions - toValue treats functions as getters and calls them!\n let unwrappedParam = configOrQueryOrCollection\n if (typeof configOrQueryOrCollection !== `function`) {\n try {\n const potentiallyUnwrapped = toValue(configOrQueryOrCollection)\n if (potentiallyUnwrapped !== configOrQueryOrCollection) {\n unwrappedParam = potentiallyUnwrapped\n }\n } catch {\n // If toValue fails, use original parameter\n unwrappedParam = configOrQueryOrCollection\n }\n }\n\n // Check if it's already a collection\n const inputIsCollection = isCollection(unwrappedParam)\n\n if (inputIsCollection) {\n // Warn when passing a collection directly with on-demand sync mode\n // In on-demand mode, data is only loaded when queries with predicates request it\n // Passing the collection directly doesn't provide any predicates, so no data loads\n const syncMode = (unwrappedParam as { config?: { syncMode?: string } })\n .config?.syncMode\n if (syncMode === `on-demand`) {\n console.warn(\n `[useLiveQuery] Warning: Passing a collection with syncMode \"on-demand\" directly to useLiveQuery ` +\n `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\\n\\n` +\n `Instead, use a query builder function:\\n` +\n ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\\n\\n` +\n `Or switch to syncMode \"eager\" if you want all data to sync automatically.`,\n )\n }\n // It's already a collection, ensure sync is started for Vue hooks\n // Only start sync if the collection is in idle state\n if (unwrappedParam.status === `idle`) {\n unwrappedParam.startSyncImmediate()\n }\n return unwrappedParam\n }\n\n // Reference deps to make computed reactive to them\n deps.forEach((dep) => toValue(dep))\n\n // Ensure we always start sync for Vue hooks\n if (typeof unwrappedParam === `function`) {\n // A query function returning null or undefined disables the query.\n return resolveLiveQueryValue(\n unwrappedParam(new BaseQueryBuilder() as InitialQueryBuilder),\n )\n } else {\n return createLiveQueryCollection({\n ...unwrappedParam,\n startSync: true,\n })\n }\n })\n\n // Reactive state that gets updated granularly through change events\n const state = reactive(new Map<string | number, any>())\n\n // Reactive data array that maintains sorted order\n const internalData = ref<Array<any>>([])\n\n // Computed wrapper for the data to match expected return type\n // Returns single item for singleResult collections, array otherwise\n const data = computed(() => {\n const currentCollection = collection.value\n if (!currentCollection) {\n return internalData.value\n }\n return isSingleResultCollection(currentCollection)\n ? internalData.value[0]\n : internalData.value\n })\n\n // Track collection status reactively\n const status = ref(\n collection.value ? collection.value.status : (`disabled` as const),\n )\n const persistedStatus = ref<LiveQueryPersistedStatus>(`unavailable`)\n const persistedError = shallowRef<unknown>(undefined)\n\n // The shared observer owns subscription, the ready-race, and status; Vue\n // materializes into its own reactive map (granular) + ordered array.\n let currentObserver: LiveQueryObserver<any, any> | null = null\n\n const syncFromObserver = (observer: LiveQueryObserver<any, any>) => {\n const snapshot = observer.getSnapshot()\n status.value = snapshot.status as CollectionStatus\n persistedStatus.value = snapshot.persistedStatus\n persistedError.value = snapshot.persistedError\n internalData.value = snapshotRows(snapshot.data)\n }\n\n // Watch for collection changes and subscribe to updates\n watchEffect((onInvalidate) => {\n const currentCollection = collection.value\n\n // Tear down any previous observer.\n currentObserver?.dispose()\n currentObserver = null\n\n // Handle null collection (disabled query)\n if (!currentCollection) {\n status.value = `disabled` as const\n persistedStatus.value = `unavailable`\n persistedError.value = undefined\n state.clear()\n internalData.value = []\n return\n }\n\n const observer = createLiveQueryObserver(currentCollection)\n currentObserver = observer\n\n // Initial rows arrive as the observer's first delta (includeInitialState);\n // apply them and every subsequent delta granularly to the reactive map.\n state.clear()\n\n const unsubscribe = observer.subscribe(\n (changes: Array<ChangeMessage<any>> | undefined) => {\n if (changes) {\n for (const change of changes) {\n switch (change.type) {\n case `insert`:\n case `update`:\n state.set(change.key, change.value)\n break\n case `delete`:\n state.delete(change.key)\n break\n }\n }\n } else {\n // Cleanup and other status-only publications carry no row deltas.\n // Rebuild the keyed view so it cannot diverge from ordered data.\n state.clear()\n for (const [key, value] of observer.getSnapshot().state ?? []) {\n state.set(key, value)\n }\n }\n syncFromObserver(observer)\n },\n )\n syncFromObserver(observer)\n\n // Cleanup when effect is invalidated\n onInvalidate(() => {\n unsubscribe()\n observer.dispose()\n currentObserver = null\n })\n })\n\n // Cleanup on unmount (only if we're in a component context)\n const instance = getCurrentInstance()\n if (instance) {\n onUnmounted(() => currentObserver?.dispose())\n }\n\n return {\n state: computed(() => state),\n data,\n collection: computed(() => getPublicCollection(collection.value)),\n status: computed(() => status.value),\n isLoading: computed(() => status.value === `loading`),\n isReady: computed(\n () => status.value === `ready` || status.value === `disabled`,\n ),\n persistedStatus: computed(() => persistedStatus.value),\n isPersistedReady: computed(() => persistedStatus.value === `ready`),\n persistedError: computed(() => persistedError.value),\n isIdle: computed(() => status.value === `idle`),\n isError: computed(() => status.value === `error`),\n isCleanedUp: computed(() => status.value === `cleaned-up`),\n }\n}\n"],"names":["computed","toValue","isCollection","resolveLiveQueryValue","BaseQueryBuilder","createLiveQueryCollection","reactive","ref","isSingleResultCollection","shallowRef","watchEffect","createLiveQueryObserver","getCurrentInstance","onUnmounted","getPublicCollection"],"mappings":";;;;AAqCA,SAAS,aAAa,MAA2B;AAC/C,MAAI,MAAM,QAAQ,IAAI,EAAG,QAAO,CAAC,GAAG,IAAI;AACxC,SAAO,SAAS,SA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eAAS,QAAA;AACT,wBAAkB;AAAA,IACpB,CAAC;AAAA,EACH,CAAC;AAGD,QAAM,WAAWC,IAAAA,mBAAA;AACjB,MAAI,UAAU;AACZC,oBAAY,MAAM,iBAAiB,SAAS;AAAA,EAC9C;AAEA,SAAO;AAAA,IACL,OAAOb,IAAAA,SAAS,MAAM,KAAK;AAAA,IAC3B;AAAA,IACA,YAAYA,IAAAA,SAAS,MAAMc,GAAAA,oBAAoB,WAAW,KAAK,CAAC;AAAA,IAChE,QAAQd,IAAAA,SAAS,MAAM,OAAO,KAAK;AAAA,IACnC,WAAWA,IAAAA,SAAS,MAAM,OAAO,UAAU,SAAS;AAAA,IACpD,SAASA,IAAAA;AAAAA,MACP,MAAM,OAAO,UAAU,WAAW,OAAO,UAAU;AAAA,IAAA;AAAA,IAErD,iBAAiBA,IAAAA,SAAS,MAAM,gBAAgB,KAAK;AAAA,IACrD,kBAAkBA,IAAAA,SAAS,MAAM,gBAAgB,UAAU,OAAO;AAAA,IAClE,gBAAgBA,IAAAA,SAAS,MAAM,eAAe,KAAK;AAAA,IACnD,QAAQA,IAAAA,SAAS,MAAM,OAAO,UAAU,MAAM;AAAA,IAC9C,SAASA,IAAAA,SAAS,MAAM,OAAO,UAAU,OAAO;AAAA,IAChD,aAAaA,IAAAA,SAAS,MAAM,OAAO,UAAU,YAAY;AAAA,EAAA;AAE7D;;"}
|
package/dist/esm/useLiveQuery.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { computed, toValue, reactive, ref, shallowRef, watchEffect, getCurrentInstance, onUnmounted } from "vue";
|
|
2
2
|
import { isCollection, resolveLiveQueryValue, BaseQueryBuilder, createLiveQueryCollection, isSingleResultCollection, createLiveQueryObserver, getPublicCollection } from "@tanstack/db";
|
|
3
|
+
function snapshotRows(data) {
|
|
4
|
+
if (Array.isArray(data)) return [...data];
|
|
5
|
+
return data === void 0 ? [] : [data];
|
|
6
|
+
}
|
|
3
7
|
function useLiveQuery(configOrQueryOrCollection, deps = []) {
|
|
4
8
|
const collection = computed(() => {
|
|
5
9
|
let unwrappedParam = configOrQueryOrCollection;
|
|
@@ -63,7 +67,7 @@ Or switch to syncMode "eager" if you want all data to sync automatically.`
|
|
|
63
67
|
status.value = snapshot.status;
|
|
64
68
|
persistedStatus.value = snapshot.persistedStatus;
|
|
65
69
|
persistedError.value = snapshot.persistedError;
|
|
66
|
-
internalData.value =
|
|
70
|
+
internalData.value = snapshotRows(snapshot.data);
|
|
67
71
|
};
|
|
68
72
|
watchEffect((onInvalidate) => {
|
|
69
73
|
const currentCollection = collection.value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLiveQuery.js","sources":["../../src/useLiveQuery.ts"],"sourcesContent":["import {\n computed,\n getCurrentInstance,\n onUnmounted,\n reactive,\n ref,\n shallowRef,\n toValue,\n watchEffect,\n} from 'vue'\nimport {\n BaseQueryBuilder,\n createLiveQueryCollection,\n createLiveQueryObserver,\n getPublicCollection,\n isCollection,\n isSingleResultCollection,\n resolveLiveQueryValue,\n} from '@tanstack/db'\nimport type {\n ChangeMessage,\n Collection,\n CollectionStatus,\n Context,\n GetResult,\n InferResultType,\n InitialQueryBuilder,\n LiveQueryCollectionConfig,\n LiveQueryObserver,\n LiveQueryPersistedStatus,\n NonSingleResult,\n QueryBuilder,\n SingleResult,\n} from '@tanstack/db'\nimport type { ComputedRef, MaybeRefOrGetter } from 'vue'\n\n/**\n * Return type for useLiveQuery hook\n * @property state - Reactive Map of query results (key → item)\n * @property data - Reactive array of query results in order, or single result for findOne queries\n * @property collection - The underlying query collection instance\n * @property status - Current query status\n * @property isLoading - True while initial query data is loading\n * @property isReady - True when query has received first data and is ready\n * @property isIdle - True when query hasn't started yet\n * @property isError - True when query encountered an error\n * @property isCleanedUp - True when query has been cleaned up\n */\nexport interface UseLiveQueryReturn<TContext extends Context> {\n state: ComputedRef<Map<string | number, GetResult<TContext>>>\n data: ComputedRef<InferResultType<TContext>>\n collection: ComputedRef<Collection<GetResult<TContext>, string | number, {}>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\ntype InferConditionalResultType<TContext extends Context> =\n TContext extends SingleResult\n ? InferResultType<TContext> | []\n : InferResultType<TContext>\n\nexport type ConditionalUseLiveQueryReturn<TContext extends Context> = Omit<\n UseLiveQueryReturn<TContext>,\n `data` | `collection` | `status`\n> & {\n data: ComputedRef<InferConditionalResultType<TContext>>\n collection: ComputedRef<Collection<\n GetResult<TContext>,\n string | number,\n {}\n > | null>\n status: ComputedRef<CollectionStatus | `disabled`>\n}\n\nexport interface UseLiveQueryReturnWithCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<Array<T>>\n collection: ComputedRef<Collection<T, TKey, TUtils>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\nexport interface UseLiveQueryReturnWithSingleResultCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<T | undefined>\n collection: ComputedRef<Collection<T, TKey, TUtils> & SingleResult>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\n/**\n * Create a live query using a query function\n * @param queryFn - Query function that defines what data to fetch\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic query with object syntax\n * const { data, isLoading } = useLiveQuery((q) =>\n * q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.completed, false))\n * .select(({ todos }) => ({ id: todos.id, text: todos.text }))\n * )\n *\n * @example\n * // With reactive dependencies\n * const minPriority = ref(5)\n * const { data, state } = useLiveQuery(\n * (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => gt(todos.priority, minPriority.value)),\n * [minPriority] // Re-run when minPriority changes\n * )\n *\n * @example\n * // Join pattern\n * const { data } = useLiveQuery((q) =>\n * q.from({ issues: issueCollection })\n * .join({ persons: personCollection }, ({ issues, persons }) =>\n * eq(issues.userId, persons.id)\n * )\n * .select(({ issues, persons }) => ({\n * id: issues.id,\n * title: issues.title,\n * userName: persons.name\n * }))\n * )\n *\n * @example\n * // Handle loading and error states in template\n * const { data, isLoading, isError, status } = useLiveQuery((q) =>\n * q.from({ todos: todoCollection })\n * )\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error: {{ status }}</div>\n * // <ul v-else>\n * // <li v-for=\"todo in data\" :key=\"todo.id\">{{ todo.text }}</li>\n * // </ul>\n */\n// Overload 1: Accept query function that always returns QueryBuilder\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n// Overload 1b: Accept query function that can return undefined/null\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (\n q: InitialQueryBuilder,\n ) => QueryBuilder<TContext> | undefined | null,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): ConditionalUseLiveQueryReturn<TContext>\n\n/**\n * Create a live query using configuration object\n * @param config - Configuration object with query and options\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic config object usage\n * const { data, status } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection }),\n * gcTime: 60000\n * })\n *\n * @example\n * // With reactive dependencies\n * const filter = ref('active')\n * const { data, isReady } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.status, filter.value))\n * }, [filter])\n *\n * @example\n * // Handle all states uniformly\n * const { data, isLoading, isReady, isError } = useLiveQuery({\n * query: (q) => q.from({ items: itemCollection })\n * })\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Something went wrong</div>\n * // <div v-else-if=\"!isReady\">Preparing...</div>\n * // <div v-else>{{ data.length }} items loaded</div>\n */\n// Overload 2: Accept config object\nexport function useLiveQuery<TContext extends Context>(\n config: LiveQueryCollectionConfig<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n/**\n * Subscribe to an existing query collection (can be reactive)\n * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a ref)\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Using pre-created query collection\n * const myLiveQuery = createLiveQueryCollection((q) =>\n * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))\n * )\n * const { data, collection } = useLiveQuery(myLiveQuery)\n *\n * @example\n * // Reactive query collection reference\n * const selectedQuery = ref(todosQuery)\n * const { data, collection } = useLiveQuery(selectedQuery)\n *\n * // Switch queries reactively\n * selectedQuery.value = archiveQuery\n *\n * @example\n * // Access query collection methods directly\n * const { data, collection, isReady } = useLiveQuery(existingQuery)\n *\n * // Use underlying collection for mutations\n * const handleToggle = (id) => {\n * collection.value.update(id, draft => { draft.completed = !draft.completed })\n * }\n *\n * @example\n * // Handle states consistently\n * const { data, isLoading, isError } = useLiveQuery(sharedQuery)\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error loading data</div>\n * // <div v-else>\n * // <Item v-for=\"item in data\" :key=\"item.id\" v-bind=\"item\" />\n * // </div>\n */\n// Overload 3: Accept pre-created live query collection (can be reactive) - non-single result\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & NonSingleResult\n >,\n): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>\n\n// Overload 4: Accept pre-created live query collection with singleResult: true\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & SingleResult\n >,\n): UseLiveQueryReturnWithSingleResultCollection<TResult, TKey, TUtils>\n\n// Implementation\nexport function useLiveQuery(\n configOrQueryOrCollection: any,\n deps: Array<MaybeRefOrGetter<unknown>> = [],\n): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {\n const collection = computed(() => {\n // First check if the original parameter might be a ref/getter\n // by seeing if toValue returns something different than the original\n // NOTE: Don't call toValue on functions - toValue treats functions as getters and calls them!\n let unwrappedParam = configOrQueryOrCollection\n if (typeof configOrQueryOrCollection !== `function`) {\n try {\n const potentiallyUnwrapped = toValue(configOrQueryOrCollection)\n if (potentiallyUnwrapped !== configOrQueryOrCollection) {\n unwrappedParam = potentiallyUnwrapped\n }\n } catch {\n // If toValue fails, use original parameter\n unwrappedParam = configOrQueryOrCollection\n }\n }\n\n // Check if it's already a collection\n const inputIsCollection = isCollection(unwrappedParam)\n\n if (inputIsCollection) {\n // Warn when passing a collection directly with on-demand sync mode\n // In on-demand mode, data is only loaded when queries with predicates request it\n // Passing the collection directly doesn't provide any predicates, so no data loads\n const syncMode = (unwrappedParam as { config?: { syncMode?: string } })\n .config?.syncMode\n if (syncMode === `on-demand`) {\n console.warn(\n `[useLiveQuery] Warning: Passing a collection with syncMode \"on-demand\" directly to useLiveQuery ` +\n `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\\n\\n` +\n `Instead, use a query builder function:\\n` +\n ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\\n\\n` +\n `Or switch to syncMode \"eager\" if you want all data to sync automatically.`,\n )\n }\n // It's already a collection, ensure sync is started for Vue hooks\n // Only start sync if the collection is in idle state\n if (unwrappedParam.status === `idle`) {\n unwrappedParam.startSyncImmediate()\n }\n return unwrappedParam\n }\n\n // Reference deps to make computed reactive to them\n deps.forEach((dep) => toValue(dep))\n\n // Ensure we always start sync for Vue hooks\n if (typeof unwrappedParam === `function`) {\n // A query function returning null or undefined disables the query.\n return resolveLiveQueryValue(\n unwrappedParam(new BaseQueryBuilder() as InitialQueryBuilder),\n )\n } else {\n return createLiveQueryCollection({\n ...unwrappedParam,\n startSync: true,\n })\n }\n })\n\n // Reactive state that gets updated granularly through change events\n const state = reactive(new Map<string | number, any>())\n\n // Reactive data array that maintains sorted order\n const internalData = ref<Array<any>>([])\n\n // Computed wrapper for the data to match expected return type\n // Returns single item for singleResult collections, array otherwise\n const data = computed(() => {\n const currentCollection = collection.value\n if (!currentCollection) {\n return internalData.value\n }\n return isSingleResultCollection(currentCollection)\n ? internalData.value[0]\n : internalData.value\n })\n\n // Track collection status reactively\n const status = ref(\n collection.value ? collection.value.status : (`disabled` as const),\n )\n const persistedStatus = ref<LiveQueryPersistedStatus>(`unavailable`)\n const persistedError = shallowRef<unknown>(undefined)\n\n // The shared observer owns subscription, the ready-race, and status; Vue\n // materializes into its own reactive map (granular) + ordered array.\n let currentObserver: LiveQueryObserver<any, any> | null = null\n\n const syncFromObserver = (observer: LiveQueryObserver<any, any>) => {\n const snapshot = observer.getSnapshot()\n status.value = snapshot.status as CollectionStatus\n persistedStatus.value = snapshot.persistedStatus\n persistedError.value = snapshot.persistedError\n internalData.value = Array.from(snapshot.state?.values() ?? [])\n }\n\n // Watch for collection changes and subscribe to updates\n watchEffect((onInvalidate) => {\n const currentCollection = collection.value\n\n // Tear down any previous observer.\n currentObserver?.dispose()\n currentObserver = null\n\n // Handle null collection (disabled query)\n if (!currentCollection) {\n status.value = `disabled` as const\n persistedStatus.value = `unavailable`\n persistedError.value = undefined\n state.clear()\n internalData.value = []\n return\n }\n\n const observer = createLiveQueryObserver(currentCollection)\n currentObserver = observer\n\n // Initial rows arrive as the observer's first delta (includeInitialState);\n // apply them and every subsequent delta granularly to the reactive map.\n state.clear()\n\n const unsubscribe = observer.subscribe(\n (changes: Array<ChangeMessage<any>> | undefined) => {\n if (changes) {\n for (const change of changes) {\n switch (change.type) {\n case `insert`:\n case `update`:\n state.set(change.key, change.value)\n break\n case `delete`:\n state.delete(change.key)\n break\n }\n }\n } else {\n // Cleanup and other status-only publications carry no row deltas.\n // Rebuild the keyed view so it cannot diverge from ordered data.\n state.clear()\n for (const [key, value] of observer.getSnapshot().state ?? []) {\n state.set(key, value)\n }\n }\n syncFromObserver(observer)\n },\n )\n syncFromObserver(observer)\n\n // Cleanup when effect is invalidated\n onInvalidate(() => {\n unsubscribe()\n observer.dispose()\n currentObserver = null\n })\n })\n\n // Cleanup on unmount (only if we're in a component context)\n const instance = getCurrentInstance()\n if (instance) {\n onUnmounted(() => currentObserver?.dispose())\n }\n\n return {\n state: computed(() => state),\n data,\n collection: computed(() => getPublicCollection(collection.value)),\n status: computed(() => status.value),\n isLoading: computed(() => status.value === `loading`),\n isReady: computed(\n () => status.value === `ready` || status.value === `disabled`,\n ),\n persistedStatus: computed(() => persistedStatus.value),\n isPersistedReady: computed(() => persistedStatus.value === `ready`),\n persistedError: computed(() => persistedError.value),\n isIdle: computed(() => status.value === `idle`),\n isError: computed(() => status.value === `error`),\n isCleanedUp: computed(() => status.value === `cleaned-up`),\n }\n}\n"],"names":[],"mappings":";;AA0RO,SAAS,aACd,2BACA,OAAyC,IACkC;AAC3E,QAAM,aAA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KAAK;AAAA,IAC3B;AAAA,IACA,YAAY,SAAS,MAAM,oBAAoB,WAAW,KAAK,CAAC;AAAA,IAChE,QAAQ,SAAS,MAAM,OAAO,KAAK;AAAA,IACnC,WAAW,SAAS,MAAM,OAAO,UAAU,SAAS;AAAA,IACpD,SAAS;AAAA,MACP,MAAM,OAAO,UAAU,WAAW,OAAO,UAAU;AAAA,IAAA;AAAA,IAErD,iBAAiB,SAAS,MAAM,gBAAgB,KAAK;AAAA,IACrD,kBAAkB,SAAS,MAAM,gBAAgB,UAAU,OAAO;AAAA,IAClE,gBAAgB,SAAS,MAAM,eAAe,KAAK;AAAA,IACnD,QAAQ,SAAS,MAAM,OAAO,UAAU,MAAM;AAAA,IAC9C,SAAS,SAAS,MAAM,OAAO,UAAU,OAAO;AAAA,IAChD,aAAa,SAAS,MAAM,OAAO,UAAU,YAAY;AAAA,EAAA;AAE7D;"}
|
|
1
|
+
{"version":3,"file":"useLiveQuery.js","sources":["../../src/useLiveQuery.ts"],"sourcesContent":["import {\n computed,\n getCurrentInstance,\n onUnmounted,\n reactive,\n ref,\n shallowRef,\n toValue,\n watchEffect,\n} from 'vue'\nimport {\n BaseQueryBuilder,\n createLiveQueryCollection,\n createLiveQueryObserver,\n getPublicCollection,\n isCollection,\n isSingleResultCollection,\n resolveLiveQueryValue,\n} from '@tanstack/db'\nimport type {\n ChangeMessage,\n Collection,\n CollectionStatus,\n Context,\n GetResult,\n InferResultType,\n InitialQueryBuilder,\n LiveQueryCollectionConfig,\n LiveQueryObserver,\n LiveQueryPersistedStatus,\n NonSingleResult,\n QueryBuilder,\n SingleResult,\n} from '@tanstack/db'\nimport type { ComputedRef, MaybeRefOrGetter } from 'vue'\n\n/** Copy a snapshot's ordered rows; a single-result query's `data` is one row. */\nfunction snapshotRows(data: unknown): Array<any> {\n if (Array.isArray(data)) return [...data]\n return data === undefined ? [] : [data]\n}\n\n/**\n * Return type for useLiveQuery hook\n * @property state - Reactive Map of query results (key → item)\n * @property data - Reactive array of query results in order, or single result for findOne queries\n * @property collection - The underlying query collection instance\n * @property status - Current query status\n * @property isLoading - True while initial query data is loading\n * @property isReady - True when query has received first data and is ready\n * @property isIdle - True when query hasn't started yet\n * @property isError - True when query encountered an error\n * @property isCleanedUp - True when query has been cleaned up\n */\nexport interface UseLiveQueryReturn<TContext extends Context> {\n state: ComputedRef<Map<string | number, GetResult<TContext>>>\n data: ComputedRef<InferResultType<TContext>>\n collection: ComputedRef<Collection<GetResult<TContext>, string | number, {}>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\ntype InferConditionalResultType<TContext extends Context> =\n TContext extends SingleResult\n ? InferResultType<TContext> | []\n : InferResultType<TContext>\n\nexport type ConditionalUseLiveQueryReturn<TContext extends Context> = Omit<\n UseLiveQueryReturn<TContext>,\n `data` | `collection` | `status`\n> & {\n data: ComputedRef<InferConditionalResultType<TContext>>\n collection: ComputedRef<Collection<\n GetResult<TContext>,\n string | number,\n {}\n > | null>\n status: ComputedRef<CollectionStatus | `disabled`>\n}\n\nexport interface UseLiveQueryReturnWithCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<Array<T>>\n collection: ComputedRef<Collection<T, TKey, TUtils>>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\nexport interface UseLiveQueryReturnWithSingleResultCollection<\n T extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n> {\n state: ComputedRef<Map<TKey, T>>\n data: ComputedRef<T | undefined>\n collection: ComputedRef<Collection<T, TKey, TUtils> & SingleResult>\n status: ComputedRef<CollectionStatus>\n isLoading: ComputedRef<boolean>\n isReady: ComputedRef<boolean>\n persistedStatus: ComputedRef<LiveQueryPersistedStatus>\n isPersistedReady: ComputedRef<boolean>\n persistedError: ComputedRef<unknown | undefined>\n isIdle: ComputedRef<boolean>\n isError: ComputedRef<boolean>\n isCleanedUp: ComputedRef<boolean>\n}\n\n/**\n * Create a live query using a query function\n * @param queryFn - Query function that defines what data to fetch\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic query with object syntax\n * const { data, isLoading } = useLiveQuery((q) =>\n * q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.completed, false))\n * .select(({ todos }) => ({ id: todos.id, text: todos.text }))\n * )\n *\n * @example\n * // With reactive dependencies\n * const minPriority = ref(5)\n * const { data, state } = useLiveQuery(\n * (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => gt(todos.priority, minPriority.value)),\n * [minPriority] // Re-run when minPriority changes\n * )\n *\n * @example\n * // Join pattern\n * const { data } = useLiveQuery((q) =>\n * q.from({ issues: issueCollection })\n * .join({ persons: personCollection }, ({ issues, persons }) =>\n * eq(issues.userId, persons.id)\n * )\n * .select(({ issues, persons }) => ({\n * id: issues.id,\n * title: issues.title,\n * userName: persons.name\n * }))\n * )\n *\n * @example\n * // Handle loading and error states in template\n * const { data, isLoading, isError, status } = useLiveQuery((q) =>\n * q.from({ todos: todoCollection })\n * )\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error: {{ status }}</div>\n * // <ul v-else>\n * // <li v-for=\"todo in data\" :key=\"todo.id\">{{ todo.text }}</li>\n * // </ul>\n */\n// Overload 1: Accept query function that always returns QueryBuilder\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n// Overload 1b: Accept query function that can return undefined/null\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (\n q: InitialQueryBuilder,\n ) => QueryBuilder<TContext> | undefined | null,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): ConditionalUseLiveQueryReturn<TContext>\n\n/**\n * Create a live query using configuration object\n * @param config - Configuration object with query and options\n * @param deps - Array of reactive dependencies that trigger query re-execution when changed\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Basic config object usage\n * const { data, status } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection }),\n * gcTime: 60000\n * })\n *\n * @example\n * // With reactive dependencies\n * const filter = ref('active')\n * const { data, isReady } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.status, filter.value))\n * }, [filter])\n *\n * @example\n * // Handle all states uniformly\n * const { data, isLoading, isReady, isError } = useLiveQuery({\n * query: (q) => q.from({ items: itemCollection })\n * })\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Something went wrong</div>\n * // <div v-else-if=\"!isReady\">Preparing...</div>\n * // <div v-else>{{ data.length }} items loaded</div>\n */\n// Overload 2: Accept config object\nexport function useLiveQuery<TContext extends Context>(\n config: LiveQueryCollectionConfig<TContext>,\n deps?: Array<MaybeRefOrGetter<unknown>>,\n): UseLiveQueryReturn<TContext>\n\n/**\n * Subscribe to an existing query collection (can be reactive)\n * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a ref)\n * @returns Reactive object with query data, state, and status information\n * @example\n * // Using pre-created query collection\n * const myLiveQuery = createLiveQueryCollection((q) =>\n * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))\n * )\n * const { data, collection } = useLiveQuery(myLiveQuery)\n *\n * @example\n * // Reactive query collection reference\n * const selectedQuery = ref(todosQuery)\n * const { data, collection } = useLiveQuery(selectedQuery)\n *\n * // Switch queries reactively\n * selectedQuery.value = archiveQuery\n *\n * @example\n * // Access query collection methods directly\n * const { data, collection, isReady } = useLiveQuery(existingQuery)\n *\n * // Use underlying collection for mutations\n * const handleToggle = (id) => {\n * collection.value.update(id, draft => { draft.completed = !draft.completed })\n * }\n *\n * @example\n * // Handle states consistently\n * const { data, isLoading, isError } = useLiveQuery(sharedQuery)\n *\n * // In template:\n * // <div v-if=\"isLoading\">Loading...</div>\n * // <div v-else-if=\"isError\">Error loading data</div>\n * // <div v-else>\n * // <Item v-for=\"item in data\" :key=\"item.id\" v-bind=\"item\" />\n * // </div>\n */\n// Overload 3: Accept pre-created live query collection (can be reactive) - non-single result\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & NonSingleResult\n >,\n): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>\n\n// Overload 4: Accept pre-created live query collection with singleResult: true\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: MaybeRefOrGetter<\n Collection<TResult, TKey, TUtils> & SingleResult\n >,\n): UseLiveQueryReturnWithSingleResultCollection<TResult, TKey, TUtils>\n\n// Implementation\nexport function useLiveQuery(\n configOrQueryOrCollection: any,\n deps: Array<MaybeRefOrGetter<unknown>> = [],\n): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {\n const collection = computed(() => {\n // First check if the original parameter might be a ref/getter\n // by seeing if toValue returns something different than the original\n // NOTE: Don't call toValue on functions - toValue treats functions as getters and calls them!\n let unwrappedParam = configOrQueryOrCollection\n if (typeof configOrQueryOrCollection !== `function`) {\n try {\n const potentiallyUnwrapped = toValue(configOrQueryOrCollection)\n if (potentiallyUnwrapped !== configOrQueryOrCollection) {\n unwrappedParam = potentiallyUnwrapped\n }\n } catch {\n // If toValue fails, use original parameter\n unwrappedParam = configOrQueryOrCollection\n }\n }\n\n // Check if it's already a collection\n const inputIsCollection = isCollection(unwrappedParam)\n\n if (inputIsCollection) {\n // Warn when passing a collection directly with on-demand sync mode\n // In on-demand mode, data is only loaded when queries with predicates request it\n // Passing the collection directly doesn't provide any predicates, so no data loads\n const syncMode = (unwrappedParam as { config?: { syncMode?: string } })\n .config?.syncMode\n if (syncMode === `on-demand`) {\n console.warn(\n `[useLiveQuery] Warning: Passing a collection with syncMode \"on-demand\" directly to useLiveQuery ` +\n `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\\n\\n` +\n `Instead, use a query builder function:\\n` +\n ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\\n\\n` +\n `Or switch to syncMode \"eager\" if you want all data to sync automatically.`,\n )\n }\n // It's already a collection, ensure sync is started for Vue hooks\n // Only start sync if the collection is in idle state\n if (unwrappedParam.status === `idle`) {\n unwrappedParam.startSyncImmediate()\n }\n return unwrappedParam\n }\n\n // Reference deps to make computed reactive to them\n deps.forEach((dep) => toValue(dep))\n\n // Ensure we always start sync for Vue hooks\n if (typeof unwrappedParam === `function`) {\n // A query function returning null or undefined disables the query.\n return resolveLiveQueryValue(\n unwrappedParam(new BaseQueryBuilder() as InitialQueryBuilder),\n )\n } else {\n return createLiveQueryCollection({\n ...unwrappedParam,\n startSync: true,\n })\n }\n })\n\n // Reactive state that gets updated granularly through change events\n const state = reactive(new Map<string | number, any>())\n\n // Reactive data array that maintains sorted order\n const internalData = ref<Array<any>>([])\n\n // Computed wrapper for the data to match expected return type\n // Returns single item for singleResult collections, array otherwise\n const data = computed(() => {\n const currentCollection = collection.value\n if (!currentCollection) {\n return internalData.value\n }\n return isSingleResultCollection(currentCollection)\n ? internalData.value[0]\n : internalData.value\n })\n\n // Track collection status reactively\n const status = ref(\n collection.value ? collection.value.status : (`disabled` as const),\n )\n const persistedStatus = ref<LiveQueryPersistedStatus>(`unavailable`)\n const persistedError = shallowRef<unknown>(undefined)\n\n // The shared observer owns subscription, the ready-race, and status; Vue\n // materializes into its own reactive map (granular) + ordered array.\n let currentObserver: LiveQueryObserver<any, any> | null = null\n\n const syncFromObserver = (observer: LiveQueryObserver<any, any>) => {\n const snapshot = observer.getSnapshot()\n status.value = snapshot.status as CollectionStatus\n persistedStatus.value = snapshot.persistedStatus\n persistedError.value = snapshot.persistedError\n internalData.value = snapshotRows(snapshot.data)\n }\n\n // Watch for collection changes and subscribe to updates\n watchEffect((onInvalidate) => {\n const currentCollection = collection.value\n\n // Tear down any previous observer.\n currentObserver?.dispose()\n currentObserver = null\n\n // Handle null collection (disabled query)\n if (!currentCollection) {\n status.value = `disabled` as const\n persistedStatus.value = `unavailable`\n persistedError.value = undefined\n state.clear()\n internalData.value = []\n return\n }\n\n const observer = createLiveQueryObserver(currentCollection)\n currentObserver = observer\n\n // Initial rows arrive as the observer's first delta (includeInitialState);\n // apply them and every subsequent delta granularly to the reactive map.\n state.clear()\n\n const unsubscribe = observer.subscribe(\n (changes: Array<ChangeMessage<any>> | undefined) => {\n if (changes) {\n for (const change of changes) {\n switch (change.type) {\n case `insert`:\n case `update`:\n state.set(change.key, change.value)\n break\n case `delete`:\n state.delete(change.key)\n break\n }\n }\n } else {\n // Cleanup and other status-only publications carry no row deltas.\n // Rebuild the keyed view so it cannot diverge from ordered data.\n state.clear()\n for (const [key, value] of observer.getSnapshot().state ?? []) {\n state.set(key, value)\n }\n }\n syncFromObserver(observer)\n },\n )\n syncFromObserver(observer)\n\n // Cleanup when effect is invalidated\n onInvalidate(() => {\n unsubscribe()\n observer.dispose()\n currentObserver = null\n })\n })\n\n // Cleanup on unmount (only if we're in a component context)\n const instance = getCurrentInstance()\n if (instance) {\n onUnmounted(() => currentObserver?.dispose())\n }\n\n return {\n state: computed(() => state),\n data,\n collection: computed(() => getPublicCollection(collection.value)),\n status: computed(() => status.value),\n isLoading: computed(() => status.value === `loading`),\n isReady: computed(\n () => status.value === `ready` || status.value === `disabled`,\n ),\n persistedStatus: computed(() => persistedStatus.value),\n isPersistedReady: computed(() => persistedStatus.value === `ready`),\n persistedError: computed(() => persistedError.value),\n isIdle: computed(() => status.value === `idle`),\n isError: computed(() => status.value === `error`),\n isCleanedUp: computed(() => status.value === `cleaned-up`),\n }\n}\n"],"names":[],"mappings":";;AAqCA,SAAS,aAAa,MAA2B;AAC/C,MAAI,MAAM,QAAQ,IAAI,EAAG,QAAO,CAAC,GAAG,IAAI;AACxC,SAAO,SAAS,SAAY,CAAA,IAAK,CAAC,IAAI;AACxC;AAwPO,SAAS,aACd,2BACA,OAAyC,IACkC;AAC3E,QAAM,aAAa,SAAS,MAAM;AAIhC,QAAI,iBAAiB;AACrB,QAAI,OAAO,8BAA8B,YAAY;AACnD,UAAI;AACF,cAAM,uBAAuB,QAAQ,yBAAyB;AAC9D,YAAI,yBAAyB,2BAA2B;AACtD,2BAAiB;AAAA,QACnB;AAAA,MACF,QAAQ;AAEN,yBAAiB;AAAA,MACnB;AAAA,IACF;AAGA,UAAM,oBAAoB,aAAa,cAAc;AAErD,QAAI,mBAAmB;AAIrB,YAAM,WAAY,eACf,QAAQ;AACX,UAAI,aAAa,aAAa;AAC5B,gBAAQ;AAAA,UACN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAAA;AAAA,MAMJ;AAGA,UAAI,eAAe,WAAW,QAAQ;AACpC,uBAAe,mBAAA;AAAA,MACjB;AACA,aAAO;AAAA,IACT;AAGA,SAAK,QAAQ,CAAC,QAAQ,QAAQ,GAAG,CAAC;AAGlC,QAAI,OAAO,mBAAmB,YAAY;AAExC,aAAO;AAAA,QACL,eAAe,IAAI,iBAAA,CAAyC;AAAA,MAAA;AAAA,IAEhE,OAAO;AACL,aAAO,0BAA0B;AAAA,QAC/B,GAAG;AAAA,QACH,WAAW;AAAA,MAAA,CACZ;AAAA,IACH;AAAA,EACF,CAAC;AAGD,QAAM,QAAQ,SAAS,oBAAI,KAA2B;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AAK,KAAK,KAAK,SAAS,YAAA,EAAc,SAAS,IAAI;AAC7D,kBAAM,IAAI,KAAK,KAAK;AAAA,UACtB;AAAA,QACF;AACA,yBAAiB,QAAQ;AAAA,MAC3B;AAAA,IAAA;AAEF,qBAAiB,QAAQ;AAGzB,iBAAa,MAAM;AACjB,kBAAA;AACA,eAAS,QAAA;AACT,wBAAkB;AAAA,IACpB,CAAC;AAAA,EACH,CAAC;AAGD,QAAM,WAAW,mBAAA;AACjB,MAAI,UAAU;AACZ,gBAAY,MAAM,iBAAiB,SAAS;AAAA,EAC9C;AAEA,SAAO;AAAA,IACL,OAAO,SAAS,MAAM,KAAK;AAAA,IAC3B;AAAA,IACA,YAAY,SAAS,MAAM,oBAAoB,WAAW,KAAK,CAAC;AAAA,IAChE,QAAQ,SAAS,MAAM,OAAO,KAAK;AAAA,IACnC,WAAW,SAAS,MAAM,OAAO,UAAU,SAAS;AAAA,IACpD,SAAS;AAAA,MACP,MAAM,OAAO,UAAU,WAAW,OAAO,UAAU;AAAA,IAAA;AAAA,IAErD,iBAAiB,SAAS,MAAM,gBAAgB,KAAK;AAAA,IACrD,kBAAkB,SAAS,MAAM,gBAAgB,UAAU,OAAO;AAAA,IAClE,gBAAgB,SAAS,MAAM,eAAe,KAAK;AAAA,IACnD,QAAQ,SAAS,MAAM,OAAO,UAAU,MAAM;AAAA,IAC9C,SAAS,SAAS,MAAM,OAAO,UAAU,OAAO;AAAA,IAChD,aAAa,SAAS,MAAM,OAAO,UAAU,YAAY;AAAA,EAAA;AAE7D;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/vue-db",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.5",
|
|
4
4
|
"description": "Vue integration for @tanstack/db",
|
|
5
5
|
"author": "Kyle Mathews",
|
|
6
6
|
"license": "MIT",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"skills"
|
|
41
41
|
],
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@tanstack/db": "0.12.
|
|
43
|
+
"@tanstack/db": "0.12.1"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
46
|
"vue": ">=3.3.0"
|
package/src/useLiveQuery.ts
CHANGED
|
@@ -34,6 +34,12 @@ import type {
|
|
|
34
34
|
} from '@tanstack/db'
|
|
35
35
|
import type { ComputedRef, MaybeRefOrGetter } from 'vue'
|
|
36
36
|
|
|
37
|
+
/** Copy a snapshot's ordered rows; a single-result query's `data` is one row. */
|
|
38
|
+
function snapshotRows(data: unknown): Array<any> {
|
|
39
|
+
if (Array.isArray(data)) return [...data]
|
|
40
|
+
return data === undefined ? [] : [data]
|
|
41
|
+
}
|
|
42
|
+
|
|
37
43
|
/**
|
|
38
44
|
* Return type for useLiveQuery hook
|
|
39
45
|
* @property state - Reactive Map of query results (key → item)
|
|
@@ -378,7 +384,7 @@ export function useLiveQuery(
|
|
|
378
384
|
status.value = snapshot.status as CollectionStatus
|
|
379
385
|
persistedStatus.value = snapshot.persistedStatus
|
|
380
386
|
persistedError.value = snapshot.persistedError
|
|
381
|
-
internalData.value =
|
|
387
|
+
internalData.value = snapshotRows(snapshot.data)
|
|
382
388
|
}
|
|
383
389
|
|
|
384
390
|
// Watch for collection changes and subscribe to updates
|