@hamur/adapter-html 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 (54) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +31 -2
  3. package/dist/chunks/browser-index-2h1699xv.js +148 -0
  4. package/dist/chunks/browser-index-n6x04zrf.js +28 -0
  5. package/dist/chunks/browser-index-naq02zzj.js +4 -0
  6. package/dist/chunks/browser-index-qx74bd1y.js +302 -0
  7. package/dist/src/adapter.js +141 -0
  8. package/dist/src/error-page.js +335 -0
  9. package/dist/src/index.js +1241 -0
  10. package/dist/src/runtime/client.js +330 -0
  11. package/dist/src/runtime/island.js +40 -0
  12. package/dist/src/runtime/server.js +59 -0
  13. package/dist/types/src/adapter.d.ts +2 -0
  14. package/dist/types/src/async-data.d.ts +13 -0
  15. package/dist/types/src/context.d.ts +109 -0
  16. package/dist/types/src/error-page.d.ts +1 -0
  17. package/dist/types/src/index.d.ts +343 -0
  18. package/dist/types/src/island-html.d.ts +13 -0
  19. package/dist/types/src/island.d.ts +40 -0
  20. package/dist/types/src/lazy-hydration.d.ts +11 -0
  21. package/dist/types/src/markdown-page.d.ts +9 -0
  22. package/dist/types/src/markdown.d.ts +11 -0
  23. package/dist/types/src/plugin.d.ts +11 -0
  24. package/dist/types/src/runtime/client.d.ts +15 -0
  25. package/dist/types/src/runtime/hmr.d.ts +8 -0
  26. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  27. package/dist/types/src/runtime/hydration.d.ts +10 -0
  28. package/dist/types/src/runtime/island.d.ts +8 -0
  29. package/dist/types/src/runtime/server.d.ts +8 -0
  30. package/dist/types/src/runtime/svg-id.d.ts +2 -0
  31. package/dist/types/src/server-component.d.ts +4 -0
  32. package/dist/types/src/svg.d.ts +10 -0
  33. package/package.json +62 -4
  34. package/src/adapter.ts +25 -0
  35. package/src/async-data.ts +65 -0
  36. package/src/context.ts +445 -0
  37. package/src/env.d.ts +3 -0
  38. package/src/error-page.ts +1 -0
  39. package/src/index.ts +1620 -0
  40. package/src/island-html.ts +58 -0
  41. package/src/island.ts +126 -0
  42. package/src/lazy-hydration.ts +56 -0
  43. package/src/markdown-page.ts +17 -0
  44. package/src/markdown.ts +29 -0
  45. package/src/plugin.ts +70 -0
  46. package/src/runtime/client.ts +363 -0
  47. package/src/runtime/hmr.ts +38 -0
  48. package/src/runtime/hydration-dev.ts +12 -0
  49. package/src/runtime/hydration.ts +11 -0
  50. package/src/runtime/island.ts +52 -0
  51. package/src/runtime/server.ts +56 -0
  52. package/src/runtime/svg-id.ts +12 -0
  53. package/src/server-component.ts +30 -0
  54. package/src/svg.ts +54 -0
package/src/index.ts ADDED
@@ -0,0 +1,1620 @@
1
+ import {
2
+ addRouteMiddleware,
3
+ clearAsyncData,
4
+ $fetch,
5
+ clearError,
6
+ createForm,
7
+ disableScrollHandling,
8
+ forbidden,
9
+ navigateTo,
10
+ notFound,
11
+ permanentRedirect,
12
+ redirect,
13
+ refreshCookie,
14
+ setPageLayout,
15
+ showError,
16
+ unauthorized,
17
+ useCookie as useCookieRef,
18
+ withoutBase,
19
+ } from "hamur/app"
20
+ import { reportWebVitals, syncedState } from "hamur/app"
21
+ import type { AppHooks, WebVitalMetric } from "hamur/app"
22
+ import { deferPartId, whenAppReady } from "hamur/adapter"
23
+ import type { SyncedStateOptions } from "hamur/app"
24
+ import {
25
+ asyncDataArguments,
26
+ asyncDataKey,
27
+ stateArguments,
28
+ fetchKey,
29
+ timeAttributes,
30
+ timeView,
31
+ createLoadingIndicator,
32
+ createRouteAnnouncer,
33
+ createAnnouncer,
34
+ announcerActions,
35
+ announcerRole,
36
+ ROUTE_ANNOUNCER_ID,
37
+ ANNOUNCER_POLITE_ID,
38
+ ANNOUNCER_ASSERTIVE_ID,
39
+ isHandlerReference,
40
+ isPending,
41
+ resolveCallOptions,
42
+ settledOf,
43
+ } from "hamur/adapter"
44
+ import {
45
+ callOnce as callOnceOf,
46
+ clearState as clearStateOf,
47
+ setResponseStatus as setResponseStatusOf,
48
+ useResponseHeader as responseHeaderOf,
49
+ useRequestEvent as requestEventOf,
50
+ useRequestFetch as requestFetchOf,
51
+ useRequestHeader as requestHeaderOf,
52
+ useRequestHeaders as requestHeadersOf,
53
+ useRequestURL as requestURLOf,
54
+ usePreviewMode as previewModeOf,
55
+ } from "hamur/app"
56
+ import type { PreviewMode } from "hamur/app"
57
+ import type { $Fetch, FetchCheckedInput, FetchInputField } from "hamur/app"
58
+ import type { StateKey } from "hamur/app"
59
+ import type { HamurEvent } from "hamur/server"
60
+ import {
61
+ assertFormMethod,
62
+ createActionRunner,
63
+ functionFormAction,
64
+ publicError,
65
+ restoredResult,
66
+ runtimeConfigOf,
67
+ siteConfigOf,
68
+ sanitizeHead,
69
+ seoMetaToHead,
70
+ LINK_DEFAULTS,
71
+ createLinkSlot,
72
+ linkAttributes,
73
+ linkDefaultsOf,
74
+ linkExtraAttributes,
75
+ linkPending,
76
+ linkPrefetchProps,
77
+ linkState,
78
+ warnRemovedLinkProps,
79
+ relativeTarget,
80
+ resolveLinkTarget,
81
+ resolveRelative,
82
+ prefetchAttribute,
83
+ viewTransitionAttribute,
84
+ checkTransitionName,
85
+ navigationHook,
86
+ navigationBlocker,
87
+ routeGuard,
88
+ createBlocker,
89
+ registerSnapshot,
90
+ } from "hamur/adapter"
91
+ import type { LinkDefaults, LinkSlot, Navigation, ResolvedLinkDefaults, UseLinkOptions } from "hamur/adapter"
92
+ import { diagnosticURL, noteOutlet, prehydrate } from "hamur/adapter"
93
+ import type { DiagnosticCode } from "hamur/adapter"
94
+ import type {
95
+ Settled,
96
+ AnnouncerActions,
97
+ AnnouncerPoliteness,
98
+ AnnouncerState,
99
+ RouteAnnouncerActions,
100
+ RouteAnnouncerProps,
101
+ RouteAnnouncerState,
102
+ LoadingIndicatorActions,
103
+ LoadingIndicatorProps as LoadingIndicatorCoreProps,
104
+ LoadingIndicatorOptions,
105
+ LoadingIndicatorState,
106
+ TimeInput,
107
+ } from "hamur/adapter"
108
+ import type {
109
+ ActionOptions,
110
+ ActionRunner,
111
+ PrefetchOn,
112
+ Handler,
113
+ AfterNavigateHook,
114
+ BeforeNavigateHook,
115
+ NavigateHook,
116
+ NavigationBlocker,
117
+ NavigationGuard,
118
+ Blocker,
119
+ ShouldBlock,
120
+ UseBlockerOptions,
121
+ SnapshotOptions,
122
+ } from "hamur/adapter"
123
+ import type { HandlerForm, HamurLinkProps } from "hamur/app"
124
+ import type {
125
+ ActionFailure,
126
+ AppContext,
127
+ PickFrom,
128
+ RouteLocation,
129
+ AsyncData,
130
+ ClientRuntimeConfig,
131
+ SiteConfig,
132
+ ErrorPageProps,
133
+ FetchData,
134
+ AsyncDataEntry,
135
+ AsyncDataOptions,
136
+ AsyncDataStatus,
137
+ HeadInput,
138
+ HeadSafeInput,
139
+ SeoMetaInput,
140
+ UseCookieOptions,
141
+ HamurError,
142
+ } from "hamur/app"
143
+ import { markWaiting } from "hamur/adapter"
144
+ import type {
145
+ RouteLoaderData,
146
+ UseDataArgs,
147
+ AsyncDataHandler,
148
+ ErrorBoundaryFallbackProps,
149
+ FetchRequest,
150
+ GetCachedData,
151
+ CheckedTarget,
152
+ HandlerReference,
153
+ NavigationState,
154
+ RouteValue,
155
+ RouterApi,
156
+ } from "hamur/adapter"
157
+ import { devHydration } from "./runtime/hydration.ts"
158
+ import {
159
+ callHandler,
160
+ defaultGetCachedData,
161
+ keepCached,
162
+ refreshCached,
163
+ requestOf,
164
+ signalOf,
165
+ valueOf,
166
+ } from "./async-data.ts"
167
+ import {
168
+ RERUN_STATE_KEY,
169
+ CLIENT_MARKERS,
170
+ LINK_STATE_ATTRIBUTE,
171
+ currentRoute,
172
+ currentState,
173
+ followNavigation,
174
+ keepAnnouncerClaim,
175
+ markAnnouncerRendered,
176
+ markIndicatorRendered,
177
+ linkStateKey,
178
+ detachedHref,
179
+ isRepaintingWithData,
180
+ paintCount,
181
+ renderIn,
182
+ repaintPage,
183
+ repaintWithData,
184
+ routerOf,
185
+ settle,
186
+ } from "./context.ts"
187
+ import type { HeadPending, HtmlChildren, HtmlProps, LinkEntry } from "./context.ts"
188
+
189
+ export {
190
+ addRouteMiddleware,
191
+ clearError,
192
+ disableScrollHandling,
193
+ forbidden,
194
+ navigateTo,
195
+ notFound,
196
+ permanentRedirect,
197
+ refreshCookie,
198
+ setPageLayout,
199
+ showError,
200
+ unauthorized,
201
+ }
202
+ export { defineLazyHydrationComponent } from "./lazy-hydration.ts"
203
+ export { defineIsland, island, serverIsland } from "./island.ts"
204
+ export type { HtmlIsland, IslandOptions, ServerIslandOptions } from "./island.ts"
205
+ export { MarkdownRenderer } from "./markdown.ts"
206
+ export type { MarkdownRendererProps } from "./markdown.ts"
207
+ import { layoutOf, layoutSegments, matchesOf, routeDataOf } from "hamur/adapter"
208
+ import { isOnline, pollInterval, searchTarget, startPoll } from "hamur/adapter"
209
+ import type { SetSearch } from "hamur/adapter"
210
+ import { createAppUpdate } from "hamur/adapter"
211
+ import type { AppUpdateActions, AppUpdateState } from "hamur/adapter"
212
+ import type { MatchedRoute, RouteDataName, RouteDataOf, RouteError, RouteFor, RouteName } from "hamur/adapter"
213
+ export type { MatchedRoute, RouteDataName, RouteDataOf } from "hamur/adapter"
214
+ export type { NavigateToOptions, PickFrom } from "hamur/app"
215
+ export type { HtmlChildren, HtmlProps }
216
+ export type { Blocker, BlockerArgs, SnapshotOptions, UseBlockerOptions } from "hamur/adapter"
217
+ export type {
218
+ AfterNavigateHook,
219
+ AsyncDataHandler,
220
+ BeforeNavigateHook,
221
+ ErrorBoundaryFallbackProps,
222
+ FetchRequest,
223
+ GetCachedData,
224
+ GetCachedDataCause,
225
+ NavigateHook,
226
+ NavigateOptions,
227
+ Navigation,
228
+ NavigationState,
229
+ NavigationType,
230
+ RouteValue,
231
+ RouterApi,
232
+ } from "hamur/adapter"
233
+
234
+ export type { LinkDefaults, LinkSlot, UseLinkOptions } from "hamur/adapter"
235
+
236
+ interface LinkBaseProps extends Record<string, unknown>, HamurLinkProps {
237
+ replace?: boolean
238
+ prefetch?: boolean
239
+ prefetchOn?: PrefetchOn
240
+ /** Removed: write `to`. */
241
+ href?: never
242
+ /** Removed: write `prefetch={false}`. */
243
+ noPrefetch?: never
244
+ /** The query as a function of the validated search of the page on screen. */
245
+ query?: (prev: RouteValue["search"]) => RouteValue["search"]
246
+ /** A serializable object kept in the history entry the click pushes, read as `useRoute().state`. */
247
+ state?: Record<string, unknown>
248
+ /** `"route"` resolves a relative `to` against the path of the route, its pattern filled with its params, not the URL. */
249
+ relative?: "route"
250
+ /** The app path the address bar shows while `to` renders. */
251
+ mask?: string
252
+ /** `false` renders `to` again after a reload of the masked entry. */
253
+ unmaskOnReload?: boolean
254
+ /** `true` or `{ types }` runs this navigation in a view transition, `false` turns it off. */
255
+ viewTransition?: boolean | { types: readonly string[] }
256
+ activeClass?: string
257
+ exactActiveClass?: string
258
+ /** The class the navigator adds to this anchor while a navigation to it is in flight; `""` adds none. */
259
+ pendingClass?: string
260
+ ariaCurrentValue?: "page" | "step" | "location" | "date" | "time" | "true"
261
+ /** A plain link the navigator never intercepts, with no prefetch and `rel="external"`. */
262
+ external?: boolean
263
+ /** No `rel` is added for a `target="_blank"` or an other-origin `to`. */
264
+ noRel?: boolean
265
+ /** The class the navigator adds to this anchor once its prefetch finished. */
266
+ prefetchedClass?: string
267
+ /** `false` keeps the scroll position for the navigation the click starts. */
268
+ scroll?: boolean
269
+ /** ms a hover or focus waits before it prefetches; one that ends sooner prefetches nothing. */
270
+ prefetchDelay?: number
271
+ /** Runs for a navigation this anchor started, after the `onBeforeNavigate` hooks; `nav.cancel()` stops it. Kept like `state`, through `data-hamur-link`. */
272
+ onBeforeNavigate?: (nav: Navigation) => void
273
+ /** A function renders the link itself: it is given the `LinkSlot` and `Link` returns what it returns. */
274
+ children?: string | ((link: LinkSlot) => string)
275
+ }
276
+
277
+ /** `T` is the string `to`, which is checked against the route table. */
278
+ export type LinkProps<T extends string = string> = LinkBaseProps & { to: CheckedTarget<T> | RouteLocation }
279
+
280
+ const ESCAPES: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }
281
+
282
+ function escapeAttribute(value: unknown): string {
283
+ return String(value).replace(/[&<>"]/g, (char) => ESCAPES[char]!)
284
+ }
285
+
286
+ function attributeString(attributes: Array<[string, unknown]>): string {
287
+ let out = ""
288
+ for (const [name, value] of attributes) {
289
+ if (value === undefined || value === null || value === false) continue
290
+ out += value === true ? ` ${name}` : ` ${name}="${escapeAttribute(value)}"`
291
+ }
292
+ return out
293
+ }
294
+
295
+ function keepLinkState(states: Map<string, LinkEntry>, href: string, entry: LinkEntry): number {
296
+ let occurrence = 0
297
+ while (states.has(linkStateKey(href, occurrence))) occurrence++
298
+ states.set(linkStateKey(href, occurrence), entry)
299
+ return occurrence
300
+ }
301
+
302
+ function resolveLink<A extends object>(props: LinkProps, attrs: A) {
303
+ warnRemovedLinkProps(props)
304
+ const { to: target, query, relative, mask, external } = props
305
+ const current = currentState()
306
+ const searched = current
307
+ ? searchTarget(relativeTarget(target, current.route, relative), current.route, query)
308
+ : target
309
+ const { to, props: rest } = resolveLinkTarget(current?.app, searched, attrs, current?.href, external)
310
+ const href = current ? current.href(to) : detachedHref(to)
311
+ const state = current
312
+ ? linkState(typeof to === "string" ? to : withoutBase(href, current.baseURL), current.route)
313
+ : undefined
314
+ return {
315
+ current,
316
+ to,
317
+ href,
318
+ state,
319
+ rest,
320
+ maskHref: mask === undefined ? undefined : current ? current.href(mask) : detachedHref(mask),
321
+ }
322
+ }
323
+
324
+ function slotOf(
325
+ props: LinkProps,
326
+ d: ResolvedLinkDefaults,
327
+ { current, to, href, state, maskHref }: ReturnType<typeof resolveLink>,
328
+ ): LinkSlot {
329
+ const {
330
+ state: entryState,
331
+ query,
332
+ mask,
333
+ unmaskOnReload,
334
+ viewTransition,
335
+ replace,
336
+ prefetch,
337
+ prefetchOn,
338
+ pendingClass = d.pendingClass,
339
+ ariaCurrentValue = "page",
340
+ external,
341
+ noRel,
342
+ prefetchedClass = d.prefetchedClass,
343
+ scroll,
344
+ prefetchDelay = d.prefetchDelay,
345
+ rel,
346
+ target,
347
+ } = props
348
+ return createLinkSlot({
349
+ href,
350
+ to,
351
+ attrs: linkAttributes({
352
+ href,
353
+ external,
354
+ ...linkPrefetchProps({ prefetch, prefetchOn }, d),
355
+ replace,
356
+ viewTransition,
357
+ pendingClass,
358
+ trim: !!query,
359
+ mask: maskHref,
360
+ unmaskOnReload,
361
+ ariaCurrent: state?.exact ? ariaCurrentValue : undefined,
362
+ rel,
363
+ target,
364
+ noRel,
365
+ prefetchedClass,
366
+ scroll,
367
+ prefetchDelay,
368
+ externalRelAttribute: d.externalRelAttribute,
369
+ }),
370
+ active: !!state?.active,
371
+ exact: !!state?.exact,
372
+ pending: !!current?.navigator?.get && linkPending(href, current.navigator.get(), current.baseURL),
373
+ external,
374
+ options: {
375
+ replace,
376
+ state: entryState,
377
+ mask,
378
+ unmaskOnReload,
379
+ viewTransition,
380
+ scroll: scroll === false ? false : undefined,
381
+ },
382
+ router: current ? routerOf(current.navigator, current.baseURL, current) : null,
383
+ })
384
+ }
385
+
386
+ const NO_DEFAULTS: LinkDefaults = {}
387
+
388
+ function linkOf(
389
+ props: LinkProps & { children?: string | ((link: LinkSlot) => string) },
390
+ defaults: LinkDefaults,
391
+ ): string {
392
+ const {
393
+ to: _to,
394
+ href: _href,
395
+ noPrefetch: _noPrefetch,
396
+ query,
397
+ state: entryState,
398
+ relative: _relative,
399
+ mask,
400
+ unmaskOnReload,
401
+ viewTransition,
402
+ replace,
403
+ prefetch,
404
+ prefetchOn,
405
+ activeClass,
406
+ exactActiveClass,
407
+ pendingClass,
408
+ ariaCurrentValue = "page",
409
+ external,
410
+ noRel,
411
+ prefetchedClass,
412
+ scroll,
413
+ prefetchDelay,
414
+ onBeforeNavigate,
415
+ children,
416
+ ...attrs
417
+ } = props
418
+ const resolved = resolveLink(props, attrs)
419
+ const { current, href, state, maskHref, rest } = resolved
420
+ const d = linkDefaultsOf(current?.app, defaults)
421
+ if (typeof children === "function") return children(slotOf(props, d, resolved))
422
+ const mode = external ? "false" : prefetchAttribute(linkPrefetchProps({ prefetch, prefetchOn }, d))
423
+ const pending = pendingClass ?? d.pendingClass
424
+ const { class: own, ...others } = rest
425
+ const classes = [
426
+ own,
427
+ state?.active && (activeClass ?? d.activeClass),
428
+ state?.exact && (exactActiveClass ?? d.exactActiveClass),
429
+ ]
430
+ .filter(Boolean)
431
+ .join(" ")
432
+ const entry: LinkEntry = { state: entryState, onBeforeNavigate }
433
+ const extras = linkExtraAttributes({
434
+ href,
435
+ external,
436
+ noRel,
437
+ rel: rest.rel,
438
+ target: rest.target,
439
+ prefetchedClass: prefetchedClass ?? d.prefetchedClass,
440
+ scroll,
441
+ prefetchDelay: prefetchDelay ?? d.prefetchDelay,
442
+ externalRelAttribute: d.externalRelAttribute,
443
+ })
444
+ const attributes: Array<[string, unknown]> = [
445
+ ["class", classes || undefined],
446
+ ...Object.entries(others).filter(([name]) => !(name === "rel" && extras.rel !== undefined)),
447
+ ...(state?.exact && others["aria-current"] === undefined
448
+ ? [["aria-current", ariaCurrentValue] as [string, unknown]]
449
+ : []),
450
+ ["href", href],
451
+ ["data-hamur-prefetch", mode],
452
+ ["data-hamur-view-transition", viewTransitionAttribute(viewTransition)],
453
+ ["data-hamur-mask", maskHref],
454
+ ["data-hamur-unmask", mask !== undefined && unmaskOnReload === false ? "false" : undefined],
455
+ [
456
+ LINK_STATE_ATTRIBUTE,
457
+ (entryState !== undefined || onBeforeNavigate !== undefined) && current
458
+ ? keepLinkState((current.linkStates ??= new Map()), href, entry)
459
+ : undefined,
460
+ ],
461
+ ["data-hamur-pending-class", pending === LINK_DEFAULTS.pendingClass ? undefined : pending],
462
+ ...Object.entries(extras),
463
+ ]
464
+ return `<a${attributeString(attributes)}${replace ? " data-hamur-replace" : ""}${query ? " data-hamur-trim" : ""}>${children ?? ""}</a>`
465
+ }
466
+
467
+ export function Link<T extends string = string>(props: LinkProps<T>): string {
468
+ return linkOf(props as LinkProps, NO_DEFAULTS)
469
+ }
470
+
471
+ /** A `Link` with `defaults` over `app.link`; a prop of the element wins. */
472
+ export function defineLink(defaults: LinkDefaults): typeof Link {
473
+ return ((props: LinkProps) => linkOf(props, defaults)) as typeof Link
474
+ }
475
+
476
+ /** The `LinkSlot` of a link to `to`, a plain object read while the page is painted; `app.link` sets its defaults. */
477
+ export function useLink<T extends string = string>(
478
+ to: CheckedTarget<T> | RouteLocation,
479
+ options?: UseLinkOptions,
480
+ ): LinkSlot {
481
+ const props = { to, ...options } as LinkProps
482
+ return slotOf(props, linkDefaultsOf(currentState()?.app), resolveLink(props, props))
483
+ }
484
+
485
+ export interface NavigateProps<T extends string = string> {
486
+ to: CheckedTarget<T, false> | RouteLocation
487
+ replace?: boolean
488
+ }
489
+
490
+ const navigatedTrees = new WeakSet<object>()
491
+
492
+ /** Navigates to `to` once after the page is painted; during SSR it throws the redirect `navigateTo` throws there. */
493
+ export function Navigate<T extends string = string>({ to, replace }: NavigateProps<T>): string {
494
+ const target = to as string | RouteLocation
495
+ if (isServer) throw redirect<string>(target)
496
+ const tree = currentState()?.tree
497
+ if (tree && navigatedTrees.has(tree)) return ""
498
+ if (tree) navigatedTrees.add(tree)
499
+ queueMicrotask(() => void navigateTo<string>(target, { replace }))
500
+ return ""
501
+ }
502
+
503
+ interface FormBaseProps extends Record<string, unknown> {
504
+ encType?: "application/x-www-form-urlencoded" | "multipart/form-data"
505
+ replace?: boolean
506
+ reset?: boolean
507
+ reloadDocument?: boolean
508
+ refresh?: boolean
509
+ /** With a server function: the store of `useAction(fn, { instance })` this form belongs to. */
510
+ instance?: string | number
511
+ restore?: boolean
512
+ }
513
+
514
+ export type FormProps<N extends string = string> = FormBaseProps &
515
+ /** A server function posts to this page with `?_fn=<id>`; the post is a document post, as a hydrated html page runs no component code. */
516
+ (
517
+ | { action: ((...args: never[]) => unknown) & { readonly url: string }; method?: "post" }
518
+ | { action?: string | (RouteLocation & { name: N }); method?: "get" }
519
+ )
520
+
521
+ export function Form<N extends string = string>(
522
+ { action, method, encType, replace, reset, reloadDocument, refresh, instance, restore, ...rest }: FormProps<N>,
523
+ body = "",
524
+ ): string {
525
+ assertFormMethod(action, method)
526
+ const current = currentState()
527
+ const page = current ? current.route.fullPath.replace(/#.*$/, "") : undefined
528
+ const target =
529
+ typeof action === "function"
530
+ ? functionFormAction(action as never, current ? current.href(page!) : "/", instance)
531
+ : action !== undefined
532
+ ? current
533
+ ? current.href(action as string | RouteLocation)
534
+ : detachedHref(action as string | RouteLocation)
535
+ : current
536
+ ? current.href(page!)
537
+ : undefined
538
+ const attributes: Array<[string, unknown]> = [
539
+ ...Object.entries(rest),
540
+ ["method", typeof action === "function" ? "post" : "get"],
541
+ ["action", target],
542
+ ["enctype", encType],
543
+ ["data-hamur-form", ""],
544
+ ["data-hamur-replace", replace ? "" : undefined],
545
+ ["data-hamur-reset", reset ? "" : undefined],
546
+ ["data-hamur-reload", reloadDocument || typeof action === "function" ? "" : undefined],
547
+ ["data-hamur-refresh", refresh === false ? "false" : undefined],
548
+ ["data-hamur-restore", restore === false ? "false" : undefined],
549
+ ]
550
+ return `<form${attributeString(attributes)}>${body}</form>`
551
+ }
552
+
553
+ export type TimeProps = TimeInput & Record<string, unknown>
554
+
555
+ export function Time(props: TimeProps): string {
556
+ const current = currentState()
557
+ if (!current) throw new Error("Time() must be called inside a Hamur app")
558
+ const view = timeView(current.app, current.route.path, props)
559
+ const attributes: Array<[string, unknown]> = [
560
+ ...Object.entries(timeAttributes(props)),
561
+ ["datetime", view.iso],
562
+ ["data-locale", view.locale],
563
+ ["data-time-zone", view.timeZone],
564
+ ]
565
+ return `<time${attributeString(attributes)}>${escapeAttribute(view.text)}</time>`
566
+ }
567
+
568
+ /** `estimatedProgress` is a function and cannot cross the server's string; pass it to `useLoadingIndicator(options)`. */
569
+ export type LoadingIndicatorProps = Omit<LoadingIndicatorCoreProps, "estimatedProgress">
570
+
571
+ export function LoadingIndicator(props: LoadingIndicatorProps = {}): string {
572
+ markIndicatorRendered()
573
+ const attributes: Array<[string, unknown]> = [
574
+ ["data-hamur-loading-indicator", true],
575
+ ["aria-hidden", "true"],
576
+ ["data-hamur-color", props.color],
577
+ ["data-hamur-error-color", props.errorColor],
578
+ ["data-hamur-height", props.height],
579
+ ["data-hamur-duration", props.duration],
580
+ ["data-hamur-throttle", props.throttle],
581
+ ]
582
+ return `<div${attributeString(attributes)}></div>`
583
+ }
584
+
585
+ export function useLoadingIndicator(
586
+ options?: LoadingIndicatorOptions,
587
+ ): LoadingIndicatorState & LoadingIndicatorActions {
588
+ const current = currentState()
589
+ if (!current) throw new Error("useLoadingIndicator() must be called inside a Hamur app")
590
+ const store = createLoadingIndicator(current.app, options)
591
+ followNavigation(current.app, current.navigator)
592
+ return {
593
+ get progress() {
594
+ return store.get().progress
595
+ },
596
+ get isLoading() {
597
+ return store.get().isLoading
598
+ },
599
+ get error() {
600
+ return store.get().error
601
+ },
602
+ start: store.start,
603
+ finish: store.finish,
604
+ set: store.set,
605
+ clear: store.clear,
606
+ }
607
+ }
608
+
609
+ export function useAppUpdate(): AppUpdateState & AppUpdateActions & { subscribe(listener: () => void): () => void } {
610
+ rerunOnHydrate()
611
+ const store = createAppUpdate(useApp())
612
+ return {
613
+ get available() {
614
+ return store.get().available
615
+ },
616
+ get buildId() {
617
+ return store.get().buildId
618
+ },
619
+ get time() {
620
+ return store.get().time
621
+ },
622
+ subscribe: store.subscribe,
623
+ check: store.check,
624
+ }
625
+ }
626
+
627
+ export type { RouteAnnouncerProps }
628
+
629
+ export function RouteAnnouncer(props: RouteAnnouncerProps = {}): string {
630
+ const current = currentState()
631
+ if (!current) throw new Error("RouteAnnouncer() must be called inside a Hamur app")
632
+ markAnnouncerRendered()
633
+ const store = createRouteAnnouncer(current.app)
634
+ const key = {}
635
+ const claimed = store.claim(key)
636
+ keepAnnouncerClaim(() => store.release(key))
637
+ if (!claimed)
638
+ return `<div${attributeString([
639
+ ["aria-live", "off"],
640
+ ["aria-atomic", "true"],
641
+ ])}></div>`
642
+ const live = props.politeness ?? store.get().politeness
643
+ const attributes: Array<[string, unknown]> = [
644
+ ["id", ROUTE_ANNOUNCER_ID],
645
+ ["data-hamur-announcer", "route"],
646
+ ["aria-live", live],
647
+ ["aria-atomic", "true"],
648
+ ["role", announcerRole(live)],
649
+ ["data-hamur-politeness", props.politeness],
650
+ ["class", props.class],
651
+ ["style", props.style],
652
+ ]
653
+ return `<div${attributeString(attributes)}></div>`
654
+ }
655
+
656
+ export function useRouteAnnouncer(): RouteAnnouncerState & RouteAnnouncerActions {
657
+ const current = currentState()
658
+ if (!current) throw new Error("useRouteAnnouncer() must be called inside a Hamur app")
659
+ const store = createRouteAnnouncer(current.app)
660
+ return {
661
+ get message() {
662
+ return store.get().message
663
+ },
664
+ get politeness() {
665
+ return store.get().politeness
666
+ },
667
+ set: store.set,
668
+ polite: store.polite,
669
+ assertive: store.assertive,
670
+ }
671
+ }
672
+
673
+ export function Announcer(): string {
674
+ if (!currentState()) throw new Error("Announcer() must be called inside a Hamur app")
675
+ markAnnouncerRendered()
676
+ return [
677
+ `<div${attributeString([
678
+ ["id", ANNOUNCER_POLITE_ID],
679
+ ["data-hamur-announcer", "polite"],
680
+ ["aria-live", "polite"],
681
+ ["aria-atomic", "true"],
682
+ ["role", "status"],
683
+ ])}></div>`,
684
+ `<div${attributeString([
685
+ ["id", ANNOUNCER_ASSERTIVE_ID],
686
+ ["data-hamur-announcer", "assertive"],
687
+ ["aria-live", "assertive"],
688
+ ["aria-atomic", "true"],
689
+ ["role", "alert"],
690
+ ])}></div>`,
691
+ ].join("")
692
+ }
693
+
694
+ export function useAnnouncer({ politeness = "polite" }: { politeness?: AnnouncerPoliteness } = {}): Pick<
695
+ AnnouncerState,
696
+ "message" | "politeness"
697
+ > &
698
+ AnnouncerActions {
699
+ const current = currentState()
700
+ if (!current) throw new Error("useAnnouncer() must be called inside a Hamur app")
701
+ const store = createAnnouncer(current.app)
702
+ return {
703
+ get message() {
704
+ return store.get().message
705
+ },
706
+ get politeness() {
707
+ return store.get().politeness
708
+ },
709
+ ...announcerActions(store, politeness),
710
+ }
711
+ }
712
+
713
+ export function useRoute<N extends RouteName>(name: N): RouteFor<N>
714
+ export function useRoute<N extends RouteName = never>(): RouteFor<N>
715
+ export function useRoute(): RouteValue
716
+ export function useRoute(name?: string): RouteValue {
717
+ const route = currentRoute()
718
+ if (!route) throw new Error("useRoute() must be called inside a Hamur app")
719
+ return route
720
+ }
721
+
722
+ export function useResolvedPath(to: string, { relative }: { relative?: "route" } = {}): string {
723
+ return resolveRelative(to, useRoute(), relative)
724
+ }
725
+
726
+ export function useRouter(): RouterApi {
727
+ const state = currentState()
728
+ if (!state) throw new Error("useRouter() must be called inside a Hamur app")
729
+ return routerOf(state.navigator, state.baseURL, state)
730
+ }
731
+
732
+ export function useData<T = unknown>(...unknownRoute: UseDataArgs<T>): RouteLoaderData<T> {
733
+ const state = currentState()
734
+ if (!state) throw new Error("useData() must be called inside a Hamur app")
735
+ const id = state.id
736
+ return (id === undefined ? null : (state.data[id] ?? null)) as RouteLoaderData<T>
737
+ }
738
+
739
+ export function useError(): RouteError | undefined
740
+ export function useError(): ErrorPageProps | undefined {
741
+ const state = currentState()
742
+ if (!state) throw new Error("useError() must be called inside a Hamur app")
743
+ if (state.boundaryError) return state.boundaryError
744
+ const stored = state.app.error?.get()
745
+ if (stored) return stored
746
+ return state.tree.error ? state.route.error : undefined
747
+ }
748
+
749
+ export function useRouteData<N extends RouteDataName>(name: N): RouteDataOf<N> {
750
+ const state = currentState()
751
+ if (!state) throw new Error("useRouteData() must be called inside a Hamur app")
752
+ return routeDataOf(state.route, state.data, name) as RouteDataOf<N>
753
+ }
754
+
755
+ export function useMatches(): MatchedRoute[] {
756
+ const state = currentState()
757
+ if (!state) throw new Error("useMatches() must be called inside a Hamur app")
758
+ return matchesOf(state.route, state.data)
759
+ }
760
+
761
+ const isDev = (import.meta as { dev?: boolean }).dev === true
762
+ const warnedSlots = new Set<string>()
763
+
764
+ export function Outlet({ context, name }: { context?: unknown; name?: string } = {}): string {
765
+ const state = currentState()
766
+ if (!state) throw new Error("Outlet() must be called inside a Hamur app")
767
+ const render = (): string => {
768
+ if (name === undefined) {
769
+ if (isDev) noteOutlet(state.id)
770
+ return state.outlet?.() ?? ""
771
+ }
772
+ const slot = state.slots?.[name]
773
+ if (!slot && isDev && !warnedSlots.has(`${state.id}:${name}`)) {
774
+ warnedSlots.add(`${state.id}:${name}`)
775
+ console.warn(`Outlet name "${name}" has no slot in ${state.id}`)
776
+ }
777
+ return slot?.() ?? ""
778
+ }
779
+ if (context === undefined) return render()
780
+ const above = state.outletValue
781
+ state.outletValue = context
782
+ try {
783
+ return render()
784
+ } finally {
785
+ state.outletValue = above
786
+ }
787
+ }
788
+
789
+ export function useOutletContext<T = unknown>(): T {
790
+ const state = currentState()
791
+ if (!state) throw new Error("useOutletContext() must be called inside a Hamur app")
792
+ return state.outletValue as T
793
+ }
794
+
795
+ export function useLayoutSegments(): string[] {
796
+ const state = currentState()
797
+ if (!state) throw new Error("useLayoutSegments() must be called inside a Hamur app")
798
+ return layoutSegments(state.route, state.id)
799
+ }
800
+
801
+ export function useLayoutSegment(): string | null {
802
+ return useLayoutSegments()[0] ?? null
803
+ }
804
+
805
+ export function useLayout(): { name: string | false; props: Record<string, unknown> } {
806
+ const state = currentState()
807
+ if (!state) throw new Error("useLayout() must be called inside a Hamur app")
808
+ return layoutOf(state.tree)
809
+ }
810
+
811
+ export interface ErrorBoundaryProps {
812
+ children: () => string | HtmlChildren
813
+ fallback: (props: ErrorBoundaryFallbackProps) => string
814
+ }
815
+
816
+ export function ErrorBoundary({ children, fallback }: ErrorBoundaryProps): string {
817
+ const parts = currentState()?.deferred
818
+ const kept = parts?.length ?? 0
819
+ try {
820
+ return settle(children())
821
+ } catch (error) {
822
+ if (parts) parts.length = kept
823
+ const app = currentState()?.app
824
+ return fallback({ error: app ? publicError(app, error) : error, reset: repaintPage })
825
+ }
826
+ }
827
+
828
+ export interface AwaitOptions<T> {
829
+ fallback?: string
830
+ then: (value: Awaited<T>) => string
831
+ error?: (error: Error) => string
832
+ }
833
+
834
+ const learned = new WeakMap<object, Settled>()
835
+ const watching = new WeakSet<object>()
836
+
837
+ /** The browser's own promise carries no status: the outcome is kept on the side and the page paints again once it is known. */
838
+ function learnOutcome(promise: PromiseLike<unknown>): void {
839
+ if (watching.has(promise)) return
840
+ watching.add(promise)
841
+ const settle = (outcome: Settled) => {
842
+ learned.set(promise, outcome)
843
+ queueMicrotask(() => repaintWithData(paintCount()))
844
+ }
845
+ promise.then(
846
+ (value) => settle({ status: "fulfilled", value }),
847
+ (reason) => settle({ status: "rejected", reason }),
848
+ )
849
+ }
850
+
851
+ export function Await<T>(promise: T, { fallback = "", then, error }: AwaitOptions<T>): string {
852
+ const shown = (outcome: Settled): string => {
853
+ if (outcome.status === "fulfilled") return then(outcome.value as Awaited<T>)
854
+ if (error) return error(outcome.reason as Error)
855
+ throw outcome.reason
856
+ }
857
+ const outcome: Settled | undefined =
858
+ typeof (promise as { then?: unknown } | null)?.then === "function"
859
+ ? (settledOf(promise as PromiseLike<unknown>) ?? learned.get(promise as object))
860
+ : { status: "fulfilled", value: promise }
861
+ if (outcome) return shown(outcome)
862
+ if (!isServer) learnOutcome(promise as PromiseLike<unknown>)
863
+ const state = currentState()
864
+ if (!state?.deferred) return fallback
865
+ const id = state.deferred.length
866
+ const value = Promise.resolve(promise as PromiseLike<unknown>)
867
+ value.catch(() => {})
868
+ const captured = { ...state }
869
+ state.deferred.push({
870
+ id,
871
+ value,
872
+ render: (settled) =>
873
+ renderIn(captured, () =>
874
+ shown(
875
+ "error" in settled
876
+ ? { status: "rejected", reason: settled.error }
877
+ : { status: "fulfilled", value: settled.value },
878
+ ),
879
+ ),
880
+ })
881
+ return `<hamur-defer id="${deferPartId(id)}">${fallback}</hamur-defer>`
882
+ }
883
+
884
+ /** The server writes `fallback` and, after it, the children in a `<template>` that the client entry swaps in once the app mounted; a script-free page keeps the fallback. The browser paints the children at once. */
885
+ export function ClientOnly(children: () => string, { fallback = "" }: { fallback?: string } = {}): string {
886
+ if (!isServer) return children()
887
+ if (currentState()?.route.meta.scripts === false) return fallback
888
+ return `<!--${CLIENT_MARKERS[0]}-->${fallback}<!--${CLIENT_MARKERS[1]}--><template data-hamur-client>${children()}</template>`
889
+ }
890
+
891
+ /** The children under `import.meta.dev` or in the `hamur dev` client, `fallback` otherwise; the production build rewrites the call to `DevOnly(undefined, …)` so the children's code is gone. */
892
+ export function DevOnly(children: (() => string) | undefined, { fallback = "" }: { fallback?: string } = {}): string {
893
+ return (isDev || devHydration.devClient === true) && children ? children() : fallback
894
+ }
895
+
896
+ export function DefaultErrorPage({ error }: { error: ErrorPageProps }): string {
897
+ const code =
898
+ isDev && error.code
899
+ ? `<p><a href="${escapeAttribute(diagnosticURL(error.code as DiagnosticCode))}" target="_blank" rel="noopener">${escapeAttribute(error.code)}</a></p>`
900
+ : ""
901
+ const stack = error.stack ? `<pre>${escapeAttribute(error.stack)}</pre>` : ""
902
+ return `<main style="font-family:system-ui,sans-serif;text-align:center;padding:4rem 1rem"><h1 style="font-size:4rem;margin:0">${error.status}</h1><p>${escapeAttribute(error.message)}</p>${code}${stack}${Link({ to: "/", children: "Back home" })}</main>`
903
+ }
904
+
905
+ export function useApp(): AppContext {
906
+ const state = currentState()
907
+ if (!state) throw new Error("useApp() must be called inside a Hamur app")
908
+ return state.app
909
+ }
910
+
911
+ export function useId(): string {
912
+ const state = currentState()
913
+ if (!state) throw new Error("useId() must be called inside a Hamur app")
914
+ return `s-${state.ids.next++}`
915
+ }
916
+
917
+ export function useHydrated(): () => boolean {
918
+ const app = useApp()
919
+ return () => !isServer && !app.asyncData.hydrating
920
+ }
921
+
922
+ export function useRequestEvent(): HamurEvent | undefined {
923
+ return requestEventOf(useApp())
924
+ }
925
+
926
+ /** 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. */
927
+ export function usePreviewMode(): PreviewMode {
928
+ return previewModeOf(useApp())
929
+ }
930
+
931
+ export function useRequestHeaders(names?: readonly string[]): Record<string, string> {
932
+ return requestHeadersOf(useApp(), names)
933
+ }
934
+
935
+ export function useRequestHeader(name: string): string | undefined {
936
+ return requestHeaderOf(useApp(), name)
937
+ }
938
+
939
+ export function useRequestURL(): URL {
940
+ return requestURLOf(useApp())
941
+ }
942
+
943
+ export function useRequestFetch(): $Fetch {
944
+ return requestFetchOf(useApp())
945
+ }
946
+
947
+ export function setResponseStatus(status: number, statusText?: string): void {
948
+ setResponseStatusOf(useApp(), status, statusText)
949
+ }
950
+
951
+ export function useResponseHeader(name: string): { value: string | undefined } {
952
+ const header = responseHeaderOf(useApp(), name)
953
+ return {
954
+ get value() {
955
+ return header.get()
956
+ },
957
+ set value(next: string | undefined) {
958
+ header.set(next)
959
+ },
960
+ }
961
+ }
962
+
963
+ export function useAsyncDataEntry<T = unknown>(key: string): { data: T | undefined }
964
+ export function useAsyncDataEntry<I, O>(fn: Handler<I, O>, input?: I): { data: O | undefined }
965
+ export function useAsyncDataEntry<T = unknown>(
966
+ target: string | HandlerReference,
967
+ input?: unknown,
968
+ ): { data: T | undefined } {
969
+ const key = typeof target === "string" ? target : asyncDataKey(target, input)
970
+ const store = useApp().asyncData
971
+ return {
972
+ get data() {
973
+ return store.get<T>(key)?.data
974
+ },
975
+ set data(next: T | undefined) {
976
+ store.setData(key, next)
977
+ },
978
+ }
979
+ }
980
+
981
+ export function clearState(keys?: Parameters<typeof clearStateOf>[1], options?: { reset?: boolean }): void {
982
+ clearStateOf(useApp(), keys, options)
983
+ }
984
+
985
+ export function callOnce(
986
+ key: string,
987
+ fn: () => unknown | Promise<unknown>,
988
+ options?: { mode?: "render" | "navigation" },
989
+ ): Promise<void> {
990
+ return callOnceOf(useApp(), key, fn, options)
991
+ }
992
+
993
+ export function useRuntimeConfig(): ClientRuntimeConfig {
994
+ return runtimeConfigOf(useApp())
995
+ }
996
+
997
+ export function useSiteConfig(): SiteConfig {
998
+ return siteConfigOf(useApp())
999
+ }
1000
+
1001
+ export function onPrehydrate(fn: (el: Element) => void): string {
1002
+ const id = prehydrate(useApp(), fn)
1003
+ return id === undefined ? "" : `data-hamur-p="${id}"`
1004
+ }
1005
+
1006
+ export const onBeforeNavigate = (fn: BeforeNavigateHook): (() => void) => navigationHook("before", fn)
1007
+ export const onNavigate = (fn: NavigateHook): (() => void) => navigationHook("navigate", fn)
1008
+ export const onAfterNavigate = (fn: AfterNavigateHook): (() => void) => navigationHook("after", fn)
1009
+ /** Called while a page renders in the browser, the registration lasts until the next paint (the page leaves or repaints). */
1010
+ function scoped(remove: () => void): () => void {
1011
+ currentState()?.scoped?.push(remove)
1012
+ return remove
1013
+ }
1014
+
1015
+ export const onBeforeRouteLeave = (fn: NavigationGuard): (() => void) =>
1016
+ scoped(routeGuard("leave", currentState()?.id, fn))
1017
+ export const onBeforeRouteUpdate = (fn: NavigationGuard): (() => void) =>
1018
+ scoped(routeGuard("update", currentState()?.id, fn))
1019
+ export const usePreventNavigate = (fn: NavigationBlocker): (() => void) => scoped(navigationBlocker(fn))
1020
+ export const useSnapshot = <T>(key: string, options: SnapshotOptions<T>): (() => void) =>
1021
+ scoped(registerSnapshot(key, options))
1022
+
1023
+ /** Registered while the page renders in the browser and removed before the next paint, so before the next page's `adapter.update`. */
1024
+ export function useRuntimeHook<K extends keyof AppHooks>(name: K, fn: AppHooks[K]): void {
1025
+ scoped(useApp().hooks.hook(name, fn))
1026
+ }
1027
+
1028
+ /** Registered while the page renders in the browser and removed before the next paint. */
1029
+ export function useReportWebVitals(fn: (metric: WebVitalMetric) => void | Promise<void>): void {
1030
+ scoped(reportWebVitals(useApp(), fn))
1031
+ }
1032
+
1033
+ interface ReadyVisit {
1034
+ render: unknown
1035
+ index: number
1036
+ scheduled: number
1037
+ }
1038
+
1039
+ const readyOfApp = new WeakMap<AppContext, ReadyVisit>()
1040
+
1041
+ /** The page function runs again on each repaint: the calls of one render are counted, and only those beyond the count already scheduled in this visit run. A navigation starts a new visit. */
1042
+ export function onAppReady(fn: () => void | Promise<void>): void {
1043
+ if (typeof window === "undefined") return
1044
+ const app = useApp()
1045
+ let visit = readyOfApp.get(app)
1046
+ if (!visit) {
1047
+ const created: ReadyVisit = (visit = { render: undefined, index: 0, scheduled: 0 })
1048
+ readyOfApp.set(app, created)
1049
+ navigationHook("navigate", () => {
1050
+ created.scheduled = 0
1051
+ })
1052
+ }
1053
+ const render = currentState()?.scoped
1054
+ if (visit.render !== render) {
1055
+ visit.render = render
1056
+ visit.index = 0
1057
+ }
1058
+ const index = visit.index++
1059
+ if (index < visit.scheduled) return
1060
+ visit.scheduled = index + 1
1061
+ whenAppReady(app, fn)
1062
+ }
1063
+
1064
+ /** Registers at once (during a render, until the next paint); `subscribe` tells a page script when the state changes, `remove()` unregisters. */
1065
+ export function useBlocker(
1066
+ options: ShouldBlock | UseBlockerOptions,
1067
+ ): Blocker & { subscribe(listener: () => void): () => void; remove(): void } {
1068
+ const store = createBlocker(options)
1069
+ const remove = scoped(store.start())
1070
+ return {
1071
+ get state() {
1072
+ return store.get().state
1073
+ },
1074
+ get location() {
1075
+ return store.get().location
1076
+ },
1077
+ proceed: () => store.get().proceed(),
1078
+ reset: () => store.get().reset(),
1079
+ subscribe: store.subscribe,
1080
+ remove,
1081
+ }
1082
+ }
1083
+
1084
+ export function useNavigation(): NavigationState {
1085
+ const state = currentState()
1086
+ if (!state) throw new Error("useNavigation() must be called inside a Hamur app")
1087
+ if (state.completesNavigation) return { state: "idle", pending: false }
1088
+ return state.navigator?.get?.() ?? { state: "idle", pending: false }
1089
+ }
1090
+
1091
+ export function useSearch(): { readonly value: RouteValue["search"]; set: SetSearch }
1092
+ export function useSearch<S>(select: (search: RouteValue["search"]) => S): { readonly value: S; set: SetSearch }
1093
+ export function useSearch<S>(select?: (search: RouteValue["search"]) => S): {
1094
+ readonly value: S | RouteValue["search"]
1095
+ set: SetSearch
1096
+ } {
1097
+ const state = currentState()
1098
+ if (!state) throw new Error("useSearch() must be called inside a Hamur app")
1099
+ const router = useRouter()
1100
+ const value = select ? select(state.route.search) : state.route.search
1101
+ const set: SetSearch = (change, { replace = true } = {}) => {
1102
+ const update = { query: (prev: RouteValue["search"]) => (typeof change === "function" ? change(prev) : change) }
1103
+ return replace ? router.replace(update) : router.navigate(update)
1104
+ }
1105
+ return { value, set }
1106
+ }
1107
+
1108
+ interface PagePoll {
1109
+ stop(): void
1110
+ page: string
1111
+ }
1112
+
1113
+ const pollsOfApp = new WeakMap<object, Map<string, PagePoll>>()
1114
+
1115
+ export function usePoll(ms: number, options: { keys?: string[] } = {}): () => void {
1116
+ pollInterval(ms)
1117
+ const router = useRouter()
1118
+ if (typeof document === "undefined") return () => {}
1119
+ const state = currentState()!
1120
+ let polls = pollsOfApp.get(state.app)
1121
+ if (!polls) {
1122
+ const registry = (polls = new Map<string, PagePoll>())
1123
+ pollsOfApp.set(state.app, registry)
1124
+ navigationHook("after", ({ to }) => {
1125
+ for (const [, poll] of [...registry]) if (poll.page !== to?.name) poll.stop()
1126
+ })
1127
+ }
1128
+ const id = JSON.stringify([ms, options.keys ?? null])
1129
+ const running = polls.get(id)
1130
+ if (running) return running.stop
1131
+ const registry = polls
1132
+ const stop = startPoll(ms, () => (options.keys ? router.refresh(options.keys) : router.refresh()))
1133
+ const poll: PagePoll = {
1134
+ page: state.route.name,
1135
+ stop() {
1136
+ stop()
1137
+ registry.delete(id)
1138
+ },
1139
+ }
1140
+ registry.set(id, poll)
1141
+ return poll.stop
1142
+ }
1143
+
1144
+ export function useOnline(): { readonly value: boolean } {
1145
+ return {
1146
+ get value() {
1147
+ return isOnline()
1148
+ },
1149
+ }
1150
+ }
1151
+
1152
+ /** During a server render, asks `hydrate` to run the page again in the browser, for a composable whose work happens only there. */
1153
+ export function rerunOnHydrate(): void {
1154
+ if (typeof document === "undefined") currentState()?.app.state.set(RERUN_STATE_KEY, true)
1155
+ }
1156
+
1157
+ export function useSyncedState<T>(
1158
+ key: string,
1159
+ initial: T,
1160
+ options: SyncedStateOptions = {},
1161
+ ): { get(): T; set(value: T): void; subscribe(callback: (value: T) => void): () => void } {
1162
+ rerunOnHydrate()
1163
+ const { get, set, subscribe } = syncedState(key, initial, options)
1164
+ return { get, set, subscribe }
1165
+ }
1166
+
1167
+ const handlerForms = new WeakMap<AppContext, WeakMap<object, HandlerForm<any, any>>>()
1168
+
1169
+ export function useForm<I, O>(fn: Handler<I, O>): HandlerForm<I, O> {
1170
+ const state = currentState()
1171
+ if (!state) throw new Error("useForm() must be called inside a Hamur app")
1172
+ let byFunction = handlerForms.get(state.app)
1173
+ if (!byFunction) handlerForms.set(state.app, (byFunction = new WeakMap()))
1174
+ let form = byFunction.get(fn)
1175
+ if (!form) {
1176
+ byFunction.set(fn, (form = createForm(fn, { app: state.app, submitted: () => currentState() ?? state })))
1177
+ form.subscribe(repaintPage)
1178
+ }
1179
+ return form
1180
+ }
1181
+
1182
+ const actions = new WeakMap<
1183
+ AppContext,
1184
+ WeakMap<object, Map<string | undefined, { runner: ActionRunner<any, any>; options: ActionOptions<any> }>>
1185
+ >()
1186
+
1187
+ export function useAction<I, O>(
1188
+ fn: Handler<I, O>,
1189
+ options: ActionOptions<O> & { instance?: string | number } = {},
1190
+ ): {
1191
+ run: ActionRunner<I, O>["run"]
1192
+ readonly state: O | undefined
1193
+ readonly pending: boolean
1194
+ readonly error: HamurError | undefined
1195
+ readonly failure: ActionFailure | undefined
1196
+ reset(): void
1197
+ subscribe(listener: () => void): () => void
1198
+ } {
1199
+ const state = currentState()
1200
+ if (!state) throw new Error("useAction() must be called inside a Hamur app")
1201
+ let byFunction = actions.get(state.app)
1202
+ if (!byFunction) actions.set(state.app, (byFunction = new WeakMap()))
1203
+ let instances = byFunction.get(fn)
1204
+ if (!instances) byFunction.set(fn, (instances = new Map()))
1205
+ const { instance } = options
1206
+ const key = instance === undefined ? undefined : String(instance)
1207
+ let entry = instances.get(key)
1208
+ if (!entry) {
1209
+ const created = { options, runner: undefined as unknown as ActionRunner<I, O> }
1210
+ created.runner = createActionRunner(fn, {
1211
+ app: state.app,
1212
+ instance,
1213
+ options: () => created.options,
1214
+ refresh: () => routerOf(state.navigator, state.baseURL).refresh(),
1215
+ restored: restoredResult<O>(state.handlerState, fn.id, instance),
1216
+ })
1217
+ instances.set(key, (entry = created))
1218
+ }
1219
+ entry.options = options
1220
+ const { runner } = entry as { runner: ActionRunner<I, O> }
1221
+ return {
1222
+ run: runner.run,
1223
+ reset: runner.reset,
1224
+ subscribe: runner.subscribe,
1225
+ get state() {
1226
+ return runner.get().state
1227
+ },
1228
+ get pending() {
1229
+ return runner.get().pending
1230
+ },
1231
+ get error() {
1232
+ return runner.get().error
1233
+ },
1234
+ get failure() {
1235
+ return runner.get().failure
1236
+ },
1237
+ }
1238
+ }
1239
+
1240
+ function pushHead(name: string, input: HeadInput, options?: HeadPending["options"]): void {
1241
+ const state = currentState()
1242
+ if (!state) throw new Error(`${name}() must be called inside a Hamur app`)
1243
+ if (!options?.server && typeof document === "undefined") state.app.state?.set(RERUN_STATE_KEY, true)
1244
+ if (state.pending) {
1245
+ state.pending.push({ input, options })
1246
+ return
1247
+ }
1248
+ const entry = state.head.push(input, options)
1249
+ state.entries?.push(entry)
1250
+ }
1251
+
1252
+ export function useHead(input: HeadInput): void {
1253
+ pushHead("useHead", input)
1254
+ }
1255
+
1256
+ export function useSeoMeta(input: SeoMetaInput): void {
1257
+ useHead(seoMetaToHead(input))
1258
+ }
1259
+
1260
+ type ServerHeadInput = Omit<HeadInput, "title" | "titleTemplate">
1261
+ type ServerSeoMetaInput = Omit<SeoMetaInput, "title" | "titleTemplate">
1262
+
1263
+ export function useHeadSafe(input: HeadSafeInput): void {
1264
+ useHead(sanitizeHead(input))
1265
+ }
1266
+
1267
+ export function useServerHead(input: ServerHeadInput): void {
1268
+ if (typeof document === "undefined") pushHead("useServerHead", input, { server: true })
1269
+ }
1270
+
1271
+ export function useServerSeoMeta(input: ServerSeoMetaInput): void {
1272
+ if (typeof document === "undefined") useServerHead(seoMetaToHead(input))
1273
+ }
1274
+
1275
+ export function useState<T>(key: StateKey<T>): { value: T }
1276
+ export function useState<T = unknown>(key: string, init?: T | (() => T)): { value: T }
1277
+ export function useState<T = unknown>(...args: unknown[]): { value: T } {
1278
+ const { key, init } = stateArguments(args) as { key: string; init: T | (() => T) | undefined }
1279
+ const store = currentState()?.app.state
1280
+ if (!store) throw new Error("useState() must be called inside a Hamur app")
1281
+ store.use(key, init)
1282
+ return {
1283
+ get value() {
1284
+ return store.get<T>(key) as T
1285
+ },
1286
+ set value(next: T) {
1287
+ store.set(key, next)
1288
+ },
1289
+ }
1290
+ }
1291
+
1292
+ export function useCookie<T = string>(
1293
+ name: string,
1294
+ options: Omit<UseCookieOptions<T>, "app"> & { default: () => T },
1295
+ ): { value: T }
1296
+ export function useCookie<T = string>(
1297
+ name: string,
1298
+ options?: Omit<UseCookieOptions<T>, "app">,
1299
+ ): { value: T | undefined }
1300
+ export function useCookie<T = string>(
1301
+ name: string,
1302
+ options: Omit<UseCookieOptions<T>, "app"> = {},
1303
+ ): { value: T | undefined } {
1304
+ const cookie = useCookieRef<T>(name, { ...options, app: useApp() })
1305
+ return {
1306
+ get value() {
1307
+ return cookie.get()
1308
+ },
1309
+ set value(next: T | undefined) {
1310
+ cookie.set(next)
1311
+ },
1312
+ }
1313
+ }
1314
+
1315
+ export interface UseAsyncDataOptions<T = unknown, R = T, K extends keyof T & string = never, D = T> extends Omit<
1316
+ AsyncDataOptions<T, R, D>,
1317
+ "pick"
1318
+ > {
1319
+ /** Accepted for the same options in every adapter and ignored: nothing watches. */
1320
+ watch?: false
1321
+ getCachedData?: GetCachedData<T>
1322
+ /** Top-level keys of an object result to keep. */
1323
+ pick?: readonly K[]
1324
+ }
1325
+
1326
+ export interface UseFetchOptions<T = unknown, R = T, K extends keyof T & string = never, D = T>
1327
+ extends FetchRequest, UseAsyncDataOptions<T, R, K, D> {
1328
+ /** The store key, instead of the one derived from the url and the request. */
1329
+ key?: string
1330
+ }
1331
+
1332
+ export interface UseAsyncDataResult<T, D = undefined> {
1333
+ readonly data: T | D
1334
+ readonly error: HamurError | undefined
1335
+ readonly status: AsyncDataStatus
1336
+ /** `status === "pending"`, or `idle` without data under `app.asyncData.pendingWhenIdle`. */
1337
+ readonly pending: boolean
1338
+ refresh(): Promise<void>
1339
+ /** The same function as `refresh`. */
1340
+ execute(): Promise<void>
1341
+ /** Resets the entry of this key to `idle` (`clearAsyncData`). */
1342
+ clear(): void
1343
+ /** A browser render that left the entry pending paints the page again when it settles; for other changes, such as `refresh()`, render from the listener. */
1344
+ subscribe(listener: () => void): () => void
1345
+ }
1346
+
1347
+ const isServer = typeof document === "undefined"
1348
+
1349
+ interface Hold {
1350
+ paint: number
1351
+ store: AsyncData
1352
+ key: string
1353
+ waiting: boolean
1354
+ stop: () => void
1355
+ }
1356
+
1357
+ let holds: Hold[] = []
1358
+
1359
+ // Every key a paint read stays subscribed until a later paint has subscribed its own, so the store never purges an
1360
+ // entry the page still shows; the earlier paint's keys are let go only then, purged and their runs aborted.
1361
+ function holdForPaint(store: AsyncData, key: string, pending: boolean): void {
1362
+ const paint = paintCount()
1363
+ let hold = holds.find((item) => item.paint === paint && item.store === store && item.key === key)
1364
+ if (!hold) {
1365
+ const created: Hold = { paint, store, key, waiting: false, stop: () => {} }
1366
+ created.stop = store.subscribe(key, () => {
1367
+ const status = store.get(key)?.status
1368
+ if (!created.waiting || status === "pending" || status === "idle") return
1369
+ created.waiting = false
1370
+ queueMicrotask(() => repaintWithData(paint))
1371
+ })
1372
+ holds.push((hold = created))
1373
+ }
1374
+ if (pending) hold.waiting = true
1375
+ const earlier = holds.filter((item) => item.paint !== paint)
1376
+ if (!earlier.length) return
1377
+ holds = holds.filter((item) => item.paint === paint)
1378
+ for (const item of earlier) item.stop()
1379
+ }
1380
+
1381
+ export function useAsyncData<I, R, T = R, K extends keyof T & string = never, D = T>(
1382
+ fn: Handler<I, R>,
1383
+ input: NoInfer<I> | (() => NoInfer<I>) | undefined,
1384
+ options: UseAsyncDataOptions<T, R, K, D> & { default: () => D },
1385
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1386
+ export function useAsyncData<I, R, T = R, K extends keyof T & string = never>(
1387
+ fn: Handler<I, R>,
1388
+ input?: NoInfer<I> | (() => NoInfer<I>),
1389
+ options?: UseAsyncDataOptions<T, R, K, undefined>,
1390
+ ): UseAsyncDataResult<PickFrom<T, K>>
1391
+ export function useAsyncData<T = unknown, R = T, K extends keyof T & string = never, D = T>(
1392
+ keyOrGetter: string | (() => string),
1393
+ handler: AsyncDataHandler<R>,
1394
+ options: UseAsyncDataOptions<T, R, K, D> & { default: () => D },
1395
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1396
+ export function useAsyncData<T = unknown, R = T, K extends keyof T & string = never>(
1397
+ keyOrGetter: string | (() => string),
1398
+ handler: AsyncDataHandler<R>,
1399
+ options?: UseAsyncDataOptions<T, R, K, undefined>,
1400
+ ): UseAsyncDataResult<PickFrom<T, K>>
1401
+ export function useAsyncData(...args: unknown[]): UseAsyncDataResult<any, any> {
1402
+ const [first, second, given] = asyncDataArguments("useAsyncData", args) as [
1403
+ string | (() => string) | HandlerReference,
1404
+ unknown,
1405
+ UseAsyncDataOptions<any, any, any, any> | undefined,
1406
+ ]
1407
+ const options = given ?? {}
1408
+ if (!isHandlerReference(first))
1409
+ return keyedAsyncData(first as string | (() => string), second as AsyncDataHandler<unknown>, options)
1410
+ const input = valueOf(second)
1411
+ return keyedAsyncData(
1412
+ asyncDataKey(first as HandlerReference, input),
1413
+ callHandler(useApp(), first as HandlerReference, input),
1414
+ options,
1415
+ )
1416
+ }
1417
+
1418
+ function keyedAsyncData<T, R, K extends keyof T & string, D>(
1419
+ keyOrGetter: string | (() => string),
1420
+ handler: AsyncDataHandler<R>,
1421
+ options: UseAsyncDataOptions<T, R, K, D>,
1422
+ ): UseAsyncDataResult<PickFrom<T, K>, D> {
1423
+ const key = valueOf(keyOrGetter)
1424
+ const app = useApp()
1425
+ const store = app.asyncData
1426
+ const {
1427
+ server,
1428
+ lazy,
1429
+ default: init,
1430
+ transform,
1431
+ immediate,
1432
+ dedupe,
1433
+ pick,
1434
+ getCachedData = defaultGetCachedData,
1435
+ } = options
1436
+ const settings = {
1437
+ server,
1438
+ lazy,
1439
+ default: init as AsyncDataOptions<T, R>["default"],
1440
+ transform,
1441
+ immediate,
1442
+ dedupe,
1443
+ pick,
1444
+ }
1445
+ const again = !isServer && isRepaintingWithData()
1446
+ keepCached(app, key, getCachedData)
1447
+ const entry: AsyncDataEntry<T> = store.fetch<T, R>(
1448
+ key,
1449
+ handler,
1450
+ again ? settings : { ...settings, cached: getCachedData(key, app, { cause: "initial" }) },
1451
+ )
1452
+ if (isServer) {
1453
+ if (entry.status === "pending") markWaiting(store)
1454
+ } else
1455
+ holdForPaint(
1456
+ store,
1457
+ key,
1458
+ entry.status === "pending" ||
1459
+ (store.hydrating && server === false && immediate !== false && entry.status === "idle"),
1460
+ )
1461
+ const read = () => store.get<T>(key) ?? entry
1462
+ const refresh = () => refreshCached(app, key, handler, settings, getCachedData, "refresh:manual")
1463
+ if (!isServer && !store.refreshHook(key))
1464
+ store.onRefresh(key, () => refreshCached(app, key, handler, settings, getCachedData, "refresh:hook"))
1465
+ return {
1466
+ get data() {
1467
+ return read().data as PickFrom<T, K> | D
1468
+ },
1469
+ get error() {
1470
+ return read().error
1471
+ },
1472
+ get status() {
1473
+ return read().status
1474
+ },
1475
+ get pending() {
1476
+ return isPending(app, read())
1477
+ },
1478
+ refresh,
1479
+ execute: refresh,
1480
+ clear: () => clearAsyncData(app, key),
1481
+ subscribe: (listener) => store.subscribe(key, listener),
1482
+ }
1483
+ }
1484
+
1485
+ /** What a literal `useFetch` call is checked against; any other call stays loose. */
1486
+ type FetchInput<X> = X extends { key: infer K extends string; input: infer I }
1487
+ ? FetchInputField<I, K, I | (() => I)>
1488
+ : unknown
1489
+ type Unkeyed<O, X> = X extends { key: infer K extends string } ? Omit<O, K> : O
1490
+ type FetchCall<U extends string, M extends string, B extends string | undefined> = {
1491
+ method?: M | string
1492
+ baseURL?: B | string
1493
+ } & FetchInput<FetchCheckedInput<U, M, B>>
1494
+
1495
+ export function useFetch<
1496
+ U extends string,
1497
+ M extends string = "GET",
1498
+ K extends keyof FetchData<U, M> & string = never,
1499
+ D = undefined,
1500
+ B extends string | undefined = undefined,
1501
+ >(
1502
+ url: U | (() => U),
1503
+ options?: Unkeyed<UseFetchOptions<FetchData<U, M>, FetchData<U, M>, K, D>, FetchCheckedInput<U, M, B>> &
1504
+ FetchCall<U, M, B>,
1505
+ ): UseAsyncDataResult<PickFrom<FetchData<U, M>, K>, D>
1506
+ export function useFetch<
1507
+ T = unknown,
1508
+ R = T,
1509
+ K extends keyof T & string = never,
1510
+ D = T,
1511
+ U extends string = string,
1512
+ M extends string = "GET",
1513
+ B extends string | undefined = undefined,
1514
+ >(
1515
+ urlOrGetter: U | (() => U),
1516
+ options: Unkeyed<UseFetchOptions<T, R, K, D>, FetchCheckedInput<U, M, B>> & { default: () => D } & FetchCall<U, M, B>,
1517
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1518
+ export function useFetch<
1519
+ T = unknown,
1520
+ R = T,
1521
+ K extends keyof T & string = never,
1522
+ U extends string = string,
1523
+ M extends string = "GET",
1524
+ B extends string | undefined = undefined,
1525
+ >(
1526
+ urlOrGetter: U | (() => U),
1527
+ options?: Unkeyed<UseFetchOptions<T, R, K, undefined>, FetchCheckedInput<U, M, B>> & FetchCall<U, M, B>,
1528
+ ): UseAsyncDataResult<PickFrom<T, K>>
1529
+ export function useFetch<T = unknown, R = T, K extends keyof T & string = never, D = T>(
1530
+ urlOrGetter: string | (() => string),
1531
+ options: UseFetchOptions<T, R, K, D> = {},
1532
+ ): UseAsyncDataResult<PickFrom<T, K>, D> {
1533
+ return fetchWith<T, R, K, D>(undefined, urlOrGetter, options)
1534
+ }
1535
+
1536
+ function fetchWith<T, R, K extends keyof T & string, D>(
1537
+ client: $Fetch | undefined,
1538
+ urlOrGetter: string | (() => string),
1539
+ options: UseFetchOptions<T, R, K, D>,
1540
+ ): UseAsyncDataResult<PickFrom<T, K>, D> {
1541
+ const {
1542
+ key,
1543
+ server,
1544
+ lazy,
1545
+ default: init,
1546
+ transform,
1547
+ immediate,
1548
+ dedupe,
1549
+ pick,
1550
+ watch: _watch,
1551
+ getCachedData,
1552
+ ...rest
1553
+ } = options
1554
+ const url = valueOf(urlOrGetter)
1555
+ const request = requestOf(rest)
1556
+ const fetcher = client ?? useApp().fetch ?? $fetch
1557
+ return useAsyncData<T, R, K, D>(
1558
+ key ?? fetchKey(url, request),
1559
+ ({ signal }) => fetcher<R>(url, { ...request, signal: signalOf(request.signal, signal) }),
1560
+ { server, lazy, default: init as () => D, transform, immediate, dedupe, pick, getCachedData },
1561
+ )
1562
+ }
1563
+
1564
+ /** `createUseFetch` defaults change what a call sends (method, body, query, baseURL), so its calls check nothing. */
1565
+ interface UseFetchLoose {
1566
+ <U extends string, M extends string = "GET", K extends keyof FetchData<U, M> & string = never, D = undefined>(
1567
+ url: U | (() => U),
1568
+ options?: UseFetchOptions<FetchData<U, M>, FetchData<U, M>, K, D> & { method?: M },
1569
+ ): UseAsyncDataResult<PickFrom<FetchData<U, M>, K>, D>
1570
+ <T = unknown, R = T, K extends keyof T & string = never, D = T>(
1571
+ url: string | (() => string),
1572
+ options: UseFetchOptions<T, R, K, D> & { default: () => D },
1573
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1574
+ <T = unknown, R = T, K extends keyof T & string = never>(
1575
+ url: string | (() => string),
1576
+ options?: UseFetchOptions<T, R, K, undefined>,
1577
+ ): UseAsyncDataResult<PickFrom<T, K>>
1578
+ }
1579
+
1580
+ type AnyFetchOptions = UseFetchOptions<any, any, any, any>
1581
+
1582
+ /** `useFetch` with `defaults` under every call's options; `$fetch` replaces the request-bound client, e.g. a `$fetch.create` one. */
1583
+ export function createUseFetch(
1584
+ defaults: AnyFetchOptions | ((options: AnyFetchOptions) => AnyFetchOptions),
1585
+ { $fetch: client }: { $fetch?: $Fetch } = {},
1586
+ ): UseFetchLoose {
1587
+ return ((url: string | (() => string), options?: AnyFetchOptions) =>
1588
+ fetchWith(client, url, resolveCallOptions(defaults, options))) as unknown as UseFetchLoose
1589
+ }
1590
+
1591
+ /** `useAsyncData` with `defaults` under every call's options. */
1592
+ export function createUseAsyncData(
1593
+ defaults:
1594
+ | UseAsyncDataOptions<any, any, any, any>
1595
+ | ((options: UseAsyncDataOptions<any, any, any, any>) => UseAsyncDataOptions<any, any, any, any>),
1596
+ ): typeof useAsyncData {
1597
+ return ((...args: unknown[]) => {
1598
+ const [first, second, options] = asyncDataArguments("useAsyncData", args)
1599
+ return useAsyncData(
1600
+ first as never,
1601
+ second as never,
1602
+ resolveCallOptions(defaults, options as UseAsyncDataOptions<any, any, any, any> | undefined),
1603
+ )
1604
+ }) as typeof useAsyncData
1605
+ }
1606
+
1607
+ export const useLazyFetch: typeof useFetch = ((url: string | (() => string), options?: AnyFetchOptions) =>
1608
+ useFetch(url, { ...options, lazy: true })) as typeof useFetch
1609
+
1610
+ export const useLazyAsyncData: typeof useAsyncData = ((...args: unknown[]) => {
1611
+ const [first, second, options] = asyncDataArguments("useLazyAsyncData", args)
1612
+ return useAsyncData(first as never, second as never, {
1613
+ ...(options as UseAsyncDataOptions<any, any, any, any>),
1614
+ lazy: true,
1615
+ })
1616
+ }) as typeof useAsyncData
1617
+
1618
+ export function transitionName(name: string): string {
1619
+ return `view-transition-name: ${checkTransitionName(name)}`
1620
+ }