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