@open-pencil/html-engine 0.0.0-stage → 0.17.0-beta.4

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/src/runtime.ts ADDED
@@ -0,0 +1,257 @@
1
+ import {
2
+ createHeadlessCSSRuntime,
3
+ parseFontFaceRules,
4
+ parseStylesheetImports,
5
+ type CSSFontFaceRule,
6
+ type CSSComputeOptions,
7
+ type CSSRuntime,
8
+ type DesignDocument,
9
+ type DesignElement,
10
+ type DesignLayout,
11
+ type DesignStyleDeclaration,
12
+ type DesignViewport
13
+ } from '@open-pencil/dom-css'
14
+ import type { Rect } from '@open-pencil/scene-graph/primitives'
15
+
16
+ import type { HTMLEngine, HTMLEngineFetch, HTMLEngineResource } from './engine'
17
+ import { loadHTMLEngine } from './load'
18
+ import type { HTMLEngineCapture, HTMLEngineLine, HTMLEngineNode } from './schema'
19
+
20
+ /** The viewport a document is laid out in when the caller names none, as HTML import uses. */
21
+ const DEFAULT_VIEWPORT: DesignViewport = { width: 1440, height: 900 }
22
+
23
+ /** A font a page's `@font-face` rule loads: the face the rule declares, and the file as TrueType or OpenType. */
24
+ export interface HTMLEngineFontFace {
25
+ family: string
26
+ weight: number
27
+ italic: boolean
28
+ url: string
29
+ bytes: Uint8Array
30
+ }
31
+
32
+ export interface HTMLEngineRuntimeOptions {
33
+ /** The engine to lay documents out with, with the fonts they may use registered. */
34
+ engine?: () => Promise<HTMLEngine>
35
+ /** The document's URL, which its relative URLs resolve against. */
36
+ baseURL?: string
37
+ /**
38
+ * Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for
39
+ * its `@font-face` rules when it comes with a CSS content type.
40
+ */
41
+ fetch?: HTMLEngineFetch
42
+ /**
43
+ * Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so
44
+ * a host can draw that text in the same font. The layout waits for it.
45
+ */
46
+ onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>
47
+ }
48
+
49
+ function isStylesheet(resource: HTMLEngineResource): boolean {
50
+ return resource.contentType?.split(';')[0]?.trim().toLowerCase() === 'text/css'
51
+ }
52
+
53
+ /**
54
+ * A fetch that also reads the page's `@font-face` rules, from its own CSS and every stylesheet it
55
+ * fetches, and passes each font they load to `onFontFace` as the engine receives it.
56
+ */
57
+ function fontFaceFetch(
58
+ engine: HTMLEngine,
59
+ cssText: string,
60
+ options: HTMLEngineRuntimeOptions
61
+ ): HTMLEngineFetch | undefined {
62
+ const { fetch, onFontFace } = options
63
+ if (!fetch || !onFontFace) return fetch
64
+ const rules = new Map<string, CSSFontFaceRule[]>()
65
+ // What CSS imports is a stylesheet whatever its name or the type it is served as.
66
+ const stylesheets = new Set<string>()
67
+ // The engine fetches a file once per rule that names it; each face is passed on once.
68
+ const delivered = new Set<string>()
69
+ const learn = (css: string, base: string | undefined) => {
70
+ for (const rule of parseFontFaceRules(css, base)) {
71
+ for (const source of rule.sources) rules.set(source, [...(rules.get(source) ?? []), rule])
72
+ }
73
+ for (const url of parseStylesheetImports(css, base)) stylesheets.add(url)
74
+ }
75
+ learn(cssText, options.baseURL)
76
+ return async (url, signal) => {
77
+ const resource = await fetch(url, signal)
78
+ if (!resource) return null
79
+ if (isStylesheet(resource) || stylesheets.has(url) || stylesheets.has(resource.url)) {
80
+ learn(new TextDecoder().decode(resource.bytes), resource.url)
81
+ }
82
+ // One file can serve several rules, such as a family and an alias of it.
83
+ const served = rules.get(url) ?? rules.get(resource.url) ?? []
84
+ const bytes = served.length > 0 ? engine.decodeFont(resource.bytes) : null
85
+ for (const rule of served) {
86
+ const face = `${url}|${rule.family}|${rule.weight}|${rule.italic}`
87
+ if (!bytes || delivered.has(face)) continue
88
+ delivered.add(face)
89
+ await onFontFace({
90
+ family: rule.family,
91
+ weight: rule.weight,
92
+ italic: rule.italic,
93
+ url,
94
+ bytes
95
+ })
96
+ }
97
+ return resource
98
+ }
99
+ }
100
+
101
+ type Box = HTMLEngineCapture['nodes'][number]['box']
102
+
103
+ function rect(box: NonNullable<Box>): Rect {
104
+ const [x, y, width, height] = box
105
+ return { x, y, width, height }
106
+ }
107
+
108
+ function hasArea(box: NonNullable<Box>): boolean {
109
+ return box[2] > 0 && box[3] > 0
110
+ }
111
+
112
+ /** Children of each captured node that are elements, by the node's index; generated content left out. */
113
+ function elementChildren(capture: HTMLEngineCapture): Map<number, number[]> {
114
+ const children = new Map<number, number[]>()
115
+ for (const [index, node] of capture.nodes.entries()) {
116
+ if (node.parent === undefined || node.tag === undefined || node.tag.startsWith('::')) continue
117
+ const siblings = children.get(node.parent) ?? []
118
+ siblings.push(index)
119
+ children.set(node.parent, siblings)
120
+ }
121
+ return children
122
+ }
123
+
124
+ /**
125
+ * Elements the HTML parser inserts around others where the markup leaves them out, such as the
126
+ * `tbody` around a table's rows; a serialized document need not hold them.
127
+ */
128
+ const IMPLIED_WRAPPERS = new Set(['tbody'])
129
+
130
+ /**
131
+ * Each element of the document with the captured element it was laid out as: matched in order
132
+ * and by tag, looking through wrappers the parser inserted. A mismatch ends the matching among
133
+ * those siblings, so it never pairs an element with another's box.
134
+ */
135
+ function pairElements(
136
+ document: DesignDocument,
137
+ capture: HTMLEngineCapture
138
+ ): [DesignElement, HTMLEngineNode][] {
139
+ const children = elementChildren(capture)
140
+ const body = capture.nodes.findIndex((node) => node.tag === 'body')
141
+ const pairs: [DesignElement, HTMLEngineNode][] = []
142
+ const pair = (elements: readonly DesignElement[], parent: number, shaderFrame = false) => {
143
+ const queue = [...(children.get(parent) ?? [])]
144
+ // The serializer writes a shader's still frame as an image ahead of its layer's children.
145
+ const first = queue.at(0)
146
+ if (shaderFrame && first !== undefined && capture.nodes[first].tag === 'img') queue.shift()
147
+ for (const element of elements) {
148
+ let node = queue.shift()
149
+ // The HTML parser keeps SVG's mixed-case names, such as `linearGradient`; the document may not.
150
+ while (node !== undefined && !sameTag(capture.nodes[node].tag, element.tagName)) {
151
+ const tag = capture.nodes[node].tag
152
+ if (tag === undefined || !IMPLIED_WRAPPERS.has(tag)) return
153
+ queue.unshift(...(children.get(node) ?? []))
154
+ node = queue.shift()
155
+ }
156
+ if (node === undefined) return
157
+ pairs.push([element, capture.nodes[node]])
158
+ pair(designElements(element.children), node, element.shader?.frame !== undefined)
159
+ }
160
+ }
161
+ if (body !== -1) pair(designElements(document.children), body)
162
+ return pairs
163
+ }
164
+
165
+ function sameTag(captured: string | undefined, tagName: string): boolean {
166
+ return captured?.toLowerCase() === tagName.toLowerCase()
167
+ }
168
+
169
+ function designElements(nodes: DesignDocument['children']): DesignElement[] {
170
+ return nodes.filter((node): node is DesignElement => node.type === 'element')
171
+ }
172
+
173
+ /** Shorthands a browser runtime reports, `overflow` and `gap`, built from their captured longhands. */
174
+ function withShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {
175
+ // Captures leave initial values out.
176
+ const value = (property: string, initial: string) =>
177
+ Object.hasOwn(style, property) ? style[property] : initial
178
+ const pair = (first: string, second: string) => (first === second ? first : `${first} ${second}`)
179
+ const shorthands: DesignStyleDeclaration = {}
180
+ if (Object.hasOwn(style, 'overflow-x') || Object.hasOwn(style, 'overflow-y')) {
181
+ shorthands.overflow = pair(value('overflow-x', 'visible'), value('overflow-y', 'visible'))
182
+ }
183
+ if (Object.hasOwn(style, 'row-gap') || Object.hasOwn(style, 'column-gap')) {
184
+ shorthands.gap = pair(value('row-gap', 'normal'), value('column-gap', 'normal'))
185
+ }
186
+ return { ...style, ...shorthands }
187
+ }
188
+
189
+ /** White space values that keep spaces, so a line of them takes room as a line of words does. */
190
+ const PRESERVED_WHITE_SPACE = new Set(['pre', 'pre-wrap', 'break-spaces'])
191
+
192
+ /**
193
+ * A line as a browser's text rects make it: across its words, leaving out inline boxes, and
194
+ * nothing for a line without text. Where white space is kept, a line of spaces counts too.
195
+ */
196
+ function textLine(line: HTMLEngineLine, keepsSpaces: boolean): Rect | null {
197
+ const texts = line.runs.filter((run) => 'text' in run && run.text.length > 0)
198
+ const words = keepsSpaces ? texts : texts.filter((run) => 'text' in run && run.text.trim() !== '')
199
+ if (words.length === 0) return null
200
+ const left = Math.min(...words.map((run) => run.x))
201
+ const right = Math.max(...words.map((run) => run.x + run.width))
202
+ return { x: left, y: line.y, width: right - left, height: line.height }
203
+ }
204
+
205
+ function layoutOf(node: HTMLEngineNode): DesignLayout | undefined {
206
+ if (!node.box) return undefined
207
+ const layout: DesignLayout = { box: rect(node.box) }
208
+ const fragments = node.fragments?.filter(hasArea)
209
+ if (fragments && fragments.length > 0) {
210
+ layout.fragments = fragments.map(rect)
211
+ return layout
212
+ }
213
+ const whiteSpace = node.style?.['white-space']
214
+ const keepsSpaces = whiteSpace !== undefined && PRESERVED_WHITE_SPACE.has(whiteSpace)
215
+ const lines = (node.lines ?? [])
216
+ .map((line) => textLine(line, keepsSpaces))
217
+ .filter((line) => line !== null)
218
+ if (lines.length > 0) layout.lines = lines
219
+ return layout
220
+ }
221
+
222
+ function documentHTML(body: string, cssText: string): string {
223
+ // `</style` would end the stylesheet early.
224
+ const css = cssText.replaceAll(/<\/style/gi, '<\\/style')
225
+ return `<!doctype html><html><head><style>${css}</style></head><body>${body}</body></html>`
226
+ }
227
+
228
+ /**
229
+ * A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,
230
+ * without one: computed styles and, when asked, the boxes, inline fragments, and text lines a
231
+ * browser runtime records, before transforms. Documents are parsed and serialized as the headless
232
+ * runtime does.
233
+ */
234
+ export function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}): CSSRuntime {
235
+ const markup = createHeadlessCSSRuntime()
236
+ const engine = options.engine ?? loadHTMLEngine
237
+ return {
238
+ kind: 'headless',
239
+ parseHTML: (html) => markup.parseHTML(html),
240
+ serializeHTML: (document) => markup.serializeHTML(document),
241
+ async computeStyles(document, cssText = '', compute: CSSComputeOptions = {}) {
242
+ const laidOut = await engine()
243
+ const capture = await laidOut.layout(documentHTML(markup.serializeHTML(document), cssText), {
244
+ baseURL: options.baseURL,
245
+ viewport: compute.viewport ?? DEFAULT_VIEWPORT,
246
+ fetch: fontFaceFetch(laidOut, cssText, options)
247
+ })
248
+ const styled = structuredClone(document)
249
+ for (const [element, node] of pairElements(styled, capture)) {
250
+ // Every captured property's computed value, so none falls back to a stale inline one.
251
+ element.computedStyle = withShorthands({ ...capture.initial, ...node.style })
252
+ if (compute.layout) element.layout = layoutOf(node)
253
+ }
254
+ return styled
255
+ }
256
+ }
257
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,70 @@
1
+ import * as v from 'valibot'
2
+
3
+ const rectSchema = v.tuple([v.number(), v.number(), v.number(), v.number()])
4
+
5
+ const glyphRunSchema = v.object({
6
+ /** The engine's id of the node whose text the run draws. */
7
+ node: v.number(),
8
+ x: v.number(),
9
+ width: v.number(),
10
+ text: v.string()
11
+ })
12
+
13
+ const inlineBoxRunSchema = v.object({
14
+ /** The engine's id of the atomic inline, such as an `inline-block`, the line holds. */
15
+ box: v.number(),
16
+ x: v.number(),
17
+ width: v.number()
18
+ })
19
+
20
+ const lineSchema = v.object({
21
+ x: v.number(),
22
+ y: v.number(),
23
+ width: v.number(),
24
+ height: v.number(),
25
+ baseline: v.number(),
26
+ runs: v.array(v.union([glyphRunSchema, inlineBoxRunSchema]))
27
+ })
28
+
29
+ const capturedNodeSchema = v.object({
30
+ /** The engine's own id, which runs and inline boxes refer to. */
31
+ id: v.number(),
32
+ /** The index in `nodes` of the element holding it. */
33
+ parent: v.optional(v.number()),
34
+ /** Set on text nodes, which carry nothing else. */
35
+ text: v.optional(v.string()),
36
+ /** The element's local name, or `::before` and `::after` for generated content. */
37
+ tag: v.optional(v.string()),
38
+ /** Attributes by name, namespaced ones with their prefix, as `xlink:href`. */
39
+ attrs: v.optional(v.record(v.string(), v.string())),
40
+ /** The border box, in page pixels. */
41
+ box: v.optional(rectSchema),
42
+ /** What the image element holds, such as `raster 640x480` or `svg`. */
43
+ image: v.optional(v.string()),
44
+ /**
45
+ * Computed values: those with a fixed initial value only when they differ from it, and always
46
+ * the ones whose initial value depends on the element or is inherited, such as `display`,
47
+ * `color`, sizes, and font properties.
48
+ */
49
+ style: v.optional(v.record(v.string(), v.string())),
50
+ /** An inline element's box on each line it spans, in page pixels. */
51
+ fragments: v.optional(v.array(rectSchema)),
52
+ /** The lines of the inline formatting context the element holds, in page pixels. */
53
+ lines: v.optional(v.array(lineSchema))
54
+ })
55
+
56
+ /** The document the engine laid out: every node, parents before children. */
57
+ export const captureSchema = v.object({
58
+ engine: v.literal('blitz'),
59
+ viewport: v.tuple([v.number(), v.number()]),
60
+ /** The initial values of the properties nodes leave out of `style` when they hold them. */
61
+ initial: v.record(v.string(), v.string()),
62
+ nodes: v.array(capturedNodeSchema)
63
+ })
64
+
65
+ /** The resources the document is waiting for, as `[request id, URL]` pairs. */
66
+ export const requestsSchema = v.array(v.tuple([v.number(), v.string()]))
67
+
68
+ export type HTMLEngineCapture = v.InferOutput<typeof captureSchema>
69
+ export type HTMLEngineNode = v.InferOutput<typeof capturedNodeSchema>
70
+ export type HTMLEngineLine = v.InferOutput<typeof lineSchema>