@open-pencil/html-engine 0.17.0-beta.4 → 0.17.0-beta.6
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/README.md +1 -1
- package/dist/chunks/engine.js +14 -11
- package/dist/chunks/engine.js.map +1 -1
- package/dist/chunks/index.js +108 -14
- package/dist/chunks/index.js.map +1 -1
- package/dist/index.d.ts +16 -21
- package/dist/index.d.ts.map +1 -1
- package/package.json +4 -3
- package/src/engine.ts +10 -27
- package/src/images.ts +1 -1
- package/src/index.ts +1 -6
- package/src/load.ts +3 -1
- package/src/runtime.ts +136 -18
- package/src/schema.ts +6 -0
- package/wasm/THIRD-PARTY-NOTICES.md +36 -36
- package/wasm/html-engine.wasm +0 -0
- package/wasm/html-engine.wasm.sha256 +1 -1
package/README.md
CHANGED
|
@@ -22,6 +22,6 @@ const capture = await engine.layout(html, {
|
|
|
22
22
|
|
|
23
23
|
`createHTMLEngineRuntime()` is a `CSSRuntime` for `@open-pencil/dom-css`: it gives each element its computed style and, when asked, the box, inline fragments, and text lines a browser runtime records, so HTML imports headless as it does in a browser. Its `onFontFace` option receives each font the page's `@font-face` rules load, with the family, weight, and style the rule declares, so a host can draw the page's text in it.
|
|
24
24
|
|
|
25
|
-
The engine fetches nothing itself: the host answers each stylesheet, font, and image the document asks for, or declines it. Raster images are laid out at their pixel size, read from their headers. The engine has no fonts of its own, so the host registers the ones layout may use.
|
|
25
|
+
The engine fetches nothing itself: the host answers each stylesheet, font, and image the document asks for, or declines it. Raster images are laid out at their pixel size, read from their headers. The engine has no fonts of its own, so the host registers the ones layout may use and points `sans-serif` at one: without a font for its text, a paragraph lays nothing out, its inline boxes and images included.
|
|
26
26
|
|
|
27
27
|
The module, `wasm/html-engine.wasm`, is built from the Rust crate in `crate/` by `bun run build`, which needs Rust; rustup installs the toolchain `rust-toolchain.toml` pins. A host that serves the module somewhere other than beside this package sets `setHTMLEngineLocator`. The published package carries `wasm/THIRD-PARTY-NOTICES.md`, which the release writes with the licenses and sources of the Rust crates compiled into the module.
|
package/dist/chunks/engine.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
|
+
import { createMutex } from "@open-pencil/std/async";
|
|
3
|
+
import { DEADLINE_MS, untilAborted } from "@open-pencil/std/timing";
|
|
2
4
|
//#region src/images.ts
|
|
3
5
|
function ascii(bytes, at, length) {
|
|
4
|
-
return
|
|
6
|
+
return Array.from(bytes.subarray(at, at + length), (code) => String.fromCharCode(code)).join("");
|
|
5
7
|
}
|
|
6
8
|
function webpSize(bytes, view) {
|
|
7
9
|
const chunk = ascii(bytes, 12, 4);
|
|
@@ -144,6 +146,12 @@ const capturedNodeSchema = v.object({
|
|
|
144
146
|
* `color`, sizes, and font properties.
|
|
145
147
|
*/
|
|
146
148
|
style: v.optional(v.record(v.string(), v.string())),
|
|
149
|
+
/**
|
|
150
|
+
* Computed values where `style`'s used ones lose what the page set: the sizes (`width`,
|
|
151
|
+
* `height`, their minimums and maximums, and `flex-basis`) before layout resolves `auto` and
|
|
152
|
+
* percentages to pixels, such as `auto`, `50%`, or `390px`, and `line-height`, such as `1.5`.
|
|
153
|
+
*/
|
|
154
|
+
computed: v.optional(v.record(v.string(), v.string())),
|
|
147
155
|
/** An inline element's box on each line it spans, in page pixels. */
|
|
148
156
|
fragments: v.optional(v.array(rectSchema)),
|
|
149
157
|
/** The lines of the inline formatting context the element holds, in page pixels. */
|
|
@@ -183,18 +191,15 @@ const EXPORTS = [
|
|
|
183
191
|
* How long a request may take by default: as long as the browser runtime waits for an image, so
|
|
184
192
|
* one request that never ends cannot hold this layout, or the ones queued behind it, forever.
|
|
185
193
|
*/
|
|
186
|
-
const REQUEST_TIMEOUT_MS =
|
|
194
|
+
const REQUEST_TIMEOUT_MS = DEADLINE_MS.request;
|
|
187
195
|
/** The largest viewport side the module takes, as a signed 32-bit length. */
|
|
188
196
|
const MAX_VIEWPORT = 2147483647;
|
|
189
197
|
function checkViewport({ width, height }) {
|
|
190
198
|
for (const side of [width, height]) if (!Number.isInteger(side) || side <= 0 || side > MAX_VIEWPORT) throw new RangeError(`The viewport needs whole positive pixel sizes, not ${width}×${height}`);
|
|
191
199
|
}
|
|
192
|
-
/** A fetch that gives up, answering null, once `signal` aborts. */
|
|
200
|
+
/** A fetch that gives up, answering null, once it fails or `signal` aborts. */
|
|
193
201
|
function withDeadline(request, signal) {
|
|
194
|
-
|
|
195
|
-
signal.addEventListener("abort", () => resolve(null), { once: true });
|
|
196
|
-
});
|
|
197
|
-
return Promise.race([request.catch(() => null), expired]);
|
|
202
|
+
return untilAborted(request, signal).catch(() => null);
|
|
198
203
|
}
|
|
199
204
|
/** Blitz's wasm-bindgen imports, which no capture calls: they trap with their name instead. */
|
|
200
205
|
function unboundImports(module) {
|
|
@@ -251,7 +256,7 @@ var HTMLEngine = class HTMLEngine {
|
|
|
251
256
|
#exports;
|
|
252
257
|
#encoder = new TextEncoder();
|
|
253
258
|
#decoder = new TextDecoder();
|
|
254
|
-
#
|
|
259
|
+
#layouts = createMutex();
|
|
255
260
|
constructor(exports) {
|
|
256
261
|
this.#exports = exports;
|
|
257
262
|
}
|
|
@@ -339,9 +344,7 @@ var HTMLEngine = class HTMLEngine {
|
|
|
339
344
|
}
|
|
340
345
|
/** Lays the document out once every resource it asks for is answered, and captures it. */
|
|
341
346
|
layout(html, options) {
|
|
342
|
-
|
|
343
|
-
this.#queue = run.catch(() => void 0);
|
|
344
|
-
return run;
|
|
347
|
+
return this.#layouts.run(() => this.#layout(html, options));
|
|
345
348
|
}
|
|
346
349
|
};
|
|
347
350
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.js","names":["#exports","#encoder","#decoder","#withBytes","#withText","#output","#answer","#layout","#pump","#queue"],"sources":["../../src/images.ts","../../src/schema.ts","../../src/engine.ts"],"sourcesContent":["/**\n * The engine decodes no raster images, so layout learns an image's size from a stand-in SVG of\n * the same pixel size, read from the file's header. Formats are the ones browsers lay out from\n * their headers alone: PNG, GIF, WebP, JPEG, and AVIF.\n */\n\ntype Size = [width: number, height: number]\n\nfunction ascii(bytes: Uint8Array, at: number, length: number): string {\n return String.fromCharCode(...bytes.subarray(at, at + length))\n}\n\nfunction webpSize(bytes: Uint8Array, view: DataView): Size | null {\n const chunk = ascii(bytes, 12, 4)\n if (chunk === 'VP8 ')\n return [view.getUint16(26, true) & 0x3fff, view.getUint16(28, true) & 0x3fff]\n if (chunk === 'VP8L') {\n const bits = view.getUint32(21, true)\n return [(bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1]\n }\n if (chunk === 'VP8X') {\n const width = 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16))\n const height = 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16))\n return [width, height]\n }\n return null\n}\n\n/** Start-of-frame markers, which carry the size; C4, C8, and CC are other segments. */\nfunction isStartOfFrame(marker: number): boolean {\n return marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc\n}\n\nconst APP1 = 0xe1\nconst ORIENTATION_TAG = 0x0112\n\n/**\n * The Exif Orientation in an APP1 segment starting at `at`: 1 when the Exif data names none,\n * and null when the segment is not Exif, such as XMP, which says nothing about orientation. Orientations 5\n * to 8 turn the image a quarter, so browsers lay it out with width and height swapped.\n */\nfunction exifOrientation(\n bytes: Uint8Array,\n view: DataView,\n at: number,\n end: number\n): number | null {\n const tiff = at + 10\n if (tiff + 8 > end || ascii(bytes, at + 4, 6) !== 'Exif\\0\\0') return null\n const littleEndian = ascii(bytes, tiff, 2) === 'II'\n const firstIFD = tiff + view.getUint32(tiff + 4, littleEndian)\n if (firstIFD + 2 > end) return 1\n const entries = view.getUint16(firstIFD, littleEndian)\n for (let entry = 0; entry < entries; entry++) {\n const offset = firstIFD + 2 + entry * 12\n if (offset + 12 > end) return 1\n if (view.getUint16(offset, littleEndian) === ORIENTATION_TAG) {\n return view.getUint16(offset + 8, littleEndian)\n }\n }\n return 1\n}\n\nfunction jpegSize(bytes: Uint8Array, view: DataView): Size | null {\n let orientation = 1\n let at = 2\n while (at + 9 < bytes.length) {\n if (bytes[at] !== 0xff) return null\n // Any number of 0xFF fill bytes may come before a marker.\n let markerAt = at + 1\n while (markerAt < bytes.length && bytes[markerAt] === 0xff) markerAt++\n if (markerAt + 7 >= bytes.length) return null\n const marker = bytes[markerAt]\n // A segment's length counts its own two bytes, so less is a broken file.\n const length = view.getUint16(markerAt + 1)\n if (length < 2) return null\n const segment = markerAt - 1\n const end = Math.min(bytes.length, markerAt + 1 + length)\n if (marker === APP1) orientation = exifOrientation(bytes, view, segment, end) ?? orientation\n if (isStartOfFrame(marker)) {\n const size: Size = [view.getUint16(markerAt + 6), view.getUint16(markerAt + 4)]\n return orientation >= 5 && orientation <= 8 ? [size[1], size[0]] : size\n }\n at = end\n }\n return null\n}\n\nconst ISPE = [0x69, 0x73, 0x70, 0x65]\n\n/**\n * An AVIF's size from its `ispe` box, wherever the file puts it: the box's type, then its\n * version and flags, then two 32-bit sizes. A match counts only when the size the box header\n * before it gives holds all of that and fits in the file.\n */\nfunction avifSize(bytes: Uint8Array, view: DataView): Size | null {\n for (let at = 4; at + 16 <= bytes.length; at++) {\n if (ISPE.some((byte, index) => bytes[at + index] !== byte)) continue\n const boxSize = view.getUint32(at - 4)\n if (boxSize < 20 || at - 4 + boxSize > bytes.length) continue\n return [view.getUint32(at + 8), view.getUint32(at + 12)]\n }\n return null\n}\n\n/** An image file's pixel size from its header, or null for a format it does not know. */\nexport function rasterImageSize(bytes: Uint8Array): Size | null {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n // The size is in the IHDR chunk, which a PNG must start with.\n if (\n bytes.length > 24 &&\n bytes[0] === 0x89 &&\n ascii(bytes, 1, 3) === 'PNG' &&\n ascii(bytes, 12, 4) === 'IHDR'\n ) {\n return [view.getUint32(16), view.getUint32(20)]\n }\n if (bytes.length > 10 && ascii(bytes, 0, 3) === 'GIF') {\n return [view.getUint16(6, true), view.getUint16(8, true)]\n }\n if (bytes.length > 30 && ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP') {\n return webpSize(bytes, view)\n }\n if (bytes.length > 4 && bytes[0] === 0xff && bytes[1] === 0xd8) return jpegSize(bytes, view)\n if (bytes.length > 32 && ascii(bytes, 4, 4) === 'ftyp' && /avi[fs]/.test(ascii(bytes, 8, 4))) {\n return avifSize(bytes, view)\n }\n return null\n}\n\n/** An empty SVG of the image's size, which the engine lays out as the image would be. */\nexport function imageStandIn([width, height]: Size): Uint8Array {\n return new TextEncoder().encode(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\"/>`\n )\n}\n","import * as v from 'valibot'\n\nconst rectSchema = v.tuple([v.number(), v.number(), v.number(), v.number()])\n\nconst glyphRunSchema = v.object({\n /** The engine's id of the node whose text the run draws. */\n node: v.number(),\n x: v.number(),\n width: v.number(),\n text: v.string()\n})\n\nconst inlineBoxRunSchema = v.object({\n /** The engine's id of the atomic inline, such as an `inline-block`, the line holds. */\n box: v.number(),\n x: v.number(),\n width: v.number()\n})\n\nconst lineSchema = v.object({\n x: v.number(),\n y: v.number(),\n width: v.number(),\n height: v.number(),\n baseline: v.number(),\n runs: v.array(v.union([glyphRunSchema, inlineBoxRunSchema]))\n})\n\nconst capturedNodeSchema = v.object({\n /** The engine's own id, which runs and inline boxes refer to. */\n id: v.number(),\n /** The index in `nodes` of the element holding it. */\n parent: v.optional(v.number()),\n /** Set on text nodes, which carry nothing else. */\n text: v.optional(v.string()),\n /** The element's local name, or `::before` and `::after` for generated content. */\n tag: v.optional(v.string()),\n /** Attributes by name, namespaced ones with their prefix, as `xlink:href`. */\n attrs: v.optional(v.record(v.string(), v.string())),\n /** The border box, in page pixels. */\n box: v.optional(rectSchema),\n /** What the image element holds, such as `raster 640x480` or `svg`. */\n image: v.optional(v.string()),\n /**\n * Computed values: those with a fixed initial value only when they differ from it, and always\n * the ones whose initial value depends on the element or is inherited, such as `display`,\n * `color`, sizes, and font properties.\n */\n style: v.optional(v.record(v.string(), v.string())),\n /** An inline element's box on each line it spans, in page pixels. */\n fragments: v.optional(v.array(rectSchema)),\n /** The lines of the inline formatting context the element holds, in page pixels. */\n lines: v.optional(v.array(lineSchema))\n})\n\n/** The document the engine laid out: every node, parents before children. */\nexport const captureSchema = v.object({\n engine: v.literal('blitz'),\n viewport: v.tuple([v.number(), v.number()]),\n /** The initial values of the properties nodes leave out of `style` when they hold them. */\n initial: v.record(v.string(), v.string()),\n nodes: v.array(capturedNodeSchema)\n})\n\n/** The resources the document is waiting for, as `[request id, URL]` pairs. */\nexport const requestsSchema = v.array(v.tuple([v.number(), v.string()]))\n\nexport type HTMLEngineCapture = v.InferOutput<typeof captureSchema>\nexport type HTMLEngineNode = v.InferOutput<typeof capturedNodeSchema>\nexport type HTMLEngineLine = v.InferOutput<typeof lineSchema>\n","import * as v from 'valibot'\n\nimport { imageStandIn, rasterImageSize } from './images'\nimport { captureSchema, requestsSchema, type HTMLEngineCapture } from './schema'\n\n/**\n * The module's exports: strings and bytes cross as (pointer, length), and results land in one\n * output buffer whose length the call returns.\n */\nconst EXPORTS = [\n 'alloc',\n 'dealloc',\n 'output_ptr',\n 'fonts_reset',\n 'font_decode',\n 'font_add',\n 'font_generic',\n 'open',\n 'pump',\n 'provide',\n 'fail',\n 'capture'\n] as const\n\ntype EngineExports = Record<(typeof EXPORTS)[number], (...args: number[]) => number> & {\n memory: WebAssembly.Memory\n}\n\n/** A resource the document asked for, as the host fetched it: its final URL and its bytes. */\nexport interface HTMLEngineResource {\n url: string\n bytes: Uint8Array\n /** The resource's media type, such as `text/css`, when the host knows it. */\n contentType?: string\n}\n\n/**\n * Fetches a stylesheet, font, or image the document refers to; null when it cannot. `signal`\n * aborts when the request runs out of time, and the layout goes on without it.\n */\nexport type HTMLEngineFetch = (\n url: string,\n signal: AbortSignal\n) => Promise<HTMLEngineResource | null>\n\nexport interface HTMLEngineLayoutOptions {\n /** The document's URL, which relative URLs in it resolve against. */\n baseURL?: string\n /** In whole CSS pixels. */\n viewport: { width: number; height: number }\n /** Answers the document's requests; without one, every request fails. */\n fetch?: HTMLEngineFetch\n /** How long one request may take before the layout goes on without it. */\n requestTimeoutMs?: number\n}\n\n/**\n * How long a request may take by default: as long as the browser runtime waits for an image, so\n * one request that never ends cannot hold this layout, or the ones queued behind it, forever.\n */\nconst REQUEST_TIMEOUT_MS = 10_000\n\n/** The largest viewport side the module takes, as a signed 32-bit length. */\nconst MAX_VIEWPORT = 0x7fffffff\n\nfunction checkViewport({ width, height }: HTMLEngineLayoutOptions['viewport']): void {\n for (const side of [width, height]) {\n if (!Number.isInteger(side) || side <= 0 || side > MAX_VIEWPORT) {\n throw new RangeError(`The viewport needs whole positive pixel sizes, not ${width}×${height}`)\n }\n }\n}\n\n/** A fetch that gives up, answering null, once `signal` aborts. */\nfunction withDeadline<T>(request: Promise<T>, signal: AbortSignal): Promise<T | null> {\n const expired = new Promise<null>((resolve) => {\n signal.addEventListener('abort', () => resolve(null), { once: true })\n })\n return Promise.race([request.catch(() => null), expired])\n}\n\n/** Blitz's wasm-bindgen imports, which no capture calls: they trap with their name instead. */\nfunction unboundImports(module: WebAssembly.Module): WebAssembly.Imports {\n const imports: Record<string, Record<string, () => never>> = {}\n for (const { module: namespace, name } of WebAssembly.Module.imports(module)) {\n imports[namespace] ??= {}\n imports[namespace][name] = () => {\n throw new Error(`The HTML engine called its unbound import ${namespace}.${name}`)\n }\n }\n return imports\n}\n\nfunction engineExports(exports: WebAssembly.Exports): EngineExports {\n const { memory } = exports\n if (!(memory instanceof WebAssembly.Memory)) throw new Error('The HTML engine has no memory')\n const functions: Partial<Record<(typeof EXPORTS)[number], (...args: number[]) => number>> = {}\n for (const name of EXPORTS) {\n const exported = exports[name]\n if (typeof exported !== 'function') throw new Error(`The HTML engine lacks ${name}`)\n functions[name] = (...args) => Number(Reflect.apply(exported, undefined, args))\n }\n return {\n ...(functions as Record<(typeof EXPORTS)[number], (...args: number[]) => number>),\n memory\n }\n}\n\n/** The URL an image element's `src` resolves to, or null when it does not parse. */\nfunction imageURL(src: string, baseURL: string | undefined): string | null {\n try {\n return new URL(src, baseURL).href\n } catch {\n return null\n }\n}\n\n/**\n * The engine lays raster images out from SVG stand-ins and reports them as SVG; `rasters` holds\n * what each stood-in URL really was, which the capture reports instead.\n */\nfunction restoreImageKinds(\n capture: HTMLEngineCapture,\n rasters: ReadonlyMap<string, string>,\n baseURL: string | undefined\n): void {\n for (const node of capture.nodes) {\n const src = node.attrs?.src\n if (node.image !== 'svg' || src === undefined) continue\n const url = imageURL(src, baseURL)\n const kind = url === null ? undefined : rasters.get(url)\n if (kind) node.image = kind\n }\n}\n\n/**\n * Blitz, Stylo, Taffy, and Parley compiled to WebAssembly: lays HTML out as a browser does and\n * captures every element's box and computed styles, and the lines its text sets. The engine holds one document at a\n * time, so layouts on one instance run one after another.\n */\nexport class HTMLEngine {\n readonly #exports: EngineExports\n readonly #encoder = new TextEncoder()\n readonly #decoder = new TextDecoder()\n #queue: Promise<unknown> = Promise.resolve()\n\n private constructor(exports: EngineExports) {\n this.#exports = exports\n }\n\n /** Instantiates the module from its bytes or a compiled `WebAssembly.Module`. */\n static async instantiate(source: BufferSource | WebAssembly.Module): Promise<HTMLEngine> {\n const module = source instanceof WebAssembly.Module ? source : await WebAssembly.compile(source)\n const instance = await WebAssembly.instantiate(module, unboundImports(module))\n return new HTMLEngine(engineExports(instance.exports))\n }\n\n #withBytes<T>(bytes: Uint8Array, use: (pointer: number, length: number) => T): T {\n const pointer = this.#exports.alloc(bytes.length)\n new Uint8Array(this.#exports.memory.buffer, pointer, bytes.length).set(bytes)\n try {\n return use(pointer, bytes.length)\n } finally {\n this.#exports.dealloc(pointer, bytes.length)\n }\n }\n\n #withText<T>(text: string, use: (pointer: number, length: number) => T): T {\n return this.#withBytes(this.#encoder.encode(text), use)\n }\n\n #output(length: number): string {\n const pointer = this.#exports.output_ptr()\n return this.#decoder.decode(new Uint8Array(this.#exports.memory.buffer, pointer, length))\n }\n\n /**\n * Registers a font file for layouts that start after it; `alias` also registers it under\n * that family name, as browsers alias `-apple-system` to the system font. Returns the number\n * of faces it holds.\n */\n addFont(bytes: Uint8Array, alias?: string): number {\n return this.#withBytes(bytes, (pointer, length) =>\n this.#withText(alias ?? '', (aliasPointer, aliasLength) =>\n this.#exports.font_add(pointer, length, aliasPointer, aliasLength)\n )\n )\n }\n\n /**\n * Sets the registered families a generic family such as `sans-serif` falls back to, in order.\n * False when none of them is registered.\n */\n setGenericFamily(generic: string, families: readonly string[]): boolean {\n return this.#withText(generic, (genericPointer, genericLength) =>\n this.#withText(families.join('\\n'), (pointer, length) =>\n Boolean(this.#exports.font_generic(genericPointer, genericLength, pointer, length))\n )\n )\n }\n\n /** A font file as TrueType or OpenType, with WOFF and WOFF2 decompressed; others unchanged. */\n decodeFont(bytes: Uint8Array): Uint8Array {\n const length = this.#withBytes(bytes, (pointer, size) =>\n this.#exports.font_decode(pointer, size)\n )\n return new Uint8Array(this.#exports.memory.buffer, this.#exports.output_ptr(), length).slice()\n }\n\n /** Forgets every registered font. */\n resetFonts(): void {\n this.#exports.fonts_reset()\n }\n\n #pump(): [number, string][] {\n const parsed = v.safeParse(\n v.pipe(v.string(), v.parseJson(), requestsSchema),\n this.#output(this.#exports.pump())\n )\n if (!parsed.success) throw new Error('The HTML engine reported requests in an unknown shape')\n return parsed.output\n }\n\n /**\n * Answers one request, and returns what an image really was when the engine got a stand-in\n * for it, keyed by the URLs it was asked for and fetched from.\n */\n async #answer(\n id: number,\n url: string,\n options: HTMLEngineLayoutOptions\n ): Promise<[string[], string] | null> {\n const signal = AbortSignal.timeout(options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS)\n const { fetch } = options\n // An async wrapper turns a callback that throws before it returns into a rejection.\n const resource = fetch ? await withDeadline((async () => fetch(url, signal))(), signal) : null\n if (!resource) {\n this.#exports.fail(id)\n return null\n }\n const size = rasterImageSize(resource.bytes)\n const bytes = size ? imageStandIn(size) : resource.bytes\n this.#withText(resource.url, (urlPointer, urlLength) =>\n this.#withBytes(bytes, (pointer, length) =>\n this.#exports.provide(id, urlPointer, urlLength, pointer, length)\n )\n )\n return size ? [[url, resource.url], `raster ${size[0]}x${size[1]}`] : null\n }\n\n async #layout(html: string, options: HTMLEngineLayoutOptions): Promise<HTMLEngineCapture> {\n checkViewport(options.viewport)\n const { width, height } = options.viewport\n this.#withText(html, (htmlPointer, htmlLength) =>\n this.#withText(options.baseURL ?? '', (urlPointer, urlLength) =>\n this.#exports.open(htmlPointer, htmlLength, urlPointer, urlLength, width, height)\n )\n )\n // Answers can ask for more, such as a stylesheet's fonts, so pump until nothing is waiting.\n const rasters = new Map<string, string>()\n for (let requests = this.#pump(); requests.length > 0; requests = this.#pump()) {\n const answers = await Promise.all(requests.map(([id, url]) => this.#answer(id, url, options)))\n for (const [urls, kind] of answers.filter((answer) => answer !== null)) {\n for (const key of urls) rasters.set(key, kind)\n }\n }\n const parsed = v.safeParse(\n v.pipe(v.string(), v.parseJson(), captureSchema),\n this.#output(this.#exports.capture())\n )\n if (!parsed.success) throw new Error('The HTML engine captured a document in an unknown shape')\n restoreImageKinds(parsed.output, rasters, options.baseURL)\n return parsed.output\n }\n\n /** Lays the document out once every resource it asks for is answered, and captures it. */\n layout(html: string, options: HTMLEngineLayoutOptions): Promise<HTMLEngineCapture> {\n const run = this.#queue.then(() => this.#layout(html, options))\n this.#queue = run.catch(() => undefined)\n return run\n }\n}\n"],"mappings":";;AAQA,SAAS,MAAM,OAAmB,IAAY,QAAwB;CACpE,OAAO,OAAO,aAAa,GAAG,MAAM,SAAS,IAAI,KAAK,MAAM,CAAC;AAC/D;AAEA,SAAS,SAAS,OAAmB,MAA6B;CAChE,MAAM,QAAQ,MAAM,OAAO,IAAI,CAAC;CAChC,IAAI,UAAU,QACZ,OAAO,CAAC,KAAK,UAAU,IAAI,IAAI,IAAI,OAAQ,KAAK,UAAU,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,IAAI,IAAI;CACxE;CAEA,MAAMO,QAAQ,MAAc,SAA8D;EACxF,cAAc,QAAQ,QAAQ;EAC9B,MAAM,EAAE,OAAO,WAAW,QAAQ;EAClC,KAAKH,UAAU,OAAO,aAAa,eACjC,KAAKA,UAAU,QAAQ,WAAW,KAAK,YAAY,cACjD,KAAKJ,SAAS,KAAK,aAAa,YAAY,YAAY,WAAW,OAAO,MAAM,CAClF,CACF;EAEA,MAAM,0BAAU,IAAI,IAAoB;EACxC,KAAK,IAAI,WAAW,KAAKQ,MAAM,GAAG,SAAS,SAAS,GAAG,WAAW,KAAKA,MAAM,GAAG;GAC9E,MAAM,UAAU,MAAM,QAAQ,IAAI,SAAS,KAAK,CAAC,IAAI,SAAS,KAAKF,QAAQ,IAAI,KAAK,OAAO,CAAC,CAAC;GAC7F,KAAK,MAAM,CAAC,MAAM,SAAS,QAAQ,QAAQ,WAAW,WAAW,IAAI,GACnE,KAAK,MAAM,OAAO,MAAM,QAAQ,IAAI,KAAK,IAAI;EAEjD;EACA,MAAM,SAAS,EAAE,UACf,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,GAAG,aAAa,GAC/C,KAAKD,QAAQ,KAAKL,SAAS,QAAQ,CAAC,CACtC;EACA,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,MAAM,yDAAyD;EAC9F,kBAAkB,OAAO,QAAQ,SAAS,QAAQ,OAAO;EACzD,OAAO,OAAO;CAChB;;CAGA,OAAO,MAAc,SAA8D;EACjF,MAAM,MAAM,KAAKS,OAAO,WAAW,KAAKF,QAAQ,MAAM,OAAO,CAAC;EAC9D,KAAKE,SAAS,IAAI,YAAY,KAAA,CAAS;EACvC,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"engine.js","names":["#exports","#encoder","#decoder","#withBytes","#withText","#output","#answer","#layout","#pump","#layouts"],"sources":["../../src/images.ts","../../src/schema.ts","../../src/engine.ts"],"sourcesContent":["/**\n * The engine decodes no raster images, so layout learns an image's size from a stand-in SVG of\n * the same pixel size, read from the file's header. Formats are the ones browsers lay out from\n * their headers alone: PNG, GIF, WebP, JPEG, and AVIF.\n */\n\ntype Size = [width: number, height: number]\n\nfunction ascii(bytes: Uint8Array, at: number, length: number): string {\n return Array.from(bytes.subarray(at, at + length), (code) => String.fromCharCode(code)).join('')\n}\n\nfunction webpSize(bytes: Uint8Array, view: DataView): Size | null {\n const chunk = ascii(bytes, 12, 4)\n if (chunk === 'VP8 ')\n return [view.getUint16(26, true) & 0x3fff, view.getUint16(28, true) & 0x3fff]\n if (chunk === 'VP8L') {\n const bits = view.getUint32(21, true)\n return [(bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1]\n }\n if (chunk === 'VP8X') {\n const width = 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16))\n const height = 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16))\n return [width, height]\n }\n return null\n}\n\n/** Start-of-frame markers, which carry the size; C4, C8, and CC are other segments. */\nfunction isStartOfFrame(marker: number): boolean {\n return marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc\n}\n\nconst APP1 = 0xe1\nconst ORIENTATION_TAG = 0x0112\n\n/**\n * The Exif Orientation in an APP1 segment starting at `at`: 1 when the Exif data names none,\n * and null when the segment is not Exif, such as XMP, which says nothing about orientation. Orientations 5\n * to 8 turn the image a quarter, so browsers lay it out with width and height swapped.\n */\nfunction exifOrientation(\n bytes: Uint8Array,\n view: DataView,\n at: number,\n end: number\n): number | null {\n const tiff = at + 10\n if (tiff + 8 > end || ascii(bytes, at + 4, 6) !== 'Exif\\0\\0') return null\n const littleEndian = ascii(bytes, tiff, 2) === 'II'\n const firstIFD = tiff + view.getUint32(tiff + 4, littleEndian)\n if (firstIFD + 2 > end) return 1\n const entries = view.getUint16(firstIFD, littleEndian)\n for (let entry = 0; entry < entries; entry++) {\n const offset = firstIFD + 2 + entry * 12\n if (offset + 12 > end) return 1\n if (view.getUint16(offset, littleEndian) === ORIENTATION_TAG) {\n return view.getUint16(offset + 8, littleEndian)\n }\n }\n return 1\n}\n\nfunction jpegSize(bytes: Uint8Array, view: DataView): Size | null {\n let orientation = 1\n let at = 2\n while (at + 9 < bytes.length) {\n if (bytes[at] !== 0xff) return null\n // Any number of 0xFF fill bytes may come before a marker.\n let markerAt = at + 1\n while (markerAt < bytes.length && bytes[markerAt] === 0xff) markerAt++\n if (markerAt + 7 >= bytes.length) return null\n const marker = bytes[markerAt]\n // A segment's length counts its own two bytes, so less is a broken file.\n const length = view.getUint16(markerAt + 1)\n if (length < 2) return null\n const segment = markerAt - 1\n const end = Math.min(bytes.length, markerAt + 1 + length)\n if (marker === APP1) orientation = exifOrientation(bytes, view, segment, end) ?? orientation\n if (isStartOfFrame(marker)) {\n const size: Size = [view.getUint16(markerAt + 6), view.getUint16(markerAt + 4)]\n return orientation >= 5 && orientation <= 8 ? [size[1], size[0]] : size\n }\n at = end\n }\n return null\n}\n\nconst ISPE = [0x69, 0x73, 0x70, 0x65]\n\n/**\n * An AVIF's size from its `ispe` box, wherever the file puts it: the box's type, then its\n * version and flags, then two 32-bit sizes. A match counts only when the size the box header\n * before it gives holds all of that and fits in the file.\n */\nfunction avifSize(bytes: Uint8Array, view: DataView): Size | null {\n for (let at = 4; at + 16 <= bytes.length; at++) {\n if (ISPE.some((byte, index) => bytes[at + index] !== byte)) continue\n const boxSize = view.getUint32(at - 4)\n if (boxSize < 20 || at - 4 + boxSize > bytes.length) continue\n return [view.getUint32(at + 8), view.getUint32(at + 12)]\n }\n return null\n}\n\n/** An image file's pixel size from its header, or null for a format it does not know. */\nexport function rasterImageSize(bytes: Uint8Array): Size | null {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n // The size is in the IHDR chunk, which a PNG must start with.\n if (\n bytes.length > 24 &&\n bytes[0] === 0x89 &&\n ascii(bytes, 1, 3) === 'PNG' &&\n ascii(bytes, 12, 4) === 'IHDR'\n ) {\n return [view.getUint32(16), view.getUint32(20)]\n }\n if (bytes.length > 10 && ascii(bytes, 0, 3) === 'GIF') {\n return [view.getUint16(6, true), view.getUint16(8, true)]\n }\n if (bytes.length > 30 && ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP') {\n return webpSize(bytes, view)\n }\n if (bytes.length > 4 && bytes[0] === 0xff && bytes[1] === 0xd8) return jpegSize(bytes, view)\n if (bytes.length > 32 && ascii(bytes, 4, 4) === 'ftyp' && /avi[fs]/.test(ascii(bytes, 8, 4))) {\n return avifSize(bytes, view)\n }\n return null\n}\n\n/** An empty SVG of the image's size, which the engine lays out as the image would be. */\nexport function imageStandIn([width, height]: Size): Uint8Array {\n return new TextEncoder().encode(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\"/>`\n )\n}\n","import * as v from 'valibot'\n\nconst rectSchema = v.tuple([v.number(), v.number(), v.number(), v.number()])\n\nconst glyphRunSchema = v.object({\n /** The engine's id of the node whose text the run draws. */\n node: v.number(),\n x: v.number(),\n width: v.number(),\n text: v.string()\n})\n\nconst inlineBoxRunSchema = v.object({\n /** The engine's id of the atomic inline, such as an `inline-block`, the line holds. */\n box: v.number(),\n x: v.number(),\n width: v.number()\n})\n\nconst lineSchema = v.object({\n x: v.number(),\n y: v.number(),\n width: v.number(),\n height: v.number(),\n baseline: v.number(),\n runs: v.array(v.union([glyphRunSchema, inlineBoxRunSchema]))\n})\n\nconst capturedNodeSchema = v.object({\n /** The engine's own id, which runs and inline boxes refer to. */\n id: v.number(),\n /** The index in `nodes` of the element holding it. */\n parent: v.optional(v.number()),\n /** Set on text nodes, which carry nothing else. */\n text: v.optional(v.string()),\n /** The element's local name, or `::before` and `::after` for generated content. */\n tag: v.optional(v.string()),\n /** Attributes by name, namespaced ones with their prefix, as `xlink:href`. */\n attrs: v.optional(v.record(v.string(), v.string())),\n /** The border box, in page pixels. */\n box: v.optional(rectSchema),\n /** What the image element holds, such as `raster 640x480` or `svg`. */\n image: v.optional(v.string()),\n /**\n * Computed values: those with a fixed initial value only when they differ from it, and always\n * the ones whose initial value depends on the element or is inherited, such as `display`,\n * `color`, sizes, and font properties.\n */\n style: v.optional(v.record(v.string(), v.string())),\n /**\n * Computed values where `style`'s used ones lose what the page set: the sizes (`width`,\n * `height`, their minimums and maximums, and `flex-basis`) before layout resolves `auto` and\n * percentages to pixels, such as `auto`, `50%`, or `390px`, and `line-height`, such as `1.5`.\n */\n computed: v.optional(v.record(v.string(), v.string())),\n /** An inline element's box on each line it spans, in page pixels. */\n fragments: v.optional(v.array(rectSchema)),\n /** The lines of the inline formatting context the element holds, in page pixels. */\n lines: v.optional(v.array(lineSchema))\n})\n\n/** The document the engine laid out: every node, parents before children. */\nexport const captureSchema = v.object({\n engine: v.literal('blitz'),\n viewport: v.tuple([v.number(), v.number()]),\n /** The initial values of the properties nodes leave out of `style` when they hold them. */\n initial: v.record(v.string(), v.string()),\n nodes: v.array(capturedNodeSchema)\n})\n\n/** The resources the document is waiting for, as `[request id, URL]` pairs. */\nexport const requestsSchema = v.array(v.tuple([v.number(), v.string()]))\n\nexport type HTMLEngineCapture = v.InferOutput<typeof captureSchema>\nexport type HTMLEngineNode = v.InferOutput<typeof capturedNodeSchema>\nexport type HTMLEngineLine = v.InferOutput<typeof lineSchema>\n","import * as v from 'valibot'\n\nimport type { DesignResourceFetch } from '@open-pencil/dom-css'\nimport { createMutex } from '@open-pencil/std/async'\nimport { DEADLINE_MS, untilAborted } from '@open-pencil/std/timing'\n\nimport { imageStandIn, rasterImageSize } from './images'\nimport { captureSchema, requestsSchema, type HTMLEngineCapture } from './schema'\n\n/**\n * The module's exports: strings and bytes cross as (pointer, length), and results land in one\n * output buffer whose length the call returns.\n */\nconst EXPORTS = [\n 'alloc',\n 'dealloc',\n 'output_ptr',\n 'fonts_reset',\n 'font_decode',\n 'font_add',\n 'font_generic',\n 'open',\n 'pump',\n 'provide',\n 'fail',\n 'capture'\n] as const\n\ntype EngineExports = Record<(typeof EXPORTS)[number], (...args: number[]) => number> & {\n memory: WebAssembly.Memory\n}\n\n/** A resource the document asked for, as the host fetched it: its final URL and its bytes. */\nexport interface HTMLEngineLayoutOptions {\n /** The document's URL, which relative URLs in it resolve against. */\n baseURL?: string\n /** In whole CSS pixels. */\n viewport: { width: number; height: number }\n /** Answers the document's requests; without one, every request fails. */\n fetch?: DesignResourceFetch\n /** How long one request may take before the layout goes on without it. */\n requestTimeoutMs?: number\n}\n\n/**\n * How long a request may take by default: as long as the browser runtime waits for an image, so\n * one request that never ends cannot hold this layout, or the ones queued behind it, forever.\n */\nconst REQUEST_TIMEOUT_MS = DEADLINE_MS.request\n\n/** The largest viewport side the module takes, as a signed 32-bit length. */\nconst MAX_VIEWPORT = 0x7fffffff\n\nfunction checkViewport({ width, height }: HTMLEngineLayoutOptions['viewport']): void {\n for (const side of [width, height]) {\n if (!Number.isInteger(side) || side <= 0 || side > MAX_VIEWPORT) {\n throw new RangeError(`The viewport needs whole positive pixel sizes, not ${width}×${height}`)\n }\n }\n}\n\n/** A fetch that gives up, answering null, once it fails or `signal` aborts. */\nfunction withDeadline<T>(request: Promise<T>, signal: AbortSignal): Promise<T | null> {\n return untilAborted(request, signal).catch(() => null)\n}\n\n/** Blitz's wasm-bindgen imports, which no capture calls: they trap with their name instead. */\nfunction unboundImports(module: WebAssembly.Module): WebAssembly.Imports {\n const imports: Record<string, Record<string, () => never>> = {}\n for (const { module: namespace, name } of WebAssembly.Module.imports(module)) {\n imports[namespace] ??= {}\n imports[namespace][name] = () => {\n throw new Error(`The HTML engine called its unbound import ${namespace}.${name}`)\n }\n }\n return imports\n}\n\nfunction engineExports(exports: WebAssembly.Exports): EngineExports {\n const { memory } = exports\n if (!(memory instanceof WebAssembly.Memory)) throw new Error('The HTML engine has no memory')\n const functions: Partial<Record<(typeof EXPORTS)[number], (...args: number[]) => number>> = {}\n for (const name of EXPORTS) {\n const exported = exports[name]\n if (typeof exported !== 'function') throw new Error(`The HTML engine lacks ${name}`)\n functions[name] = (...args) => Number(Reflect.apply(exported, undefined, args))\n }\n return {\n ...(functions as Record<(typeof EXPORTS)[number], (...args: number[]) => number>),\n memory\n }\n}\n\n/** The URL an image element's `src` resolves to, or null when it does not parse. */\nfunction imageURL(src: string, baseURL: string | undefined): string | null {\n try {\n return new URL(src, baseURL).href\n } catch {\n return null\n }\n}\n\n/**\n * The engine lays raster images out from SVG stand-ins and reports them as SVG; `rasters` holds\n * what each stood-in URL really was, which the capture reports instead.\n */\nfunction restoreImageKinds(\n capture: HTMLEngineCapture,\n rasters: ReadonlyMap<string, string>,\n baseURL: string | undefined\n): void {\n for (const node of capture.nodes) {\n const src = node.attrs?.src\n if (node.image !== 'svg' || src === undefined) continue\n const url = imageURL(src, baseURL)\n const kind = url === null ? undefined : rasters.get(url)\n if (kind) node.image = kind\n }\n}\n\n/**\n * Blitz, Stylo, Taffy, and Parley compiled to WebAssembly: lays HTML out as a browser does and\n * captures every element's box and computed styles, and the lines its text sets. The engine holds one document at a\n * time, so layouts on one instance run one after another.\n */\nexport class HTMLEngine {\n readonly #exports: EngineExports\n readonly #encoder = new TextEncoder()\n readonly #decoder = new TextDecoder()\n #layouts = createMutex()\n\n private constructor(exports: EngineExports) {\n this.#exports = exports\n }\n\n /** Instantiates the module from its bytes or a compiled `WebAssembly.Module`. */\n static async instantiate(source: BufferSource | WebAssembly.Module): Promise<HTMLEngine> {\n const module = source instanceof WebAssembly.Module ? source : await WebAssembly.compile(source)\n const instance = await WebAssembly.instantiate(module, unboundImports(module))\n return new HTMLEngine(engineExports(instance.exports))\n }\n\n #withBytes<T>(bytes: Uint8Array, use: (pointer: number, length: number) => T): T {\n const pointer = this.#exports.alloc(bytes.length)\n new Uint8Array(this.#exports.memory.buffer, pointer, bytes.length).set(bytes)\n try {\n return use(pointer, bytes.length)\n } finally {\n this.#exports.dealloc(pointer, bytes.length)\n }\n }\n\n #withText<T>(text: string, use: (pointer: number, length: number) => T): T {\n return this.#withBytes(this.#encoder.encode(text), use)\n }\n\n #output(length: number): string {\n const pointer = this.#exports.output_ptr()\n return this.#decoder.decode(new Uint8Array(this.#exports.memory.buffer, pointer, length))\n }\n\n /**\n * Registers a font file for layouts that start after it; `alias` also registers it under\n * that family name, as browsers alias `-apple-system` to the system font. Returns the number\n * of faces it holds.\n */\n addFont(bytes: Uint8Array, alias?: string): number {\n return this.#withBytes(bytes, (pointer, length) =>\n this.#withText(alias ?? '', (aliasPointer, aliasLength) =>\n this.#exports.font_add(pointer, length, aliasPointer, aliasLength)\n )\n )\n }\n\n /**\n * Sets the registered families a generic family such as `sans-serif` falls back to, in order.\n * False when none of them is registered.\n */\n setGenericFamily(generic: string, families: readonly string[]): boolean {\n return this.#withText(generic, (genericPointer, genericLength) =>\n this.#withText(families.join('\\n'), (pointer, length) =>\n Boolean(this.#exports.font_generic(genericPointer, genericLength, pointer, length))\n )\n )\n }\n\n /** A font file as TrueType or OpenType, with WOFF and WOFF2 decompressed; others unchanged. */\n decodeFont(bytes: Uint8Array): Uint8Array {\n const length = this.#withBytes(bytes, (pointer, size) =>\n this.#exports.font_decode(pointer, size)\n )\n return new Uint8Array(this.#exports.memory.buffer, this.#exports.output_ptr(), length).slice()\n }\n\n /** Forgets every registered font. */\n resetFonts(): void {\n this.#exports.fonts_reset()\n }\n\n #pump(): [number, string][] {\n const parsed = v.safeParse(\n v.pipe(v.string(), v.parseJson(), requestsSchema),\n this.#output(this.#exports.pump())\n )\n if (!parsed.success) throw new Error('The HTML engine reported requests in an unknown shape')\n return parsed.output\n }\n\n /**\n * Answers one request, and returns what an image really was when the engine got a stand-in\n * for it, keyed by the URLs it was asked for and fetched from.\n */\n async #answer(\n id: number,\n url: string,\n options: HTMLEngineLayoutOptions\n ): Promise<[string[], string] | null> {\n const signal = AbortSignal.timeout(options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS)\n const { fetch } = options\n // An async wrapper turns a callback that throws before it returns into a rejection.\n const resource = fetch ? await withDeadline((async () => fetch(url, signal))(), signal) : null\n if (!resource) {\n this.#exports.fail(id)\n return null\n }\n const size = rasterImageSize(resource.bytes)\n const bytes = size ? imageStandIn(size) : resource.bytes\n this.#withText(resource.url, (urlPointer, urlLength) =>\n this.#withBytes(bytes, (pointer, length) =>\n this.#exports.provide(id, urlPointer, urlLength, pointer, length)\n )\n )\n return size ? [[url, resource.url], `raster ${size[0]}x${size[1]}`] : null\n }\n\n async #layout(html: string, options: HTMLEngineLayoutOptions): Promise<HTMLEngineCapture> {\n checkViewport(options.viewport)\n const { width, height } = options.viewport\n this.#withText(html, (htmlPointer, htmlLength) =>\n this.#withText(options.baseURL ?? '', (urlPointer, urlLength) =>\n this.#exports.open(htmlPointer, htmlLength, urlPointer, urlLength, width, height)\n )\n )\n // Answers can ask for more, such as a stylesheet's fonts, so pump until nothing is waiting.\n const rasters = new Map<string, string>()\n for (let requests = this.#pump(); requests.length > 0; requests = this.#pump()) {\n const answers = await Promise.all(requests.map(([id, url]) => this.#answer(id, url, options)))\n for (const [urls, kind] of answers.filter((answer) => answer !== null)) {\n for (const key of urls) rasters.set(key, kind)\n }\n }\n const parsed = v.safeParse(\n v.pipe(v.string(), v.parseJson(), captureSchema),\n this.#output(this.#exports.capture())\n )\n if (!parsed.success) throw new Error('The HTML engine captured a document in an unknown shape')\n restoreImageKinds(parsed.output, rasters, options.baseURL)\n return parsed.output\n }\n\n /** Lays the document out once every resource it asks for is answered, and captures it. */\n layout(html: string, options: HTMLEngineLayoutOptions): Promise<HTMLEngineCapture> {\n return this.#layouts.run(() => this.#layout(html, options))\n }\n}\n"],"mappings":";;;;AAQA,SAAS,MAAM,OAAmB,IAAY,QAAwB;CACpE,OAAO,MAAM,KAAK,MAAM,SAAS,IAAI,KAAK,MAAM,IAAI,SAAS,OAAO,aAAa,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE;AACjG;AAEA,SAAS,SAAS,OAAmB,MAA6B;CAChE,MAAM,QAAQ,MAAM,OAAO,IAAI,CAAC;CAChC,IAAI,UAAU,QACZ,OAAO,C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AK,IAAI,IAAI;CACxE;CAEA,MAAMO,QAAQ,MAAc,SAA8D;EACxF,cAAc,QAAQ,QAAQ;EAC9B,MAAM,EAAE,OAAO,WAAW,QAAQ;EAClC,KAAKH,UAAU,OAAO,aAAa,eACjC,KAAKA,UAAU,QAAQ,WAAW,KAAK,YAAY,cACjD,KAAKJ,SAAS,KAAK,aAAa,YAAY,YAAY,WAAW,OAAO,MAAM,CAClF,CACF;EAEA,MAAM,0BAAU,IAAI,IAAoB;EACxC,KAAK,IAAI,WAAW,KAAKQ,MAAM,GAAG,SAAS,SAAS,GAAG,WAAW,KAAKA,MAAM,GAAG;GAC9E,MAAM,UAAU,MAAM,QAAQ,IAAI,SAAS,KAAK,CAAC,IAAI,SAAS,KAAKF,QAAQ,IAAI,KAAK,OAAO,CAAC,CAAC;GAC7F,KAAK,MAAM,CAAC,MAAM,SAAS,QAAQ,QAAQ,WAAW,WAAW,IAAI,GACnE,KAAK,MAAM,OAAO,MAAM,QAAQ,IAAI,KAAK,IAAI;EAEjD;EACA,MAAM,SAAS,EAAE,UACf,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,GAAG,aAAa,GAC/C,KAAKD,QAAQ,KAAKL,SAAS,QAAQ,CAAC,CACtC;EACA,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,MAAM,yDAAyD;EAC9F,kBAAkB,OAAO,QAAQ,SAAS,QAAQ,OAAO;EACzD,OAAO,OAAO;CAChB;;CAGA,OAAO,MAAc,SAA8D;EACjF,OAAO,KAAKS,SAAS,UAAU,KAAKF,QAAQ,MAAM,OAAO,CAAC;CAC5D;AACF"}
|
package/dist/chunks/index.js
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { HTMLEngine } from "./engine.js";
|
|
2
|
-
import {
|
|
2
|
+
import { DEADLINE_MS } from "@open-pencil/std/timing";
|
|
3
|
+
import { parseFontFaceRules, parseHTMLDocument, parseStylesheetImports } from "@open-pencil/dom-css";
|
|
4
|
+
import { serializeHTML } from "@open-pencil/dom-css/export";
|
|
5
|
+
import { parseCSSColor } from "@open-pencil/scene-graph/css";
|
|
6
|
+
import { computeBounds } from "@open-pencil/scene-graph/geometry";
|
|
7
|
+
import { insertAll, maxOf, minOf } from "@open-pencil/std/arrays";
|
|
3
8
|
//#region src/load.ts
|
|
4
9
|
let locator = () => import.meta.resolve("@open-pencil/html-engine/wasm/html-engine.wasm");
|
|
5
10
|
let loading = null;
|
|
@@ -7,7 +12,7 @@ let loading = null;
|
|
|
7
12
|
* How long a remote module may take to arrive, so a request that never settles cannot hold every
|
|
8
13
|
* later load waiting on it; a failed load is retried by the next caller.
|
|
9
14
|
*/
|
|
10
|
-
const MODULE_LOAD_TIMEOUT_MS =
|
|
15
|
+
const MODULE_LOAD_TIMEOUT_MS = DEADLINE_MS.transfer;
|
|
11
16
|
/** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */
|
|
12
17
|
function setHTMLEngineLocator(locate) {
|
|
13
18
|
locator = locate;
|
|
@@ -130,7 +135,7 @@ function pairElements(document, capture) {
|
|
|
130
135
|
while (node !== void 0 && !sameTag(capture.nodes[node].tag, element.tagName)) {
|
|
131
136
|
const tag = capture.nodes[node].tag;
|
|
132
137
|
if (tag === void 0 || !IMPLIED_WRAPPERS.has(tag)) return;
|
|
133
|
-
queue
|
|
138
|
+
insertAll(queue, 0, children.get(node) ?? []);
|
|
134
139
|
node = queue.shift();
|
|
135
140
|
}
|
|
136
141
|
if (node === void 0) return;
|
|
@@ -173,8 +178,8 @@ function textLine(line, keepsSpaces) {
|
|
|
173
178
|
const texts = line.runs.filter((run) => "text" in run && run.text.length > 0);
|
|
174
179
|
const words = keepsSpaces ? texts : texts.filter((run) => "text" in run && run.text.trim() !== "");
|
|
175
180
|
if (words.length === 0) return null;
|
|
176
|
-
const left =
|
|
177
|
-
const right =
|
|
181
|
+
const left = minOf(words.map((run) => run.x));
|
|
182
|
+
const right = maxOf(words.map((run) => run.x + run.width));
|
|
178
183
|
return {
|
|
179
184
|
x: left,
|
|
180
185
|
y: line.y,
|
|
@@ -188,6 +193,7 @@ function layoutOf(node) {
|
|
|
188
193
|
const fragments = node.fragments?.filter(hasArea);
|
|
189
194
|
if (fragments && fragments.length > 0) {
|
|
190
195
|
layout.fragments = fragments.map(rect);
|
|
196
|
+
layout.box = computeBounds(layout.fragments);
|
|
191
197
|
return layout;
|
|
192
198
|
}
|
|
193
199
|
const whiteSpace = node.style?.["white-space"];
|
|
@@ -202,31 +208,119 @@ function documentHTML(body, cssText) {
|
|
|
202
208
|
/**
|
|
203
209
|
* A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,
|
|
204
210
|
* without one: computed styles and, when asked, the boxes, inline fragments, and text lines a
|
|
205
|
-
* browser runtime records, before transforms. Documents are parsed and serialized
|
|
206
|
-
* runtime does.
|
|
211
|
+
* browser runtime records, before transforms. Documents are parsed and serialized by dom-css.
|
|
207
212
|
*/
|
|
213
|
+
/** The `::before` and `::after` nodes of each captured element, by the element's index. */
|
|
214
|
+
function generatedChildren(capture) {
|
|
215
|
+
const generated = /* @__PURE__ */ new Map();
|
|
216
|
+
for (const [index, node] of capture.nodes.entries()) {
|
|
217
|
+
if (node.parent === void 0 || !node.tag?.startsWith("::")) continue;
|
|
218
|
+
generated.set(node.parent, [...generated.get(node.parent) ?? [], index]);
|
|
219
|
+
}
|
|
220
|
+
return generated;
|
|
221
|
+
}
|
|
222
|
+
/** The text a captured node holds directly, as a pseudo-element's generated content. */
|
|
223
|
+
/** Each captured node's own text, its text children's joined in order, by the node's index. */
|
|
224
|
+
function ownTexts(capture) {
|
|
225
|
+
const texts = /* @__PURE__ */ new Map();
|
|
226
|
+
for (const node of capture.nodes) {
|
|
227
|
+
if (node.text === void 0 || node.parent === void 0) continue;
|
|
228
|
+
texts.set(node.parent, (texts.get(node.parent) ?? "") + node.text);
|
|
229
|
+
}
|
|
230
|
+
return texts;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Shows each element's `::before` and `::after` as elements of their own, first and last among its
|
|
234
|
+
* children, with the style, box, and text the engine generated for them, so they are imported as
|
|
235
|
+
* any element is.
|
|
236
|
+
*/
|
|
237
|
+
function showGeneratedContent(capture, pairs, layout) {
|
|
238
|
+
const indexes = new Map(capture.nodes.map((node, index) => [node, index]));
|
|
239
|
+
const generated = generatedChildren(capture);
|
|
240
|
+
const texts = ownTexts(capture);
|
|
241
|
+
for (const [element, node] of pairs) {
|
|
242
|
+
const index = indexes.get(node);
|
|
243
|
+
for (const pseudo of (index === void 0 ? void 0 : generated.get(index)) ?? []) {
|
|
244
|
+
const captured = capture.nodes[pseudo];
|
|
245
|
+
const text = texts.get(pseudo) ?? "";
|
|
246
|
+
const child = {
|
|
247
|
+
type: "element",
|
|
248
|
+
tagName: captured.tag ?? "::before",
|
|
249
|
+
attrs: {},
|
|
250
|
+
children: text ? [{
|
|
251
|
+
type: "text",
|
|
252
|
+
text
|
|
253
|
+
}] : [],
|
|
254
|
+
computedStyle: withShorthands({
|
|
255
|
+
...capture.initial,
|
|
256
|
+
...captured.style,
|
|
257
|
+
...captured.computed
|
|
258
|
+
})
|
|
259
|
+
};
|
|
260
|
+
if (layout) child.layout = layoutOf(captured);
|
|
261
|
+
if (captured.tag === "::after") element.children.push(child);
|
|
262
|
+
else element.children.unshift(child);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* The color the page's canvas is painted, as CSS takes it: the root element's background, or the
|
|
268
|
+
* body's when the root has none.
|
|
269
|
+
*/
|
|
270
|
+
function canvasBackground(capture) {
|
|
271
|
+
const background = (tag) => {
|
|
272
|
+
const color = capture.nodes.find((candidate) => candidate.tag === tag)?.style?.["background-color"];
|
|
273
|
+
return color && parseCSSColor(color) ? color : void 0;
|
|
274
|
+
};
|
|
275
|
+
return background("html") ?? background("body");
|
|
276
|
+
}
|
|
277
|
+
/** A fetch that also keeps what it answered, by the URL asked for and the one it came from. */
|
|
278
|
+
function keepingFetch(fetch, answered) {
|
|
279
|
+
if (!fetch) return void 0;
|
|
280
|
+
return async (url, signal) => {
|
|
281
|
+
const resource = await fetch(url, signal);
|
|
282
|
+
if (resource) answered.set(url, resource).set(resource.url, resource);
|
|
283
|
+
return resource;
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
/** What an `<img>` loaded, by its `src` resolved against the page's address. */
|
|
287
|
+
function imageOf(element, answered, baseURL) {
|
|
288
|
+
const { src } = element.attrs;
|
|
289
|
+
if (element.tagName.toLowerCase() !== "img" || !src || !URL.canParse(src, baseURL)) return;
|
|
290
|
+
return answered.get(new URL(src, baseURL).href);
|
|
291
|
+
}
|
|
208
292
|
function createHTMLEngineRuntime(options = {}) {
|
|
209
|
-
const markup = createHeadlessCSSRuntime();
|
|
210
293
|
const engine = options.engine ?? loadHTMLEngine;
|
|
211
294
|
return {
|
|
212
295
|
kind: "headless",
|
|
213
|
-
parseHTML:
|
|
214
|
-
serializeHTML
|
|
296
|
+
parseHTML: parseHTMLDocument,
|
|
297
|
+
serializeHTML,
|
|
215
298
|
async computeStyles(document, cssText = "", compute = {}) {
|
|
216
299
|
const laidOut = await engine();
|
|
217
|
-
const
|
|
300
|
+
const answered = /* @__PURE__ */ new Map();
|
|
301
|
+
const fetch = keepingFetch(options.fetch, answered);
|
|
302
|
+
const capture = await laidOut.layout(documentHTML(serializeHTML(document), cssText), {
|
|
218
303
|
baseURL: options.baseURL,
|
|
219
304
|
viewport: compute.viewport ?? DEFAULT_VIEWPORT,
|
|
220
|
-
fetch: fontFaceFetch(laidOut, cssText,
|
|
305
|
+
fetch: fontFaceFetch(laidOut, cssText, {
|
|
306
|
+
...options,
|
|
307
|
+
fetch
|
|
308
|
+
})
|
|
221
309
|
});
|
|
222
310
|
const styled = structuredClone(document);
|
|
223
|
-
|
|
311
|
+
const pairs = pairElements(styled, capture);
|
|
312
|
+
for (const [element, node] of pairs) {
|
|
224
313
|
element.computedStyle = withShorthands({
|
|
225
314
|
...capture.initial,
|
|
226
|
-
...node.style
|
|
315
|
+
...node.style,
|
|
316
|
+
...node.computed
|
|
227
317
|
});
|
|
228
318
|
if (compute.layout) element.layout = layoutOf(node);
|
|
319
|
+
const image = imageOf(element, answered, options.baseURL);
|
|
320
|
+
if (image) element.image = image;
|
|
229
321
|
}
|
|
322
|
+
showGeneratedContent(capture, pairs, compute.layout === true);
|
|
323
|
+
styled.background = canvasBackground(capture);
|
|
230
324
|
return styled;
|
|
231
325
|
}
|
|
232
326
|
};
|
package/dist/chunks/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/load.ts","../../src/runtime.ts"],"sourcesContent":["import { HTMLEngine } from './engine'\n\n/**\n * Where the engine's module (`html-engine.wasm`) loads from. By default it is read beside this\n * package, as Node and Bun resolve it; a host that serves it elsewhere, such as a bundled app,\n * points here instead.\n */\nexport type HTMLEngineLocator = () => string\n\nlet locator: HTMLEngineLocator = () =>\n import.meta.resolve('@open-pencil/html-engine/wasm/html-engine.wasm')\n\nlet loading: Promise<HTMLEngine> | null = null\n\n/**\n * How long a remote module may take to arrive, so a request that never settles cannot hold every\n * later load waiting on it; a failed load is retried by the next caller.\n */\nconst MODULE_LOAD_TIMEOUT_MS = 60_000\n\n/** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */\nexport function setHTMLEngineLocator(locate: HTMLEngineLocator): void {\n locator = locate\n loading = null\n}\n\nasync function readModule(url: string): Promise<ArrayBuffer> {\n if (!url.startsWith('file:')) {\n const response = await fetch(url, { signal: AbortSignal.timeout(MODULE_LOAD_TIMEOUT_MS) })\n if (!response.ok)\n throw new Error(`html-engine.wasm failed to load from ${url}: ${response.status}`)\n return response.arrayBuffer()\n }\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n const file = await readFile(new URL(url)).catch((error: unknown) => {\n throw new Error(\n `html-engine.wasm is missing at ${url}; build it with bun run build in packages/html-engine`,\n { cause: error }\n )\n })\n return file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength)\n}\n\n/** The engine, loaded once; a failed load is retried by the next caller. */\nexport function loadHTMLEngine(): Promise<HTMLEngine> {\n if (loading) return loading\n const load = readModule(locator()).then((bytes) => HTMLEngine.instantiate(bytes))\n loading = load\n load.catch(() => {\n if (loading === load) loading = null\n })\n return load\n}\n","import {\n createHeadlessCSSRuntime,\n parseFontFaceRules,\n parseStylesheetImports,\n type CSSFontFaceRule,\n type CSSComputeOptions,\n type CSSRuntime,\n type DesignDocument,\n type DesignElement,\n type DesignLayout,\n type DesignStyleDeclaration,\n type DesignViewport\n} from '@open-pencil/dom-css'\nimport type { Rect } from '@open-pencil/scene-graph/primitives'\n\nimport type { HTMLEngine, HTMLEngineFetch, HTMLEngineResource } from './engine'\nimport { loadHTMLEngine } from './load'\nimport type { HTMLEngineCapture, HTMLEngineLine, HTMLEngineNode } from './schema'\n\n/** The viewport a document is laid out in when the caller names none, as HTML import uses. */\nconst DEFAULT_VIEWPORT: DesignViewport = { width: 1440, height: 900 }\n\n/** A font a page's `@font-face` rule loads: the face the rule declares, and the file as TrueType or OpenType. */\nexport interface HTMLEngineFontFace {\n family: string\n weight: number\n italic: boolean\n url: string\n bytes: Uint8Array\n}\n\nexport interface HTMLEngineRuntimeOptions {\n /** The engine to lay documents out with, with the fonts they may use registered. */\n engine?: () => Promise<HTMLEngine>\n /** The document's URL, which its relative URLs resolve against. */\n baseURL?: string\n /**\n * Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for\n * its `@font-face` rules when it comes with a CSS content type.\n */\n fetch?: HTMLEngineFetch\n /**\n * Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so\n * a host can draw that text in the same font. The layout waits for it.\n */\n onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>\n}\n\nfunction isStylesheet(resource: HTMLEngineResource): boolean {\n return resource.contentType?.split(';')[0]?.trim().toLowerCase() === 'text/css'\n}\n\n/**\n * A fetch that also reads the page's `@font-face` rules, from its own CSS and every stylesheet it\n * fetches, and passes each font they load to `onFontFace` as the engine receives it.\n */\nfunction fontFaceFetch(\n engine: HTMLEngine,\n cssText: string,\n options: HTMLEngineRuntimeOptions\n): HTMLEngineFetch | undefined {\n const { fetch, onFontFace } = options\n if (!fetch || !onFontFace) return fetch\n const rules = new Map<string, CSSFontFaceRule[]>()\n // What CSS imports is a stylesheet whatever its name or the type it is served as.\n const stylesheets = new Set<string>()\n // The engine fetches a file once per rule that names it; each face is passed on once.\n const delivered = new Set<string>()\n const learn = (css: string, base: string | undefined) => {\n for (const rule of parseFontFaceRules(css, base)) {\n for (const source of rule.sources) rules.set(source, [...(rules.get(source) ?? []), rule])\n }\n for (const url of parseStylesheetImports(css, base)) stylesheets.add(url)\n }\n learn(cssText, options.baseURL)\n return async (url, signal) => {\n const resource = await fetch(url, signal)\n if (!resource) return null\n if (isStylesheet(resource) || stylesheets.has(url) || stylesheets.has(resource.url)) {\n learn(new TextDecoder().decode(resource.bytes), resource.url)\n }\n // One file can serve several rules, such as a family and an alias of it.\n const served = rules.get(url) ?? rules.get(resource.url) ?? []\n const bytes = served.length > 0 ? engine.decodeFont(resource.bytes) : null\n for (const rule of served) {\n const face = `${url}|${rule.family}|${rule.weight}|${rule.italic}`\n if (!bytes || delivered.has(face)) continue\n delivered.add(face)\n await onFontFace({\n family: rule.family,\n weight: rule.weight,\n italic: rule.italic,\n url,\n bytes\n })\n }\n return resource\n }\n}\n\ntype Box = HTMLEngineCapture['nodes'][number]['box']\n\nfunction rect(box: NonNullable<Box>): Rect {\n const [x, y, width, height] = box\n return { x, y, width, height }\n}\n\nfunction hasArea(box: NonNullable<Box>): boolean {\n return box[2] > 0 && box[3] > 0\n}\n\n/** Children of each captured node that are elements, by the node's index; generated content left out. */\nfunction elementChildren(capture: HTMLEngineCapture): Map<number, number[]> {\n const children = new Map<number, number[]>()\n for (const [index, node] of capture.nodes.entries()) {\n if (node.parent === undefined || node.tag === undefined || node.tag.startsWith('::')) continue\n const siblings = children.get(node.parent) ?? []\n siblings.push(index)\n children.set(node.parent, siblings)\n }\n return children\n}\n\n/**\n * Elements the HTML parser inserts around others where the markup leaves them out, such as the\n * `tbody` around a table's rows; a serialized document need not hold them.\n */\nconst IMPLIED_WRAPPERS = new Set(['tbody'])\n\n/**\n * Each element of the document with the captured element it was laid out as: matched in order\n * and by tag, looking through wrappers the parser inserted. A mismatch ends the matching among\n * those siblings, so it never pairs an element with another's box.\n */\nfunction pairElements(\n document: DesignDocument,\n capture: HTMLEngineCapture\n): [DesignElement, HTMLEngineNode][] {\n const children = elementChildren(capture)\n const body = capture.nodes.findIndex((node) => node.tag === 'body')\n const pairs: [DesignElement, HTMLEngineNode][] = []\n const pair = (elements: readonly DesignElement[], parent: number, shaderFrame = false) => {\n const queue = [...(children.get(parent) ?? [])]\n // The serializer writes a shader's still frame as an image ahead of its layer's children.\n const first = queue.at(0)\n if (shaderFrame && first !== undefined && capture.nodes[first].tag === 'img') queue.shift()\n for (const element of elements) {\n let node = queue.shift()\n // The HTML parser keeps SVG's mixed-case names, such as `linearGradient`; the document may not.\n while (node !== undefined && !sameTag(capture.nodes[node].tag, element.tagName)) {\n const tag = capture.nodes[node].tag\n if (tag === undefined || !IMPLIED_WRAPPERS.has(tag)) return\n queue.unshift(...(children.get(node) ?? []))\n node = queue.shift()\n }\n if (node === undefined) return\n pairs.push([element, capture.nodes[node]])\n pair(designElements(element.children), node, element.shader?.frame !== undefined)\n }\n }\n if (body !== -1) pair(designElements(document.children), body)\n return pairs\n}\n\nfunction sameTag(captured: string | undefined, tagName: string): boolean {\n return captured?.toLowerCase() === tagName.toLowerCase()\n}\n\nfunction designElements(nodes: DesignDocument['children']): DesignElement[] {\n return nodes.filter((node): node is DesignElement => node.type === 'element')\n}\n\n/** Shorthands a browser runtime reports, `overflow` and `gap`, built from their captured longhands. */\nfunction withShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {\n // Captures leave initial values out.\n const value = (property: string, initial: string) =>\n Object.hasOwn(style, property) ? style[property] : initial\n const pair = (first: string, second: string) => (first === second ? first : `${first} ${second}`)\n const shorthands: DesignStyleDeclaration = {}\n if (Object.hasOwn(style, 'overflow-x') || Object.hasOwn(style, 'overflow-y')) {\n shorthands.overflow = pair(value('overflow-x', 'visible'), value('overflow-y', 'visible'))\n }\n if (Object.hasOwn(style, 'row-gap') || Object.hasOwn(style, 'column-gap')) {\n shorthands.gap = pair(value('row-gap', 'normal'), value('column-gap', 'normal'))\n }\n return { ...style, ...shorthands }\n}\n\n/** White space values that keep spaces, so a line of them takes room as a line of words does. */\nconst PRESERVED_WHITE_SPACE = new Set(['pre', 'pre-wrap', 'break-spaces'])\n\n/**\n * A line as a browser's text rects make it: across its words, leaving out inline boxes, and\n * nothing for a line without text. Where white space is kept, a line of spaces counts too.\n */\nfunction textLine(line: HTMLEngineLine, keepsSpaces: boolean): Rect | null {\n const texts = line.runs.filter((run) => 'text' in run && run.text.length > 0)\n const words = keepsSpaces ? texts : texts.filter((run) => 'text' in run && run.text.trim() !== '')\n if (words.length === 0) return null\n const left = Math.min(...words.map((run) => run.x))\n const right = Math.max(...words.map((run) => run.x + run.width))\n return { x: left, y: line.y, width: right - left, height: line.height }\n}\n\nfunction layoutOf(node: HTMLEngineNode): DesignLayout | undefined {\n if (!node.box) return undefined\n const layout: DesignLayout = { box: rect(node.box) }\n const fragments = node.fragments?.filter(hasArea)\n if (fragments && fragments.length > 0) {\n layout.fragments = fragments.map(rect)\n return layout\n }\n const whiteSpace = node.style?.['white-space']\n const keepsSpaces = whiteSpace !== undefined && PRESERVED_WHITE_SPACE.has(whiteSpace)\n const lines = (node.lines ?? [])\n .map((line) => textLine(line, keepsSpaces))\n .filter((line) => line !== null)\n if (lines.length > 0) layout.lines = lines\n return layout\n}\n\nfunction documentHTML(body: string, cssText: string): string {\n // `</style` would end the stylesheet early.\n const css = cssText.replaceAll(/<\\/style/gi, '<\\\\/style')\n return `<!doctype html><html><head><style>${css}</style></head><body>${body}</body></html>`\n}\n\n/**\n * A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,\n * without one: computed styles and, when asked, the boxes, inline fragments, and text lines a\n * browser runtime records, before transforms. Documents are parsed and serialized as the headless\n * runtime does.\n */\nexport function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}): CSSRuntime {\n const markup = createHeadlessCSSRuntime()\n const engine = options.engine ?? loadHTMLEngine\n return {\n kind: 'headless',\n parseHTML: (html) => markup.parseHTML(html),\n serializeHTML: (document) => markup.serializeHTML(document),\n async computeStyles(document, cssText = '', compute: CSSComputeOptions = {}) {\n const laidOut = await engine()\n const capture = await laidOut.layout(documentHTML(markup.serializeHTML(document), cssText), {\n baseURL: options.baseURL,\n viewport: compute.viewport ?? DEFAULT_VIEWPORT,\n fetch: fontFaceFetch(laidOut, cssText, options)\n })\n const styled = structuredClone(document)\n for (const [element, node] of pairElements(styled, capture)) {\n // Every captured property's computed value, so none falls back to a stale inline one.\n element.computedStyle = withShorthands({ ...capture.initial, ...node.style })\n if (compute.layout) element.layout = layoutOf(node)\n }\n return styled\n }\n }\n}\n"],"mappings":";;;AASA,IAAI,gBACF,YAAY,QAAQ,gDAAgD;AAEtE,IAAI,UAAsC;;;;;AAM1C,MAAM,yBAAyB;;AAG/B,SAAgB,qBAAqB,QAAiC;CACpE,UAAU;CACV,UAAU;AACZ;AAEA,eAAe,WAAW,KAAmC;CAC3D,IAAI,CAAC,IAAI,WAAW,OAAO,GAAG;EAC5B,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,QAAQ,YAAY,QAAQ,sBAAsB,EAAE,CAAC;EACzF,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,wCAAwC,IAAI,IAAI,SAAS,QAAQ;EACnF,OAAO,SAAS,YAAY;CAC9B;CACA,MAAM,EAAE,aAAa,MAAM;;EAA0B;;CACrD,MAAM,OAAO,MAAM,SAAS,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,OAAO,UAAmB;EAClE,MAAM,IAAI,MACR,kCAAkC,IAAI,wDAC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AsB,IAAI,UAAU;CACpF,MAAM,SAAS,KAAK,SAAS,CAAC,EAAA,CAC3B,KAAK,SAAS,SAAS,MAAM,WAAW,CAAC,CAAC,CAC1C,QAAQ,SAAS,SAAS,IAAI;CACjC,IAAI,MAAM,SAAS,GAAG,OAAO,QAAQ;CACrC,OAAO;AACT;AAEA,SAAS,aAAa,MAAc,SAAyB;CAG3D,OAAO,qCADK,QAAQ,WAAW,cAAc,WACC,EAAE,uBAAuB,KAAK;AAC9E;;;;;;;AAQA,SAAgB,wBAAwB,UAAoC,CAAC,GAAe;CAC1F,MAAM,SAAS,yBAAyB;CACxC,MAAM,SAAS,QAAQ,UAAU;CACjC,OAAO;EACL,MAAM;EACN,YAAY,SAAS,OAAO,UAAU,IAAI;EAC1C,gBAAgB,aAAa,OAAO,cAAc,QAAQ;EAC1D,MAAM,cAAc,UAAU,UAAU,IAAI,UAA6B,CAAC,GAAG;GAC3E,MAAM,UAAU,MAAM,OAAO;GAC7B,MAAM,UAAU,MAAM,QAAQ,OAAO,aAAa,OAAO,cAAc,QAAQ,GAAG,OAAO,GAAG;IAC1F,SAAS,QAAQ;IACjB,UAAU,QAAQ,YAAY;IAC9B,OAAO,cAAc,SAAS,SAAS,OAAO;GAChD,CAAC;GACD,MAAM,SAAS,gBAAgB,QAAQ;GACvC,KAAK,MAAM,CAAC,SAAS,SAAS,aAAa,QAAQ,OAAO,GAAG;IAE3D,QAAQ,gBAAgB,eAAe;KAAE,GAAG,QAAQ;KAAS,GAAG,KAAK;IAAM,CAAC;IAC5E,IAAI,QAAQ,QAAQ,QAAQ,SAAS,SAAS,IAAI;GACpD;GACA,OAAO;EACT;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/load.ts","../../src/runtime.ts"],"sourcesContent":["import { DEADLINE_MS } from '@open-pencil/std/timing'\n\nimport { HTMLEngine } from './engine'\n\n/**\n * Where the engine's module (`html-engine.wasm`) loads from. By default it is read beside this\n * package, as Node and Bun resolve it; a host that serves it elsewhere, such as a bundled app,\n * points here instead.\n */\nexport type HTMLEngineLocator = () => string\n\nlet locator: HTMLEngineLocator = () =>\n import.meta.resolve('@open-pencil/html-engine/wasm/html-engine.wasm')\n\nlet loading: Promise<HTMLEngine> | null = null\n\n/**\n * How long a remote module may take to arrive, so a request that never settles cannot hold every\n * later load waiting on it; a failed load is retried by the next caller.\n */\nconst MODULE_LOAD_TIMEOUT_MS = DEADLINE_MS.transfer\n\n/** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */\nexport function setHTMLEngineLocator(locate: HTMLEngineLocator): void {\n locator = locate\n loading = null\n}\n\nasync function readModule(url: string): Promise<ArrayBuffer> {\n if (!url.startsWith('file:')) {\n const response = await fetch(url, { signal: AbortSignal.timeout(MODULE_LOAD_TIMEOUT_MS) })\n if (!response.ok)\n throw new Error(`html-engine.wasm failed to load from ${url}: ${response.status}`)\n return response.arrayBuffer()\n }\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n const file = await readFile(new URL(url)).catch((error: unknown) => {\n throw new Error(\n `html-engine.wasm is missing at ${url}; build it with bun run build in packages/html-engine`,\n { cause: error }\n )\n })\n return file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength)\n}\n\n/** The engine, loaded once; a failed load is retried by the next caller. */\nexport function loadHTMLEngine(): Promise<HTMLEngine> {\n if (loading) return loading\n const load = readModule(locator()).then((bytes) => HTMLEngine.instantiate(bytes))\n loading = load\n load.catch(() => {\n if (loading === load) loading = null\n })\n return load\n}\n","import {\n parseFontFaceRules,\n parseHTMLDocument,\n parseStylesheetImports,\n type CSSFontFaceRule,\n type CSSComputeOptions,\n type CSSRuntime,\n type DesignDocument,\n type DesignElement,\n type DesignLayout,\n type DesignResource,\n type DesignResourceFetch,\n type DesignStyleDeclaration,\n type DesignViewport\n} from '@open-pencil/dom-css'\nimport { serializeHTML } from '@open-pencil/dom-css/export'\nimport { parseCSSColor } from '@open-pencil/scene-graph/css'\nimport { computeBounds } from '@open-pencil/scene-graph/geometry'\nimport type { Rect } from '@open-pencil/scene-graph/primitives'\nimport { insertAll, maxOf, minOf } from '@open-pencil/std/arrays'\n\nimport type { HTMLEngine } from './engine'\nimport { loadHTMLEngine } from './load'\nimport type { HTMLEngineCapture, HTMLEngineLine, HTMLEngineNode } from './schema'\n\n/** The viewport a document is laid out in when the caller names none, as HTML import uses. */\nconst DEFAULT_VIEWPORT: DesignViewport = { width: 1440, height: 900 }\n\n/** A font a page's `@font-face` rule loads: the face the rule declares, and the file as TrueType or OpenType. */\nexport interface HTMLEngineFontFace {\n family: string\n weight: number\n italic: boolean\n url: string\n bytes: Uint8Array\n}\n\nexport interface HTMLEngineRuntimeOptions {\n /** The engine to lay documents out with, with the fonts they may use registered. */\n engine?: () => Promise<HTMLEngine>\n /** The document's URL, which its relative URLs resolve against. */\n baseURL?: string\n /**\n * Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for\n * its `@font-face` rules when it comes with a CSS content type.\n */\n fetch?: DesignResourceFetch\n /**\n * Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so\n * a host can draw that text in the same font. The layout waits for it.\n */\n onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>\n}\n\nfunction isStylesheet(resource: DesignResource): boolean {\n return resource.contentType?.split(';')[0]?.trim().toLowerCase() === 'text/css'\n}\n\n/**\n * A fetch that also reads the page's `@font-face` rules, from its own CSS and every stylesheet it\n * fetches, and passes each font they load to `onFontFace` as the engine receives it.\n */\nfunction fontFaceFetch(\n engine: HTMLEngine,\n cssText: string,\n options: HTMLEngineRuntimeOptions\n): DesignResourceFetch | undefined {\n const { fetch, onFontFace } = options\n if (!fetch || !onFontFace) return fetch\n const rules = new Map<string, CSSFontFaceRule[]>()\n // What CSS imports is a stylesheet whatever its name or the type it is served as.\n const stylesheets = new Set<string>()\n // The engine fetches a file once per rule that names it; each face is passed on once.\n const delivered = new Set<string>()\n const learn = (css: string, base: string | undefined) => {\n for (const rule of parseFontFaceRules(css, base)) {\n for (const source of rule.sources) rules.set(source, [...(rules.get(source) ?? []), rule])\n }\n for (const url of parseStylesheetImports(css, base)) stylesheets.add(url)\n }\n learn(cssText, options.baseURL)\n return async (url, signal) => {\n const resource = await fetch(url, signal)\n if (!resource) return null\n if (isStylesheet(resource) || stylesheets.has(url) || stylesheets.has(resource.url)) {\n learn(new TextDecoder().decode(resource.bytes), resource.url)\n }\n // One file can serve several rules, such as a family and an alias of it.\n const served = rules.get(url) ?? rules.get(resource.url) ?? []\n const bytes = served.length > 0 ? engine.decodeFont(resource.bytes) : null\n for (const rule of served) {\n const face = `${url}|${rule.family}|${rule.weight}|${rule.italic}`\n if (!bytes || delivered.has(face)) continue\n delivered.add(face)\n await onFontFace({\n family: rule.family,\n weight: rule.weight,\n italic: rule.italic,\n url,\n bytes\n })\n }\n return resource\n }\n}\n\ntype Box = HTMLEngineCapture['nodes'][number]['box']\n\nfunction rect(box: NonNullable<Box>): Rect {\n const [x, y, width, height] = box\n return { x, y, width, height }\n}\n\nfunction hasArea(box: NonNullable<Box>): boolean {\n return box[2] > 0 && box[3] > 0\n}\n\n/** Children of each captured node that are elements, by the node's index; generated content left out. */\nfunction elementChildren(capture: HTMLEngineCapture): Map<number, number[]> {\n const children = new Map<number, number[]>()\n for (const [index, node] of capture.nodes.entries()) {\n if (node.parent === undefined || node.tag === undefined || node.tag.startsWith('::')) continue\n const siblings = children.get(node.parent) ?? []\n siblings.push(index)\n children.set(node.parent, siblings)\n }\n return children\n}\n\n/**\n * Elements the HTML parser inserts around others where the markup leaves them out, such as the\n * `tbody` around a table's rows; a serialized document need not hold them.\n */\nconst IMPLIED_WRAPPERS = new Set(['tbody'])\n\n/**\n * Each element of the document with the captured element it was laid out as: matched in order\n * and by tag, looking through wrappers the parser inserted. A mismatch ends the matching among\n * those siblings, so it never pairs an element with another's box.\n */\nfunction pairElements(\n document: DesignDocument,\n capture: HTMLEngineCapture\n): [DesignElement, HTMLEngineNode][] {\n const children = elementChildren(capture)\n const body = capture.nodes.findIndex((node) => node.tag === 'body')\n const pairs: [DesignElement, HTMLEngineNode][] = []\n const pair = (elements: readonly DesignElement[], parent: number, shaderFrame = false) => {\n const queue = [...(children.get(parent) ?? [])]\n // The serializer writes a shader's still frame as an image ahead of its layer's children.\n const first = queue.at(0)\n if (shaderFrame && first !== undefined && capture.nodes[first].tag === 'img') queue.shift()\n for (const element of elements) {\n let node = queue.shift()\n // The HTML parser keeps SVG's mixed-case names, such as `linearGradient`; the document may not.\n while (node !== undefined && !sameTag(capture.nodes[node].tag, element.tagName)) {\n const tag = capture.nodes[node].tag\n if (tag === undefined || !IMPLIED_WRAPPERS.has(tag)) return\n insertAll(queue, 0, children.get(node) ?? [])\n node = queue.shift()\n }\n if (node === undefined) return\n pairs.push([element, capture.nodes[node]])\n pair(designElements(element.children), node, element.shader?.frame !== undefined)\n }\n }\n if (body !== -1) pair(designElements(document.children), body)\n return pairs\n}\n\nfunction sameTag(captured: string | undefined, tagName: string): boolean {\n return captured?.toLowerCase() === tagName.toLowerCase()\n}\n\nfunction designElements(nodes: DesignDocument['children']): DesignElement[] {\n return nodes.filter((node): node is DesignElement => node.type === 'element')\n}\n\n/** Shorthands a browser runtime reports, `overflow` and `gap`, built from their captured longhands. */\nfunction withShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {\n // Captures leave initial values out.\n const value = (property: string, initial: string) =>\n Object.hasOwn(style, property) ? style[property] : initial\n const pair = (first: string, second: string) => (first === second ? first : `${first} ${second}`)\n const shorthands: DesignStyleDeclaration = {}\n if (Object.hasOwn(style, 'overflow-x') || Object.hasOwn(style, 'overflow-y')) {\n shorthands.overflow = pair(value('overflow-x', 'visible'), value('overflow-y', 'visible'))\n }\n if (Object.hasOwn(style, 'row-gap') || Object.hasOwn(style, 'column-gap')) {\n shorthands.gap = pair(value('row-gap', 'normal'), value('column-gap', 'normal'))\n }\n return { ...style, ...shorthands }\n}\n\n/** White space values that keep spaces, so a line of them takes room as a line of words does. */\nconst PRESERVED_WHITE_SPACE = new Set(['pre', 'pre-wrap', 'break-spaces'])\n\n/**\n * A line as a browser's text rects make it: across its words, leaving out inline boxes, and\n * nothing for a line without text. Where white space is kept, a line of spaces counts too.\n */\nfunction textLine(line: HTMLEngineLine, keepsSpaces: boolean): Rect | null {\n const texts = line.runs.filter((run) => 'text' in run && run.text.length > 0)\n const words = keepsSpaces ? texts : texts.filter((run) => 'text' in run && run.text.trim() !== '')\n if (words.length === 0) return null\n const left = minOf(words.map((run) => run.x))\n const right = maxOf(words.map((run) => run.x + run.width))\n return { x: left, y: line.y, width: right - left, height: line.height }\n}\n\nfunction layoutOf(node: HTMLEngineNode): DesignLayout | undefined {\n if (!node.box) return undefined\n const layout: DesignLayout = { box: rect(node.box) }\n const fragments = node.fragments?.filter(hasArea)\n if (fragments && fragments.length > 0) {\n layout.fragments = fragments.map(rect)\n // An inline element's box is the one around its fragments, as getBoundingClientRect gives.\n layout.box = computeBounds(layout.fragments)\n return layout\n }\n const whiteSpace = node.style?.['white-space']\n const keepsSpaces = whiteSpace !== undefined && PRESERVED_WHITE_SPACE.has(whiteSpace)\n const lines = (node.lines ?? [])\n .map((line) => textLine(line, keepsSpaces))\n .filter((line) => line !== null)\n if (lines.length > 0) layout.lines = lines\n return layout\n}\n\nfunction documentHTML(body: string, cssText: string): string {\n // `</style` would end the stylesheet early.\n const css = cssText.replaceAll(/<\\/style/gi, '<\\\\/style')\n return `<!doctype html><html><head><style>${css}</style></head><body>${body}</body></html>`\n}\n\n/**\n * A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,\n * without one: computed styles and, when asked, the boxes, inline fragments, and text lines a\n * browser runtime records, before transforms. Documents are parsed and serialized by dom-css.\n */\n/** The `::before` and `::after` nodes of each captured element, by the element's index. */\nfunction generatedChildren(capture: HTMLEngineCapture): Map<number, number[]> {\n const generated = new Map<number, number[]>()\n for (const [index, node] of capture.nodes.entries()) {\n if (node.parent === undefined || !node.tag?.startsWith('::')) continue\n generated.set(node.parent, [...(generated.get(node.parent) ?? []), index])\n }\n return generated\n}\n\n/** The text a captured node holds directly, as a pseudo-element's generated content. */\n/** Each captured node's own text, its text children's joined in order, by the node's index. */\nfunction ownTexts(capture: HTMLEngineCapture): Map<number, string> {\n const texts = new Map<number, string>()\n for (const node of capture.nodes) {\n if (node.text === undefined || node.parent === undefined) continue\n texts.set(node.parent, (texts.get(node.parent) ?? '') + node.text)\n }\n return texts\n}\n\n/**\n * Shows each element's `::before` and `::after` as elements of their own, first and last among its\n * children, with the style, box, and text the engine generated for them, so they are imported as\n * any element is.\n */\nfunction showGeneratedContent(\n capture: HTMLEngineCapture,\n pairs: readonly [DesignElement, HTMLEngineNode][],\n layout: boolean\n): void {\n const indexes = new Map(capture.nodes.map((node, index) => [node, index]))\n const generated = generatedChildren(capture)\n const texts = ownTexts(capture)\n for (const [element, node] of pairs) {\n const index = indexes.get(node)\n for (const pseudo of (index === undefined ? undefined : generated.get(index)) ?? []) {\n const captured = capture.nodes[pseudo]\n const text = texts.get(pseudo) ?? ''\n const child: DesignElement = {\n type: 'element',\n tagName: captured.tag ?? '::before',\n attrs: {},\n children: text ? [{ type: 'text', text }] : [],\n computedStyle: withShorthands({\n ...capture.initial,\n ...captured.style,\n ...captured.computed\n })\n }\n if (layout) child.layout = layoutOf(captured)\n if (captured.tag === '::after') element.children.push(child)\n else element.children.unshift(child)\n }\n }\n}\n\n/**\n * The color the page's canvas is painted, as CSS takes it: the root element's background, or the\n * body's when the root has none.\n */\nfunction canvasBackground(capture: HTMLEngineCapture): string | undefined {\n const background = (tag: string) => {\n const node = capture.nodes.find((candidate) => candidate.tag === tag)\n const color = node?.style?.['background-color']\n return color && parseCSSColor(color) ? color : undefined\n }\n return background('html') ?? background('body')\n}\n\n/** A fetch that also keeps what it answered, by the URL asked for and the one it came from. */\nfunction keepingFetch(\n fetch: DesignResourceFetch | undefined,\n answered: Map<string, DesignResource>\n): DesignResourceFetch | undefined {\n if (!fetch) return undefined\n return async (url, signal) => {\n const resource = await fetch(url, signal)\n if (resource) answered.set(url, resource).set(resource.url, resource)\n return resource\n }\n}\n\n/** What an `<img>` loaded, by its `src` resolved against the page's address. */\nfunction imageOf(\n element: DesignElement,\n answered: ReadonlyMap<string, DesignResource>,\n baseURL: string | undefined\n): DesignResource | undefined {\n const { src } = element.attrs\n if (element.tagName.toLowerCase() !== 'img' || !src || !URL.canParse(src, baseURL)) {\n return undefined\n }\n return answered.get(new URL(src, baseURL).href)\n}\n\nexport function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}): CSSRuntime {\n const engine = options.engine ?? loadHTMLEngine\n return {\n kind: 'headless',\n parseHTML: parseHTMLDocument,\n serializeHTML,\n async computeStyles(document, cssText = '', compute: CSSComputeOptions = {}) {\n const laidOut = await engine()\n // The pictures the engine loads to lay images out go with their elements, so the layers\n // they become show them without fetching them again.\n const answered = new Map<string, DesignResource>()\n const fetch = keepingFetch(options.fetch, answered)\n const capture = await laidOut.layout(documentHTML(serializeHTML(document), cssText), {\n baseURL: options.baseURL,\n viewport: compute.viewport ?? DEFAULT_VIEWPORT,\n fetch: fontFaceFetch(laidOut, cssText, { ...options, fetch })\n })\n const styled = structuredClone(document)\n const pairs = pairElements(styled, capture)\n for (const [element, node] of pairs) {\n // Every captured property's computed value, so none falls back to a stale inline one, with\n // sizes and line heights as the page set them rather than as layout resolved them, so the\n // importer tells a size the page fixed from one that fills or hugs and keeps a line height\n // that scales with the font; the boxes layout gave stay in `layout`.\n element.computedStyle = withShorthands({\n ...capture.initial,\n ...node.style,\n ...node.computed\n })\n if (compute.layout) element.layout = layoutOf(node)\n const image = imageOf(element, answered, options.baseURL)\n if (image) element.image = image\n }\n showGeneratedContent(capture, pairs, compute.layout === true)\n styled.background = canvasBackground(capture)\n return styled\n }\n }\n}\n"],"mappings":";;;;;;;;AAWA,IAAI,gBACF,YAAY,QAAQ,gDAAgD;AAEtE,IAAI,UAAsC;;;;;AAM1C,MAAM,yBAAyB,YAAY;;AAG3C,SAAgB,qBAAqB,QAAiC;CACpE,U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GAC7B;GACA,qBAAqB,SAAS,OAAO,QAAQ,WAAW,IAAI;GAC5D,OAAO,aAAa,iBAAiB,OAAO;GAC5C,OAAO;EACT;CACF;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
|
-
import { CSSRuntime } from "@open-pencil/dom-css";
|
|
2
|
+
import { CSSRuntime, DesignResourceFetch } from "@open-pencil/dom-css";
|
|
3
3
|
//#region src/schema.d.ts
|
|
4
4
|
declare const lineSchema: v.ObjectSchema<{
|
|
5
5
|
readonly x: v.NumberSchema<undefined>;
|
|
@@ -41,6 +41,12 @@ declare const capturedNodeSchema: v.ObjectSchema<{
|
|
|
41
41
|
* `color`, sizes, and font properties.
|
|
42
42
|
*/
|
|
43
43
|
readonly style: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
44
|
+
/**
|
|
45
|
+
* Computed values where `style`'s used ones lose what the page set: the sizes (`width`,
|
|
46
|
+
* `height`, their minimums and maximums, and `flex-basis`) before layout resolves `auto` and
|
|
47
|
+
* percentages to pixels, such as `auto`, `50%`, or `390px`, and `line-height`, such as `1.5`.
|
|
48
|
+
*/
|
|
49
|
+
readonly computed: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
44
50
|
/** An inline element's box on each line it spans, in page pixels. */
|
|
45
51
|
readonly fragments: v.OptionalSchema<v.ArraySchema<v.TupleSchema<[v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>], undefined>, undefined>, undefined>;
|
|
46
52
|
/** The lines of the inline formatting context the element holds, in page pixels. */
|
|
@@ -91,6 +97,12 @@ declare const captureSchema: v.ObjectSchema<{
|
|
|
91
97
|
* `color`, sizes, and font properties.
|
|
92
98
|
*/
|
|
93
99
|
readonly style: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
100
|
+
/**
|
|
101
|
+
* Computed values where `style`'s used ones lose what the page set: the sizes (`width`,
|
|
102
|
+
* `height`, their minimums and maximums, and `flex-basis`) before layout resolves `auto` and
|
|
103
|
+
* percentages to pixels, such as `auto`, `50%`, or `390px`, and `line-height`, such as `1.5`.
|
|
104
|
+
*/
|
|
105
|
+
readonly computed: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
94
106
|
/** An inline element's box on each line it spans, in page pixels. */
|
|
95
107
|
readonly fragments: v.OptionalSchema<v.ArraySchema<v.TupleSchema<[v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>], undefined>, undefined>, undefined>;
|
|
96
108
|
/** The lines of the inline formatting context the element holds, in page pixels. */
|
|
@@ -121,17 +133,6 @@ type HTMLEngineLine = v.InferOutput<typeof lineSchema>;
|
|
|
121
133
|
//#endregion
|
|
122
134
|
//#region src/engine.d.ts
|
|
123
135
|
/** A resource the document asked for, as the host fetched it: its final URL and its bytes. */
|
|
124
|
-
interface HTMLEngineResource {
|
|
125
|
-
url: string;
|
|
126
|
-
bytes: Uint8Array;
|
|
127
|
-
/** The resource's media type, such as `text/css`, when the host knows it. */
|
|
128
|
-
contentType?: string;
|
|
129
|
-
}
|
|
130
|
-
/**
|
|
131
|
-
* Fetches a stylesheet, font, or image the document refers to; null when it cannot. `signal`
|
|
132
|
-
* aborts when the request runs out of time, and the layout goes on without it.
|
|
133
|
-
*/
|
|
134
|
-
type HTMLEngineFetch = (url: string, signal: AbortSignal) => Promise<HTMLEngineResource | null>;
|
|
135
136
|
interface HTMLEngineLayoutOptions {
|
|
136
137
|
/** The document's URL, which relative URLs in it resolve against. */
|
|
137
138
|
baseURL?: string;
|
|
@@ -141,7 +142,7 @@ interface HTMLEngineLayoutOptions {
|
|
|
141
142
|
height: number;
|
|
142
143
|
};
|
|
143
144
|
/** Answers the document's requests; without one, every request fails. */
|
|
144
|
-
fetch?:
|
|
145
|
+
fetch?: DesignResourceFetch;
|
|
145
146
|
/** How long one request may take before the layout goes on without it. */
|
|
146
147
|
requestTimeoutMs?: number;
|
|
147
148
|
}
|
|
@@ -214,20 +215,14 @@ interface HTMLEngineRuntimeOptions {
|
|
|
214
215
|
* Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for
|
|
215
216
|
* its `@font-face` rules when it comes with a CSS content type.
|
|
216
217
|
*/
|
|
217
|
-
fetch?:
|
|
218
|
+
fetch?: DesignResourceFetch;
|
|
218
219
|
/**
|
|
219
220
|
* Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so
|
|
220
221
|
* a host can draw that text in the same font. The layout waits for it.
|
|
221
222
|
*/
|
|
222
223
|
onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>;
|
|
223
224
|
}
|
|
224
|
-
/**
|
|
225
|
-
* A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,
|
|
226
|
-
* without one: computed styles and, when asked, the boxes, inline fragments, and text lines a
|
|
227
|
-
* browser runtime records, before transforms. Documents are parsed and serialized as the headless
|
|
228
|
-
* runtime does.
|
|
229
|
-
*/
|
|
230
225
|
declare function createHTMLEngineRuntime(options?: HTMLEngineRuntimeOptions): CSSRuntime;
|
|
231
226
|
//#endregion
|
|
232
|
-
export { HTMLEngine, type HTMLEngineCapture, type
|
|
227
|
+
export { HTMLEngine, type HTMLEngineCapture, type HTMLEngineFontFace, type HTMLEngineLayoutOptions, type HTMLEngineLine, type HTMLEngineLocator, type HTMLEngineNode, type HTMLEngineRuntimeOptions, createHTMLEngineRuntime, loadHTMLEngine, rasterImageSize, setHTMLEngineLocator };
|
|
233
228
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/schema.ts","../src/engine.ts","../src/images.ts","../src/load.ts","../src/runtime.ts"],"mappings":";;;cAmBM,YAAU,EAAA;;;;;;;;;;;;;;;;;;;cASV,oBAAkB,EAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/schema.ts","../src/engine.ts","../src/images.ts","../src/load.ts","../src/runtime.ts"],"mappings":";;;cAmBM,YAAU,EAAA;;;;;;;;;;;;;;;;;;;cASV,oBAAkB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkCX,eAAa,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAWd,oBAAoB,EAAE,mBAAmB;KACzC,iBAAiB,EAAE,mBAAmB;KACtC,iBAAiB,EAAE,mBAAmB;;;;UC1CjC;;EAEf;;EAEA;IAAY;IAAe;;;EAE3B,QAAQ;;EAER;;;;;;;cAoFW;;UAMJ;;SAKM,YAAY,QAAQ,eAAe,YAAY,SAAS,QAAQ;;;;;;EA8B7E,QAAQ,OAAO,YAAY;;;;;EAY3B,iBAAiB,iBAAiB;;EASlC,WAAW,OAAO,aAAa;;EAQ/B;;EAkEA,OAAO,cAAc,SAAS,0BAA0B,QAAQ;;;;;;;;;KC/P7D,QAAQ,eAAe;;iBAoGZ,gBAAgB,OAAO,aAAa;;;;;;;;KCjGxC;;iBAcI,qBAAqB,QAAQ;;iBAuB7B,kBAAkB,QAAQ;;;;UCjBzB;EACf;EACA;EACA;EACA;EACA,OAAO;;UAGQ;;EAEf,eAAe,QAAQ;;EAEvB;;;;;EAKA,QAAQ;;;;;EAKR,cAAc,MAAM,8BAA8B;;iBA6RpC,wBAAwB,UAAS,2BAAgC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-pencil/html-engine",
|
|
3
|
-
"version": "0.17.0-beta.
|
|
3
|
+
"version": "0.17.0-beta.6",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -11,11 +11,12 @@
|
|
|
11
11
|
"main": "./dist/index.js",
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
13
|
"dependencies": {
|
|
14
|
-
"@open-pencil/dom-css": "^0.17.0-beta.
|
|
14
|
+
"@open-pencil/dom-css": "^0.17.0-beta.6",
|
|
15
|
+
"@open-pencil/std": "^0.17.0-beta.6",
|
|
15
16
|
"valibot": "^1.5.0"
|
|
16
17
|
},
|
|
17
18
|
"peerDependencies": {
|
|
18
|
-
"@open-pencil/scene-graph": "^0.17.0-beta.
|
|
19
|
+
"@open-pencil/scene-graph": "^0.17.0-beta.6"
|
|
19
20
|
},
|
|
20
21
|
"exports": {
|
|
21
22
|
".": {
|
package/src/engine.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import * as v from 'valibot'
|
|
2
2
|
|
|
3
|
+
import type { DesignResourceFetch } from '@open-pencil/dom-css'
|
|
4
|
+
import { createMutex } from '@open-pencil/std/async'
|
|
5
|
+
import { DEADLINE_MS, untilAborted } from '@open-pencil/std/timing'
|
|
6
|
+
|
|
3
7
|
import { imageStandIn, rasterImageSize } from './images'
|
|
4
8
|
import { captureSchema, requestsSchema, type HTMLEngineCapture } from './schema'
|
|
5
9
|
|
|
@@ -27,29 +31,13 @@ type EngineExports = Record<(typeof EXPORTS)[number], (...args: number[]) => num
|
|
|
27
31
|
}
|
|
28
32
|
|
|
29
33
|
/** A resource the document asked for, as the host fetched it: its final URL and its bytes. */
|
|
30
|
-
export interface HTMLEngineResource {
|
|
31
|
-
url: string
|
|
32
|
-
bytes: Uint8Array
|
|
33
|
-
/** The resource's media type, such as `text/css`, when the host knows it. */
|
|
34
|
-
contentType?: string
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Fetches a stylesheet, font, or image the document refers to; null when it cannot. `signal`
|
|
39
|
-
* aborts when the request runs out of time, and the layout goes on without it.
|
|
40
|
-
*/
|
|
41
|
-
export type HTMLEngineFetch = (
|
|
42
|
-
url: string,
|
|
43
|
-
signal: AbortSignal
|
|
44
|
-
) => Promise<HTMLEngineResource | null>
|
|
45
|
-
|
|
46
34
|
export interface HTMLEngineLayoutOptions {
|
|
47
35
|
/** The document's URL, which relative URLs in it resolve against. */
|
|
48
36
|
baseURL?: string
|
|
49
37
|
/** In whole CSS pixels. */
|
|
50
38
|
viewport: { width: number; height: number }
|
|
51
39
|
/** Answers the document's requests; without one, every request fails. */
|
|
52
|
-
fetch?:
|
|
40
|
+
fetch?: DesignResourceFetch
|
|
53
41
|
/** How long one request may take before the layout goes on without it. */
|
|
54
42
|
requestTimeoutMs?: number
|
|
55
43
|
}
|
|
@@ -58,7 +46,7 @@ export interface HTMLEngineLayoutOptions {
|
|
|
58
46
|
* How long a request may take by default: as long as the browser runtime waits for an image, so
|
|
59
47
|
* one request that never ends cannot hold this layout, or the ones queued behind it, forever.
|
|
60
48
|
*/
|
|
61
|
-
const REQUEST_TIMEOUT_MS =
|
|
49
|
+
const REQUEST_TIMEOUT_MS = DEADLINE_MS.request
|
|
62
50
|
|
|
63
51
|
/** The largest viewport side the module takes, as a signed 32-bit length. */
|
|
64
52
|
const MAX_VIEWPORT = 0x7fffffff
|
|
@@ -71,12 +59,9 @@ function checkViewport({ width, height }: HTMLEngineLayoutOptions['viewport']):
|
|
|
71
59
|
}
|
|
72
60
|
}
|
|
73
61
|
|
|
74
|
-
/** A fetch that gives up, answering null, once `signal` aborts. */
|
|
62
|
+
/** A fetch that gives up, answering null, once it fails or `signal` aborts. */
|
|
75
63
|
function withDeadline<T>(request: Promise<T>, signal: AbortSignal): Promise<T | null> {
|
|
76
|
-
|
|
77
|
-
signal.addEventListener('abort', () => resolve(null), { once: true })
|
|
78
|
-
})
|
|
79
|
-
return Promise.race([request.catch(() => null), expired])
|
|
64
|
+
return untilAborted(request, signal).catch(() => null)
|
|
80
65
|
}
|
|
81
66
|
|
|
82
67
|
/** Blitz's wasm-bindgen imports, which no capture calls: they trap with their name instead. */
|
|
@@ -142,7 +127,7 @@ export class HTMLEngine {
|
|
|
142
127
|
readonly #exports: EngineExports
|
|
143
128
|
readonly #encoder = new TextEncoder()
|
|
144
129
|
readonly #decoder = new TextDecoder()
|
|
145
|
-
#
|
|
130
|
+
#layouts = createMutex()
|
|
146
131
|
|
|
147
132
|
private constructor(exports: EngineExports) {
|
|
148
133
|
this.#exports = exports
|
|
@@ -275,8 +260,6 @@ export class HTMLEngine {
|
|
|
275
260
|
|
|
276
261
|
/** Lays the document out once every resource it asks for is answered, and captures it. */
|
|
277
262
|
layout(html: string, options: HTMLEngineLayoutOptions): Promise<HTMLEngineCapture> {
|
|
278
|
-
|
|
279
|
-
this.#queue = run.catch(() => undefined)
|
|
280
|
-
return run
|
|
263
|
+
return this.#layouts.run(() => this.#layout(html, options))
|
|
281
264
|
}
|
|
282
265
|
}
|
package/src/images.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
type Size = [width: number, height: number]
|
|
8
8
|
|
|
9
9
|
function ascii(bytes: Uint8Array, at: number, length: number): string {
|
|
10
|
-
return
|
|
10
|
+
return Array.from(bytes.subarray(at, at + length), (code) => String.fromCharCode(code)).join('')
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
function webpSize(bytes: Uint8Array, view: DataView): Size | null {
|
package/src/index.ts
CHANGED
|
@@ -1,9 +1,4 @@
|
|
|
1
|
-
export {
|
|
2
|
-
HTMLEngine,
|
|
3
|
-
type HTMLEngineFetch,
|
|
4
|
-
type HTMLEngineLayoutOptions,
|
|
5
|
-
type HTMLEngineResource
|
|
6
|
-
} from './engine'
|
|
1
|
+
export { HTMLEngine, type HTMLEngineLayoutOptions } from './engine'
|
|
7
2
|
export { rasterImageSize } from './images'
|
|
8
3
|
export { loadHTMLEngine, setHTMLEngineLocator, type HTMLEngineLocator } from './load'
|
|
9
4
|
export {
|
package/src/load.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { DEADLINE_MS } from '@open-pencil/std/timing'
|
|
2
|
+
|
|
1
3
|
import { HTMLEngine } from './engine'
|
|
2
4
|
|
|
3
5
|
/**
|
|
@@ -16,7 +18,7 @@ let loading: Promise<HTMLEngine> | null = null
|
|
|
16
18
|
* How long a remote module may take to arrive, so a request that never settles cannot hold every
|
|
17
19
|
* later load waiting on it; a failed load is retried by the next caller.
|
|
18
20
|
*/
|
|
19
|
-
const MODULE_LOAD_TIMEOUT_MS =
|
|
21
|
+
const MODULE_LOAD_TIMEOUT_MS = DEADLINE_MS.transfer
|
|
20
22
|
|
|
21
23
|
/** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */
|
|
22
24
|
export function setHTMLEngineLocator(locate: HTMLEngineLocator): void {
|
package/src/runtime.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
|
-
createHeadlessCSSRuntime,
|
|
3
2
|
parseFontFaceRules,
|
|
3
|
+
parseHTMLDocument,
|
|
4
4
|
parseStylesheetImports,
|
|
5
5
|
type CSSFontFaceRule,
|
|
6
6
|
type CSSComputeOptions,
|
|
@@ -8,12 +8,18 @@ import {
|
|
|
8
8
|
type DesignDocument,
|
|
9
9
|
type DesignElement,
|
|
10
10
|
type DesignLayout,
|
|
11
|
+
type DesignResource,
|
|
12
|
+
type DesignResourceFetch,
|
|
11
13
|
type DesignStyleDeclaration,
|
|
12
14
|
type DesignViewport
|
|
13
15
|
} from '@open-pencil/dom-css'
|
|
16
|
+
import { serializeHTML } from '@open-pencil/dom-css/export'
|
|
17
|
+
import { parseCSSColor } from '@open-pencil/scene-graph/css'
|
|
18
|
+
import { computeBounds } from '@open-pencil/scene-graph/geometry'
|
|
14
19
|
import type { Rect } from '@open-pencil/scene-graph/primitives'
|
|
20
|
+
import { insertAll, maxOf, minOf } from '@open-pencil/std/arrays'
|
|
15
21
|
|
|
16
|
-
import type { HTMLEngine
|
|
22
|
+
import type { HTMLEngine } from './engine'
|
|
17
23
|
import { loadHTMLEngine } from './load'
|
|
18
24
|
import type { HTMLEngineCapture, HTMLEngineLine, HTMLEngineNode } from './schema'
|
|
19
25
|
|
|
@@ -38,7 +44,7 @@ export interface HTMLEngineRuntimeOptions {
|
|
|
38
44
|
* Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for
|
|
39
45
|
* its `@font-face` rules when it comes with a CSS content type.
|
|
40
46
|
*/
|
|
41
|
-
fetch?:
|
|
47
|
+
fetch?: DesignResourceFetch
|
|
42
48
|
/**
|
|
43
49
|
* Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so
|
|
44
50
|
* a host can draw that text in the same font. The layout waits for it.
|
|
@@ -46,7 +52,7 @@ export interface HTMLEngineRuntimeOptions {
|
|
|
46
52
|
onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>
|
|
47
53
|
}
|
|
48
54
|
|
|
49
|
-
function isStylesheet(resource:
|
|
55
|
+
function isStylesheet(resource: DesignResource): boolean {
|
|
50
56
|
return resource.contentType?.split(';')[0]?.trim().toLowerCase() === 'text/css'
|
|
51
57
|
}
|
|
52
58
|
|
|
@@ -58,7 +64,7 @@ function fontFaceFetch(
|
|
|
58
64
|
engine: HTMLEngine,
|
|
59
65
|
cssText: string,
|
|
60
66
|
options: HTMLEngineRuntimeOptions
|
|
61
|
-
):
|
|
67
|
+
): DesignResourceFetch | undefined {
|
|
62
68
|
const { fetch, onFontFace } = options
|
|
63
69
|
if (!fetch || !onFontFace) return fetch
|
|
64
70
|
const rules = new Map<string, CSSFontFaceRule[]>()
|
|
@@ -150,7 +156,7 @@ function pairElements(
|
|
|
150
156
|
while (node !== undefined && !sameTag(capture.nodes[node].tag, element.tagName)) {
|
|
151
157
|
const tag = capture.nodes[node].tag
|
|
152
158
|
if (tag === undefined || !IMPLIED_WRAPPERS.has(tag)) return
|
|
153
|
-
queue
|
|
159
|
+
insertAll(queue, 0, children.get(node) ?? [])
|
|
154
160
|
node = queue.shift()
|
|
155
161
|
}
|
|
156
162
|
if (node === undefined) return
|
|
@@ -197,8 +203,8 @@ function textLine(line: HTMLEngineLine, keepsSpaces: boolean): Rect | null {
|
|
|
197
203
|
const texts = line.runs.filter((run) => 'text' in run && run.text.length > 0)
|
|
198
204
|
const words = keepsSpaces ? texts : texts.filter((run) => 'text' in run && run.text.trim() !== '')
|
|
199
205
|
if (words.length === 0) return null
|
|
200
|
-
const left =
|
|
201
|
-
const right =
|
|
206
|
+
const left = minOf(words.map((run) => run.x))
|
|
207
|
+
const right = maxOf(words.map((run) => run.x + run.width))
|
|
202
208
|
return { x: left, y: line.y, width: right - left, height: line.height }
|
|
203
209
|
}
|
|
204
210
|
|
|
@@ -208,6 +214,8 @@ function layoutOf(node: HTMLEngineNode): DesignLayout | undefined {
|
|
|
208
214
|
const fragments = node.fragments?.filter(hasArea)
|
|
209
215
|
if (fragments && fragments.length > 0) {
|
|
210
216
|
layout.fragments = fragments.map(rect)
|
|
217
|
+
// An inline element's box is the one around its fragments, as getBoundingClientRect gives.
|
|
218
|
+
layout.box = computeBounds(layout.fragments)
|
|
211
219
|
return layout
|
|
212
220
|
}
|
|
213
221
|
const whiteSpace = node.style?.['white-space']
|
|
@@ -228,29 +236,139 @@ function documentHTML(body: string, cssText: string): string {
|
|
|
228
236
|
/**
|
|
229
237
|
* A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,
|
|
230
238
|
* 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
|
|
232
|
-
* runtime does.
|
|
239
|
+
* browser runtime records, before transforms. Documents are parsed and serialized by dom-css.
|
|
233
240
|
*/
|
|
241
|
+
/** The `::before` and `::after` nodes of each captured element, by the element's index. */
|
|
242
|
+
function generatedChildren(capture: HTMLEngineCapture): Map<number, number[]> {
|
|
243
|
+
const generated = new Map<number, number[]>()
|
|
244
|
+
for (const [index, node] of capture.nodes.entries()) {
|
|
245
|
+
if (node.parent === undefined || !node.tag?.startsWith('::')) continue
|
|
246
|
+
generated.set(node.parent, [...(generated.get(node.parent) ?? []), index])
|
|
247
|
+
}
|
|
248
|
+
return generated
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** The text a captured node holds directly, as a pseudo-element's generated content. */
|
|
252
|
+
/** Each captured node's own text, its text children's joined in order, by the node's index. */
|
|
253
|
+
function ownTexts(capture: HTMLEngineCapture): Map<number, string> {
|
|
254
|
+
const texts = new Map<number, string>()
|
|
255
|
+
for (const node of capture.nodes) {
|
|
256
|
+
if (node.text === undefined || node.parent === undefined) continue
|
|
257
|
+
texts.set(node.parent, (texts.get(node.parent) ?? '') + node.text)
|
|
258
|
+
}
|
|
259
|
+
return texts
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Shows each element's `::before` and `::after` as elements of their own, first and last among its
|
|
264
|
+
* children, with the style, box, and text the engine generated for them, so they are imported as
|
|
265
|
+
* any element is.
|
|
266
|
+
*/
|
|
267
|
+
function showGeneratedContent(
|
|
268
|
+
capture: HTMLEngineCapture,
|
|
269
|
+
pairs: readonly [DesignElement, HTMLEngineNode][],
|
|
270
|
+
layout: boolean
|
|
271
|
+
): void {
|
|
272
|
+
const indexes = new Map(capture.nodes.map((node, index) => [node, index]))
|
|
273
|
+
const generated = generatedChildren(capture)
|
|
274
|
+
const texts = ownTexts(capture)
|
|
275
|
+
for (const [element, node] of pairs) {
|
|
276
|
+
const index = indexes.get(node)
|
|
277
|
+
for (const pseudo of (index === undefined ? undefined : generated.get(index)) ?? []) {
|
|
278
|
+
const captured = capture.nodes[pseudo]
|
|
279
|
+
const text = texts.get(pseudo) ?? ''
|
|
280
|
+
const child: DesignElement = {
|
|
281
|
+
type: 'element',
|
|
282
|
+
tagName: captured.tag ?? '::before',
|
|
283
|
+
attrs: {},
|
|
284
|
+
children: text ? [{ type: 'text', text }] : [],
|
|
285
|
+
computedStyle: withShorthands({
|
|
286
|
+
...capture.initial,
|
|
287
|
+
...captured.style,
|
|
288
|
+
...captured.computed
|
|
289
|
+
})
|
|
290
|
+
}
|
|
291
|
+
if (layout) child.layout = layoutOf(captured)
|
|
292
|
+
if (captured.tag === '::after') element.children.push(child)
|
|
293
|
+
else element.children.unshift(child)
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* The color the page's canvas is painted, as CSS takes it: the root element's background, or the
|
|
300
|
+
* body's when the root has none.
|
|
301
|
+
*/
|
|
302
|
+
function canvasBackground(capture: HTMLEngineCapture): string | undefined {
|
|
303
|
+
const background = (tag: string) => {
|
|
304
|
+
const node = capture.nodes.find((candidate) => candidate.tag === tag)
|
|
305
|
+
const color = node?.style?.['background-color']
|
|
306
|
+
return color && parseCSSColor(color) ? color : undefined
|
|
307
|
+
}
|
|
308
|
+
return background('html') ?? background('body')
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** A fetch that also keeps what it answered, by the URL asked for and the one it came from. */
|
|
312
|
+
function keepingFetch(
|
|
313
|
+
fetch: DesignResourceFetch | undefined,
|
|
314
|
+
answered: Map<string, DesignResource>
|
|
315
|
+
): DesignResourceFetch | undefined {
|
|
316
|
+
if (!fetch) return undefined
|
|
317
|
+
return async (url, signal) => {
|
|
318
|
+
const resource = await fetch(url, signal)
|
|
319
|
+
if (resource) answered.set(url, resource).set(resource.url, resource)
|
|
320
|
+
return resource
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** What an `<img>` loaded, by its `src` resolved against the page's address. */
|
|
325
|
+
function imageOf(
|
|
326
|
+
element: DesignElement,
|
|
327
|
+
answered: ReadonlyMap<string, DesignResource>,
|
|
328
|
+
baseURL: string | undefined
|
|
329
|
+
): DesignResource | undefined {
|
|
330
|
+
const { src } = element.attrs
|
|
331
|
+
if (element.tagName.toLowerCase() !== 'img' || !src || !URL.canParse(src, baseURL)) {
|
|
332
|
+
return undefined
|
|
333
|
+
}
|
|
334
|
+
return answered.get(new URL(src, baseURL).href)
|
|
335
|
+
}
|
|
336
|
+
|
|
234
337
|
export function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}): CSSRuntime {
|
|
235
|
-
const markup = createHeadlessCSSRuntime()
|
|
236
338
|
const engine = options.engine ?? loadHTMLEngine
|
|
237
339
|
return {
|
|
238
340
|
kind: 'headless',
|
|
239
|
-
parseHTML:
|
|
240
|
-
serializeHTML
|
|
341
|
+
parseHTML: parseHTMLDocument,
|
|
342
|
+
serializeHTML,
|
|
241
343
|
async computeStyles(document, cssText = '', compute: CSSComputeOptions = {}) {
|
|
242
344
|
const laidOut = await engine()
|
|
243
|
-
|
|
345
|
+
// The pictures the engine loads to lay images out go with their elements, so the layers
|
|
346
|
+
// they become show them without fetching them again.
|
|
347
|
+
const answered = new Map<string, DesignResource>()
|
|
348
|
+
const fetch = keepingFetch(options.fetch, answered)
|
|
349
|
+
const capture = await laidOut.layout(documentHTML(serializeHTML(document), cssText), {
|
|
244
350
|
baseURL: options.baseURL,
|
|
245
351
|
viewport: compute.viewport ?? DEFAULT_VIEWPORT,
|
|
246
|
-
fetch: fontFaceFetch(laidOut, cssText, options)
|
|
352
|
+
fetch: fontFaceFetch(laidOut, cssText, { ...options, fetch })
|
|
247
353
|
})
|
|
248
354
|
const styled = structuredClone(document)
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
355
|
+
const pairs = pairElements(styled, capture)
|
|
356
|
+
for (const [element, node] of pairs) {
|
|
357
|
+
// Every captured property's computed value, so none falls back to a stale inline one, with
|
|
358
|
+
// sizes and line heights as the page set them rather than as layout resolved them, so the
|
|
359
|
+
// importer tells a size the page fixed from one that fills or hugs and keeps a line height
|
|
360
|
+
// that scales with the font; the boxes layout gave stay in `layout`.
|
|
361
|
+
element.computedStyle = withShorthands({
|
|
362
|
+
...capture.initial,
|
|
363
|
+
...node.style,
|
|
364
|
+
...node.computed
|
|
365
|
+
})
|
|
252
366
|
if (compute.layout) element.layout = layoutOf(node)
|
|
367
|
+
const image = imageOf(element, answered, options.baseURL)
|
|
368
|
+
if (image) element.image = image
|
|
253
369
|
}
|
|
370
|
+
showGeneratedContent(capture, pairs, compute.layout === true)
|
|
371
|
+
styled.background = canvasBackground(capture)
|
|
254
372
|
return styled
|
|
255
373
|
}
|
|
256
374
|
}
|
package/src/schema.ts
CHANGED
|
@@ -47,6 +47,12 @@ const capturedNodeSchema = v.object({
|
|
|
47
47
|
* `color`, sizes, and font properties.
|
|
48
48
|
*/
|
|
49
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())),
|
|
50
56
|
/** An inline element's box on each line it spans, in page pixels. */
|
|
51
57
|
fragments: v.optional(v.array(rectSchema)),
|
|
52
58
|
/** The lines of the inline formatting context the element holds, in page pixels. */
|
|
@@ -2108,8 +2108,6 @@ limitations under the License.
|
|
|
2108
2108
|
|
|
2109
2109
|
## Apache License 2.0
|
|
2110
2110
|
|
|
2111
|
-
- servo_arc 0.5.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
2112
|
-
- stylo_malloc_size_of 0.22.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
2113
2111
|
- [arrayvec 0.7.8](https://crates.io/crates/arrayvec/0.7.8)
|
|
2114
2112
|
- [base64 0.23.1](https://crates.io/crates/base64/0.23.1)
|
|
2115
2113
|
- [bitflags 2.13.2](https://crates.io/crates/bitflags/2.13.2)
|
|
@@ -2126,7 +2124,7 @@ limitations under the License.
|
|
|
2126
2124
|
- [fastrand 2.5.0](https://crates.io/crates/fastrand/2.5.0)
|
|
2127
2125
|
- [flate2 1.1.10](https://crates.io/crates/flate2/1.1.10)
|
|
2128
2126
|
- [fnv 1.0.7](https://crates.io/crates/fnv/1.0.7)
|
|
2129
|
-
- [fontique 0.
|
|
2127
|
+
- [fontique 0.13.0](https://crates.io/crates/fontique/0.13.0)
|
|
2130
2128
|
- [form_urlencoded 1.2.2](https://crates.io/crates/form_urlencoded/1.2.2)
|
|
2131
2129
|
- [hashbrown 0.17.1](https://crates.io/crates/hashbrown/0.17.1)
|
|
2132
2130
|
- [heck 0.5.0](https://crates.io/crates/heck/0.5.0)
|
|
@@ -2149,20 +2147,22 @@ limitations under the License.
|
|
|
2149
2147
|
- [parking_lot 0.12.5](https://crates.io/crates/parking_lot/0.12.5)
|
|
2150
2148
|
- [parking_lot_core 0.9.12](https://crates.io/crates/parking_lot_core/0.9.12)
|
|
2151
2149
|
- [parlance 0.1.1](https://crates.io/crates/parlance/0.1.1)
|
|
2152
|
-
- [parley 0.
|
|
2153
|
-
- [parley_data 0.
|
|
2150
|
+
- [parley 0.13.0](https://crates.io/crates/parley/0.13.0)
|
|
2151
|
+
- [parley_data 0.13.0](https://crates.io/crates/parley_data/0.13.0)
|
|
2154
2152
|
- [percent-encoding 2.3.2](https://crates.io/crates/percent-encoding/2.3.2)
|
|
2155
2153
|
- [rayon-core 1.13.0](https://crates.io/crates/rayon-core/1.13.0)
|
|
2156
2154
|
- [rayon 1.12.0](https://crates.io/crates/rayon/1.12.0)
|
|
2157
2155
|
- [roxmltree 0.21.2](https://crates.io/crates/roxmltree/0.21.2)
|
|
2158
2156
|
- [scopeguard 1.2.0](https://crates.io/crates/scopeguard/1.2.0)
|
|
2157
|
+
- [servo_arc 0.6.0](https://crates.io/crates/servo_arc/0.6.0)
|
|
2159
2158
|
- [simplecss 0.2.2](https://crates.io/crates/simplecss/0.2.2)
|
|
2160
2159
|
- [smallbitvec 2.6.1](https://crates.io/crates/smallbitvec/2.6.1)
|
|
2161
2160
|
- [smallvec 1.16.4](https://crates.io/crates/smallvec/1.16.4)
|
|
2162
2161
|
- [smol_str 0.3.7](https://crates.io/crates/smol_str/0.3.7)
|
|
2163
2162
|
- [stable_deref_trait 1.2.1](https://crates.io/crates/stable_deref_trait/1.2.1)
|
|
2164
2163
|
- [string_cache 0.11.0](https://crates.io/crates/string_cache/0.11.0)
|
|
2165
|
-
- [
|
|
2164
|
+
- [stylo_malloc_size_of 0.24.0](https://crates.io/crates/stylo_malloc_size_of/0.24.0)
|
|
2165
|
+
- [svgtypes 0.16.2](https://crates.io/crates/svgtypes/0.16.2)
|
|
2166
2166
|
- [tendril 0.5.1](https://crates.io/crates/tendril/0.5.1)
|
|
2167
2167
|
- [thread_local 1.1.10](https://crates.io/crates/thread_local/1.1.10)
|
|
2168
2168
|
- [unicode-bidi 0.3.18](https://crates.io/crates/unicode-bidi/0.3.18)
|
|
@@ -2996,8 +2996,8 @@ limitations under the License.
|
|
|
2996
2996
|
## Apache License 2.0
|
|
2997
2997
|
|
|
2998
2998
|
- [font-types 0.12.7](https://crates.io/crates/font-types/0.12.7)
|
|
2999
|
-
- [read-fonts 0.
|
|
3000
|
-
- [skrifa 0.
|
|
2999
|
+
- [read-fonts 0.46.0](https://crates.io/crates/read-fonts/0.46.0)
|
|
3000
|
+
- [skrifa 0.49.0](https://crates.io/crates/skrifa/0.49.0)
|
|
3001
3001
|
|
|
3002
3002
|
```text
|
|
3003
3003
|
Apache License
|
|
@@ -3142,11 +3142,11 @@ limitations under the License.
|
|
|
3142
3142
|
|
|
3143
3143
|
## Apache License 2.0
|
|
3144
3144
|
|
|
3145
|
-
- blitz-dom 0.3.0-beta.4, built from `git+https://github.com/
|
|
3146
|
-
- blitz-html 0.3.0-beta.4, built from `git+https://github.com/
|
|
3147
|
-
- blitz-traits 0.3.0-beta.4, built from `git+https://github.com/
|
|
3148
|
-
- debug_timer 0.1.3, built from `git+https://github.com/
|
|
3149
|
-
- stylo_taffy 0.3.0-beta.4, built from `git+https://github.com/
|
|
3145
|
+
- blitz-dom 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=72ca31a350317da83dbf8cfc74d34b3bf56cd214#72ca31a350317da83dbf8cfc74d34b3bf56cd214`
|
|
3146
|
+
- blitz-html 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=72ca31a350317da83dbf8cfc74d34b3bf56cd214#72ca31a350317da83dbf8cfc74d34b3bf56cd214`
|
|
3147
|
+
- blitz-traits 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=72ca31a350317da83dbf8cfc74d34b3bf56cd214#72ca31a350317da83dbf8cfc74d34b3bf56cd214`
|
|
3148
|
+
- debug_timer 0.1.3, built from `git+https://github.com/open-pencil/blitz?rev=72ca31a350317da83dbf8cfc74d34b3bf56cd214#72ca31a350317da83dbf8cfc74d34b3bf56cd214`
|
|
3149
|
+
- stylo_taffy 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=72ca31a350317da83dbf8cfc74d34b3bf56cd214#72ca31a350317da83dbf8cfc74d34b3bf56cd214`
|
|
3150
3150
|
- [allocator-api2 0.2.21](https://crates.io/crates/allocator-api2/0.2.21)
|
|
3151
3151
|
- [color 0.3.3](https://crates.io/crates/color/0.3.3)
|
|
3152
3152
|
- [dtoa 1.0.11](https://crates.io/crates/dtoa/1.0.11)
|
|
@@ -3156,7 +3156,7 @@ limitations under the License.
|
|
|
3156
3156
|
- [libc 0.2.191](https://crates.io/crates/libc/0.2.191)
|
|
3157
3157
|
- [linebender_resource_handle 0.1.1](https://crates.io/crates/linebender_resource_handle/0.1.1)
|
|
3158
3158
|
- [miniz_oxide 0.9.1](https://crates.io/crates/miniz_oxide/0.9.1)
|
|
3159
|
-
- [parley_engine 0.
|
|
3159
|
+
- [parley_engine 0.13.0](https://crates.io/crates/parley_engine/0.13.0)
|
|
3160
3160
|
- [pin-project-lite 0.2.17](https://crates.io/crates/pin-project-lite/0.2.17)
|
|
3161
3161
|
- [proc-macro2 1.0.107](https://crates.io/crates/proc-macro2/1.0.107)
|
|
3162
3162
|
- [quote 1.0.47](https://crates.io/crates/quote/1.0.47)
|
|
@@ -3170,7 +3170,7 @@ limitations under the License.
|
|
|
3170
3170
|
- [syn 3.0.9](https://crates.io/crates/syn/3.0.9)
|
|
3171
3171
|
- [thin-vec 0.2.21](https://crates.io/crates/thin-vec/0.2.21)
|
|
3172
3172
|
- [unicode-ident 1.0.27](https://crates.io/crates/unicode-ident/1.0.27)
|
|
3173
|
-
- [usvg 0.
|
|
3173
|
+
- [usvg 0.50.0](https://crates.io/crates/usvg/0.50.0)
|
|
3174
3174
|
|
|
3175
3175
|
```text
|
|
3176
3176
|
Apache License
|
|
@@ -3637,7 +3637,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
|
|
|
3637
3637
|
|
|
3638
3638
|
## MIT License
|
|
3639
3639
|
|
|
3640
|
-
- [parley_emoji 0.
|
|
3640
|
+
- [parley_emoji 0.13.0](https://crates.io/crates/parley_emoji/0.13.0)
|
|
3641
3641
|
|
|
3642
3642
|
```text
|
|
3643
3643
|
Copyright 2020 the Parley Authors
|
|
@@ -3761,7 +3761,7 @@ SOFTWARE.
|
|
|
3761
3761
|
|
|
3762
3762
|
## MIT License
|
|
3763
3763
|
|
|
3764
|
-
- taffy 0.15.0, built from `git+https://github.com/
|
|
3764
|
+
- taffy 0.15.0, built from `git+https://github.com/open-pencil/taffy?rev=eeb0e4e7e94a825ed5f4e88d4238c3d31ede21c7#eeb0e4e7e94a825ed5f4e88d4238c3d31ede21c7`
|
|
3765
3765
|
|
|
3766
3766
|
```text
|
|
3767
3767
|
MIT License
|
|
@@ -4117,7 +4117,7 @@ SOFTWARE.
|
|
|
4117
4117
|
|
|
4118
4118
|
## MIT License
|
|
4119
4119
|
|
|
4120
|
-
- [harfrust 0.
|
|
4120
|
+
- [harfrust 0.15.0](https://crates.io/crates/harfrust/0.15.0)
|
|
4121
4121
|
|
|
4122
4122
|
```text
|
|
4123
4123
|
The MIT License (MIT)
|
|
@@ -5291,16 +5291,16 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice
|
|
|
5291
5291
|
|
|
5292
5292
|
## Mozilla Public License 2.0
|
|
5293
5293
|
|
|
5294
|
-
- stylo 0.22.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
5295
|
-
- selectors 0.41.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
5296
|
-
- stylo_atoms 0.22.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
5297
|
-
- stylo_derive 0.22.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
5298
|
-
- stylo_dom 0.22.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
5299
|
-
- stylo_static_prefs 0.22.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
5300
|
-
- stylo_traits 0.22.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
5301
|
-
- to_shmem 0.6.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
5302
|
-
- to_shmem_derive 0.2.0, built from `git+https://github.com/DioxusLabs/stylo?rev=d6502e0002e9c40c43a0a4776f9e7eb93be360e3#d6502e0002e9c40c43a0a4776f9e7eb93be360e3`
|
|
5303
5294
|
- [app_units 0.7.8](https://crates.io/crates/app_units/0.7.8)
|
|
5295
|
+
- [selectors 0.43.0](https://crates.io/crates/selectors/0.43.0)
|
|
5296
|
+
- [stylo 0.24.0](https://crates.io/crates/stylo/0.24.0)
|
|
5297
|
+
- [stylo_atoms 0.24.0](https://crates.io/crates/stylo_atoms/0.24.0)
|
|
5298
|
+
- [stylo_derive 0.24.0](https://crates.io/crates/stylo_derive/0.24.0)
|
|
5299
|
+
- [stylo_dom 0.24.0](https://crates.io/crates/stylo_dom/0.24.0)
|
|
5300
|
+
- [stylo_static_prefs 0.24.0](https://crates.io/crates/stylo_static_prefs/0.24.0)
|
|
5301
|
+
- [stylo_traits 0.24.0](https://crates.io/crates/stylo_traits/0.24.0)
|
|
5302
|
+
- [to_shmem 0.8.0](https://crates.io/crates/to_shmem/0.8.0)
|
|
5303
|
+
- [to_shmem_derive 0.3.0](https://crates.io/crates/to_shmem_derive/0.3.0)
|
|
5304
5304
|
|
|
5305
5305
|
```text
|
|
5306
5306
|
Mozilla Public License Version 2.0
|
|
@@ -5728,17 +5728,17 @@ authorization of the copyright holder.
|
|
|
5728
5728
|
|
|
5729
5729
|
## Unicode License v3
|
|
5730
5730
|
|
|
5731
|
-
- [icu_collections 2.
|
|
5731
|
+
- [icu_collections 2.3.0](https://crates.io/crates/icu_collections/2.3.0)
|
|
5732
5732
|
- [icu_locale_core 2.4.0](https://crates.io/crates/icu_locale_core/2.4.0)
|
|
5733
|
-
- [icu_locale_fallback 2.
|
|
5734
|
-
- [icu_locale_fallback_data 2.
|
|
5735
|
-
- [icu_normalizer 2.
|
|
5736
|
-
- [icu_normalizer_data 2.
|
|
5737
|
-
- [icu_properties 2.
|
|
5738
|
-
- [icu_properties_data 2.
|
|
5733
|
+
- [icu_locale_fallback 2.3.0](https://crates.io/crates/icu_locale_fallback/2.3.0)
|
|
5734
|
+
- [icu_locale_fallback_data 2.3.0](https://crates.io/crates/icu_locale_fallback_data/2.3.0)
|
|
5735
|
+
- [icu_normalizer 2.3.0](https://crates.io/crates/icu_normalizer/2.3.0)
|
|
5736
|
+
- [icu_normalizer_data 2.3.0](https://crates.io/crates/icu_normalizer_data/2.3.0)
|
|
5737
|
+
- [icu_properties 2.3.0](https://crates.io/crates/icu_properties/2.3.0)
|
|
5738
|
+
- [icu_properties_data 2.3.0](https://crates.io/crates/icu_properties_data/2.3.0)
|
|
5739
5739
|
- [icu_provider 2.4.0](https://crates.io/crates/icu_provider/2.4.0)
|
|
5740
|
-
- [icu_segmenter 2.
|
|
5741
|
-
- [icu_segmenter_data 2.
|
|
5740
|
+
- [icu_segmenter 2.3.0](https://crates.io/crates/icu_segmenter/2.3.0)
|
|
5741
|
+
- [icu_segmenter_data 2.3.0](https://crates.io/crates/icu_segmenter_data/2.3.0)
|
|
5742
5742
|
- [litemap 0.8.3](https://crates.io/crates/litemap/0.8.3)
|
|
5743
5743
|
- [potential_utf 0.1.6](https://crates.io/crates/potential_utf/0.1.6)
|
|
5744
5744
|
- [tinystr 0.8.5](https://crates.io/crates/tinystr/0.8.5)
|
package/wasm/html-engine.wasm
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
db79b6ca528525e61f8143e25b54f95a402c9100538e33bcc0d188779d0aac79
|