@hamur/adapter-html 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +31 -2
  3. package/dist/chunks/browser-index-2h1699xv.js +148 -0
  4. package/dist/chunks/browser-index-n6x04zrf.js +28 -0
  5. package/dist/chunks/browser-index-naq02zzj.js +4 -0
  6. package/dist/chunks/browser-index-qx74bd1y.js +302 -0
  7. package/dist/src/adapter.js +141 -0
  8. package/dist/src/error-page.js +335 -0
  9. package/dist/src/index.js +1241 -0
  10. package/dist/src/runtime/client.js +330 -0
  11. package/dist/src/runtime/island.js +40 -0
  12. package/dist/src/runtime/server.js +59 -0
  13. package/dist/types/src/adapter.d.ts +2 -0
  14. package/dist/types/src/async-data.d.ts +13 -0
  15. package/dist/types/src/context.d.ts +109 -0
  16. package/dist/types/src/error-page.d.ts +1 -0
  17. package/dist/types/src/index.d.ts +343 -0
  18. package/dist/types/src/island-html.d.ts +13 -0
  19. package/dist/types/src/island.d.ts +40 -0
  20. package/dist/types/src/lazy-hydration.d.ts +11 -0
  21. package/dist/types/src/markdown-page.d.ts +9 -0
  22. package/dist/types/src/markdown.d.ts +11 -0
  23. package/dist/types/src/plugin.d.ts +11 -0
  24. package/dist/types/src/runtime/client.d.ts +15 -0
  25. package/dist/types/src/runtime/hmr.d.ts +8 -0
  26. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  27. package/dist/types/src/runtime/hydration.d.ts +10 -0
  28. package/dist/types/src/runtime/island.d.ts +8 -0
  29. package/dist/types/src/runtime/server.d.ts +8 -0
  30. package/dist/types/src/runtime/svg-id.d.ts +2 -0
  31. package/dist/types/src/server-component.d.ts +4 -0
  32. package/dist/types/src/svg.d.ts +10 -0
  33. package/package.json +44 -4
  34. package/src/adapter.ts +25 -0
  35. package/src/async-data.ts +65 -0
  36. package/src/context.ts +445 -0
  37. package/src/env.d.ts +3 -0
  38. package/src/error-page.ts +1 -0
  39. package/src/index.ts +1620 -0
  40. package/src/island-html.ts +58 -0
  41. package/src/island.ts +126 -0
  42. package/src/lazy-hydration.ts +56 -0
  43. package/src/markdown-page.ts +17 -0
  44. package/src/markdown.ts +29 -0
  45. package/src/plugin.ts +70 -0
  46. package/src/runtime/client.ts +363 -0
  47. package/src/runtime/hmr.ts +38 -0
  48. package/src/runtime/hydration-dev.ts +12 -0
  49. package/src/runtime/hydration.ts +11 -0
  50. package/src/runtime/island.ts +52 -0
  51. package/src/runtime/server.ts +56 -0
  52. package/src/runtime/svg-id.ts +12 -0
  53. package/src/server-component.ts +30 -0
  54. package/src/svg.ts +54 -0
@@ -0,0 +1,363 @@
1
+ import type { AppContext, HeadEntry } from "hamur/app"
2
+ import {
3
+ createAnnouncer,
4
+ createLoadingIndicator,
5
+ createRouteAnnouncer,
6
+ fetchServerComponent,
7
+ hideAnnouncer,
8
+ paintLoadingIndicator,
9
+ serverComponentProps,
10
+ setAdapterInstance,
11
+ setLinkState,
12
+ takeServerHTML,
13
+ writeRouteAnnouncer,
14
+ } from "hamur/adapter"
15
+ import type { LoadingIndicatorLook, LoadingIndicatorOptions } from "hamur/adapter"
16
+ import type { ClientContext, ServerComponentView } from "hamur/adapter"
17
+ import {
18
+ RERUN_STATE_KEY,
19
+ CLIENT_MARKERS,
20
+ CLIENT_TEMPLATE,
21
+ LAYOUT_MARKERS,
22
+ LINK_STATE_ATTRIBUTE,
23
+ currentState,
24
+ followNavigation,
25
+ PAGE_MARKERS,
26
+ linkStateKey,
27
+ renderTree,
28
+ repaintPage,
29
+ setCurrent,
30
+ setRepaint,
31
+ releaseAnnouncerClaims,
32
+ takeAnnouncerRendered,
33
+ takeIndicatorRendered,
34
+ type LinkEntry,
35
+ type RenderOut,
36
+ } from "../context.ts"
37
+ import { isPage, serverComponentHTML, serverComponentId } from "../server-component.ts"
38
+ import { devHydration } from "./hydration.ts"
39
+
40
+ let entries: HeadEntry[] = []
41
+ let scoped: Array<() => void> = []
42
+
43
+ function keepLinkStates(root: Element, states: Map<string, LinkEntry>): void {
44
+ for (const anchor of root.querySelectorAll(`a[${LINK_STATE_ATTRIBUTE}]`)) {
45
+ const entry = states.get(
46
+ linkStateKey(anchor.getAttribute("href") ?? "", anchor.getAttribute(LINK_STATE_ATTRIBUTE)!),
47
+ )
48
+ anchor.removeAttribute(LINK_STATE_ATTRIBUTE)
49
+ if (entry) setLinkState(anchor, entry.state, entry.onBeforeNavigate)
50
+ }
51
+ }
52
+
53
+ function renderOut(): Required<Omit<RenderOut, "deferred">> {
54
+ for (const remove of scoped) remove()
55
+ scoped = []
56
+ return { linkStates: new Map(), scoped }
57
+ }
58
+
59
+ const COMMENT = 8
60
+ const ELEMENT = 1
61
+ const isDev = (import.meta as { dev?: boolean }).dev === true
62
+ const warnedKeepAlive = new Set<string>()
63
+
64
+ /** The build cannot read `meta.keepalive`, so a route that sets it is told once in dev that html keeps nothing. */
65
+ function warnKeepAlive(ctx: ClientContext): void {
66
+ if (!isDev || ctx.route.meta.keepalive !== true) return
67
+ const route = ctx.route.matched.at(-1)?.path ?? ctx.route.path
68
+ if (warnedKeepAlive.has(route)) return
69
+ warnedKeepAlive.add(route)
70
+ console.warn(`meta.keepalive of ${route} has no effect in html apps (no component state)`)
71
+ }
72
+
73
+ interface Held {
74
+ id: string
75
+ value: string
76
+ start: number | null
77
+ end: number | null
78
+ }
79
+
80
+ /** A focused input or textarea with an id: its value and caret survive the repaint, which replaces the root's HTML. */
81
+ function holdFocus(root: Element): Held | undefined {
82
+ if (
83
+ typeof document === "undefined" ||
84
+ typeof HTMLInputElement === "undefined" ||
85
+ typeof HTMLTextAreaElement === "undefined"
86
+ )
87
+ return undefined
88
+ const active = document.activeElement
89
+ if (
90
+ !(active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement) ||
91
+ !active.id ||
92
+ typeof root.contains !== "function" ||
93
+ !root.contains(active)
94
+ )
95
+ return undefined
96
+ return { id: active.id, value: active.value, start: active.selectionStart, end: active.selectionEnd }
97
+ }
98
+
99
+ function restoreFocus(root: Element, held: Held): void {
100
+ if (typeof root.querySelectorAll !== "function") return
101
+ const next = [...root.querySelectorAll("input, textarea")].find((element) => element.id === held.id) as
102
+ HTMLInputElement | HTMLTextAreaElement | undefined
103
+ if (!next) return
104
+ next.value = held.value
105
+ next.focus?.({ preventScroll: true })
106
+ if (held.start !== null && held.end !== null) next.setSelectionRange?.(held.start, held.end)
107
+ }
108
+
109
+ function repaint(ctx: ClientContext): void {
110
+ paint(ctx)
111
+ setCurrent(ctx)
112
+ }
113
+
114
+ function paint(ctx: ClientContext, completesNavigation = false): void {
115
+ setRepaint(() => paint(ctx))
116
+ if (import.meta.hot) void import("./hmr.ts").then((hmr) => hmr.track(ctx, repaint))
117
+ for (const entry of entries) entry.dispose()
118
+ entries = []
119
+ takeIndicatorRendered()
120
+ takeAnnouncerRendered()
121
+ releaseAnnouncerClaims()
122
+ const out = renderOut()
123
+ const held = holdFocus(ctx.root)
124
+ ctx.setRootHTML(renderTree(ctx, entries, completesNavigation, out))
125
+ if (held) restoreFocus(ctx.root, held)
126
+ if (out.linkStates.size) keepLinkStates(ctx.root, out.linkStates)
127
+ ctx.head.apply()
128
+ if (takeIndicatorRendered()) driveLoadingIndicators(ctx)
129
+ if (takeAnnouncerRendered()) driveAnnouncers(ctx)
130
+ else stopAnnouncers()
131
+ }
132
+
133
+ const INDICATOR = "[data-hamur-loading-indicator]"
134
+ let driven: { app: AppContext; stop(): void } | undefined
135
+
136
+ function numberOf(value: string | undefined): number | undefined {
137
+ return value === undefined ? undefined : Number(value)
138
+ }
139
+
140
+ function lookOf({ dataset }: HTMLElement): LoadingIndicatorLook {
141
+ const look: LoadingIndicatorLook = {}
142
+ if (dataset.hamurColor !== undefined) look.color = dataset.hamurColor
143
+ if (dataset.hamurErrorColor !== undefined) look.errorColor = dataset.hamurErrorColor
144
+ if (dataset.hamurHeight !== undefined) look.height = Number(dataset.hamurHeight)
145
+ return look
146
+ }
147
+
148
+ /** Binds every `[data-hamur-loading-indicator]` under the root to the app's store; the options are the first element's. */
149
+ function driveLoadingIndicators(ctx: ClientContext): void {
150
+ const elements = ctx.root.querySelectorAll<HTMLElement>(INDICATOR)
151
+ const first = elements[0]
152
+ if (!first) return
153
+ const options: LoadingIndicatorOptions = {}
154
+ const duration = numberOf(first.dataset.hamurDuration)
155
+ const throttle = numberOf(first.dataset.hamurThrottle)
156
+ if (duration !== undefined) options.duration = duration
157
+ if (throttle !== undefined) options.throttle = throttle
158
+ const store = createLoadingIndicator(ctx.app, options)
159
+ followNavigation(ctx.app, ctx.navigator)
160
+ const render = () => {
161
+ for (const element of ctx.root.querySelectorAll<HTMLElement>(INDICATOR))
162
+ paintLoadingIndicator(element, store.get(), lookOf(element))
163
+ }
164
+ render()
165
+ if (driven?.app === ctx.app) return
166
+ driven?.stop()
167
+ driven = { app: ctx.app, stop: store.subscribe(render) }
168
+ }
169
+
170
+ const ANNOUNCER = "[data-hamur-announcer]"
171
+
172
+ interface DrivenAnnouncers {
173
+ app: AppContext
174
+ route?: () => void
175
+ page?: () => void
176
+ stop?: () => void
177
+ }
178
+
179
+ let announcing: DrivenAnnouncers | undefined
180
+
181
+ /** Unmounts the regions the runtime drives, so the navigator's own comes back; html has no component lifecycle to do it from. */
182
+ function stopAnnouncers(): void {
183
+ announcing?.stop?.()
184
+ announcing?.route?.()
185
+ announcing?.page?.()
186
+ announcing = undefined
187
+ }
188
+
189
+ function announcerElements(root: Element): { route?: HTMLElement; polite?: HTMLElement; assertive?: HTMLElement } {
190
+ const found: { route?: HTMLElement; polite?: HTMLElement; assertive?: HTMLElement } = {}
191
+ for (const element of root.querySelectorAll<HTMLElement>(ANNOUNCER)) {
192
+ const kind = element.dataset.hamurAnnouncer
193
+ if (kind === "route" || kind === "polite" || kind === "assertive") found[kind] ??= element
194
+ }
195
+ return found
196
+ }
197
+
198
+ /** Binds the regions `RouteAnnouncer()` and `Announcer()` wrote to the app's stores; each paint replaces the elements, so the state is written again. */
199
+ function driveAnnouncers(ctx: ClientContext): void {
200
+ if (announcing && announcing.app !== ctx.app) stopAnnouncers()
201
+ const found = announcerElements(ctx.root)
202
+ const routeStore = createRouteAnnouncer(ctx.app)
203
+ const pageStore = createAnnouncer(ctx.app)
204
+ const driven = (announcing ??= { app: ctx.app })
205
+ if (found.route && !driven.route) driven.route = routeStore.mount()
206
+ if (!found.route && driven.route) {
207
+ driven.route()
208
+ driven.route = undefined
209
+ }
210
+ const paged = !!(found.polite || found.assertive)
211
+ if (paged && !driven.page) driven.page = pageStore.mount()
212
+ if (!paged && driven.page) {
213
+ driven.page()
214
+ driven.page = undefined
215
+ }
216
+ if (found.route && !found.route.hasAttribute("class") && !found.route.hasAttribute("style"))
217
+ hideAnnouncer(found.route)
218
+ if (found.polite) hideAnnouncer(found.polite)
219
+ if (found.assertive) hideAnnouncer(found.assertive)
220
+ const render = () => {
221
+ const now = announcerElements(ctx.root)
222
+ if (now.route)
223
+ writeRouteAnnouncer(now.route, {
224
+ ...routeStore.get(),
225
+ ...(now.route.dataset.hamurPoliteness ? { politeness: now.route.dataset.hamurPoliteness as never } : {}),
226
+ })
227
+ if (now.polite) now.polite.textContent = pageStore.get().regions.polite
228
+ if (now.assertive) now.assertive.textContent = pageStore.get().regions.assertive
229
+ }
230
+ render()
231
+ if (driven.stop) return
232
+ const stops = [routeStore.subscribe(render), pageStore.subscribe(render)]
233
+ driven.stop = () => stops.forEach((stop) => stop())
234
+ }
235
+
236
+ /** Replaces the fallback each `ClientOnly` wrote with the children of the `<template>` after it; a template that came out of another one is found on the next pass. */
237
+ function swapClientOnly(root: Element): void {
238
+ for (
239
+ let templates = root.querySelectorAll<HTMLTemplateElement>(CLIENT_TEMPLATE);
240
+ templates.length;
241
+ templates = root.querySelectorAll<HTMLTemplateElement>(CLIENT_TEMPLATE)
242
+ ) {
243
+ for (const template of templates) {
244
+ for (let node = template.previousSibling; node; node = template.previousSibling) {
245
+ const marker = node.nodeType === COMMENT
246
+ const data = marker ? (node as Comment).data : ""
247
+ node.remove()
248
+ if (marker && data === CLIENT_MARKERS[0]) break
249
+ }
250
+ template.replaceWith(template.content)
251
+ }
252
+ }
253
+ }
254
+
255
+ export async function hydrate(ctx: ClientContext): Promise<void> {
256
+ await setAdapterInstance(ctx.app, null)
257
+ const watch = devHydration.watch?.(ctx.root, swapClientOnly)
258
+ ctx.app?.hooks?.hookOnce("app:mounted", () => swapClientOnly(ctx.root))
259
+ warnKeepAlive(ctx)
260
+ setRepaint(() => paint(ctx))
261
+ if (import.meta.hot) void import("./hmr.ts").then((hmr) => hmr.track(ctx, repaint))
262
+ // Rendered to a string that is thrown away: the composables meet their keys, so a restored entry gets its handler for
263
+ // `router.refresh(key)`, a deferred `server: false` run repaints when it settles, a live handler's entry follows its stream,
264
+ // a `useSyncedState` call opens its socket, the `useHead` entries the server wrote are pushed so the next `apply()` keeps their tags,
265
+ // and the `Link` states of the server's HTML are found by the same href and occurrence.
266
+ const data = ctx.payload.data as { $deferred?: unknown; $async?: Record<string, { live?: unknown }> } | undefined
267
+ const rendered =
268
+ data?.$deferred === true ||
269
+ Object.keys(data?.$async ?? {}).length > 0 ||
270
+ ctx.app?.state?.get(RERUN_STATE_KEY) === true ||
271
+ ctx.root.querySelector(`a[${LINK_STATE_ATTRIBUTE}]`)
272
+ takeIndicatorRendered()
273
+ takeAnnouncerRendered()
274
+ releaseAnnouncerClaims()
275
+ // In dev every first page renders its string, so the hydration report can compare it with the server's; a deferred value's placeholder differs by design.
276
+ if (rendered || watch) {
277
+ const out = renderOut()
278
+ const html = renderTree(ctx, entries, false, out)
279
+ if (data?.$deferred !== true) watch?.done(html)
280
+ if (out.linkStates.size) keepLinkStates(ctx.root, out.linkStates)
281
+ }
282
+ setCurrent(ctx)
283
+ if (takeIndicatorRendered() || (!rendered && ctx.root.querySelector(INDICATOR))) driveLoadingIndicators(ctx)
284
+ if (takeAnnouncerRendered() || (!rendered && ctx.root.querySelector(ANNOUNCER))) driveAnnouncers(ctx)
285
+ }
286
+
287
+ export async function mount(ctx: ClientContext): Promise<void> {
288
+ await setAdapterInstance(ctx.app, null)
289
+ warnKeepAlive(ctx)
290
+ paint(ctx)
291
+ setCurrent(ctx)
292
+ }
293
+
294
+ export function update(ctx: ClientContext): void {
295
+ warnKeepAlive(ctx)
296
+ paint(ctx, ctx.tree.components.at(-1)?.pending !== true)
297
+ setCurrent(ctx)
298
+ }
299
+
300
+ function findComment(parent: Node, data: string): Node | undefined {
301
+ for (const node of Array.from(parent.childNodes)) {
302
+ if (node.nodeType === COMMENT && (node as Comment).data === data) return node
303
+ const inner = node.nodeType === ELEMENT ? findComment(node, data) : undefined
304
+ if (inner) return inner
305
+ }
306
+ return undefined
307
+ }
308
+
309
+ function between(root: Element, [open, close]: readonly [string, string]): Element[] {
310
+ const start = findComment(root, open)
311
+ const found: Element[] = []
312
+ for (let node = start?.nextSibling ?? null; node; node = node.nextSibling) {
313
+ if (node.nodeType === COMMENT && (node as Comment).data === close) return found
314
+ if (node.nodeType === ELEMENT) found.push(node as Element)
315
+ }
316
+ return []
317
+ }
318
+
319
+ /** The element nodes between the page markers and between the layout markers of the HTML under `ctx.root`; a pair the HTML does not hold gives none. */
320
+ export function transitionTargets(ctx: ClientContext): { page: Element[]; layout: Element[] } {
321
+ return { page: between(ctx.root, PAGE_MARKERS), layout: between(ctx.root, LAYOUT_MARKERS) }
322
+ }
323
+
324
+ type Shown = { view: ServerComponentView } | { error: unknown } | "loading"
325
+
326
+ const shown = new WeakMap<AppContext, Map<string, Shown>>()
327
+
328
+ /**
329
+ * The client side of a server-only component. A paint is a string, so the answer of a component the browser has not
330
+ * seen is requested once and paints again; the server HTML of the page that loaded, and the markup of a server-only page the
331
+ * navigator fetched, are taken from the DOM and kept by name and props.
332
+ */
333
+ export function serverComponent(name: string): (props?: Record<string, unknown>) => string {
334
+ return (props = {}) => {
335
+ const state = currentState()
336
+ if (!state) throw new Error(`${name}.server must be rendered inside a Hamur app`)
337
+ const { app } = state
338
+ const text = isPage(name) ? "" : serverComponentProps(name, props)
339
+ const uid = serverComponentId(name, text)
340
+ let kept = shown.get(app)
341
+ if (!kept) shown.set(app, (kept = new Map()))
342
+ const key = `${name}\0${text}`
343
+ let entry = kept.get(key)
344
+ if (!entry || isPage(name)) {
345
+ const html = takeServerHTML(app, uid, name)
346
+ if (html !== undefined) kept.set(key, (entry = { view: { html } }))
347
+ }
348
+ if (!entry) {
349
+ kept.set(key, "loading")
350
+ fetchServerComponent(app, name, text)
351
+ .then(
352
+ (view) => kept.set(key, { view }),
353
+ (error: unknown) => kept.set(key, { error }),
354
+ )
355
+ .then(repaintPage)
356
+ return serverComponentHTML(name, uid, "")
357
+ }
358
+ if (entry === "loading") return serverComponentHTML(name, uid, "")
359
+ if ("error" in entry) throw entry.error
360
+ if (entry.view.head) state.entries?.push(state.head.push(entry.view.head))
361
+ return serverComponentHTML(name, uid, String(entry.view.html))
362
+ }
363
+ }
@@ -0,0 +1,38 @@
1
+ import type { ClientContext } from "hamur/adapter"
2
+ import type { HtmlComponent } from "../context.ts"
3
+
4
+ interface Slot {
5
+ impl: HtmlComponent
6
+ wrapper: HtmlComponent
7
+ }
8
+
9
+ const slots = new Map<string, Slot>()
10
+ let last: { ctx: ClientContext; repaint(ctx: ClientContext): void } | undefined
11
+
12
+ /** Called by the client entry on every hydrate, mount and update, so `rerender` knows the context on screen. */
13
+ export function track(ctx: ClientContext, repaint: (ctx: ClientContext) => void): void {
14
+ last = { ctx, repaint }
15
+ }
16
+
17
+ /** Paints the last context again after a page, layout or app module was re-evaluated; a throw reloads the document. */
18
+ export function rerender(): void {
19
+ if (!last) return location.reload()
20
+ try {
21
+ last.repaint(last.ctx)
22
+ } catch (error) {
23
+ console.error(error)
24
+ location.reload()
25
+ }
26
+ }
27
+
28
+ /** The module's default export under a stable identity: importers and the render tree keep calling the latest implementation. */
29
+ export function hot(id: string, impl: HtmlComponent): HtmlComponent {
30
+ if (typeof impl !== "function") return impl
31
+ let slot = slots.get(id)
32
+ if (!slot) {
33
+ const created: Slot = { impl, wrapper: (props) => created.impl(props) }
34
+ slots.set(id, (slot = created))
35
+ }
36
+ slot.impl = impl
37
+ return slot.wrapper
38
+ }
@@ -0,0 +1,12 @@
1
+ import { snapshotHydration } from "hamur/adapter/dev"
2
+ import { devHydration } from "./hydration.ts"
3
+
4
+ devHydration.devClient = true
5
+
6
+ /** The server's markup as the client renders it: each `ClientOnly` fallback already swapped for its children, on a copy. */
7
+ devHydration.watch = (root, swapClientOnly) => {
8
+ const copy = root.cloneNode(true) as Element
9
+ swapClientOnly(copy)
10
+ const snapshot = snapshotHydration(root, copy.innerHTML)
11
+ return { done: (client) => void snapshot.compare(undefined, client) }
12
+ }
@@ -0,0 +1,11 @@
1
+ /** What `hydration-dev.ts` hands the client runtime in `hamur dev`; a production client never sets it. */
2
+ export interface HydrationWatch {
3
+ /** The client's render string of the first page, compared with the server markup saved before. */
4
+ done(client: string): void
5
+ }
6
+
7
+ export const devHydration: {
8
+ watch?: (root: Element, swapClientOnly: (root: Element) => void) => HydrationWatch
9
+ /** `true` in the `hamur dev` client, where `import.meta.dev` is not defined, so `DevOnly` renders what the dev server rendered. */
10
+ devClient?: true
11
+ } = {}
@@ -0,0 +1,52 @@
1
+ import { setServerHTML } from "hamur/adapter"
2
+ import type { IslandContext } from "hamur/adapter"
3
+ import type { HtmlIsland } from "../island.ts"
4
+
5
+ const cleanups = new WeakMap<Element, () => void>()
6
+
7
+ const components = new WeakMap<Element, unknown>()
8
+
9
+ function start(el: Element, component: unknown, props: Record<string, unknown>): void {
10
+ components.set(el, component)
11
+ const cleanup = (component as HtmlIsland<Record<string, unknown>>).hydrate(el, props)
12
+ if (typeof cleanup === "function") cleanups.set(el, cleanup)
13
+ }
14
+
15
+ /** Hands the island's server HTML in `el` to its `hydrate`. */
16
+ export function hydrateIsland(
17
+ el: Element,
18
+ component: unknown,
19
+ props: Record<string, unknown>,
20
+ _ctx: IslandContext,
21
+ ): void {
22
+ start(el, component, props)
23
+ }
24
+
25
+ /** Writes the island's `render` into `el` in place of the fallback it holds, then hydrates it. */
26
+ export function mountIsland(
27
+ el: Element,
28
+ component: unknown,
29
+ props: Record<string, unknown>,
30
+ _ctx: IslandContext,
31
+ ): void {
32
+ el.replaceChildren()
33
+ setServerHTML(el, (component as HtmlIsland<Record<string, unknown>>).render(props))
34
+ start(el, component, props)
35
+ }
36
+
37
+ export function unmountIsland(el: Element): void {
38
+ cleanups.get(el)?.()
39
+ cleanups.delete(el)
40
+ components.delete(el)
41
+ }
42
+
43
+ /** Calls the island's `update` with the new props, or, without one, writes its `render` again and hydrates it anew. */
44
+ export function updateIsland(el: Element, props: Record<string, unknown>): void {
45
+ const component = components.get(el) as HtmlIsland<Record<string, unknown>> | undefined
46
+ if (!component) return
47
+ if (component.update) return component.update(el, props)
48
+ cleanups.get(el)?.()
49
+ cleanups.delete(el)
50
+ setServerHTML(el, component.render(props))
51
+ start(el, component, props)
52
+ }
@@ -0,0 +1,56 @@
1
+ import { renderInPasses, serverComponentProps, setAdapterInstance } from "hamur/adapter"
2
+ import type { ComponentRenderContext, RenderContext, RenderResult } from "hamur/adapter"
3
+ import { renderTree, type DeferredPart } from "../context.ts"
4
+ import { inIslandRoot } from "../island.ts"
5
+ import { collectingIslands, islandsSettled, renderSettled } from "../island-html.ts"
6
+ import { lazyModules } from "../lazy-hydration.ts"
7
+ import { isPage, serverComponentHTML, serverComponentId } from "../server-component.ts"
8
+
9
+ export async function render(ctx: RenderContext): Promise<RenderResult> {
10
+ await setAdapterInstance(ctx.app, null)
11
+ return renderInPasses<RenderResult>({
12
+ app: ctx.app,
13
+ head: ctx.head,
14
+ render: async (head) => {
15
+ await lazyModules()
16
+ const deferred: DeferredPart[] = []
17
+ const pending: Promise<void>[] = []
18
+ const body = collectingIslands(pending, () => renderTree({ ...ctx, head }, undefined, false, { deferred }))
19
+ await islandsSettled(ctx.app, pending)
20
+ return deferred.length ? { body, deferred } : { body }
21
+ },
22
+ })
23
+ }
24
+
25
+ /** `component` rendered with `props`: a function returning a string, or an object whose `render` is one. */
26
+ export async function renderComponent(
27
+ component: unknown,
28
+ props: Record<string, unknown>,
29
+ ctx?: ComponentRenderContext,
30
+ ): Promise<{ html: string }> {
31
+ const render = typeof component === "function" ? component : (component as { render?: unknown } | null)?.render
32
+ if (typeof render !== "function")
33
+ throw new TypeError(
34
+ "renderComponent of the html adapter takes a function returning a string, or an object with a render function",
35
+ )
36
+ const html = await renderSettled(() => {
37
+ const out: unknown = inIslandRoot(ctx, () => render.call(component, props))
38
+ if (typeof out !== "string")
39
+ throw new TypeError("renderComponent of the html adapter: the component must return a string")
40
+ return out
41
+ })
42
+ return { html }
43
+ }
44
+
45
+ /** The server side of a server-only component: its string inside `hamur-component`, its props checked as the client sends them. */
46
+ export function serverComponent(
47
+ name: string,
48
+ component: (props: Record<string, unknown>) => string,
49
+ ): (props?: Record<string, unknown>) => string {
50
+ return (props = {}) => {
51
+ const text = isPage(name) ? "" : serverComponentProps(name, props)
52
+ const output = component(props)
53
+ if (typeof output !== "string") throw new TypeError(`"${name}" must return a string`)
54
+ return serverComponentHTML(name, serverComponentId(name, text), output)
55
+ }
56
+ }
@@ -0,0 +1,12 @@
1
+ import { currentState } from "../context.ts"
2
+
3
+ const counts = new WeakMap<object, number>()
4
+ const outside = {}
5
+
6
+ /** Counted per render, so the server's markup and a repaint's agree. */
7
+ export function svgInstanceId(): string {
8
+ const render = currentState() ?? outside
9
+ const count = counts.get(render) ?? 0
10
+ counts.set(render, count + 1)
11
+ return `svg${count}`
12
+ }
@@ -0,0 +1,30 @@
1
+ import { serverComponentAttributes } from "hamur/adapter"
2
+ import { currentState } from "./context.ts"
3
+
4
+ const counts = new WeakMap<object, number>()
5
+ const outside = {}
6
+
7
+ const escape = (text: string): string => text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;")
8
+
9
+ function hashOf(text: string): string {
10
+ let hash = 0x811c9dc5
11
+ for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193)
12
+ return (hash >>> 0).toString(36)
13
+ }
14
+
15
+ /** html has no component ids: the position in the render and a hash of the name and props, so the browser takes the server HTML only for the same component with the same props. */
16
+ export function serverComponentId(name: string, text: string): string {
17
+ const render = currentState() ?? outside
18
+ const count = counts.get(render) ?? 0
19
+ counts.set(render, count + 1)
20
+ return `c${count}-${hashOf(`${name}\0${text}`)}`
21
+ }
22
+
23
+ export const isPage = (name: string): boolean => name.startsWith("page:")
24
+
25
+ export function serverComponentHTML(name: string, uid: string, html: string): string {
26
+ const attributes = Object.entries(serverComponentAttributes(name))
27
+ .map(([key, value]) => ` ${key}="${escape(value)}"`)
28
+ .join("")
29
+ return `<hamur-component name="${escape(name)}" uid="${uid}"${attributes}>${html}</hamur-component>`
30
+ }
package/src/svg.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { join } from "node:path"
2
+ import { svgCode, type SvgCode, type SvgNode, type SvgSource, type SvgValue } from "hamur/adapter"
3
+
4
+ const SVG_ID = join(import.meta.dir, "runtime/svg-id.ts")
5
+ const ESCAPES: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }
6
+ const escape = (text: string) => text.replace(/[&<>"]/g, (char) => ESCAPES[char]!)
7
+ const literal = (text: string) => text.replace(/[\\`]|\$\{/g, (found) => `\\${found}`)
8
+
9
+ const valueMarkup = (value: SvgValue): string =>
10
+ typeof value === "string"
11
+ ? literal(escape(value))
12
+ : value
13
+ .map((part) => (typeof part === "string" ? literal(escape(part)) : `\${uid}-${literal(escape(part.id))}`))
14
+ .join("")
15
+
16
+ function nodeMarkup(code: SvgCode, node: SvgNode): string {
17
+ if (typeof node === "string" || Array.isArray(node)) return valueMarkup(node)
18
+ const attributes = Object.entries(code.attrs(node))
19
+ .map(([name, value]) => ` ${name}="${valueMarkup(value)}"`)
20
+ .join("")
21
+ return `<${node.tag}${attributes}>${node.children.map((child) => nodeMarkup(code, child)).join("")}</${node.tag}>`
22
+ }
23
+
24
+ function module(svg: SvgSource): { contents: string; extension: string } {
25
+ const code = svgCode(svg, { title: "title", props: "rest" })
26
+ const hidden = code.hidden ? `${code.hidden} ? { "aria-hidden": "true" } : {}` : "{}"
27
+ const contents = `import { svgInstanceId } from ${JSON.stringify(SVG_ID)};
28
+
29
+ const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
30
+ const escape = (value) => String(value).replace(/[&<>"]/g, (char) => ESCAPES[char]);
31
+
32
+ export default function SvgComponent(props = {}) {
33
+ const { title, ...rest } = props;
34
+ const uid = svgInstanceId();
35
+ const attributes = {
36
+ ...${code.props(svg.attrs)},
37
+ ...(${hidden}),
38
+ ...rest,
39
+ };
40
+ let out = "";
41
+ for (const [name, value] of Object.entries(attributes)) {
42
+ if (value === undefined || value === null || value === false) continue;
43
+ out += value === true ? \` \${name}\` : \` \${name}="\${escape(value)}"\`;
44
+ }
45
+ return \`<svg\${out}>\${title == null ? "" : \`<title>\${escape(title)}</title>\`}\` + \`${svg.children.map((child) => nodeMarkup(code, child)).join("")}\` + "</svg>";
46
+ }
47
+ `
48
+ return { contents, extension: ".js" }
49
+ }
50
+
51
+ export const svgComponent = {
52
+ types: `(props?: Record<string, string | number | boolean> & { title?: string }) => string`,
53
+ module,
54
+ }