@molecule/app-query-solid 0.0.0-stage → 0.0.1-stage

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Solid primitives for `@molecule/app-query`.
3
+ *
4
+ * **Load page data with {@link useQuery}, not `fetch` inside a `createEffect`.** A hand-written
5
+ * load effect that cancels its request on cleanup (a `cancelled` flag, or an `AbortController`)
6
+ * re-runs its cleanup on EVERY re-run whenever one of its tracked dependencies is a function
7
+ * created inline each run — `const [messages, setError] = useApiErrors()` returning arrow
8
+ * functions is the usual source. The effect's own guard (`if (loaded === slug) return`) then
9
+ * returns without refetching, so the response is discarded whenever it arrives after a
10
+ * re-run: always on a remote server, never on localhost, which is why the page passes locally
11
+ * and fails on the live URL. `useQuery` subscribes once per key, keeps its request stable
12
+ * across updates, and aborts it only when the key changes or the page unmounts.
13
+ *
14
+ * {@link useQuery} observes one document from the app's shared cache and
15
+ * returns cached data on the first read; {@link usePrefetch} and
16
+ * {@link intentPrefetchProps} warm a document when a person is about to
17
+ * open it. Together they make a detail page open with no loading state.
18
+ *
19
+ * This package needs a bonded client: install `@molecule/app-query` with a bond
20
+ * (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
21
+ * `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
22
+ *
23
+ * **Keep displayed records on the query cache.** Render `query.data` directly. A custom
24
+ * mutation handler publishes its saved response with `query.setData(saved)`; every observer
25
+ * and the next visit receive it, and subsequent refreshes still update the view. A local
26
+ * signal copy hydrated only once per record hides later query answers. Editable form
27
+ * drafts remain local until saved. Prefer {@link createQueryResource} for a complete resource;
28
+ * its writes already publish the response and refresh its tracked collections.
29
+ *
30
+ * @example
31
+ * ```tsx
32
+ * import { Match, Show, Switch } from 'solid-js'
33
+ * import { getClient, isHttpError } from '@molecule/app-http'
34
+ * import { t } from '@molecule/app-i18n'
35
+ * import { intentPrefetchProps, useQuery } from '@molecule/app-query-solid'
36
+ *
37
+ * interface PackageDocument {
38
+ * name: string
39
+ * description: string
40
+ * }
41
+ *
42
+ * const packageQuery = (name: string) => ({
43
+ * key: ['package', name],
44
+ * fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
45
+ * try {
46
+ * const response = await getClient().get<PackageDocument | null>(
47
+ * `/data/packages/${encodeURIComponent(name)}.json`,
48
+ * { signal },
49
+ * )
50
+ * return response.data
51
+ * } catch (error) {
52
+ * if (isHttpError(error) && error.status === 404) return null
53
+ * throw error
54
+ * }
55
+ * },
56
+ * })
57
+ *
58
+ * function PackageLink(props: { name: string }) {
59
+ * return (
60
+ * <a href={`/packages/${props.name}`} {...intentPrefetchProps(packageQuery(props.name))}>
61
+ * {props.name}
62
+ * </a>
63
+ * )
64
+ * }
65
+ *
66
+ * function PackagePage(props: { name: string }) {
67
+ * // The options are an accessor, so a changed name (route param, input) re-keys
68
+ * // the observer on the same mounted component, the way React re-renders useQuery.
69
+ * const query = useQuery(() => packageQuery(props.name))
70
+ * const loaded = (): PackageDocument | null => {
71
+ * if (query.status === 'error') return null
72
+ * if (query.status === 'idle' || query.status === 'loading') return null
73
+ * if (query.data === undefined || query.data === null) return null
74
+ * return query.data
75
+ * }
76
+ * return (
77
+ * <Switch>
78
+ * <Match when={query.status === 'error'}>
79
+ * <p role="alert">
80
+ * {t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' })}
81
+ * </p>
82
+ * </Match>
83
+ * <Match when={query.status === 'idle' || query.status === 'loading'}>
84
+ * <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
85
+ * </Match>
86
+ * <Match when={query.data === undefined || query.data === null}>
87
+ * <p>{t('packages.notFound', undefined, { defaultValue: 'Package not found.' })}</p>
88
+ * </Match>
89
+ * <Match when={loaded()} keyed>
90
+ * {(doc) => (
91
+ * <article>
92
+ * <h1>{doc.name}</h1>
93
+ * <p>{doc.description}</p>
94
+ * </article>
95
+ * )}
96
+ * </Match>
97
+ * </Switch>
98
+ * )
99
+ * }
100
+ * ```
101
+ *
102
+ * @example
103
+ * A list whose page and filter live in the URL: derive the key from the route and pass
104
+ * `keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
105
+ * until the next page answers. The app's HTTP client sends the session, so the viewer is part of
106
+ * what the answer depends on: key on it and pass the same value as `principal` — an account
107
+ * switch then drops the previous account's rows at once. Pass `null` while the session is still
108
+ * being restored (`status === 'loading'`; the HTTP client holds the request until then anyway),
109
+ * so restoring a session never swaps a key that already rendered rows.
110
+ *
111
+ * ```tsx
112
+ * import { For, Show } from 'solid-js'
113
+ * import { unwrapList } from '@molecule/app-http'
114
+ * import { useAuth, useHttpClient, useListRoute, useTranslation } from '@molecule/app-solid'
115
+ * import { useQuery } from '@molecule/app-query-solid'
116
+ *
117
+ * interface Invoice {
118
+ * id: string
119
+ * number: string
120
+ * }
121
+ *
122
+ * function InvoiceList() {
123
+ * const http = useHttpClient()
124
+ * const { t } = useTranslation()
125
+ * const { status, user } = useAuth<{ id: string }>()
126
+ * const list = useListRoute({ pageSize: 20, filters: { status: {} } })
127
+ * const viewer = (): string => (user() ? String(user().id) : 'anonymous')
128
+ * const query = useQuery(
129
+ * () =>
130
+ * status() === 'loading' || !list.canLoad
131
+ * ? null
132
+ * : {
133
+ * key: ['invoices', viewer(), list.filters, list.page],
134
+ * principal: viewer(),
135
+ * keepPreviousData: true,
136
+ * fetch: async (signal: AbortSignal) =>
137
+ * unwrapList<Invoice>(
138
+ * await http.get('/api/invoices', {
139
+ * signal,
140
+ * params: { ...list.filters, limit: list.pageSize, offset: list.offset },
141
+ * }),
142
+ * ),
143
+ * },
144
+ * )
145
+ *
146
+ * // Status renders outside the item list (it is not an item), and the empty state
147
+ * // describes only the key on screen, never a retained previous page.
148
+ * return (
149
+ * <section>
150
+ * <Show when={query.isFetching || status() === 'loading'}>
151
+ * <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
152
+ * </Show>
153
+ * <Show when={query.status === 'error'}>
154
+ * <p role="alert">
155
+ * {t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' })}
156
+ * </p>
157
+ * </Show>
158
+ * <ul>
159
+ * <For each={query.data ?? []}>
160
+ * {(invoice) => (
161
+ * <li>
162
+ * <a href={`/invoices/${invoice.id}`}>{invoice.number}</a>
163
+ * </li>
164
+ * )}
165
+ * </For>
166
+ * </ul>
167
+ * <Show when={!query.isPreviousData && query.data?.length === 0}>
168
+ * <p>{t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' })}</p>
169
+ * </Show>
170
+ * <a href={list.href({ page: list.page + 1 })}>
171
+ * {t('common.next', undefined, { defaultValue: 'Next page' })}
172
+ * </a>
173
+ * </section>
174
+ * )
175
+ * }
176
+ * ```
177
+ *
178
+ * @example
179
+ * A mutation or a failed load has to change a page that is ALREADY mounted, and
180
+ * the cache never starts that request by itself: `set()` paints a mutation's own
181
+ * response, `invalidate()` marks what it affects for the next mount, and an
182
+ * explicit `fetch()` retries into the mounted page.
183
+ *
184
+ * ```tsx
185
+ * import { getClient } from '@molecule/app-http'
186
+ * import { t } from '@molecule/app-i18n'
187
+ * import { getQueryClient } from '@molecule/app-query'
188
+ *
189
+ * // The key names what the document actually depends on — here the signed-in
190
+ * // principal, the filter and the page. Another principal's feed is a
191
+ * // different document, so an invalidation scoped to this one leaves it alone.
192
+ * const feedKey = (principal: string, filter: string, page: number) =>
193
+ * ['feed', principal, filter, page] as const
194
+ *
195
+ * const feedOptions = (principal: string, filter: string, page: number) => ({
196
+ * key: feedKey(principal, filter, page),
197
+ * fetch: async (signal: AbortSignal) =>
198
+ * (await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
199
+ * })
200
+ *
201
+ * async function setFollowing(principal: string, authorId: string, follow: boolean) {
202
+ * const client = getQueryClient()
203
+ * const http = getClient()
204
+ * const { data: body } = follow
205
+ * ? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
206
+ * : await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
207
+ * // The response IS the document: paint it now, with no second round trip.
208
+ * // (If it were only a count or a flag, skip set() and invalidate() instead.)
209
+ * client.set(feedKey(principal, 'following', 1), body.feed)
210
+ * // Future reads of every feed this principal owns are stale.
211
+ * client.invalidate(['feed', principal])
212
+ * }
213
+ *
214
+ * function Retry(props: { principal: string }) {
215
+ * return (
216
+ * <button
217
+ * onClick={() => {
218
+ * // invalidate() alone would leave the mounted page on its error;
219
+ * // an explicit fetch retries into it. useQuery shows the outcome.
220
+ * void getQueryClient()
221
+ * .fetch(feedOptions(props.principal, 'following', 1))
222
+ * // The mounted useQuery observer presents this failure via status/error.
223
+ * .catch((_error) => {})
224
+ * }}
225
+ * >
226
+ * {t('common.retry', undefined, { defaultValue: 'Retry' })}
227
+ * </button>
228
+ * )
229
+ * }
230
+ * ```
231
+ *
232
+ * @example
233
+ * One API resource described once, for every page that reads or changes it.
234
+ * `createQueryResource` returns the list and detail reads as `useQuery` options and the writes
235
+ * as functions that put the server's record into the cache and fetch the lists on screen again,
236
+ * so a page never mirrors a response into a local signal. A flag the API models as a sub-path
237
+ * (`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
238
+ * record and is the `commit` of `useOptimisticValue`.
239
+ *
240
+ * ```tsx
241
+ * import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
242
+ * import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-solid'
243
+ * import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-solid'
244
+ *
245
+ * interface Invoice {
246
+ * id: string
247
+ * number: string
248
+ * flagged: boolean
249
+ * }
250
+ *
251
+ * export const invoices = createQueryResource<Invoice>({
252
+ * name: 'invoices',
253
+ * path: '/invoices',
254
+ * http: getClient,
255
+ * readList: (response) => unwrapList<Invoice>(response),
256
+ * readOne: (response) => unwrapSingle<Invoice>(response),
257
+ * })
258
+ *
259
+ * function InvoicePage(props: { id: string }) {
260
+ * const { user } = useAuth<{ id: string }>()
261
+ * const { t } = useTranslation()
262
+ * const viewer = (): string => {
263
+ * const current = user()
264
+ * return current ? String(current.id) : 'anonymous'
265
+ * }
266
+ * const query = useQuery(() => invoices.detail(viewer(), props.id))
267
+ * return (
268
+ * <QueryContent
269
+ * query={query}
270
+ * pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
271
+ * missing={<p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>}
272
+ * error={() => <p role="alert">{t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}</p>}
273
+ * >
274
+ * {(invoice) => <FlagButton invoice={invoice} viewer={viewer()} />}
275
+ * </QueryContent>
276
+ * )
277
+ * }
278
+ *
279
+ * function FlagButton(props: { invoice: Invoice; viewer: string }) {
280
+ * const { t } = useTranslation()
281
+ * const flag = useOptimisticValue({
282
+ * value: props.invoice.flagged,
283
+ * commit: async (on) => (await invoices.toggle(props.viewer, props.invoice.id, 'flag', on)).flagged,
284
+ * })
285
+ * return (
286
+ * <button type="button" aria-pressed={flag.value()} onClick={() => flag.update((on) => !on)}>
287
+ * {flag.value()
288
+ * ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
289
+ * : t('invoice.flag', undefined, { defaultValue: 'Flag' })} {props.invoice.number}
290
+ * </button>
291
+ * )
292
+ * }
293
+ * ```
294
+ *
295
+ * @example
296
+ * A pager needs the whole response, including its total. Keep that read on the same resource
297
+ * as its mutations, including alternate list paths; a separate hand-written `QueryOptions`
298
+ * is outside the resource's refresh tracking.
299
+ *
300
+ * ```typescript
301
+ * import { getClient } from '@molecule/app-http'
302
+ * import { createQueryResource } from '@molecule/app-query-solid'
303
+ *
304
+ * interface TicketPage { tickets: { id: string; subject: string }[]; total: number }
305
+ * const tickets = createQueryResource<TicketPage['tickets'][number]>({
306
+ * name: 'tickets', path: '/tickets', http: getClient,
307
+ * readOne: (response) => response.data as TicketPage['tickets'][number],
308
+ * })
309
+ * const page = tickets.listPage('agent-1', { limit: 10, offset: 20 },
310
+ * (response) => response.data as TicketPage)
311
+ * // useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
312
+ * // and tickets.refresh('agent-1') refresh this page too.
313
+ * // A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
314
+ * // Use one canonical page reader per path; list() still returns only its own rows.
315
+ * // For immediate deletion from an opaque page, add a fifth argument:
316
+ * // (page, id) => {
317
+ * // const rows = page.tickets.filter((row) => String(row.id) !== id)
318
+ * // return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
319
+ * // }
320
+ * ```
321
+ * A resource mutation also waits out a pre-mutation list request before fetching again;
322
+ * joining that older in-flight read alone would leave the new record absent.
323
+ * Successful deletion removes a row immediately, including one just created through the
324
+ * resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit
325
+ * successful create can recreate the identity. Opaque listPage envelopes need their own
326
+ * removeFromPage adapter; no row or total property is guessed.
327
+ *
328
+ * @remarks
329
+ * - **`useQuery` reads the cache synchronously on the first render.** A
330
+ * document prefetched from a hovered link, or seeded with `client.set()`
331
+ * from a server-rendered JSON island, renders at once — no spinner, no
332
+ * layout shift. Render loading from `status === 'idle' || status === 'loading'`;
333
+ * `undefined` data can also accompany a completed error. A completed `null`
334
+ * response is missing, not pending. The detail example treats only HTTP 404
335
+ * or a successful null response as missing; other errors stay load failures.
336
+ * The app's bonded HTTP client rejects non-2xx responses. Native `fetch`
337
+ * resolves them, so a custom fetcher must check `response.ok` before JSON.
338
+ * - **A component body runs once in Solid: pass the options as an accessor.**
339
+ * `useQuery(() => packageQuery(props.name))` follows a changed name (route
340
+ * param, input, parent state) on the same mounted hook, the way React
341
+ * re-renders `useQuery` with a new options object. Options built once from
342
+ * props are read once — a later prop change would not re-key the observer.
343
+ * - **Mount a detail region and its actions only after its initial document arrives.**
344
+ * A visible container is not a loaded document: a caller may wait for that container and
345
+ * read its text once, or click its button, while `data` is still undefined. Put the loading
346
+ * message outside the detail region, as in `PackagePage` above. Keep record-dependent
347
+ * controls absent or natively disabled until the record exists; returning early inside
348
+ * an enabled click handler loses that click. `client.set()` protects a cache mutation
349
+ * from an older read, but cannot recover a click whose handler never sent the mutation.
350
+ * - **The key is the identity.** Building `options` inside the accessor is
351
+ * fine; the hook resubscribes only when the key's value changes, not when
352
+ * the `fetch` closure does.
353
+ * - **A key change normally resets to the new key's state.** For a list's own
354
+ * page/filter/view change, opt into `keepPreviousData` with a `principal`;
355
+ * `isPreviousData` tells you the rows on screen belong to the key you just
356
+ * left. A completed response (including an empty list) replaces them, and a
357
+ * changed principal drops them, so an account switch never shows the previous
358
+ * account's rows. Do not emulate this with a local signal mirror of the
359
+ * query data — that mirror is what serves stale rows under a new page, or
360
+ * blanks the list on an update.
361
+ * - **The key names the viewer whenever the answer can depend on it.** The
362
+ * app's HTTP client sends the session, so the server may filter or
363
+ * personalize even a list that guests can see (a `favorited` or `following`
364
+ * flag), and the cache serves a key's document to whoever observes it,
365
+ * across sign-in and sign-out. Key such a list on the viewer
366
+ * (`user() ? String(user().id) : 'anonymous'`), pass the same value as
367
+ * `principal`, and pass `null` while the session is still being restored
368
+ * (`status === 'loading'`; the HTTP client holds the request until then
369
+ * anyway), so restoring a session never swaps a key that already rendered
370
+ * rows. A viewer-free key with `principal: 'public'` is only for an endpoint
371
+ * that answers every viewer the same. A protected `useListRoute` view also
372
+ * passes `null` while `canLoad` is false.
373
+ * - **Render loading, empty and error status outside the item list**, and never
374
+ * give a placeholder the item's own class or element shape: a list read by
375
+ * the item class (or by `:first-child`) must contain only real items. An
376
+ * empty array is a loaded empty state, not a missing response; render it
377
+ * only when `isPreviousData` is not set, because a retained document belongs
378
+ * to the key you just left.
379
+ * - `intentPrefetchProps` spreads three handlers onto a link. It is a plain
380
+ * function (not a primitive), so it works inside `<For>` too.
381
+ * - Prefetching respects the browser's data-saver setting and skips 2G
382
+ * connections (`shouldPrefetch()` in the core) — do not bypass that for
383
+ * "important" links; the person can still click.
384
+ * - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
385
+ * entry and updates every observer of that key. After a mutation whose response is not the
386
+ * whole document, `await query.refetch()` reloads the displayed list. It resolves with the
387
+ * resulting state (including `status: 'error'` on failure); a disabled query stays idle.
388
+ * Prefer `client.set(key, response)` when the mutation already returned the whole document.
389
+ * - Errors are not thrown from the hook; read `status === 'error'` and
390
+ * `error`. `client.invalidate()` does NOT refetch a mounted page — it only
391
+ * marks documents stale, so the page keeps its error (or its old document)
392
+ * until the app retries with `client.fetch(options)` or the page subscribes
393
+ * again (a key change or a re-mount).
394
+ * - After a mutation, `client.set(key, response)` paints the server's own
395
+ * answer at once and supersedes an older fetch already in flight for that
396
+ * key, so its response cannot undo the mutation. An existing `fetch()` caller
397
+ * still settles independently of the cache write; read `client.get(key)` for the newest document.
398
+ * `client.invalidate(prefix)` marks the affected reads stale for their next
399
+ * mount. Which key and which scope is the app's decision: the cache does not
400
+ * infer it from auth or form state.
401
+ *
402
+ * Render resource-dependent lists and controls through {@link QueryContent}. Its child function
403
+ * receives only loaded, non-null data; loading and error content never mount item actions.
404
+ * It renders cached content during refresh and treats an empty list, false and zero as data.
405
+ * Put the list, or the record's own container (its card, header or profile block), inside the
406
+ * child and every status line (loading, error, `isFetching` refresh) beside it, never inside it:
407
+ * a reader that finds the container and reads its paragraph must read the record, not "Loading…".
408
+ *
409
+ * ```tsx
410
+ * <QueryContent query={query} pending={<p role="status">{loadingLabel}</p>}
411
+ * missing={<p>{missingLabel}</p>} error={() => <p role="alert">{errorLabel}</p>}>
412
+ * {(record) => <RecordActions record={record} />}
413
+ * </QueryContent>
414
+ * ```
415
+ *
416
+ * Keep every resource identity in the query key. A boundary cannot correct a query that supplies
417
+ * another record's cached data. For a list, map real rows inside the child; never style a status
418
+ * placeholder as a row. QueryContent is headless and owns no translations or styling.
419
+ *
420
+ * @module
421
+ */
422
+ export * from './query-content.js';
423
+ export * from './resource.js';
424
+ export * from './types.js';
425
+ export * from './use-prefetch.js';
426
+ export * from './use-query.js';
427
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoaG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,mBAAmB,CAAA;AACjC,cAAc,gBAAgB,CAAA"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Render resource-dependent content only after its document exists — the Solid
3
+ * counterpart of `QueryContent` in `@molecule/app-query-react`, with the same
4
+ * props and the same DOM. The component is headless: it owns no translations
5
+ * and no styling, and renders exactly the chosen branch.
6
+ * @module
7
+ */
8
+ import { type JSX } from 'solid-js';
9
+ import type { QueryContentProps } from './types.js';
10
+ /**
11
+ * The loaded-data branch receives a non-null document. Pending, failed initial reads and
12
+ * missing records never mount that branch, so its actions cannot swallow an early click.
13
+ * Cached data remains mounted during refresh, including a failed refresh. Status fallbacks
14
+ * belong outside the list or record container rendered by `children`, and so does a refresh
15
+ * line; the default fallbacks render nothing.
16
+ *
17
+ * @param props - Query state, loaded content and optional status fallbacks.
18
+ * @returns Loaded content or the appropriate fallback, switching as the state changes.
19
+ */
20
+ export declare function QueryContent<T>(props: QueryContentProps<T>): JSX.Element;
21
+ //# sourceMappingURL=query-content.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-content.d.ts","sourceRoot":"","sources":["../src/query-content.tsx"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAc,KAAK,GAAG,EAAE,MAAM,UAAU,CAAA;AAE/C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAEnD;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,KAAK,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,OAAO,CAexE"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Render resource-dependent content only after its document exists — the Solid
3
+ * counterpart of `QueryContent` in `@molecule/app-query-react`, with the same
4
+ * props and the same DOM. The component is headless: it owns no translations
5
+ * and no styling, and renders exactly the chosen branch.
6
+ * @module
7
+ */
8
+ import { createMemo } from 'solid-js';
9
+ /**
10
+ * The loaded-data branch receives a non-null document. Pending, failed initial reads and
11
+ * missing records never mount that branch, so its actions cannot swallow an early click.
12
+ * Cached data remains mounted during refresh, including a failed refresh. Status fallbacks
13
+ * belong outside the list or record container rendered by `children`, and so does a refresh
14
+ * line; the default fallbacks render nothing.
15
+ *
16
+ * @param props - Query state, loaded content and optional status fallbacks.
17
+ * @returns Loaded content or the appropriate fallback, switching as the state changes.
18
+ */
19
+ export function QueryContent(props) {
20
+ // The branch accessor returns the rendered branch (a node, `null`, or what a
21
+ // render-function prop returned); Solid re-reads it as the state changes.
22
+ const branch = createMemo(() => {
23
+ const query = props.query;
24
+ const data = query.data;
25
+ if (data === undefined) {
26
+ return query.status === 'error' && props.error
27
+ ? props.error(query.error)
28
+ : (props.pending ?? null);
29
+ }
30
+ if (data === null)
31
+ return props.missing ?? null;
32
+ return props.children(data);
33
+ });
34
+ return <>{branch}</>;
35
+ }
36
+ //# sourceMappingURL=query-content.jsx.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-content.jsx","sourceRoot":"","sources":["../src/query-content.tsx"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAY,MAAM,UAAU,CAAA;AAI/C;;;;;;;;;GASG;AACH,MAAM,UAAU,YAAY,CAAI,KAA2B;IACzD,6EAA6E;IAC7E,0EAA0E;IAC1E,MAAM,MAAM,GAAG,UAAU,CAAc,GAAG,EAAE;QAC1C,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAA;QACzB,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAA;QACvB,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,KAAK,CAAC,MAAM,KAAK,OAAO,IAAI,KAAK,CAAC,KAAK;gBAC5C,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC;gBAC1B,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,CAAA;QAC7B,CAAC;QACD,IAAI,IAAI,KAAK,IAAI;YAAE,OAAO,KAAK,CAAC,OAAO,IAAI,IAAI,CAAA;QAC/C,OAAO,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;IAC7B,CAAC,CAAC,CAAA;IACF,OAAO,EAAE,CAAC,MAAM,CAAC,GAAG,CAAA;AACtB,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
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
+ * Solid pages import it next to `useQuery` and `QueryContent`.
5
+ *
6
+ * @module
7
+ */
8
+ export type { QueryResource, QueryResourceConfig, ResourceHttp, ResourceResponse, } from '@molecule/app-query';
9
+ export { createQueryResource } from '@molecule/app-query';
10
+ //# sourceMappingURL=resource.d.ts.map
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,9 @@
1
+ /**
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
+ * Solid pages import it next to `useQuery` and `QueryContent`.
5
+ *
6
+ * @module
7
+ */
8
+ export { createQueryResource } from '@molecule/app-query';
9
+ //# sourceMappingURL=resource.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource.js","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAQH,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAA"}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Solid query observer contracts — the counterparts of the types
3
+ * `@molecule/app-query-react` exports, with the node-valued props typed as
4
+ * Solid `JSX`.
5
+ * @module
6
+ */
7
+ import type { JSX } from 'solid-js';
8
+ import type { QueryState } from '@molecule/app-query';
9
+ /**
10
+ * A mounted query's state and its explicit cache and refresh actions. The state
11
+ * fields read as plain values at read time (each reads the observer's current
12
+ * state), so a JSX binding that reads them re-renders when the document
13
+ * changes, and a test can snapshot the object at any moment.
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
+ /** State from useQuery, or any compatible query observer. */
38
+ query: Pick<QueryState<T>, 'data' | 'status' | 'error'>;
39
+ /** Mounted only with a real document, including false, zero and an empty list. */
40
+ children: (data: NonNullable<T>) => JSX.Element;
41
+ /** Initial idle/loading content. Render a status node, never a fake item or action. */
42
+ pending?: JSX.Element;
43
+ /** Content for a loaded null record. Null is distinct from an unfinished request. */
44
+ missing?: JSX.Element;
45
+ /** A failed initial read. Cached data stays visible if its refresh fails. */
46
+ error?: (error: unknown) => JSX.Element;
47
+ }
48
+ //# 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,GAAG,EAAE,MAAM,UAAU,CAAA;AAEnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAErD;;;;;GAKG;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,6DAA6D;IAC7D,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,CAAC,CAAA;IACvD,kFAAkF;IAClF,QAAQ,EAAE,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,OAAO,CAAA;IAC/C,uFAAuF;IACvF,OAAO,CAAC,EAAE,GAAG,CAAC,OAAO,CAAA;IACrB,qFAAqF;IACrF,OAAO,CAAC,EAAE,GAAG,CAAC,OAAO,CAAA;IACrB,6EAA6E;IAC7E,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,GAAG,CAAC,OAAO,CAAA;CACxC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,31 @@
1
+ /**
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 Solid primitive and link
4
+ * handlers.
5
+ *
6
+ * @module
7
+ */
8
+ import type { QueryOptions } from '@molecule/app-query';
9
+ export { prefetchQuery } from '@molecule/app-query';
10
+ /**
11
+ * A stable `prefetch(options)` function for event handlers.
12
+ *
13
+ * @returns The prefetch function.
14
+ */
15
+ export declare function usePrefetch(): <T>(options: QueryOptions<T>) => void;
16
+ /** The handlers {@link intentPrefetchProps} returns. */
17
+ export interface IntentPrefetchProps {
18
+ onPointerEnter: () => void;
19
+ onFocus: () => void;
20
+ onTouchStart: () => void;
21
+ }
22
+ /**
23
+ * Event handlers that warm a document at the first sign of intent: the
24
+ * pointer arriving, keyboard focus, or a touch starting. Spread them onto a
25
+ * link: `<a {...intentPrefetchProps(packageQuery(name))} />`.
26
+ *
27
+ * @param options - Key, fetch, freshness.
28
+ * @returns The handlers.
29
+ */
30
+ export declare function intentPrefetchProps<T>(options: QueryOptions<T>): IntentPrefetchProps;
31
+ //# sourceMappingURL=use-prefetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-prefetch.d.ts","sourceRoot":"","sources":["../src/use-prefetch.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,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"}
@@ -0,0 +1,30 @@
1
+ /**
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 Solid primitive and link
4
+ * 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.
12
+ *
13
+ * @returns The prefetch function.
14
+ */
15
+ export function usePrefetch() {
16
+ return prefetchQuery;
17
+ }
18
+ /**
19
+ * Event handlers that warm a document at the first sign of intent: the
20
+ * pointer arriving, keyboard focus, or a touch starting. Spread them onto a
21
+ * link: `<a {...intentPrefetchProps(packageQuery(name))} />`.
22
+ *
23
+ * @param options - Key, fetch, freshness.
24
+ * @returns The handlers.
25
+ */
26
+ export function intentPrefetchProps(options) {
27
+ const go = () => prefetchQuery(options);
28
+ return { onPointerEnter: go, onFocus: go, onTouchStart: go };
29
+ }
30
+ //# sourceMappingURL=use-prefetch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-prefetch.js","sourceRoot":"","sources":["../src/use-prefetch.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAEnD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAEnD;;;;GAIG;AACH,MAAM,UAAU,WAAW;IACzB,OAAO,aAAa,CAAA;AACtB,CAAC;AASD;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAAI,OAAwB;IAC7D,MAAM,EAAE,GAAG,GAAS,EAAE,CAAC,aAAa,CAAC,OAAO,CAAC,CAAA;IAC7C,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,YAAY,EAAE,EAAE,EAAE,CAAA;AAC9D,CAAC"}