@hamur/adapter-preact 0.0.0-stage → 0.0.2

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.
Files changed (68) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +35 -2
  3. package/dist/chunks/browser-index-89d71ade.js +118 -0
  4. package/dist/chunks/browser-index-ezte15pp.js +67 -0
  5. package/dist/chunks/browser-index-hsy7tnbg.js +21 -0
  6. package/dist/chunks/browser-index-k3m2axbw.js +274 -0
  7. package/dist/src/adapter.js +456 -0
  8. package/dist/src/error-page.js +391 -0
  9. package/dist/src/index.js +1506 -0
  10. package/dist/src/keepalive.js +6 -0
  11. package/dist/src/runtime/client.js +96 -0
  12. package/dist/src/runtime/island.js +33 -0
  13. package/dist/src/runtime/server.js +95 -0
  14. package/dist/types/src/activation.d.ts +15 -0
  15. package/dist/types/src/adapter.d.ts +2 -0
  16. package/dist/types/src/async-data.d.ts +13 -0
  17. package/dist/types/src/client-component.d.ts +11 -0
  18. package/dist/types/src/client-fallback.d.ts +2 -0
  19. package/dist/types/src/context.d.ts +81 -0
  20. package/dist/types/src/error-page.d.ts +1 -0
  21. package/dist/types/src/head.d.ts +5 -0
  22. package/dist/types/src/index.d.ts +429 -0
  23. package/dist/types/src/island-html.d.ts +13 -0
  24. package/dist/types/src/island.d.ts +19 -0
  25. package/dist/types/src/jsx-locator.d.ts +6 -0
  26. package/dist/types/src/keepalive.d.ts +26 -0
  27. package/dist/types/src/lazy-hydration.d.ts +12 -0
  28. package/dist/types/src/markdown-page.d.ts +9 -0
  29. package/dist/types/src/markdown.d.ts +12 -0
  30. package/dist/types/src/plugin.d.ts +36 -0
  31. package/dist/types/src/route-boundary.d.ts +41 -0
  32. package/dist/types/src/runtime/client.d.ts +10 -0
  33. package/dist/types/src/runtime/hmr.d.ts +31 -0
  34. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  35. package/dist/types/src/runtime/hydration.d.ts +8 -0
  36. package/dist/types/src/runtime/island.d.ts +8 -0
  37. package/dist/types/src/runtime/server.d.ts +11 -0
  38. package/dist/types/src/server-island.d.ts +10 -0
  39. package/dist/types/src/svg.d.ts +10 -0
  40. package/package.json +71 -4
  41. package/src/activation.ts +51 -0
  42. package/src/adapter.ts +35 -0
  43. package/src/async-data.ts +65 -0
  44. package/src/client-component.ts +23 -0
  45. package/src/client-fallback.ts +2 -0
  46. package/src/context.ts +372 -0
  47. package/src/env.d.ts +3 -0
  48. package/src/error-page.ts +1 -0
  49. package/src/head.ts +34 -0
  50. package/src/index.ts +1868 -0
  51. package/src/island-html.ts +58 -0
  52. package/src/island.ts +56 -0
  53. package/src/jsx-locator.ts +199 -0
  54. package/src/keepalive.ts +100 -0
  55. package/src/lazy-hydration.ts +101 -0
  56. package/src/markdown-page.ts +18 -0
  57. package/src/markdown.ts +58 -0
  58. package/src/plugin.ts +231 -0
  59. package/src/route-boundary.ts +51 -0
  60. package/src/runtime/client.ts +85 -0
  61. package/src/runtime/hmr.ts +141 -0
  62. package/src/runtime/hydration-dev.ts +8 -0
  63. package/src/runtime/hydration.ts +7 -0
  64. package/src/runtime/island.ts +37 -0
  65. package/src/runtime/server.ts +102 -0
  66. package/src/server-island.ts +35 -0
  67. package/src/svg.ts +27 -0
  68. package/src/webmcp.d.ts +18 -0
package/src/index.ts ADDED
@@ -0,0 +1,1868 @@
1
+ /// <reference path="./webmcp.d.ts" />
2
+ import { Component, Fragment, createElement } from "preact"
3
+ import { reportWebVitals, syncedState } from "hamur/app"
4
+ import type { SyncedStateOptions } from "hamur/app"
5
+ import { Suspense } from "preact/compat"
6
+ import {
7
+ asyncDataArguments,
8
+ asyncDataKey,
9
+ stateArguments,
10
+ fetchKey,
11
+ timeAttributes,
12
+ timeView,
13
+ watchTime,
14
+ createLoadingIndicator,
15
+ loadingIndicatorOptions,
16
+ paintLoadingIndicator,
17
+ createRouteAnnouncer,
18
+ createAnnouncer,
19
+ announcerActions,
20
+ announcerRole,
21
+ hideAnnouncer,
22
+ ROUTE_ANNOUNCER_ID,
23
+ ANNOUNCER_POLITE_ID,
24
+ ANNOUNCER_ASSERTIVE_ID,
25
+ isHandlerReference,
26
+ isPending,
27
+ resolveCallOptions,
28
+ settledOf,
29
+ } from "hamur/adapter"
30
+ import type { ComponentChildren, CSSProperties, FunctionComponent, TimeHTMLAttributes } from "preact"
31
+ import {
32
+ useCallback,
33
+ useContext,
34
+ useEffect,
35
+ useId,
36
+ useLayoutEffect,
37
+ useMemo,
38
+ useRef,
39
+ useState as useLocalState,
40
+ } from "preact/hooks"
41
+ import {
42
+ clearAsyncData,
43
+ createForm,
44
+ enhance,
45
+ navigateTo,
46
+ redirect,
47
+ useCookie as cookieOf,
48
+ withoutBase,
49
+ } from "hamur/app"
50
+ import {
51
+ callOnce as callOnceOf,
52
+ clearState as clearStateOf,
53
+ setResponseStatus as setResponseStatusOf,
54
+ useResponseHeader as responseHeaderOf,
55
+ useRequestEvent as requestEventOf,
56
+ useRequestFetch as requestFetchOf,
57
+ useRequestHeader as requestHeaderOf,
58
+ useRequestHeaders as requestHeadersOf,
59
+ useRequestURL as requestURLOf,
60
+ usePreviewMode as previewModeOf,
61
+ } from "hamur/app"
62
+ import type { PreviewMode } from "hamur/app"
63
+ import type { $Fetch, FetchCheckedInput, FetchInputField } from "hamur/app"
64
+ import type { StateKey } from "hamur/app"
65
+ import type { HamurEvent } from "hamur/server"
66
+ import type { AppHooks, WebVitalMetric } from "hamur/app"
67
+ import { whenAppReady } from "hamur/adapter"
68
+ import {
69
+ layoutSegments,
70
+ IDLE_FORM_STATUS,
71
+ assertFormMethod,
72
+ createActionRunner,
73
+ createFormStatus,
74
+ functionFormAction,
75
+ linkActionRunner,
76
+ restoredResult,
77
+ runFunctionForm,
78
+ publicError,
79
+ runtimeConfigOf,
80
+ siteConfigOf,
81
+ sanitizeHead,
82
+ seoMetaToHead,
83
+ createLinkSlot,
84
+ linkAttributes,
85
+ linkExtraAttributes,
86
+ linkState,
87
+ warnRemovedLinkProps,
88
+ relativeTarget,
89
+ resolveLinkTarget,
90
+ resolveRelative,
91
+ prefetchAttribute,
92
+ viewTransitionAttribute,
93
+ checkTransitionName,
94
+ optimisticSource,
95
+ navigationHook,
96
+ navigationBlocker,
97
+ routeGuard,
98
+ createBlocker,
99
+ registerSnapshot,
100
+ setLinkState,
101
+ linkPending,
102
+ LINK_DEFAULTS,
103
+ linkDefaultsOf,
104
+ linkPrefetchProps,
105
+ } from "hamur/adapter"
106
+ import type {
107
+ Settled,
108
+ AnnouncerActions,
109
+ AnnouncerPoliteness,
110
+ AnnouncerState,
111
+ RouteAnnouncerActions,
112
+ RouteAnnouncerPoliteness,
113
+ RouteAnnouncerState,
114
+ LoadingIndicatorActions,
115
+ LoadingIndicatorProps,
116
+ LoadingIndicatorOptions,
117
+ LoadingIndicatorState,
118
+ TimeInput,
119
+ } from "hamur/adapter"
120
+ import { diagnosticURL, noteOutlet, prehydrate } from "hamur/adapter"
121
+ import type { DiagnosticCode } from "hamur/adapter"
122
+ import type { LinkDefaults, LinkSlot, ResolvedLinkDefaults, UseLinkOptions } from "hamur/adapter"
123
+ import type {
124
+ ActionOptions,
125
+ ActionRunner,
126
+ FormStatus,
127
+ PrefetchOn,
128
+ Handler,
129
+ AfterNavigateHook,
130
+ BeforeNavigateHook,
131
+ NavigateHook,
132
+ NavigationHookKind,
133
+ Navigation,
134
+ NavigationBlocker,
135
+ NavigationGuard,
136
+ RouteGuardKind,
137
+ Blocker,
138
+ BlockerStore,
139
+ ShouldBlock,
140
+ UseBlockerOptions,
141
+ SnapshotOptions,
142
+ } from "hamur/adapter"
143
+ import type { HandlerForm, HamurLinkProps } from "hamur/app"
144
+ import type {
145
+ RouteLoaderData,
146
+ UseDataArgs,
147
+ AsyncDataHandler,
148
+ ErrorBoundaryFallbackProps,
149
+ FetchRequest,
150
+ GetCachedData,
151
+ GetCachedDataCause,
152
+ CheckedTarget,
153
+ HandlerReference,
154
+ NavigationState,
155
+ RouteValue,
156
+ RouterApi,
157
+ } from "hamur/adapter"
158
+ import type {
159
+ ActionFailure,
160
+ AppContext,
161
+ FormSubmitArgs,
162
+ PendingRun,
163
+ PickFrom,
164
+ RouteLocation,
165
+ AsyncDataEntry,
166
+ ClientRuntimeConfig,
167
+ SiteConfig,
168
+ FetchData,
169
+ AsyncDataOptions,
170
+ AsyncDataStatus,
171
+ UseCookieOptions,
172
+ ErrorPageProps,
173
+ Head,
174
+ HeadEntry,
175
+ HeadInput,
176
+ HeadSafeInput,
177
+ SeoMetaInput,
178
+ HamurError,
179
+ } from "hamur/app"
180
+ import {
181
+ ActivationContext,
182
+ AppContextContext,
183
+ BaseURLContext,
184
+ FormStatusContext,
185
+ HrefContext,
186
+ LinkHrefContext,
187
+ SubmittedContext,
188
+ NavigationContext,
189
+ DataContext,
190
+ EntryContext,
191
+ ErrorContext,
192
+ HeadContext,
193
+ LayoutContext,
194
+ OutletContext,
195
+ NeverHydratedContext,
196
+ OutletValueContext,
197
+ SlotsContext,
198
+ RouteContext,
199
+ RouterContext,
200
+ SearchContext,
201
+ StateContext,
202
+ } from "./context.ts"
203
+ import { $fetch } from "hamur/app"
204
+ import { later, shown } from "./activation.ts"
205
+ import { ClientOnlyContext } from "./client-component.ts"
206
+ import { clientFallback, markWaiting } from "hamur/adapter"
207
+ import { clientFallbackIds } from "./client-fallback.ts"
208
+ import { mountHead, nextRank } from "./head.ts"
209
+ import {
210
+ callHandler,
211
+ defaultGetCachedData,
212
+ keepCached,
213
+ refreshCached,
214
+ requestOf,
215
+ signalOf,
216
+ valueOf,
217
+ } from "./async-data.ts"
218
+
219
+ export {
220
+ addRouteMiddleware,
221
+ clearError,
222
+ disableScrollHandling,
223
+ forbidden,
224
+ navigateTo,
225
+ notFound,
226
+ permanentRedirect,
227
+ refreshCookie,
228
+ setPageLayout,
229
+ showError,
230
+ unauthorized,
231
+ } from "hamur/app"
232
+ export { defineLazyHydrationComponent } from "./lazy-hydration.ts"
233
+ export { Island } from "./island.ts"
234
+ export type { IslandProps } from "./island.ts"
235
+ export { ServerIsland } from "./server-island.ts"
236
+ export type { ServerIslandProps } from "./server-island.ts"
237
+ export { MarkdownRenderer } from "./markdown.ts"
238
+ export type { MarkdownRendererProps } from "./markdown.ts"
239
+ import { matchesOf, routeDataOf } from "hamur/adapter"
240
+ import { equalSearch, isOnline, pollInterval, searchTarget, startPoll, subscribeOnline } from "hamur/adapter"
241
+ import type { SetSearch } from "hamur/adapter"
242
+ import { APP_UPDATE_OFF, createAppUpdate } from "hamur/adapter"
243
+ import type { AppUpdateActions, AppUpdateState } from "hamur/adapter"
244
+ import type { MatchedRoute, RouteDataName, RouteDataOf, RouteError, RouteFor, RouteName } from "hamur/adapter"
245
+ export type { MatchedRoute, RouteDataName, RouteDataOf } from "hamur/adapter"
246
+ export type { NavigateToOptions, PickFrom } from "hamur/app"
247
+ export type { Blocker, BlockerArgs, SnapshotOptions, UseBlockerOptions } from "hamur/adapter"
248
+ export type {
249
+ AfterNavigateHook,
250
+ AsyncDataHandler,
251
+ BeforeNavigateHook,
252
+ ErrorBoundaryFallbackProps,
253
+ FetchRequest,
254
+ GetCachedData,
255
+ GetCachedDataCause,
256
+ NavigateHook,
257
+ NavigateOptions,
258
+ Navigation,
259
+ NavigationState,
260
+ NavigationType,
261
+ RouteValue,
262
+ RouterApi,
263
+ } from "hamur/adapter"
264
+
265
+ export type { LinkDefaults, LinkSlot, UseLinkOptions } from "hamur/adapter"
266
+
267
+ interface LinkBaseProps extends Record<string, unknown>, HamurLinkProps {
268
+ replace?: boolean
269
+ prefetch?: boolean
270
+ prefetchOn?: PrefetchOn
271
+ /** Removed: write `to`. */
272
+ href?: never
273
+ /** Removed: write `prefetch={false}`. */
274
+ noPrefetch?: never
275
+ /** The query as a function of the validated search of the page on screen. */
276
+ query?: (prev: RouteValue["search"]) => RouteValue["search"]
277
+ /** A serializable object kept in the history entry the click pushes, read as `useRoute().state`. */
278
+ state?: Record<string, unknown>
279
+ /** `"route"` resolves a relative `to` against the path of the route, its pattern filled with its params, not the URL. */
280
+ relative?: "route"
281
+ /** The app path the address bar shows while `to` renders. */
282
+ mask?: string
283
+ /** `false` renders `to` again after a reload of the masked entry. */
284
+ unmaskOnReload?: boolean
285
+ /** `true` or `{ types }` runs this navigation in a view transition, `false` turns it off. */
286
+ viewTransition?: boolean | { types: readonly string[] }
287
+ activeClass?: string
288
+ exactActiveClass?: string
289
+ /** The class the navigator adds to this anchor while a navigation to it is in flight; `""` adds none. */
290
+ pendingClass?: string
291
+ ariaCurrentValue?: "page" | "step" | "location" | "date" | "time" | "true"
292
+ /** A plain link the navigator never intercepts, with no prefetch and `rel="external"`. */
293
+ external?: boolean
294
+ /** No `rel` is added for a `target="_blank"` or an other-origin `to`. */
295
+ noRel?: boolean
296
+ /** The class the navigator adds to this anchor once its prefetch finished. */
297
+ prefetchedClass?: string
298
+ /** `false` keeps the scroll position for the navigation the click starts. */
299
+ scroll?: boolean
300
+ /** ms a hover or focus waits before it prefetches; one that ends sooner prefetches nothing. */
301
+ prefetchDelay?: number
302
+ /** Runs for a navigation this anchor started, after the `onBeforeNavigate` hooks; `nav.cancel()` stops it. */
303
+ onBeforeNavigate?: (nav: Navigation) => void
304
+ /** A function renders the link itself: it is given the `LinkSlot` and `Link` renders only what it returns. */
305
+ children?: ComponentChildren | ((link: LinkSlot) => ComponentChildren)
306
+ }
307
+
308
+ /** `T` is the string `to`, which is checked against the route table. */
309
+ export type LinkProps<T extends string = string> = LinkBaseProps & { to: CheckedTarget<T> | RouteLocation }
310
+
311
+ type AppRef = ((element: HTMLAnchorElement | null) => void | (() => void)) | { current: HTMLAnchorElement | null }
312
+
313
+ const NO_DEFAULTS: LinkDefaults = {}
314
+
315
+ function linkElement(props: LinkProps, defaults: LinkDefaults) {
316
+ return createElement(typeof props.children === "function" ? CustomLink : AnchorLink, {
317
+ link: props,
318
+ defaults,
319
+ } as never)
320
+ }
321
+
322
+ export function Link<T extends string = string>(props: LinkProps<T>) {
323
+ return linkElement(props as LinkProps, NO_DEFAULTS)
324
+ }
325
+
326
+ /** A `Link` with `defaults` over `app.link`; a prop of the element wins. */
327
+ export function defineLink(defaults: LinkDefaults): typeof Link {
328
+ return ((props: LinkProps) => linkElement(props, defaults)) as typeof Link
329
+ }
330
+
331
+ /** The `LinkSlot` of a link to `to`, for an element that renders its own `<a>`; `app.link` sets its defaults. */
332
+ export function useLink<T extends string = string>(
333
+ to: CheckedTarget<T> | RouteLocation,
334
+ options?: UseLinkOptions,
335
+ ): LinkSlot {
336
+ return useLinkSlot({ to, ...options } as never, linkDefaultsOf(useContext(AppContextContext)))
337
+ }
338
+
339
+ export interface NavigateProps<T extends string = string> {
340
+ to: CheckedTarget<T, false> | RouteLocation
341
+ replace?: boolean
342
+ }
343
+
344
+ /** Navigates to `to` once after mount; during SSR it throws the redirect `navigateTo` throws there. */
345
+ export function Navigate<T extends string = string>({ to, replace }: NavigateProps<T>): null {
346
+ const target = to as string | RouteLocation
347
+ if (isServer) throw redirect<string>(target)
348
+ const started = useRef(false)
349
+ useEffect(() => {
350
+ if (started.current) return
351
+ started.current = true
352
+ void navigateTo<string>(target, { replace })
353
+ }, [])
354
+ return null
355
+ }
356
+
357
+ function useLinkTarget<A extends object>(props: LinkProps, attrs: A) {
358
+ warnRemovedLinkProps(props)
359
+ const { to: target, query, relative } = props
360
+ const route = useContext(RouteContext)
361
+ const hrefOf = useContext(HrefContext)
362
+ const app = useContext(AppContextContext)
363
+ const searched = route ? searchTarget(relativeTarget(target, route, relative), route, query) : target
364
+ const { to, props: rest } = resolveLinkTarget(app, searched, attrs, hrefOf, props.external)
365
+ return { to, route, hrefOf, href: hrefOf(to), rest }
366
+ }
367
+
368
+ function AnchorLink({ link: props, defaults }: { link: LinkProps; defaults: LinkDefaults }) {
369
+ const d = linkDefaultsOf(useContext(AppContextContext), defaults)
370
+ const {
371
+ to: _to,
372
+ href: _href,
373
+ noPrefetch: _noPrefetch,
374
+ query,
375
+ state: entryState,
376
+ relative: _relative,
377
+ mask,
378
+ unmaskOnReload,
379
+ viewTransition,
380
+ replace,
381
+ prefetch,
382
+ prefetchOn,
383
+ activeClass = d.activeClass,
384
+ exactActiveClass = d.exactActiveClass,
385
+ pendingClass = d.pendingClass,
386
+ ariaCurrentValue = "page",
387
+ external,
388
+ noRel,
389
+ prefetchedClass = d.prefetchedClass,
390
+ scroll,
391
+ prefetchDelay = d.prefetchDelay,
392
+ onBeforeNavigate,
393
+ children,
394
+ ...attrs
395
+ } = props as LinkProps & { children?: ComponentChildren }
396
+ const mode = external ? "false" : prefetchAttribute(linkPrefetchProps({ prefetch, prefetchOn }, d))
397
+ const baseURL = useContext(BaseURLContext)
398
+ const { to, route, hrefOf, href, rest } = useLinkTarget(props, attrs)
399
+ const anchor = useRef<HTMLAnchorElement | null>(null)
400
+ const appRef = rest.ref as AppRef | undefined
401
+ const ref = useCallback(
402
+ (element: HTMLAnchorElement | null) => {
403
+ anchor.current = element
404
+ if (typeof appRef !== "function") return void (appRef && (appRef.current = element))
405
+ const cleanup = appRef(element)
406
+ return typeof cleanup === "function" ? () => void ((anchor.current = null), cleanup()) : undefined
407
+ },
408
+ [appRef],
409
+ )
410
+ const before = useRef(onBeforeNavigate)
411
+ before.current = onBeforeNavigate
412
+ const hasBefore = onBeforeNavigate !== undefined
413
+ useLayoutEffect(() => {
414
+ const element = anchor.current
415
+ if (!element || (entryState === undefined && !hasBefore)) return
416
+ setLinkState(element, entryState, hasBefore ? (nav) => before.current?.(nav) : undefined)
417
+ return () => setLinkState(element, undefined)
418
+ }, [entryState, hasBefore])
419
+ const state = route ? linkState(typeof to === "string" ? to : withoutBase(href, baseURL), route) : undefined
420
+ const key = "className" in rest ? "className" : "class"
421
+ const classes = [rest[key], state?.active && activeClass, state?.exact && exactActiveClass].filter(Boolean).join(" ")
422
+ return createElement(
423
+ "a",
424
+ {
425
+ ...rest,
426
+ ref,
427
+ ...(classes ? { [key]: classes } : {}),
428
+ ...(state?.exact && rest["aria-current"] === undefined ? { "aria-current": ariaCurrentValue } : {}),
429
+ href,
430
+ "data-hamur-prefetch": mode,
431
+ "data-hamur-replace": replace ? "" : undefined,
432
+ "data-hamur-view-transition": viewTransitionAttribute(viewTransition),
433
+ "data-hamur-pending-class": pendingClass === LINK_DEFAULTS.pendingClass ? undefined : pendingClass,
434
+ "data-hamur-trim": query ? "" : undefined,
435
+ "data-hamur-mask": mask === undefined ? undefined : hrefOf(mask),
436
+ "data-hamur-unmask": mask !== undefined && unmaskOnReload === false ? "false" : undefined,
437
+ ...linkExtraAttributes({
438
+ href,
439
+ external,
440
+ noRel,
441
+ rel: rest.rel,
442
+ target: rest.target,
443
+ prefetchedClass,
444
+ scroll,
445
+ prefetchDelay,
446
+ externalRelAttribute: d.externalRelAttribute,
447
+ }),
448
+ },
449
+ createElement(LinkHrefContext.Provider, { value: href }, children),
450
+ )
451
+ }
452
+
453
+ function CustomLink({ link: props, defaults }: { link: LinkProps; defaults: LinkDefaults }) {
454
+ const slot = useLinkSlot(props, linkDefaultsOf(useContext(AppContextContext), defaults))
455
+ return createElement(
456
+ LinkHrefContext.Provider,
457
+ { value: slot.href },
458
+ (props.children as (link: LinkSlot) => ComponentChildren)(slot),
459
+ )
460
+ }
461
+
462
+ function useLinkSlot(props: LinkProps, d: ResolvedLinkDefaults): LinkSlot {
463
+ const {
464
+ state: entryState,
465
+ mask,
466
+ unmaskOnReload,
467
+ viewTransition,
468
+ replace,
469
+ prefetch,
470
+ prefetchOn,
471
+ pendingClass = d.pendingClass,
472
+ ariaCurrentValue = "page",
473
+ external,
474
+ noRel,
475
+ prefetchedClass = d.prefetchedClass,
476
+ scroll,
477
+ prefetchDelay = d.prefetchDelay,
478
+ query,
479
+ rel,
480
+ target,
481
+ } = props
482
+ const baseURL = useContext(BaseURLContext)
483
+ const router = useContext(RouterContext)
484
+ const navigation = useNavigation()
485
+ const { to, route, hrefOf, href } = useLinkTarget(props, props)
486
+ const state = route ? linkState(typeof to === "string" ? to : withoutBase(href, baseURL), route) : undefined
487
+ return createLinkSlot({
488
+ href,
489
+ to,
490
+ attrs: linkAttributes({
491
+ href,
492
+ external,
493
+ ...linkPrefetchProps({ prefetch, prefetchOn }, d),
494
+ replace,
495
+ viewTransition,
496
+ pendingClass,
497
+ trim: !!query,
498
+ mask: mask === undefined ? undefined : hrefOf(mask),
499
+ unmaskOnReload,
500
+ ariaCurrent: state?.exact ? ariaCurrentValue : undefined,
501
+ rel,
502
+ target,
503
+ noRel,
504
+ prefetchedClass,
505
+ scroll,
506
+ prefetchDelay,
507
+ externalRelAttribute: d.externalRelAttribute,
508
+ }),
509
+ active: !!state?.active,
510
+ exact: !!state?.exact,
511
+ pending: linkPending(href, navigation, baseURL),
512
+ external,
513
+ options: {
514
+ replace,
515
+ state: entryState,
516
+ mask,
517
+ unmaskOnReload,
518
+ viewTransition,
519
+ scroll: scroll === false ? false : undefined,
520
+ },
521
+ router,
522
+ })
523
+ }
524
+
525
+ interface FormBaseProps extends Record<string, unknown> {
526
+ encType?: "application/x-www-form-urlencoded" | "multipart/form-data"
527
+ replace?: boolean
528
+ reset?: boolean
529
+ reloadDocument?: boolean
530
+ refresh?: boolean
531
+ /** With a server function: the store of `useAction(fn, { instance })` this form belongs to. */
532
+ instance?: string | number
533
+ restore?: boolean
534
+ onSubmit?: (args: FormSubmitArgs) => void
535
+ children?: ComponentChildren
536
+ }
537
+
538
+ export type FormProps<N extends string = string> = FormBaseProps &
539
+ /** A server function posts to this page with `?_fn=<id>`. */
540
+ (
541
+ | { action: ((...args: never[]) => unknown) & { readonly url: string }; method?: "post" }
542
+ | { action?: string | (RouteLocation & { name: N }); method?: "get" }
543
+ )
544
+
545
+ export function Form<N extends string = string>({
546
+ action,
547
+ method,
548
+ encType,
549
+ replace,
550
+ reset,
551
+ reloadDocument,
552
+ refresh,
553
+ instance,
554
+ restore,
555
+ onSubmit,
556
+ children,
557
+ ...rest
558
+ }: FormProps<N>) {
559
+ assertFormMethod(action, method)
560
+ const route = useContext(RouteContext)
561
+ const href = useContext(HrefContext)
562
+ const element = useRef<HTMLFormElement>(null)
563
+ const callback = useRef(onSubmit)
564
+ callback.current = onSubmit
565
+ const status = useMemo(createFormStatus, [])
566
+ const app = useContext(AppContextContext)
567
+ const router = useContext(RouterContext)
568
+ const fn = typeof action === "function" ? action : undefined
569
+ useLayoutEffect(
570
+ () =>
571
+ enhance(element.current!, {
572
+ onSubmit: (args) => {
573
+ status.submitted(args.formData)
574
+ callback.current?.(args)
575
+ },
576
+ ...(fn && app
577
+ ? {
578
+ call: (input: Record<string, unknown>, formData: FormData) =>
579
+ runFunctionForm(
580
+ app,
581
+ fn as never,
582
+ input,
583
+ formData,
584
+ () => router?.refresh() ?? Promise.resolve(),
585
+ status,
586
+ { refresh, instance },
587
+ ),
588
+ }
589
+ : {}),
590
+ }),
591
+ [status, fn, app, router, refresh, instance],
592
+ )
593
+ const page = route ? route.fullPath.replace(/#.*$/, "") : undefined
594
+ const target =
595
+ typeof action === "function"
596
+ ? functionFormAction(action as never, href(page ?? "/"), instance)
597
+ : action !== undefined
598
+ ? href(action as string | RouteLocation)
599
+ : page !== undefined
600
+ ? href(page)
601
+ : undefined
602
+ return createElement(
603
+ FormStatusContext.Provider,
604
+ { value: status },
605
+ createElement(
606
+ "form",
607
+ {
608
+ ...rest,
609
+ ref: element,
610
+ method: fn ? "post" : "get",
611
+ action: target,
612
+ enctype: encType,
613
+ "data-hamur-form": "",
614
+ "data-hamur-replace": replace ? "" : undefined,
615
+ "data-hamur-reset": reset ? "" : undefined,
616
+ "data-hamur-reload": reloadDocument ? "" : undefined,
617
+ "data-hamur-refresh": refresh === false ? "false" : undefined,
618
+ "data-hamur-restore": restore === false ? "false" : undefined,
619
+ },
620
+ children,
621
+ ),
622
+ )
623
+ }
624
+
625
+ export function useFormStatus(): FormStatus {
626
+ const store = useContext(FormStatusContext)
627
+ const [status, setStatus] = useLocalState(store ? store.get() : IDLE_FORM_STATUS)
628
+ useEffect(() => {
629
+ if (!store) return
630
+ setStatus(store.get())
631
+ return store.subscribe(() => setStatus(store.get()))
632
+ }, [store])
633
+ return status
634
+ }
635
+
636
+ export function useForm<I, O>(fn: Handler<I, O>): HandlerForm<I, O> {
637
+ const app = useContext(AppContextContext)
638
+ if (!app) throw new Error("useForm() must be called inside a Hamur app")
639
+ const current = useContext(SubmittedContext)
640
+ const submitted = useRef(current)
641
+ submitted.current = current
642
+ const form = useMemo(() => createForm(fn, { app, submitted: () => submitted.current }), [fn, app])
643
+ const [, setVersion] = useLocalState(form.version())
644
+ useEffect(() => {
645
+ setVersion(form.version())
646
+ return form.subscribe(() => setVersion(form.version()))
647
+ }, [form])
648
+ return form
649
+ }
650
+
651
+ export interface UseActionResult<I, O> {
652
+ run: ActionRunner<I, O>["run"]
653
+ state: O | undefined
654
+ pending: boolean
655
+ error: HamurError | undefined
656
+ failure: ActionFailure | undefined
657
+ reset(): void
658
+ }
659
+
660
+ export function useAction<I, O>(
661
+ fn: Handler<I, O>,
662
+ options: ActionOptions<O> & { instance?: string | number } = {},
663
+ ): UseActionResult<I, O> {
664
+ const { instance } = options
665
+ const router = useRouter()
666
+ const latest = useRef({ options, router })
667
+ latest.current = { options, router }
668
+ const { handlerState } = useContext(SubmittedContext)
669
+ const app = useContext(AppContextContext)
670
+ const runner = useMemo(
671
+ () =>
672
+ createActionRunner(fn, {
673
+ app,
674
+ instance,
675
+ options: () => latest.current.options,
676
+ refresh: () => latest.current.router.refresh(),
677
+ restored: restoredResult<O>(handlerState, fn.id, instance),
678
+ }),
679
+ [fn, instance, app],
680
+ )
681
+ const [snapshot, setSnapshot] = useLocalState(runner.get())
682
+ const below = useContext(FormStatusContext)
683
+ useEffect(() => {
684
+ setSnapshot(runner.get())
685
+ const unlink = below
686
+ ? below.owner.link(fn.id, runner, instance)
687
+ : app
688
+ ? linkActionRunner(app, fn.id, runner, instance)
689
+ : undefined
690
+ const stop = runner.subscribe(() => setSnapshot(runner.get()))
691
+ return () => {
692
+ stop()
693
+ unlink?.()
694
+ }
695
+ }, [runner, app, below, fn, instance])
696
+ const { state, pending, error, failure } = snapshot
697
+ return useMemo(
698
+ () => ({ run: runner.run, state, pending, error, failure, reset: runner.reset }),
699
+ [runner, state, pending, error, failure],
700
+ )
701
+ }
702
+
703
+ export function useRoute<N extends RouteName>(name: N): RouteFor<N>
704
+ export function useRoute<N extends RouteName = never>(): RouteFor<N>
705
+ export function useRoute(): RouteValue
706
+ export function useRoute(name?: string): RouteValue {
707
+ const route = useContext(RouteContext)
708
+ if (!route) throw new Error("useRoute() must be called inside a Hamur app")
709
+ return route
710
+ }
711
+
712
+ export function useResolvedPath(to: string, { relative }: { relative?: "route" } = {}): string {
713
+ return resolveRelative(to, useRoute(), relative)
714
+ }
715
+
716
+ export function useRouter(): RouterApi {
717
+ const router = useContext(RouterContext)
718
+ if (!router) throw new Error("useRouter() must be called inside a Hamur app")
719
+ return router
720
+ }
721
+
722
+ export function useData<T = unknown>(...unknownRoute: UseDataArgs<T>): RouteLoaderData<T> {
723
+ const data = useContext(DataContext)
724
+ const key = useContext(EntryContext)
725
+ if (key === null) throw new Error("useData() must be called inside a Hamur app")
726
+ return (data[key] ?? null) as RouteLoaderData<T>
727
+ }
728
+
729
+ export function useRouteData<N extends RouteDataName>(name: N): RouteDataOf<N> {
730
+ const route = useContext(RouteContext)
731
+ const data = useContext(DataContext)
732
+ if (!route) throw new Error("useRouteData() must be called inside a Hamur app")
733
+ return routeDataOf(route, data, name) as RouteDataOf<N>
734
+ }
735
+
736
+ export function useMatches(): MatchedRoute[] {
737
+ const route = useContext(RouteContext)
738
+ const data = useContext(DataContext)
739
+ if (!route) throw new Error("useMatches() must be called inside a Hamur app")
740
+ return useMemo(() => matchesOf(route, data), [route, data])
741
+ }
742
+
743
+ const isDev = (import.meta as { dev?: boolean }).dev === true
744
+ const warnedSlots = new Set<string>()
745
+
746
+ export function Outlet({ context, name }: { context?: unknown; name?: string }) {
747
+ const next = useContext(OutletContext) ?? null
748
+ const slots = useContext(SlotsContext)
749
+ const owner = useContext(EntryContext)
750
+ let child = next
751
+ if (isDev && name === undefined) noteOutlet(owner)
752
+ if (name !== undefined) {
753
+ child = slots?.[name] ?? null
754
+ const key = `${owner}:${name}`
755
+ if (isDev && !(slots && name in slots) && !warnedSlots.has(key)) {
756
+ warnedSlots.add(key)
757
+ console.warn(`Outlet name "${name}" has no slot in ${owner}`)
758
+ }
759
+ }
760
+ return context === undefined ? child : createElement(OutletValueContext.Provider as never, { value: context }, child)
761
+ }
762
+
763
+ export function useOutletContext<T = unknown>(): T {
764
+ return useContext(OutletValueContext) as T
765
+ }
766
+
767
+ export function useLayoutSegments(): string[] {
768
+ const route = useContext(RouteContext)
769
+ const entry = useContext(EntryContext)
770
+ if (!route) throw new Error("useLayoutSegments() must be called inside a Hamur app")
771
+ return useMemo(() => layoutSegments(route, entry), [route, entry])
772
+ }
773
+
774
+ export function useLayoutSegment(): string | null {
775
+ return useLayoutSegments()[0] ?? null
776
+ }
777
+
778
+ export function useLayout(): { name: string | false; props: Record<string, unknown> } {
779
+ const layout = useContext(LayoutContext)
780
+ if (!layout) throw new Error("useLayout() must be called inside a Hamur app")
781
+ return layout
782
+ }
783
+
784
+ export function ClientOnly({ children, fallback }: { children?: ComponentChildren; fallback?: ComponentChildren }) {
785
+ const [hydrated, setHydrated] = useLocalState(false)
786
+ useEffect(() => setHydrated(true), [])
787
+ if (!hydrated) return fallback ?? null
788
+ return createElement(ClientOnlyContext.Provider, { value: { fallback } }, children)
789
+ }
790
+
791
+ export { useId }
792
+
793
+ export function useHydrated(): boolean {
794
+ const app = useApp()
795
+ const [hydrated, setHydrated] = useLocalState(!isServer && !app.asyncData.hydrating)
796
+ useEffect(() => {
797
+ const sync = () => setHydrated(!app.asyncData.hydrating)
798
+ sync()
799
+ return app.hooks.hook("app:mounted", sync)
800
+ }, [app])
801
+ return hydrated
802
+ }
803
+
804
+ export function DevOnly({ children, fallback }: { children?: ComponentChildren; fallback?: ComponentChildren }) {
805
+ return isDev ? children : (fallback ?? null)
806
+ }
807
+
808
+ const isThenable = (value: unknown): value is PromiseLike<unknown> =>
809
+ typeof (value as { then?: unknown } | null)?.then === "function"
810
+
811
+ const outcomes = new WeakMap<object, Settled>()
812
+ const waits = new WeakMap<object, PromiseLike<unknown>>()
813
+
814
+ function outcomeOf(promise: PromiseLike<unknown>): Settled {
815
+ const known = settledOf(promise) ?? outcomes.get(promise)
816
+ if (known) return known
817
+ let wait = waits.get(promise)
818
+ if (!wait) {
819
+ wait = promise.then(
820
+ (value) => void outcomes.set(promise, { status: "fulfilled", value }),
821
+ (reason) => void outcomes.set(promise, { status: "rejected", reason }),
822
+ )
823
+ waits.set(promise, wait)
824
+ }
825
+ throw wait
826
+ }
827
+
828
+ export interface AwaitProps<T> {
829
+ resolve: T
830
+ fallback?: ComponentChildren
831
+ error?: (error: Error) => ComponentChildren
832
+ children: (value: Awaited<T>) => ComponentChildren
833
+ }
834
+
835
+ let warnedAwait = false
836
+
837
+ function Resolved<T>({ resolve, error, children }: Omit<AwaitProps<T>, "fallback">): ComponentChildren {
838
+ const outcome: Settled = isThenable(resolve) ? outcomeOf(resolve) : { status: "fulfilled", value: resolve }
839
+ if (outcome.status === "rejected") {
840
+ if (error) return error(outcome.reason as Error)
841
+ throw outcome.reason
842
+ }
843
+ if (typeof children !== "function") {
844
+ if (isDev && !warnedAwait) {
845
+ warnedAwait = true
846
+ console.warn("Await has nothing to render for its value")
847
+ }
848
+ return null
849
+ }
850
+ return children(outcome.value as Awaited<T>)
851
+ }
852
+
853
+ export function Await<T>({ fallback, ...props }: AwaitProps<T>): ComponentChildren {
854
+ return createElement(
855
+ Suspense,
856
+ { fallback: fallback ?? null },
857
+ createElement(Resolved as FunctionComponent<Omit<AwaitProps<T>, "fallback">>, props),
858
+ )
859
+ }
860
+
861
+ export function useDeferred<T>(promise: T): Awaited<T> {
862
+ if (!isThenable(promise)) return promise as Awaited<T>
863
+ const outcome = outcomeOf(promise)
864
+ if (outcome.status === "rejected") throw outcome.reason
865
+ return outcome.value as Awaited<T>
866
+ }
867
+
868
+ export type TimeProps = TimeInput & Omit<TimeHTMLAttributes<HTMLTimeElement>, keyof TimeInput>
869
+
870
+ export function Time(props: TimeProps) {
871
+ const app = useApp()
872
+ const [now, setNow] = useLocalState<number | undefined>(undefined)
873
+ const view = timeView(app, useRoute().path, props, now)
874
+ const { interval } = view
875
+ useEffect(() => (interval === undefined ? undefined : watchTime(interval, setNow)), [interval])
876
+ return createElement(
877
+ "time",
878
+ { ...timeAttributes(props), datetime: view.iso, "data-locale": view.locale, "data-time-zone": view.timeZone },
879
+ view.text,
880
+ )
881
+ }
882
+
883
+ export type { LoadingIndicatorProps } from "hamur/adapter"
884
+
885
+ export function useLoadingIndicator(
886
+ options?: LoadingIndicatorOptions,
887
+ ): LoadingIndicatorState & LoadingIndicatorActions {
888
+ const store = createLoadingIndicator(useApp(), options)
889
+ const source = useContext(NavigationContext)
890
+ const [state, setState] = useLocalState(store.get())
891
+ useEffect(() => {
892
+ setState(store.get())
893
+ return store.subscribe(() => setState(store.get()))
894
+ }, [store])
895
+ useEffect(() => (source ? store.follow(source) : undefined), [store, source])
896
+ return { ...state, start: store.start, finish: store.finish, set: store.set, clear: store.clear }
897
+ }
898
+
899
+ export function useAppUpdate(): AppUpdateState & AppUpdateActions {
900
+ const store = createAppUpdate(useApp())
901
+ const [state, setState] = useLocalState<AppUpdateState>(APP_UPDATE_OFF)
902
+ useEffect(() => {
903
+ setState(store.get())
904
+ return store.subscribe(() => setState(store.get()))
905
+ }, [store])
906
+ return { ...state, check: store.check }
907
+ }
908
+
909
+ export function LoadingIndicator(props: LoadingIndicatorProps) {
910
+ const { color, errorColor, height } = props
911
+ const { progress, isLoading, error } = useLoadingIndicator(loadingIndicatorOptions(props))
912
+ const element = useRef<HTMLDivElement>(null)
913
+ useEffect(() => {
914
+ if (element.current)
915
+ paintLoadingIndicator(element.current, { progress, isLoading, error }, { color, errorColor, height })
916
+ }, [progress, isLoading, error, color, errorColor, height])
917
+ return createElement("div", { ref: element, "data-hamur-loading-indicator": "", "aria-hidden": "true" })
918
+ }
919
+
920
+ export function useRouteAnnouncer(): RouteAnnouncerState & RouteAnnouncerActions {
921
+ const store = createRouteAnnouncer(useApp())
922
+ const [state, setState] = useLocalState(store.get())
923
+ useEffect(() => {
924
+ setState(store.get())
925
+ return store.subscribe(() => setState(store.get()))
926
+ }, [store])
927
+ return { ...state, set: store.set, polite: store.polite, assertive: store.assertive }
928
+ }
929
+
930
+ export function RouteAnnouncer({
931
+ politeness,
932
+ class: className,
933
+ style,
934
+ }: {
935
+ politeness?: RouteAnnouncerPoliteness
936
+ class?: string
937
+ style?: CSSProperties | string
938
+ children?: ComponentChildren
939
+ }) {
940
+ const store = createRouteAnnouncer(useApp())
941
+ const { message, politeness: current } = useRouteAnnouncer()
942
+ const element = useRef<HTMLDivElement>(null)
943
+ const key = useId()
944
+ const [, setTick] = useLocalState(0)
945
+ const owner = store.claim(key, () => setTick((count) => count + 1))
946
+ const styled = !!className || !!style
947
+ useEffect(() => () => store.release(key), [store, key])
948
+ useEffect(() => (owner ? store.mount() : undefined), [store, owner])
949
+ useEffect(() => {
950
+ if (owner && !styled && element.current) hideAnnouncer(element.current)
951
+ }, [owner, styled])
952
+ if (!owner) return createElement("div", { "aria-live": "off", "aria-atomic": "true" })
953
+ const live = politeness ?? current
954
+ return createElement(
955
+ "div",
956
+ {
957
+ ref: element,
958
+ id: ROUTE_ANNOUNCER_ID,
959
+ "aria-live": live,
960
+ "aria-atomic": "true",
961
+ role: announcerRole(live),
962
+ class: className,
963
+ style,
964
+ },
965
+ message,
966
+ )
967
+ }
968
+
969
+ export function useAnnouncer({ politeness = "polite" }: { politeness?: AnnouncerPoliteness } = {}): Pick<
970
+ AnnouncerState,
971
+ "message" | "politeness"
972
+ > &
973
+ AnnouncerActions {
974
+ const store = createAnnouncer(useApp())
975
+ const [state, setState] = useLocalState(store.get())
976
+ useEffect(() => {
977
+ setState(store.get())
978
+ return store.subscribe(() => setState(store.get()))
979
+ }, [store])
980
+ const actions = useMemo(() => announcerActions(store, politeness), [store, politeness])
981
+ return { message: state.message, politeness: state.politeness, ...actions }
982
+ }
983
+
984
+ export function Announcer() {
985
+ const store = createAnnouncer(useApp())
986
+ const [{ regions }, setState] = useLocalState(store.get())
987
+ const polite = useRef<HTMLDivElement>(null)
988
+ const assertive = useRef<HTMLDivElement>(null)
989
+ useEffect(() => {
990
+ setState(store.get())
991
+ return store.subscribe(() => setState(store.get()))
992
+ }, [store])
993
+ useEffect(() => store.mount(), [store])
994
+ useEffect(() => {
995
+ for (const element of [polite.current, assertive.current]) if (element) hideAnnouncer(element)
996
+ }, [])
997
+ return createElement(
998
+ Fragment,
999
+ null,
1000
+ createElement(
1001
+ "div",
1002
+ { ref: polite, id: ANNOUNCER_POLITE_ID, "aria-live": "polite", "aria-atomic": "true", role: "status" },
1003
+ regions.polite,
1004
+ ),
1005
+ createElement(
1006
+ "div",
1007
+ { ref: assertive, id: ANNOUNCER_ASSERTIVE_ID, "aria-live": "assertive", "aria-atomic": "true", role: "alert" },
1008
+ regions.assertive,
1009
+ ),
1010
+ )
1011
+ }
1012
+
1013
+ export function useApp(): AppContext {
1014
+ const app = useContext(AppContextContext)
1015
+ if (!app) throw new Error("useApp() must be called inside a Hamur app")
1016
+ return app
1017
+ }
1018
+
1019
+ export function useRuntimeHook<K extends keyof AppHooks>(name: K, fn: AppHooks[K]): void {
1020
+ const app = useApp()
1021
+ const latest = useRef(fn)
1022
+ latest.current = fn
1023
+ useEffect(
1024
+ () =>
1025
+ app.hooks.hook(name, ((...args: unknown[]) =>
1026
+ (latest.current as (...rest: unknown[]) => unknown)(...args)) as AppHooks[K]),
1027
+ [app, name],
1028
+ )
1029
+ }
1030
+
1031
+ export function useReportWebVitals(fn: (metric: WebVitalMetric) => void | Promise<void>): void {
1032
+ const app = useApp()
1033
+ const latest = useRef(fn)
1034
+ latest.current = fn
1035
+ useEffect(() => reportWebVitals(app, (metric) => latest.current(metric)), [app])
1036
+ }
1037
+
1038
+ export function onAppReady(fn: () => void | Promise<void>): void {
1039
+ const app = useApp()
1040
+ const latest = useRef(fn)
1041
+ latest.current = fn
1042
+ const scheduled = useRef(false)
1043
+ useEffect(() => {
1044
+ if (scheduled.current) return
1045
+ scheduled.current = true
1046
+ whenAppReady(app, () => latest.current())
1047
+ }, [app])
1048
+ }
1049
+
1050
+ export function onPrehydrate(fn: (el: Element) => void): string | undefined {
1051
+ return prehydrate(useApp(), fn)
1052
+ }
1053
+
1054
+ export function useRequestEvent(): HamurEvent | undefined {
1055
+ return requestEventOf(useApp())
1056
+ }
1057
+
1058
+ /** Preview mode: enabled by the payload's `draft` or by `?preview=true` on the first URL; `state` is the app's own store for preview values. */
1059
+ export function usePreviewMode(): PreviewMode {
1060
+ return previewModeOf(useApp())
1061
+ }
1062
+
1063
+ export function useRequestHeaders(names?: readonly string[]): Record<string, string> {
1064
+ return requestHeadersOf(useApp(), names)
1065
+ }
1066
+
1067
+ export function useRequestHeader(name: string): string | undefined {
1068
+ return requestHeaderOf(useApp(), name)
1069
+ }
1070
+
1071
+ export function useRequestURL(): URL {
1072
+ return requestURLOf(useApp())
1073
+ }
1074
+
1075
+ export function useRequestFetch(): $Fetch {
1076
+ return requestFetchOf(useApp())
1077
+ }
1078
+
1079
+ export function setResponseStatus(status: number, statusText?: string): void {
1080
+ setResponseStatusOf(useApp(), status, statusText)
1081
+ }
1082
+
1083
+ export function useResponseHeader(name: string): [string | undefined, (value: string | undefined) => void] {
1084
+ const header = responseHeaderOf(useApp(), name)
1085
+ return [header.get(), header.set]
1086
+ }
1087
+
1088
+ export function HttpStatusCode({ code, text }: { code: number; text?: string }): null {
1089
+ setResponseStatus(code, text)
1090
+ return null
1091
+ }
1092
+
1093
+ export function HttpHeader({ name, value }: { name: string; value: string }): null {
1094
+ responseHeaderOf(useApp(), name).set(value)
1095
+ return null
1096
+ }
1097
+
1098
+ export function useAsyncDataEntry<T = unknown>(key: string): { data: T | undefined; setData(data: T): void }
1099
+ export function useAsyncDataEntry<I, O>(fn: Handler<I, O>, input?: I): { data: O | undefined; setData(data: O): void }
1100
+ export function useAsyncDataEntry<T = unknown>(
1101
+ target: string | HandlerReference,
1102
+ input?: unknown,
1103
+ ): { data: T | undefined; setData(data: T): void } {
1104
+ const key = typeof target === "string" ? target : asyncDataKey(target, input)
1105
+ const app = useApp()
1106
+ const [data, setLocal] = useLocalState(() => app.asyncData.get<T>(key)?.data)
1107
+ useEffect(() => {
1108
+ setLocal(app.asyncData.get<T>(key)?.data)
1109
+ return app.asyncData.subscribe(key, () => setLocal(app.asyncData.get<T>(key)?.data))
1110
+ }, [app, key])
1111
+ const setData = useCallback((next: T) => app.asyncData.setData(key, next), [app, key])
1112
+ return { data, setData }
1113
+ }
1114
+
1115
+ export function clearState(keys?: Parameters<typeof clearStateOf>[1], options?: { reset?: boolean }): void {
1116
+ clearStateOf(useApp(), keys, options)
1117
+ }
1118
+
1119
+ export function callOnce(
1120
+ key: string,
1121
+ fn: () => unknown | Promise<unknown>,
1122
+ options?: { mode?: "render" | "navigation" },
1123
+ ): Promise<void> {
1124
+ return callOnceOf(useApp(), key, fn, options)
1125
+ }
1126
+
1127
+ export function useRuntimeConfig(): ClientRuntimeConfig {
1128
+ return runtimeConfigOf(useApp())
1129
+ }
1130
+
1131
+ export function useSiteConfig(): SiteConfig {
1132
+ return siteConfigOf(useApp())
1133
+ }
1134
+
1135
+ const IDLE: NavigationState = { state: "idle", pending: false }
1136
+
1137
+ export function useNavigation(): NavigationState {
1138
+ const source = useContext(NavigationContext)
1139
+ const [navigation, setNavigation] = useLocalState(source ? source.get() : IDLE)
1140
+ useEffect(() => {
1141
+ if (!source) return
1142
+ setNavigation(source.get())
1143
+ return source.subscribe(() => setNavigation(source.get()))
1144
+ }, [source])
1145
+ return navigation
1146
+ }
1147
+
1148
+ const NOT_PENDING = { pending: false }
1149
+
1150
+ /** Inside a `Link`'s children, whether a navigation to that link is in flight; `{ pending: false }` anywhere else. */
1151
+ export function useLinkStatus(): { pending: boolean } {
1152
+ const href = useContext(LinkHrefContext)
1153
+ const baseURL = useContext(BaseURLContext)
1154
+ const state = useNavigation()
1155
+ return href !== null && linkPending(href, state, baseURL) ? { pending: true } : NOT_PENDING
1156
+ }
1157
+
1158
+ function useNavigationHook(kind: NavigationHookKind, fn: (navigation: Navigation) => unknown): void {
1159
+ const latest = useRef(fn)
1160
+ latest.current = fn
1161
+ useLayoutEffect(() => navigationHook(kind, ((navigation: Navigation) => latest.current(navigation)) as never), [kind])
1162
+ }
1163
+
1164
+ export const onBeforeNavigate = (fn: BeforeNavigateHook): void => useNavigationHook("before", fn)
1165
+ export const onNavigate = (fn: NavigateHook): void => useNavigationHook("navigate", fn)
1166
+ export const onAfterNavigate = (fn: AfterNavigateHook): void => useNavigationHook("after", fn)
1167
+
1168
+ /** Runs `fn` after the component mounts and each time its kept page is shown again. */
1169
+ export function onPageActivated(fn: () => void): void {
1170
+ const own = useContext(ActivationContext)
1171
+ const latest = useRef(fn)
1172
+ latest.current = fn
1173
+ useEffect(() => {
1174
+ const run = () => latest.current()
1175
+ if (shown(own)) later(true, run)
1176
+ own?.on.add(run)
1177
+ return () => void own?.on.delete(run)
1178
+ }, [own])
1179
+ }
1180
+
1181
+ /** Runs `fn` each time its kept page is hidden and when the component unmounts on screen. */
1182
+ export function onPageDeactivated(fn: () => void): void {
1183
+ const own = useContext(ActivationContext)
1184
+ const latest = useRef(fn)
1185
+ latest.current = fn
1186
+ useEffect(() => {
1187
+ const run = () => latest.current()
1188
+ own?.off.add(run)
1189
+ return () => {
1190
+ own?.off.delete(run)
1191
+ if (shown(own)) later(false, run)
1192
+ }
1193
+ }, [own])
1194
+ }
1195
+
1196
+ function useRouteGuard(kind: RouteGuardKind, fn: NavigationGuard): void {
1197
+ const entry = useContext(EntryContext)
1198
+ const latest = useRef(fn)
1199
+ latest.current = fn
1200
+ useLayoutEffect(() => routeGuard(kind, entry ?? undefined, (to, from) => latest.current(to, from)), [kind, entry])
1201
+ }
1202
+
1203
+ export const onBeforeRouteLeave = (fn: NavigationGuard): void => useRouteGuard("leave", fn)
1204
+ export const onBeforeRouteUpdate = (fn: NavigationGuard): void => useRouteGuard("update", fn)
1205
+
1206
+ export function usePreventNavigate(fn: NavigationBlocker): void {
1207
+ const latest = useRef(fn)
1208
+ latest.current = fn
1209
+ useLayoutEffect(() => navigationBlocker((args) => latest.current(args)), [])
1210
+ }
1211
+
1212
+ export function useBlocker(options: ShouldBlock | UseBlockerOptions): Blocker {
1213
+ const store = useRef<BlockerStore | null>(null)
1214
+ store.current ??= createBlocker(options)
1215
+ store.current.setOptions(options)
1216
+ const blocker = store.current
1217
+ const [value, setValue] = useLocalState(blocker.get())
1218
+ useLayoutEffect(() => {
1219
+ const unsubscribe = blocker.subscribe(() => setValue(blocker.get()))
1220
+ const stop = blocker.start()
1221
+ return () => (stop(), unsubscribe())
1222
+ }, [blocker])
1223
+ useLayoutEffect(() => blocker.sync())
1224
+ return value
1225
+ }
1226
+
1227
+ export function useSnapshot<T>(key: string, options: SnapshotOptions<T>): void {
1228
+ const latest = useRef(options)
1229
+ latest.current = options
1230
+ useLayoutEffect(
1231
+ () =>
1232
+ registerSnapshot<T>(key, {
1233
+ capture: () => latest.current.capture(),
1234
+ restore: (value) => latest.current.restore(value),
1235
+ }),
1236
+ [key],
1237
+ )
1238
+ }
1239
+
1240
+ export function useSearch(): { value: RouteValue["search"]; set: SetSearch }
1241
+ export function useSearch<S>(select: (search: RouteValue["search"]) => S): { value: S; set: SetSearch }
1242
+ export function useSearch<S>(select?: (search: RouteValue["search"]) => S): {
1243
+ value: S | RouteValue["search"]
1244
+ set: SetSearch
1245
+ } {
1246
+ const store = useContext(SearchContext)
1247
+ if (!store) throw new Error("useSearch() must be called inside a Hamur app")
1248
+ const read = () => (select ? select(store.get()) : store.get())
1249
+ const latest = useRef(read)
1250
+ latest.current = read
1251
+ const shown = useRef<unknown>(undefined)
1252
+ const next = read()
1253
+ if (shown.current === undefined || !equalSearch(shown.current, next)) shown.current = next
1254
+ const [, force] = useLocalState(0)
1255
+ useEffect(
1256
+ () => store.subscribe(() => !equalSearch(shown.current, latest.current()) && force((count) => count + 1)),
1257
+ [store],
1258
+ )
1259
+ const set = useCallback<SetSearch>(
1260
+ (change, { replace = true } = {}) => {
1261
+ const update = { query: (prev: RouteValue["search"]) => (typeof change === "function" ? change(prev) : change) }
1262
+ return replace ? store.router().replace(update) : store.router().navigate(update)
1263
+ },
1264
+ [store],
1265
+ )
1266
+ return useMemo(() => ({ value: shown.current as S, set }), [shown.current, set])
1267
+ }
1268
+
1269
+ export function usePoll(ms: number, options: { keys?: string[] } = {}): void {
1270
+ pollInterval(ms)
1271
+ const current = useRouter()
1272
+ const router = useRef(current)
1273
+ router.current = current
1274
+ const keys = useRef(options.keys)
1275
+ keys.current = options.keys
1276
+ useEffect(
1277
+ () => startPoll(ms, () => (keys.current ? router.current.refresh(keys.current) : router.current.refresh())),
1278
+ [ms],
1279
+ )
1280
+ }
1281
+
1282
+ export function useOnline(): boolean {
1283
+ const [online, setOnline] = useLocalState(true)
1284
+ useEffect(() => {
1285
+ setOnline(isOnline())
1286
+ return subscribeOnline(setOnline)
1287
+ }, [])
1288
+ return online
1289
+ }
1290
+
1291
+ export function useSyncedState<T>(key: string, initial: T, options: SyncedStateOptions = {}): [T, (value: T) => void] {
1292
+ const state = useMemo(() => syncedState(key, initial, options), [key, options.room])
1293
+ const [value, setValue] = useLocalState<T>(initial)
1294
+ useEffect(() => {
1295
+ setValue(() => state.get())
1296
+ return state.subscribe((next) => setValue(() => next))
1297
+ }, [state])
1298
+ return [value, state.set]
1299
+ }
1300
+
1301
+ export function useOptimistic<T, A = PendingRun>(value: T, reduce: (current: T, pending: A[]) => T): T {
1302
+ const app = useContext(AppContextContext)
1303
+ const source = useMemo(() => optimisticSource(app), [app])
1304
+ const [pending, setPending] = useLocalState(source.get)
1305
+ useEffect(() => {
1306
+ setPending(() => source.get())
1307
+ return source.subscribe(() => setPending(() => source.get()))
1308
+ }, [source])
1309
+ return pending.length ? reduce(value, pending as unknown as A[]) : value
1310
+ }
1311
+
1312
+ export function useError(): RouteError | undefined
1313
+ export function useError(): ErrorPageProps | undefined {
1314
+ const { store, initial } = useContext(ErrorContext)
1315
+ const [error, setError] = useLocalState(store ? store.get() : initial)
1316
+ useEffect(() => {
1317
+ if (!store) return
1318
+ setError(store.get())
1319
+ return store.subscribe(() => setError(store.get()))
1320
+ }, [store])
1321
+ return error
1322
+ }
1323
+
1324
+ export interface ErrorBoundaryProps {
1325
+ fallback: (props: ErrorBoundaryFallbackProps) => ComponentChildren
1326
+ children?: ComponentChildren
1327
+ }
1328
+
1329
+ interface BoundaryRecord {
1330
+ name: string
1331
+ message: string
1332
+ }
1333
+
1334
+ const recordError = ({ name, message }: BoundaryRecord) => Object.assign(new Error(message), { name })
1335
+
1336
+ /** Gives its boundary an id and the app; on the client a boundary that failed in the server HTML hydrates the fallback with the server's error. */
1337
+ function BoundaryChildren({ boundary, children }: { boundary: ErrorBoundary; children?: ComponentChildren }) {
1338
+ const key = `$boundary:${useId()}`
1339
+ const app = useContext(AppContextContext)
1340
+ boundary.key = key
1341
+ boundary.app = app
1342
+ const seeded = isServer ? undefined : app?.state?.get<BoundaryRecord>(key)
1343
+ useLayoutEffect(() => {
1344
+ if (!seeded) return
1345
+ app!.state.set(key, undefined)
1346
+ boundary.setState({ failed: true, error: recordError(seeded) })
1347
+ }, [])
1348
+ return seeded ? boundary.props.fallback({ error: recordError(seeded), reset: boundary.reset }) : children
1349
+ }
1350
+
1351
+ export class ErrorBoundary extends Component<ErrorBoundaryProps, { failed: boolean; error: unknown }> {
1352
+ state = { failed: false, error: undefined as unknown }
1353
+ key: string | undefined
1354
+ app: AppContext | null = null
1355
+
1356
+ static getDerivedStateFromError(error: unknown) {
1357
+ return { failed: true, error }
1358
+ }
1359
+
1360
+ reset = () => this.setState({ failed: false, error: undefined })
1361
+
1362
+ render() {
1363
+ if (!this.state.failed) return createElement(BoundaryChildren, { boundary: this, children: this.props.children })
1364
+ if (isServer && this.app) {
1365
+ const error = (this.state.error = publicError(this.app, this.state.error))
1366
+ if (this.key && error instanceof Error)
1367
+ this.app.state?.set(this.key, { name: error.name, message: error.message })
1368
+ }
1369
+ return this.props.fallback({ error: this.state.error, reset: this.reset })
1370
+ }
1371
+ }
1372
+
1373
+ export interface ClientFallbackProps {
1374
+ fallback?: ComponentChildren
1375
+ keepFallback?: boolean
1376
+ onSsrError?: (error: unknown) => unknown
1377
+ children?: ComponentChildren
1378
+ }
1379
+
1380
+ /** Gives its boundary an id and the app; on the client a boundary the server rendered as its fallback hydrates it, then renders the children fresh. */
1381
+ function FallbackChildren({ boundary, children }: { boundary: ClientFallback; children?: ComponentChildren }) {
1382
+ const id = useId()
1383
+ boundary.id = id
1384
+ boundary.app = useContext(AppContextContext)
1385
+ const [rendered] = useLocalState(() => !isServer && clientFallbackIds.has(id))
1386
+ const [fresh, setFresh] = useLocalState(false)
1387
+ useLayoutEffect(() => {
1388
+ if (!rendered) return
1389
+ clientFallbackIds.delete(id)
1390
+ setFresh(true)
1391
+ }, [])
1392
+ if (rendered && !fresh) return boundary.props.fallback ?? null
1393
+ return rendered && boundary.props.keepFallback
1394
+ ? createElement(Suspense, { fallback: boundary.props.fallback ?? null }, children)
1395
+ : children
1396
+ }
1397
+
1398
+ /** A throw in `children` during SSR renders `fallback` in the HTML; the browser renders `children` again from scratch. */
1399
+ export class ClientFallback extends Component<ClientFallbackProps, { failed: boolean; error: unknown }> {
1400
+ state = { failed: false, error: undefined as unknown }
1401
+ id: string | undefined
1402
+ app: AppContext | null = null
1403
+
1404
+ static getDerivedStateFromError(error: unknown) {
1405
+ return { failed: true, error }
1406
+ }
1407
+
1408
+ render() {
1409
+ if (!this.state.failed) return createElement(FallbackChildren, { boundary: this, children: this.props.children })
1410
+ if (isServer && this.app && this.id) clientFallback(this.app, this.id, this.state.error, this.props.onSsrError)
1411
+ return this.props.fallback ?? null
1412
+ }
1413
+ }
1414
+
1415
+ export function DefaultErrorPage({ error }: { error: ErrorPageProps }) {
1416
+ return createElement(
1417
+ "main",
1418
+ { style: { fontFamily: "system-ui, sans-serif", textAlign: "center", padding: "4rem 1rem" } },
1419
+ createElement("h1", { style: { fontSize: "4rem", margin: 0 } }, String(error.status)),
1420
+ createElement("p", null, error.message),
1421
+ isDev && error.code
1422
+ ? createElement(
1423
+ "p",
1424
+ null,
1425
+ createElement(
1426
+ "a",
1427
+ { href: diagnosticURL(error.code as DiagnosticCode), target: "_blank", rel: "noopener" },
1428
+ error.code,
1429
+ ),
1430
+ )
1431
+ : null,
1432
+ error.stack ? createElement("pre", { style: { textAlign: "left", overflow: "auto" } }, error.stack) : null,
1433
+ createElement(Link, { to: "/" }, "Back home"),
1434
+ )
1435
+ }
1436
+
1437
+ const pendingApply = new WeakSet<Head>()
1438
+
1439
+ function scheduleApply(head: Head) {
1440
+ if (pendingApply.has(head)) return
1441
+ pendingApply.add(head)
1442
+ queueMicrotask(() => {
1443
+ pendingApply.delete(head)
1444
+ head.apply()
1445
+ })
1446
+ }
1447
+
1448
+ const isServer = typeof window === "undefined"
1449
+
1450
+ function useHeadOnServer(head: Head, input: HeadInput, options?: { server: true }): void {
1451
+ const entry = useRef<HeadEntry | undefined>(undefined)
1452
+ if (entry.current) entry.current.patch(input)
1453
+ else entry.current = head.push(input, options)
1454
+ }
1455
+
1456
+ function useClientHead(head: Head, input: HeadInput): void {
1457
+ const rank = useRef(0)
1458
+ rank.current ||= nextRank()
1459
+ const entry = useRef<HeadEntry | undefined>(undefined)
1460
+ useLayoutEffect(() => {
1461
+ entry.current = mountHead(head, rank.current, input)
1462
+ scheduleApply(head)
1463
+ return () => {
1464
+ entry.current?.dispose()
1465
+ entry.current = undefined
1466
+ scheduleApply(head)
1467
+ }
1468
+ }, [head])
1469
+ useLayoutEffect(() => {
1470
+ entry.current?.patch(input)
1471
+ scheduleApply(head)
1472
+ })
1473
+ }
1474
+
1475
+ export function useHead(input: HeadInput): void {
1476
+ const head = useContext(HeadContext)
1477
+ if (!head) throw new Error("useHead() must be called inside a Hamur app")
1478
+ if (isServer) useHeadOnServer(head, input)
1479
+ else useClientHead(head, input)
1480
+ }
1481
+
1482
+ export function useSeoMeta(input: SeoMetaInput): void {
1483
+ useHead(seoMetaToHead(input))
1484
+ }
1485
+
1486
+ type ServerHeadInput = Omit<HeadInput, "title" | "titleTemplate">
1487
+ type ServerSeoMetaInput = Omit<SeoMetaInput, "title" | "titleTemplate">
1488
+
1489
+ export function useHeadSafe(input: HeadSafeInput): void {
1490
+ useHead(sanitizeHead(input))
1491
+ }
1492
+
1493
+ type HeadProps<K extends "meta" | "link" | "script" | "style"> = NonNullable<HeadInput[K]>[number]
1494
+ type HeadAttrsProps = Record<string, string>
1495
+
1496
+ export function HeadTitle({ title, template }: { title: string; template?: string }): null {
1497
+ useHead({ title, titleTemplate: template })
1498
+ return null
1499
+ }
1500
+
1501
+ export const HeadMeta: FunctionComponent<HeadProps<"meta">> = (props) => {
1502
+ useHead({ meta: [{ ...(props as HeadProps<"meta">) }] })
1503
+ return null
1504
+ }
1505
+
1506
+ export const HeadLink: FunctionComponent<HeadProps<"link">> = (props) => {
1507
+ useHead({ link: [{ ...(props as HeadProps<"link">) }] })
1508
+ return null
1509
+ }
1510
+
1511
+ export const HeadScript: FunctionComponent<HeadProps<"script">> = (props) => {
1512
+ useHead({ script: [{ ...(props as HeadProps<"script">) }] })
1513
+ return null
1514
+ }
1515
+
1516
+ export const HeadStyle: FunctionComponent<HeadProps<"style">> = (props) => {
1517
+ useHead({ style: [{ ...(props as HeadProps<"style">) }] })
1518
+ return null
1519
+ }
1520
+
1521
+ export const HtmlAttrs: FunctionComponent<HeadAttrsProps> = (props) => {
1522
+ useHead({ htmlAttrs: { ...(props as HeadAttrsProps) } })
1523
+ return null
1524
+ }
1525
+
1526
+ export const BodyAttrs: FunctionComponent<HeadAttrsProps> = (props) => {
1527
+ useHead({ bodyAttrs: { ...(props as HeadAttrsProps) } })
1528
+ return null
1529
+ }
1530
+
1531
+ export function useServerHead(input: ServerHeadInput): void {
1532
+ if (!isServer) return
1533
+ const head = useContext(HeadContext)
1534
+ if (!head) throw new Error("useServerHead() must be called inside a Hamur app")
1535
+ useHeadOnServer(head, input, { server: true })
1536
+ }
1537
+
1538
+ export function useServerSeoMeta(input: ServerSeoMetaInput): void {
1539
+ if (isServer) useServerHead(seoMetaToHead(input))
1540
+ }
1541
+
1542
+ export function useState<T>(key: StateKey<T>): [T, (value: T | ((previous: T) => T)) => void]
1543
+ export function useState<T>(key: string, init?: T | (() => T)): [T, (value: T | ((previous: T) => T)) => void]
1544
+ export function useState<T>(...args: unknown[]): [T, (value: T | ((previous: T) => T)) => void] {
1545
+ const { key, init } = stateArguments(args) as { key: string; init: T | (() => T) | undefined }
1546
+ const state = useContext(StateContext)
1547
+ if (!state) throw new Error("useState() must be called inside a Hamur app")
1548
+ state.use(key, init)
1549
+ const [value, setValue] = useLocalState(() => state.get<T>(key) as T)
1550
+ useEffect(() => {
1551
+ setValue(state.get<T>(key) as T)
1552
+ return state.subscribe(key, () => setValue(state.get<T>(key) as T))
1553
+ }, [state, key])
1554
+ const set = useCallback(
1555
+ (next: T | ((previous: T) => T)) =>
1556
+ state.set(key, typeof next === "function" ? (next as (previous: T) => T)(state.get<T>(key) as T) : next),
1557
+ [state, key],
1558
+ )
1559
+ return [value, set]
1560
+ }
1561
+
1562
+ export function useCookie<T = string>(
1563
+ name: string,
1564
+ options: Omit<UseCookieOptions<T>, "app"> & { default: () => T },
1565
+ ): [T, (value: T | undefined) => void]
1566
+ export function useCookie<T = string>(
1567
+ name: string,
1568
+ options?: Omit<UseCookieOptions<T>, "app">,
1569
+ ): [T | undefined, (value: T | undefined) => void]
1570
+ export function useCookie<T = string>(
1571
+ name: string,
1572
+ options: Omit<UseCookieOptions<T>, "app"> = {},
1573
+ ): [T | undefined, (value: T | undefined) => void] {
1574
+ const app = useContext(AppContextContext)
1575
+ const live = useRef<UseCookieOptions<T>>({}).current
1576
+ for (const key of Object.keys(live)) delete live[key as keyof typeof live]
1577
+ Object.assign(live, options, app ? { app } : {})
1578
+ const cookie = useMemo(() => cookieOf<T>(name, live), [name, app])
1579
+ const [value, setValue] = useLocalState(() => cookie.get())
1580
+ useEffect(() => {
1581
+ setValue(() => cookie.get())
1582
+ return cookie.subscribe((next) => setValue(() => next))
1583
+ }, [cookie])
1584
+ const set = useCallback((next: T | undefined) => cookie.set(next), [cookie])
1585
+ return [value, set]
1586
+ }
1587
+
1588
+ export interface UseAsyncDataOptions<T = unknown, R = T, K extends keyof T & string = never, D = T> extends Omit<
1589
+ AsyncDataOptions<T, R, D>,
1590
+ "pick"
1591
+ > {
1592
+ /** Values that re-run the handler when they change. `false` is accepted and does nothing: nothing watches implicitly. */
1593
+ watch?: readonly unknown[] | false
1594
+ getCachedData?: GetCachedData<T>
1595
+ /** Top-level keys of an object result to keep. */
1596
+ pick?: readonly K[]
1597
+ }
1598
+
1599
+ export interface UseAsyncDataResult<T, D = undefined> {
1600
+ data: T | D
1601
+ error: HamurError | undefined
1602
+ status: AsyncDataStatus
1603
+ /** `status === "pending"`, or `idle` without data under `app.asyncData.pendingWhenIdle`. */
1604
+ pending: boolean
1605
+ refresh(): Promise<void>
1606
+ /** The same function as `refresh`. */
1607
+ execute(): Promise<void>
1608
+ /** Resets the entry of this key to `idle` (`clearAsyncData`). */
1609
+ clear(): void
1610
+ }
1611
+
1612
+ export interface UseFetchOptions<T = unknown, R = T, K extends keyof T & string = never, D = T>
1613
+ extends FetchRequest, UseAsyncDataOptions<T, R, K, D> {
1614
+ /** The store key, instead of the one derived from the url and the request. */
1615
+ key?: string
1616
+ }
1617
+
1618
+ export function useAsyncData<I, R, T = R, K extends keyof T & string = never, D = T>(
1619
+ fn: Handler<I, R>,
1620
+ input: NoInfer<I> | (() => NoInfer<I>) | undefined,
1621
+ options: UseAsyncDataOptions<T, R, K, D> & { default: () => D },
1622
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1623
+ export function useAsyncData<I, R, T = R, K extends keyof T & string = never>(
1624
+ fn: Handler<I, R>,
1625
+ input?: NoInfer<I> | (() => NoInfer<I>),
1626
+ options?: UseAsyncDataOptions<T, R, K, undefined>,
1627
+ ): UseAsyncDataResult<PickFrom<T, K>>
1628
+ export function useAsyncData<T = unknown, R = T, K extends keyof T & string = never, D = T>(
1629
+ keyOrGetter: string | (() => string),
1630
+ handler: AsyncDataHandler<R>,
1631
+ options: UseAsyncDataOptions<T, R, K, D> & { default: () => D },
1632
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1633
+ export function useAsyncData<T = unknown, R = T, K extends keyof T & string = never>(
1634
+ keyOrGetter: string | (() => string),
1635
+ handler: AsyncDataHandler<R>,
1636
+ options?: UseAsyncDataOptions<T, R, K, undefined>,
1637
+ ): UseAsyncDataResult<PickFrom<T, K>>
1638
+ export function useAsyncData(...args: unknown[]): UseAsyncDataResult<any, any> {
1639
+ const [first, second, given] = asyncDataArguments("useAsyncData", args) as [
1640
+ string | (() => string) | HandlerReference,
1641
+ unknown,
1642
+ UseAsyncDataOptions<any, any, any, any> | undefined,
1643
+ ]
1644
+ const options = given ?? {}
1645
+ const app = useApp()
1646
+ if (!isHandlerReference(first))
1647
+ return keyedAsyncData(first as string | (() => string), second as AsyncDataHandler<unknown>, options)
1648
+ const input = valueOf(second)
1649
+ return keyedAsyncData(
1650
+ asyncDataKey(first as HandlerReference, input),
1651
+ callHandler(app, first as HandlerReference, input),
1652
+ options,
1653
+ )
1654
+ }
1655
+
1656
+ function keyedAsyncData<T, R, K extends keyof T & string, D>(
1657
+ keyOrGetter: string | (() => string),
1658
+ handler: AsyncDataHandler<R>,
1659
+ options: UseAsyncDataOptions<T, R, K, D>,
1660
+ ): UseAsyncDataResult<PickFrom<T, K>, D> {
1661
+ const key = valueOf(keyOrGetter)
1662
+ const app = useApp()
1663
+ const store = app.asyncData
1664
+ store.neverHydrated(key, useContext(NeverHydratedContext))
1665
+ const {
1666
+ server,
1667
+ lazy,
1668
+ default: init,
1669
+ transform,
1670
+ immediate,
1671
+ dedupe,
1672
+ pick,
1673
+ watch,
1674
+ getCachedData = defaultGetCachedData,
1675
+ } = options
1676
+ const settings = {
1677
+ server,
1678
+ lazy,
1679
+ default: init as AsyncDataOptions<T, R>["default"],
1680
+ transform,
1681
+ immediate,
1682
+ dedupe,
1683
+ pick,
1684
+ }
1685
+ const read = (): AsyncDataEntry<T> =>
1686
+ store.get<T>(key) ?? { data: init?.() as T | undefined, error: undefined, status: "idle", promise: undefined }
1687
+ const created = useRef<string | undefined>(undefined)
1688
+ if (created.current !== key) {
1689
+ created.current = key
1690
+ keepCached(app, key, getCachedData)
1691
+ const started = store.fetch<T, R>(key, handler, {
1692
+ ...settings,
1693
+ cached: getCachedData(key, app, { cause: "initial" }),
1694
+ })
1695
+ if (isServer && started.status === "pending") markWaiting(store)
1696
+ }
1697
+ const [state, setState] = useLocalState(() => ({ key, entry: read() }))
1698
+ // A layout effect runs in the commit that unmounts the key's previous user, so the entry is never purged in between.
1699
+ useLayoutEffect(() => {
1700
+ const sync = () =>
1701
+ setState((previous) =>
1702
+ previous.key === key && previous.entry === store.get(key) ? previous : { key, entry: read() },
1703
+ )
1704
+ const unsubscribe = store.subscribe(key, sync)
1705
+ sync()
1706
+ return unsubscribe
1707
+ }, [store, key])
1708
+ const entry = state.key === key ? state.entry : read()
1709
+ const latest = useRef({ handler, settings, getCachedData })
1710
+ latest.current = { handler, settings, getCachedData }
1711
+ const again = (cause: GetCachedDataCause) =>
1712
+ refreshCached(app, key, latest.current.handler, latest.current.settings, latest.current.getCachedData, cause)
1713
+ const refresh = useCallback(() => again("refresh:manual"), [app, key])
1714
+ useEffect(() => store.onRefresh(key, () => again("refresh:hook")), [store, key])
1715
+ const first = useRef(true)
1716
+ useEffect(() => {
1717
+ if (first.current) first.current = false
1718
+ else void again("watch")
1719
+ }, watch || [])
1720
+ const clear = () => clearAsyncData(app, key)
1721
+ return {
1722
+ data: entry.data as PickFrom<T, K> | D,
1723
+ error: entry.error,
1724
+ status: entry.status,
1725
+ pending: isPending(app, entry),
1726
+ refresh,
1727
+ execute: refresh,
1728
+ clear,
1729
+ }
1730
+ }
1731
+
1732
+ /** What a literal `useFetch` call is checked against; any other call stays loose. */
1733
+ type FetchInput<X> = X extends { key: infer K extends string; input: infer I }
1734
+ ? FetchInputField<I, K, I | (() => I)>
1735
+ : unknown
1736
+ type Unkeyed<O, X> = X extends { key: infer K extends string } ? Omit<O, K> : O
1737
+ type FetchCall<U extends string, M extends string, B extends string | undefined> = {
1738
+ method?: M | string
1739
+ baseURL?: B | string
1740
+ } & FetchInput<FetchCheckedInput<U, M, B>>
1741
+
1742
+ export function useFetch<
1743
+ U extends string,
1744
+ M extends string = "GET",
1745
+ K extends keyof FetchData<U, M> & string = never,
1746
+ D = undefined,
1747
+ B extends string | undefined = undefined,
1748
+ >(
1749
+ url: U | (() => U),
1750
+ options?: Unkeyed<UseFetchOptions<FetchData<U, M>, FetchData<U, M>, K, D>, FetchCheckedInput<U, M, B>> &
1751
+ FetchCall<U, M, B>,
1752
+ ): UseAsyncDataResult<PickFrom<FetchData<U, M>, K>, D>
1753
+ export function useFetch<
1754
+ T = unknown,
1755
+ R = T,
1756
+ K extends keyof T & string = never,
1757
+ D = T,
1758
+ U extends string = string,
1759
+ M extends string = "GET",
1760
+ B extends string | undefined = undefined,
1761
+ >(
1762
+ urlOrGetter: U | (() => U),
1763
+ options: Unkeyed<UseFetchOptions<T, R, K, D>, FetchCheckedInput<U, M, B>> & { default: () => D } & FetchCall<U, M, B>,
1764
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1765
+ export function useFetch<
1766
+ T = unknown,
1767
+ R = T,
1768
+ K extends keyof T & string = never,
1769
+ U extends string = string,
1770
+ M extends string = "GET",
1771
+ B extends string | undefined = undefined,
1772
+ >(
1773
+ urlOrGetter: U | (() => U),
1774
+ options?: Unkeyed<UseFetchOptions<T, R, K, undefined>, FetchCheckedInput<U, M, B>> & FetchCall<U, M, B>,
1775
+ ): UseAsyncDataResult<PickFrom<T, K>>
1776
+ export function useFetch<T = unknown, R = T, K extends keyof T & string = never, D = T>(
1777
+ urlOrGetter: string | (() => string),
1778
+ options: UseFetchOptions<T, R, K, D> = {},
1779
+ ): UseAsyncDataResult<PickFrom<T, K>, D> {
1780
+ return fetchWith<T, R, K, D>(undefined, urlOrGetter, options)
1781
+ }
1782
+
1783
+ function fetchWith<T, R, K extends keyof T & string, D>(
1784
+ client: $Fetch | undefined,
1785
+ urlOrGetter: string | (() => string),
1786
+ options: UseFetchOptions<T, R, K, D>,
1787
+ ): UseAsyncDataResult<PickFrom<T, K>, D> {
1788
+ const {
1789
+ key,
1790
+ server,
1791
+ lazy,
1792
+ default: init,
1793
+ transform,
1794
+ immediate,
1795
+ dedupe,
1796
+ pick,
1797
+ watch,
1798
+ getCachedData,
1799
+ ...rest
1800
+ } = options
1801
+ const url = valueOf(urlOrGetter)
1802
+ const request = requestOf(rest)
1803
+ const app = useApp()
1804
+ const fetcher = client ?? app.fetch ?? $fetch
1805
+ return useAsyncData<T, R, K, D>(
1806
+ key ?? fetchKey(url, request),
1807
+ ({ signal }) => fetcher<R>(url, { ...request, signal: signalOf(request.signal, signal) }),
1808
+ { server, lazy, default: init as () => D, transform, immediate, dedupe, pick, watch, getCachedData },
1809
+ )
1810
+ }
1811
+
1812
+ /** `createUseFetch` defaults change what a call sends (method, body, query, baseURL), so its calls check nothing. */
1813
+ interface UseFetchLoose {
1814
+ <U extends string, M extends string = "GET", K extends keyof FetchData<U, M> & string = never, D = undefined>(
1815
+ url: U | (() => U),
1816
+ options?: UseFetchOptions<FetchData<U, M>, FetchData<U, M>, K, D> & { method?: M },
1817
+ ): UseAsyncDataResult<PickFrom<FetchData<U, M>, K>, D>
1818
+ <T = unknown, R = T, K extends keyof T & string = never, D = T>(
1819
+ url: string | (() => string),
1820
+ options: UseFetchOptions<T, R, K, D> & { default: () => D },
1821
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1822
+ <T = unknown, R = T, K extends keyof T & string = never>(
1823
+ url: string | (() => string),
1824
+ options?: UseFetchOptions<T, R, K, undefined>,
1825
+ ): UseAsyncDataResult<PickFrom<T, K>>
1826
+ }
1827
+
1828
+ type AnyFetchOptions = UseFetchOptions<any, any, any, any>
1829
+
1830
+ /** `useFetch` with `defaults` under every call's options; `$fetch` replaces the request-bound client, e.g. a `$fetch.create` one. */
1831
+ export function createUseFetch(
1832
+ defaults: AnyFetchOptions | ((options: AnyFetchOptions) => AnyFetchOptions),
1833
+ { $fetch: client }: { $fetch?: $Fetch } = {},
1834
+ ): UseFetchLoose {
1835
+ return ((url: string | (() => string), options?: AnyFetchOptions) =>
1836
+ fetchWith(client, url, resolveCallOptions(defaults, options))) as unknown as UseFetchLoose
1837
+ }
1838
+
1839
+ /** `useAsyncData` with `defaults` under every call's options. */
1840
+ export function createUseAsyncData(
1841
+ defaults:
1842
+ | UseAsyncDataOptions<any, any, any, any>
1843
+ | ((options: UseAsyncDataOptions<any, any, any, any>) => UseAsyncDataOptions<any, any, any, any>),
1844
+ ): typeof useAsyncData {
1845
+ return ((...args: unknown[]) => {
1846
+ const [first, second, options] = asyncDataArguments("useAsyncData", args)
1847
+ return useAsyncData(
1848
+ first as never,
1849
+ second as never,
1850
+ resolveCallOptions(defaults, options as UseAsyncDataOptions<any, any, any, any> | undefined),
1851
+ )
1852
+ }) as typeof useAsyncData
1853
+ }
1854
+
1855
+ export const useLazyFetch: typeof useFetch = ((url: string | (() => string), options?: AnyFetchOptions) =>
1856
+ useFetch(url, { ...options, lazy: true })) as typeof useFetch
1857
+
1858
+ export const useLazyAsyncData: typeof useAsyncData = ((...args: unknown[]) => {
1859
+ const [first, second, options] = asyncDataArguments("useLazyAsyncData", args)
1860
+ return useAsyncData(first as never, second as never, {
1861
+ ...(options as UseAsyncDataOptions<any, any, any, any>),
1862
+ lazy: true,
1863
+ })
1864
+ }) as typeof useAsyncData
1865
+
1866
+ export function transitionName(name: string): { style: { viewTransitionName: string } } {
1867
+ return { style: { viewTransitionName: checkTransitionName(name) } }
1868
+ }