@hamur/adapter-solid 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +35 -2
  3. package/dist/chunks/browser-index-8rhv2s58.js +14 -0
  4. package/dist/chunks/browser-index-b05qbzsh.js +165 -0
  5. package/dist/chunks/browser-index-n80jt19y.js +114 -0
  6. package/dist/chunks/browser-index-ncnkshd9.js +39 -0
  7. package/dist/chunks/browser-index-r4jwfgh7.js +407 -0
  8. package/dist/src/adapter.js +556 -0
  9. package/dist/src/error-page.js +466 -0
  10. package/dist/src/index.js +1535 -0
  11. package/dist/src/keepalive.js +6 -0
  12. package/dist/src/runtime/client.js +174 -0
  13. package/dist/src/runtime/island.js +58 -0
  14. package/dist/src/runtime/server.js +138 -0
  15. package/dist/types/src/activation.d.ts +15 -0
  16. package/dist/types/src/adapter.d.ts +4 -0
  17. package/dist/types/src/async-data.d.ts +21 -0
  18. package/dist/types/src/client-component.d.ts +10 -0
  19. package/dist/types/src/client-fallback.d.ts +2 -0
  20. package/dist/types/src/context.d.ts +89 -0
  21. package/dist/types/src/error-page.d.ts +1 -0
  22. package/dist/types/src/index.d.ts +392 -0
  23. package/dist/types/src/island-html.d.ts +13 -0
  24. package/dist/types/src/island.d.ts +20 -0
  25. package/dist/types/src/jsx-locator.d.ts +6 -0
  26. package/dist/types/src/keepalive.d.ts +30 -0
  27. package/dist/types/src/lazy-hydration.d.ts +13 -0
  28. package/dist/types/src/markdown-page.d.ts +9 -0
  29. package/dist/types/src/markdown.d.ts +13 -0
  30. package/dist/types/src/plugin.d.ts +44 -0
  31. package/dist/types/src/runtime/client.d.ts +13 -0
  32. package/dist/types/src/runtime/hmr-solid.d.ts +5 -0
  33. package/dist/types/src/runtime/hmr.d.ts +27 -0
  34. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  35. package/dist/types/src/runtime/hydration.d.ts +10 -0
  36. package/dist/types/src/runtime/island.d.ts +8 -0
  37. package/dist/types/src/runtime/portal.d.ts +13 -0
  38. package/dist/types/src/runtime/server.d.ts +14 -0
  39. package/dist/types/src/runtime/trusted.d.ts +2 -0
  40. package/dist/types/src/server-island.d.ts +10 -0
  41. package/dist/types/src/svg.d.ts +10 -0
  42. package/package.json +74 -4
  43. package/src/activation.ts +51 -0
  44. package/src/adapter.ts +42 -0
  45. package/src/async-data.ts +105 -0
  46. package/src/client-component.ts +40 -0
  47. package/src/client-fallback.ts +2 -0
  48. package/src/context.ts +495 -0
  49. package/src/env.d.ts +3 -0
  50. package/src/error-page.ts +1 -0
  51. package/src/index.ts +1900 -0
  52. package/src/island-html.ts +58 -0
  53. package/src/island.ts +55 -0
  54. package/src/jsx-locator.ts +199 -0
  55. package/src/keepalive.ts +147 -0
  56. package/src/lazy-hydration.ts +146 -0
  57. package/src/markdown-page.ts +18 -0
  58. package/src/markdown.ts +70 -0
  59. package/src/plugin.ts +310 -0
  60. package/src/runtime/client.ts +175 -0
  61. package/src/runtime/hmr-solid.ts +19 -0
  62. package/src/runtime/hmr.ts +231 -0
  63. package/src/runtime/hydration-dev.ts +41 -0
  64. package/src/runtime/hydration.ts +9 -0
  65. package/src/runtime/island.ts +66 -0
  66. package/src/runtime/portal.ts +64 -0
  67. package/src/runtime/server.ts +160 -0
  68. package/src/runtime/trusted.ts +16 -0
  69. package/src/server-island.ts +47 -0
  70. package/src/solid.d.ts +4 -0
  71. package/src/svg.ts +53 -0
  72. package/src/webmcp.d.ts +20 -0
@@ -0,0 +1,58 @@
1
+ import { markWaiting } from "hamur/adapter"
2
+ import type { AppContext } from "hamur/app"
3
+
4
+ type Outcome = { value: unknown } | { error: unknown }
5
+
6
+ const outcomes = new WeakMap<Promise<unknown>, Outcome>()
7
+ let current: Promise<void>[] | undefined
8
+
9
+ /**
10
+ * The HTML of an island whose root has finished rendering (or the attributes of a server island), or `undefined` while it renders, recorded in `pending`
11
+ * so the render is done again once it has settled. A failed island throws where its `Island` renders, so the nearest
12
+ * route boundary shows the error. An island's HTML is always rendered in its place, never spliced into the markup.
13
+ */
14
+ export function settledIsland<T = string>(
15
+ promise: Promise<T>,
16
+ pending: Promise<void>[] | undefined = current,
17
+ ): T | undefined {
18
+ const outcome = outcomes.get(promise)
19
+ if (outcome) {
20
+ if ("error" in outcome) throw outcome.error
21
+ return outcome.value as T
22
+ }
23
+ pending?.push(
24
+ promise.then(
25
+ (value) => void outcomes.set(promise, { value }),
26
+ (error: unknown) => void outcomes.set(promise, { error }),
27
+ ),
28
+ )
29
+ return undefined
30
+ }
31
+
32
+ /** Runs a synchronous render whose `Island`s record the islands still rendering in `pending`. */
33
+ export function collectingIslands<T>(pending: Promise<void>[], render: () => T): T {
34
+ const outer = current
35
+ current = pending
36
+ try {
37
+ return render()
38
+ } finally {
39
+ current = outer
40
+ }
41
+ }
42
+
43
+ /** A pass of `renderInPasses` that met islands still rendering waits for them and is dropped, so the next pass renders them in place. */
44
+ export async function islandsSettled(app: AppContext, pending: Promise<void>[]): Promise<void> {
45
+ if (!pending.length) return
46
+ await Promise.all(pending)
47
+ markWaiting(app.asyncData)
48
+ }
49
+
50
+ /** An island's own root, rendered again until every island inside it has settled. */
51
+ export async function renderSettled<T>(render: (pending: Promise<void>[]) => T | Promise<T>): Promise<T> {
52
+ for (;;) {
53
+ const pending: Promise<void>[] = []
54
+ const result = await collectingIslands(pending, () => render(pending))
55
+ if (!pending.length) return result
56
+ await Promise.all(pending)
57
+ }
58
+ }
package/src/island.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { createComponent, createUniqueId, useContext } from "solid-js"
2
+ import type { Component } from "solid-js"
3
+ import { dynamic, isServer } from "@solidjs/web"
4
+ import type { JSX } from "@solidjs/web"
5
+ import { ISLAND_ELEMENT, renderIsland, type IslandOn } from "hamur/adapter"
6
+ import { AppContext } from "./context.ts"
7
+ import { settledIsland } from "./island-html.ts"
8
+
9
+ const IslandElement = dynamic(() => ISLAND_ELEMENT, { static: true }) as Component<Record<string, unknown>>
10
+
11
+ export interface IslandProps<P extends Record<string, any>> {
12
+ /** The default export of a file under `app/islands/`. */
13
+ component: Component<P>
14
+ props?: P
15
+ /** The island directive: when the island hydrates, `"only"` to mount it in the browser alone, or a directive a module adds; default `"load"`. */
16
+ on?: IslandOn
17
+ /** The island's id across swaps; a swap to a page with the same id keeps its element and state. */
18
+ persist?: string
19
+ /** With `persist`, a swap keeps the island's old props. */
20
+ persistProps?: boolean
21
+ /** What the server renders in place of the island under `on="only"`. */
22
+ fallback?: JSX.Element
23
+ /** Rendered on the server only and given to the island as its `children`, inside `<hamur-slot>`; never hydrated. */
24
+ children?: JSX.Element
25
+ }
26
+
27
+ /** On an island page, `component` rendered as a root of its own inside `<hamur-island>`, hydrated on its own in the browser. */
28
+ export function Island<P extends Record<string, any>>(props: IslandProps<P>): JSX.Element {
29
+ const state = useContext(AppContext)
30
+ if (!state) throw new Error("Island must be rendered inside a Hamur app")
31
+ const id = createUniqueId()
32
+ // In the browser an Island only runs inside an island that hydrates: an element with no children keeps the inner element's server HTML.
33
+ if (!isServer) return createComponent(IslandElement, {})
34
+ const app = state().app
35
+ // `children` is read only inside the slot's own root, so the page never renders it in place.
36
+ const slot = "children" in props ? { component: () => props.children } : undefined
37
+ const island = renderIsland(
38
+ app,
39
+ id,
40
+ props.component,
41
+ (props.props ?? {}) as Record<string, unknown>,
42
+ props.on,
43
+ slot,
44
+ { persist: props.persist, persistProps: props.persistProps },
45
+ )
46
+ if (!island.html) {
47
+ return createComponent(IslandElement, {
48
+ ...island.attributes,
49
+ get children() {
50
+ return props.fallback
51
+ },
52
+ })
53
+ }
54
+ return createComponent(IslandElement, { innerHTML: settledIsland(island.html) ?? "", ...island.attributes })
55
+ }
@@ -0,0 +1,199 @@
1
+ const ATTRIBUTE = "data-hamur-src"
2
+ const CONTROL = new Set(["if", "for", "while", "switch", "catch", "with"])
3
+ const HOST_TAG = /^[a-z][a-z0-9-]*$/
4
+ const FUNCTION = /^(?:export\s+)?(default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)?\s*(?:<[^>(]*>)?\s*\(/gm
5
+ const ARROW_DECLARATION =
6
+ /^(?:export\s+)?(?:const|let|var)\s+[A-Z][\w$]*\s*(?::[^=\n]+)?=\s*(?:(?:React\.)?(?:memo|forwardRef)\s*\(\s*)?(?:async\s+)?/gm
7
+ const DEFAULT_ARROW = /^export\s+default\s+(?:async\s+)?(?=\(|[A-Za-z_$][\w$]*\s*=>)/gm
8
+ const FUNCTION_EXPRESSION = /function\s*\*?\s*[\w$]*\s*(?:<[^>(]*>)?\s*\(/y
9
+ const BLOCK_AFTER_PARAMS = /\s*(?::[^{;]*?)?\s*\{/y
10
+ const ARROW_AFTER_PARAMS = /\s*(?::[^=]*?)?=>\s*/y
11
+ const BARE_ARROW = /[A-Za-z_$][\w$]*\s*=>\s*/y
12
+
13
+ /** The index after the string, comment or template that starts at `i`, or `i` when none does. */
14
+ function skip(source: string, i: number): number {
15
+ const char = source[i]
16
+ if (char === "/" && source[i + 1] === "/") {
17
+ const end = source.indexOf("\n", i)
18
+ return end === -1 ? source.length : end
19
+ }
20
+ if (char === "/" && source[i + 1] === "*") {
21
+ const end = source.indexOf("*/", i + 2)
22
+ return end === -1 ? source.length : end + 2
23
+ }
24
+ if (char === '"' || char === "'") {
25
+ let j = i + 1
26
+ while (j < source.length && source[j] !== char && source[j] !== "\n") j += source[j] === "\\" ? 2 : 1
27
+ return source[j] === char ? j + 1 : j
28
+ }
29
+ if (char === "`") {
30
+ let j = i + 1
31
+ while (j < source.length && source[j] !== "`") {
32
+ if (source[j] === "\\") j += 2
33
+ else if (source[j] === "$" && source[j + 1] === "{") {
34
+ const end = matching(source, j + 1)
35
+ j = end === -1 ? source.length : end + 1
36
+ } else j++
37
+ }
38
+ return j + 1
39
+ }
40
+ return i
41
+ }
42
+
43
+ /** The index of the bracket that closes the one at `open`, or -1. */
44
+ function matching(source: string, open: number): number {
45
+ const up = source[open]!
46
+ const down = up === "(" ? ")" : up === "{" ? "}" : "]"
47
+ let depth = 0
48
+ for (let i = open; i < source.length;) {
49
+ const next = skip(source, i)
50
+ if (next !== i) {
51
+ i = next
52
+ continue
53
+ }
54
+ if (source[i] === up) depth++
55
+ else if (source[i] === down && --depth === 0) return i
56
+ i++
57
+ }
58
+ return -1
59
+ }
60
+
61
+ /** Whether the `{` at `at` opens a function body, as opposed to a block, an object or a JSX expression. */
62
+ function opensFunction(source: string, at: number): boolean {
63
+ let j = at - 1
64
+ while (j >= 0 && /\s/.test(source[j]!)) j--
65
+ if (source[j] === ">" && source[j - 1] === "=") return true
66
+ if (source[j] !== ")") return false
67
+ let depth = 0
68
+ for (; j >= 0; j--) {
69
+ if (source[j] === ")") depth++
70
+ else if (source[j] === "(" && --depth === 0) break
71
+ }
72
+ const word = /([\w$]+)\s*$/.exec(source.slice(Math.max(0, j - 40), j))?.[1]
73
+ return word === undefined || !CONTROL.has(word)
74
+ }
75
+
76
+ /** The index after each `return` in the function body that opens at `open`, leaving out the returns of nested functions. */
77
+ function returnsOf(source: string, open: number, close: number): number[] {
78
+ const found: number[] = []
79
+ const nested: boolean[] = []
80
+ let depth = 0
81
+ for (let i = open + 1; i < close;) {
82
+ const next = skip(source, i)
83
+ if (next !== i) {
84
+ i = next
85
+ continue
86
+ }
87
+ const char = source[i]!
88
+ if (char === "{") {
89
+ const fn = opensFunction(source, i)
90
+ nested.push(fn)
91
+ if (fn) depth++
92
+ } else if (char === "}") {
93
+ if (nested.pop()) depth--
94
+ } else if (
95
+ depth === 0 &&
96
+ char === "r" &&
97
+ source.startsWith("return", i) &&
98
+ !/[\w$.]/.test(source[i - 1] ?? "") &&
99
+ !/[\w$]/.test(source[i + 6] ?? "")
100
+ ) {
101
+ found.push(i + 6)
102
+ i += 6
103
+ continue
104
+ }
105
+ i++
106
+ }
107
+ return found
108
+ }
109
+
110
+ /** The `<` and the end of the name when a host element starts at `from`, past whitespace and opening parentheses. */
111
+ function hostRoot(source: string, from: number): { start: number; nameEnd: number } | undefined {
112
+ let i = from
113
+ while (/[\s(]/.test(source[i] ?? "")) i++
114
+ if (source[i] !== "<") return undefined
115
+ const name = /^<([A-Za-z][\w.:-]*)(?=[\s/>])/.exec(source.slice(i, i + 80))?.[1]
116
+ return name !== undefined && HOST_TAG.test(name) ? { start: i, nameEnd: i + 1 + name.length } : undefined
117
+ }
118
+
119
+ /** From `at`, a function's body: where its roots are searched. */
120
+ function rootsFrom(source: string, at: number): Array<{ start: number; nameEnd: number }> {
121
+ const block = /\s*/y
122
+ block.lastIndex = at
123
+ block.exec(source)
124
+ const start = block.lastIndex
125
+ if (source[start] !== "{") {
126
+ const root = hostRoot(source, start)
127
+ return root ? [root] : []
128
+ }
129
+ const close = matching(source, start)
130
+ if (close === -1) return []
131
+ return returnsOf(source, start, close).flatMap((index) => hostRoot(source, index) ?? [])
132
+ }
133
+
134
+ /** The place after the parameters of a function that starts at `at`: its body, or `undefined` when `at` is not a function. */
135
+ function bodyAt(source: string, at: number): number | undefined {
136
+ if (source.startsWith("function", at)) {
137
+ FUNCTION_EXPRESSION.lastIndex = at
138
+ if (!FUNCTION_EXPRESSION.test(source)) return undefined
139
+ return afterParams(source, FUNCTION_EXPRESSION.lastIndex - 1, BLOCK_AFTER_PARAMS)
140
+ }
141
+ if (source[at] === "(") return afterParams(source, at, ARROW_AFTER_PARAMS)
142
+ BARE_ARROW.lastIndex = at
143
+ return BARE_ARROW.test(source) ? BARE_ARROW.lastIndex : undefined
144
+ }
145
+
146
+ function afterParams(source: string, open: number, next: RegExp): number | undefined {
147
+ const close = matching(source, open)
148
+ if (close === -1) return undefined
149
+ next.lastIndex = close + 1
150
+ if (!next.test(source)) return undefined
151
+ return next === BLOCK_AFTER_PARAMS ? next.lastIndex - 1 : next.lastIndex
152
+ }
153
+
154
+ /**
155
+ * The source locator: adds `data-hamur-src="<file>:<line>:<column>"` to the host element each component of
156
+ * `source` returns from its own body (a capitalised function or arrow, a default export, `memo` and `forwardRef`
157
+ * around one); the position is the element's `<`, 1-based. Insertions stay on their line, so no line moves.
158
+ */
159
+ export function locateJsx(source: string, file: string): string {
160
+ if (!source.includes("<")) return source
161
+ const starts: number[] = []
162
+ for (const match of source.matchAll(FUNCTION)) {
163
+ if (match[1] === undefined && !/^[A-Z]/.test(match[2] ?? "")) continue
164
+ const body = afterParams(source, match.index + match[0].length - 1, BLOCK_AFTER_PARAMS)
165
+ if (body !== undefined) starts.push(body)
166
+ }
167
+ for (const pattern of [ARROW_DECLARATION, DEFAULT_ARROW]) {
168
+ for (const match of source.matchAll(pattern)) {
169
+ const body = bodyAt(source, match.index + match[0].length)
170
+ if (body !== undefined) starts.push(body)
171
+ }
172
+ }
173
+ const roots = new Map<number, { start: number; nameEnd: number }>()
174
+ for (const start of starts) for (const root of rootsFrom(source, start)) roots.set(root.start, root)
175
+ if (roots.size === 0) return source
176
+ const lineStarts = [0]
177
+ for (let i = source.indexOf("\n"); i !== -1; i = source.indexOf("\n", i + 1)) lineStarts.push(i + 1)
178
+ let out = ""
179
+ let last = 0
180
+ for (const { start, nameEnd } of [...roots.values()].sort((a, b) => a.start - b.start)) {
181
+ if (
182
+ source
183
+ .slice(nameEnd, nameEnd + 200)
184
+ .split(">", 1)[0]!
185
+ .includes(ATTRIBUTE)
186
+ )
187
+ continue
188
+ let low = 0
189
+ let high = lineStarts.length - 1
190
+ while (low < high) {
191
+ const mid = (low + high + 1) >> 1
192
+ if (lineStarts[mid]! <= start) low = mid
193
+ else high = mid - 1
194
+ }
195
+ out += `${source.slice(last, nameEnd)} ${ATTRIBUTE}="${file}:${low + 1}:${start - lineStarts[low]! + 1}"`
196
+ last = nameEnd
197
+ }
198
+ return out + source.slice(last)
199
+ }
@@ -0,0 +1,147 @@
1
+ import type {
2
+ Accessor,
3
+ Component,
4
+ Context,
5
+ createComponent,
6
+ createEffect,
7
+ createMemo,
8
+ mapArray,
9
+ onCleanup,
10
+ untrack,
11
+ useContext,
12
+ } from "solid-js"
13
+ import type { JSX, dynamic } from "@solidjs/web"
14
+ import type { KeptUnit } from "hamur/adapter"
15
+ import type { Activation, activation, detach, setHidden } from "./activation.ts"
16
+ import type { AppState, Props, routeValue } from "./context.ts"
17
+
18
+ /** What the outlet takes from the adapter's base: this module imports nothing at run time, so loading it splits no chunk of the base. */
19
+ export interface KeepAliveBase {
20
+ createComponent: typeof createComponent
21
+ createEffect: typeof createEffect
22
+ createMemo: typeof createMemo
23
+ mapArray: typeof mapArray
24
+ onCleanup: typeof onCleanup
25
+ untrack: typeof untrack
26
+ useContext: typeof useContext
27
+ dynamic: typeof dynamic
28
+ ActivationContext: Context<Activation | null>
29
+ AppContext: Context<Accessor<AppState> | null>
30
+ activation: typeof activation
31
+ detach: typeof detach
32
+ setHidden: typeof setHidden
33
+ routeValue: typeof routeValue
34
+ holderOf(state: AppState, index: number): { kept?: KeptUnit[] } | undefined
35
+ Nest(props: Props & { bare?: boolean }): JSX.Element
36
+ }
37
+
38
+ const SHOWN = "\0shown"
39
+
40
+ /** A place that renders a page level while keep-alive is on: each kept unit, then the current entry, keyed by the keep-alive key. */
41
+ export function createKeptOutlet({
42
+ createComponent,
43
+ createEffect,
44
+ createMemo,
45
+ mapArray,
46
+ onCleanup,
47
+ untrack,
48
+ useContext,
49
+ dynamic,
50
+ ActivationContext,
51
+ AppContext,
52
+ activation,
53
+ detach,
54
+ setHidden,
55
+ routeValue,
56
+ holderOf,
57
+ Nest,
58
+ }: KeepAliveBase): (props: Props) => JSX.Element {
59
+ const keptStates = new WeakMap<KeptUnit, AppState>()
60
+ const Div = dynamic(() => "div", { static: true }) as Component<Record<string, unknown>>
61
+
62
+ /** The app state a kept unit renders with while hidden: the route, payload and tree it was last shown with. */
63
+ function keptState(state: AppState, unit: KeptUnit): AppState {
64
+ let own = keptStates.get(unit)
65
+ if (!own) {
66
+ const { data = {}, handlerState } = unit.payload as { data?: Record<string, unknown>; handlerState?: unknown }
67
+ keptStates.set(
68
+ unit,
69
+ (own = {
70
+ ...state,
71
+ route: routeValue({ route: unit.route, payload: unit.payload, tree: unit.tree, app: state.app }),
72
+ components: unit.tree.components,
73
+ data,
74
+ handlerState,
75
+ tree: unit.tree,
76
+ }),
77
+ )
78
+ }
79
+ return own
80
+ }
81
+
82
+ /** One keep-alive page, `display:contents` while shown and `hidden` while kept, with the same instance in both. */
83
+ function KeptPage(props: Props, key: string): JSX.Element {
84
+ const unit = createMemo(() => holderOf(props.state(), props.index)?.kept?.find((item) => item.key === key))
85
+ const state = createMemo(() => {
86
+ const current = unit()
87
+ return current ? keptState(untrack(props.state), current) : props.state()
88
+ })
89
+ const own = activation(useContext(ActivationContext) ?? undefined, untrack(unit) !== undefined)
90
+ createEffect(
91
+ () => unit() !== undefined,
92
+ (hidden) => setHidden(own, hidden),
93
+ )
94
+ onCleanup(() => detach(own))
95
+ return createComponent(ActivationContext, {
96
+ value: own,
97
+ get children() {
98
+ return createComponent(AppContext, {
99
+ value: state,
100
+ get children() {
101
+ return createComponent(Div, {
102
+ "data-hamur-keepalive": key,
103
+ get hidden() {
104
+ return unit() ? true : undefined
105
+ },
106
+ get style() {
107
+ return unit() ? undefined : "display:contents"
108
+ },
109
+ get children() {
110
+ return createComponent(Nest, {
111
+ state,
112
+ get index() {
113
+ return unit() ? 0 : props.index
114
+ },
115
+ bare: true,
116
+ })
117
+ },
118
+ })
119
+ },
120
+ })
121
+ },
122
+ })
123
+ }
124
+
125
+ return (props) => {
126
+ const keys = createMemo(() => {
127
+ const state = props.state()
128
+ const list = (holderOf(state, props.index)?.kept ?? []).map((unit) => unit.key)
129
+ const entry = state.components[props.index]
130
+ if (entry) list.push(entry.keepalive ?? SHOWN)
131
+ return list
132
+ })
133
+ return createMemo(
134
+ mapArray(keys, (key) =>
135
+ key === SHOWN
136
+ ? createComponent(Nest, {
137
+ state: props.state,
138
+ get index() {
139
+ return props.index
140
+ },
141
+ bare: true,
142
+ })
143
+ : KeptPage(props, key),
144
+ ),
145
+ ) as unknown as JSX.Element
146
+ }
147
+ }
@@ -0,0 +1,146 @@
1
+ import {
2
+ createComponent,
3
+ createEffect,
4
+ createMemo,
5
+ createSignal,
6
+ flush,
7
+ isHydrating,
8
+ omit,
9
+ onCleanup,
10
+ untrack,
11
+ useContext,
12
+ } from "solid-js"
13
+ import type { Component } from "solid-js"
14
+ import { enableServerComponentHydration, sharedConfig } from "solid-js/internal"
15
+ import { dynamic, isServer } from "@solidjs/web"
16
+ import type { JSX } from "@solidjs/web"
17
+ import { HYDRATE_ELEMENT, hydrateOnAttribute, markWaiting, replayInteraction, whenTriggered } from "hamur/adapter"
18
+ import type { HydrateOn, HydrateOnOptions } from "hamur/adapter"
19
+ import { AppContext, NeverHydratedContext } from "./context.ts"
20
+
21
+ type Props = Record<string, any>
22
+ type Module<P extends Props> = { default: Component<P> }
23
+
24
+ const pending = new Set<Promise<unknown>>()
25
+ const HydrateElement = dynamic(() => HYDRATE_ELEMENT, { static: true }) as Component<Record<string, unknown>>
26
+
27
+ type HydrateWindow = (id: 0, fn: () => JSX.Element, scope: { registry: Map<string, object> }) => JSX.Element
28
+
29
+ /**
30
+ * Renders `fn` against the server nodes under `wrapper` after Solid's own hydration ended, as Solid does for
31
+ * a boundary that resolves late: `sharedConfig.hydrateWindow` claims the nodes of the registry it is given.
32
+ */
33
+ function hydrateLate(wrapper: Element, fn: () => JSX.Element): JSX.Element {
34
+ enableServerComponentHydration()
35
+ const registry = new Map<string, object>()
36
+ for (const node of wrapper.querySelectorAll("[_hk]")) {
37
+ const key = node.getAttribute("_hk")!
38
+ if (!registry.has(key)) registry.set(key, node)
39
+ }
40
+ return (sharedConfig as { hydrateWindow: HydrateWindow }).hydrateWindow(0, fn, { registry })
41
+ }
42
+
43
+ /** The server renders synchronously, so `render` awaits the lazy modules still loading before each pass. */
44
+ export function lazyModules(): Promise<unknown> | undefined {
45
+ return pending.size ? Promise.allSettled(pending) : undefined
46
+ }
47
+
48
+ /** Renders the component on the server and, after hydration, keeps its server DOM until `on` fires; after a client navigation it mounts at once. */
49
+ export function defineLazyHydrationComponent<P extends Props>(
50
+ on: HydrateOn,
51
+ loader: () => Promise<Module<P>>,
52
+ options: Omit<HydrateOnOptions, "signal"> = {},
53
+ ): Component<P & { onHydrated?: () => void }> {
54
+ const attribute = hydrateOnAttribute(on)
55
+ let resolved: Module<P> | undefined
56
+ let failed: { error: unknown } | undefined
57
+ let loading: Promise<Module<P>> | undefined
58
+ const load = (): Promise<Module<P>> => {
59
+ if (loading) return loading
60
+ const current = (loading = loader().then(
61
+ (loaded) => (resolved = loaded),
62
+ (error: unknown) => {
63
+ if (isServer) failed = { error }
64
+ loading = undefined
65
+ throw error
66
+ },
67
+ ))
68
+ if (isServer) {
69
+ pending.add(current)
70
+ void current.then(
71
+ () => pending.delete(current),
72
+ () => pending.delete(current),
73
+ )
74
+ }
75
+ return current
76
+ }
77
+ if (isServer) void load().catch(() => {})
78
+
79
+ return (props) => {
80
+ const rest = omit(props, "onHydrated")
81
+ if (isServer) {
82
+ const state = useContext(AppContext)
83
+ return createComponent(HydrateElement, {
84
+ on: attribute,
85
+ // The part renders under an owner of its own on both sides, the client's memo that shows it once triggered.
86
+ children: createMemo(() => {
87
+ if (failed) throw failed.error
88
+ if (resolved) {
89
+ const part = resolved.default
90
+ if (on !== "never") return createComponent(part, rest as unknown as P)
91
+ return createComponent(NeverHydratedContext, {
92
+ value: true,
93
+ get children() {
94
+ return createComponent(part, rest as unknown as P)
95
+ },
96
+ })
97
+ }
98
+ if (state) markWaiting(state().app.asyncData)
99
+ void load().catch(() => {})
100
+ return ""
101
+ }),
102
+ })
103
+ }
104
+ let wrapper: HTMLElement | undefined
105
+ let served: boolean | undefined
106
+ const [shown, setShown] = createSignal<Module<P> | undefined>(isHydrating() ? undefined : resolved)
107
+ const controller = new AbortController()
108
+ onCleanup(() => controller.abort())
109
+ const show = (loaded: Module<P>) => {
110
+ if (controller.signal.aborted) return
111
+ setShown(() => loaded)
112
+ flush()
113
+ props.onHydrated?.()
114
+ if (wrapper) replayInteraction(wrapper)
115
+ }
116
+ // The server creates no effect here: a transparent one takes no hydration key, so the part's keys stay the server's.
117
+ createEffect(
118
+ () => undefined,
119
+ () => {
120
+ if (untrack(shown)) {
121
+ props.onHydrated?.()
122
+ return
123
+ }
124
+ void (
125
+ served && wrapper ? whenTriggered(wrapper, on, { ...options, signal: controller.signal }).then(load) : load()
126
+ ).then(show)
127
+ },
128
+ { transparent: true },
129
+ )
130
+ // Solid's own `lazy` holds the page's hydration until it loads; the gate keeps the child's server HTML and hydrates it once shown.
131
+ const child = (): JSX.Element => {
132
+ const loaded = shown()
133
+ if (!loaded) {
134
+ served ??= isHydrating()
135
+ return ""
136
+ }
137
+ const render = () => createComponent(loaded.default, rest as unknown as P)
138
+ return served && wrapper && !isHydrating() ? hydrateLate(wrapper, render) : render()
139
+ }
140
+ return createComponent(HydrateElement, {
141
+ on: attribute,
142
+ ref: (element: HTMLElement) => (wrapper = element),
143
+ children: createMemo(child),
144
+ })
145
+ }
146
+ }
@@ -0,0 +1,18 @@
1
+ import { markdownPageCode } from "hamur/adapter/build"
2
+ import type { MarkdownSource } from "hamur/adapter"
3
+
4
+ function module(source: MarkdownSource): { contents: string; extension: string } {
5
+ const { imports, value, props, head } = markdownPageCode(source)
6
+ const contents = `${imports}import { createComponent } from "solid-js";
7
+ import { MarkdownRenderer, useHead } from "@hamur/adapter-solid";
8
+
9
+ const value = ${value};
10
+
11
+ export default function MarkdownPage() {
12
+ ${head ? ` useHead(${head});\n` : ""} return createComponent(MarkdownRenderer, ${props});
13
+ }
14
+ `
15
+ return { contents, extension: ".js" }
16
+ }
17
+
18
+ export const markdownComponent = { module }