@dotgui/embed 0.1.1 → 0.4.0

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.
@@ -0,0 +1,262 @@
1
+ /**
2
+ * The renderer, off the page's main thread.
3
+ *
4
+ * Every `<gui-canvas>` on a page shares this one worker: one copy of the WASM
5
+ * module, and one cache of fetched fonts and assets. Each element gets its own
6
+ * engine, keyed by the element, and — where the browser can transfer a canvas
7
+ * to a worker — its own `OffscreenCanvas`, which this draws into directly, so
8
+ * a frame's pixels never cross back to the page.
9
+ *
10
+ * Requests arrive as `{ id, type, ...payload }` and are answered with
11
+ * `{ id, ok, result }` or `{ id, ok: false, error }`.
12
+ */
13
+ import init, { Engine, normalize_markup } from './pkg/dotgui_renderer_wasm.js'
14
+
15
+ const wasmReady = init()
16
+
17
+ /**
18
+ * Fonts this package ships, offered to every engine as if installed. A browser
19
+ * has no font directory, so a `source="system"` family that no host supplies
20
+ * falls back to these instead of drawing nothing.
21
+ */
22
+ const BUNDLED_FONTS = [new URL('./fonts/Inter.woff2', import.meta.url).href]
23
+
24
+ /** key → { engine, canvas } */
25
+ const engines = new Map()
26
+
27
+ /**
28
+ * Bytes fetched for any engine, by URL or font path, so switching documents
29
+ * does not download an 8 MB system font again.
30
+ */
31
+ const fetched = new Map()
32
+ function fetchOnce(key, request) {
33
+ if (!fetched.has(key)) {
34
+ fetched.set(key, fetch(request)
35
+ // A failed fetch is held as empty bytes, so it is not asked for again.
36
+ .then((response) => (response.ok ? response.arrayBuffer() : new ArrayBuffer(0)))
37
+ .catch(() => new ArrayBuffer(0))
38
+ .then((buffer) => new Uint8Array(buffer)))
39
+ }
40
+ return fetched.get(key)
41
+ }
42
+
43
+ /**
44
+ * The host's font files: those a `font-list` endpoint names, when the page has
45
+ * one, then the bundled ones. Fetched once per endpoint.
46
+ */
47
+ const fontLists = new Map()
48
+ async function fontList(endpoint) {
49
+ return [...(endpoint ? await hostFontList(endpoint) : []), ...BUNDLED_FONTS]
50
+ }
51
+ function hostFontList(endpoint) {
52
+ if (!fontLists.has(endpoint)) {
53
+ fontLists.set(endpoint, fetch(endpoint)
54
+ .then((response) => (response.ok ? response.json() : []))
55
+ .catch(() => []))
56
+ }
57
+ return fontLists.get(endpoint)
58
+ }
59
+
60
+ function entry(key) {
61
+ const found = engines.get(key)
62
+ if (!found) throw new Error(`no engine ${key}`)
63
+ return found
64
+ }
65
+
66
+ /** Fetches `[key, request]` pairs and hands each to the engine under its key. */
67
+ async function supply(engine, wanted) {
68
+ const bytes = await Promise.all(wanted.map(([key, request]) => fetchOnce(key, request)))
69
+ wanted.forEach(([key], i) => engine.set_asset(key, bytes[i]))
70
+ }
71
+
72
+ /** A remote URL as fetched: through the page's asset proxy when it has one, otherwise directly. */
73
+ const viaProxy = (proxy, url) => (proxy ? proxy + encodeURIComponent(url) : url)
74
+
75
+ /**
76
+ * Where a host font file's bytes come from: a bundled font is a URL already;
77
+ * an installed one is served by the page's font endpoint.
78
+ */
79
+ const fontFileRequest = (fontFile, file) =>
80
+ /^(https?|blob|data):/.test(file) ? file : fontFile + encodeURIComponent(file)
81
+
82
+ /**
83
+ * Fetches the fonts the engine cannot — web fonts directly or through the
84
+ * asset proxy, host font files through the font endpoint — until it asks for
85
+ * nothing more. Each round can reveal more: a stylesheet names its font files,
86
+ * and a family that is not installed falls back to the next UI font.
87
+ */
88
+ async function supplyFonts(engine, xml, library, proxy, fontFile) {
89
+ let supplied = 0
90
+ for (let round = 0; round < 8; round++) {
91
+ const wanted = [
92
+ ...engine.missing_font_urls(xml, library).map((url) => [url, viaProxy(proxy, url)]),
93
+ ...engine.missing_font_files(xml, library).map((file) => [file, fontFileRequest(fontFile, file)]),
94
+ ]
95
+ if (wanted.length === 0) break
96
+ await supply(engine, wanted)
97
+ supplied += wanted.length
98
+ }
99
+ return supplied
100
+ }
101
+
102
+ /**
103
+ * Paints over the canvas only the areas where `xml` differs from the markup it
104
+ * shows, and answers like a render; `null` when the page has to be painted
105
+ * whole instead.
106
+ */
107
+ function patch(engine, canvas, last, xml, library) {
108
+ const started = performance.now()
109
+ const areas = engine.changed_areas(last.xml, xml, library)
110
+ if (areas === undefined) return null
111
+ const context = canvas.getContext('2d')
112
+ let layout = null
113
+ let warnings = []
114
+ let drawMs = 0
115
+ for (let i = 0; i < areas.length; i += 4) {
116
+ const frame = engine.render_area(xml, areas[i], areas[i + 1], areas[i + 2], areas[i + 3], last.drawnDensity, library)
117
+ const drawStarted = performance.now()
118
+ context.putImageData(new ImageData(new Uint8ClampedArray(frame.pixels), frame.width, frame.height), frame.x, frame.y)
119
+ drawMs += performance.now() - drawStarted
120
+ layout ??= frame.layout
121
+ warnings = frame.warnings
122
+ frame.free()
123
+ }
124
+ if (layout === null) {
125
+ // Nothing paints differently, but the layout's attributes may have: the
126
+ // page still answers hit tests from the new one.
127
+ const frame = engine.render_area(xml, 0, 0, 1, 1, last.drawnDensity, library)
128
+ layout = frame.layout
129
+ warnings = frame.warnings
130
+ frame.free()
131
+ }
132
+ return {
133
+ width: last.width,
134
+ height: last.height,
135
+ layout: JSON.parse(layout),
136
+ warnings,
137
+ engineMs: performance.now() - started - drawMs,
138
+ drawMs,
139
+ repainted: areas.length / 4,
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Reads documents in `modes` (RFC-0037), `{ axis: value }`, when they differ
145
+ * from the modes the engine has. Same markup in other tokens paints whole.
146
+ */
147
+ function applyModes(target, modes) {
148
+ const wanted = JSON.stringify(modes)
149
+ if ((target.modes ?? '{}') === wanted) return
150
+ target.engine.clear_modes()
151
+ for (const [axis, value] of Object.entries(modes)) target.engine.set_mode(axis, value)
152
+ target.modes = wanted
153
+ target.last = null
154
+ }
155
+
156
+ const handlers = {
157
+ normalize({ xml }) {
158
+ return [normalize_markup(xml)]
159
+ },
160
+
161
+ /**
162
+ * A fresh engine for `key`. The canvas is transferred once, on the first
163
+ * open; later opens — loading another document — keep it.
164
+ */
165
+ async open({ key, canvas, fontList: endpoint }) {
166
+ const previous = engines.get(key)
167
+ previous?.engine.free()
168
+ const engine = new Engine()
169
+ engine.set_host_font_files(await fontList(endpoint))
170
+ engines.set(key, { engine, canvas: canvas ?? previous?.canvas ?? null })
171
+ return [null]
172
+ },
173
+
174
+
175
+ /** Keeps the package's assets and library; answers with its pages. */
176
+ loadPackage({ key, bytes }) {
177
+ return [JSON.parse(entry(key).engine.load_package(new Uint8Array(bytes)))]
178
+ },
179
+
180
+ /**
181
+ * Renders once the fonts are in, without waiting for images: fonts decide
182
+ * the layout, images only fill boxes the markup has already sized. The
183
+ * result says how many images are still missing, for the page to fetch with
184
+ * `supplyImages` and render again.
185
+ *
186
+ * `library` says the markup is the package's `library.guix`: its page is
187
+ * drawn, and the documents drawn after it resolve against this markup.
188
+ */
189
+ async render({ key, xml, library, density, proxy, fontFile, modes = {} }) {
190
+ const target = entry(key)
191
+ const { engine, canvas } = target
192
+ applyModes(target, modes)
193
+ const fontsStarted = performance.now()
194
+ const suppliedFonts = await supplyFonts(engine, xml, library, proxy, fontFile)
195
+ const fontsMs = performance.now() - fontsStarted
196
+ const missingImages = engine.missing_image_urls(xml, library).length
197
+
198
+ // An edit to the markup the canvas already shows repaints only what it
199
+ // changed. Anything else — another page, another density, fonts or
200
+ // images that have just arrived — paints the page whole.
201
+ const last = target.last
202
+ const patchable = canvas && last && last.xml !== xml && last.library === library &&
203
+ last.density === density && !suppliedFonts && !target.assetsArrived
204
+ if (patchable) {
205
+ const patched = patch(engine, canvas, last, xml, library)
206
+ if (patched) {
207
+ target.last = { ...last, xml }
208
+ return [{ ...patched, density: last.drawnDensity, warnings: patched.warnings, fontsMs, missingImages }]
209
+ }
210
+ }
211
+
212
+ const started = performance.now()
213
+ const frame = engine.render(xml, density, library)
214
+ const engineMs = performance.now() - started
215
+ const { width, height } = frame
216
+ // Less than asked for when the page is too long for a canvas at that density.
217
+ const drawnDensity = frame.density
218
+ const layout = JSON.parse(frame.layout)
219
+ const warnings = frame.warnings
220
+ const pixels = frame.pixels
221
+ // The frame owns its pixels inside WASM memory until it is freed; a
222
+ // large screen at 2x is tens of megabytes.
223
+ frame.free()
224
+
225
+ const result = { width, height, density: drawnDensity, layout, warnings, engineMs, fontsMs, missingImages }
226
+ target.last = { xml, library, density, drawnDensity, width, height }
227
+ target.assetsArrived = false
228
+ if (!canvas) {
229
+ // No OffscreenCanvas: hand the pixels to the page, without copying.
230
+ return [{ ...result, pixels: pixels.buffer }, [pixels.buffer]]
231
+ }
232
+ const drawStarted = performance.now()
233
+ canvas.width = width
234
+ canvas.height = height
235
+ canvas.getContext('2d').putImageData(new ImageData(new Uint8ClampedArray(pixels.buffer), width, height), 0, 0)
236
+ return [{ ...result, drawMs: performance.now() - drawStarted }]
237
+ },
238
+
239
+ async supplyImages({ key, xml, library, proxy }) {
240
+ const target = entry(key)
241
+ const wanted = target.engine.missing_image_urls(xml, library).map((url) => [url, viaProxy(proxy, url)])
242
+ await supply(target.engine, wanted)
243
+ if (wanted.length > 0) target.assetsArrived = true
244
+ return [wanted.length]
245
+ },
246
+
247
+ close({ key }) {
248
+ engines.get(key)?.engine.free()
249
+ engines.delete(key)
250
+ return [null]
251
+ },
252
+ }
253
+
254
+ self.onmessage = async ({ data: { id, type, ...payload } }) => {
255
+ try {
256
+ await wasmReady
257
+ const [result, transfer = []] = await handlers[type](payload)
258
+ self.postMessage({ id, ok: true, result }, transfer)
259
+ } catch (error) {
260
+ self.postMessage({ id, ok: false, error: String(error?.message ?? error) })
261
+ }
262
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dotgui/embed",
3
- "version": "0.1.1",
4
- "description": "Drop-in browser layer that renders .gui files anywhere. A thin wrapper over @dotgui/kit's renderer — one CDN script, zero dependencies for the consumer.",
3
+ "version": "0.4.0",
4
+ "description": "Drop-in browser player that renders .gui files anywhere \u2014 one CDN script. Drawn by @dotgui/render, the Rust renderer as WebAssembly.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "./dist/gui-embed.esm.js",
@@ -10,7 +10,11 @@
10
10
  "unpkg": "./dist/gui-embed.js",
11
11
  "jsdelivr": "./dist/gui-embed.js",
12
12
  "exports": {
13
- ".": "./src/index.ts"
13
+ ".": {
14
+ "types": "./src/index.ts",
15
+ "default": "./dist/gui-embed.esm.js"
16
+ },
17
+ "./dist/*": "./dist/*"
14
18
  },
15
19
  "files": [
16
20
  "dist/",
@@ -18,10 +22,9 @@
18
22
  "README.md"
19
23
  ],
20
24
  "scripts": {
21
- "build": "bun run build:cdn && bun run build:esm",
22
- "build:cdn": "bun build ./src/auto.ts --outfile ./dist/gui-embed.js --format iife --minify",
23
- "build:esm": "bun build ./src/index.ts --outfile ./dist/gui-embed.esm.js --format esm --minify",
24
- "typecheck": "tsc --noEmit"
25
+ "build": "bun run build.ts",
26
+ "typecheck": "tsc --noEmit",
27
+ "prepublishOnly": "bun run build.ts"
25
28
  },
26
29
  "keywords": [
27
30
  "dotgui",
@@ -29,14 +32,16 @@
29
32
  "embed",
30
33
  "web-component",
31
34
  "cdn",
32
- "renderer"
35
+ "renderer",
36
+ "wasm"
33
37
  ],
34
38
  "repository": {
35
39
  "type": "git",
36
40
  "url": "https://github.com/dotgui/embed"
37
41
  },
38
42
  "dependencies": {
39
- "@dotgui/kit": "^0.1.0"
43
+ "@dotgui/kit": "^0.4.1",
44
+ "@dotgui/render": "^0.4.0"
40
45
  },
41
46
  "devDependencies": {
42
47
  "bun-types": "latest",
package/src/auto.ts CHANGED
@@ -3,12 +3,35 @@
3
3
  *
4
4
  * <script src="https://unpkg.com/@dotgui/embed"></script>
5
5
  *
6
- * After this, any `<gui>` or `<gui-embed>` on the page renders with no further
7
- * code. This is the zero-friction path (e.g. an AI emitting a renderable .gui).
6
+ * After this, any `<gui-embed>` on the page renders with no further code. This
7
+ * is the zero-friction path (e.g. an AI emitting a renderable .gui).
8
+ *
9
+ * The renderer runs in a worker beside this script: `render-worker.js`, with
10
+ * its WebAssembly and fonts, ship in `dist/` next to `gui-embed.js`.
8
11
  */
9
12
  import * as embed from './index'
10
13
 
14
+ declare const __EMBED_VERSION__: string
15
+
16
+ /**
17
+ * The worker's URL, from where this script was loaded. A CDN's bare package
18
+ * URL (`unpkg.com/@dotgui/embed`) names no file to resolve against, so it is
19
+ * pinned to this build's version and its `dist/`.
20
+ */
21
+ function workerUrl(): string | null {
22
+ const script = document.currentScript as HTMLScriptElement | null
23
+ if (!script?.src) return null
24
+ const url = new URL(script.src)
25
+ if (!/\.m?js$/.test(url.pathname)) {
26
+ const path = url.pathname.replace(/\/$/, '')
27
+ const versioned = (path.split('/').pop() ?? '').includes('@')
28
+ url.pathname = `${path}${versioned ? '' : `@${__EMBED_VERSION__}`}/dist/gui-embed.js`
29
+ }
30
+ return new URL('./render-worker.js', url).href
31
+ }
32
+
33
+ embed.config.workerUrl = workerUrl()
11
34
  embed.install()
12
35
 
13
- // Expose the API on a global for non-module pages (and the prototype demo).
36
+ // Expose the API on a global for non-module pages (and the demo).
14
37
  ;(globalThis as unknown as { GuiEmbed?: typeof embed }).GuiEmbed = embed