@hamur/adapter-preact 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +35 -2
  3. package/dist/chunks/browser-index-89d71ade.js +118 -0
  4. package/dist/chunks/browser-index-ezte15pp.js +67 -0
  5. package/dist/chunks/browser-index-hsy7tnbg.js +21 -0
  6. package/dist/chunks/browser-index-k3m2axbw.js +274 -0
  7. package/dist/src/adapter.js +456 -0
  8. package/dist/src/error-page.js +391 -0
  9. package/dist/src/index.js +1506 -0
  10. package/dist/src/keepalive.js +6 -0
  11. package/dist/src/runtime/client.js +96 -0
  12. package/dist/src/runtime/island.js +33 -0
  13. package/dist/src/runtime/server.js +95 -0
  14. package/dist/types/src/activation.d.ts +15 -0
  15. package/dist/types/src/adapter.d.ts +2 -0
  16. package/dist/types/src/async-data.d.ts +13 -0
  17. package/dist/types/src/client-component.d.ts +11 -0
  18. package/dist/types/src/client-fallback.d.ts +2 -0
  19. package/dist/types/src/context.d.ts +81 -0
  20. package/dist/types/src/error-page.d.ts +1 -0
  21. package/dist/types/src/head.d.ts +5 -0
  22. package/dist/types/src/index.d.ts +429 -0
  23. package/dist/types/src/island-html.d.ts +13 -0
  24. package/dist/types/src/island.d.ts +19 -0
  25. package/dist/types/src/jsx-locator.d.ts +6 -0
  26. package/dist/types/src/keepalive.d.ts +26 -0
  27. package/dist/types/src/lazy-hydration.d.ts +12 -0
  28. package/dist/types/src/markdown-page.d.ts +9 -0
  29. package/dist/types/src/markdown.d.ts +12 -0
  30. package/dist/types/src/plugin.d.ts +36 -0
  31. package/dist/types/src/route-boundary.d.ts +41 -0
  32. package/dist/types/src/runtime/client.d.ts +10 -0
  33. package/dist/types/src/runtime/hmr.d.ts +31 -0
  34. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  35. package/dist/types/src/runtime/hydration.d.ts +8 -0
  36. package/dist/types/src/runtime/island.d.ts +8 -0
  37. package/dist/types/src/runtime/server.d.ts +11 -0
  38. package/dist/types/src/server-island.d.ts +10 -0
  39. package/dist/types/src/svg.d.ts +10 -0
  40. package/package.json +71 -4
  41. package/src/activation.ts +51 -0
  42. package/src/adapter.ts +35 -0
  43. package/src/async-data.ts +65 -0
  44. package/src/client-component.ts +23 -0
  45. package/src/client-fallback.ts +2 -0
  46. package/src/context.ts +372 -0
  47. package/src/env.d.ts +3 -0
  48. package/src/error-page.ts +1 -0
  49. package/src/head.ts +34 -0
  50. package/src/index.ts +1868 -0
  51. package/src/island-html.ts +58 -0
  52. package/src/island.ts +56 -0
  53. package/src/jsx-locator.ts +199 -0
  54. package/src/keepalive.ts +100 -0
  55. package/src/lazy-hydration.ts +101 -0
  56. package/src/markdown-page.ts +18 -0
  57. package/src/markdown.ts +58 -0
  58. package/src/plugin.ts +231 -0
  59. package/src/route-boundary.ts +51 -0
  60. package/src/runtime/client.ts +85 -0
  61. package/src/runtime/hmr.ts +141 -0
  62. package/src/runtime/hydration-dev.ts +8 -0
  63. package/src/runtime/hydration.ts +7 -0
  64. package/src/runtime/island.ts +37 -0
  65. package/src/runtime/server.ts +102 -0
  66. package/src/server-island.ts +35 -0
  67. package/src/svg.ts +27 -0
  68. package/src/webmcp.d.ts +18 -0
package/src/context.ts ADDED
@@ -0,0 +1,372 @@
1
+ import { Component, createContext, createElement, Fragment } from "preact"
2
+ import type { ComponentChildren, Context, VNode } from "preact"
3
+ import { useContext, useLayoutEffect, useMemo } from "preact/hooks"
4
+ import type { AppContext, ClearErrorOptions, ErrorPageProps, ErrorStore, Head, State } from "hamur/app"
5
+ import type {
6
+ ClientContext,
7
+ FormStatusStore,
8
+ NavigationState,
9
+ RenderContext,
10
+ RenderTree,
11
+ ResolvedRoute,
12
+ RouteValue,
13
+ RouterApi,
14
+ } from "hamur/adapter"
15
+ import { createRouterApi, layoutOf, reportClientError, routeBoundary, type RouterSource } from "hamur/adapter"
16
+ import type { RenderEntry } from "hamur/adapter"
17
+ import type { KeptOutlet } from "./keepalive.ts"
18
+ import { activation, detach, setHidden, type Activation } from "./activation.ts"
19
+ import { Guard, RouteBoundary, rethrown } from "./route-boundary.ts"
20
+ import { routeStateOf, setServerHTML, emptyServerHTML, SLOT_ELEMENT } from "hamur/adapter"
21
+ import { withBase } from "hamur/app"
22
+ import type { RouteLocation } from "hamur/app"
23
+
24
+ export const RouteContext: Context<RouteValue | null> = createContext<RouteValue | null>(null)
25
+ export const RouterContext = createContext<RouterApi | null>(null)
26
+ /** `true` below a `"never"` lazy component, so its async data stays out of the payload. */
27
+ export const NeverHydratedContext = createContext(false)
28
+
29
+ export interface SearchStore {
30
+ get(): RouteValue["search"]
31
+ subscribe(listener: () => void): () => void
32
+ router(): RouterApi
33
+ }
34
+
35
+ /** One store per app, so `useSearch(select)` reads the search without the route context that re-renders every reader. */
36
+ export const SearchContext = createContext<SearchStore | null>(null)
37
+ const searchStores = new WeakMap<
38
+ object,
39
+ { store: SearchStore; set(search: RouteValue["search"], router: RouterApi): void }
40
+ >()
41
+
42
+ function searchStoreOf(app: object, search: RouteValue["search"], router: RouterApi): SearchStore {
43
+ let entry = searchStores.get(app)
44
+ if (!entry) {
45
+ let current = search
46
+ let currentRouter = router
47
+ const listeners = new Set<() => void>()
48
+ entry = {
49
+ store: {
50
+ get: () => current,
51
+ router: () => currentRouter,
52
+ subscribe: (listener) => (listeners.add(listener), () => void listeners.delete(listener)),
53
+ },
54
+ set(next, nextRouter) {
55
+ currentRouter = nextRouter
56
+ if (next === current) return
57
+ current = next
58
+ for (const listener of [...listeners]) listener()
59
+ },
60
+ }
61
+ searchStores.set(app, entry)
62
+ }
63
+ entry.set(search, router)
64
+ return entry.store
65
+ }
66
+ export const BaseURLContext = createContext("/")
67
+ export const HrefContext = createContext<RenderContext["href"]>((to) => {
68
+ if (typeof to !== "string") throw new Error(`Link to the route "${to.name}" must be rendered inside a Hamur app`)
69
+ return withBase(to, "/")
70
+ })
71
+ export const DataContext = createContext<Record<string, unknown>>({})
72
+ export const EntryContext = createContext<string | null>(null)
73
+ export interface ErrorSource {
74
+ store?: ErrorStore
75
+ initial?: ErrorPageProps
76
+ }
77
+
78
+ export const ErrorContext = createContext<ErrorSource>({})
79
+ export const HeadContext = createContext<Head | null>(null)
80
+ export const StateContext = createContext<State | null>(null)
81
+ export const OutletContext = createContext<ComponentChildren>(null)
82
+ export const SlotsContext = createContext<Record<string, ComponentChildren> | null>(null)
83
+ export const OutletValueContext = createContext<unknown>(undefined)
84
+ export const LayoutContext = createContext<ReturnType<typeof layoutOf> | null>(null)
85
+ export const ActivationContext = createContext<Activation | undefined>(undefined)
86
+
87
+ export interface NavigationSource {
88
+ get(): NavigationState
89
+ subscribe(listener: () => void): () => void
90
+ }
91
+
92
+ export interface Submitted {
93
+ /** The `{ id, instance?, value | failure | error }` of a no-JS post to a page. */
94
+ handlerState?: unknown
95
+ }
96
+
97
+ export const SubmittedContext = createContext<Submitted>({})
98
+ export const FormStatusContext = createContext<FormStatusStore | null>(null)
99
+ export const AppContextContext = createContext<AppContext | null>(null)
100
+ export const NavigationContext = createContext<NavigationSource | null>(null)
101
+
102
+ /** The `href` of the `Link` whose children render, read by `useLinkStatus()`. */
103
+ export const LinkHrefContext = createContext<string | null>(null)
104
+
105
+ function navigationOf(navigator: unknown): NavigationSource | null {
106
+ const source = navigator as Partial<NavigationSource> | undefined
107
+ return typeof source?.get === "function" && typeof source.subscribe === "function"
108
+ ? (source as NavigationSource)
109
+ : null
110
+ }
111
+
112
+ export function routerOf(
113
+ navigator: unknown,
114
+ baseURL = "/",
115
+ page?: Omit<RouterSource, "navigator" | "baseURL">,
116
+ ): RouterApi {
117
+ return createRouterApi({ ...page, navigator, baseURL })
118
+ }
119
+
120
+ export function routeValue(
121
+ ctx: Pick<RenderContext, "route"> & Partial<Pick<RenderContext, "app" | "payload" | "tree">>,
122
+ ): RouteValue {
123
+ const { route } = ctx
124
+ return {
125
+ path: route.path,
126
+ fullPath: route.fullPath,
127
+ params: route.params,
128
+ query: route.query,
129
+ search: route.search,
130
+ hash: route.hash,
131
+ name: route.name,
132
+ meta: route.meta,
133
+ matched: route.matched,
134
+ groups: route.groups ?? [],
135
+ ...routeStateOf(ctx),
136
+ } as RouteValue
137
+ }
138
+
139
+ function boundaryView(ctx: Source, entry: RenderEntry, error: unknown): VNode {
140
+ if (typeof error === "object" && error !== null && rethrown.has(error)) throw error
141
+ const caught = routeBoundary(ctx as RenderContext | ClientContext, entry, error)
142
+ if (!caught) throw error
143
+ const clearError = (options?: ClearErrorOptions) => ctx.app.error?.clear(options) ?? Promise.resolve()
144
+ return createElement(
145
+ Guard as never,
146
+ null,
147
+ createElement(
148
+ EntryContext.Provider as never,
149
+ { value: caught.id },
150
+ createElement(
151
+ ErrorContext.Provider as never,
152
+ { value: { initial: caught.error } },
153
+ createElement(caught.component as never, { error: caught.error, clearError }),
154
+ ),
155
+ ),
156
+ ) as VNode
157
+ }
158
+
159
+ /** An intercepting chain reads the intercepted route with the history entry of the page kept. */
160
+ function intercepted(slot: RenderTree, ctx: Source, node: ComponentChildren | undefined): ComponentChildren {
161
+ if (!slot.route) return node ?? null
162
+ const { state, key, navigationType } = ctx.route
163
+ return createElement(
164
+ RouteContext.Provider as never,
165
+ { value: routeValue({ ...ctx, route: { ...slot.route, state, key, navigationType }, tree: slot }) },
166
+ node,
167
+ ) as VNode
168
+ }
169
+
170
+ let keptOutlet: KeptOutlet | undefined
171
+
172
+ /** The core's keep-alive feature loads the outlet (`Adapter.keepAliveOutlet`) and hands it to `installKeepAlive` before the first tree that holds kept units; it takes what it needs from the object it is built with, so its chunk imports nothing from the base. */
173
+ export function installKeepAlive(module: typeof import("./keepalive.ts")): void {
174
+ keptOutlet ??= module.createKeptOutlet({
175
+ createElement,
176
+ Fragment,
177
+ useContext,
178
+ useMemo,
179
+ useLayoutEffect,
180
+ ActivationContext,
181
+ activation,
182
+ detach,
183
+ setHidden,
184
+ RouteContext,
185
+ DataContext,
186
+ routeValue,
187
+ nest,
188
+ })
189
+ }
190
+
191
+ function keepAlive(): KeptOutlet {
192
+ if (!keptOutlet)
193
+ throw new Error(
194
+ "A tree with kept pages was rendered before the keep-alive part of the Preact adapter was installed",
195
+ )
196
+ return keptOutlet
197
+ }
198
+
199
+ function nest(tree: RenderTree, ctx: Source): ComponentChildren | undefined {
200
+ let child: ComponentChildren | undefined
201
+ for (let index = tree.components.length - 1; index >= 0; index--) {
202
+ const entry = tree.components[index]!
203
+ const { id, component, props } = entry
204
+ if (entry.kept !== undefined) child = keepAlive()(entry, tree.components[index + 1], child, ctx)
205
+ let element = (
206
+ child === undefined
207
+ ? createElement(component as never, props ?? null)
208
+ : createElement(component as never, props ?? null, child)
209
+ ) as VNode
210
+ if (entry.caught)
211
+ element = createElement(
212
+ Guard as never,
213
+ null,
214
+ createElement(ErrorContext.Provider as never, { value: { initial: props?.error as ErrorPageProps } }, element),
215
+ ) as VNode
216
+ const slots = entry.outlets
217
+ ? Object.fromEntries(
218
+ Object.entries(entry.outlets).map(([name, slot]) => [name, intercepted(slot, ctx, nest(slot, ctx))]),
219
+ )
220
+ : null
221
+ child = createElement(
222
+ EntryContext.Provider as never,
223
+ { value: id },
224
+ createElement(
225
+ SlotsContext.Provider as never,
226
+ { value: slots },
227
+ createElement(OutletContext.Provider as never, { value: child ?? null }, element),
228
+ ),
229
+ ) as VNode
230
+ if (entry.boundary)
231
+ child = createElement(
232
+ RouteBoundary as never,
233
+ { resetOn: entry, fallback: (error: unknown) => boundaryView(ctx, entry, error) },
234
+ child,
235
+ ) as VNode
236
+ if (entry.key !== undefined) child = createElement(Fragment, { key: entry.key }, child) as VNode
237
+ }
238
+ return child
239
+ }
240
+
241
+ export type Source = Pick<RenderContext | ClientContext, "route" | "tree"> &
242
+ Pick<RenderContext, "app" | "head"> &
243
+ Partial<Pick<RenderContext, "payload" | "baseURL">> &
244
+ Pick<RenderContext, "href"> & { navigator?: unknown }
245
+
246
+ const EMPTY: Record<string, unknown> = {}
247
+
248
+ export function buildElement(ctx: Source): VNode<any> {
249
+ const error: ErrorSource = {
250
+ store: ctx.app.error,
251
+ initial: routeStateOf({ payload: ctx.payload, tree: ctx.tree }).error,
252
+ }
253
+ const route = routeValue(ctx)
254
+ const router = routerOf(ctx.navigator, ctx.baseURL, ctx)
255
+ return createElement(
256
+ RouteContext.Provider,
257
+ { value: route },
258
+ createElement(
259
+ SearchContext.Provider,
260
+ { value: searchStoreOf(ctx.app, route.search, router) },
261
+ createElement(
262
+ RouterContext.Provider,
263
+ { value: router },
264
+ createElement(
265
+ DataContext.Provider,
266
+ { value: (ctx.payload?.data as Record<string, unknown> | undefined) ?? EMPTY },
267
+ createElement(
268
+ ErrorContext.Provider,
269
+ { value: error },
270
+ createElement(
271
+ HeadContext.Provider,
272
+ { value: ctx.head },
273
+ createElement(
274
+ StateContext.Provider,
275
+ { value: ctx.app.state },
276
+ createElement(
277
+ AppContextContext.Provider,
278
+ { value: ctx.app },
279
+ createElement(
280
+ SubmittedContext.Provider,
281
+ { value: { handlerState: ctx.payload?.handlerState } },
282
+ createElement(
283
+ NavigationContext.Provider,
284
+ { value: navigationOf(ctx.navigator) },
285
+ createElement(
286
+ BaseURLContext.Provider,
287
+ { value: ctx.baseURL ?? "/" },
288
+ createElement(
289
+ HrefContext.Provider,
290
+ { value: ctx.href },
291
+ createElement(
292
+ LayoutContext.Provider,
293
+ { value: layoutOf(ctx.tree) },
294
+ ctx.tree.kept === undefined
295
+ ? nest(ctx.tree, ctx)
296
+ : keepAlive()(ctx.tree, ctx.tree.components[0], nest(ctx.tree, ctx), ctx),
297
+ ),
298
+ ),
299
+ ),
300
+ ),
301
+ ),
302
+ ),
303
+ ),
304
+ ),
305
+ ),
306
+ ),
307
+ ),
308
+ ),
309
+ )
310
+ }
311
+
312
+ interface RootBoundaryProps {
313
+ app: AppContext
314
+ children: ComponentChildren
315
+ }
316
+
317
+ /** The root boundary: renders nothing for the tree that threw and reports it once the diff is done. */
318
+ export class RootBoundary extends Component<RootBoundaryProps, { failed?: ComponentChildren }> {
319
+ override componentDidCatch(error: unknown): void {
320
+ this.setState({ failed: this.props.children })
321
+ queueMicrotask(() => reportClientError(this.props.app, error, { render: true }))
322
+ }
323
+
324
+ override render() {
325
+ return this.state.failed === this.props.children ? null : this.props.children
326
+ }
327
+ }
328
+
329
+ const ISLAND_ENTRY = "island"
330
+ let keptSlot: { __html: string } | undefined
331
+
332
+ /**
333
+ * The island's children, in the slot element `uid` names: the server writes their HTML; Preact does not apply an empty
334
+ * `dangerouslySetInnerHTML` while hydrating, so the browser keeps the nodes the server wrote and writes the same HTML only into a
335
+ * slot element it creates anew.
336
+ */
337
+ function slotElement(uid: string, html: string): VNode {
338
+ if (typeof window === "undefined")
339
+ return createElement(SLOT_ELEMENT, { uid, dangerouslySetInnerHTML: { __html: html } }) as VNode
340
+ // Preact assigns `__html` to `innerHTML` on a new element, which Trusted Types refuses as a string.
341
+ keptSlot ??= { __html: emptyServerHTML() as string }
342
+ const fill = (node: Element | null) => {
343
+ if (node && html && !node.hasChildNodes()) setServerHTML(node, html)
344
+ }
345
+ return createElement(SLOT_ELEMENT, { uid, dangerouslySetInnerHTML: keptSlot, ref: fill }) as VNode
346
+ }
347
+
348
+ /** An island as a root of its own: the app's route, state and head contexts around one entry, its `useId` values under the island's `uid`; a `Link` takes a path, as no route table ships. */
349
+ export function islandElement(
350
+ component: unknown,
351
+ props: Record<string, unknown>,
352
+ ctx: { app: AppContext; route: ResolvedRoute; baseURL: string; idPrefix: string; slots?: { default?: string } },
353
+ ): VNode {
354
+ const href = (to: string | RouteLocation) => {
355
+ if (typeof to !== "string")
356
+ throw new Error(`Link to the route "${to.name}" cannot render in an island; give it a path`)
357
+ return withBase(to, ctx.baseURL)
358
+ }
359
+ const slot = ctx.slots?.default
360
+ const entryProps = slot === undefined ? props : { ...props, children: slotElement(`s${ctx.idPrefix}`, slot) }
361
+ const root: VNode & { __m?: [string, number] } = buildElement({
362
+ app: ctx.app,
363
+ head: ctx.app.head,
364
+ route: ctx.route,
365
+ baseURL: ctx.baseURL,
366
+ href,
367
+ tree: { components: [{ id: ISLAND_ENTRY, component, props: entryProps }] },
368
+ })
369
+ // Preact's `useId` counts from the nearest vnode holding its mangled `_mask`, else the root; seeding it gives each island `P<uid>-<n>`.
370
+ root.__m = [ctx.idPrefix, 0]
371
+ return root
372
+ }
package/src/env.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ interface ImportMeta {
2
+ readonly dev?: boolean
3
+ }
@@ -0,0 +1 @@
1
+ export { DefaultErrorPage as default } from "./index.ts"
package/src/head.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { Head, HeadEntry, HeadInput } from "hamur/app"
2
+
3
+ interface Mounted {
4
+ rank: number
5
+ input: HeadInput
6
+ entry: HeadEntry
7
+ }
8
+
9
+ const mounted = new WeakMap<Head, Set<Mounted>>()
10
+ let ranks = 0
11
+
12
+ /** Render order, parent first: a component takes one the first time it renders. */
13
+ export const nextRank = (): number => ++ranks
14
+
15
+ /** Layout effects run child first; an entry pushed after entries of a higher rank goes in front of them, so a page still wins over its layout. */
16
+ export function mountHead(head: Head, rank: number, input: HeadInput): HeadEntry {
17
+ const live = mounted.get(head) ?? new Set<Mounted>()
18
+ mounted.set(head, live)
19
+ const later = [...live].filter((other) => other.rank > rank).sort((a, b) => a.rank - b.rank)
20
+ for (const other of later) other.entry.dispose()
21
+ const self: Mounted = { rank, input, entry: head.push(input) }
22
+ for (const other of later) other.entry = head.push(other.input)
23
+ live.add(self)
24
+ return {
25
+ patch(next) {
26
+ self.input = next
27
+ self.entry.patch(next)
28
+ },
29
+ dispose() {
30
+ self.entry.dispose()
31
+ live.delete(self)
32
+ },
33
+ }
34
+ }