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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.
@@ -1,7 +1,7 @@
1
1
  import * as v from "valibot";
2
2
  //#region src/images.ts
3
3
  function ascii(bytes, at, length) {
4
- return String.fromCharCode(...bytes.subarray(at, at + length));
4
+ return Array.from(bytes.subarray(at, at + length), (code) => String.fromCharCode(code)).join("");
5
5
  }
6
6
  function webpSize(bytes, view) {
7
7
  const chunk = ascii(bytes, 12, 4);
@@ -144,6 +144,12 @@ const capturedNodeSchema = v.object({
144
144
  * `color`, sizes, and font properties.
145
145
  */
146
146
  style: v.optional(v.record(v.string(), v.string())),
147
+ /**
148
+ * Computed values where `style`'s used ones lose what the page set: the sizes (`width`,
149
+ * `height`, their minimums and maximums, and `flex-basis`) before layout resolves `auto` and
150
+ * percentages to pixels, such as `auto`, `50%`, or `390px`, and `line-height`, such as `1.5`.
151
+ */
152
+ computed: v.optional(v.record(v.string(), v.string())),
147
153
  /** An inline element's box on each line it spans, in page pixels. */
148
154
  fragments: v.optional(v.array(rectSchema)),
149
155
  /** The lines of the inline formatting context the element holds, in page pixels. */
@@ -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,IAAI,IAAI,IAAI,KAAM;CAC9E,IAAI,UAAU,QAAQ;EACpB,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;EACpC,OAAO,EAAE,OAAO,SAAU,IAAK,QAAQ,KAAM,SAAU,CAAC;CAC1D;CACA,IAAI,UAAU,QAGZ,OAAO,CAFO,KAAK,MAAM,MAAO,MAAM,OAAO,IAAM,MAAM,OAAO,KACjD,KAAK,MAAM,MAAO,MAAM,OAAO,IAAM,MAAM,OAAO,GAC5C;CAEvB,OAAO;AACT;;AAGA,SAAS,eAAe,QAAyB;CAC/C,OAAO,UAAU,OAAQ,UAAU,OAAQ,WAAW,OAAQ,WAAW,OAAQ,WAAW;AAC9F;AAEA,MAAM,OAAO;AACb,MAAM,kBAAkB;;;;;;AAOxB,SAAS,gBACP,OACA,MACA,IACA,KACe;CACf,MAAM,OAAO,KAAK;CAClB,IAAI,OAAO,IAAI,OAAO,MAAM,OAAO,KAAK,GAAG,CAAC,MAAM,YAAY,OAAO;CACrE,MAAM,eAAe,MAAM,OAAO,MAAM,CAAC,MAAM;CAC/C,MAAM,WAAW,OAAO,KAAK,UAAU,OAAO,GAAG,YAAY;CAC7D,IAAI,WAAW,IAAI,KAAK,OAAO;CAC/B,MAAM,UAAU,KAAK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,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","#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 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 { 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,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,CAAC,KAAK,UAAU,IAAI,IAAI,IAAI,OAAQ,KAAK,UAAU,IAAI,IAAI,IAAI,KAAM;CAC9E,IAAI,UAAU,QAAQ;EACpB,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;EACpC,OAAO,EAAE,OAAO,SAAU,IAAK,QAAQ,KAAM,SAAU,CAAC;CAC1D;CACA,IAAI,UAAU,QAGZ,OAAO,CAFO,KAAK,MAAM,MAAO,MAAM,OAAO,IAAM,MAAM,OAAO,KACjD,KAAK,MAAM,MAAO,MAAM,OAAO,IAAM,MAAM,OAAO,GAC5C;CAEvB,OAAO;AACT;;AAGA,SAAS,eAAe,QAAyB;CAC/C,OAAO,UAAU,OAAQ,UAAU,OAAQ,WAAW,OAAQ,WAAW,OAAQ,WAAW;AAC9F;AAEA,MAAM,OAAO;AACb,MAAM,kBAAkB;;;;;;AAOxB,SAAS,gBACP,OACA,MACA,IACA,KACe;CACf,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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,5 +1,8 @@
1
1
  import { HTMLEngine } from "./engine.js";
2
- import { createHeadlessCSSRuntime, parseFontFaceRules, parseStylesheetImports } from "@open-pencil/dom-css";
2
+ import { parseFontFaceRules, parseHTMLDocument, parseStylesheetImports } from "@open-pencil/dom-css";
3
+ import { serializeHTML } from "@open-pencil/dom-css/export";
4
+ import { insertAll, maxOf, minOf } from "@open-pencil/scene-graph/arrays";
5
+ import { computeBounds } from "@open-pencil/scene-graph/geometry";
3
6
  //#region src/load.ts
4
7
  let locator = () => import.meta.resolve("@open-pencil/html-engine/wasm/html-engine.wasm");
5
8
  let loading = null;
@@ -130,7 +133,7 @@ function pairElements(document, capture) {
130
133
  while (node !== void 0 && !sameTag(capture.nodes[node].tag, element.tagName)) {
131
134
  const tag = capture.nodes[node].tag;
132
135
  if (tag === void 0 || !IMPLIED_WRAPPERS.has(tag)) return;
133
- queue.unshift(...children.get(node) ?? []);
136
+ insertAll(queue, 0, children.get(node) ?? []);
134
137
  node = queue.shift();
135
138
  }
136
139
  if (node === void 0) return;
@@ -173,8 +176,8 @@ function textLine(line, keepsSpaces) {
173
176
  const texts = line.runs.filter((run) => "text" in run && run.text.length > 0);
174
177
  const words = keepsSpaces ? texts : texts.filter((run) => "text" in run && run.text.trim() !== "");
175
178
  if (words.length === 0) return null;
176
- const left = Math.min(...words.map((run) => run.x));
177
- const right = Math.max(...words.map((run) => run.x + run.width));
179
+ const left = minOf(words.map((run) => run.x));
180
+ const right = maxOf(words.map((run) => run.x + run.width));
178
181
  return {
179
182
  x: left,
180
183
  y: line.y,
@@ -188,6 +191,7 @@ function layoutOf(node) {
188
191
  const fragments = node.fragments?.filter(hasArea);
189
192
  if (fragments && fragments.length > 0) {
190
193
  layout.fragments = fragments.map(rect);
194
+ layout.box = computeBounds(layout.fragments);
191
195
  return layout;
192
196
  }
193
197
  const whiteSpace = node.style?.["white-space"];
@@ -202,19 +206,17 @@ function documentHTML(body, cssText) {
202
206
  /**
203
207
  * A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,
204
208
  * 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 as the headless
206
- * runtime does.
209
+ * browser runtime records, before transforms. Documents are parsed and serialized by dom-css.
207
210
  */
208
211
  function createHTMLEngineRuntime(options = {}) {
209
- const markup = createHeadlessCSSRuntime();
210
212
  const engine = options.engine ?? loadHTMLEngine;
211
213
  return {
212
214
  kind: "headless",
213
- parseHTML: (html) => markup.parseHTML(html),
214
- serializeHTML: (document) => markup.serializeHTML(document),
215
+ parseHTML: parseHTMLDocument,
216
+ serializeHTML,
215
217
  async computeStyles(document, cssText = "", compute = {}) {
216
218
  const laidOut = await engine();
217
- const capture = await laidOut.layout(documentHTML(markup.serializeHTML(document), cssText), {
219
+ const capture = await laidOut.layout(documentHTML(serializeHTML(document), cssText), {
218
220
  baseURL: options.baseURL,
219
221
  viewport: compute.viewport ?? DEFAULT_VIEWPORT,
220
222
  fetch: fontFaceFetch(laidOut, cssText, options)
@@ -223,7 +225,8 @@ function createHTMLEngineRuntime(options = {}) {
223
225
  for (const [element, node] of pairElements(styled, capture)) {
224
226
  element.computedStyle = withShorthands({
225
227
  ...capture.initial,
226
- ...node.style
228
+ ...node.style,
229
+ ...node.computed
227
230
  });
228
231
  if (compute.layout) element.layout = layoutOf(node);
229
232
  }
@@ -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,wDACtC,EAAE,OAAO,MAAM,CACjB;CACF,CAAC;CACD,OAAO,KAAK,OAAO,MAAM,KAAK,YAAY,KAAK,aAAa,KAAK,UAAU;AA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C,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 { 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 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 DesignStyleDeclaration,\n type DesignViewport\n} from '@open-pencil/dom-css'\nimport { serializeHTML } from '@open-pencil/dom-css/export'\nimport { insertAll, maxOf, minOf } from '@open-pencil/scene-graph/arrays'\nimport { computeBounds } from '@open-pencil/scene-graph/geometry'\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 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 */\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 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)\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, 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 }\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,wDACtC,EAAE,OAAO,MAAM,CACjB;CACF,CAAC;CACD,OAAO,KAAK,OAAO,MAAM,KAAK,YAAY,KAAK,aAAa,KAAK,UAAU;AAC7E;;AAGA,SAAgB,iBAAsC;CACpD,IAAI,SAAS,OAAO;CACpB,MAAM,OAAO,WAAW,QAAQ,CAAC,CAAC,CAAC,MAAM,UAAU,WAAW,YAAY,KAAK,CAAC;CAChF,UAAU;CACV,KAAK,YAAY;EACf,IAAI,YAAY,MAAM,UAAU;CAClC,CAAC;CACD,OAAO;AACT;;;;AC7BA,MAAM,mBAAmC;CAAE,OAAO;CAAM,QAAQ;AAAI;AA4BpE,SAAS,aAAa,UAAuC;CAC3D,OAAO,S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W;EACX;EACA,MAAM,cAAc,UAAU,UAAU,IAAI,UAA6B,CAAC,GAAG;GAC3E,MAAM,UAAU,MAAM,OAAO;GAC7B,MAAM,UAAU,MAAM,QAAQ,OAAO,aAAa,cAAc,QAAQ,GAAG,OAAO,GAAG;IACnF,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;IAK3D,QAAQ,gBAAgB,eAAe;KACrC,GAAG,QAAQ;KACX,GAAG,KAAK;KACR,GAAG,KAAK;IACV,CAAC;IACD,IAAI,QAAQ,QAAQ,QAAQ,SAAS,SAAS,IAAI;GACpD;GACA,OAAO;EACT;CACF;AACF"}
package/dist/index.d.ts CHANGED
@@ -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. */
@@ -224,8 +236,7 @@ interface HTMLEngineRuntimeOptions {
224
236
  /**
225
237
  * A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,
226
238
  * 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.
239
+ * browser runtime records, before transforms. Documents are parsed and serialized by dom-css.
229
240
  */
230
241
  declare function createHTMLEngineRuntime(options?: HTMLEngineRuntimeOptions): CSSRuntime;
231
242
  //#endregion
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA4BX,eAAa,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAWd,oBAAoB,EAAE,mBAAmB;KACzC,iBAAiB,EAAE,mBAAmB;KACtC,iBAAiB,EAAE,mB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SAAS,QAAQ;;;;;;EA8B7E,QAAQ,OAAO,YAAY;;;;;EAY3B,iBAAiB,iBAAiB;;EASlC,WAAW,OAAO,aAAa;;EAQ/B;;EAkEA,OAAO,cAAc,SAAS,0BAA0B,QAAQ;;;;;;;;;KC9Q7D,QAAQ,eAAe;;iBAoGZ,gBAAgB,OAAO,aAAa;;;;;;;;KCnGxC;;iBAcI,qBAAqB,QAAQ;;iBAuB7B,kBAAkB,QAAQ;;;;UClBzB;EACf;EACA;EACA;EACA;EACA,OAAO;;UAGQ;;EAEf,eAAe,QAAQ;;EAEvB;;;;;EAKA,QAAQ;;;;;EAKR,cAAc,MAAM,8BAA8B;;;;;;;iBA6LpC,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.4",
3
+ "version": "0.17.0-beta.5",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -11,11 +11,11 @@
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.4",
14
+ "@open-pencil/dom-css": "^0.17.0-beta.5",
15
15
  "valibot": "^1.5.0"
16
16
  },
17
17
  "peerDependencies": {
18
- "@open-pencil/scene-graph": "^0.17.0-beta.4"
18
+ "@open-pencil/scene-graph": "^0.17.0-beta.5"
19
19
  },
20
20
  "exports": {
21
21
  ".": {
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 String.fromCharCode(...bytes.subarray(at, at + length))
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/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,
@@ -11,6 +11,9 @@ import {
11
11
  type DesignStyleDeclaration,
12
12
  type DesignViewport
13
13
  } from '@open-pencil/dom-css'
14
+ import { serializeHTML } from '@open-pencil/dom-css/export'
15
+ import { insertAll, maxOf, minOf } from '@open-pencil/scene-graph/arrays'
16
+ import { computeBounds } from '@open-pencil/scene-graph/geometry'
14
17
  import type { Rect } from '@open-pencil/scene-graph/primitives'
15
18
 
16
19
  import type { HTMLEngine, HTMLEngineFetch, HTMLEngineResource } from './engine'
@@ -150,7 +153,7 @@ function pairElements(
150
153
  while (node !== undefined && !sameTag(capture.nodes[node].tag, element.tagName)) {
151
154
  const tag = capture.nodes[node].tag
152
155
  if (tag === undefined || !IMPLIED_WRAPPERS.has(tag)) return
153
- queue.unshift(...(children.get(node) ?? []))
156
+ insertAll(queue, 0, children.get(node) ?? [])
154
157
  node = queue.shift()
155
158
  }
156
159
  if (node === undefined) return
@@ -197,8 +200,8 @@ function textLine(line: HTMLEngineLine, keepsSpaces: boolean): Rect | null {
197
200
  const texts = line.runs.filter((run) => 'text' in run && run.text.length > 0)
198
201
  const words = keepsSpaces ? texts : texts.filter((run) => 'text' in run && run.text.trim() !== '')
199
202
  if (words.length === 0) return null
200
- const left = Math.min(...words.map((run) => run.x))
201
- const right = Math.max(...words.map((run) => run.x + run.width))
203
+ const left = minOf(words.map((run) => run.x))
204
+ const right = maxOf(words.map((run) => run.x + run.width))
202
205
  return { x: left, y: line.y, width: right - left, height: line.height }
203
206
  }
204
207
 
@@ -208,6 +211,8 @@ function layoutOf(node: HTMLEngineNode): DesignLayout | undefined {
208
211
  const fragments = node.fragments?.filter(hasArea)
209
212
  if (fragments && fragments.length > 0) {
210
213
  layout.fragments = fragments.map(rect)
214
+ // An inline element's box is the one around its fragments, as getBoundingClientRect gives.
215
+ layout.box = computeBounds(layout.fragments)
211
216
  return layout
212
217
  }
213
218
  const whiteSpace = node.style?.['white-space']
@@ -228,27 +233,32 @@ function documentHTML(body: string, cssText: string): string {
228
233
  /**
229
234
  * A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,
230
235
  * without one: computed styles and, when asked, the boxes, inline fragments, and text lines a
231
- * browser runtime records, before transforms. Documents are parsed and serialized as the headless
232
- * runtime does.
236
+ * browser runtime records, before transforms. Documents are parsed and serialized by dom-css.
233
237
  */
234
238
  export function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}): CSSRuntime {
235
- const markup = createHeadlessCSSRuntime()
236
239
  const engine = options.engine ?? loadHTMLEngine
237
240
  return {
238
241
  kind: 'headless',
239
- parseHTML: (html) => markup.parseHTML(html),
240
- serializeHTML: (document) => markup.serializeHTML(document),
242
+ parseHTML: parseHTMLDocument,
243
+ serializeHTML,
241
244
  async computeStyles(document, cssText = '', compute: CSSComputeOptions = {}) {
242
245
  const laidOut = await engine()
243
- const capture = await laidOut.layout(documentHTML(markup.serializeHTML(document), cssText), {
246
+ const capture = await laidOut.layout(documentHTML(serializeHTML(document), cssText), {
244
247
  baseURL: options.baseURL,
245
248
  viewport: compute.viewport ?? DEFAULT_VIEWPORT,
246
249
  fetch: fontFaceFetch(laidOut, cssText, options)
247
250
  })
248
251
  const styled = structuredClone(document)
249
252
  for (const [element, node] of pairElements(styled, capture)) {
250
- // Every captured property's computed value, so none falls back to a stale inline one.
251
- element.computedStyle = withShorthands({ ...capture.initial, ...node.style })
253
+ // Every captured property's computed value, so none falls back to a stale inline one, with
254
+ // sizes and line heights as the page set them rather than as layout resolved them, so the
255
+ // importer tells a size the page fixed from one that fills or hugs and keeps a line height
256
+ // that scales with the font; the boxes layout gave stay in `layout`.
257
+ element.computedStyle = withShorthands({
258
+ ...capture.initial,
259
+ ...node.style,
260
+ ...node.computed
261
+ })
252
262
  if (compute.layout) element.layout = layoutOf(node)
253
263
  }
254
264
  return styled
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.12.0](https://crates.io/crates/fontique/0.12.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.12.0](https://crates.io/crates/parley/0.12.0)
2153
- - [parley_data 0.12.0](https://crates.io/crates/parley_data/0.12.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
- - [svgtypes 0.16.1](https://crates.io/crates/svgtypes/0.16.1)
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.41.0](https://crates.io/crates/read-fonts/0.41.0)
3000
- - [skrifa 0.44.0](https://crates.io/crates/skrifa/0.44.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/DioxusLabs/blitz?rev=f540c664d6c37cbe1a232880223b28ef4a56f2af#f540c664d6c37cbe1a232880223b28ef4a56f2af`
3146
- - blitz-html 0.3.0-beta.4, built from `git+https://github.com/DioxusLabs/blitz?rev=f540c664d6c37cbe1a232880223b28ef4a56f2af#f540c664d6c37cbe1a232880223b28ef4a56f2af`
3147
- - blitz-traits 0.3.0-beta.4, built from `git+https://github.com/DioxusLabs/blitz?rev=f540c664d6c37cbe1a232880223b28ef4a56f2af#f540c664d6c37cbe1a232880223b28ef4a56f2af`
3148
- - debug_timer 0.1.3, built from `git+https://github.com/DioxusLabs/blitz?rev=f540c664d6c37cbe1a232880223b28ef4a56f2af#f540c664d6c37cbe1a232880223b28ef4a56f2af`
3149
- - stylo_taffy 0.3.0-beta.4, built from `git+https://github.com/DioxusLabs/blitz?rev=f540c664d6c37cbe1a232880223b28ef4a56f2af#f540c664d6c37cbe1a232880223b28ef4a56f2af`
3145
+ - blitz-dom 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=eabcebd1c4906a49fad3de54bf268d8ffba666a2#eabcebd1c4906a49fad3de54bf268d8ffba666a2`
3146
+ - blitz-html 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=eabcebd1c4906a49fad3de54bf268d8ffba666a2#eabcebd1c4906a49fad3de54bf268d8ffba666a2`
3147
+ - blitz-traits 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=eabcebd1c4906a49fad3de54bf268d8ffba666a2#eabcebd1c4906a49fad3de54bf268d8ffba666a2`
3148
+ - debug_timer 0.1.3, built from `git+https://github.com/open-pencil/blitz?rev=eabcebd1c4906a49fad3de54bf268d8ffba666a2#eabcebd1c4906a49fad3de54bf268d8ffba666a2`
3149
+ - stylo_taffy 0.3.0-beta.4, built from `git+https://github.com/open-pencil/blitz?rev=eabcebd1c4906a49fad3de54bf268d8ffba666a2#eabcebd1c4906a49fad3de54bf268d8ffba666a2`
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.12.0](https://crates.io/crates/parley_engine/0.12.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.48.1](https://crates.io/crates/usvg/0.48.1)
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.12.0](https://crates.io/crates/parley_emoji/0.12.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/DioxusLabs/taffy?rev=affd437f20432c253b88c39374ef83017b263d81#affd437f20432c253b88c39374ef83017b263d81`
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.12.0](https://crates.io/crates/harfrust/0.12.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.4.0](https://crates.io/crates/icu_collections/2.4.0)
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.4.0](https://crates.io/crates/icu_locale_fallback/2.4.0)
5734
- - [icu_locale_fallback_data 2.4.0](https://crates.io/crates/icu_locale_fallback_data/2.4.0)
5735
- - [icu_normalizer 2.4.0](https://crates.io/crates/icu_normalizer/2.4.0)
5736
- - [icu_normalizer_data 2.4.0](https://crates.io/crates/icu_normalizer_data/2.4.0)
5737
- - [icu_properties 2.4.0](https://crates.io/crates/icu_properties/2.4.0)
5738
- - [icu_properties_data 2.4.0](https://crates.io/crates/icu_properties_data/2.4.0)
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.4.0](https://crates.io/crates/icu_segmenter/2.4.0)
5741
- - [icu_segmenter_data 2.4.0](https://crates.io/crates/icu_segmenter_data/2.4.0)
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)
Binary file
@@ -1 +1 @@
1
- 9fce825a1c59e1f2df2e7d389822b549578d8725b6f33dee976088b062081147
1
+ 1afba8ec3f58a672766715c148916f03be542e3b1eb98be2e984d471c06d1dfe