@molecule/app-query-svelte 0.0.0-stage → 1.1.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/LICENSE +202 -0
- package/README.md +636 -2
- package/dist/QueryContent.svelte +53 -0
- package/dist/QueryContent.svelte.d.ts +26 -0
- package/dist/QueryContent.svelte.d.ts.map +1 -0
- package/dist/components.d.ts +8 -0
- package/dist/components.d.ts.map +1 -0
- package/dist/components.js +7 -0
- package/dist/index.d.ts +300 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +299 -0
- package/dist/resource.d.ts +11 -0
- package/dist/resource.d.ts.map +1 -0
- package/dist/resource.js +9 -0
- package/dist/types.d.ts +63 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/dist/usePrefetch.d.ts +40 -0
- package/dist/usePrefetch.d.ts.map +1 -0
- package/dist/usePrefetch.js +44 -0
- package/dist/useQuery.d.ts +72 -0
- package/dist/useQuery.d.ts.map +1 -0
- package/dist/useQuery.js +298 -0
- package/package.json +75 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,YAAY,EACV,aAAa,EACb,mBAAmB,EACnB,YAAY,EACZ,gBAAgB,GACjB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAA"}
|
package/dist/resource.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One API resource on the shared query cache. `createQueryResource` is
|
|
3
|
+
* framework-neutral, so it lives in `@molecule/app-query` (with its full
|
|
4
|
+
* documentation); this package re-exports it so Svelte pages import it next to
|
|
5
|
+
* `useQuery` and `QueryContent`.
|
|
6
|
+
*
|
|
7
|
+
* @module
|
|
8
|
+
*/
|
|
9
|
+
export { createQueryResource } from '@molecule/app-query';
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Svelte query observer contracts: the same names and shapes as
|
|
3
|
+
* `@molecule/app-query-react`'s, with Svelte's own node and reactivity types.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import type { Snippet } from 'svelte';
|
|
8
|
+
import type { Readable } from 'svelte/store';
|
|
9
|
+
import type { QueryState } from '@molecule/app-query';
|
|
10
|
+
/**
|
|
11
|
+
* A mounted query's state and its explicit cache and refresh actions. The
|
|
12
|
+
* Svelte hook hands this out as a readable store of these objects (one per
|
|
13
|
+
* change), so a component reads `data` and `status` with `$result.data`.
|
|
14
|
+
*/
|
|
15
|
+
export interface UseQueryResult<T> extends QueryState<T> {
|
|
16
|
+
/**
|
|
17
|
+
* Publish a saved document to this key and all its observers. Render `data`
|
|
18
|
+
* directly instead of copying it to local state: later cache updates then
|
|
19
|
+
* remain visible. A function receives this key's current cached document,
|
|
20
|
+
* never retained previous-page data. Returning `undefined` leaves the cache
|
|
21
|
+
* unchanged. A disabled (`null`) query does nothing, including not calling an
|
|
22
|
+
* updater. Like React state setters, wrap a function-valued document in an
|
|
23
|
+
* updater. A saved callback stays bound to its original key. The write
|
|
24
|
+
* supersedes older in-flight reads, using the bonded client's `set` contract.
|
|
25
|
+
*/
|
|
26
|
+
setData: (value: T | ((previous: T | undefined) => T | undefined)) => void;
|
|
27
|
+
/**
|
|
28
|
+
* Fetch this key again, even when its cached document is fresh. Observers
|
|
29
|
+
* receive the updated state. Resolves with that state, including an error
|
|
30
|
+
* when the request fails; a disabled (`null`) query resolves idle without a
|
|
31
|
+
* request.
|
|
32
|
+
*/
|
|
33
|
+
refetch: () => Promise<QueryState<T>>;
|
|
34
|
+
}
|
|
35
|
+
/** A loaded document owns its controls; absent documents expose only status content. */
|
|
36
|
+
export interface QueryContentProps<T> {
|
|
37
|
+
/**
|
|
38
|
+
* State from `useQuery` — as the readable store the hook returns, or as a
|
|
39
|
+
* compatible observer's plain state object. Both follow the query.
|
|
40
|
+
*/
|
|
41
|
+
query: Readable<Pick<QueryState<T>, 'data' | 'status' | 'error'>> | Pick<QueryState<T>, 'data' | 'status' | 'error'>;
|
|
42
|
+
/** Mounted only with a real document, including false, zero and an empty list. */
|
|
43
|
+
children: Snippet<[NonNullable<T>]>;
|
|
44
|
+
/** Initial idle/loading content. Render a status snippet, never a fake item or action. */
|
|
45
|
+
pending?: Snippet | null;
|
|
46
|
+
/** Content for a loaded null record. Null is distinct from an unfinished request. */
|
|
47
|
+
missing?: Snippet | null;
|
|
48
|
+
/** A failed initial read. Cached data stays visible if its refresh fails. */
|
|
49
|
+
error?: Snippet<[unknown]> | null;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The handlers {@link intentPrefetchProps} returns, in Svelte 5's listener
|
|
53
|
+
* naming (lowercase DOM event attributes, spreadable onto an `<a>`).
|
|
54
|
+
*/
|
|
55
|
+
export interface IntentPrefetchProps {
|
|
56
|
+
/** Warms the document when the pointer arrives. */
|
|
57
|
+
onpointerenter: () => void;
|
|
58
|
+
/** Warms the document on keyboard focus. */
|
|
59
|
+
onfocus: () => void;
|
|
60
|
+
/** Warms the document when a touch starts. */
|
|
61
|
+
ontouchstart: () => void;
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAA;AACrC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAE5C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAErD;;;;GAIG;AACH,MAAM,WAAW,cAAc,CAAC,CAAC,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAC;IACtD;;;;;;;;;OASG;IACH,OAAO,EAAE,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC,GAAG,SAAS,KAAK,CAAC,GAAG,SAAS,CAAC,KAAK,IAAI,CAAA;IAC1E;;;;;OAKG;IACH,OAAO,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA;CACtC;AAED,wFAAwF;AACxF,MAAM,WAAW,iBAAiB,CAAC,CAAC;IAClC;;;OAGG;IACH,KAAK,EACD,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,CAAC,CAAC,GAC1D,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,CAAC,CAAA;IACpD,kFAAkF;IAClF,QAAQ,EAAE,OAAO,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACnC,0FAA0F;IAC1F,OAAO,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;IACxB,qFAAqF;IACrF,OAAO,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;IACxB,6EAA6E;IAC7E,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAA;CAClC;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAClC,mDAAmD;IACnD,cAAc,EAAE,MAAM,IAAI,CAAA;IAC1B,4CAA4C;IAC5C,OAAO,EAAE,MAAM,IAAI,CAAA;IACnB,8CAA8C;IAC9C,YAAY,EAAE,MAAM,IAAI,CAAA;CACzB"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Warm the cache ahead of a navigation, in Svelte: `prefetchQuery` itself is
|
|
3
|
+
* framework-neutral and lives in `@molecule/app-query`; this module re-exports
|
|
4
|
+
* it and adds the Svelte hook and the link handlers.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import type { QueryOptions } from '@molecule/app-query';
|
|
9
|
+
export { prefetchQuery } from '@molecule/app-query';
|
|
10
|
+
import type { IntentPrefetchProps } from './types.js';
|
|
11
|
+
/**
|
|
12
|
+
* A stable `prefetch(options)` function for event handlers. One identity for
|
|
13
|
+
* the component's life (React's `useCallback` with no dependencies).
|
|
14
|
+
*
|
|
15
|
+
* @returns The prefetch function.
|
|
16
|
+
* @example
|
|
17
|
+
* ```svelte
|
|
18
|
+
* <script lang="ts">
|
|
19
|
+
* import { usePrefetch } from '@molecule/app-query-svelte'
|
|
20
|
+
*
|
|
21
|
+
* const prefetch = usePrefetch()
|
|
22
|
+
* </script>
|
|
23
|
+
*
|
|
24
|
+
* <button onclick={() => prefetch(packageQuery('api-auth'))}>Show packages</button>
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function usePrefetch(): <T>(options: QueryOptions<T>) => void;
|
|
28
|
+
/**
|
|
29
|
+
* Event handlers that warm a document at the first sign of intent: the
|
|
30
|
+
* pointer arriving, keyboard focus, or a touch starting. Spread them onto a
|
|
31
|
+
* link — the names are Svelte 5's lowercase DOM event attributes:
|
|
32
|
+
* `<a href={to} {...intentPrefetchProps(packageQuery(name))}>{name}</a>`. It
|
|
33
|
+
* is a plain function (not a hook), so it works inside `{#each}` too.
|
|
34
|
+
*
|
|
35
|
+
* @template T - The document type.
|
|
36
|
+
* @param options - Key, fetch, freshness.
|
|
37
|
+
* @returns The handlers.
|
|
38
|
+
*/
|
|
39
|
+
export declare function intentPrefetchProps<T>(options: QueryOptions<T>): IntentPrefetchProps;
|
|
40
|
+
//# sourceMappingURL=usePrefetch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usePrefetch.d.ts","sourceRoot":"","sources":["../src/usePrefetch.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAGvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAEnD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAErD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,CAGnE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAGpF"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Warm the cache ahead of a navigation, in Svelte: `prefetchQuery` itself is
|
|
3
|
+
* framework-neutral and lives in `@molecule/app-query`; this module re-exports
|
|
4
|
+
* it and adds the Svelte hook and the link handlers.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import { prefetchQuery } from '@molecule/app-query';
|
|
9
|
+
export { prefetchQuery } from '@molecule/app-query';
|
|
10
|
+
/**
|
|
11
|
+
* A stable `prefetch(options)` function for event handlers. One identity for
|
|
12
|
+
* the component's life (React's `useCallback` with no dependencies).
|
|
13
|
+
*
|
|
14
|
+
* @returns The prefetch function.
|
|
15
|
+
* @example
|
|
16
|
+
* ```svelte
|
|
17
|
+
* <script lang="ts">
|
|
18
|
+
* import { usePrefetch } from '@molecule/app-query-svelte'
|
|
19
|
+
*
|
|
20
|
+
* const prefetch = usePrefetch()
|
|
21
|
+
* </script>
|
|
22
|
+
*
|
|
23
|
+
* <button onclick={() => prefetch(packageQuery('api-auth'))}>Show packages</button>
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export function usePrefetch() {
|
|
27
|
+
const prefetch = (options) => prefetchQuery(options);
|
|
28
|
+
return prefetch;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Event handlers that warm a document at the first sign of intent: the
|
|
32
|
+
* pointer arriving, keyboard focus, or a touch starting. Spread them onto a
|
|
33
|
+
* link — the names are Svelte 5's lowercase DOM event attributes:
|
|
34
|
+
* `<a href={to} {...intentPrefetchProps(packageQuery(name))}>{name}</a>`. It
|
|
35
|
+
* is a plain function (not a hook), so it works inside `{#each}` too.
|
|
36
|
+
*
|
|
37
|
+
* @template T - The document type.
|
|
38
|
+
* @param options - Key, fetch, freshness.
|
|
39
|
+
* @returns The handlers.
|
|
40
|
+
*/
|
|
41
|
+
export function intentPrefetchProps(options) {
|
|
42
|
+
const go = () => prefetchQuery(options);
|
|
43
|
+
return { onpointerenter: go, onfocus: go, ontouchstart: go };
|
|
44
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Observe one document from the app's shared query cache as a readable store:
|
|
3
|
+
* the Svelte counterpart of `@molecule/app-query-react`'s `useQuery`, with the
|
|
4
|
+
* same options, the same retained-previous-document contract and the same
|
|
5
|
+
* cache behavior. The cache, keys and fetch logic all live in
|
|
6
|
+
* `@molecule/app-query`; this module binds them to Svelte's stores exactly as
|
|
7
|
+
* the React package binds them with `useState`/`useEffect`.
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
import { type Readable } from 'svelte/store';
|
|
12
|
+
import type { QueryOptions } from '@molecule/app-query';
|
|
13
|
+
import type { UseQueryResult } from './types.js';
|
|
14
|
+
/**
|
|
15
|
+
* The document for `options.key`, kept current: cached data is delivered on
|
|
16
|
+
* the very first read (so a warmed page never flashes a loading state), a
|
|
17
|
+
* stale or missing document is fetched, and every change updates the returned
|
|
18
|
+
* store. Pass `null` to observe nothing. A key change resets to that key's
|
|
19
|
+
* state; the hook never hands a caller another key's document — unless the
|
|
20
|
+
* caller opts into {@link QueryOptions.keepPreviousData}, and then only within
|
|
21
|
+
* one {@link QueryOptions.principal}.
|
|
22
|
+
*
|
|
23
|
+
* The request is stable across updates — an unrelated store or component
|
|
24
|
+
* change neither restarts it nor cancels it, so a response that arrives after
|
|
25
|
+
* one still lands. It is aborted only when the key changes or the component is
|
|
26
|
+
* destroyed (the `signal` given to `options.fetch`). Pass the options as a
|
|
27
|
+
* readable store and a changed key re-observes on the same component, the way
|
|
28
|
+
* React re-renders `useQuery` with new options.
|
|
29
|
+
*
|
|
30
|
+
* For a LIST, put the route's page, filter and selected view in the key and
|
|
31
|
+
* pass `keepPreviousData` with a `principal`: a page or filter change then
|
|
32
|
+
* keeps the rows already on screen until the new page answers, instead of
|
|
33
|
+
* rendering a loading state over an empty list. The key names everything the
|
|
34
|
+
* answer depends on, so a list the server can filter or personalize per viewer
|
|
35
|
+
* puts the viewer in its key and passes the same value as `principal`
|
|
36
|
+
* (`'anonymous'` when signed out): an account switch then drops the previous
|
|
37
|
+
* account's document immediately.
|
|
38
|
+
*
|
|
39
|
+
* For custom mutation handlers, `setData(saved)` publishes the server's
|
|
40
|
+
* response to this key and every observer. Use `setData(current => next)` for
|
|
41
|
+
* a local cache update. Render `data` directly; a component-local copy stops
|
|
42
|
+
* observing later server responses.
|
|
43
|
+
*
|
|
44
|
+
* @template T - The document type.
|
|
45
|
+
* @param options - Key, fetch, freshness, and optionally `principal` with
|
|
46
|
+
* `keepPreviousData`; or `null`; or a readable store of either, so changed
|
|
47
|
+
* options are followed without remounting.
|
|
48
|
+
* @returns A readable store of the document's state with `setData()` and
|
|
49
|
+
* `refetch()`. `isPreviousData` is `true` while `data` is the previous key's
|
|
50
|
+
* document for the same principal.
|
|
51
|
+
* @throws {Error} When `keepPreviousData` is set without `principal` — the
|
|
52
|
+
* hook cannot tell a route change from a principal switch, so it refuses
|
|
53
|
+
* rather than risk showing one principal's document to another.
|
|
54
|
+
* @example
|
|
55
|
+
* ```svelte
|
|
56
|
+
* <script lang="ts">
|
|
57
|
+
* import { useQuery } from '@molecule/app-query-svelte'
|
|
58
|
+
*
|
|
59
|
+
* const query = useQuery({
|
|
60
|
+
* key: ['package', 'api-auth'],
|
|
61
|
+
* fetch: async (signal: AbortSignal) =>
|
|
62
|
+
* (await getClient().get(`/data/packages/api-auth.json`, { signal })).data,
|
|
63
|
+
* })
|
|
64
|
+
* </script>
|
|
65
|
+
*
|
|
66
|
+
* {#if $query.status === 'success'}
|
|
67
|
+
* <h1>{$query.data?.name}</h1>
|
|
68
|
+
* {/if}
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export declare function useQuery<T>(options: QueryOptions<T> | null | Readable<QueryOptions<T> | null>): Readable<UseQueryResult<T>>;
|
|
72
|
+
//# sourceMappingURL=useQuery.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,EAAO,KAAK,QAAQ,EAA2B,MAAM,cAAc,CAAA;AAE1E,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,qBAAqB,CAAA;AAGnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAmDhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EACxB,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GACjE,QAAQ,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAiN7B"}
|
package/dist/useQuery.js
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Observe one document from the app's shared query cache as a readable store:
|
|
3
|
+
* the Svelte counterpart of `@molecule/app-query-react`'s `useQuery`, with the
|
|
4
|
+
* same options, the same retained-previous-document contract and the same
|
|
5
|
+
* cache behavior. The cache, keys and fetch logic all live in
|
|
6
|
+
* `@molecule/app-query`; this module binds them to Svelte's stores exactly as
|
|
7
|
+
* the React package binds them with `useState`/`useEffect`.
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
import { onDestroy } from 'svelte';
|
|
12
|
+
import { get, writable } from 'svelte/store';
|
|
13
|
+
import { getQueryClient, hashQueryKey } from '@molecule/app-query';
|
|
14
|
+
/** The refusal when `keepPreviousData` arrives without a principal (React's message). */
|
|
15
|
+
const PRINCIPAL_REQUIRED = 'useQuery: keepPreviousData requires principal — the viewer the document is for (the signed-in id, "anonymous" while signed out, or "public" for an endpoint that answers every viewer the same) so a viewer switch never shows the previous document.';
|
|
16
|
+
/**
|
|
17
|
+
* Whether a value is a readable store (the read half of the Svelte store
|
|
18
|
+
* contract). A hook's options may arrive as one, so a changed options object
|
|
19
|
+
* reaches the same mount the way a React re-render does.
|
|
20
|
+
*
|
|
21
|
+
* @param value - The options, or a store of them.
|
|
22
|
+
* @returns True for a store.
|
|
23
|
+
*/
|
|
24
|
+
function isStore(value) {
|
|
25
|
+
return (typeof value === 'object' &&
|
|
26
|
+
value !== null &&
|
|
27
|
+
typeof value.subscribe === 'function');
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The state of a disabled (`null`) query: nothing observed, nothing fetched.
|
|
31
|
+
*
|
|
32
|
+
* @template T - The document type the result is shaped as.
|
|
33
|
+
* @returns A fresh idle state.
|
|
34
|
+
*/
|
|
35
|
+
function idle() {
|
|
36
|
+
return {
|
|
37
|
+
data: undefined,
|
|
38
|
+
status: 'idle',
|
|
39
|
+
error: undefined,
|
|
40
|
+
isFetching: false,
|
|
41
|
+
updatedAt: undefined,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The document for `options.key`, kept current: cached data is delivered on
|
|
46
|
+
* the very first read (so a warmed page never flashes a loading state), a
|
|
47
|
+
* stale or missing document is fetched, and every change updates the returned
|
|
48
|
+
* store. Pass `null` to observe nothing. A key change resets to that key's
|
|
49
|
+
* state; the hook never hands a caller another key's document — unless the
|
|
50
|
+
* caller opts into {@link QueryOptions.keepPreviousData}, and then only within
|
|
51
|
+
* one {@link QueryOptions.principal}.
|
|
52
|
+
*
|
|
53
|
+
* The request is stable across updates — an unrelated store or component
|
|
54
|
+
* change neither restarts it nor cancels it, so a response that arrives after
|
|
55
|
+
* one still lands. It is aborted only when the key changes or the component is
|
|
56
|
+
* destroyed (the `signal` given to `options.fetch`). Pass the options as a
|
|
57
|
+
* readable store and a changed key re-observes on the same component, the way
|
|
58
|
+
* React re-renders `useQuery` with new options.
|
|
59
|
+
*
|
|
60
|
+
* For a LIST, put the route's page, filter and selected view in the key and
|
|
61
|
+
* pass `keepPreviousData` with a `principal`: a page or filter change then
|
|
62
|
+
* keeps the rows already on screen until the new page answers, instead of
|
|
63
|
+
* rendering a loading state over an empty list. The key names everything the
|
|
64
|
+
* answer depends on, so a list the server can filter or personalize per viewer
|
|
65
|
+
* puts the viewer in its key and passes the same value as `principal`
|
|
66
|
+
* (`'anonymous'` when signed out): an account switch then drops the previous
|
|
67
|
+
* account's document immediately.
|
|
68
|
+
*
|
|
69
|
+
* For custom mutation handlers, `setData(saved)` publishes the server's
|
|
70
|
+
* response to this key and every observer. Use `setData(current => next)` for
|
|
71
|
+
* a local cache update. Render `data` directly; a component-local copy stops
|
|
72
|
+
* observing later server responses.
|
|
73
|
+
*
|
|
74
|
+
* @template T - The document type.
|
|
75
|
+
* @param options - Key, fetch, freshness, and optionally `principal` with
|
|
76
|
+
* `keepPreviousData`; or `null`; or a readable store of either, so changed
|
|
77
|
+
* options are followed without remounting.
|
|
78
|
+
* @returns A readable store of the document's state with `setData()` and
|
|
79
|
+
* `refetch()`. `isPreviousData` is `true` while `data` is the previous key's
|
|
80
|
+
* document for the same principal.
|
|
81
|
+
* @throws {Error} When `keepPreviousData` is set without `principal` — the
|
|
82
|
+
* hook cannot tell a route change from a principal switch, so it refuses
|
|
83
|
+
* rather than risk showing one principal's document to another.
|
|
84
|
+
* @example
|
|
85
|
+
* ```svelte
|
|
86
|
+
* <script lang="ts">
|
|
87
|
+
* import { useQuery } from '@molecule/app-query-svelte'
|
|
88
|
+
*
|
|
89
|
+
* const query = useQuery({
|
|
90
|
+
* key: ['package', 'api-auth'],
|
|
91
|
+
* fetch: async (signal: AbortSignal) =>
|
|
92
|
+
* (await getClient().get(`/data/packages/api-auth.json`, { signal })).data,
|
|
93
|
+
* })
|
|
94
|
+
* </script>
|
|
95
|
+
*
|
|
96
|
+
* {#if $query.status === 'success'}
|
|
97
|
+
* <h1>{$query.data?.name}</h1>
|
|
98
|
+
* {/if}
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
export function useQuery(options) {
|
|
102
|
+
// The store form is how an app (and the conformance kit) passes options that
|
|
103
|
+
// change on a live component: a new key re-observes here, on the same mount.
|
|
104
|
+
const source = isStore(options) ? options : null;
|
|
105
|
+
/** The options' current value. */
|
|
106
|
+
const readOptions = () =>
|
|
107
|
+
// `source` below is exactly the store half of the union, so the other half is the plain form.
|
|
108
|
+
source ? get(source) : options;
|
|
109
|
+
// Refuse before anything is observed: nothing is subscribed, nothing fetches.
|
|
110
|
+
const first = readOptions();
|
|
111
|
+
if (first?.keepPreviousData === true && first.principal === undefined) {
|
|
112
|
+
throw new Error(PRINCIPAL_REQUIRED);
|
|
113
|
+
}
|
|
114
|
+
// The first options object seen for each key (React's useMemo(…, [hash])): a
|
|
115
|
+
// fresh `fetch` closure for the same key never resubscribes.
|
|
116
|
+
let stable = first;
|
|
117
|
+
let hash = stable ? hashQueryKey(stable.key) : '';
|
|
118
|
+
// The viewer and the retention flag are read from the CURRENT options on
|
|
119
|
+
// every change, the way React reads them on every render.
|
|
120
|
+
let principal = first?.principal;
|
|
121
|
+
let keepPreviousData = first?.keepPreviousData === true;
|
|
122
|
+
// The last state a subscription delivered, and the hash it belongs to.
|
|
123
|
+
let state = {
|
|
124
|
+
hash,
|
|
125
|
+
value: stable ? getQueryClient().getState(stable.key) : idle(),
|
|
126
|
+
};
|
|
127
|
+
// The previous document is remembered across changes, so the update that
|
|
128
|
+
// first observes a new key still has the rows a person is looking at.
|
|
129
|
+
let loaded = null;
|
|
130
|
+
// A key's document belongs to the principal that was current when the hook
|
|
131
|
+
// started observing that key: a principal change the key does not reflect
|
|
132
|
+
// never relabels the document on screen as the new principal's.
|
|
133
|
+
let observed = null;
|
|
134
|
+
/**
|
|
135
|
+
* React's render-time value: the observed key's state, or — while the new key
|
|
136
|
+
* has no answer of its own — the retained previous document for the same
|
|
137
|
+
* principal, stamped `isPreviousData`.
|
|
138
|
+
*
|
|
139
|
+
* @returns The state to expose.
|
|
140
|
+
*/
|
|
141
|
+
const compute = () => {
|
|
142
|
+
const current = state.hash === hash
|
|
143
|
+
? state.value
|
|
144
|
+
: stable
|
|
145
|
+
? getQueryClient().getState(stable.key)
|
|
146
|
+
: idle();
|
|
147
|
+
const previous = keepPreviousData ? loaded : null;
|
|
148
|
+
return previous !== null &&
|
|
149
|
+
previous.principal === principal &&
|
|
150
|
+
previous.hash !== hash &&
|
|
151
|
+
current.data === undefined &&
|
|
152
|
+
(current.status === 'idle' || current.status === 'loading')
|
|
153
|
+
? {
|
|
154
|
+
...current,
|
|
155
|
+
data: previous.value.data,
|
|
156
|
+
updatedAt: previous.value.updatedAt,
|
|
157
|
+
isPreviousData: true,
|
|
158
|
+
}
|
|
159
|
+
: current;
|
|
160
|
+
};
|
|
161
|
+
/**
|
|
162
|
+
* React's memory effect: what the document on screen is remembered as, so a
|
|
163
|
+
* retained previous document survives its fetch. A document is remembered
|
|
164
|
+
* only as its own principal's answer; anything else (no principal, a switch,
|
|
165
|
+
* a failure, a key observed under another principal) clears it.
|
|
166
|
+
*
|
|
167
|
+
* @param value - The state just computed.
|
|
168
|
+
*/
|
|
169
|
+
const remember = (value) => {
|
|
170
|
+
if (observed?.hash !== hash)
|
|
171
|
+
observed = { hash, principal };
|
|
172
|
+
if (value.isPreviousData === true)
|
|
173
|
+
return;
|
|
174
|
+
loaded =
|
|
175
|
+
principal !== undefined &&
|
|
176
|
+
observed.principal === principal &&
|
|
177
|
+
value.data !== undefined &&
|
|
178
|
+
value.status === 'success'
|
|
179
|
+
? { hash, principal, value }
|
|
180
|
+
: null;
|
|
181
|
+
};
|
|
182
|
+
/**
|
|
183
|
+
* The cache and refresh actions, bound to the key they were created for
|
|
184
|
+
* (React's `useCallback(…, [stable])`): a key change rebinds them, and a
|
|
185
|
+
* fresh options object with the same key keeps the originals.
|
|
186
|
+
*/
|
|
187
|
+
let setData = () => { };
|
|
188
|
+
let refetch = async () => idle();
|
|
189
|
+
/** Rebinds the actions to the current `stable` options. */
|
|
190
|
+
const bind = () => {
|
|
191
|
+
const bound = stable;
|
|
192
|
+
setData = (value) => {
|
|
193
|
+
if (!bound)
|
|
194
|
+
return;
|
|
195
|
+
const client = getQueryClient();
|
|
196
|
+
const next = typeof value === 'function'
|
|
197
|
+
? value(client.get(bound.key))
|
|
198
|
+
: value;
|
|
199
|
+
if (next !== undefined)
|
|
200
|
+
client.set(bound.key, next);
|
|
201
|
+
};
|
|
202
|
+
refetch = async () => {
|
|
203
|
+
if (!bound)
|
|
204
|
+
return idle();
|
|
205
|
+
const client = getQueryClient();
|
|
206
|
+
client.invalidate(bound.key);
|
|
207
|
+
try {
|
|
208
|
+
await client.fetch(bound);
|
|
209
|
+
}
|
|
210
|
+
catch (_error) {
|
|
211
|
+
// The cache publishes the failure to every observer. Return that state
|
|
212
|
+
// just as the initial subscription does, so an event handler can safely
|
|
213
|
+
// use `void query.refetch()`.
|
|
214
|
+
}
|
|
215
|
+
return client.getState(bound.key);
|
|
216
|
+
};
|
|
217
|
+
};
|
|
218
|
+
/** Ends the current client subscription (the observed key's). */
|
|
219
|
+
let unsubscribe = null;
|
|
220
|
+
/**
|
|
221
|
+
* React's subscription effect: one client observer per key, rebuilt on a key
|
|
222
|
+
* change (which aborts the abandoned fetch) and closed when the component is
|
|
223
|
+
* destroyed. The client is read at call time, so a provider replaced at
|
|
224
|
+
* runtime answers the next key.
|
|
225
|
+
*/
|
|
226
|
+
const observe = () => {
|
|
227
|
+
unsubscribe?.();
|
|
228
|
+
if (!stable) {
|
|
229
|
+
unsubscribe = null;
|
|
230
|
+
state = { hash: '', value: idle() };
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const bound = stable;
|
|
234
|
+
const boundHash = hash;
|
|
235
|
+
unsubscribe = getQueryClient().subscribe(bound, (value) => {
|
|
236
|
+
state = { hash: boundHash, value };
|
|
237
|
+
push();
|
|
238
|
+
});
|
|
239
|
+
};
|
|
240
|
+
/**
|
|
241
|
+
* Applies changed options: the viewer and retention flag are read fresh, and
|
|
242
|
+
* only a changed KEY resubscribes (React's `useMemo` keeps the first options
|
|
243
|
+
* object per key).
|
|
244
|
+
*
|
|
245
|
+
* @param next - The options the store delivered.
|
|
246
|
+
*/
|
|
247
|
+
const applyOptions = (next) => {
|
|
248
|
+
if (next?.keepPreviousData === true && next.principal === undefined) {
|
|
249
|
+
// React throws while rendering the changed options: refuse rather than
|
|
250
|
+
// risk showing one principal's document to another.
|
|
251
|
+
throw new Error(PRINCIPAL_REQUIRED);
|
|
252
|
+
}
|
|
253
|
+
principal = next?.principal;
|
|
254
|
+
keepPreviousData = next?.keepPreviousData === true;
|
|
255
|
+
const nextHash = next ? hashQueryKey(next.key) : '';
|
|
256
|
+
if (nextHash === hash) {
|
|
257
|
+
push();
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
hash = nextHash;
|
|
261
|
+
stable = next;
|
|
262
|
+
bind();
|
|
263
|
+
observe();
|
|
264
|
+
push();
|
|
265
|
+
};
|
|
266
|
+
/** The store, null until the initial value below creates it. */
|
|
267
|
+
let store = null;
|
|
268
|
+
/**
|
|
269
|
+
* Recomputes the exposed value and publishes it. Before the store exists the
|
|
270
|
+
* recomputation only maintains the memory: the client's synchronous first
|
|
271
|
+
* notification is part of computing the initial value.
|
|
272
|
+
*/
|
|
273
|
+
const push = () => {
|
|
274
|
+
const value = compute();
|
|
275
|
+
remember(value);
|
|
276
|
+
store?.set({ ...value, setData, refetch });
|
|
277
|
+
};
|
|
278
|
+
bind();
|
|
279
|
+
// React's subscription effect runs after the first render; the client's
|
|
280
|
+
// synchronous notification lands while the initial value is computed.
|
|
281
|
+
observe();
|
|
282
|
+
const initial = compute();
|
|
283
|
+
remember(initial);
|
|
284
|
+
store = writable({ ...initial, setData, refetch });
|
|
285
|
+
if (source) {
|
|
286
|
+
const stopOptions = source.subscribe((next) => applyOptions(next));
|
|
287
|
+
onDestroy(() => {
|
|
288
|
+
stopOptions();
|
|
289
|
+
unsubscribe?.();
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
onDestroy(() => {
|
|
294
|
+
unsubscribe?.();
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
return store;
|
|
298
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,77 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@molecule/app-query-svelte",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Svelte hooks for @molecule/app-query — read a cached document synchronously, observe it, and prefetch on intent",
|
|
5
|
+
"homepage": "https://www.molecule.dev/packages/app-query-svelte",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"svelte": "./dist/index.js",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"svelte": "./dist/index.js",
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"!dist/**/__tests__",
|
|
21
|
+
"!dist/**/*.test.*",
|
|
22
|
+
"!dist/**/*.spec.*",
|
|
23
|
+
"README.md"
|
|
24
|
+
],
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings && svelte-package --input src --output dist --tsconfig ./tsconfig.json",
|
|
27
|
+
"dev": "svelte-package --input src --output dist --tsconfig ./tsconfig.json --watch",
|
|
28
|
+
"test": "vitest run",
|
|
29
|
+
"test:watch": "vitest"
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"molecule",
|
|
33
|
+
"query",
|
|
34
|
+
"cache",
|
|
35
|
+
"prefetch",
|
|
36
|
+
"svelte",
|
|
37
|
+
"hooks"
|
|
38
|
+
],
|
|
39
|
+
"author": "Molecule Dev, Inc. (https://molecule.dev)",
|
|
40
|
+
"license": "Apache-2.0",
|
|
41
|
+
"repository": {
|
|
42
|
+
"type": "git",
|
|
43
|
+
"url": "https://github.com/molecule-dev/molecule.git",
|
|
44
|
+
"directory": "packages/app/features/query-svelte"
|
|
45
|
+
},
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=20"
|
|
48
|
+
},
|
|
49
|
+
"bugs": "https://github.com/molecule-dev/molecule/issues",
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
},
|
|
53
|
+
"peerDependencies": {
|
|
54
|
+
"@molecule/app-query": "^1.2.0",
|
|
55
|
+
"svelte": "^5.0.0"
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"@molecule/app-framework-conformance": "0.0.0",
|
|
59
|
+
"@molecule/app-i18n": "1.2.1",
|
|
60
|
+
"@molecule/app-icons": "1.0.4",
|
|
61
|
+
"@molecule/app-query": "1.2.0",
|
|
62
|
+
"@molecule/app-query-memory": "1.0.5",
|
|
63
|
+
"@molecule/app-query-tanstack": "1.0.5",
|
|
64
|
+
"@molecule/app-svelte": "3.6.0",
|
|
65
|
+
"@molecule/app-ui": "1.3.11",
|
|
66
|
+
"@molecule/app-ui-svelte": "1.1.3",
|
|
67
|
+
"@sveltejs/package": "3.0.2",
|
|
68
|
+
"@sveltejs/vite-plugin-svelte": "7.1.2",
|
|
69
|
+
"@types/node": "26.6.5",
|
|
70
|
+
"jsdom": "30.1.3",
|
|
71
|
+
"svelte": "5.57.2",
|
|
72
|
+
"svelte-check": "4.7.7",
|
|
73
|
+
"typescript": "6.0.3",
|
|
74
|
+
"vite": "8.3.5",
|
|
75
|
+
"vitest": "4.1.12"
|
|
76
|
+
}
|
|
77
|
+
}
|