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

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