@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/README.md CHANGED
@@ -1,3 +1,637 @@
1
- # Temporary Holding Version
1
+ <!--
2
+ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
+ Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
+ Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
+ To change this document, edit the module-level JSDoc in src/index.ts.
6
+ Generated: 2026-11-14T15:30:33.015Z
7
+ -->
2
8
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
9
+ # @molecule/app-query-svelte
10
+
11
+ Svelte hooks for `@molecule/app-query` — the Svelte counterpart of
12
+ `@molecule/app-query-react`, with the same props and the same DOM: read a
13
+ cached document synchronously, observe it, and prefetch on intent.
14
+
15
+ **Load page data with {@link useQuery}, not `fetch` inside an effect.** A hand-written
16
+ load effect that cancels its request on cleanup re-runs that cleanup whenever one of its
17
+ dependencies is a function created inline each render, and then discards the response whenever
18
+ it arrives after one — always on a remote server, never on localhost, which is why the page
19
+ passes locally and fails on the live URL. `useQuery` subscribes once per key, keeps its request
20
+ stable across updates, and aborts it only when the key changes or the component is destroyed.
21
+
22
+ {@link useQuery} observes one document from the app's shared cache and
23
+ delivers cached data on the first read; {@link usePrefetch} and
24
+ {@link intentPrefetchProps} warm a document when a person is about to open
25
+ it. Together they make a detail page open with no loading state.
26
+
27
+ This package needs a bonded client: install `@molecule/app-query` with a bond
28
+ (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
29
+ `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
30
+
31
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
32
+ > It is written to be read by coding agents as much as by people, and is generated from this
33
+ > package's source — edit `src/index.ts` JSDoc, not this file.
34
+
35
+ ## Quick Start
36
+
37
+ A detail page: the document is fetched once per key, cached documents paint at once, and only
38
+ an HTTP 404 or a completed `null` is "missing" — other errors stay load failures.
39
+
40
+ ```svelte
41
+ <script lang="ts">
42
+ import { isHttpError, getClient } from '@molecule/app-http'
43
+ import { useTranslation } from '@molecule/app-svelte'
44
+ import { intentPrefetchProps, useQuery } from '@molecule/app-query-svelte'
45
+
46
+ interface PackageDocument {
47
+ name: string
48
+ description: string
49
+ }
50
+
51
+ const packageQuery = (name: string) => ({
52
+ key: ['package', name],
53
+ fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
54
+ try {
55
+ const response = await getClient().get<PackageDocument | null>(
56
+ `/data/packages/${encodeURIComponent(name)}.json`,
57
+ { signal },
58
+ )
59
+ return response.data
60
+ } catch (error) {
61
+ if (isHttpError(error) && error.status === 404) return null
62
+ throw error
63
+ }
64
+ },
65
+ })
66
+
67
+ let { name } = $props()
68
+ const { t } = useTranslation()
69
+ const query = useQuery(packageQuery(name))
70
+ </script>
71
+
72
+ {#if $query.status === 'error'}
73
+ <p role="alert">
74
+ {t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' })}
75
+ </p>
76
+ {:else if $query.status === 'idle' || $query.status === 'loading'}
77
+ <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
78
+ {:else if $query.data == null}
79
+ <p>{t('packages.notFound', undefined, { defaultValue: 'Package not found.' })}</p>
80
+ {:else}
81
+ <article>
82
+ <h1>{$query.data.name}</h1>
83
+ <p>{$query.data.description}</p>
84
+ </article>
85
+ {/if}
86
+
87
+ <a href={`/packages/${name}`} {...intentPrefetchProps(packageQuery(name))}>{name}</a>
88
+ ```
89
+
90
+ A list whose page and filter live in the URL: derive the key from the route and pass
91
+ `keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
92
+ until the next page answers. Key the list on the viewer and pass the same value as `principal`
93
+ — an account switch then drops the previous account's rows at once. Pass `null` while the
94
+ session is still being restored, so restoring a session never swaps a key that already
95
+ rendered rows. The options arrive as a readable store, so a changed page or filter
96
+ re-observes on the same component.
97
+
98
+ ```svelte
99
+ <script lang="ts">
100
+ import { derived } from 'svelte/store'
101
+ import { unwrapList } from '@molecule/app-http'
102
+ import { useTranslation } from '@molecule/app-svelte'
103
+ import { useQuery } from '@molecule/app-query-svelte'
104
+ import { useAuth, useHttpClient, useListRoute } from '@molecule/app-svelte'
105
+
106
+ interface Invoice {
107
+ id: string
108
+ number: string
109
+ }
110
+
111
+ const http = useHttpClient()
112
+ const { t } = useTranslation()
113
+ const auth = useAuth<{ id: string }>()
114
+ const list = useListRoute({ pageSize: 20, filters: { status: {} } })
115
+ const viewer = $derived($auth.user ? String($auth.user.id) : 'anonymous')
116
+ const query = useQuery(
117
+ derived(list.page, (page) => ({
118
+ key: ['invoices', viewer, $list.filters, page],
119
+ principal: viewer,
120
+ keepPreviousData: true,
121
+ fetch: async (signal: AbortSignal) =>
122
+ unwrapList<Invoice>(
123
+ await http.get('/api/invoices', {
124
+ signal,
125
+ params: { ...$list.filters, limit: $list.pageSize, offset: $list.offset },
126
+ }),
127
+ ),
128
+ })),
129
+ )
130
+ </script>
131
+
132
+ <section>
133
+ {#if $query.status === 'loading' || $query.isFetching}
134
+ <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
135
+ {/if}
136
+ {#if $query.status === 'error'}
137
+ <p role="alert">
138
+ {t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' })}
139
+ </p>
140
+ {/if}
141
+ <ul>
142
+ {#each $query.data ?? [] as invoice (invoice.id)}
143
+ <li><a href={`/invoices/${invoice.id}`}>{invoice.number}</a></li>
144
+ {/each}
145
+ </ul>
146
+ {#if !$query.isPreviousData && $query.data?.length === 0}
147
+ <p>{t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' })}</p>
148
+ {/if}
149
+ <a href={$list.href({ page: $list.page + 1 })}>
150
+ {t('common.next', undefined, { defaultValue: 'Next page' })}
151
+ </a>
152
+ </section>
153
+ ```
154
+
155
+ A mutation or a failed load has to change a page that is ALREADY mounted, and
156
+ the cache never starts that request by itself: `set()` paints a mutation's own
157
+ response, `invalidate()` marks what it affects for the next mount, and an
158
+ explicit `fetch()` retries into the mounted page.
159
+
160
+ ```svelte
161
+ <script lang="ts">
162
+ import { getClient } from '@molecule/app-http'
163
+ import { getQueryClient } from '@molecule/app-query'
164
+
165
+ // The key names what the document actually depends on — here the signed-in
166
+ // principal, the filter and the page. Another principal's feed is a
167
+ // different document, so an invalidation scoped to this one leaves it alone.
168
+ const feedKey = (principal: string, filter: string, page: number) =>
169
+ ['feed', principal, filter, page] as const
170
+
171
+ const feedOptions = (principal: string, filter: string, page: number) => ({
172
+ key: feedKey(principal, filter, page),
173
+ fetch: async (signal: AbortSignal) =>
174
+ (await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
175
+ })
176
+
177
+ async function setFollowing(principal: string, authorId: string, follow: boolean) {
178
+ const client = getQueryClient()
179
+ const http = getClient()
180
+ const { data: body } = follow
181
+ ? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
182
+ : await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
183
+ // The response IS the document: paint it now, with no second round trip.
184
+ client.set(feedKey(principal, 'following', 1), body.feed)
185
+ // Future reads of every feed this principal owns are stale.
186
+ client.invalidate(['feed', principal])
187
+ }
188
+ </script>
189
+ ```
190
+
191
+ One API resource described once, for every page that reads or changes it.
192
+ `createQueryResource` returns the list and detail reads as `useQuery` options and the writes
193
+ as functions that put the server's record into the cache and fetch the lists on screen again,
194
+ so a page never mirrors a response into local state. A flag the API models as a sub-path
195
+ (`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
196
+ record and is the `commit` of `OptimisticToggleButton` (or of `useOptimisticValue` from
197
+ `@molecule/app-svelte` for custom controls). Render resource-dependent lists and controls
198
+ through {@link QueryContent}: its child snippet receives only loaded, non-null data, so
199
+ loading and error content never mount item actions.
200
+
201
+ ```svelte
202
+ <!-- InvoicePage.svelte -->
203
+ <script module lang="ts">
204
+ import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
205
+ import { createQueryResource } from '@molecule/app-query-svelte'
206
+
207
+ interface Invoice {
208
+ id: string
209
+ number: string
210
+ flagged: boolean
211
+ }
212
+
213
+ // The list and detail reads are useQuery options; the writes paint the
214
+ // server's own record and refresh the lists on screen.
215
+ export const invoices = createQueryResource<Invoice>({
216
+ name: 'invoices',
217
+ path: '/invoices',
218
+ http: getClient,
219
+ readList: (response) => unwrapList<Invoice>(response),
220
+ readOne: (response) => unwrapSingle<Invoice>(response),
221
+ })
222
+ </script>
223
+
224
+ <script lang="ts">
225
+ import { QueryContent, useQuery } from '@molecule/app-query-svelte'
226
+ import { OptimisticToggleButton } from '@molecule/app-ui-svelte'
227
+ import { useTranslation } from '@molecule/app-svelte'
228
+
229
+ let { id }: { id: string } = $props()
230
+ const { t } = useTranslation()
231
+ const viewer = 'reader'
232
+ const query = useQuery(invoices.detail(viewer, id))
233
+ </script>
234
+
235
+ <QueryContent {query}>
236
+ {#snippet pending()}
237
+ <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
238
+ {/snippet}
239
+ {#snippet missing()}
240
+ <p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>
241
+ {/snippet}
242
+ {#snippet children(invoice)}
243
+ <!-- Mounted only with the loaded record. The change shows at once and
244
+ saves in order; `toggle` waits out older list reads, and an inverse
245
+ click during that interval queues after the running save. -->
246
+ <OptimisticToggleButton
247
+ value={invoice.flagged}
248
+ commit={async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged}
249
+ activeLabel={t('invoice.unflag', undefined, { defaultValue: 'Unflag' })}
250
+ inactiveLabel={t('invoice.flag', undefined, { defaultValue: 'Flag' })}
251
+ />
252
+ {/snippet}
253
+ </QueryContent>
254
+ ```
255
+
256
+ ## Type
257
+
258
+ `feature`
259
+
260
+ ## Installation
261
+
262
+ ```bash
263
+ npm install @molecule/app-query-svelte @molecule/app-query svelte
264
+ ```
265
+
266
+ ## API
267
+
268
+ ### Interfaces
269
+
270
+ #### `ResourceResponse`
271
+
272
+ The part of an HTTP response a resource reads.
273
+
274
+ ```typescript
275
+ interface ResourceResponse {
276
+ /** The parsed response body. */
277
+ data: unknown
278
+ }
279
+ ```
280
+
281
+ #### `ResourceHttp`
282
+
283
+ The HTTP client a resource calls: the app's own bonded client (`getClient()` from
284
+ `@molecule/app-http`) has this shape. Only what a resource uses is named here.
285
+
286
+ ```typescript
287
+ interface ResourceHttp {
288
+ /** Reads `path`; `signal` cancels it and `params` become the query string. */
289
+ get(
290
+ path: string,
291
+ options?: { signal?: AbortSignal; params?: Record<string, unknown> },
292
+ ): Promise<ResourceResponse>
293
+ /** Creates at `path`. */
294
+ post(path: string, body?: unknown): Promise<ResourceResponse>
295
+ /** Replaces at `path`. */
296
+ put(path: string, body?: unknown): Promise<ResourceResponse>
297
+ /** Changes part of the record at `path`. */
298
+ patch(path: string, body?: unknown): Promise<ResourceResponse>
299
+ /** Removes at `path`. */
300
+ delete(path: string): Promise<ResourceResponse>
301
+ }
302
+ ```
303
+
304
+ #### `QueryResourceConfig`
305
+
306
+ What {@link createQueryResource} needs to know about one resource.
307
+
308
+ ```typescript
309
+ interface QueryResourceConfig<T> {
310
+ /** The first element of every cache key of this resource, e.g. `'invoices'`. */
311
+ name: string
312
+ /** The collection's path under the API base, e.g. `'/invoices'`. */
313
+ path: string
314
+ /** The app's HTTP client, read on every call so a client bonded later is the one used. */
315
+ http: () => ResourceHttp
316
+ /** The field a record is addressed by in a URL. Defaults to `'id'`. */
317
+ id?: keyof T & string
318
+ /** The HTTP method the API updates a record with. Defaults to `'put'`. */
319
+ updateMethod?: 'put' | 'patch'
320
+ /** Reads the records out of a list response. Defaults to the body itself. */
321
+ readList?: (response: ResourceResponse) => T[]
322
+ /** Reads the record out of a detail or write response. Defaults to the body itself. */
323
+ readOne?: (response: ResourceResponse) => T | null
324
+ }
325
+ ```
326
+
327
+ #### `QueryResource`
328
+
329
+ The reads and writes {@link createQueryResource} returns.
330
+
331
+ ```typescript
332
+ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
333
+ /**
334
+ * `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
335
+ * or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
336
+ */
337
+ list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>
338
+ /**
339
+ * Options for a collection's whole page (rows plus totals), or a filtered collection path.
340
+ * Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
341
+ * canonical page response for `path`; row-only `list` reads keep a separate cache entry.
342
+ * Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
343
+ * immediately and keep stale list responses from restoring them.
344
+ */
345
+ listPage<Page>(
346
+ viewer: string,
347
+ params: Record<string, unknown>,
348
+ readPage: (response: ResourceResponse) => Page,
349
+ path?: string,
350
+ removeFromPage?: (page: Page, id: string) => Page,
351
+ ): QueryOptions<Page>
352
+ /**
353
+ * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
354
+ * observes nothing). A missing record resolves to null, not to an error.
355
+ */
356
+ detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null
357
+ /** Creates a record, shows it in the cache and refreshes the lists on screen. */
358
+ create(viewer: string, input: Create): Promise<T>
359
+ /** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
360
+ update(viewer: string, id: string, input: Update): Promise<T>
361
+ /** Removes a record from detail and tracked row lists, then refreshes those lists. */
362
+ remove(viewer: string, id: string): Promise<void>
363
+ /**
364
+ * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
365
+ * `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
366
+ * of `useOptimisticValue`.
367
+ * The saved detail is published before tracked lists finish refreshing; this promise waits
368
+ * for those refreshes. Render the shared controller's value and let it queue inverse clicks
369
+ * during that interval. A page-local busy guard can drop a click on the newly changed label.
370
+ */
371
+ toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
372
+ /** Fetches the lists on screen again, after a change this resource did not make itself. */
373
+ refresh(viewer: string): Promise<void>
374
+ }
375
+ ```
376
+
377
+ #### `UseQueryResult`
378
+
379
+ A mounted query's state and its explicit cache and refresh actions. The
380
+ Svelte hook hands this out as a readable store of these objects (one per
381
+ change), so a component reads `data` and `status` with `$result.data`.
382
+
383
+ ```typescript
384
+ interface UseQueryResult<T> extends QueryState<T> {
385
+ /**
386
+ * Publish a saved document to this key and all its observers. Render `data`
387
+ * directly instead of copying it to local state: later cache updates then
388
+ * remain visible. A function receives this key's current cached document,
389
+ * never retained previous-page data. Returning `undefined` leaves the cache
390
+ * unchanged. A disabled (`null`) query does nothing, including not calling an
391
+ * updater. Like React state setters, wrap a function-valued document in an
392
+ * updater. A saved callback stays bound to its original key. The write
393
+ * supersedes older in-flight reads, using the bonded client's `set` contract.
394
+ */
395
+ setData: (value: T | ((previous: T | undefined) => T | undefined)) => void
396
+ /**
397
+ * Fetch this key again, even when its cached document is fresh. Observers
398
+ * receive the updated state. Resolves with that state, including an error
399
+ * when the request fails; a disabled (`null`) query resolves idle without a
400
+ * request.
401
+ */
402
+ refetch: () => Promise<QueryState<T>>
403
+ }
404
+ ```
405
+
406
+ #### `QueryContentProps`
407
+
408
+ A loaded document owns its controls; absent documents expose only status content.
409
+
410
+ ```typescript
411
+ interface QueryContentProps<T> {
412
+ /**
413
+ * State from `useQuery` — as the readable store the hook returns, or as a
414
+ * compatible observer's plain state object. Both follow the query.
415
+ */
416
+ query:
417
+ | Readable<Pick<QueryState<T>, 'data' | 'status' | 'error'>>
418
+ | Pick<QueryState<T>, 'data' | 'status' | 'error'>
419
+ /** Mounted only with a real document, including false, zero and an empty list. */
420
+ children: Snippet<[NonNullable<T>]>
421
+ /** Initial idle/loading content. Render a status snippet, never a fake item or action. */
422
+ pending?: Snippet | null
423
+ /** Content for a loaded null record. Null is distinct from an unfinished request. */
424
+ missing?: Snippet | null
425
+ /** A failed initial read. Cached data stays visible if its refresh fails. */
426
+ error?: Snippet<[unknown]> | null
427
+ }
428
+ ```
429
+
430
+ #### `IntentPrefetchProps`
431
+
432
+ The handlers {@link intentPrefetchProps} returns, in Svelte 5's listener
433
+ naming (lowercase DOM event attributes, spreadable onto an `<a>`).
434
+
435
+ ```typescript
436
+ interface IntentPrefetchProps {
437
+ /** Warms the document when the pointer arrives. */
438
+ onpointerenter: () => void
439
+ /** Warms the document on keyboard focus. */
440
+ onfocus: () => void
441
+ /** Warms the document when a touch starts. */
442
+ ontouchstart: () => void
443
+ }
444
+ ```
445
+
446
+ ### Functions
447
+
448
+ #### `prefetchQuery(options)`
449
+
450
+ Warms the cache for a document, when the connection can afford it (see
451
+ `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
452
+ in-flight document is skipped, and failures are swallowed.
453
+
454
+ ```typescript
455
+ function prefetchQuery<T>(options: QueryOptions<T>): void
456
+ ```
457
+
458
+ - `options` — Key, fetch, freshness.
459
+
460
+ #### `createQueryResource(config)`
461
+
462
+ Describe one API resource once and get its reads and writes on the shared cache.
463
+
464
+ A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
465
+ re-solve the same problems on every screen: a late answer for the previous page lands
466
+ over the current one, and a list still shows what it showed before a comment was added.
467
+ Here the reads are `useQuery` options (one key per
468
+ viewer, page and filter; the previous rows stay until the next answer) and every write puts
469
+ the server's own record into the cache and fetches the lists on screen again.
470
+
471
+ The factory supplies data operations. Mount a keyed
472
+ control inside `QueryContent` (your framework's query package: `@molecule/app-query-react`,
473
+ `-vue`, …) so it receives a loaded record and stays mounted during refresh.
474
+ For a server-backed toggle, use `useOptimisticValue` from your framework binding
475
+ (`@molecule/app-react`, `@molecule/app-vue`, …), or `OptimisticToggleButton` from its UI
476
+ package (`@molecule/app-ui-react`, …) for a boolean. Pass `toggle` as its
477
+ commit adapter, return the saved flag/count, and render the controller's value for the action
478
+ label too. Do not block clicks while that commit is pending. The resource example in
479
+ `@molecule/app-query-react` composes these APIs; a custom handler must provide the same
480
+ readiness and ordering itself.
481
+
482
+ Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
483
+ and the query provider are whatever the app bonded.
484
+
485
+ ```typescript
486
+ function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
487
+ config: QueryResourceConfig<T>,
488
+ ): QueryResource<T, Create, Update>
489
+ ```
490
+
491
+ - `config` — The resource's name, path, HTTP client and response readers.
492
+
493
+ **Returns:** List and detail query options, and create, update, remove, toggle and refresh.
494
+
495
+ #### `usePrefetch()`
496
+
497
+ A stable `prefetch(options)` function for event handlers. One identity for
498
+ the component's life (React's `useCallback` with no dependencies).
499
+
500
+ ```typescript
501
+ function usePrefetch(): <T>(options: QueryOptions<T>) => void
502
+ ```
503
+
504
+ **Returns:** The prefetch function.
505
+
506
+ #### `intentPrefetchProps(options)`
507
+
508
+ Event handlers that warm a document at the first sign of intent: the
509
+ pointer arriving, keyboard focus, or a touch starting. Spread them onto a
510
+ link — the names are Svelte 5's lowercase DOM event attributes:
511
+ `<a href={to} {...intentPrefetchProps(packageQuery(name))}>{name}</a>`. It
512
+ is a plain function (not a hook), so it works inside `{#each}` too.
513
+
514
+ ```typescript
515
+ function intentPrefetchProps<T>(options: QueryOptions<T>): IntentPrefetchProps
516
+ ```
517
+
518
+ - `options` — Key, fetch, freshness.
519
+
520
+ **Returns:** The handlers.
521
+
522
+ #### `useQuery(options)`
523
+
524
+ The document for `options.key`, kept current: cached data is delivered on
525
+ the very first read (so a warmed page never flashes a loading state), a
526
+ stale or missing document is fetched, and every change updates the returned
527
+ store. Pass `null` to observe nothing. A key change resets to that key's
528
+ state; the hook never hands a caller another key's document — unless the
529
+ caller opts into {@link QueryOptions.keepPreviousData}, and then only within
530
+ one {@link QueryOptions.principal}.
531
+
532
+ The request is stable across updates — an unrelated store or component
533
+ change neither restarts it nor cancels it, so a response that arrives after
534
+ one still lands. It is aborted only when the key changes or the component is
535
+ destroyed (the `signal` given to `options.fetch`). Pass the options as a
536
+ readable store and a changed key re-observes on the same component, the way
537
+ React re-renders `useQuery` with new options.
538
+
539
+ For a LIST, put the route's page, filter and selected view in the key and
540
+ pass `keepPreviousData` with a `principal`: a page or filter change then
541
+ keeps the rows already on screen until the new page answers, instead of
542
+ rendering a loading state over an empty list. The key names everything the
543
+ answer depends on, so a list the server can filter or personalize per viewer
544
+ puts the viewer in its key and passes the same value as `principal`
545
+ (`'anonymous'` when signed out): an account switch then drops the previous
546
+ account's document immediately.
547
+
548
+ For custom mutation handlers, `setData(saved)` publishes the server's
549
+ response to this key and every observer. Use `setData(current => next)` for
550
+ a local cache update. Render `data` directly; a component-local copy stops
551
+ observing later server responses.
552
+
553
+ ```typescript
554
+ function useQuery<T>(
555
+ options: QueryOptions<T> | null | Readable<QueryOptions<T> | null>,
556
+ ): Readable<UseQueryResult<T>>
557
+ ```
558
+
559
+ - `options` — Key, fetch, freshness, and optionally `principal` with `keepPreviousData`; or `null`; or a readable store of either, so changed options are followed without remounting.
560
+
561
+ **Returns:** A readable store of the document's state with `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
562
+
563
+ ### Constants
564
+
565
+ #### `QueryContent`
566
+
567
+ ```typescript
568
+ const QueryContent: LegacyComponentType
569
+ ```
570
+
571
+ ## Injection Notes
572
+
573
+ ### Requirements
574
+
575
+ Peer dependencies:
576
+
577
+ - `@molecule/app-query` ^1.2.0
578
+ - `svelte` ^5.0.0
579
+
580
+ ### Runtime Dependencies
581
+
582
+ - `@molecule/app-query`
583
+ - `svelte`
584
+
585
+ - **`useQuery` reads the cache synchronously on the first read.** A
586
+ document prefetched from a hovered link, or seeded with `client.set()`,
587
+ renders at once — no spinner, no layout shift. Render loading from
588
+ `status === 'idle' || status === 'loading'`; `undefined` data can also
589
+ accompany a completed error. A completed `null` response is missing, not
590
+ pending. The app's bonded HTTP client rejects non-2xx responses. Native
591
+ `fetch` resolves them, so a custom fetcher must check `response.ok`
592
+ before JSON.
593
+ - **Pass the options as a readable store when they change on a live
594
+ component** — a route param, a session id, a page number:
595
+ `useQuery(storeOfOptions)` follows a changed key on the same component,
596
+ the way React re-renders `useQuery` with new options.
597
+ - **Mount a detail region and its actions only after its initial document
598
+ arrives.** A visible container is not a loaded document: a caller may wait
599
+ for that container and read its text once, or click its button, while
600
+ `data` is still undefined. Put the loading message outside the detail
601
+ region, and keep record-dependent controls absent until the record exists.
602
+ - **The key is the identity.** Building `options` inline is fine; the hook
603
+ resubscribes only when the key's value changes, not when the `fetch`
604
+ closure does.
605
+ - **A key change normally resets to the new key's state.** For a list's own
606
+ page/filter/view change, opt into `keepPreviousData` with a `principal`;
607
+ `isPreviousData` tells you the rows on screen belong to the key you just
608
+ left. A completed response (including an empty list) replaces them, and a
609
+ changed principal drops them, so an account switch never shows the previous
610
+ account's rows. Do not emulate this with a local copy of the query data.
611
+ - **Render loading, empty and error status outside the item list**, and never
612
+ give a placeholder the item's own class or element shape. An empty array is
613
+ a loaded empty state, not a missing response; render it only when
614
+ `isPreviousData` is not set.
615
+ - `intentPrefetchProps` spreads three Svelte event handlers onto a link. It
616
+ is a plain function (not a hook), so it works inside `{#each}` too.
617
+ - Prefetching respects the browser's data-saver setting and skips 2G
618
+ connections (`shouldPrefetch()` in the core) — do not bypass that for
619
+ "important" links; the person can still click.
620
+ - **Refresh a mounted document with `query.refetch()`.** It fetches even a
621
+ fresh cache entry and updates every observer of that key. After a mutation
622
+ whose response is not the whole document, `await query.refetch()` reloads
623
+ the displayed list. It resolves with the resulting state (including
624
+ `status: 'error'` on failure); a disabled query stays idle. Prefer
625
+ `client.set(key, response)` when the mutation already returned the whole
626
+ document.
627
+ - Errors are not thrown from the hook; read `status === 'error'` and
628
+ `error`. `client.invalidate()` does NOT refetch a mounted page — it only
629
+ marks documents stale, so the page keeps its error (or its old document)
630
+ until the app retries with `client.fetch(options)` or the page subscribes
631
+ again (a key change or a re-mount).
632
+ - After a mutation, `client.set(key, response)` paints the server's own
633
+ answer at once and supersedes an older fetch already in flight for that
634
+ key, so its response cannot undo the mutation.
635
+ - Keep every resource identity in the query key. A boundary cannot correct a
636
+ query that supplies another record's cached data. QueryContent is headless
637
+ and owns no translations or styling.
@@ -0,0 +1,53 @@
1
+ <!--
2
+ QueryContent: the Svelte counterpart of `@molecule/app-query-react`'s
3
+ `QueryContent` — renders the children snippet only for a loaded, non-null
4
+ document. The loaded-data branch receives a non-null document; pending,
5
+ failed initial reads and missing records never mount that branch, so its
6
+ actions cannot swallow an early click. Cached data remains mounted during
7
+ refresh, including a failed refresh. Status fallbacks belong outside the
8
+ list or record container rendered by `children`, and so does a refresh
9
+ line; the default fallbacks render nothing. Headless: it owns no
10
+ translations and no styling.
11
+ -->
12
+ <script lang="ts" generics="T">
13
+ import { type Readable, readonly, writable } from 'svelte/store'
14
+
15
+ import type { QueryState } from '@molecule/app-query'
16
+
17
+ import type { QueryContentProps } from './types.js'
18
+
19
+ /** The part of a query state this component renders from. */
20
+ type QueryView = Pick<QueryState<T>, 'data' | 'status' | 'error'>
21
+
22
+ let {
23
+ query,
24
+ children,
25
+ pending = null,
26
+ missing = null,
27
+ error = null,
28
+ }: QueryContentProps<T> = $props()
29
+
30
+ /**
31
+ * The state as a readable store, whichever prop form arrived: the store
32
+ * `useQuery` returned is observed as it is, and a plain state object (the
33
+ * React prop's shape) is wrapped — so both
34
+ * `<QueryContent query={query}>` and `query={$query}` follow the query.
35
+ */
36
+ const view: Readable<QueryView> = $derived(
37
+ typeof (query as Partial<Readable<QueryView>>).subscribe === 'function'
38
+ ? (query as Readable<QueryView>)
39
+ : readonly(writable(query as QueryView)),
40
+ )
41
+ </script>
42
+
43
+ {#if $view.data === undefined}
44
+ {#if $view.status === 'error' && error}
45
+ {@render error($view.error)}
46
+ {:else if pending}
47
+ {@render pending()}
48
+ {/if}
49
+ {:else if $view.data === null}
50
+ {#if missing}{@render missing()}{/if}
51
+ {:else}
52
+ {@render children($view.data)}
53
+ {/if}