@molecule/app-query-angular 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/LICENSE +202 -0
- package/README.md +979 -2
- package/dist/index.d.ts +464 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +464 -0
- package/dist/index.js.map +1 -0
- package/dist/query-content.component.d.ts +73 -0
- package/dist/query-content.component.d.ts.map +1 -0
- package/dist/query-content.component.js +148 -0
- package/dist/query-content.component.js.map +1 -0
- package/dist/resource.d.ts +11 -0
- package/dist/resource.d.ts.map +1 -0
- package/dist/resource.js +10 -0
- package/dist/resource.js.map +1 -0
- package/dist/types.d.ts +70 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/use-prefetch.d.ts +46 -0
- package/dist/use-prefetch.d.ts.map +1 -0
- package/dist/use-prefetch.js +31 -0
- package/dist/use-prefetch.js.map +1 -0
- package/dist/use-query.d.ts +72 -0
- package/dist/use-query.d.ts.map +1 -0
- package/dist/use-query.js +265 -0
- package/dist/use-query.js.map +1 -0
- package/package.json +73 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Angular hooks for `@molecule/app-query` — the Angular counterpart of
|
|
3
|
+
* `@molecule/app-query-react`, with the same exports, the same contracts and
|
|
4
|
+
* the same rendered result for the same input.
|
|
5
|
+
*
|
|
6
|
+
* **Load page data with {@link useQuery}, not a hand-written load effect.** An
|
|
7
|
+
* effect that cancels its own request on cleanup (a `cancelled` flag, or an
|
|
8
|
+
* `AbortController`) re-runs its cleanup whenever one of its tracked
|
|
9
|
+
* dependencies is a function created inline each run — and its own guard then
|
|
10
|
+
* returns without refetching, so the response is discarded whenever it arrives
|
|
11
|
+
* after a re-render: always on a remote server, never on localhost, which is
|
|
12
|
+
* why the page passes locally and fails on the live URL. `useQuery`
|
|
13
|
+
* subscribes once per key, keeps its request stable across template refreshes,
|
|
14
|
+
* and aborts it only when the key changes or the component is destroyed.
|
|
15
|
+
*
|
|
16
|
+
* {@link useQuery} observes one document from the app's shared cache and
|
|
17
|
+
* returns cached data on the first read; {@link usePrefetch} and
|
|
18
|
+
* {@link intentPrefetchProps} warm a document when a person is about to open
|
|
19
|
+
* it. Together they make a detail page open with no loading state.
|
|
20
|
+
*
|
|
21
|
+
* This package needs a bonded client: install `@molecule/app-query` with a bond
|
|
22
|
+
* (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the
|
|
23
|
+
* bond's `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/`
|
|
24
|
+
* does this). Call the hooks in an injection context — a component field
|
|
25
|
+
* initializer or constructor. A component whose options change with its own
|
|
26
|
+
* state passes a `Signal` of options (an `input()`/`computed()`), and every
|
|
27
|
+
* change is followed on the same instance, the way React re-renders `useQuery`
|
|
28
|
+
* with a new options object.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* import { Component, OnChanges, computed, input } from '@angular/core'
|
|
33
|
+
* import { getClient, isHttpError } from '@molecule/app-http'
|
|
34
|
+
* import { t } from '@molecule/app-i18n'
|
|
35
|
+
* import { intentPrefetchProps, useQuery } from '@molecule/app-query-angular'
|
|
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
|
+
* // A link warms its document at the first sign of intent: the handlers
|
|
59
|
+
* // `intentPrefetchProps` returns are named after the DOM events an Angular
|
|
60
|
+
* // template binds, so a component puts them on its host listeners.
|
|
61
|
+
* @Component({
|
|
62
|
+
* selector: 'a[mol-package-link]',
|
|
63
|
+
* template: '<ng-content></ng-content>',
|
|
64
|
+
* inputs: ['name'],
|
|
65
|
+
* host: {
|
|
66
|
+
* '(pointerenter)': 'warm.pointerenter()',
|
|
67
|
+
* '(focus)': 'warm.focus()',
|
|
68
|
+
* '(touchstart)': 'warm.touchstart()',
|
|
69
|
+
* },
|
|
70
|
+
* })
|
|
71
|
+
* export class PackageLink implements OnChanges {
|
|
72
|
+
* name = ''
|
|
73
|
+
*
|
|
74
|
+
* warm = intentPrefetchProps(packageQuery(this.name))
|
|
75
|
+
*
|
|
76
|
+
* ngOnChanges(): void {
|
|
77
|
+
* this.warm = intentPrefetchProps(packageQuery(this.name))
|
|
78
|
+
* }
|
|
79
|
+
* }
|
|
80
|
+
*
|
|
81
|
+
* // The page reads the document synchronously when it is cached (a warmed page
|
|
82
|
+
* // opens with no loading state) and follows a changed name on the same
|
|
83
|
+
* // instance. Until a name arrives, `null` observes nothing.
|
|
84
|
+
* @Component({
|
|
85
|
+
* selector: 'mol-package-page',
|
|
86
|
+
* template: `
|
|
87
|
+
* @if (query.status === 'error') {
|
|
88
|
+
* <p role="alert">{{ t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' }) }}</p>
|
|
89
|
+
* } @else if (query.status === 'idle' || query.status === 'loading') {
|
|
90
|
+
* <p role="status">{{ t('common.loading', undefined, { defaultValue: 'Loading…' }) }}</p>
|
|
91
|
+
* } @else if (query.data === null) {
|
|
92
|
+
* <p>{{ t('packages.notFound', undefined, { defaultValue: 'Package not found.' }) }}</p>
|
|
93
|
+
* } @else {
|
|
94
|
+
* <article><h1>{{ query.data?.name }}</h1><p>{{ query.data?.description }}</p></article>
|
|
95
|
+
* }
|
|
96
|
+
* `,
|
|
97
|
+
* })
|
|
98
|
+
* export class PackagePage {
|
|
99
|
+
* // Expose the i18n function so every template binding re-reads it.
|
|
100
|
+
* protected readonly t = t
|
|
101
|
+
* readonly name = input('')
|
|
102
|
+
*
|
|
103
|
+
* readonly query = useQuery<PackageDocument | null>(
|
|
104
|
+
* computed(() => (this.name() ? packageQuery(this.name()) : null)),
|
|
105
|
+
* )
|
|
106
|
+
* }
|
|
107
|
+
*
|
|
108
|
+
* // `<a [mol-package-link][name]="next" [href]="href">{{ next }}</a>` warms the
|
|
109
|
+
* // next package while the reader hovers, focuses or touches the link, so the
|
|
110
|
+
* // page it opens renders from cache with no loading state.
|
|
111
|
+
* ```
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* A list whose page and filter live in the URL: derive the key from the route
|
|
115
|
+
* (a `computed` over the route inputs) and pass `keepPreviousData` with a
|
|
116
|
+
* `principal`, so a page/filter change keeps the rows already on screen until
|
|
117
|
+
* the next page answers. The app's HTTP client sends the session, so the viewer
|
|
118
|
+
* is part of what the answer depends on: key on it and pass the same value as
|
|
119
|
+
* `principal` — an account switch then drops the previous account's rows at
|
|
120
|
+
* once. Pass `null` while the session is still being restored (`status ===
|
|
121
|
+
* 'loading'`; the HTTP client holds the request until then anyway), so
|
|
122
|
+
* restoring a session never swaps a key that already rendered rows.
|
|
123
|
+
*
|
|
124
|
+
* ```typescript
|
|
125
|
+
* import { Component, computed, input } from '@angular/core'
|
|
126
|
+
* import { getClient, unwrapList } from '@molecule/app-http'
|
|
127
|
+
* import { t } from '@molecule/app-i18n'
|
|
128
|
+
* import { useQuery } from '@molecule/app-query-angular'
|
|
129
|
+
*
|
|
130
|
+
* interface Invoice {
|
|
131
|
+
* id: string
|
|
132
|
+
* number: string
|
|
133
|
+
* }
|
|
134
|
+
*
|
|
135
|
+
* @Component({
|
|
136
|
+
* selector: 'mol-invoice-list',
|
|
137
|
+
* template: `
|
|
138
|
+
* @if (query.status === 'loading' || query.isFetching) {
|
|
139
|
+
* <p role="status">{{ t('common.loading', undefined, { defaultValue: 'Loading…' }) }}</p>
|
|
140
|
+
* }
|
|
141
|
+
* @if (query.status === 'error') {
|
|
142
|
+
* <p role="alert">{{ t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' }) }}</p>
|
|
143
|
+
* }
|
|
144
|
+
* <ul>
|
|
145
|
+
* @for (invoice of query.data ?? []; track invoice.id) {
|
|
146
|
+
* <li><a [href]="'/invoices/' + invoice.id">{{ invoice.number }}</a></li>
|
|
147
|
+
* }
|
|
148
|
+
* </ul>
|
|
149
|
+
* @if (!query.isPreviousData && query.data?.length === 0) {
|
|
150
|
+
* <p>{{ t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' }) }}</p>
|
|
151
|
+
* }
|
|
152
|
+
* <a [href]="nextHref()">{{ t('common.next', undefined, { defaultValue: 'Next page' }) }}</a>
|
|
153
|
+
* `,
|
|
154
|
+
* })
|
|
155
|
+
* export class InvoiceList {
|
|
156
|
+
* // Expose the i18n function so every template binding re-reads it.
|
|
157
|
+
* protected readonly t = t
|
|
158
|
+
* // The viewer whose invoices these are (also in the key).
|
|
159
|
+
* readonly viewer = input('anonymous')
|
|
160
|
+
* // The page to show.
|
|
161
|
+
* readonly page = input(1)
|
|
162
|
+
*
|
|
163
|
+
* readonly query = useQuery<Invoice[]>(
|
|
164
|
+
* computed(() => ({
|
|
165
|
+
* key: ['invoices', this.viewer(), this.page()],
|
|
166
|
+
* principal: this.viewer(),
|
|
167
|
+
* keepPreviousData: true,
|
|
168
|
+
* fetch: async (signal: AbortSignal) =>
|
|
169
|
+
* unwrapList<Invoice>(
|
|
170
|
+
* await getClient().get('/api/invoices', {
|
|
171
|
+
* signal,
|
|
172
|
+
* params: { limit: 20, offset: (this.page() - 1) * 20 },
|
|
173
|
+
* }),
|
|
174
|
+
* ),
|
|
175
|
+
* })),
|
|
176
|
+
* )
|
|
177
|
+
*
|
|
178
|
+
* readonly nextHref = computed(() => `/invoices?page=${this.page() + 1}`)
|
|
179
|
+
* }
|
|
180
|
+
* ```
|
|
181
|
+
*
|
|
182
|
+
* @example
|
|
183
|
+
* A mutation or a failed load has to change a page that is ALREADY mounted, and
|
|
184
|
+
* the cache never starts that request by itself: `set()` paints a mutation's own
|
|
185
|
+
* response, `invalidate()` marks what it affects for the next mount, and an
|
|
186
|
+
* explicit `fetch()` retries into the mounted page.
|
|
187
|
+
*
|
|
188
|
+
* ```typescript
|
|
189
|
+
* import { Component, input } from '@angular/core'
|
|
190
|
+
* import { getClient } from '@molecule/app-http'
|
|
191
|
+
* import { t } from '@molecule/app-i18n'
|
|
192
|
+
* import { getQueryClient } from '@molecule/app-query'
|
|
193
|
+
*
|
|
194
|
+
* // The key names what the document actually depends on — here the signed-in
|
|
195
|
+
* // principal, the filter and the page. Another principal's feed is a
|
|
196
|
+
* // different document, so an invalidation scoped to this one leaves it alone.
|
|
197
|
+
* const feedKey = (principal: string, filter: string, page: number) =>
|
|
198
|
+
* ['feed', principal, filter, page] as const
|
|
199
|
+
*
|
|
200
|
+
* const feedOptions = (principal: string, filter: string, page: number) => ({
|
|
201
|
+
* key: feedKey(principal, filter, page),
|
|
202
|
+
* fetch: async (signal: AbortSignal) =>
|
|
203
|
+
* (await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
|
|
204
|
+
* })
|
|
205
|
+
*
|
|
206
|
+
* async function setFollowing(principal: string, authorId: string, follow: boolean): Promise<void> {
|
|
207
|
+
* const client = getQueryClient()
|
|
208
|
+
* const http = getClient()
|
|
209
|
+
* const { data: body } = follow
|
|
210
|
+
* ? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
|
|
211
|
+
* : await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
|
|
212
|
+
* // The response IS the document: paint it now, with no second round trip.
|
|
213
|
+
* // (If it were only a count or a flag, skip set() and invalidate() instead.)
|
|
214
|
+
* client.set(feedKey(principal, 'following', 1), body.feed)
|
|
215
|
+
* // Future reads of every feed this principal owns are stale.
|
|
216
|
+
* client.invalidate(['feed', principal])
|
|
217
|
+
* }
|
|
218
|
+
*
|
|
219
|
+
* @Component({
|
|
220
|
+
* selector: 'button[mol-feed-retry]',
|
|
221
|
+
* template: `{{ t('common.retry', undefined, { defaultValue: 'Retry' }) }}`,
|
|
222
|
+
* host: { type: 'button', '(click)': 'retry()' },
|
|
223
|
+
* })
|
|
224
|
+
* export class FeedRetry {
|
|
225
|
+
* // Expose the i18n function so every template binding re-reads it.
|
|
226
|
+
* protected readonly t = t
|
|
227
|
+
* readonly principal = input.required<string>()
|
|
228
|
+
*
|
|
229
|
+
* retry(): void {
|
|
230
|
+
* // invalidate() alone would leave the mounted page on its error;
|
|
231
|
+
* // an explicit fetch retries into it. useQuery shows the outcome.
|
|
232
|
+
* void getQueryClient()
|
|
233
|
+
* .fetch(feedOptions(this.principal(), 'following', 1))
|
|
234
|
+
* .catch((_error) => {
|
|
235
|
+
* // The mounted useQuery observer presents this failure via status/error.
|
|
236
|
+
* })
|
|
237
|
+
* }
|
|
238
|
+
* }
|
|
239
|
+
* ```
|
|
240
|
+
*
|
|
241
|
+
* @example
|
|
242
|
+
* One API resource described once, for every page that reads or changes it.
|
|
243
|
+
* `createQueryResource` returns the list and detail reads as `useQuery` options
|
|
244
|
+
* and the writes as functions that put the server's record into the cache and
|
|
245
|
+
* fetch the lists on screen again, so a page never mirrors a response into
|
|
246
|
+
* component state. A flag the API models as a sub-path (`POST
|
|
247
|
+
* /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with
|
|
248
|
+
* the saved record and is the `commit` of `OptimisticToggleButton` (from
|
|
249
|
+
* `@molecule/app-ui-angular`).
|
|
250
|
+
*
|
|
251
|
+
* ```typescript
|
|
252
|
+
* import { Component, computed, input } from '@angular/core'
|
|
253
|
+
* import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
|
|
254
|
+
* import { t } from '@molecule/app-i18n'
|
|
255
|
+
* import { OptimisticToggleButton } from '@molecule/app-ui-angular'
|
|
256
|
+
* import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-angular'
|
|
257
|
+
*
|
|
258
|
+
* interface Invoice {
|
|
259
|
+
* id: string
|
|
260
|
+
* number: string
|
|
261
|
+
* flagged: boolean
|
|
262
|
+
* }
|
|
263
|
+
*
|
|
264
|
+
* export const invoices = createQueryResource<Invoice>({
|
|
265
|
+
* name: 'invoices',
|
|
266
|
+
* path: '/invoices',
|
|
267
|
+
* http: getClient,
|
|
268
|
+
* readList: (response) => unwrapList<Invoice>(response),
|
|
269
|
+
* readOne: (response) => unwrapSingle<Invoice | null>(response),
|
|
270
|
+
* })
|
|
271
|
+
*
|
|
272
|
+
* // The record's own action: a flag control whose click shows at once, whose
|
|
273
|
+
* // save follows, and whose label goes back to the server's value only when the
|
|
274
|
+
* // save fails. OptimisticToggleButton takes the server value as an input, so a
|
|
275
|
+
* // fresh query answer updates it after a completed save.
|
|
276
|
+
* @Component({
|
|
277
|
+
* selector: 'mol-flag-control',
|
|
278
|
+
* template: `
|
|
279
|
+
* <button type="button" mol-optimistic-toggle-button [value]="invoice().flagged" [commit]="save">
|
|
280
|
+
* <span slot="activeLabel">{{ t('invoice.unflag', undefined, { defaultValue: 'Unflag' }) }}</span>
|
|
281
|
+
* <span slot="inactiveLabel">{{ t('invoice.flag', undefined, { defaultValue: 'Flag' }) }}</span>
|
|
282
|
+
* {{ invoice().number }}
|
|
283
|
+
* </button>
|
|
284
|
+
* `,
|
|
285
|
+
* imports: [OptimisticToggleButton],
|
|
286
|
+
* })
|
|
287
|
+
* export class InvoiceFlagControl {
|
|
288
|
+
* readonly invoice = input.required<Invoice>()
|
|
289
|
+
* readonly viewer = input.required<string>()
|
|
290
|
+
* protected readonly t = t
|
|
291
|
+
*
|
|
292
|
+
* readonly save = async (flagged: boolean): Promise<boolean> =>
|
|
293
|
+
* (await invoices.toggle(this.viewer(), this.invoice().id, 'flag', flagged)).flagged
|
|
294
|
+
* }
|
|
295
|
+
*
|
|
296
|
+
* // Render the record's own container (here the flag control) through
|
|
297
|
+
* // QueryContent: its children template runs only with a loaded, non-null
|
|
298
|
+
* // document, so an action can never swallow an early click. Every status
|
|
299
|
+
* // line stays beside it.
|
|
300
|
+
* @Component({
|
|
301
|
+
* selector: 'mol-invoice-page',
|
|
302
|
+
* template: `
|
|
303
|
+
* <mol-query-content
|
|
304
|
+
* [query]="query"
|
|
305
|
+
* [pending]="pending"
|
|
306
|
+
* [missing]="missing"
|
|
307
|
+
* [error]="failed"
|
|
308
|
+
* [children]="content"
|
|
309
|
+
* >
|
|
310
|
+
* <ng-template #pending>
|
|
311
|
+
* <p role="status">{{ t('common.loading', undefined, { defaultValue: 'Loading…' }) }}</p>
|
|
312
|
+
* </ng-template>
|
|
313
|
+
* <ng-template #missing>
|
|
314
|
+
* <p role="alert">{{ t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' }) }}</p>
|
|
315
|
+
* </ng-template>
|
|
316
|
+
* <ng-template #failed let-_error>
|
|
317
|
+
* <p role="alert">{{ t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' }) }}</p>
|
|
318
|
+
* </ng-template>
|
|
319
|
+
* <ng-template #content let-invoice>
|
|
320
|
+
* <mol-flag-control [invoice]="invoice" [viewer]="viewer()"></mol-flag-control>
|
|
321
|
+
* </ng-template>
|
|
322
|
+
* </mol-query-content>
|
|
323
|
+
* `,
|
|
324
|
+
* imports: [QueryContent, InvoiceFlagControl],
|
|
325
|
+
* })
|
|
326
|
+
* export class InvoicePage {
|
|
327
|
+
* // Expose the i18n function so every template binding re-reads it.
|
|
328
|
+
* protected readonly t = t
|
|
329
|
+
* readonly id = input('')
|
|
330
|
+
* readonly viewer = input('')
|
|
331
|
+
*
|
|
332
|
+
* readonly query = useQuery(
|
|
333
|
+
* computed(() => (this.viewer() && this.id() ? invoices.detail(this.viewer(), this.id()) : null)),
|
|
334
|
+
* )
|
|
335
|
+
* }
|
|
336
|
+
* ```
|
|
337
|
+
*
|
|
338
|
+
* @example
|
|
339
|
+
* A pager needs the whole response, including its total. Keep that read on the
|
|
340
|
+
* same resource as its mutations, including alternate list paths; a separate
|
|
341
|
+
* hand-written options object is outside the resource's refresh tracking.
|
|
342
|
+
*
|
|
343
|
+
* ```typescript
|
|
344
|
+
* import { getClient } from '@molecule/app-http'
|
|
345
|
+
* import { createQueryResource } from '@molecule/app-query-angular'
|
|
346
|
+
*
|
|
347
|
+
* interface TicketPage { tickets: { id: string; subject: string }[]; total: number }
|
|
348
|
+
* const tickets = createQueryResource<TicketPage['tickets'][number]>({
|
|
349
|
+
* name: 'tickets', path: '/tickets', http: getClient,
|
|
350
|
+
* readOne: (response) => response.data as TicketPage['tickets'][number],
|
|
351
|
+
* })
|
|
352
|
+
* const page = tickets.listPage('agent-1', { limit: 10, offset: 20 },
|
|
353
|
+
* (response) => response.data as TicketPage)
|
|
354
|
+
* // useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
|
|
355
|
+
* // and tickets.refresh('agent-1') refresh this page too.
|
|
356
|
+
* // A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
|
|
357
|
+
* // Use one canonical page reader per path; list() still returns only its own rows.
|
|
358
|
+
* // For immediate deletion from an opaque page, add a fifth argument:
|
|
359
|
+
* // (page, id) => {
|
|
360
|
+
* // const rows = page.tickets.filter((row) => String(row.id) !== id)
|
|
361
|
+
* // return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
|
|
362
|
+
* // }
|
|
363
|
+
* ```
|
|
364
|
+
* A resource mutation also waits out a pre-mutation list request before fetching again;
|
|
365
|
+
* joining that older in-flight read alone would leave the new record absent.
|
|
366
|
+
* Successful deletion removes a row immediately, including one just created through the
|
|
367
|
+
* resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit
|
|
368
|
+
* successful create can recreate the identity. Opaque listPage envelopes need their own
|
|
369
|
+
* removeFromPage adapter; no row or total property is guessed.
|
|
370
|
+
*
|
|
371
|
+
* @remarks
|
|
372
|
+
* - **`useQuery` reads the cache synchronously on the first render.** A
|
|
373
|
+
* document prefetched from a hovered link, or seeded with `client.set()`
|
|
374
|
+
* from a server-rendered JSON island, renders at once — no spinner, no
|
|
375
|
+
* layout shift. Render loading from `status === 'idle' || status === 'loading'`;
|
|
376
|
+
* `undefined` data can also accompany a completed error. A completed `null`
|
|
377
|
+
* response is missing, not pending. The detail example treats only HTTP 404
|
|
378
|
+
* or a successful null response as missing; other errors stay load failures.
|
|
379
|
+
* The app's bonded HTTP client rejects non-2xx responses. Native `fetch`
|
|
380
|
+
* resolves them, so a custom fetcher must check `response.ok` before JSON.
|
|
381
|
+
* - **Mount a detail region and its actions only after its initial document arrives.**
|
|
382
|
+
* A visible container is not a loaded document: a caller may wait for that container and
|
|
383
|
+
* read its text once, or click its button, while `data` is still undefined. Put the loading
|
|
384
|
+
* message outside the detail region, as in `PackagePage` above. Keep record-dependent
|
|
385
|
+
* controls absent or natively disabled until the record exists; returning early inside
|
|
386
|
+
* an enabled click handler loses that click. `client.set()` protects a cache mutation
|
|
387
|
+
* from an older read, but cannot recover a click whose handler never sent the mutation.
|
|
388
|
+
* - **The key is the identity.** Building the options inline inside a
|
|
389
|
+
* `computed` is fine; the hook resubscribes only when the key's value
|
|
390
|
+
* changes, not when the `fetch` closure does.
|
|
391
|
+
* - **A key change normally resets to the new key's state.** For a list's own
|
|
392
|
+
* page/filter/view change, opt into `keepPreviousData` with a `principal`;
|
|
393
|
+
* `isPreviousData` tells you the rows on screen belong to the key you just
|
|
394
|
+
* left. A completed response (including an empty list) replaces them, and a
|
|
395
|
+
* changed principal drops them, so an account switch never shows the previous
|
|
396
|
+
* account's rows. Do not emulate this with a component-local copy of the
|
|
397
|
+
* query data — that mirror is what serves stale rows under a new page, or
|
|
398
|
+
* blanks the list on a re-render.
|
|
399
|
+
* - **The key names the viewer whenever the answer can depend on it.** The
|
|
400
|
+
* app's HTTP client sends the session, so the server may filter or
|
|
401
|
+
* personalize even a list that guests can see (a `favorited` or `following`
|
|
402
|
+
* flag), and the cache serves a key's document to whoever observes it,
|
|
403
|
+
* across sign-in and sign-out. Key such a list on the viewer
|
|
404
|
+
* (`user ? String(user.id) : 'anonymous'`), pass the same value as
|
|
405
|
+
* `principal`, and pass `null` while the session is still being restored
|
|
406
|
+
* (`status === 'loading'`; the HTTP client holds the request until then
|
|
407
|
+
* anyway), so restoring a session never swaps a key that already rendered
|
|
408
|
+
* rows. A viewer-free key with `principal: 'public'` is only for an endpoint
|
|
409
|
+
* that answers every viewer the same. A protected route view also passes
|
|
410
|
+
* `null` while it cannot load yet.
|
|
411
|
+
* - **Render loading, empty and error status outside the item list**, and never
|
|
412
|
+
* give a placeholder the item's own class or element shape: a list read by
|
|
413
|
+
* the item class (or by `:first-child`) must contain only real items. An
|
|
414
|
+
* empty array is a loaded empty state, not a missing response; render it
|
|
415
|
+
* only when `isPreviousData` is not set, because a retained document belongs
|
|
416
|
+
* to the key you just left.
|
|
417
|
+
* - `intentPrefetchProps` returns three handlers named after the DOM events an
|
|
418
|
+
* Angular template binds (`pointerenter`, `focus`, `touchstart`). It is a
|
|
419
|
+
* plain function (not a hook), so it works inside `@for` too.
|
|
420
|
+
* - Prefetching respects the browser's data-saver setting and skips 2G
|
|
421
|
+
* connections (`shouldPrefetch()` in the core) — do not bypass that for
|
|
422
|
+
* "important" links; the person can still click.
|
|
423
|
+
* - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
|
|
424
|
+
* entry and updates every observer of that key. After a mutation whose response is not the
|
|
425
|
+
* whole document, `await query.refetch()` reloads the displayed list. It resolves with the
|
|
426
|
+
* resulting state (including `status: 'error'` on failure); a disabled query stays idle.
|
|
427
|
+
* Prefer `client.set(key, response)` when the mutation already returned the whole document.
|
|
428
|
+
* - Errors are not thrown from the hook; read `status === 'error'` and
|
|
429
|
+
* `error`. `client.invalidate()` does NOT refetch a mounted page — it only
|
|
430
|
+
* marks documents stale, so the page keeps its error (or its old document)
|
|
431
|
+
* until the app retries with `client.fetch(options)` or the page subscribes
|
|
432
|
+
* again (a key change or a re-mount).
|
|
433
|
+
* - After a mutation, `client.set(key, response)` paints the server's own
|
|
434
|
+
* answer at once and supersedes an older fetch already in flight for that
|
|
435
|
+
* key, so its response cannot undo the mutation. An existing `fetch()` caller
|
|
436
|
+
* still settles independently of the cache write; read `client.get(key)` for the newest document.
|
|
437
|
+
* `client.invalidate(prefix)` marks the affected reads stale for their next
|
|
438
|
+
* mount. Which key and which scope is the app's decision: the cache does not
|
|
439
|
+
* infer it from auth or form state.
|
|
440
|
+
* - The result's state fields are signals read through plain properties
|
|
441
|
+
* (`query.data`, `query.isPreviousData`), so a template binding that reads
|
|
442
|
+
* them re-renders when the document changes, and the object can be handed to
|
|
443
|
+
* `QueryContent`'s `query` input unchanged.
|
|
444
|
+
*
|
|
445
|
+
* Render resource-dependent lists and controls through {@link QueryContent}. Its children
|
|
446
|
+
* template receives only loaded, non-null data; loading and error content never mount item
|
|
447
|
+
* actions. It renders cached content during refresh and treats an empty list, false and zero
|
|
448
|
+
* as data. Put the list, or the record's own container (its card, header or profile block),
|
|
449
|
+
* inside the children template and every status line (loading, error, `isFetching` refresh)
|
|
450
|
+
* beside it, never inside it: a reader that finds the container and reads its paragraph must
|
|
451
|
+
* read the record, not "Loading…".
|
|
452
|
+
*
|
|
453
|
+
* Keep every resource identity in the query key. A boundary cannot correct a query that supplies
|
|
454
|
+
* another record's cached data. For a list, map real rows inside the children template; never
|
|
455
|
+
* style a status placeholder as a row.
|
|
456
|
+
*
|
|
457
|
+
* @module
|
|
458
|
+
*/
|
|
459
|
+
export * from './query-content.component.js';
|
|
460
|
+
export * from './resource.js';
|
|
461
|
+
export * from './types.js';
|
|
462
|
+
export * from './use-prefetch.js';
|
|
463
|
+
export * from './use-query.js';
|
|
464
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAycG;AAEH,cAAc,8BAA8B,CAAA;AAC5C,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,mBAAmB,CAAA;AACjC,cAAc,gBAAgB,CAAA"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Render resource-dependent content only after its document exists — the
|
|
3
|
+
* Angular counterpart of `QueryContent` in `@molecule/app-query-react`, with
|
|
4
|
+
* the node-valued props as `TemplateRef`s. The component is headless: it owns
|
|
5
|
+
* no translations and no styling, and projects the rendered branch beside the
|
|
6
|
+
* host (`display: contents`), so the DOM is exactly the branch's own.
|
|
7
|
+
* @module
|
|
8
|
+
*/
|
|
9
|
+
import { type DoCheck, type OnChanges, type TemplateRef } from '@angular/core';
|
|
10
|
+
import type { QueryContentContext, QueryContentErrorContext, QueryContentProps } from './types.js';
|
|
11
|
+
import * as i0 from "@angular/core";
|
|
12
|
+
/**
|
|
13
|
+
* The loaded-data branch receives a non-null document. Pending, failed initial
|
|
14
|
+
* reads and missing records never mount that branch, so its actions cannot
|
|
15
|
+
* swallow an early click. Cached data remains mounted during refresh, including
|
|
16
|
+
* a failed refresh. Status fallbacks belong outside the list or record
|
|
17
|
+
* container rendered by `children`, and so does a refresh line; the default
|
|
18
|
+
* fallbacks render nothing.
|
|
19
|
+
*
|
|
20
|
+
* The templates receive the render arguments as template context: `children`
|
|
21
|
+
* gets the document as `$implicit` and `a0` (`let-data`), `error` gets the
|
|
22
|
+
* error value (`let-error`), and `pending`/`missing` render without a context.
|
|
23
|
+
*/
|
|
24
|
+
export declare class QueryContent<T = unknown> implements DoCheck, OnChanges {
|
|
25
|
+
/** State from useQuery, or any compatible query observer. */
|
|
26
|
+
query: QueryContentProps<T>['query'];
|
|
27
|
+
/** Mounted only with a real document, including false, zero and an empty list. */
|
|
28
|
+
children: TemplateRef<QueryContentContext<T>> | null;
|
|
29
|
+
/** Initial idle/loading content. Render a status template, never a fake item or action. */
|
|
30
|
+
pending: TemplateRef<unknown> | null;
|
|
31
|
+
/** Content for a loaded null record. Null is distinct from an unfinished request. */
|
|
32
|
+
missing: TemplateRef<unknown> | null;
|
|
33
|
+
/** A failed initial read. Cached data stays visible if its refresh fails. */
|
|
34
|
+
error: TemplateRef<QueryContentErrorContext> | null;
|
|
35
|
+
/** Where the chosen branch renders. */
|
|
36
|
+
private outlet;
|
|
37
|
+
/** Marks this region for check when the observed document changes. */
|
|
38
|
+
private readonly changeDetector;
|
|
39
|
+
/** The observer the reactivity effect is subscribed to (a new prop re-subscribes it). */
|
|
40
|
+
private readonly observer;
|
|
41
|
+
/** The template currently mounted. */
|
|
42
|
+
private current;
|
|
43
|
+
/** The context object the mounted view reads (updated in place). */
|
|
44
|
+
private readonly context;
|
|
45
|
+
/** The mounted branch view, when a template is showing. */
|
|
46
|
+
private view?;
|
|
47
|
+
constructor();
|
|
48
|
+
/**
|
|
49
|
+
* The branch the current query state shows.
|
|
50
|
+
* @returns The template and its context, or nothing.
|
|
51
|
+
*/
|
|
52
|
+
private branch;
|
|
53
|
+
/**
|
|
54
|
+
* Follows a replaced `query` prop: the reactivity effect subscribes to the
|
|
55
|
+
* new observer's own signals on its next run.
|
|
56
|
+
*/
|
|
57
|
+
ngOnChanges(): void;
|
|
58
|
+
/**
|
|
59
|
+
* Mounts the branch the query state shows, and refreshes the mounted view's
|
|
60
|
+
* context when the state changes. Runs on every change-detection pass, so an
|
|
61
|
+
* input set by a host binding is always folded in before this runs.
|
|
62
|
+
*/
|
|
63
|
+
ngDoCheck(): void;
|
|
64
|
+
/**
|
|
65
|
+
* Shows the branch the current query state describes: a different template
|
|
66
|
+
* replaces the mounted view, and a changed document (or error) is written into
|
|
67
|
+
* the context the mounted view reads.
|
|
68
|
+
*/
|
|
69
|
+
private update;
|
|
70
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<QueryContent<any>, never>;
|
|
71
|
+
static ɵcmp: i0.ɵɵComponentDeclaration<QueryContent<any>, "mol-query-content", never, { "query": { "alias": "query"; "required": false; }; "pending": { "alias": "pending"; "required": false; }; "missing": { "alias": "missing"; "required": false; }; "children": { "alias": "children"; "required": false; }; "error": { "alias": "error"; "required": false; }; }, {}, never, never, true, never>;
|
|
72
|
+
}
|
|
73
|
+
//# sourceMappingURL=query-content.component.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-content.component.d.ts","sourceRoot":"","sources":["../src/query-content.component.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAGL,KAAK,OAAO,EAIZ,KAAK,SAAS,EAEd,KAAK,WAAW,EAIjB,MAAM,eAAe,CAAA;AAEtB,OAAO,KAAK,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;;AAQlG;;;;;;;;;;;GAWG;AACH,qBAUa,YAAY,CAAC,CAAC,GAAG,OAAO,CAAE,YAAW,OAAO,EAAE,SAAS;IAClE,6DAA6D;IAC7D,KAAK,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAwD;IAC5F,kFAAkF;IAClF,QAAQ,EAAE,WAAW,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAO;IAC3D,2FAA2F;IAC3F,OAAO,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAO;IAC3C,qFAAqF;IACrF,OAAO,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAO;IAC3C,6EAA6E;IAC7E,KAAK,EAAE,WAAW,CAAC,wBAAwB,CAAC,GAAG,IAAI,CAAO;IAE1D,uCAAuC;IAEvC,OAAO,CAAC,MAAM,CAAmB;IACjC,sEAAsE;IACtE,OAAO,CAAC,QAAQ,CAAC,cAAc,CAA4B;IAC3D,yFAAyF;IACzF,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAoD;IAC7E,sCAAsC;IACtC,OAAO,CAAC,OAAO,CAAoC;IACnD,oEAAoE;IACpE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA8B;IACtD,2DAA2D;IAC3D,OAAO,CAAC,IAAI,CAAC,CAA0B;;IAsBvC;;;OAGG;IACH,OAAO,CAAC,MAAM;IAcd;;;OAGG;IACH,WAAW,IAAI,IAAI;IAInB;;;;OAIG;IACH,SAAS,IAAI,IAAI;IAIjB;;;;OAIG;IACH,OAAO,CAAC,MAAM;yCAtFH,YAAY;2CAAZ,YAAY;CAoGxB"}
|