@hamur/adapter-vue 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 +32 -2
- package/dist/chunks/browser-index-43pdsfp6.js +69 -0
- package/dist/chunks/browser-index-d1bxd40m.js +320 -0
- package/dist/chunks/browser-index-nhft0ewv.js +161 -0
- package/dist/src/adapter.js +402 -0
- package/dist/src/index.js +1348 -0
- package/dist/src/keepalive.js +6 -0
- package/dist/src/runtime/client.js +20 -0
- package/dist/src/runtime/island.js +45 -0
- package/dist/src/runtime/server.js +238 -0
- package/dist/types/src/adapter.d.ts +2 -0
- package/dist/types/src/async-data.d.ts +14 -0
- package/dist/types/src/client-component.d.ts +12 -0
- package/dist/types/src/client-fallback.d.ts +2 -0
- package/dist/types/src/components/AwaitValue.d.ts +15 -0
- package/dist/types/src/components/ClientFallback.server.d.ts +17 -0
- package/dist/types/src/components/ErrorBoundary.server.d.ts +21 -0
- package/dist/types/src/components/error-code.d.ts +1 -0
- package/dist/types/src/context.d.ts +65 -0
- package/dist/types/src/index.d.ts +329 -0
- package/dist/types/src/island.d.ts +68 -0
- package/dist/types/src/keepalive.d.ts +22 -0
- package/dist/types/src/lazy-hydration.d.ts +10 -0
- package/dist/types/src/markdown-page.d.ts +9 -0
- package/dist/types/src/markdown.d.ts +45 -0
- package/dist/types/src/plugin.d.ts +45 -0
- package/dist/types/src/route-boundary.d.ts +35 -0
- package/dist/types/src/route-boundary.server.d.ts +5 -0
- package/dist/types/src/runtime/client.d.ts +11 -0
- package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
- package/dist/types/src/runtime/hydration.d.ts +8 -0
- package/dist/types/src/runtime/island.d.ts +8 -0
- package/dist/types/src/runtime/server.d.ts +12 -0
- package/dist/types/src/server-island.d.ts +33 -0
- package/dist/types/src/svg.d.ts +10 -0
- package/package.json +64 -4
- package/src/adapter.ts +25 -0
- package/src/async-data.ts +77 -0
- package/src/client-component.ts +39 -0
- package/src/client-fallback.ts +2 -0
- package/src/components/Await.vue +30 -0
- package/src/components/AwaitValue.ts +41 -0
- package/src/components/ClientFallback.server.ts +41 -0
- package/src/components/ClientFallback.vue +31 -0
- package/src/components/ClientOnly.vue +16 -0
- package/src/components/DefaultErrorPage.vue +19 -0
- package/src/components/DevOnly.vue +8 -0
- package/src/components/ErrorBoundary.server.ts +69 -0
- package/src/components/ErrorBoundary.vue +32 -0
- package/src/components/Form.vue +85 -0
- package/src/components/Link.vue +200 -0
- package/src/components/Navigate.vue +16 -0
- package/src/components/Outlet.vue +28 -0
- package/src/components/error-code.ts +7 -0
- package/src/context.ts +391 -0
- package/src/index.ts +1528 -0
- package/src/island.ts +53 -0
- package/src/keepalive.ts +92 -0
- package/src/lazy-hydration.ts +53 -0
- package/src/markdown-page.ts +21 -0
- package/src/markdown.ts +80 -0
- package/src/plugin.ts +398 -0
- package/src/route-boundary.server.ts +29 -0
- package/src/route-boundary.ts +48 -0
- package/src/runtime/client.ts +137 -0
- package/src/runtime/hydration-dev.ts +38 -0
- package/src/runtime/hydration.ts +7 -0
- package/src/runtime/island.ts +60 -0
- package/src/runtime/server.ts +145 -0
- package/src/server-island.ts +38 -0
- package/src/svg.ts +28 -0
- package/src/vue.d.ts +5 -0
- package/src/webmcp.d.ts +18 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,1528 @@
|
|
|
1
|
+
/// <reference path="./webmcp.d.ts" />
|
|
2
|
+
import {
|
|
3
|
+
computed,
|
|
4
|
+
customRef,
|
|
5
|
+
defineComponent,
|
|
6
|
+
getCurrentInstance,
|
|
7
|
+
getCurrentScope,
|
|
8
|
+
h,
|
|
9
|
+
inject,
|
|
10
|
+
isRef,
|
|
11
|
+
onActivated,
|
|
12
|
+
onBeforeUpdate,
|
|
13
|
+
onDeactivated,
|
|
14
|
+
onMounted,
|
|
15
|
+
onScopeDispose,
|
|
16
|
+
onServerPrefetch,
|
|
17
|
+
reactive,
|
|
18
|
+
shallowReactive,
|
|
19
|
+
shallowRef,
|
|
20
|
+
toValue,
|
|
21
|
+
useId,
|
|
22
|
+
watch,
|
|
23
|
+
watchEffect,
|
|
24
|
+
onUnmounted,
|
|
25
|
+
} from "vue"
|
|
26
|
+
import { reportWebVitals, syncedState } from "hamur/app"
|
|
27
|
+
import type { SyncedStateOptions } from "hamur/app"
|
|
28
|
+
import {
|
|
29
|
+
asyncDataArguments,
|
|
30
|
+
asyncDataKey,
|
|
31
|
+
checkTransitionName,
|
|
32
|
+
stateArguments,
|
|
33
|
+
fetchKey,
|
|
34
|
+
TIME_PROPS,
|
|
35
|
+
timeView,
|
|
36
|
+
watchTime,
|
|
37
|
+
LOADING_INDICATOR_PROPS,
|
|
38
|
+
createLoadingIndicator,
|
|
39
|
+
loadingIndicatorOptions,
|
|
40
|
+
paintLoadingIndicator,
|
|
41
|
+
createRouteAnnouncer,
|
|
42
|
+
createAnnouncer,
|
|
43
|
+
announcerActions,
|
|
44
|
+
announcerRole,
|
|
45
|
+
hideAnnouncer,
|
|
46
|
+
ROUTE_ANNOUNCER_ID,
|
|
47
|
+
ANNOUNCER_POLITE_ID,
|
|
48
|
+
ANNOUNCER_ASSERTIVE_ID,
|
|
49
|
+
isHandlerReference,
|
|
50
|
+
isPending,
|
|
51
|
+
resolveCallOptions,
|
|
52
|
+
} from "hamur/adapter"
|
|
53
|
+
import type { AppHooks, WebVitalMetric } from "hamur/app"
|
|
54
|
+
import { whenAppReady } from "hamur/adapter"
|
|
55
|
+
import type {
|
|
56
|
+
ComputedRef,
|
|
57
|
+
DefineSetupFnComponent,
|
|
58
|
+
FunctionalComponent,
|
|
59
|
+
MaybeRef,
|
|
60
|
+
MaybeRefOrGetter,
|
|
61
|
+
Ref,
|
|
62
|
+
ShallowRef,
|
|
63
|
+
WatchSource,
|
|
64
|
+
} from "vue"
|
|
65
|
+
import { clearAsyncData, createForm, useCookie as cookieOf, withoutBase } from "hamur/app"
|
|
66
|
+
import type { RouteLocation } from "hamur/app"
|
|
67
|
+
import {
|
|
68
|
+
callOnce as callOnceOf,
|
|
69
|
+
clearState as clearStateOf,
|
|
70
|
+
setResponseStatus as setResponseStatusOf,
|
|
71
|
+
useResponseHeader as responseHeaderOf,
|
|
72
|
+
useRequestEvent as requestEventOf,
|
|
73
|
+
useRequestFetch as requestFetchOf,
|
|
74
|
+
useRequestHeader as requestHeaderOf,
|
|
75
|
+
useRequestHeaders as requestHeadersOf,
|
|
76
|
+
useRequestURL as requestURLOf,
|
|
77
|
+
usePreviewMode as previewModeOf,
|
|
78
|
+
} from "hamur/app"
|
|
79
|
+
import type { PreviewMode } from "hamur/app"
|
|
80
|
+
import type { $Fetch, FetchCheckedInput, FetchInputField } from "hamur/app"
|
|
81
|
+
import type { StateKey as StateKeyOf } from "hamur/app"
|
|
82
|
+
import type { HamurEvent } from "hamur/server"
|
|
83
|
+
import {
|
|
84
|
+
layoutSegments,
|
|
85
|
+
IDLE_FORM_STATUS,
|
|
86
|
+
createActionRunner,
|
|
87
|
+
linkActionRunner,
|
|
88
|
+
restoredResult,
|
|
89
|
+
optimisticSource,
|
|
90
|
+
runtimeConfigOf,
|
|
91
|
+
siteConfigOf,
|
|
92
|
+
sanitizeHead,
|
|
93
|
+
seoMetaToHead,
|
|
94
|
+
navigationHook,
|
|
95
|
+
navigationBlocker,
|
|
96
|
+
routeGuard,
|
|
97
|
+
createBlocker,
|
|
98
|
+
registerSnapshot,
|
|
99
|
+
} from "hamur/adapter"
|
|
100
|
+
import type {
|
|
101
|
+
AnnouncerActions,
|
|
102
|
+
AnnouncerPoliteness,
|
|
103
|
+
RouteAnnouncerActions,
|
|
104
|
+
RouteAnnouncerPoliteness,
|
|
105
|
+
LoadingIndicatorActions,
|
|
106
|
+
LoadingIndicatorProps,
|
|
107
|
+
LoadingIndicatorOptions,
|
|
108
|
+
TimeInput,
|
|
109
|
+
} from "hamur/adapter"
|
|
110
|
+
import { prehydrate } from "hamur/adapter"
|
|
111
|
+
import type {
|
|
112
|
+
ActionOptions,
|
|
113
|
+
ActionRunner,
|
|
114
|
+
FormStatus,
|
|
115
|
+
Handler,
|
|
116
|
+
AfterNavigateHook,
|
|
117
|
+
BeforeNavigateHook,
|
|
118
|
+
NavigateHook,
|
|
119
|
+
NavigationHookKind,
|
|
120
|
+
Navigation,
|
|
121
|
+
NavigationBlocker,
|
|
122
|
+
NavigationGuard,
|
|
123
|
+
RouteGuardKind,
|
|
124
|
+
Blocker,
|
|
125
|
+
ShouldBlock,
|
|
126
|
+
UseBlockerOptions,
|
|
127
|
+
SnapshotOptions,
|
|
128
|
+
} from "hamur/adapter"
|
|
129
|
+
import type { HandlerForm } from "hamur/app"
|
|
130
|
+
import {
|
|
131
|
+
linkPending,
|
|
132
|
+
createLinkSlot,
|
|
133
|
+
linkAttributes,
|
|
134
|
+
linkDefaultsOf,
|
|
135
|
+
linkPrefetchProps,
|
|
136
|
+
linkState,
|
|
137
|
+
relativeTarget,
|
|
138
|
+
resolveLinkTarget,
|
|
139
|
+
searchTarget,
|
|
140
|
+
} from "hamur/adapter"
|
|
141
|
+
import type { CheckedTarget, LinkDefaults, LinkSlot, UseLinkOptions } from "hamur/adapter"
|
|
142
|
+
import type {
|
|
143
|
+
RouteLoaderData,
|
|
144
|
+
UseDataArgs,
|
|
145
|
+
AsyncDataHandler,
|
|
146
|
+
GetCachedData,
|
|
147
|
+
GetCachedDataCause,
|
|
148
|
+
HandlerReference,
|
|
149
|
+
NavigationState,
|
|
150
|
+
RouteValue,
|
|
151
|
+
RouterApi,
|
|
152
|
+
} from "hamur/adapter"
|
|
153
|
+
import type {
|
|
154
|
+
ActionFailure,
|
|
155
|
+
AppContext,
|
|
156
|
+
PendingRun,
|
|
157
|
+
PickFrom,
|
|
158
|
+
AsyncDataEntry,
|
|
159
|
+
ClientRuntimeConfig,
|
|
160
|
+
SiteConfig,
|
|
161
|
+
FetchData,
|
|
162
|
+
AsyncDataOptions,
|
|
163
|
+
AsyncDataStatus,
|
|
164
|
+
UseCookieOptions,
|
|
165
|
+
ErrorPageProps,
|
|
166
|
+
Head,
|
|
167
|
+
HeadInput,
|
|
168
|
+
HeadSafeInput,
|
|
169
|
+
SeoMetaInput,
|
|
170
|
+
HamurError,
|
|
171
|
+
} from "hamur/app"
|
|
172
|
+
import {
|
|
173
|
+
AppKey,
|
|
174
|
+
DataKey,
|
|
175
|
+
EntryKey,
|
|
176
|
+
ErrorKey,
|
|
177
|
+
FormStatusKey,
|
|
178
|
+
HeadKey,
|
|
179
|
+
HrefKey,
|
|
180
|
+
LayoutKey,
|
|
181
|
+
SubmittedKey,
|
|
182
|
+
BaseURLKey,
|
|
183
|
+
HeadPatchesKey,
|
|
184
|
+
LinkHrefKey,
|
|
185
|
+
NavigationKey,
|
|
186
|
+
NeverHydratedKey,
|
|
187
|
+
OutletValueKey,
|
|
188
|
+
RouteKey,
|
|
189
|
+
RouterKey,
|
|
190
|
+
StateKey,
|
|
191
|
+
detachedHref,
|
|
192
|
+
} from "./context.ts"
|
|
193
|
+
import { $fetch } from "hamur/app"
|
|
194
|
+
import type { FetchOptions } from "hamur/app"
|
|
195
|
+
import { deepToValue, defaultGetCachedData, hasReactive, keepCached, refreshCached, signalOf } from "./async-data.ts"
|
|
196
|
+
|
|
197
|
+
export {
|
|
198
|
+
addRouteMiddleware,
|
|
199
|
+
clearError,
|
|
200
|
+
disableScrollHandling,
|
|
201
|
+
forbidden,
|
|
202
|
+
navigateTo,
|
|
203
|
+
notFound,
|
|
204
|
+
permanentRedirect,
|
|
205
|
+
refreshCookie,
|
|
206
|
+
setPageLayout,
|
|
207
|
+
showError,
|
|
208
|
+
unauthorized,
|
|
209
|
+
} from "hamur/app"
|
|
210
|
+
export { defineLazyHydrationComponent } from "./lazy-hydration.ts"
|
|
211
|
+
export { Island } from "./island.ts"
|
|
212
|
+
export type { IslandProps } from "./island.ts"
|
|
213
|
+
export { ServerIsland } from "./server-island.ts"
|
|
214
|
+
export type { ServerIslandProps } from "./server-island.ts"
|
|
215
|
+
export { MarkdownRenderer } from "./markdown.ts"
|
|
216
|
+
export type { MarkdownRendererProps } from "./markdown.ts"
|
|
217
|
+
import { matchesOf, routeDataOf } from "hamur/adapter"
|
|
218
|
+
import { equalSearch, isOnline, pollInterval, resolveRelative, startPoll, subscribeOnline } from "hamur/adapter"
|
|
219
|
+
import type { SetSearch } from "hamur/adapter"
|
|
220
|
+
import { APP_UPDATE_OFF, createAppUpdate } from "hamur/adapter"
|
|
221
|
+
import type { AppUpdateActions, AppUpdateState } from "hamur/adapter"
|
|
222
|
+
import type { MatchedRoute, RouteDataName, RouteDataOf, RouteError, RouteFor, RouteName } from "hamur/adapter"
|
|
223
|
+
export type { MatchedRoute, RouteDataName, RouteDataOf } from "hamur/adapter"
|
|
224
|
+
export type { NavigateToOptions, PickFrom } from "hamur/app"
|
|
225
|
+
export { default as Link } from "./components/Link.vue"
|
|
226
|
+
import LinkComponent from "./components/Link.vue"
|
|
227
|
+
export { default as Form } from "./components/Form.vue"
|
|
228
|
+
export { default as Outlet } from "./components/Outlet.vue"
|
|
229
|
+
export { default as ClientFallback } from "./components/ClientFallback.vue"
|
|
230
|
+
export { default as ClientOnly } from "./components/ClientOnly.vue"
|
|
231
|
+
export { default as DevOnly } from "./components/DevOnly.vue"
|
|
232
|
+
export { default as Await } from "./components/Await.vue"
|
|
233
|
+
export { default as Navigate } from "./components/Navigate.vue"
|
|
234
|
+
export { default as ErrorBoundary } from "./components/ErrorBoundary.vue"
|
|
235
|
+
export { default as DefaultErrorPage } from "./components/DefaultErrorPage.vue"
|
|
236
|
+
export type { Blocker, BlockerArgs, SnapshotOptions, UseBlockerOptions } from "hamur/adapter"
|
|
237
|
+
export type {
|
|
238
|
+
AfterNavigateHook,
|
|
239
|
+
AsyncDataHandler,
|
|
240
|
+
BeforeNavigateHook,
|
|
241
|
+
ErrorBoundaryFallbackProps,
|
|
242
|
+
GetCachedData,
|
|
243
|
+
GetCachedDataCause,
|
|
244
|
+
NavigateHook,
|
|
245
|
+
NavigateOptions,
|
|
246
|
+
Navigation,
|
|
247
|
+
NavigationState,
|
|
248
|
+
NavigationType,
|
|
249
|
+
RouteValue,
|
|
250
|
+
RouterApi,
|
|
251
|
+
} from "hamur/adapter"
|
|
252
|
+
export type { LinkDefaults, LinkSlot, UseLinkOptions } from "hamur/adapter"
|
|
253
|
+
|
|
254
|
+
export function useDeferred<T>(promise: T): Promise<Awaited<T>> {
|
|
255
|
+
return Promise.resolve(promise) as Promise<Awaited<T>>
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function useRoute<N extends RouteName>(name: N): RouteFor<N>
|
|
259
|
+
export function useRoute<N extends RouteName = never>(): RouteFor<N>
|
|
260
|
+
export function useRoute(): RouteValue
|
|
261
|
+
export function useRoute(name?: string): RouteValue {
|
|
262
|
+
const route = inject(RouteKey, null)
|
|
263
|
+
if (!route) throw new Error("useRoute() must be called inside a Hamur app")
|
|
264
|
+
return route
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function useResolvedPath(
|
|
268
|
+
to: MaybeRefOrGetter<string>,
|
|
269
|
+
{ relative }: { relative?: "route" } = {},
|
|
270
|
+
): ComputedRef<string> {
|
|
271
|
+
const route = useRoute()
|
|
272
|
+
return computed(() => resolveRelative(toValue(to), route, relative))
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export function useOutletContext<T = unknown>(): ComputedRef<T> {
|
|
276
|
+
const value = inject(OutletValueKey, null)
|
|
277
|
+
return computed(() => value?.() as T)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function useLayoutSegments(): ComputedRef<string[]> {
|
|
281
|
+
const route = inject(RouteKey, null)
|
|
282
|
+
const entry = inject(EntryKey, null)
|
|
283
|
+
if (!route || !entry) throw new Error("useLayoutSegments() must be called inside a Hamur app")
|
|
284
|
+
return computed(() => layoutSegments(route, entry()))
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export function useLayoutSegment(): ComputedRef<string | null> {
|
|
288
|
+
const segments = useLayoutSegments()
|
|
289
|
+
return computed(() => segments.value[0] ?? null)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export function useLayout(): ComputedRef<{ name: string | false; props: Record<string, unknown> }> {
|
|
293
|
+
const layout = inject(LayoutKey, null)
|
|
294
|
+
if (!layout) throw new Error("useLayout() must be called inside a Hamur app")
|
|
295
|
+
return layout
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export function useRouter(): RouterApi {
|
|
299
|
+
const router = inject(RouterKey, null)
|
|
300
|
+
if (!router) throw new Error("useRouter() must be called inside a Hamur app")
|
|
301
|
+
return router
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function useData<T = unknown>(...unknownRoute: UseDataArgs<T>): ComputedRef<RouteLoaderData<T>> {
|
|
305
|
+
const data = inject(DataKey, null)
|
|
306
|
+
const key = inject(EntryKey, null)
|
|
307
|
+
if (!data || !key) throw new Error("useData() must be called inside a Hamur app")
|
|
308
|
+
return computed(() => (data.value[key()] ?? null) as RouteLoaderData<T>)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export function useRouteData<N extends RouteDataName>(name: N): ComputedRef<RouteDataOf<N>> {
|
|
312
|
+
const route = inject(RouteKey, null)
|
|
313
|
+
const data = inject(DataKey, null)
|
|
314
|
+
if (!route || !data) throw new Error("useRouteData() must be called inside a Hamur app")
|
|
315
|
+
return computed(() => routeDataOf(route, data.value, name) as RouteDataOf<N>)
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export function useMatches(): ComputedRef<MatchedRoute[]> {
|
|
319
|
+
const route = inject(RouteKey, null)
|
|
320
|
+
const data = inject(DataKey, null)
|
|
321
|
+
if (!route || !data) throw new Error("useMatches() must be called inside a Hamur app")
|
|
322
|
+
return computed(() => matchesOf(route, data.value))
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export function useApp(): AppContext {
|
|
326
|
+
const app = inject(AppKey, null)
|
|
327
|
+
if (!app) throw new Error("useApp() must be called inside a Hamur app")
|
|
328
|
+
return app
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export function useRuntimeHook<K extends keyof AppHooks>(name: K, fn: AppHooks[K]): void {
|
|
332
|
+
onScopeDispose(useApp().hooks.hook(name, fn))
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export function useReportWebVitals(fn: (metric: WebVitalMetric) => void | Promise<void>): void {
|
|
336
|
+
onScopeDispose(reportWebVitals(useApp(), fn))
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export function onAppReady(fn: () => void | Promise<void>): void {
|
|
340
|
+
whenAppReady(useApp(), fn)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export function onPrehydrate(fn: (el: Element) => void): string | undefined {
|
|
344
|
+
return prehydrate(useApp(), fn)
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function useRequestEvent(): HamurEvent | undefined {
|
|
348
|
+
return requestEventOf(useApp())
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** 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. */
|
|
352
|
+
export function usePreviewMode(): PreviewMode {
|
|
353
|
+
return previewModeOf(useApp())
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export function useRequestHeaders(names?: readonly string[]): Record<string, string> {
|
|
357
|
+
return requestHeadersOf(useApp(), names)
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export function useRequestHeader(name: string): string | undefined {
|
|
361
|
+
return requestHeaderOf(useApp(), name)
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export function useRequestURL(): URL {
|
|
365
|
+
return requestURLOf(useApp())
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export function useRequestFetch(): $Fetch {
|
|
369
|
+
return requestFetchOf(useApp())
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
export function setResponseStatus(status: number, statusText?: string): void {
|
|
373
|
+
setResponseStatusOf(useApp(), status, statusText)
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export function useResponseHeader(name: string): Ref<string | undefined> {
|
|
377
|
+
const header = responseHeaderOf(useApp(), name)
|
|
378
|
+
return customRef<string | undefined>((track) => ({
|
|
379
|
+
get() {
|
|
380
|
+
track()
|
|
381
|
+
return header.get()
|
|
382
|
+
},
|
|
383
|
+
set: header.set,
|
|
384
|
+
}))
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export const HttpStatusCode: FunctionalComponent<{ code: number; text?: string }> = (props) => {
|
|
388
|
+
setResponseStatus(props.code, props.text)
|
|
389
|
+
return null
|
|
390
|
+
}
|
|
391
|
+
HttpStatusCode.props = ["code", "text"]
|
|
392
|
+
|
|
393
|
+
export const HttpHeader: FunctionalComponent<{ name: string; value: string }> = (props) => {
|
|
394
|
+
responseHeaderOf(useApp(), props.name).set(props.value)
|
|
395
|
+
return null
|
|
396
|
+
}
|
|
397
|
+
HttpHeader.props = ["name", "value"]
|
|
398
|
+
|
|
399
|
+
export const Time = defineComponent(
|
|
400
|
+
(props: TimeInput) => {
|
|
401
|
+
const app = useApp()
|
|
402
|
+
const route = useRoute()
|
|
403
|
+
const now = shallowRef<number | undefined>()
|
|
404
|
+
const view = computed(() => timeView(app, route.path, props, now.value))
|
|
405
|
+
let stop: (() => void) | undefined
|
|
406
|
+
onMounted(() =>
|
|
407
|
+
watch(
|
|
408
|
+
() => view.value.interval,
|
|
409
|
+
(interval) => {
|
|
410
|
+
stop?.()
|
|
411
|
+
stop = interval === undefined ? undefined : watchTime(interval, (next) => (now.value = next))
|
|
412
|
+
},
|
|
413
|
+
{ immediate: true },
|
|
414
|
+
),
|
|
415
|
+
)
|
|
416
|
+
onUnmounted(() => stop?.())
|
|
417
|
+
return () =>
|
|
418
|
+
h(
|
|
419
|
+
"time",
|
|
420
|
+
{ datetime: view.value.iso, "data-locale": view.value.locale, "data-time-zone": view.value.timeZone },
|
|
421
|
+
view.value.text,
|
|
422
|
+
)
|
|
423
|
+
},
|
|
424
|
+
{
|
|
425
|
+
name: "Time",
|
|
426
|
+
props: [...TIME_PROPS],
|
|
427
|
+
},
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
export type { LoadingIndicatorProps } from "hamur/adapter"
|
|
431
|
+
|
|
432
|
+
export function useLoadingIndicator(options?: LoadingIndicatorOptions): {
|
|
433
|
+
progress: Readonly<Ref<number>>
|
|
434
|
+
isLoading: Readonly<Ref<boolean>>
|
|
435
|
+
error: Readonly<Ref<boolean>>
|
|
436
|
+
} & LoadingIndicatorActions {
|
|
437
|
+
const store = createLoadingIndicator(useApp(), options)
|
|
438
|
+
const navigation = useNavigation()
|
|
439
|
+
const state = shallowRef(store.get())
|
|
440
|
+
whileMounted(() => {
|
|
441
|
+
state.value = store.get()
|
|
442
|
+
const stopState = store.subscribe(() => (state.value = store.get()))
|
|
443
|
+
const stopFollow = store.follow({
|
|
444
|
+
get: () => navigation.value,
|
|
445
|
+
subscribe: (listener) => watch(navigation, listener, { flush: "sync" }),
|
|
446
|
+
})
|
|
447
|
+
return () => {
|
|
448
|
+
stopState()
|
|
449
|
+
stopFollow()
|
|
450
|
+
}
|
|
451
|
+
})
|
|
452
|
+
return {
|
|
453
|
+
progress: computed(() => state.value.progress),
|
|
454
|
+
isLoading: computed(() => state.value.isLoading),
|
|
455
|
+
error: computed(() => state.value.error),
|
|
456
|
+
start: store.start,
|
|
457
|
+
finish: store.finish,
|
|
458
|
+
set: store.set,
|
|
459
|
+
clear: store.clear,
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
export function useAppUpdate(): { [K in keyof AppUpdateState]: Readonly<Ref<AppUpdateState[K]>> } & AppUpdateActions {
|
|
464
|
+
const store = createAppUpdate(useApp())
|
|
465
|
+
const state = shallowRef<AppUpdateState>(APP_UPDATE_OFF)
|
|
466
|
+
whileMounted(() => {
|
|
467
|
+
state.value = store.get()
|
|
468
|
+
return store.subscribe(() => (state.value = store.get()))
|
|
469
|
+
})
|
|
470
|
+
return {
|
|
471
|
+
available: computed(() => state.value.available),
|
|
472
|
+
buildId: computed(() => state.value.buildId),
|
|
473
|
+
time: computed(() => state.value.time),
|
|
474
|
+
check: store.check,
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
export const LoadingIndicator = defineComponent(
|
|
479
|
+
(props: LoadingIndicatorProps) => {
|
|
480
|
+
const { progress, isLoading, error } = useLoadingIndicator(loadingIndicatorOptions(props))
|
|
481
|
+
const element = shallowRef<HTMLElement | null>(null)
|
|
482
|
+
onMounted(() =>
|
|
483
|
+
watch(
|
|
484
|
+
() => [progress.value, isLoading.value, error.value, props.color, props.errorColor, props.height],
|
|
485
|
+
() =>
|
|
486
|
+
element.value &&
|
|
487
|
+
paintLoadingIndicator(
|
|
488
|
+
element.value,
|
|
489
|
+
{ progress: progress.value, isLoading: isLoading.value, error: error.value },
|
|
490
|
+
{ color: props.color, errorColor: props.errorColor, height: props.height },
|
|
491
|
+
),
|
|
492
|
+
{ immediate: true, flush: "post" },
|
|
493
|
+
),
|
|
494
|
+
)
|
|
495
|
+
return () => h("div", { ref: element, "data-hamur-loading-indicator": "", "aria-hidden": "true" })
|
|
496
|
+
},
|
|
497
|
+
{
|
|
498
|
+
name: "LoadingIndicator",
|
|
499
|
+
props: [...LOADING_INDICATOR_PROPS],
|
|
500
|
+
},
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
export function useRouteAnnouncer(): {
|
|
504
|
+
message: Readonly<Ref<string>>
|
|
505
|
+
politeness: Readonly<Ref<RouteAnnouncerPoliteness>>
|
|
506
|
+
} & RouteAnnouncerActions {
|
|
507
|
+
const store = createRouteAnnouncer(useApp())
|
|
508
|
+
const state = shallowRef(store.get())
|
|
509
|
+
whileMounted(() => {
|
|
510
|
+
state.value = store.get()
|
|
511
|
+
return store.subscribe(() => (state.value = store.get()))
|
|
512
|
+
})
|
|
513
|
+
return {
|
|
514
|
+
message: computed(() => state.value.message),
|
|
515
|
+
politeness: computed(() => state.value.politeness),
|
|
516
|
+
set: store.set,
|
|
517
|
+
polite: store.polite,
|
|
518
|
+
assertive: store.assertive,
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export const RouteAnnouncer = defineComponent(
|
|
523
|
+
(props: { politeness?: RouteAnnouncerPoliteness }, { attrs }) => {
|
|
524
|
+
const store = createRouteAnnouncer(useApp())
|
|
525
|
+
const { message, politeness } = useRouteAnnouncer()
|
|
526
|
+
const element = shallowRef<HTMLElement | null>(null)
|
|
527
|
+
const key = {}
|
|
528
|
+
const tick = shallowRef(0)
|
|
529
|
+
const owner = computed(() => (tick.value, store.claim(key, () => tick.value++)))
|
|
530
|
+
let unmount: (() => void) | undefined
|
|
531
|
+
let stop: (() => void) | undefined
|
|
532
|
+
onMounted(() => {
|
|
533
|
+
stop = watch(
|
|
534
|
+
owner,
|
|
535
|
+
(owns) => {
|
|
536
|
+
unmount?.()
|
|
537
|
+
unmount = undefined
|
|
538
|
+
if (!owns) return
|
|
539
|
+
unmount = store.mount()
|
|
540
|
+
if (!attrs.class && !attrs.style && element.value) hideAnnouncer(element.value)
|
|
541
|
+
},
|
|
542
|
+
{ immediate: true, flush: "post" },
|
|
543
|
+
)
|
|
544
|
+
})
|
|
545
|
+
onUnmounted(() => {
|
|
546
|
+
stop?.()
|
|
547
|
+
unmount?.()
|
|
548
|
+
store.release(key)
|
|
549
|
+
})
|
|
550
|
+
return () => {
|
|
551
|
+
if (!owner.value) return h("div", { "aria-live": "off", "aria-atomic": "true" })
|
|
552
|
+
const live = props.politeness ?? politeness.value
|
|
553
|
+
return h(
|
|
554
|
+
"div",
|
|
555
|
+
{ ref: element, id: ROUTE_ANNOUNCER_ID, "aria-live": live, "aria-atomic": "true", role: announcerRole(live) },
|
|
556
|
+
message.value,
|
|
557
|
+
)
|
|
558
|
+
}
|
|
559
|
+
},
|
|
560
|
+
{
|
|
561
|
+
name: "RouteAnnouncer",
|
|
562
|
+
props: ["politeness"],
|
|
563
|
+
},
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
export function useAnnouncer({ politeness = "polite" }: { politeness?: AnnouncerPoliteness } = {}): {
|
|
567
|
+
message: Readonly<Ref<string>>
|
|
568
|
+
politeness: Readonly<Ref<AnnouncerPoliteness>>
|
|
569
|
+
} & AnnouncerActions {
|
|
570
|
+
const store = createAnnouncer(useApp())
|
|
571
|
+
const state = shallowRef(store.get())
|
|
572
|
+
whileMounted(() => {
|
|
573
|
+
state.value = store.get()
|
|
574
|
+
return store.subscribe(() => (state.value = store.get()))
|
|
575
|
+
})
|
|
576
|
+
return {
|
|
577
|
+
message: computed(() => state.value.message),
|
|
578
|
+
politeness: computed(() => state.value.politeness),
|
|
579
|
+
...announcerActions(store, politeness),
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
export const Announcer = defineComponent(
|
|
584
|
+
() => {
|
|
585
|
+
const store = createAnnouncer(useApp())
|
|
586
|
+
const state = shallowRef(store.get())
|
|
587
|
+
const polite = shallowRef<HTMLElement | null>(null)
|
|
588
|
+
const assertive = shallowRef<HTMLElement | null>(null)
|
|
589
|
+
onMounted(() => {
|
|
590
|
+
for (const element of [polite.value, assertive.value]) if (element) hideAnnouncer(element)
|
|
591
|
+
})
|
|
592
|
+
whileMounted(() => {
|
|
593
|
+
state.value = store.get()
|
|
594
|
+
const stop = store.subscribe(() => (state.value = store.get()))
|
|
595
|
+
const unmount = store.mount()
|
|
596
|
+
return () => {
|
|
597
|
+
stop()
|
|
598
|
+
unmount()
|
|
599
|
+
}
|
|
600
|
+
})
|
|
601
|
+
return () => [
|
|
602
|
+
h(
|
|
603
|
+
"div",
|
|
604
|
+
{ ref: polite, id: ANNOUNCER_POLITE_ID, "aria-live": "polite", "aria-atomic": "true", role: "status" },
|
|
605
|
+
state.value.regions.polite,
|
|
606
|
+
),
|
|
607
|
+
h(
|
|
608
|
+
"div",
|
|
609
|
+
{ ref: assertive, id: ANNOUNCER_ASSERTIVE_ID, "aria-live": "assertive", "aria-atomic": "true", role: "alert" },
|
|
610
|
+
state.value.regions.assertive,
|
|
611
|
+
),
|
|
612
|
+
]
|
|
613
|
+
},
|
|
614
|
+
{ name: "Announcer" },
|
|
615
|
+
)
|
|
616
|
+
|
|
617
|
+
export function useAsyncDataEntry<T = unknown>(key: string): { data: Ref<T | undefined> }
|
|
618
|
+
export function useAsyncDataEntry<I, O>(fn: Handler<I, O>, input?: I): { data: Ref<O | undefined> }
|
|
619
|
+
export function useAsyncDataEntry<T = unknown>(
|
|
620
|
+
target: string | HandlerReference,
|
|
621
|
+
input?: unknown,
|
|
622
|
+
): { data: Ref<T | undefined> } {
|
|
623
|
+
const store = useApp().asyncData
|
|
624
|
+
const key =
|
|
625
|
+
typeof target === "string" ? target : asyncDataKey(target, deepToValue(input as MaybeRefOrGetter<unknown>))
|
|
626
|
+
const data = customRef<T | undefined>((track, trigger) => {
|
|
627
|
+
if (getCurrentScope()) onScopeDispose(store.subscribe(key, trigger))
|
|
628
|
+
return {
|
|
629
|
+
get() {
|
|
630
|
+
track()
|
|
631
|
+
return store.get<T>(key)?.data
|
|
632
|
+
},
|
|
633
|
+
set(next) {
|
|
634
|
+
store.setData(key, next)
|
|
635
|
+
},
|
|
636
|
+
}
|
|
637
|
+
})
|
|
638
|
+
return { data }
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
export const useNuxtData = useAsyncDataEntry
|
|
642
|
+
|
|
643
|
+
export function clearState(keys?: Parameters<typeof clearStateOf>[1], options?: { reset?: boolean }): void {
|
|
644
|
+
clearStateOf(useApp(), keys, options)
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
export function callOnce(
|
|
648
|
+
key: string,
|
|
649
|
+
fn: () => unknown | Promise<unknown>,
|
|
650
|
+
options?: { mode?: "render" | "navigation" },
|
|
651
|
+
): Promise<void> {
|
|
652
|
+
return callOnceOf(useApp(), key, fn, options)
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
export function useRuntimeConfig(): ClientRuntimeConfig {
|
|
656
|
+
return runtimeConfigOf(useApp())
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
export function useSiteConfig(): SiteConfig {
|
|
660
|
+
return siteConfigOf(useApp())
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
export function useNavigation(): Readonly<ShallowRef<NavigationState>> {
|
|
664
|
+
const navigation = inject(NavigationKey, null)
|
|
665
|
+
if (!navigation) throw new Error("useNavigation() must be called inside a Hamur app")
|
|
666
|
+
return navigation
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/** A `Link` with `defaults` over `app.link`; a prop of the element wins. */
|
|
670
|
+
export function defineLink(defaults: LinkDefaults): typeof LinkComponent {
|
|
671
|
+
return defineComponent({
|
|
672
|
+
name: "Link",
|
|
673
|
+
inheritAttrs: false,
|
|
674
|
+
setup:
|
|
675
|
+
(_, { attrs, slots }) =>
|
|
676
|
+
() =>
|
|
677
|
+
h(LinkComponent as never, { ...attrs, defaults }, slots),
|
|
678
|
+
}) as never
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/** The `LinkSlot` of a link to `to`, for an element that renders its own `<a>`; `app.link` sets its defaults. */
|
|
682
|
+
export function useLink<T extends string = string>(
|
|
683
|
+
to: MaybeRefOrGetter<CheckedTarget<T> | RouteLocation>,
|
|
684
|
+
options?: MaybeRefOrGetter<UseLinkOptions>,
|
|
685
|
+
): ComputedRef<LinkSlot> {
|
|
686
|
+
const baseURL = inject(BaseURLKey, "/")
|
|
687
|
+
const resolve = inject(HrefKey, detachedHref)
|
|
688
|
+
const route = inject(RouteKey, null)
|
|
689
|
+
const app = inject(AppKey, null)
|
|
690
|
+
const router = inject(RouterKey, null)
|
|
691
|
+
const navigation = inject(NavigationKey, null)
|
|
692
|
+
return computed(() => {
|
|
693
|
+
const given = toValue(options) ?? {}
|
|
694
|
+
const defaults = linkDefaultsOf(app)
|
|
695
|
+
const base = toValue(to) as string | RouteLocation
|
|
696
|
+
const searched = route ? searchTarget(relativeTarget(base, route, given.relative), route, given.query) : base
|
|
697
|
+
const { to: target } = resolveLinkTarget(app, searched, given, resolve, given.external)
|
|
698
|
+
const href = resolve(target)
|
|
699
|
+
const state = route
|
|
700
|
+
? linkState(typeof target === "string" ? target : withoutBase(href, baseURL), route)
|
|
701
|
+
: { active: false, exact: false }
|
|
702
|
+
return createLinkSlot({
|
|
703
|
+
href,
|
|
704
|
+
to: target,
|
|
705
|
+
attrs: linkAttributes({
|
|
706
|
+
href,
|
|
707
|
+
external: given.external,
|
|
708
|
+
...linkPrefetchProps({}, defaults),
|
|
709
|
+
replace: given.replace,
|
|
710
|
+
viewTransition: given.viewTransition,
|
|
711
|
+
pendingClass: defaults.pendingClass,
|
|
712
|
+
trim: !!given.query,
|
|
713
|
+
ariaCurrent: state.exact ? "page" : undefined,
|
|
714
|
+
prefetchedClass: defaults.prefetchedClass,
|
|
715
|
+
scroll: given.scroll,
|
|
716
|
+
prefetchDelay: defaults.prefetchDelay,
|
|
717
|
+
externalRelAttribute: defaults.externalRelAttribute,
|
|
718
|
+
}),
|
|
719
|
+
active: state.active,
|
|
720
|
+
exact: state.exact,
|
|
721
|
+
pending: navigation !== null && linkPending(href, navigation.value, baseURL),
|
|
722
|
+
external: given.external,
|
|
723
|
+
options: {
|
|
724
|
+
replace: given.replace,
|
|
725
|
+
state: given.state,
|
|
726
|
+
viewTransition: given.viewTransition,
|
|
727
|
+
scroll: given.scroll === false ? false : undefined,
|
|
728
|
+
},
|
|
729
|
+
router,
|
|
730
|
+
})
|
|
731
|
+
})
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/** Inside a `Link`'s slot, whether a navigation to that link is in flight; `pending` is false anywhere else. */
|
|
735
|
+
export function useLinkStatus(): { pending: ComputedRef<boolean> } {
|
|
736
|
+
const href = inject(LinkHrefKey, null)
|
|
737
|
+
const navigation = inject(NavigationKey, null)
|
|
738
|
+
const baseURL = inject(BaseURLKey, "/")
|
|
739
|
+
return {
|
|
740
|
+
pending: computed(() => href !== null && navigation !== null && linkPending(href.value, navigation.value, baseURL)),
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function navigationHookWhileMounted(kind: NavigationHookKind, fn: (navigation: Navigation) => unknown): void {
|
|
745
|
+
let off: (() => void) | undefined
|
|
746
|
+
onMounted(() => (off = navigationHook(kind, fn as never)))
|
|
747
|
+
onUnmounted(() => off?.())
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
export const onBeforeNavigate = (fn: BeforeNavigateHook): void => navigationHookWhileMounted("before", fn)
|
|
751
|
+
export const onNavigate = (fn: NavigateHook): void => navigationHookWhileMounted("navigate", fn)
|
|
752
|
+
export const onAfterNavigate = (fn: AfterNavigateHook): void => navigationHookWhileMounted("after", fn)
|
|
753
|
+
|
|
754
|
+
// `ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE` of @vue/runtime-core 3.5.44: set on the vnode `KeepAlive` caches; `onActivated` never runs for one it leaves out.
|
|
755
|
+
const SHOULD_KEEP_ALIVE = 256
|
|
756
|
+
|
|
757
|
+
function keptByKeepAlive(): boolean {
|
|
758
|
+
for (let instance = getCurrentInstance(); instance?.parent; instance = instance.parent) {
|
|
759
|
+
if ((instance.parent.vnode.type as { __isKeepAlive?: boolean }).__isKeepAlive)
|
|
760
|
+
return (instance.vnode.shapeFlag & SHOULD_KEEP_ALIVE) !== 0
|
|
761
|
+
}
|
|
762
|
+
return false
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/** Runs `fn` after the component mounts and each time its kept page is shown again (`onActivated`). */
|
|
766
|
+
export function onPageActivated(fn: () => void): void {
|
|
767
|
+
if (keptByKeepAlive()) onActivated(fn)
|
|
768
|
+
else onMounted(fn)
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** Runs `fn` each time its kept page is hidden and when the component unmounts (`onDeactivated`). */
|
|
772
|
+
export function onPageDeactivated(fn: () => void): void {
|
|
773
|
+
if (keptByKeepAlive()) onDeactivated(fn)
|
|
774
|
+
else onUnmounted(fn)
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
function whileMounted(register: () => () => void): void {
|
|
778
|
+
let off: (() => void) | undefined
|
|
779
|
+
onMounted(() => (off = register()))
|
|
780
|
+
onUnmounted(() => off?.())
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function routeGuardWhileMounted(kind: RouteGuardKind, fn: NavigationGuard): void {
|
|
784
|
+
const entry = inject(EntryKey, null)
|
|
785
|
+
whileMounted(() => routeGuard(kind, entry?.(), fn))
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
export const onBeforeRouteLeave = (fn: NavigationGuard): void => routeGuardWhileMounted("leave", fn)
|
|
789
|
+
export const onBeforeRouteUpdate = (fn: NavigationGuard): void => routeGuardWhileMounted("update", fn)
|
|
790
|
+
|
|
791
|
+
export function usePreventNavigate(fn: NavigationBlocker): void {
|
|
792
|
+
whileMounted(() => navigationBlocker(fn))
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
export function useBlocker(options: ShouldBlock | UseBlockerOptions): Readonly<ShallowRef<Blocker>> {
|
|
796
|
+
const store = createBlocker(options)
|
|
797
|
+
const value = shallowRef(store.get())
|
|
798
|
+
whileMounted(() => {
|
|
799
|
+
const unsubscribe = store.subscribe(() => void (value.value = store.get()))
|
|
800
|
+
const stop = store.start()
|
|
801
|
+
const stopSync = watchEffect(() => store.sync())
|
|
802
|
+
return () => (stopSync(), stop(), unsubscribe())
|
|
803
|
+
})
|
|
804
|
+
return value
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
export function useSnapshot<T>(key: string, options: SnapshotOptions<T>): void {
|
|
808
|
+
whileMounted(() => registerSnapshot(key, options))
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
export function useSearch(): { value: ComputedRef<RouteValue["search"]>; set: SetSearch }
|
|
812
|
+
export function useSearch<S>(select: (search: RouteValue["search"]) => S): { value: ComputedRef<S>; set: SetSearch }
|
|
813
|
+
export function useSearch<S>(select?: (search: RouteValue["search"]) => S): {
|
|
814
|
+
value: ComputedRef<S | RouteValue["search"]>
|
|
815
|
+
set: SetSearch
|
|
816
|
+
} {
|
|
817
|
+
const route = inject(RouteKey, null)
|
|
818
|
+
const router = inject(RouterKey, null)
|
|
819
|
+
if (!route || !router) throw new Error("useSearch() must be called inside a Hamur app")
|
|
820
|
+
const value = computed<S | RouteValue["search"]>((previous) => {
|
|
821
|
+
const next = select ? select(route.search) : route.search
|
|
822
|
+
return previous !== undefined && equalSearch(previous, next) ? previous : next
|
|
823
|
+
})
|
|
824
|
+
const set: SetSearch = (change, { replace = true } = {}) => {
|
|
825
|
+
const update = { query: (prev: RouteValue["search"]) => (typeof change === "function" ? change(prev) : change) }
|
|
826
|
+
return replace ? router.replace(update) : router.navigate(update)
|
|
827
|
+
}
|
|
828
|
+
return { value, set }
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
export function usePoll(ms: number, options: { keys?: string[] } = {}): void {
|
|
832
|
+
pollInterval(ms)
|
|
833
|
+
const router = useRouter()
|
|
834
|
+
let stop: (() => void) | undefined
|
|
835
|
+
onMounted(() => (stop = startPoll(ms, () => (options.keys ? router.refresh(options.keys) : router.refresh()))))
|
|
836
|
+
onUnmounted(() => stop?.())
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
export function useOnline(): Readonly<Ref<boolean>> {
|
|
840
|
+
const online = shallowRef(true)
|
|
841
|
+
let off: (() => void) | undefined
|
|
842
|
+
onMounted(() => {
|
|
843
|
+
online.value = isOnline()
|
|
844
|
+
off = subscribeOnline((value) => (online.value = value))
|
|
845
|
+
})
|
|
846
|
+
onUnmounted(() => off?.())
|
|
847
|
+
return online
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
export function useSyncedState<T>(key: string, initial: T, options: SyncedStateOptions = {}): Ref<T> {
|
|
851
|
+
const state = syncedState(key, initial, options)
|
|
852
|
+
const value = shallowRef(initial) as Ref<T>
|
|
853
|
+
let off: (() => void) | undefined
|
|
854
|
+
onMounted(() => {
|
|
855
|
+
value.value = state.get()
|
|
856
|
+
off = state.subscribe((next) => (value.value = next))
|
|
857
|
+
})
|
|
858
|
+
onUnmounted(() => off?.())
|
|
859
|
+
return computed({ get: () => value.value, set: (next: T) => state.set(next) })
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
export { useId }
|
|
863
|
+
|
|
864
|
+
export function useHydrated(): Readonly<Ref<boolean>> {
|
|
865
|
+
const app = useApp()
|
|
866
|
+
const hydrated = shallowRef(typeof document !== "undefined" && !app.asyncData.hydrating)
|
|
867
|
+
let off: (() => void) | undefined
|
|
868
|
+
onMounted(() => {
|
|
869
|
+
hydrated.value = !app.asyncData.hydrating
|
|
870
|
+
off = app.hooks.hook("app:mounted", () => void (hydrated.value = true))
|
|
871
|
+
})
|
|
872
|
+
onUnmounted(() => off?.())
|
|
873
|
+
return hydrated
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
export function useFormStatus(): Readonly<FormStatus> {
|
|
877
|
+
const store = inject(FormStatusKey, null)
|
|
878
|
+
const status = shallowReactive<FormStatus>({ ...(store ? store.get() : IDLE_FORM_STATUS) })
|
|
879
|
+
if (store) onScopeDispose(store.subscribe(() => Object.assign(status, store.get())))
|
|
880
|
+
return status
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
export function useForm<I, O>(fn: Handler<I, O>): HandlerForm<I, O> {
|
|
884
|
+
const submitted = inject(SubmittedKey, null)
|
|
885
|
+
const version = shallowRef(0)
|
|
886
|
+
const form = createForm(fn, {
|
|
887
|
+
app: inject(AppKey, null),
|
|
888
|
+
submitted: () => submitted?.value ?? {},
|
|
889
|
+
track: () => void version.value,
|
|
890
|
+
})
|
|
891
|
+
onScopeDispose(form.subscribe(() => (version.value = form.version())))
|
|
892
|
+
return form
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
export interface UseActionResult<I, O> {
|
|
896
|
+
readonly run: ActionRunner<I, O>["run"]
|
|
897
|
+
readonly state: O | undefined
|
|
898
|
+
readonly pending: boolean
|
|
899
|
+
readonly error: HamurError | undefined
|
|
900
|
+
readonly failure: ActionFailure | undefined
|
|
901
|
+
reset(): void
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
export function useAction<I, O>(
|
|
905
|
+
fn: Handler<I, O>,
|
|
906
|
+
options: ActionOptions<O> & { instance?: string | number } = {},
|
|
907
|
+
): UseActionResult<I, O> {
|
|
908
|
+
const router = useRouter()
|
|
909
|
+
const { handlerState } = inject(SubmittedKey, null)?.value ?? {}
|
|
910
|
+
const { instance } = options
|
|
911
|
+
const app = inject(AppKey, null)
|
|
912
|
+
const runner = createActionRunner(fn, {
|
|
913
|
+
app,
|
|
914
|
+
instance,
|
|
915
|
+
options: () => options,
|
|
916
|
+
refresh: () => router.refresh(),
|
|
917
|
+
restored: restoredResult<O>(handlerState, fn.id, instance),
|
|
918
|
+
})
|
|
919
|
+
const action = shallowReactive({ ...runner.get(), run: runner.run, reset: runner.reset })
|
|
920
|
+
onScopeDispose(runner.subscribe(() => Object.assign(action, runner.get())))
|
|
921
|
+
const below = inject(FormStatusKey, null)
|
|
922
|
+
if (below) onScopeDispose(below.owner.link(fn.id, runner, instance))
|
|
923
|
+
else if (app) onScopeDispose(linkActionRunner(app, fn.id, runner, instance))
|
|
924
|
+
return action as UseActionResult<I, O>
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
export function useOptimistic<T, A = PendingRun>(
|
|
928
|
+
value: MaybeRefOrGetter<T>,
|
|
929
|
+
reduce: (current: T, pending: A[]) => T,
|
|
930
|
+
): ComputedRef<T> {
|
|
931
|
+
const source = optimisticSource(inject(AppKey, null))
|
|
932
|
+
const pending = shallowRef(source.get())
|
|
933
|
+
onScopeDispose(source.subscribe(() => (pending.value = source.get())))
|
|
934
|
+
return computed(() =>
|
|
935
|
+
pending.value.length ? reduce(toValue(value), pending.value as unknown as A[]) : toValue(value),
|
|
936
|
+
)
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
export function useError(): ShallowRef<RouteError | undefined>
|
|
940
|
+
export function useError(): ShallowRef<ErrorPageProps | undefined> {
|
|
941
|
+
const source = inject(ErrorKey, null)
|
|
942
|
+
if (!source) throw new Error("useError() must be called inside a Hamur app")
|
|
943
|
+
const { store } = source
|
|
944
|
+
const error = shallowRef(store ? store.get() : source.initial)
|
|
945
|
+
if (store) onScopeDispose(store.subscribe(() => (error.value = store.get())))
|
|
946
|
+
return error
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
const pendingApply = new WeakSet<Head>()
|
|
950
|
+
|
|
951
|
+
function scheduleApply(head: Head) {
|
|
952
|
+
if (pendingApply.has(head)) return
|
|
953
|
+
pendingApply.add(head)
|
|
954
|
+
queueMicrotask(() => {
|
|
955
|
+
pendingApply.delete(head)
|
|
956
|
+
head.apply()
|
|
957
|
+
})
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
type MaybeRefOrGetterDeep<T> = MaybeRefOrGetter<
|
|
961
|
+
T extends (...args: never[]) => unknown
|
|
962
|
+
? T
|
|
963
|
+
: T extends readonly (infer U)[]
|
|
964
|
+
? MaybeRefOrGetterDeep<U>[]
|
|
965
|
+
: T extends object
|
|
966
|
+
? { [K in keyof T]: MaybeRefOrGetterDeep<T[K]> }
|
|
967
|
+
: T
|
|
968
|
+
>
|
|
969
|
+
|
|
970
|
+
const headValue = <T>(input: MaybeRefOrGetterDeep<T>) => deepToValue(input, true) as T
|
|
971
|
+
|
|
972
|
+
export function useHead(input: MaybeRefOrGetterDeep<HeadInput>): void {
|
|
973
|
+
const head = inject(HeadKey, null)
|
|
974
|
+
if (!head) throw new Error("useHead() must be called inside a Hamur app")
|
|
975
|
+
const entry = head.push(headValue<HeadInput>(input))
|
|
976
|
+
if (hasReactive(input)) inject(HeadPatchesKey, null)?.push(() => entry.patch(headValue<HeadInput>(input)))
|
|
977
|
+
onMounted(() => scheduleApply(head))
|
|
978
|
+
watch(
|
|
979
|
+
() => headValue<HeadInput>(input),
|
|
980
|
+
(next) => {
|
|
981
|
+
entry.patch(next)
|
|
982
|
+
scheduleApply(head)
|
|
983
|
+
},
|
|
984
|
+
{ deep: true },
|
|
985
|
+
)
|
|
986
|
+
if (getCurrentScope()) {
|
|
987
|
+
onScopeDispose(() => {
|
|
988
|
+
entry.dispose()
|
|
989
|
+
if (typeof document !== "undefined") scheduleApply(head)
|
|
990
|
+
})
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
export function useSeoMeta(input: MaybeRefOrGetterDeep<SeoMetaInput>): void {
|
|
995
|
+
useHead(() => seoMetaToHead(headValue<SeoMetaInput>(input)))
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
type ServerHeadInput = Omit<HeadInput, "title" | "titleTemplate">
|
|
999
|
+
type ServerSeoMetaInput = Omit<SeoMetaInput, "title" | "titleTemplate">
|
|
1000
|
+
|
|
1001
|
+
export function useHeadSafe(input: MaybeRefOrGetterDeep<HeadSafeInput>): void {
|
|
1002
|
+
useHead(() => sanitizeHead(headValue<HeadSafeInput>(input)))
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
type HeadProps<K extends "meta" | "link" | "script" | "style"> = NonNullable<HeadInput[K]>[number]
|
|
1006
|
+
|
|
1007
|
+
// The attributes are not reactive; a snapshot taken before each update lets the getter of useHead track them.
|
|
1008
|
+
function headAttrsComponent<P extends Record<string, any>>(
|
|
1009
|
+
name: string,
|
|
1010
|
+
toInput: (attrs: Record<string, unknown>) => HeadInput,
|
|
1011
|
+
): DefineSetupFnComponent<P> {
|
|
1012
|
+
return defineComponent(
|
|
1013
|
+
(_props: P, { attrs }) => {
|
|
1014
|
+
const snapshot = shallowRef({ ...attrs })
|
|
1015
|
+
onBeforeUpdate(() => (snapshot.value = { ...attrs }))
|
|
1016
|
+
useHead(() => toInput(snapshot.value))
|
|
1017
|
+
return () => null
|
|
1018
|
+
},
|
|
1019
|
+
{ name, inheritAttrs: false },
|
|
1020
|
+
) as unknown as DefineSetupFnComponent<P>
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
export const HeadTitle = defineComponent(
|
|
1024
|
+
(props: { title: string; template?: string }) => {
|
|
1025
|
+
useHead(() => ({ title: props.title, titleTemplate: props.template }))
|
|
1026
|
+
return () => null
|
|
1027
|
+
},
|
|
1028
|
+
{ name: "HeadTitle", props: ["title", "template"] },
|
|
1029
|
+
)
|
|
1030
|
+
export const HeadMeta = headAttrsComponent<HeadProps<"meta">>("HeadMeta", (attrs) => ({
|
|
1031
|
+
meta: [attrs as HeadProps<"meta">],
|
|
1032
|
+
}))
|
|
1033
|
+
export const HeadLink = headAttrsComponent<HeadProps<"link">>("HeadLink", (attrs) => ({
|
|
1034
|
+
link: [attrs as HeadProps<"link">],
|
|
1035
|
+
}))
|
|
1036
|
+
export const HeadScript = headAttrsComponent<HeadProps<"script">>("HeadScript", (attrs) => ({
|
|
1037
|
+
script: [attrs as HeadProps<"script">],
|
|
1038
|
+
}))
|
|
1039
|
+
export const HeadStyle = headAttrsComponent<HeadProps<"style">>("HeadStyle", (attrs) => ({
|
|
1040
|
+
style: [attrs as HeadProps<"style">],
|
|
1041
|
+
}))
|
|
1042
|
+
export const HtmlAttrs = headAttrsComponent<Record<string, string>>("HtmlAttrs", (attrs) => ({
|
|
1043
|
+
htmlAttrs: attrs as Record<string, string>,
|
|
1044
|
+
}))
|
|
1045
|
+
export const BodyAttrs = headAttrsComponent<Record<string, string>>("BodyAttrs", (attrs) => ({
|
|
1046
|
+
bodyAttrs: attrs as Record<string, string>,
|
|
1047
|
+
}))
|
|
1048
|
+
|
|
1049
|
+
export function useServerHead(input: MaybeRefOrGetterDeep<ServerHeadInput>): void {
|
|
1050
|
+
if (typeof document !== "undefined") return
|
|
1051
|
+
const head = inject(HeadKey, null)
|
|
1052
|
+
if (!head) throw new Error("useServerHead() must be called inside a Hamur app")
|
|
1053
|
+
const entry = head.push(headValue<ServerHeadInput>(input), { server: true })
|
|
1054
|
+
if (hasReactive(input)) inject(HeadPatchesKey, null)?.push(() => entry.patch(headValue<ServerHeadInput>(input)))
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
export function useServerSeoMeta(input: MaybeRefOrGetterDeep<ServerSeoMetaInput>): void {
|
|
1058
|
+
useServerHead(() => seoMetaToHead(headValue<ServerSeoMetaInput>(input)))
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
export function useState<T>(key: StateKeyOf<T>): Ref<T>
|
|
1062
|
+
export function useState<T>(key: string, init?: T | (() => T)): Ref<T>
|
|
1063
|
+
export function useState<T>(...args: unknown[]): Ref<T> {
|
|
1064
|
+
const { key, init } = stateArguments(args) as { key: string; init: T | (() => T) | undefined }
|
|
1065
|
+
const state = inject(StateKey, null)
|
|
1066
|
+
if (!state) throw new Error("useState() must be called inside a Hamur app")
|
|
1067
|
+
state.use(key, init)
|
|
1068
|
+
return customRef<T>((track, trigger) => {
|
|
1069
|
+
if (getCurrentScope()) onScopeDispose(state.subscribe(key, trigger))
|
|
1070
|
+
return {
|
|
1071
|
+
get() {
|
|
1072
|
+
track()
|
|
1073
|
+
return state.get<T>(key) as T
|
|
1074
|
+
},
|
|
1075
|
+
set(value) {
|
|
1076
|
+
state.set(key, value)
|
|
1077
|
+
},
|
|
1078
|
+
}
|
|
1079
|
+
})
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
export interface UseCookieWatchOptions {
|
|
1083
|
+
/** `true` (default): a change inside an object value writes the cookie; `"shallow"`: only `.value = …` writes; `false`: nothing writes, `.value = …` is kept in the ref only. */
|
|
1084
|
+
watch?: boolean | "shallow"
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
export function useCookie<T = string>(
|
|
1088
|
+
name: string,
|
|
1089
|
+
options: Omit<UseCookieOptions<T>, "app"> & UseCookieWatchOptions & { default: () => T },
|
|
1090
|
+
): Ref<T>
|
|
1091
|
+
export function useCookie<T = string>(
|
|
1092
|
+
name: string,
|
|
1093
|
+
options?: Omit<UseCookieOptions<T>, "app"> & UseCookieWatchOptions,
|
|
1094
|
+
): Ref<T | undefined>
|
|
1095
|
+
export function useCookie<T = string>(
|
|
1096
|
+
name: string,
|
|
1097
|
+
options: Omit<UseCookieOptions<T>, "app"> & UseCookieWatchOptions = {},
|
|
1098
|
+
): Ref<T | undefined> {
|
|
1099
|
+
const app = inject(AppKey, null)
|
|
1100
|
+
const { watch: mode = true, ...rest } = options
|
|
1101
|
+
const cookie = cookieOf<T>(name, { ...rest, ...(app ? { app } : {}) })
|
|
1102
|
+
const encode = (value: T | undefined): string | undefined => {
|
|
1103
|
+
if (value === undefined) return undefined
|
|
1104
|
+
try {
|
|
1105
|
+
return rest.encode ? rest.encode(value) : JSON.stringify(value)
|
|
1106
|
+
} catch {
|
|
1107
|
+
return undefined
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
let seen: T | undefined
|
|
1111
|
+
let baseline: string | undefined
|
|
1112
|
+
let local: { value: T | undefined } | undefined
|
|
1113
|
+
const ref = customRef<T | undefined>((track, trigger) => {
|
|
1114
|
+
if (getCurrentScope())
|
|
1115
|
+
onScopeDispose(
|
|
1116
|
+
cookie.subscribe(() => {
|
|
1117
|
+
local = undefined
|
|
1118
|
+
trigger()
|
|
1119
|
+
}),
|
|
1120
|
+
)
|
|
1121
|
+
return {
|
|
1122
|
+
get() {
|
|
1123
|
+
track()
|
|
1124
|
+
if (local) return local.value
|
|
1125
|
+
const value = cookie.get()
|
|
1126
|
+
if (value !== seen) {
|
|
1127
|
+
seen = value
|
|
1128
|
+
baseline = encode(value)
|
|
1129
|
+
}
|
|
1130
|
+
return mode === true && typeof value === "object" && value !== null ? (reactive(value) as T) : value
|
|
1131
|
+
},
|
|
1132
|
+
set(value) {
|
|
1133
|
+
if (mode === false) {
|
|
1134
|
+
local = { value }
|
|
1135
|
+
trigger()
|
|
1136
|
+
} else cookie.set(value)
|
|
1137
|
+
},
|
|
1138
|
+
}
|
|
1139
|
+
})
|
|
1140
|
+
if (mode === true && getCurrentScope())
|
|
1141
|
+
watch(
|
|
1142
|
+
ref,
|
|
1143
|
+
() => {
|
|
1144
|
+
const value = cookie.get()
|
|
1145
|
+
const now = encode(value)
|
|
1146
|
+
if (now === baseline) return
|
|
1147
|
+
baseline = now
|
|
1148
|
+
cookie.set(value)
|
|
1149
|
+
},
|
|
1150
|
+
{ deep: true },
|
|
1151
|
+
)
|
|
1152
|
+
return ref
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
export interface UseAsyncDataOptions<T = unknown, R = T, K extends keyof T & string = never, D = T> extends Omit<
|
|
1156
|
+
AsyncDataOptions<T, R, D>,
|
|
1157
|
+
"pick"
|
|
1158
|
+
> {
|
|
1159
|
+
/** Sources that re-run the handler when they change. In `useFetch`, `false` also stops `url`, `query` and `body` from re-fetching on change. */
|
|
1160
|
+
watch?: WatchSource[] | false
|
|
1161
|
+
getCachedData?: GetCachedData<T>
|
|
1162
|
+
/** Top-level keys of an object result to keep. */
|
|
1163
|
+
pick?: readonly K[]
|
|
1164
|
+
/** `true` makes `data` deeply reactive; the default `false` keeps it a shallow ref, tracked by replacement only. */
|
|
1165
|
+
deep?: boolean
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
export interface UseAsyncDataResult<T, D = undefined> {
|
|
1169
|
+
data: ComputedRef<T | D>
|
|
1170
|
+
error: ComputedRef<HamurError | undefined>
|
|
1171
|
+
status: ComputedRef<AsyncDataStatus>
|
|
1172
|
+
/** `status === "pending"`, or `idle` without data under `app.asyncData.pendingWhenIdle`. */
|
|
1173
|
+
pending: ComputedRef<boolean>
|
|
1174
|
+
refresh(): Promise<void>
|
|
1175
|
+
/** The same function as `refresh`. */
|
|
1176
|
+
execute(): Promise<void>
|
|
1177
|
+
/** Resets the entry of the current key to `idle` (`clearAsyncData`). */
|
|
1178
|
+
clear(): void
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
export interface UseFetchOptions<T = unknown, R = T, K extends keyof T & string = never, D = T>
|
|
1182
|
+
extends Omit<FetchOptions, "query" | "body">, UseAsyncDataOptions<T, R, K, D> {
|
|
1183
|
+
/** The store key, instead of the one derived from the url and the request. */
|
|
1184
|
+
key?: string
|
|
1185
|
+
query?: MaybeRefOrGetter<Record<string, MaybeRef<unknown>> | undefined>
|
|
1186
|
+
body?: MaybeRefOrGetter<unknown>
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
export function useAsyncData<I, R, T = R, K extends keyof T & string = never, D = T>(
|
|
1190
|
+
fn: Handler<I, R>,
|
|
1191
|
+
input: MaybeRefOrGetter<NoInfer<I>> | undefined,
|
|
1192
|
+
options: UseAsyncDataOptions<T, R, K, D> & { default: () => D },
|
|
1193
|
+
): UseAsyncDataResult<PickFrom<T, K>, D>
|
|
1194
|
+
export function useAsyncData<I, R, T = R, K extends keyof T & string = never>(
|
|
1195
|
+
fn: Handler<I, R>,
|
|
1196
|
+
input?: MaybeRefOrGetter<NoInfer<I>>,
|
|
1197
|
+
options?: UseAsyncDataOptions<T, R, K, undefined>,
|
|
1198
|
+
): UseAsyncDataResult<PickFrom<T, K>>
|
|
1199
|
+
export function useAsyncData<T = unknown, R = T, K extends keyof T & string = never, D = T>(
|
|
1200
|
+
key: MaybeRefOrGetter<string>,
|
|
1201
|
+
handler: AsyncDataHandler<R>,
|
|
1202
|
+
options: UseAsyncDataOptions<T, R, K, D> & { default: () => D },
|
|
1203
|
+
): UseAsyncDataResult<PickFrom<T, K>, D>
|
|
1204
|
+
export function useAsyncData<T = unknown, R = T, K extends keyof T & string = never>(
|
|
1205
|
+
key: MaybeRefOrGetter<string>,
|
|
1206
|
+
handler: AsyncDataHandler<R>,
|
|
1207
|
+
options?: UseAsyncDataOptions<T, R, K, undefined>,
|
|
1208
|
+
): UseAsyncDataResult<PickFrom<T, K>>
|
|
1209
|
+
export function useAsyncData(...args: unknown[]): UseAsyncDataResult<any, any> {
|
|
1210
|
+
const [first, second, given] = asyncDataArguments("useAsyncData", args, isRef) as [
|
|
1211
|
+
MaybeRefOrGetter<string> | HandlerReference,
|
|
1212
|
+
unknown,
|
|
1213
|
+
UseAsyncDataOptions<any, any, any, any> | undefined,
|
|
1214
|
+
]
|
|
1215
|
+
const options = given ?? {}
|
|
1216
|
+
if (!isHandlerReference(first))
|
|
1217
|
+
return keyedAsyncData(first as MaybeRefOrGetter<string>, () => second as AsyncDataHandler<unknown>, options)
|
|
1218
|
+
return handlerAsyncData(first as HandlerReference, second as MaybeRefOrGetter<unknown>, options)
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
/** `input` is read deeply inside the watch of the key, so a ref or getter in it re-keys the entry. */
|
|
1222
|
+
function handlerAsyncData(
|
|
1223
|
+
fn: HandlerReference,
|
|
1224
|
+
input: MaybeRefOrGetter<unknown>,
|
|
1225
|
+
options: UseAsyncDataOptions<any, any, any, any>,
|
|
1226
|
+
): UseAsyncDataResult<any, any> {
|
|
1227
|
+
const app = useApp()
|
|
1228
|
+
const inputs = new Map<string, unknown>()
|
|
1229
|
+
const keyOf = () => {
|
|
1230
|
+
const value = deepToValue(input)
|
|
1231
|
+
const name = asyncDataKey(fn, value)
|
|
1232
|
+
inputs.set(name, value)
|
|
1233
|
+
return name
|
|
1234
|
+
}
|
|
1235
|
+
const handlerFor = (name: string): AsyncDataHandler<unknown> => {
|
|
1236
|
+
const value = inputs.has(name) ? inputs.get(name) : deepToValue(input)
|
|
1237
|
+
return ({ signal }) =>
|
|
1238
|
+
(fn as (input: unknown, init: { signal: AbortSignal; event: AppContext["event"] }) => Promise<unknown>)(value, {
|
|
1239
|
+
signal,
|
|
1240
|
+
event: app.event,
|
|
1241
|
+
})
|
|
1242
|
+
}
|
|
1243
|
+
if (getCurrentScope()) onScopeDispose(() => inputs.clear())
|
|
1244
|
+
return keyedAsyncData(keyOf, handlerFor, options, (name) => inputs.delete(name))
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
function keyedAsyncData<T, R, K extends keyof T & string = never, D = T>(
|
|
1248
|
+
key: MaybeRefOrGetter<string>,
|
|
1249
|
+
handlerFor: (key: string) => AsyncDataHandler<R>,
|
|
1250
|
+
options: UseAsyncDataOptions<T, R, K, D>,
|
|
1251
|
+
release?: (key: string) => void,
|
|
1252
|
+
): UseAsyncDataResult<PickFrom<T, K>, D> {
|
|
1253
|
+
const app = inject(AppKey, null)
|
|
1254
|
+
if (!app) throw new Error("useAsyncData() must be called inside a Hamur app")
|
|
1255
|
+
const store = app.asyncData
|
|
1256
|
+
const never = inject(NeverHydratedKey, false)
|
|
1257
|
+
const {
|
|
1258
|
+
server,
|
|
1259
|
+
lazy,
|
|
1260
|
+
default: init,
|
|
1261
|
+
transform,
|
|
1262
|
+
immediate,
|
|
1263
|
+
dedupe,
|
|
1264
|
+
pick,
|
|
1265
|
+
deep,
|
|
1266
|
+
watch: sources,
|
|
1267
|
+
getCachedData = defaultGetCachedData,
|
|
1268
|
+
} = options
|
|
1269
|
+
const settings = {
|
|
1270
|
+
server,
|
|
1271
|
+
lazy,
|
|
1272
|
+
default: init as AsyncDataOptions<T, R>["default"],
|
|
1273
|
+
transform,
|
|
1274
|
+
immediate,
|
|
1275
|
+
dedupe,
|
|
1276
|
+
pick,
|
|
1277
|
+
}
|
|
1278
|
+
const first = (name: string) => {
|
|
1279
|
+
store.neverHydrated(name, never)
|
|
1280
|
+
keepCached(app, name, getCachedData)
|
|
1281
|
+
return store.fetch<T, R>(name, handlerFor(name), {
|
|
1282
|
+
...settings,
|
|
1283
|
+
cached: getCachedData(name, app, { cause: "initial" }),
|
|
1284
|
+
})
|
|
1285
|
+
}
|
|
1286
|
+
const active = shallowRef(toValue(key))
|
|
1287
|
+
let entry = first(active.value)
|
|
1288
|
+
const changes = shallowRef(0)
|
|
1289
|
+
const changed = () => void changes.value++
|
|
1290
|
+
const scoped = getCurrentScope() !== undefined
|
|
1291
|
+
let unsubscribe = scoped ? store.subscribe(active.value, changed) : () => {}
|
|
1292
|
+
let unhook = scoped ? store.onRefresh(active.value, () => again("refresh:hook")) : () => {}
|
|
1293
|
+
let disposed = false
|
|
1294
|
+
if (scoped) onScopeDispose(() => ((disposed = true), unsubscribe(), unhook()))
|
|
1295
|
+
if (typeof key !== "string") {
|
|
1296
|
+
watch(
|
|
1297
|
+
() => toValue(key),
|
|
1298
|
+
(next, previous) => {
|
|
1299
|
+
unsubscribe()
|
|
1300
|
+
unhook()
|
|
1301
|
+
entry = first(next)
|
|
1302
|
+
if (scoped) {
|
|
1303
|
+
unsubscribe = store.subscribe(next, changed)
|
|
1304
|
+
unhook = store.onRefresh(next, () => again("refresh:hook"))
|
|
1305
|
+
}
|
|
1306
|
+
active.value = next
|
|
1307
|
+
if (previous !== next) release?.(previous)
|
|
1308
|
+
},
|
|
1309
|
+
)
|
|
1310
|
+
}
|
|
1311
|
+
const snapshot = computed<AsyncDataEntry<T>>(() => {
|
|
1312
|
+
void changes.value
|
|
1313
|
+
return store.get<T>(active.value) ?? entry
|
|
1314
|
+
})
|
|
1315
|
+
if (entry.status === "pending" && entry.promise) {
|
|
1316
|
+
const pending = entry.promise
|
|
1317
|
+
onServerPrefetch(() => pending)
|
|
1318
|
+
}
|
|
1319
|
+
const again = async (cause: GetCachedDataCause) => {
|
|
1320
|
+
const name = active.value
|
|
1321
|
+
// A disposed instance holds the key only for the run, so the purge rule removes an entry nobody reads.
|
|
1322
|
+
const hold = disposed ? store.subscribe(name, () => {}) : undefined
|
|
1323
|
+
try {
|
|
1324
|
+
await refreshCached(app, name, handlerFor(name), settings, getCachedData, cause)
|
|
1325
|
+
} finally {
|
|
1326
|
+
hold?.()
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
if (Array.isArray(sources) && sources.length) watch(sources, () => void again("watch"))
|
|
1330
|
+
const refresh = () => again("refresh:manual")
|
|
1331
|
+
return {
|
|
1332
|
+
data: computed(() => {
|
|
1333
|
+
const value = snapshot.value.data
|
|
1334
|
+
return (deep === true && value !== null && typeof value === "object" ? reactive(value) : value) as
|
|
1335
|
+
PickFrom<T, K> | D
|
|
1336
|
+
}),
|
|
1337
|
+
error: computed(() => snapshot.value.error),
|
|
1338
|
+
status: computed(() => snapshot.value.status),
|
|
1339
|
+
pending: computed(() => isPending(app, snapshot.value)),
|
|
1340
|
+
refresh,
|
|
1341
|
+
execute: refresh,
|
|
1342
|
+
clear: () => clearAsyncData(app, active.value),
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
type DeepRef<T> = T extends
|
|
1347
|
+
| Date
|
|
1348
|
+
| Blob
|
|
1349
|
+
| ArrayBufferView
|
|
1350
|
+
| ArrayBuffer
|
|
1351
|
+
| FormData
|
|
1352
|
+
| URLSearchParams
|
|
1353
|
+
| ReadableStream
|
|
1354
|
+
| ((...args: never[]) => unknown)
|
|
1355
|
+
? T
|
|
1356
|
+
: MaybeRef<T extends readonly (infer E)[] ? DeepRef<E>[] : T extends object ? { [K in keyof T]: DeepRef<T[K]> } : T>
|
|
1357
|
+
/** What a literal `useFetch` call is checked against; any other call stays loose. `query` and `body` take refs, getters and refs inside, as `deepToValue` resolves them. */
|
|
1358
|
+
type FetchInput<X> = X extends { key: infer K extends string; input: infer I }
|
|
1359
|
+
? FetchInputField<I, K, MaybeRefOrGetter<DeepRef<I>>>
|
|
1360
|
+
: unknown
|
|
1361
|
+
type Unkeyed<O, X> = X extends { key: infer K extends string } ? Omit<O, K> : O
|
|
1362
|
+
type FetchCall<U extends string, M extends string, B extends string | undefined> = {
|
|
1363
|
+
method?: M | string
|
|
1364
|
+
baseURL?: B | string
|
|
1365
|
+
} & FetchInput<FetchCheckedInput<U, M, B>>
|
|
1366
|
+
|
|
1367
|
+
export function useFetch<
|
|
1368
|
+
U extends string,
|
|
1369
|
+
M extends string = "GET",
|
|
1370
|
+
K extends keyof FetchData<U, M> & string = never,
|
|
1371
|
+
D = undefined,
|
|
1372
|
+
B extends string | undefined = undefined,
|
|
1373
|
+
>(
|
|
1374
|
+
url: MaybeRefOrGetter<U>,
|
|
1375
|
+
options?: Unkeyed<UseFetchOptions<FetchData<U, M>, FetchData<U, M>, K, D>, FetchCheckedInput<U, M, B>> &
|
|
1376
|
+
FetchCall<U, M, B>,
|
|
1377
|
+
): UseAsyncDataResult<PickFrom<FetchData<U, M>, K>, D>
|
|
1378
|
+
export function useFetch<
|
|
1379
|
+
T = unknown,
|
|
1380
|
+
R = T,
|
|
1381
|
+
K extends keyof T & string = never,
|
|
1382
|
+
D = T,
|
|
1383
|
+
U extends string = string,
|
|
1384
|
+
M extends string = "GET",
|
|
1385
|
+
B extends string | undefined = undefined,
|
|
1386
|
+
>(
|
|
1387
|
+
url: MaybeRefOrGetter<U>,
|
|
1388
|
+
options: Unkeyed<UseFetchOptions<T, R, K, D>, FetchCheckedInput<U, M, B>> & { default: () => D } & FetchCall<U, M, B>,
|
|
1389
|
+
): UseAsyncDataResult<PickFrom<T, K>, D>
|
|
1390
|
+
export function useFetch<
|
|
1391
|
+
T = unknown,
|
|
1392
|
+
R = T,
|
|
1393
|
+
K extends keyof T & string = never,
|
|
1394
|
+
U extends string = string,
|
|
1395
|
+
M extends string = "GET",
|
|
1396
|
+
B extends string | undefined = undefined,
|
|
1397
|
+
>(
|
|
1398
|
+
url: MaybeRefOrGetter<U>,
|
|
1399
|
+
options?: Unkeyed<UseFetchOptions<T, R, K, undefined>, FetchCheckedInput<U, M, B>> & FetchCall<U, M, B>,
|
|
1400
|
+
): UseAsyncDataResult<PickFrom<T, K>>
|
|
1401
|
+
export function useFetch<T = unknown, R = T, K extends keyof T & string = never, D = T>(
|
|
1402
|
+
url: MaybeRefOrGetter<string>,
|
|
1403
|
+
options: UseFetchOptions<T, R, K, D> = {},
|
|
1404
|
+
): UseAsyncDataResult<PickFrom<T, K>, D> {
|
|
1405
|
+
return fetchWith<T, R, K, D>(undefined, url, options)
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
function fetchWith<T, R, K extends keyof T & string, D>(
|
|
1409
|
+
client: $Fetch | undefined,
|
|
1410
|
+
url: MaybeRefOrGetter<string>,
|
|
1411
|
+
options: UseFetchOptions<T, R, K, D>,
|
|
1412
|
+
): UseAsyncDataResult<PickFrom<T, K>, D> {
|
|
1413
|
+
const {
|
|
1414
|
+
key: fixedKey,
|
|
1415
|
+
server,
|
|
1416
|
+
lazy,
|
|
1417
|
+
default: init,
|
|
1418
|
+
transform,
|
|
1419
|
+
immediate,
|
|
1420
|
+
dedupe,
|
|
1421
|
+
pick,
|
|
1422
|
+
deep,
|
|
1423
|
+
watch: sources,
|
|
1424
|
+
getCachedData,
|
|
1425
|
+
query,
|
|
1426
|
+
body,
|
|
1427
|
+
...rest
|
|
1428
|
+
} = options
|
|
1429
|
+
const request = (): FetchOptions => {
|
|
1430
|
+
const resolved: FetchOptions = { ...rest }
|
|
1431
|
+
const resolvedQuery = deepToValue(query) as FetchOptions["query"]
|
|
1432
|
+
const resolvedBody = deepToValue(body)
|
|
1433
|
+
if (resolvedQuery !== undefined) resolved.query = resolvedQuery
|
|
1434
|
+
if (resolvedBody !== undefined) resolved.body = resolvedBody
|
|
1435
|
+
return resolved
|
|
1436
|
+
}
|
|
1437
|
+
const fetcher = client ?? useApp().fetch ?? $fetch
|
|
1438
|
+
const requests = new Map<string, { url: string; request: FetchOptions }>()
|
|
1439
|
+
const keyOf = () => {
|
|
1440
|
+
const target = toValue(url)
|
|
1441
|
+
const resolved = request()
|
|
1442
|
+
const name = fetchKey(target, resolved)
|
|
1443
|
+
requests.set(name, { url: target, request: resolved })
|
|
1444
|
+
return name
|
|
1445
|
+
}
|
|
1446
|
+
const fixed = fixedKey !== undefined || sources === false
|
|
1447
|
+
const handlerFor = (name: string): AsyncDataHandler<R> => {
|
|
1448
|
+
const { url: target, request: resolved } = (!fixed && requests.get(name)) || {
|
|
1449
|
+
url: toValue(url),
|
|
1450
|
+
request: request(),
|
|
1451
|
+
}
|
|
1452
|
+
return ({ signal }) => fetcher<R>(target, { ...resolved, signal: signalOf(resolved.signal, signal) })
|
|
1453
|
+
}
|
|
1454
|
+
if (getCurrentScope()) onScopeDispose(() => requests.clear())
|
|
1455
|
+
const key = fixed ? (fixedKey ?? fetchKey(toValue(url), request())) : keyOf
|
|
1456
|
+
const watched =
|
|
1457
|
+
fixedKey !== undefined && sources !== false
|
|
1458
|
+
? [...(sources ?? []), () => fetchKey(toValue(url), request())]
|
|
1459
|
+
: sources
|
|
1460
|
+
return keyedAsyncData<T, R, K, D>(
|
|
1461
|
+
key,
|
|
1462
|
+
handlerFor,
|
|
1463
|
+
{ server, lazy, default: init, transform, immediate, dedupe, pick, deep, watch: watched, getCachedData },
|
|
1464
|
+
(name) => requests.delete(name),
|
|
1465
|
+
)
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
/** `createUseFetch` defaults change what a call sends (method, body, query, baseURL), so its calls check nothing. */
|
|
1469
|
+
interface UseFetchLoose {
|
|
1470
|
+
<U extends string, M extends string = "GET", K extends keyof FetchData<U, M> & string = never, D = undefined>(
|
|
1471
|
+
url: MaybeRefOrGetter<U>,
|
|
1472
|
+
options?: UseFetchOptions<FetchData<U, M>, FetchData<U, M>, K, D> & { method?: M },
|
|
1473
|
+
): UseAsyncDataResult<PickFrom<FetchData<U, M>, K>, D>
|
|
1474
|
+
<T = unknown, R = T, K extends keyof T & string = never, D = T>(
|
|
1475
|
+
url: MaybeRefOrGetter<string>,
|
|
1476
|
+
options: UseFetchOptions<T, R, K, D> & { default: () => D },
|
|
1477
|
+
): UseAsyncDataResult<PickFrom<T, K>, D>
|
|
1478
|
+
<T = unknown, R = T, K extends keyof T & string = never>(
|
|
1479
|
+
url: MaybeRefOrGetter<string>,
|
|
1480
|
+
options?: UseFetchOptions<T, R, K, undefined>,
|
|
1481
|
+
): UseAsyncDataResult<PickFrom<T, K>>
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
type AnyFetchOptions = UseFetchOptions<any, any, any, any>
|
|
1485
|
+
|
|
1486
|
+
/** `useFetch` with `defaults` under every call's options; `$fetch` replaces the request-bound client, e.g. a `$fetch.create` one. */
|
|
1487
|
+
export function createUseFetch(
|
|
1488
|
+
defaults: AnyFetchOptions | ((options: AnyFetchOptions) => AnyFetchOptions),
|
|
1489
|
+
{ $fetch: client }: { $fetch?: $Fetch } = {},
|
|
1490
|
+
): UseFetchLoose {
|
|
1491
|
+
return ((url: MaybeRefOrGetter<string>, options?: AnyFetchOptions) =>
|
|
1492
|
+
fetchWith(
|
|
1493
|
+
client,
|
|
1494
|
+
url,
|
|
1495
|
+
resolveCallOptions(defaults, options, (value) => deepToValue(value)),
|
|
1496
|
+
)) as unknown as UseFetchLoose
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
/** `useAsyncData` with `defaults` under every call's options. */
|
|
1500
|
+
export function createUseAsyncData(
|
|
1501
|
+
defaults:
|
|
1502
|
+
| UseAsyncDataOptions<any, any, any, any>
|
|
1503
|
+
| ((options: UseAsyncDataOptions<any, any, any, any>) => UseAsyncDataOptions<any, any, any, any>),
|
|
1504
|
+
): typeof useAsyncData {
|
|
1505
|
+
return ((...args: unknown[]) => {
|
|
1506
|
+
const [first, second, options] = asyncDataArguments("useAsyncData", args, isRef)
|
|
1507
|
+
return useAsyncData(
|
|
1508
|
+
first as never,
|
|
1509
|
+
second as never,
|
|
1510
|
+
resolveCallOptions(defaults, options as UseAsyncDataOptions<any, any, any, any> | undefined),
|
|
1511
|
+
)
|
|
1512
|
+
}) as typeof useAsyncData
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
export const useLazyFetch: typeof useFetch = ((url: MaybeRefOrGetter<string>, options?: AnyFetchOptions) =>
|
|
1516
|
+
useFetch(url, { ...options, lazy: true })) as typeof useFetch
|
|
1517
|
+
|
|
1518
|
+
export const useLazyAsyncData: typeof useAsyncData = ((...args: unknown[]) => {
|
|
1519
|
+
const [first, second, options] = asyncDataArguments("useLazyAsyncData", args, isRef)
|
|
1520
|
+
return useAsyncData(first as never, second as never, {
|
|
1521
|
+
...(options as UseAsyncDataOptions<any, any, any, any>),
|
|
1522
|
+
lazy: true,
|
|
1523
|
+
})
|
|
1524
|
+
}) as typeof useAsyncData
|
|
1525
|
+
|
|
1526
|
+
export function transitionName(name: string): { style: { viewTransitionName: string } } {
|
|
1527
|
+
return { style: { viewTransitionName: checkTransitionName(name) } }
|
|
1528
|
+
}
|