@molecule/app-query-react 1.6.0 → 1.6.1

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
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-11-14T04:22:15.656Z
6
+ Generated: 2026-11-14T12:29:21.947Z
7
7
  -->
8
8
 
9
9
  # @molecule/app-query-react
@@ -236,8 +236,8 @@ record and is the `commit` of `useOptimisticValue`.
236
236
 
237
237
  ```tsx
238
238
  import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
239
- import { createQueryResource, useQuery } from '@molecule/app-query-react'
240
- import { useAuth, useOptimisticValue } from '@molecule/app-react'
239
+ import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-react'
240
+ import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-react'
241
241
 
242
242
  interface Invoice {
243
243
  id: string
@@ -255,20 +255,40 @@ export const invoices = createQueryResource<Invoice>({
255
255
 
256
256
  function InvoicePage({ id }: { id: string }) {
257
257
  const { user } = useAuth<{ id: string }>()
258
+ const { t } = useTranslation()
258
259
  const viewer = user ? String(user.id) : 'anonymous'
259
- const { data: invoice, status } = useQuery(invoices.detail(viewer, id))
260
- if (status === 'idle' || status === 'loading') return <p role=status>…</p>
261
- if (!invoice) return <p role=alert>…</p>
262
- return <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />
260
+ const query = useQuery(invoices.detail(viewer, id))
261
+ return (
262
+ <QueryContent
263
+ query={query}
264
+ pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
265
+ missing={
266
+ <p role="alert">
267
+ {t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}
268
+ </p>
269
+ }
270
+ error={() => (
271
+ <p role="alert">
272
+ {t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}
273
+ </p>
274
+ )}
275
+ >
276
+ {(invoice) => <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />}
277
+ </QueryContent>
278
+ )
263
279
  }
264
280
 
265
281
  function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
282
+ const { t } = useTranslation()
266
283
  const flag = useOptimisticValue({
267
284
  value: invoice.flagged,
268
285
  commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
269
286
  })
270
287
  return (
271
- <button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
288
+ <button type="button" aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
289
+ {flag.value
290
+ ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
291
+ : t('invoice.flag', undefined, { defaultValue: 'Flag' })}{' '}
272
292
  {invoice.number}
273
293
  </button>
274
294
  )
@@ -428,6 +448,9 @@ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
428
448
  * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
429
449
  * `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
430
450
  * of `useOptimisticValue`.
451
+ * The saved detail is published before tracked lists finish refreshing; this promise waits
452
+ * for those refreshes. Render the shared controller's value and let it queue inverse clicks
453
+ * during that interval. A page-local busy guard can drop a click on the newly changed label.
431
454
  */
432
455
  toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
433
456
  /** Fetches the lists on screen again, after a change this resource did not make itself. */
@@ -493,39 +516,40 @@ interface IntentPrefetchProps {
493
516
 
494
517
  ### Functions
495
518
 
496
- #### `QueryContent(props)`
519
+ #### `prefetchQuery(options)`
497
520
 
498
- The loaded-data branch receives a non-null document. Pending, failed initial reads and
499
- missing records never mount that branch, so its actions cannot swallow an early click.
500
- Cached data remains mounted during refresh, including a failed refresh. Status fallbacks
501
- belong outside the list or record container rendered by `children`, and so does a refresh
502
- line; the default fallbacks render nothing.
521
+ Warms the cache for a document, when the connection can afford it (see
522
+ `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
523
+ in-flight document is skipped, and failures are swallowed.
503
524
 
504
525
  ```typescript
505
- function QueryContent<T>({
506
- query,
507
- children,
508
- pending = null,
509
- missing = null,
510
- error,
511
- }: QueryContentProps<T>): ReactNode
526
+ function prefetchQuery<T>(options: QueryOptions<T>): void
512
527
  ```
513
528
 
514
- - `props` — Query state, loaded content and optional status fallbacks.
515
-
516
- **Returns:** Loaded content or the appropriate fallback.
529
+ - `options` — Key, fetch, freshness.
517
530
 
518
531
  #### `createQueryResource(config)`
519
532
 
520
533
  Describe one API resource once and get its reads and writes on the shared cache.
521
534
 
522
535
  A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
523
- re-solve the same three problems on every screen: a late answer for the previous page lands
524
- over the current one, a list still shows what it showed before a comment was added, and a
525
- button is live before its record exists. Here the reads are `useQuery` options (one key per
536
+ re-solve the same problems on every screen: a late answer for the previous page lands
537
+ over the current one, and a list still shows what it showed before a comment was added.
538
+ Here the reads are `useQuery` options (one key per
526
539
  viewer, page and filter; the previous rows stay until the next answer) and every write puts
527
540
  the server's own record into the cache and fetches the lists on screen again.
528
541
 
542
+ The factory supplies data operations. Mount a keyed
543
+ control inside `QueryContent` (your framework's query package: `@molecule/app-query-react`,
544
+ `-vue`, …) so it receives a loaded record and stays mounted during refresh.
545
+ For a server-backed toggle, use `useOptimisticValue` from your framework binding
546
+ (`@molecule/app-react`, `@molecule/app-vue`, …), or `OptimisticToggleButton` from its UI
547
+ package (`@molecule/app-ui-react`, …) for a boolean. Pass `toggle` as its
548
+ commit adapter, return the saved flag/count, and render the controller's value for the action
549
+ label too. Do not block clicks while that commit is pending. The resource example in
550
+ `@molecule/app-query-react` composes these APIs; a custom handler must provide the same
551
+ readiness and ordering itself.
552
+
529
553
  Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
530
554
  and the query provider are whatever the app bonded.
531
555
 
@@ -539,17 +563,27 @@ function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
539
563
 
540
564
  **Returns:** List and detail query options, and create, update, remove, toggle and refresh.
541
565
 
542
- #### `prefetchQuery(options)`
566
+ #### `QueryContent(props)`
543
567
 
544
- Warms the cache for a document, when the connection can afford it (see
545
- `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
546
- in-flight document is skipped, and failures are swallowed.
568
+ The loaded-data branch receives a non-null document. Pending, failed initial reads and
569
+ missing records never mount that branch, so its actions cannot swallow an early click.
570
+ Cached data remains mounted during refresh, including a failed refresh. Status fallbacks
571
+ belong outside the list or record container rendered by `children`, and so does a refresh
572
+ line; the default fallbacks render nothing.
547
573
 
548
574
  ```typescript
549
- function prefetchQuery<T>(options: QueryOptions<T>): void
575
+ function QueryContent<T>({
576
+ query,
577
+ children,
578
+ pending = null,
579
+ missing = null,
580
+ error,
581
+ }: QueryContentProps<T>): ReactNode
550
582
  ```
551
583
 
552
- - `options` — Key, fetch, freshness.
584
+ - `props` — Query state, loaded content and optional status fallbacks.
585
+
586
+ **Returns:** Loaded content or the appropriate fallback.
553
587
 
554
588
  #### `usePrefetch()`
555
589
 
@@ -610,6 +644,11 @@ For custom mutation handlers, `setData(saved)` publishes the server's response t
610
644
  key and every observer. Use `setData(current => next)` for a local cache update. Render
611
645
  `data` directly; a component-local copy stops observing later server responses. Prefer
612
646
  `createQueryResource` when the API's reads and writes can share one resource definition.
647
+ Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
648
+ so a visible action cannot return early because its initial record is still missing.
649
+ Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
650
+ from `@molecule/app-react` or `OptimisticToggleButton` from `@molecule/app-ui-react` to keep
651
+ their displayed label and queued clicks on the same state while a save finishes.
613
652
 
614
653
  ```typescript
615
654
  function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>
@@ -625,7 +664,7 @@ function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>
625
664
 
626
665
  Peer dependencies:
627
666
 
628
- - `@molecule/app-query` ^1.1.0
667
+ - `@molecule/app-query` ^1.2.0
629
668
  - `react` ^18.0.0 || ^19.0.0
630
669
 
631
670
  ### Runtime Dependencies
package/dist/index.d.ts CHANGED
@@ -212,8 +212,8 @@
212
212
  *
213
213
  * ```tsx
214
214
  * import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
215
- * import { createQueryResource, useQuery } from '@molecule/app-query-react'
216
- * import { useAuth, useOptimisticValue } from '@molecule/app-react'
215
+ * import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-react'
216
+ * import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-react'
217
217
  *
218
218
  * interface Invoice {
219
219
  * id: string
@@ -231,21 +231,32 @@
231
231
  *
232
232
  * function InvoicePage({ id }: { id: string }) {
233
233
  * const { user } = useAuth<{ id: string }>()
234
+ * const { t } = useTranslation()
234
235
  * const viewer = user ? String(user.id) : 'anonymous'
235
- * const { data: invoice, status } = useQuery(invoices.detail(viewer, id))
236
- * if (status === 'idle' || status === 'loading') return <p role=status>…</p>
237
- * if (!invoice) return <p role=alert>…</p>
238
- * return <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />
236
+ * const query = useQuery(invoices.detail(viewer, id))
237
+ * return (
238
+ * <QueryContent
239
+ * query={query}
240
+ * pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
241
+ * missing={<p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>}
242
+ * error={() => <p role="alert">{t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}</p>}
243
+ * >
244
+ * {(invoice) => <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />}
245
+ * </QueryContent>
246
+ * )
239
247
  * }
240
248
  *
241
249
  * function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
250
+ * const { t } = useTranslation()
242
251
  * const flag = useOptimisticValue({
243
252
  * value: invoice.flagged,
244
253
  * commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
245
254
  * })
246
255
  * return (
247
- * <button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
248
- * {invoice.number}
256
+ * <button type="button" aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
257
+ * {flag.value
258
+ * ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
259
+ * : t('invoice.flag', undefined, { defaultValue: 'Flag' })} {invoice.number}
249
260
  * </button>
250
261
  * )
251
262
  * }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsXG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,kBAAkB,CAAA;AAChC,cAAc,eAAe,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiYG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,kBAAkB,CAAA;AAChC,cAAc,eAAe,CAAA"}
package/dist/index.js CHANGED
@@ -212,8 +212,8 @@
212
212
  *
213
213
  * ```tsx
214
214
  * import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
215
- * import { createQueryResource, useQuery } from '@molecule/app-query-react'
216
- * import { useAuth, useOptimisticValue } from '@molecule/app-react'
215
+ * import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-react'
216
+ * import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-react'
217
217
  *
218
218
  * interface Invoice {
219
219
  * id: string
@@ -231,21 +231,32 @@
231
231
  *
232
232
  * function InvoicePage({ id }: { id: string }) {
233
233
  * const { user } = useAuth<{ id: string }>()
234
+ * const { t } = useTranslation()
234
235
  * const viewer = user ? String(user.id) : 'anonymous'
235
- * const { data: invoice, status } = useQuery(invoices.detail(viewer, id))
236
- * if (status === 'idle' || status === 'loading') return <p role=status>…</p>
237
- * if (!invoice) return <p role=alert>…</p>
238
- * return <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />
236
+ * const query = useQuery(invoices.detail(viewer, id))
237
+ * return (
238
+ * <QueryContent
239
+ * query={query}
240
+ * pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
241
+ * missing={<p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>}
242
+ * error={() => <p role="alert">{t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}</p>}
243
+ * >
244
+ * {(invoice) => <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />}
245
+ * </QueryContent>
246
+ * )
239
247
  * }
240
248
  *
241
249
  * function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
250
+ * const { t } = useTranslation()
242
251
  * const flag = useOptimisticValue({
243
252
  * value: invoice.flagged,
244
253
  * commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
245
254
  * })
246
255
  * return (
247
- * <button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
248
- * {invoice.number}
256
+ * <button type="button" aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
257
+ * {flag.value
258
+ * ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
259
+ * : t('invoice.flag', undefined, { defaultValue: 'Flag' })} {invoice.number}
249
260
  * </button>
250
261
  * )
251
262
  * }
@@ -1,102 +1,10 @@
1
1
  /**
2
- * One API resource on the shared query cache: its list and detail reads as `useQuery` options,
3
- * and its writes as functions that put the server's answer into the cache.
2
+ * One API resource on the shared query cache. `createQueryResource` is framework-neutral, so it
3
+ * lives in `@molecule/app-query` (with its full documentation); this package re-exports it so
4
+ * React pages import it next to `useQuery` and `QueryContent`.
4
5
  *
5
6
  * @module
6
7
  */
7
- import type { QueryOptions } from '@molecule/app-query';
8
- /** The part of an HTTP response a resource reads. */
9
- export interface ResourceResponse {
10
- /** The parsed response body. */
11
- data: unknown;
12
- }
13
- /**
14
- * The HTTP client a resource calls: the app's own bonded client (`getClient()` from
15
- * `@molecule/app-http`) has this shape. Only what a resource uses is named here.
16
- */
17
- export interface ResourceHttp {
18
- /** Reads `path`; `signal` cancels it and `params` become the query string. */
19
- get(path: string, options?: {
20
- signal?: AbortSignal;
21
- params?: Record<string, unknown>;
22
- }): Promise<ResourceResponse>;
23
- /** Creates at `path`. */
24
- post(path: string, body?: unknown): Promise<ResourceResponse>;
25
- /** Replaces at `path`. */
26
- put(path: string, body?: unknown): Promise<ResourceResponse>;
27
- /** Changes part of the record at `path`. */
28
- patch(path: string, body?: unknown): Promise<ResourceResponse>;
29
- /** Removes at `path`. */
30
- delete(path: string): Promise<ResourceResponse>;
31
- }
32
- /** What {@link createQueryResource} needs to know about one resource. */
33
- export interface QueryResourceConfig<T> {
34
- /** The first element of every cache key of this resource, e.g. `'invoices'`. */
35
- name: string;
36
- /** The collection's path under the API base, e.g. `'/invoices'`. */
37
- path: string;
38
- /** The app's HTTP client, read on every call so a client bonded later is the one used. */
39
- http: () => ResourceHttp;
40
- /** The field a record is addressed by in a URL. Defaults to `'id'`. */
41
- id?: keyof T & string;
42
- /** The HTTP method the API updates a record with. Defaults to `'put'`. */
43
- updateMethod?: 'put' | 'patch';
44
- /** Reads the records out of a list response. Defaults to the body itself. */
45
- readList?: (response: ResourceResponse) => T[];
46
- /** Reads the record out of a detail or write response. Defaults to the body itself. */
47
- readOne?: (response: ResourceResponse) => T | null;
48
- }
49
- /** The reads and writes {@link createQueryResource} returns. */
50
- export interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
51
- /**
52
- * `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
53
- * or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
54
- */
55
- list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>;
56
- /**
57
- * Options for a collection's whole page (rows plus totals), or a filtered collection path.
58
- * Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
59
- * canonical page response for `path`; row-only `list` reads keep a separate cache entry.
60
- * Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
61
- * immediately and keep stale list responses from restoring them.
62
- */
63
- listPage<Page>(viewer: string, params: Record<string, unknown>, readPage: (response: ResourceResponse) => Page, path?: string, removeFromPage?: (page: Page, id: string) => Page): QueryOptions<Page>;
64
- /**
65
- * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
66
- * observes nothing). A missing record resolves to null, not to an error.
67
- */
68
- detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null;
69
- /** Creates a record, shows it in the cache and refreshes the lists on screen. */
70
- create(viewer: string, input: Create): Promise<T>;
71
- /** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
72
- update(viewer: string, id: string, input: Update): Promise<T>;
73
- /** Removes a record from detail and tracked row lists, then refreshes those lists. */
74
- remove(viewer: string, id: string): Promise<void>;
75
- /**
76
- * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
77
- * `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
78
- * of `useOptimisticValue`.
79
- */
80
- toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>;
81
- /** Fetches the lists on screen again, after a change this resource did not make itself. */
82
- refresh(viewer: string): Promise<void>;
83
- }
84
- /**
85
- * Describe one API resource once and get its reads and writes on the shared cache.
86
- *
87
- * A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
88
- * re-solve the same three problems on every screen: a late answer for the previous page lands
89
- * over the current one, a list still shows what it showed before a comment was added, and a
90
- * button is live before its record exists. Here the reads are `useQuery` options (one key per
91
- * viewer, page and filter; the previous rows stay until the next answer) and every write puts
92
- * the server's own record into the cache and fetches the lists on screen again.
93
- *
94
- * Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
95
- * and the query provider are whatever the app bonded.
96
- *
97
- * @param config - The resource's name, path, HTTP client and response readers.
98
- * @returns List and detail query options, and create, update, remove, toggle and refresh.
99
- * @throws {Error} When a write's response holds no record.
100
- */
101
- export declare function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(config: QueryResourceConfig<T>): QueryResource<T, Create, Update>;
8
+ export type { QueryResource, QueryResourceConfig, ResourceHttp, ResourceResponse, } from '@molecule/app-query';
9
+ export { createQueryResource } from '@molecule/app-query';
102
10
  //# sourceMappingURL=resource.d.ts.map
@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AM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAC7D,sFAAsF;IACtF,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACjD;;;;OAIG;IACH,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAC3E,2FAA2F;IAC3F,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CACvC;AAKD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,EAC7E,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAC7B,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CA8JlC"}
1
+ {"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;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 CHANGED
@@ -1,160 +1,8 @@
1
1
  /**
2
- * One API resource on the shared query cache: its list and detail reads as `useQuery` options,
3
- * and its writes as functions that put the server's answer into the cache.
2
+ * One API resource on the shared query cache. `createQueryResource` is framework-neutral, so it
3
+ * lives in `@molecule/app-query` (with its full documentation); this package re-exports it so
4
+ * React pages import it next to `useQuery` and `QueryContent`.
4
5
  *
5
6
  * @module
6
7
  */
7
- import { getQueryClient, hashQueryKey } from '@molecule/app-query';
8
- /** How many of a viewer's most recent lists a write fetches again. */
9
- const REFRESHED_LISTS = 4;
10
- /**
11
- * Describe one API resource once and get its reads and writes on the shared cache.
12
- *
13
- * A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
14
- * re-solve the same three problems on every screen: a late answer for the previous page lands
15
- * over the current one, a list still shows what it showed before a comment was added, and a
16
- * button is live before its record exists. Here the reads are `useQuery` options (one key per
17
- * viewer, page and filter; the previous rows stay until the next answer) and every write puts
18
- * the server's own record into the cache and fetches the lists on screen again.
19
- *
20
- * Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
21
- * and the query provider are whatever the app bonded.
22
- *
23
- * @param config - The resource's name, path, HTTP client and response readers.
24
- * @returns List and detail query options, and create, update, remove, toggle and refresh.
25
- * @throws {Error} When a write's response holds no record.
26
- */
27
- export function createQueryResource(config) {
28
- const readList = config.readList ?? ((response) => response.data);
29
- const readOne = config.readOne ?? ((response) => response.data);
30
- const idField = config.id ?? 'id';
31
- const base = config.path.replace(/\/+$/, '');
32
- const one = (id) => `${base}/${encodeURIComponent(id)}`;
33
- const detailKey = (viewer, id) => [config.name, viewer, 'detail', id];
34
- // The lists handed out most recently, newest last: the ones a write fetches again. A list
35
- // nobody reads any more costs one request and is then dropped by the next ones.
36
- const recent = new Map();
37
- const removed = new Map();
38
- const removals = (viewer) => removed.get(viewer) ?? new Set();
39
- const recordId = (record) => {
40
- const id = record != null ? record[idField] : undefined;
41
- return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined;
42
- };
43
- const withoutRemoved = (viewer, rows) => {
44
- const ids = removed.get(viewer);
45
- return ids?.size ? rows.filter((record) => !ids.has(recordId(record) ?? '')) : rows;
46
- };
47
- const projectPage = (viewer, page, remove) => {
48
- if (!remove)
49
- return page;
50
- for (const id of removals(viewer))
51
- page = remove(page, id);
52
- return page;
53
- };
54
- const track = (viewer, options, remove) => {
55
- const hash = hashQueryKey(options.key);
56
- recent.delete(hash);
57
- recent.set(hash, {
58
- viewer,
59
- options,
60
- ...(remove ? { remove: (page, id) => remove(page, id) } : {}),
61
- });
62
- for (const stale of [...recent.keys()].slice(0, -REFRESHED_LISTS))
63
- recent.delete(stale);
64
- return options;
65
- };
66
- const list = (viewer, params = {}) => {
67
- const options = {
68
- key: [config.name, viewer, 'list', params],
69
- principal: viewer,
70
- keepPreviousData: true,
71
- fetch: async (signal) => withoutRemoved(viewer, readList(await config.http().get(base, { signal, params }))),
72
- };
73
- return track(viewer, options, (rows) => withoutRemoved(viewer, rows));
74
- };
75
- const refresh = async (viewer) => {
76
- const client = getQueryClient();
77
- client.invalidate([config.name, viewer, 'list']);
78
- await Promise.all([...recent.values()]
79
- .filter((entry) => entry.viewer === viewer)
80
- .map(async (entry) => {
81
- // fetch() deduplicates an existing request. It may have read before this write,
82
- // so joining it alone cannot refresh the list after the mutation.
83
- const pending = client.getState(entry.options.key).isFetching;
84
- const fetch = () => client.fetch(entry.options).catch((_error) => {
85
- // The mounted query presents its own failure; the mutation already succeeded.
86
- });
87
- await fetch();
88
- if (pending) {
89
- client.invalidate(entry.options.key);
90
- await fetch();
91
- }
92
- }));
93
- };
94
- const saved = async (viewer, response, created = false) => {
95
- const record = readOne(response);
96
- if (record == null)
97
- throw new Error(`${config.name}: the response held no record`);
98
- const id = recordId(record);
99
- if (id !== undefined) {
100
- if (created)
101
- removed.get(viewer)?.delete(id);
102
- if (!removals(viewer).has(id))
103
- getQueryClient().set(detailKey(viewer, id), record);
104
- }
105
- await refresh(viewer);
106
- return record;
107
- };
108
- return {
109
- list,
110
- listPage: (viewer, params, readPage, path = base, removeFromPage) => track(viewer, {
111
- key: [config.name, viewer, 'list', 'page', path, params],
112
- principal: viewer,
113
- keepPreviousData: true,
114
- fetch: async (signal) => projectPage(viewer, readPage(await config.http().get(path, { signal, params })), removeFromPage),
115
- }, removeFromPage),
116
- detail: (viewer, id) => id == null || id === ''
117
- ? null
118
- : {
119
- key: detailKey(viewer, id),
120
- principal: viewer,
121
- fetch: async (signal) => {
122
- if (removals(viewer).has(id))
123
- return null;
124
- try {
125
- const record = readOne(await config.http().get(one(id), { signal }));
126
- return removals(viewer).has(id) ? null : record;
127
- }
128
- catch (error) {
129
- // A record that does not exist is an answer, not a failed load.
130
- if (error?.status === 404)
131
- return null;
132
- throw error;
133
- }
134
- },
135
- },
136
- create: async (viewer, input) => saved(viewer, await config.http().post(base, input), true),
137
- update: async (viewer, id, input) => saved(viewer, await config.http()[config.updateMethod ?? 'put'](one(id), input)),
138
- remove: async (viewer, id) => {
139
- await config.http().delete(one(id));
140
- const ids = removed.get(viewer) ?? new Set();
141
- ids.add(id);
142
- removed.set(viewer, ids);
143
- const client = getQueryClient();
144
- client.set(detailKey(viewer, id), null);
145
- for (const entry of recent.values()) {
146
- if (entry.viewer !== viewer || !entry.remove)
147
- continue;
148
- const page = client.getState(entry.options.key).data;
149
- if (page !== undefined)
150
- client.set(entry.options.key, entry.remove(page, id));
151
- }
152
- await refresh(viewer);
153
- },
154
- toggle: async (viewer, id, action, on) => {
155
- const path = `${one(id)}/${action.replace(/^\/+/, '')}`;
156
- return saved(viewer, on ? await config.http().post(path) : await config.http().delete(path));
157
- },
158
- refresh,
159
- };
160
- }
8
+ export { createQueryResource } from '@molecule/app-query';
@@ -1,17 +1,11 @@
1
1
  /**
2
- * Warm the cache ahead of a navigation.
2
+ * Warm the cache ahead of a navigation. `prefetchQuery` itself is framework-neutral and lives in
3
+ * `@molecule/app-query`; this module re-exports it and adds the React hook and link handlers.
3
4
  *
4
5
  * @module
5
6
  */
6
7
  import type { QueryOptions } from '@molecule/app-query';
7
- /**
8
- * Warms the cache for a document, when the connection can afford it (see
9
- * `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
10
- * in-flight document is skipped, and failures are swallowed.
11
- *
12
- * @param options - Key, fetch, freshness.
13
- */
14
- export declare function prefetchQuery<T>(options: QueryOptions<T>): void;
8
+ export { prefetchQuery } from '@molecule/app-query';
15
9
  /**
16
10
  * A stable `prefetch(options)` function for event handlers.
17
11
  *
@@ -1 +1 @@
1
- {"version":3,"file":"usePrefetch.d.ts","sourceRoot":"","sources":["../src/usePrefetch.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAGvD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,CAG/D;AAED;;;;GAIG;AACH,wBAAgB,WAAW,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,CAEnE;AAED,wDAAwD;AACxD,MAAM,WAAW,mBAAmB;IAClC,cAAc,EAAE,MAAM,IAAI,CAAA;IAC1B,OAAO,EAAE,MAAM,IAAI,CAAA;IACnB,YAAY,EAAE,MAAM,IAAI,CAAA;CACzB;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAGpF"}
1
+ {"version":3,"file":"usePrefetch.d.ts","sourceRoot":"","sources":["../src/usePrefetch.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAGvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAEnD;;;;GAIG;AACH,wBAAgB,WAAW,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,CAEnE;AAED,wDAAwD;AACxD,MAAM,WAAW,mBAAmB;IAClC,cAAc,EAAE,MAAM,IAAI,CAAA;IAC1B,OAAO,EAAE,MAAM,IAAI,CAAA;IACnB,YAAY,EAAE,MAAM,IAAI,CAAA;CACzB;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAGpF"}
@@ -1,22 +1,12 @@
1
1
  /**
2
- * Warm the cache ahead of a navigation.
2
+ * Warm the cache ahead of a navigation. `prefetchQuery` itself is framework-neutral and lives in
3
+ * `@molecule/app-query`; this module re-exports it and adds the React hook and link handlers.
3
4
  *
4
5
  * @module
5
6
  */
6
7
  import { useCallback } from 'react';
7
- import { getQueryClient, shouldPrefetch } from '@molecule/app-query';
8
- /**
9
- * Warms the cache for a document, when the connection can afford it (see
10
- * `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
11
- * in-flight document is skipped, and failures are swallowed.
12
- *
13
- * @param options - Key, fetch, freshness.
14
- */
15
- export function prefetchQuery(options) {
16
- if (!shouldPrefetch())
17
- return;
18
- getQueryClient().prefetch(options);
19
- }
8
+ import { prefetchQuery } from '@molecule/app-query';
9
+ export { prefetchQuery } from '@molecule/app-query';
20
10
  /**
21
11
  * A stable `prefetch(options)` function for event handlers.
22
12
  *
@@ -39,6 +39,11 @@ import type { UseQueryResult } from './types.js';
39
39
  * key and every observer. Use `setData(current => next)` for a local cache update. Render
40
40
  * `data` directly; a component-local copy stops observing later server responses. Prefer
41
41
  * `createQueryResource` when the API's reads and writes can share one resource definition.
42
+ * Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
43
+ * so a visible action cannot return early because its initial record is still missing.
44
+ * Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
45
+ * from `@molecule/app-react` or `OptimisticToggleButton` from `@molecule/app-ui-react` to keep
46
+ * their displayed label and queued clicks on the same state while a save finishes.
42
47
  *
43
48
  * @param options - Key, fetch, freshness, and optionally `principal` with
44
49
  * `keepPreviousData`; or `null`.
@@ -1 +1 @@
1
- {"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,qBAAqB,CAAA;AAGnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAuBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,cAAc,CAAC,CAAC,CAAC,CAkG9E"}
1
+ {"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,qBAAqB,CAAA;AAGnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAuBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,cAAc,CAAC,CAAC,CAAC,CAkG9E"}
package/dist/useQuery.js CHANGED
@@ -46,6 +46,11 @@ const IDLE = {
46
46
  * key and every observer. Use `setData(current => next)` for a local cache update. Render
47
47
  * `data` directly; a component-local copy stops observing later server responses. Prefer
48
48
  * `createQueryResource` when the API's reads and writes can share one resource definition.
49
+ * Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
50
+ * so a visible action cannot return early because its initial record is still missing.
51
+ * Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
52
+ * from `@molecule/app-react` or `OptimisticToggleButton` from `@molecule/app-ui-react` to keep
53
+ * their displayed label and queued clicks on the same state while a save finishes.
49
54
  *
50
55
  * @param options - Key, fetch, freshness, and optionally `principal` with
51
56
  * `keepPreviousData`; or `null`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/app-query-react",
3
- "version": "1.6.0",
3
+ "version": "1.6.1",
4
4
  "description": "React hooks for @molecule/app-query — read a cached document synchronously, observe it, and prefetch on intent",
5
5
  "homepage": "https://www.molecule.dev/packages/app-query-react",
6
6
  "type": "module",
@@ -36,11 +36,11 @@
36
36
  "directory": "packages/app/features/query-react"
37
37
  },
38
38
  "peerDependencies": {
39
- "@molecule/app-query": "^1.1.0",
39
+ "@molecule/app-query": "^1.2.0",
40
40
  "react": "^18.0.0 || ^19.0.0"
41
41
  },
42
42
  "devDependencies": {
43
- "@molecule/app-query": "1.1.3",
43
+ "@molecule/app-query": "1.2.0",
44
44
  "@molecule/app-query-memory": "1.0.5",
45
45
  "@molecule/app-query-tanstack": "1.0.5",
46
46
  "@types/node": "26.6.5",