@hamur/adapter-preact 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.
- package/LICENSE +22 -0
- package/README.md +35 -2
- package/dist/chunks/browser-index-89d71ade.js +118 -0
- package/dist/chunks/browser-index-ezte15pp.js +67 -0
- package/dist/chunks/browser-index-hsy7tnbg.js +21 -0
- package/dist/chunks/browser-index-k3m2axbw.js +274 -0
- package/dist/src/adapter.js +456 -0
- package/dist/src/error-page.js +391 -0
- package/dist/src/index.js +1506 -0
- package/dist/src/keepalive.js +6 -0
- package/dist/src/runtime/client.js +96 -0
- package/dist/src/runtime/island.js +33 -0
- package/dist/src/runtime/server.js +95 -0
- package/dist/types/src/activation.d.ts +15 -0
- package/dist/types/src/adapter.d.ts +2 -0
- package/dist/types/src/async-data.d.ts +13 -0
- package/dist/types/src/client-component.d.ts +11 -0
- package/dist/types/src/client-fallback.d.ts +2 -0
- package/dist/types/src/context.d.ts +81 -0
- package/dist/types/src/error-page.d.ts +1 -0
- package/dist/types/src/head.d.ts +5 -0
- package/dist/types/src/index.d.ts +429 -0
- package/dist/types/src/island-html.d.ts +13 -0
- package/dist/types/src/island.d.ts +19 -0
- package/dist/types/src/jsx-locator.d.ts +6 -0
- package/dist/types/src/keepalive.d.ts +26 -0
- package/dist/types/src/lazy-hydration.d.ts +12 -0
- package/dist/types/src/markdown-page.d.ts +9 -0
- package/dist/types/src/markdown.d.ts +12 -0
- package/dist/types/src/plugin.d.ts +36 -0
- package/dist/types/src/route-boundary.d.ts +41 -0
- package/dist/types/src/runtime/client.d.ts +10 -0
- package/dist/types/src/runtime/hmr.d.ts +31 -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 +11 -0
- package/dist/types/src/server-island.d.ts +10 -0
- package/dist/types/src/svg.d.ts +10 -0
- package/package.json +50 -4
- package/src/activation.ts +51 -0
- package/src/adapter.ts +35 -0
- package/src/async-data.ts +65 -0
- package/src/client-component.ts +23 -0
- package/src/client-fallback.ts +2 -0
- package/src/context.ts +372 -0
- package/src/env.d.ts +3 -0
- package/src/error-page.ts +1 -0
- package/src/head.ts +34 -0
- package/src/index.ts +1868 -0
- package/src/island-html.ts +58 -0
- package/src/island.ts +56 -0
- package/src/jsx-locator.ts +199 -0
- package/src/keepalive.ts +100 -0
- package/src/lazy-hydration.ts +101 -0
- package/src/markdown-page.ts +18 -0
- package/src/markdown.ts +58 -0
- package/src/plugin.ts +231 -0
- package/src/route-boundary.ts +51 -0
- package/src/runtime/client.ts +85 -0
- package/src/runtime/hmr.ts +141 -0
- package/src/runtime/hydration-dev.ts +8 -0
- package/src/runtime/hydration.ts +7 -0
- package/src/runtime/island.ts +37 -0
- package/src/runtime/server.ts +102 -0
- package/src/server-island.ts +35 -0
- package/src/svg.ts +27 -0
- package/src/webmcp.d.ts +18 -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,56 @@
|
|
|
1
|
+
import { h } from "preact"
|
|
2
|
+
import type { ComponentChild, ComponentType } from "preact"
|
|
3
|
+
import { useContext, useId } from "preact/hooks"
|
|
4
|
+
import { ISLAND_ELEMENT, renderIsland, type IslandOn } from "hamur/adapter"
|
|
5
|
+
import { AppContextContext } from "./context.ts"
|
|
6
|
+
import { settledIsland } from "./island-html.ts"
|
|
7
|
+
|
|
8
|
+
const isServer = typeof window === "undefined"
|
|
9
|
+
const KEPT = { __html: "" }
|
|
10
|
+
|
|
11
|
+
export interface IslandProps<P extends object> {
|
|
12
|
+
/** The default export of a file under `app/islands/`. */
|
|
13
|
+
component: ComponentType<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?: ComponentChild
|
|
23
|
+
/** Rendered on the server only and given to the island as its `children`, inside `<hamur-slot>`; never hydrated. */
|
|
24
|
+
children?: ComponentChild
|
|
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 object>({
|
|
29
|
+
component,
|
|
30
|
+
props,
|
|
31
|
+
on,
|
|
32
|
+
fallback,
|
|
33
|
+
children,
|
|
34
|
+
persist,
|
|
35
|
+
persistProps,
|
|
36
|
+
}: IslandProps<P>): ComponentChild {
|
|
37
|
+
const app = useContext(AppContextContext)
|
|
38
|
+
if (!app) throw new Error("Island must be rendered inside a Hamur app")
|
|
39
|
+
const id = useId()
|
|
40
|
+
// In the browser an Island only runs inside an island that hydrates, where Preact keeps the inner element's server HTML.
|
|
41
|
+
if (!isServer) return h(ISLAND_ELEMENT, { dangerouslySetInnerHTML: KEPT })
|
|
42
|
+
const island = renderIsland(
|
|
43
|
+
app,
|
|
44
|
+
id,
|
|
45
|
+
component,
|
|
46
|
+
(props ?? {}) as Record<string, unknown>,
|
|
47
|
+
on,
|
|
48
|
+
children === undefined ? undefined : { component: () => children },
|
|
49
|
+
{ persist, persistProps },
|
|
50
|
+
)
|
|
51
|
+
if (!island.html) return h(ISLAND_ELEMENT, island.attributes, fallback)
|
|
52
|
+
return h(ISLAND_ELEMENT, {
|
|
53
|
+
...island.attributes,
|
|
54
|
+
dangerouslySetInnerHTML: { __html: settledIsland(island.html) ?? "" },
|
|
55
|
+
})
|
|
56
|
+
}
|
|
@@ -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
|
+
}
|
package/src/keepalive.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { ComponentChildren, Context, VNode, createElement, Fragment } from "preact"
|
|
2
|
+
import type { useContext, useLayoutEffect, useMemo } from "preact/hooks"
|
|
3
|
+
import type { KeptUnit, RenderEntry, RenderTree, RouteValue } from "hamur/adapter"
|
|
4
|
+
import type { Activation, activation, detach, setHidden } from "./activation.ts"
|
|
5
|
+
import type { Source, routeValue } from "./context.ts"
|
|
6
|
+
|
|
7
|
+
/** 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. */
|
|
8
|
+
export interface KeepAliveBase {
|
|
9
|
+
createElement: typeof createElement
|
|
10
|
+
Fragment: typeof Fragment
|
|
11
|
+
useContext: typeof useContext
|
|
12
|
+
useMemo: typeof useMemo
|
|
13
|
+
useLayoutEffect: typeof useLayoutEffect
|
|
14
|
+
ActivationContext: Context<Activation | undefined>
|
|
15
|
+
activation: typeof activation
|
|
16
|
+
detach: typeof detach
|
|
17
|
+
setHidden: typeof setHidden
|
|
18
|
+
RouteContext: Context<RouteValue | null>
|
|
19
|
+
DataContext: Context<Record<string, unknown>>
|
|
20
|
+
routeValue: typeof routeValue
|
|
21
|
+
nest(tree: RenderTree, ctx: Source): ComponentChildren | undefined
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type KeptOutlet = (
|
|
25
|
+
holder: { kept?: KeptUnit[] },
|
|
26
|
+
below: RenderEntry | undefined,
|
|
27
|
+
child: ComponentChildren | undefined,
|
|
28
|
+
ctx: Source,
|
|
29
|
+
) => VNode[]
|
|
30
|
+
|
|
31
|
+
const SHOWN = "\0shown"
|
|
32
|
+
const EMPTY: Record<string, unknown> = {}
|
|
33
|
+
|
|
34
|
+
/** The outlet of `holder` (an entry, or the tree's top level): each kept unit hidden under its own route, payload and tree, then the current child, keyed by the keep-alive key, so a page keeps its instance between the two. */
|
|
35
|
+
export function createKeptOutlet({
|
|
36
|
+
createElement,
|
|
37
|
+
Fragment,
|
|
38
|
+
useContext,
|
|
39
|
+
useMemo,
|
|
40
|
+
useLayoutEffect,
|
|
41
|
+
ActivationContext,
|
|
42
|
+
activation,
|
|
43
|
+
detach,
|
|
44
|
+
setHidden,
|
|
45
|
+
RouteContext,
|
|
46
|
+
DataContext,
|
|
47
|
+
routeValue,
|
|
48
|
+
nest,
|
|
49
|
+
}: KeepAliveBase): KeptOutlet {
|
|
50
|
+
const keptRoutes = new WeakMap<KeptUnit, RouteValue>()
|
|
51
|
+
|
|
52
|
+
/** A keep-alive page's wrapper, `display:contents` while shown and `hidden` while kept; it tells the pages below when it is shown and hidden. */
|
|
53
|
+
function KeptPage(props: { name: string; hidden: boolean; children?: ComponentChildren }): VNode {
|
|
54
|
+
const parent = useContext(ActivationContext)
|
|
55
|
+
const own = useMemo(() => activation(parent, props.hidden), [])
|
|
56
|
+
useLayoutEffect(() => setHidden(own, props.hidden), [props.hidden])
|
|
57
|
+
useLayoutEffect(() => () => detach(own), [])
|
|
58
|
+
const attributes = props.hidden
|
|
59
|
+
? { "data-hamur-keepalive": props.name, hidden: true }
|
|
60
|
+
: { "data-hamur-keepalive": props.name, style: "display:contents" }
|
|
61
|
+
return createElement(
|
|
62
|
+
ActivationContext.Provider as never,
|
|
63
|
+
{ value: own },
|
|
64
|
+
createElement("div", attributes, props.children),
|
|
65
|
+
) as VNode
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const scoped = (route: RouteValue, payload: Source["payload"], node: ComponentChildren): VNode =>
|
|
69
|
+
createElement(
|
|
70
|
+
RouteContext.Provider as never,
|
|
71
|
+
{ value: route },
|
|
72
|
+
createElement(
|
|
73
|
+
DataContext.Provider as never,
|
|
74
|
+
{ value: (payload?.data as Record<string, unknown> | undefined) ?? EMPTY },
|
|
75
|
+
node,
|
|
76
|
+
),
|
|
77
|
+
) as VNode
|
|
78
|
+
|
|
79
|
+
return (holder, below, child, ctx) => {
|
|
80
|
+
const units = (holder.kept ?? []).map((unit) => {
|
|
81
|
+
const own: Source = { ...ctx, route: unit.route, payload: unit.payload, tree: unit.tree }
|
|
82
|
+
let route = keptRoutes.get(unit)
|
|
83
|
+
if (!route) keptRoutes.set(unit, (route = routeValue(own)))
|
|
84
|
+
return createElement(
|
|
85
|
+
KeptPage,
|
|
86
|
+
{ key: unit.key, name: unit.key, hidden: true },
|
|
87
|
+
scoped(route, unit.payload, nest(unit.tree, own)),
|
|
88
|
+
) as VNode
|
|
89
|
+
})
|
|
90
|
+
if (child === undefined) return units
|
|
91
|
+
const shown = scoped(routeValue(ctx), ctx.payload, child)
|
|
92
|
+
const key = below?.keepalive
|
|
93
|
+
return [
|
|
94
|
+
...units,
|
|
95
|
+
(key === undefined
|
|
96
|
+
? createElement(Fragment, { key: SHOWN }, shown)
|
|
97
|
+
: createElement(KeptPage, { key, name: key, hidden: false }, shown)) as VNode,
|
|
98
|
+
]
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { createElement } from "preact"
|
|
2
|
+
import type { ComponentChildren, ComponentType } from "preact"
|
|
3
|
+
import { Suspense } from "preact/compat"
|
|
4
|
+
import { useContext, useEffect, useRef, useState } from "preact/hooks"
|
|
5
|
+
import { HYDRATE_ELEMENT, hydrateOnAttribute, markWaiting, replayInteraction, whenTriggered } from "hamur/adapter"
|
|
6
|
+
import type { HydrateOn, HydrateOnOptions } from "hamur/adapter"
|
|
7
|
+
import { AppContextContext, NeverHydratedContext } from "./context.ts"
|
|
8
|
+
|
|
9
|
+
type Module<P> = { default: ComponentType<P> }
|
|
10
|
+
|
|
11
|
+
interface Loading<P> {
|
|
12
|
+
promise: Promise<void>
|
|
13
|
+
module?: Module<P>
|
|
14
|
+
failed?: { error: unknown }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const isServer = typeof window === "undefined"
|
|
18
|
+
|
|
19
|
+
/** Hydration keeps the server markup in the element; a client render has put nothing there yet. */
|
|
20
|
+
const served = (element: Element) => element.firstElementChild !== null || (element.textContent ?? "") !== ""
|
|
21
|
+
const pending = new Set<Promise<void>>()
|
|
22
|
+
|
|
23
|
+
function track<P>(promise: Promise<Module<P>>): Loading<P> {
|
|
24
|
+
const loading: Loading<P> = { promise: Promise.resolve() }
|
|
25
|
+
loading.promise = promise.then(
|
|
26
|
+
(loaded) => void (loading.module = loaded),
|
|
27
|
+
(error: unknown) => void (loading.failed = { error }),
|
|
28
|
+
)
|
|
29
|
+
return loading
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The server renders synchronously, so `render` awaits the lazy modules still loading before each pass. */
|
|
33
|
+
export function lazyModules(): Promise<unknown> | undefined {
|
|
34
|
+
return pending.size ? Promise.all(pending) : undefined
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function Hydrated<P>({ loading, props, done }: { loading: Loading<P>; props: P; done: () => void }): ComponentChildren {
|
|
38
|
+
if (loading.failed) throw loading.failed.error
|
|
39
|
+
if (!loading.module) throw loading.promise
|
|
40
|
+
useEffect(done, [])
|
|
41
|
+
return createElement(loading.module.default as ComponentType<object>, props as object)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Renders the component on the server and, after hydration, keeps its server DOM until `on` fires; after a client navigation it mounts at once. */
|
|
45
|
+
export function defineLazyHydrationComponent<P extends object>(
|
|
46
|
+
on: HydrateOn,
|
|
47
|
+
loader: () => Promise<Module<P>>,
|
|
48
|
+
options: Omit<HydrateOnOptions, "signal"> = {},
|
|
49
|
+
): ComponentType<P & { onHydrated?: () => void }> {
|
|
50
|
+
const attribute = hydrateOnAttribute(on)
|
|
51
|
+
let server: Loading<P> | undefined
|
|
52
|
+
if (isServer) {
|
|
53
|
+
server = track(loader())
|
|
54
|
+
pending.add(server.promise)
|
|
55
|
+
void server.promise.then(() => pending.delete(server!.promise))
|
|
56
|
+
}
|
|
57
|
+
return function LazyHydration({ onHydrated, ...props }: P & { onHydrated?: () => void }): ComponentChildren {
|
|
58
|
+
const app = useContext(AppContextContext)
|
|
59
|
+
const wrapper = useRef<HTMLElement>(null)
|
|
60
|
+
const hydrated = useRef(onHydrated)
|
|
61
|
+
hydrated.current = onHydrated
|
|
62
|
+
const [gate] = useState(() => {
|
|
63
|
+
if (server) return { loading: server }
|
|
64
|
+
let release!: () => void
|
|
65
|
+
const triggered = new Promise<void>((resolve) => (release = resolve))
|
|
66
|
+
return { loading: track(triggered.then(loader)), release }
|
|
67
|
+
})
|
|
68
|
+
const [done] = useState(() => {
|
|
69
|
+
let called = false
|
|
70
|
+
return () => {
|
|
71
|
+
if (called) return
|
|
72
|
+
called = true
|
|
73
|
+
hydrated.current?.()
|
|
74
|
+
if (wrapper.current) replayInteraction(wrapper.current)
|
|
75
|
+
}
|
|
76
|
+
})
|
|
77
|
+
useEffect(() => {
|
|
78
|
+
const element = wrapper.current
|
|
79
|
+
if (!gate.release || !element) return
|
|
80
|
+
if (!served(element)) return void gate.release()
|
|
81
|
+
const controller = new AbortController()
|
|
82
|
+
void whenTriggered(element, on, { ...options, signal: controller.signal }).then(gate.release)
|
|
83
|
+
return () => controller.abort()
|
|
84
|
+
}, [gate])
|
|
85
|
+
const waiting = isServer && !gate.loading.module && !gate.loading.failed
|
|
86
|
+
if (waiting && app) markWaiting(app.asyncData)
|
|
87
|
+
// Preact reads an `on` prop as an event listener; the attribute is only written by the server, and hydration keeps it.
|
|
88
|
+
const inner = waiting
|
|
89
|
+
? null
|
|
90
|
+
: createElement(
|
|
91
|
+
Suspense,
|
|
92
|
+
{ fallback: null },
|
|
93
|
+
createElement(Hydrated<P>, { loading: gate.loading, props: props as P, done }),
|
|
94
|
+
)
|
|
95
|
+
return createElement(
|
|
96
|
+
HYDRATE_ELEMENT,
|
|
97
|
+
isServer ? { on: attribute } : { ref: wrapper },
|
|
98
|
+
on === "never" ? createElement(NeverHydratedContext.Provider, { value: true }, inner) : inner,
|
|
99
|
+
)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -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 { h } from "preact";
|
|
7
|
+
import { MarkdownRenderer, useHead } from "@hamur/adapter-preact";
|
|
8
|
+
|
|
9
|
+
const value = ${value};
|
|
10
|
+
|
|
11
|
+
export default function MarkdownPage() {
|
|
12
|
+
${head ? ` useHead(${head});\n` : ""} return h(MarkdownRenderer, ${props});
|
|
13
|
+
}
|
|
14
|
+
`
|
|
15
|
+
return { contents, extension: ".js" }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const markdownComponent = { module }
|
package/src/markdown.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { Fragment, createElement, type ComponentChildren, type ComponentType, type VNode } from "preact"
|
|
2
|
+
import { markdownLink, markdownProse, markdownView, type MdView } from "hamur/adapter"
|
|
3
|
+
import type { MarkdownDocument, MdNode } from "hamur/markdown"
|
|
4
|
+
import { Link } from "./index.ts"
|
|
5
|
+
|
|
6
|
+
export interface MarkdownRendererProps {
|
|
7
|
+
/** A Markdown AST node, a list of nodes, or a document, which renders its `ast`. */
|
|
8
|
+
value: MdNode | MdNode[] | MarkdownDocument
|
|
9
|
+
/** Components by Markdown component name (kebab case); each gets the node's props as written, `children` and a prop per named slot. */
|
|
10
|
+
components?: Record<string, ComponentType<any>>
|
|
11
|
+
/** Renders `html` nodes, writing what it returns as their inner HTML; without it they are left out. A Markdown page under config `markdown.html` passes the core's Trusted Types writer. */
|
|
12
|
+
raw?: (html: string) => string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type Components = Record<string, ComponentType<any>>
|
|
16
|
+
|
|
17
|
+
function render(view: MdView, raw: (html: string) => string, components: Components): ComponentChildren {
|
|
18
|
+
if (typeof view === "string") return view
|
|
19
|
+
if ("html" in view)
|
|
20
|
+
return createElement("hamur-html", {
|
|
21
|
+
style: "display:contents",
|
|
22
|
+
dangerouslySetInnerHTML: { __html: raw(view.html) },
|
|
23
|
+
})
|
|
24
|
+
const children = view.children.map((child) => render(child, raw, components))
|
|
25
|
+
if ("component" in view) {
|
|
26
|
+
const component = Object.hasOwn(components, view.component) ? components[view.component] : undefined
|
|
27
|
+
if (component) {
|
|
28
|
+
const slots = Object.fromEntries(
|
|
29
|
+
Object.entries(view.slots).map(([name, views]) => [
|
|
30
|
+
name,
|
|
31
|
+
createElement(Fragment, null, ...views.map((slot) => render(slot, raw, components))),
|
|
32
|
+
]),
|
|
33
|
+
)
|
|
34
|
+
return createElement(component, { ...view.props, ...slots } as unknown as Record<string, unknown>, ...children)
|
|
35
|
+
}
|
|
36
|
+
return view.attrs
|
|
37
|
+
? createElement(view.component, view.attrs, ...children)
|
|
38
|
+
: createElement(Fragment, null, ...children)
|
|
39
|
+
}
|
|
40
|
+
const link = markdownLink(view)
|
|
41
|
+
if (link)
|
|
42
|
+
return createElement(
|
|
43
|
+
Link as unknown as (props: Record<string, unknown>) => VNode,
|
|
44
|
+
{ ...link.attrs, to: link.to },
|
|
45
|
+
...children,
|
|
46
|
+
)
|
|
47
|
+
return createElement(view.tag, view.attrs, ...children)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Renders the Markdown AST as Preact elements, an internal link as `Link`, a component node as its component in `components`. */
|
|
51
|
+
export function MarkdownRenderer({ value, components: given = {}, raw }: MarkdownRendererProps): VNode {
|
|
52
|
+
const { value: nodes, components } = markdownProse(value, given)
|
|
53
|
+
return createElement(
|
|
54
|
+
Fragment,
|
|
55
|
+
null,
|
|
56
|
+
...markdownView(nodes, { html: raw !== undefined, components }).map((view) => render(view, raw!, components)),
|
|
57
|
+
)
|
|
58
|
+
}
|