@dotgui/embed 0.2.0 → 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.
package/src/gui-embed.ts CHANGED
@@ -5,56 +5,66 @@
5
5
  * lives on `<gui>`. Everything here is host vocabulary, expressed in CSS:
6
6
  *
7
7
  * <gui-embed style="width:100vw;height:100vh" zoom download copy mode-switch>
8
- * <gui w="300" h="300"> … </gui>
8
+ * <script type="application/gui"> <gui w="300" h="300"> … </gui> </script>
9
9
  * </gui-embed>
10
10
  *
11
- * <gui-embed src="hero.gui" style="width:400px;aspect-ratio:auto"></gui-embed>
11
+ * <gui-embed src="hero.gui" style="width:400px"></gui-embed>
12
12
  *
13
- * The file is placed center-center, scaled to fit the canvas. Controls are
14
- * individual boolean attributes — present = on. `zoom` defaults on (it is a
15
- * player); `download`, `copy`, `mode-switch` default off.
13
+ * The drawing is `@dotgui/render`'s `<gui-canvas>`: the Rust renderer, as
14
+ * WebAssembly, in a worker. This element only places it — center-center,
15
+ * scaled to fit — and adds the player around it. Controls are individual
16
+ * boolean attributes — present = on. `zoom` defaults on (it is a player);
17
+ * `download`, `copy`, `mode-switch` default off.
16
18
  */
17
- import { render, type ZoomControl } from '@dotgui/kit/render'
18
- import {
19
- fetchGui,
20
- decodeMarkup,
21
- revokeAssets,
22
- toGuiBytes,
23
- type Decoded,
24
- } from './decode'
25
- import { detectModes, switchableAxes, type ModeAxis } from './modes'
19
+ import type { GuiCanvas, ModeAxis, RenderDetail } from '@dotgui/render/canvas'
20
+ import { pack } from '@dotgui/kit/package'
26
21
 
27
22
  const TAG = 'gui-embed'
28
23
 
24
+ /** How far a zoom may go, as a multiple of the fitted scale. */
25
+ const MIN_ZOOM = 0.25
26
+ const MAX_ZOOM = 8
27
+
29
28
  export class GuiEmbedElement extends HTMLElement {
30
- private _canvas!: HTMLDivElement
29
+ private _stage!: HTMLDivElement
30
+ private _view!: HTMLDivElement
31
+ private _canvas!: GuiCanvas
31
32
  private _bar!: HTMLDivElement
32
- private _zoomCtl: ZoomControl | null = null
33
- private _decoded: Decoded | null = null
34
- private _modes: Record<string, ModeAxis> = {}
35
- private _mode: Record<string, string> = {}
36
33
  private _ro: ResizeObserver | null = null
34
+ /** The bytes shown, kept for download: a fetched file as it came, or inline markup. */
35
+ private _bytes: Uint8Array | null = null
36
+ private _markup = ''
37
+ /** The document's size in document pixels, once drawn. */
38
+ private _size: { width: number; height: number } | null = null
39
+ /** The view: scale, and the document's top-left in the stage. */
40
+ private _scale = 1
41
+ private _x = 0
42
+ private _y = 0
37
43
  /** True once the user pans/zooms — stops auto-fit from snapping their view back. */
38
44
  private _userZoomed = false
45
+ private _settle: ReturnType<typeof setTimeout> | null = null
39
46
 
40
47
  static get observedAttributes() {
41
48
  return ['src']
42
49
  }
43
50
 
44
51
  connectedCallback() {
45
- if (!this._canvas) this._build()
52
+ if (!this._stage) this._build()
46
53
  void this._load()
47
54
  }
48
55
 
49
56
  disconnectedCallback() {
50
57
  this._ro?.disconnect()
51
58
  this._ro = null
52
- if (this._decoded) revokeAssets(this._decoded.assetMap)
53
- this._decoded = null
54
59
  }
55
60
 
56
61
  attributeChangedCallback(name: string) {
57
- if (name === 'src' && this._canvas) void this._load()
62
+ if (name === 'src' && this._stage) void this._load()
63
+ }
64
+
65
+ /** The `<gui-canvas>` drawing the file. */
66
+ get canvas(): GuiCanvas {
67
+ return this._canvas
58
68
  }
59
69
 
60
70
  // ── DOM scaffold ──────────────────────────────────────────────────────────
@@ -65,13 +75,13 @@ export class GuiEmbedElement extends HTMLElement {
65
75
  if (cs.display === 'inline') this.style.display = 'block'
66
76
  this.style.overflow = 'hidden'
67
77
 
68
- const canvas = document.createElement('div')
69
- canvas.className = 'gui-embed-canvas'
70
- // The dot grid is the CANVAS, not the file — it signals "this is rendered in
78
+ const stage = document.createElement('div')
79
+ stage.className = 'gui-embed-canvas'
80
+ // The dot grid is the STAGE, not the file — it signals "this is rendered in
71
81
  // a dotgui surface" and stays behind the file. Toggle with `grid="false"`.
72
82
  const dots = this.getAttribute('grid') !== 'false'
73
- canvas.style.cssText = [
74
- 'position:absolute;inset:0',
83
+ stage.style.cssText = [
84
+ 'position:absolute;inset:0;touch-action:none',
75
85
  'background-color:var(--gui-embed-bg, #fafaf8)',
76
86
  dots
77
87
  ? 'background-image:radial-gradient(var(--gui-embed-dot, rgba(0,0,0,.14)) 1px, transparent 1.4px);background-size:var(--gui-embed-dot-gap, 18px) var(--gui-embed-dot-gap, 18px);background-position:center'
@@ -79,17 +89,27 @@ export class GuiEmbedElement extends HTMLElement {
79
89
  ]
80
90
  .filter(Boolean)
81
91
  .join(';')
82
- this.appendChild(canvas)
92
+ this.appendChild(stage)
93
+ this._stage = stage
94
+
95
+ const view = document.createElement('div')
96
+ // max-content: the canvas keeps its document size here, and the view scales it.
97
+ view.style.cssText = 'position:absolute;left:0;top:0;width:max-content;transform-origin:0 0'
98
+ stage.appendChild(view)
99
+ this._view = view
100
+
101
+ const canvas = document.createElement('gui-canvas') as GuiCanvas
102
+ canvas.addEventListener('render', (event) => this._rendered((event as CustomEvent<RenderDetail>).detail))
103
+ canvas.addEventListener('error', (event) => this._fail((event as CustomEvent<{ message: string }>).detail.message))
104
+ view.appendChild(canvas)
83
105
  this._canvas = canvas
84
106
 
85
- // A pan/zoom canvas fits its content to the container size. When the
86
- // container resizes (responsive width, async aspect-ratio, font reflow),
87
- // refit — unless the user has taken over the viewport.
88
- const markUser = () => (this._userZoomed = true)
89
- canvas.addEventListener('wheel', markUser, { passive: true })
90
- canvas.addEventListener('pointerdown', markUser)
107
+ this._bindZoom()
108
+
109
+ // When the container resizes (responsive width, async aspect-ratio), refit —
110
+ // unless the user has taken over the viewport.
91
111
  this._ro = new ResizeObserver(() => {
92
- if (!this._userZoomed) this._zoomCtl?.(1)
112
+ if (!this._userZoomed) this.fit()
93
113
  })
94
114
  this._ro.observe(this)
95
115
 
@@ -111,75 +131,151 @@ export class GuiEmbedElement extends HTMLElement {
111
131
  // ── load + render ───────────────────────────────────────────────────────────
112
132
 
113
133
  private async _load() {
134
+ this._size = null
135
+ this._userZoomed = false
136
+ this._canvas.mode = {}
114
137
  try {
115
- let decoded: Decoded
116
138
  const src = this.getAttribute('src')
117
139
  if (src) {
118
- decoded = await fetchGui(src)
140
+ const response = await fetch(src)
141
+ if (!response.ok) throw new Error(`gui-embed: failed to fetch "${src}" (${response.status})`)
142
+ this._bytes = new Uint8Array(await response.arrayBuffer())
143
+ this._markup = ''
144
+ await this._canvas.loadBytes(this._bytes)
119
145
  } else {
120
146
  // Inline content lives in a <script type="application/gui"> child — raw
121
147
  // text the HTML parser never mangles (so `<col>`/`<img>` survive).
122
148
  const script = this.querySelector(':scope > script[type="application/gui"]')
123
- if (!script) return
124
- decoded = decodeMarkup(script.textContent ?? '')
149
+ if (!script) {
150
+ // The CDN script defines this element before the parser has reached
151
+ // its children: look again once the document is parsed.
152
+ if (document.readyState === 'loading') {
153
+ document.addEventListener('DOMContentLoaded', () => void this._load(), { once: true })
154
+ }
155
+ return
156
+ }
157
+ this._bytes = null
158
+ this._markup = script.textContent ?? ''
159
+ await this._canvas.loadMarkup(this._markup)
125
160
  }
126
-
127
- if (this._decoded) revokeAssets(this._decoded.assetMap)
128
- this._decoded = decoded
129
- this._userZoomed = false
130
-
131
- this._modes = detectModes(decoded.xml)
132
- this._mode = {}
133
- for (const [axis, ax] of Object.entries(this._modes)) this._mode[axis] = ax.default
134
-
135
- this._render()
136
161
  this._buildControls()
137
162
  } catch (err) {
138
- this._canvas.textContent = String((err as Error)?.message ?? err)
139
- this._canvas.style.cssText +=
140
- ';display:flex;align-items:center;justify-content:center;font:13px system-ui;color:#c00;padding:12px;text-align:center'
163
+ this._fail(String((err as Error)?.message ?? err))
141
164
  }
142
165
  }
143
166
 
144
- private _render() {
145
- if (!this._decoded) return
146
- const { xml, assetMap } = this._decoded
147
- const interactive = this.getAttribute('zoom') !== 'false' // default on
167
+ private _fail(message: string) {
168
+ let note = this.querySelector(':scope > .gui-embed-error') as HTMLDivElement | null
169
+ if (!note) {
170
+ note = document.createElement('div')
171
+ note.className = 'gui-embed-error'
172
+ note.style.cssText =
173
+ 'position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font:13px system-ui;color:#c00;padding:12px;text-align:center'
174
+ this.appendChild(note)
175
+ }
176
+ note.textContent = message
177
+ }
148
178
 
149
- // The pan/zoom canvas fits content to the container, so it MUST render into a
150
- // sized box — fitting against a zero-height container produces a broken
151
- // transform that a later refit can't recover. When the author only fixed a
152
- // width, do a cheap native-size pass first to learn the ratio, set the
153
- // aspect-ratio (giving the canvas a real height), then render the zoom canvas.
179
+ /** A frame arrived: size the host on the first, and keep the view fitted. */
180
+ private _rendered(detail: RenderDetail) {
181
+ this.querySelector(':scope > .gui-embed-error')?.remove()
182
+ const first = !this._size || this._size.width !== detail.width || this._size.height !== detail.height
183
+ this._size = { width: detail.width, height: detail.height }
184
+ if (!first) return
154
185
  if (!this._hasHeight()) {
155
- render(xml, this._canvas, assetMap, { mode: this._mode }) // native size, no zoom
156
- const screen = this._canvas.querySelector('.gui-relative') as HTMLElement | null
157
- const w = screen?.offsetWidth ?? 0
158
- const h = screen?.offsetHeight ?? 0
159
- if (w > 0 && h > 0) {
160
- if (this.style.width) {
161
- // Author fixed a width → derive height from the file's ratio.
162
- this.style.aspectRatio = `${w} / ${h}`
163
- } else {
164
- // No CSS size at all → size to the file's native dimensions, like an SVG.
165
- this.style.width = `${w}px`
166
- this.style.height = `${h}px`
167
- }
186
+ if (this.style.width) {
187
+ // Author fixed a width → derive height from the file's ratio.
188
+ this.style.aspectRatio = `${detail.width} / ${detail.height}`
189
+ } else {
190
+ // No CSS size at all → size to the file's native dimensions, like an SVG.
191
+ this.style.width = `${detail.width}px`
192
+ this.style.height = `${detail.height}px`
168
193
  }
169
- requestAnimationFrame(() => {
170
- this._zoomCtl = render(xml, this._canvas, assetMap, { zoom: interactive, mode: this._mode })
171
- })
172
- return
173
194
  }
174
-
175
- this._zoomCtl = render(xml, this._canvas, assetMap, { zoom: interactive, mode: this._mode })
195
+ if (!this._userZoomed) this.fit()
176
196
  }
177
197
 
178
- /** Whether the canvas already has a usable height (fixed by CSS or aspect-ratio). */
198
+ /** Whether the host already has a usable height (fixed by CSS or aspect-ratio). */
179
199
  private _hasHeight(): boolean {
180
200
  if (this.style.height || this.style.aspectRatio) return true
181
- const h = getComputedStyle(this).height
182
- return !!h && h !== 'auto' && parseFloat(h) > 1
201
+ const cs = getComputedStyle(this)
202
+ if (cs.aspectRatio && cs.aspectRatio !== 'auto') return true
203
+ return this.clientHeight > 1
204
+ }
205
+
206
+ // ── pan + zoom ──────────────────────────────────────────────────────────────
207
+
208
+ /** Places the document center-center, scaled to fit, and hands the view back to auto-fit. */
209
+ fit() {
210
+ if (!this._size) return
211
+ const { width, height } = this._size
212
+ const box = this._stage.getBoundingClientRect()
213
+ if (box.width < 1 || box.height < 1) return
214
+ this._scale = Math.min(box.width / width, box.height / height)
215
+ this._x = (box.width - width * this._scale) / 2
216
+ this._y = (box.height - height * this._scale) / 2
217
+ this._userZoomed = false
218
+ this._apply()
219
+ }
220
+
221
+ /** Zooms by `factor` about a point in the stage (its center by default). */
222
+ zoomBy(factor: number, anchorX?: number, anchorY?: number) {
223
+ if (!this._size) return
224
+ const box = this._stage.getBoundingClientRect()
225
+ const fitted = Math.min(box.width / this._size.width, box.height / this._size.height)
226
+ const next = Math.min(Math.max(this._scale * factor, fitted * MIN_ZOOM), fitted * MAX_ZOOM)
227
+ const ax = anchorX ?? box.width / 2
228
+ const ay = anchorY ?? box.height / 2
229
+ this._x = ax - ((ax - this._x) * next) / this._scale
230
+ this._y = ay - ((ay - this._y) * next) / this._scale
231
+ this._scale = next
232
+ this._userZoomed = true
233
+ this._apply()
234
+ }
235
+
236
+ private _apply() {
237
+ this._view.style.transform = `translate(${this._x}px, ${this._y}px) scale(${this._scale})`
238
+ // Draw sharp at the zoom the view settles on, not at every wheel tick.
239
+ if (this._settle) clearTimeout(this._settle)
240
+ this._settle = setTimeout(() => {
241
+ const density = Math.min(Math.max(2, Math.ceil((window.devicePixelRatio || 1) * this._scale)), 4)
242
+ if (Number(this._canvas.getAttribute('density')) !== density) this._canvas.setAttribute('density', String(density))
243
+ }, 150)
244
+ }
245
+
246
+ private _bindZoom() {
247
+ const stage = this._stage
248
+ const enabled = () => this.getAttribute('zoom') !== 'false'
249
+ stage.addEventListener(
250
+ 'wheel',
251
+ (event) => {
252
+ // Pinch on a trackpad and ctrl/⌘ + wheel zoom; a plain wheel scrolls the page.
253
+ if (!enabled() || !(event.ctrlKey || event.metaKey)) return
254
+ event.preventDefault()
255
+ const box = stage.getBoundingClientRect()
256
+ this.zoomBy(Math.exp(-event.deltaY * 0.01), event.clientX - box.left, event.clientY - box.top)
257
+ },
258
+ { passive: false },
259
+ )
260
+ let drag: { id: number; x: number; y: number } | null = null
261
+ stage.addEventListener('pointerdown', (event) => {
262
+ if (!enabled() || event.button !== 0) return
263
+ drag = { id: event.pointerId, x: event.clientX, y: event.clientY }
264
+ stage.setPointerCapture(event.pointerId)
265
+ })
266
+ stage.addEventListener('pointermove', (event) => {
267
+ if (!drag || drag.id !== event.pointerId) return
268
+ this._x += event.clientX - drag.x
269
+ this._y += event.clientY - drag.y
270
+ drag.x = event.clientX
271
+ drag.y = event.clientY
272
+ this._userZoomed = true
273
+ this._view.style.transform = `translate(${this._x}px, ${this._y}px) scale(${this._scale})`
274
+ })
275
+ const end = () => (drag = null)
276
+ stage.addEventListener('pointerup', end)
277
+ stage.addEventListener('pointercancel', end)
278
+ stage.addEventListener('dblclick', () => enabled() && this.fit())
183
279
  }
184
280
 
185
281
  // ── controls ────────────────────────────────────────────────────────────────
@@ -189,18 +285,19 @@ export class GuiEmbedElement extends HTMLElement {
189
285
  bar.innerHTML = ''
190
286
 
191
287
  if (this.getAttribute('zoom') !== 'false') {
192
- bar.appendChild(this._btn('Fit', 'Reset zoom', () => this._zoomCtl?.(1)))
288
+ bar.appendChild(this._btn('Fit', 'Reset zoom', () => this.fit()))
193
289
  }
194
290
 
195
- const axes = switchableAxes(this._modes)
291
+ const modes = this._canvas.modes
292
+ const axes = Object.keys(modes).filter((axis) => modes[axis].values.length > 1)
196
293
  if (this.hasAttribute('mode-switch') && axes.length) {
197
- for (const axis of axes) bar.appendChild(this._modeSelect(axis))
294
+ for (const axis of axes) bar.appendChild(this._modeSelect(axis, modes[axis]))
198
295
  }
199
296
 
200
297
  if (this.hasAttribute('copy')) {
201
298
  bar.appendChild(
202
299
  this._btn('Copy', 'Copy .gui markup', async () => {
203
- if (this._decoded) await navigator.clipboard.writeText(this._decoded.xml)
300
+ await navigator.clipboard.writeText(this._canvas.source)
204
301
  }),
205
302
  )
206
303
  }
@@ -217,41 +314,33 @@ export class GuiEmbedElement extends HTMLElement {
217
314
  b.type = 'button'
218
315
  b.textContent = label
219
316
  b.title = title
220
- b.style.cssText = [
221
- 'all:unset;cursor:pointer;font:600 12px/1 system-ui',
222
- 'color:#fff;padding:6px 9px;border-radius:5px',
223
- ].join(';')
317
+ b.style.cssText = ['all:unset;cursor:pointer;font:600 12px/1 system-ui', 'color:#fff;padding:6px 9px;border-radius:5px'].join(';')
224
318
  b.addEventListener('pointerenter', () => (b.style.background = 'rgba(255,255,255,.18)'))
225
319
  b.addEventListener('pointerleave', () => (b.style.background = 'transparent'))
226
320
  b.addEventListener('click', onClick)
227
321
  return b
228
322
  }
229
323
 
230
- private _modeSelect(axis: string): HTMLSelectElement {
324
+ private _modeSelect(axis: string, mode: ModeAxis): HTMLSelectElement {
231
325
  const sel = document.createElement('select')
232
326
  sel.title = `Mode: ${axis}`
233
- sel.style.cssText = [
234
- 'all:unset;cursor:pointer;font:600 12px/1 system-ui',
235
- 'color:#fff;padding:6px 9px;border-radius:5px',
236
- ].join(';')
237
- for (const value of this._modes[axis].values) {
327
+ sel.style.cssText = ['all:unset;cursor:pointer;font:600 12px/1 system-ui', 'color:#fff;padding:6px 9px;border-radius:5px'].join(';')
328
+ const current = this._canvas.mode[axis] ?? mode.default
329
+ for (const value of mode.values) {
238
330
  const opt = document.createElement('option')
239
331
  opt.value = value
240
332
  opt.textContent = value
241
333
  opt.style.color = '#000'
242
- if (value === this._mode[axis]) opt.selected = true
334
+ if (value === current) opt.selected = true
243
335
  sel.appendChild(opt)
244
336
  }
245
- sel.addEventListener('change', () => {
246
- this._mode[axis] = sel.value
247
- this._render() // re-render the active mode; renderer switches via tokens
248
- })
337
+ // The renderer switches via tokens; the markup is unchanged.
338
+ sel.addEventListener('change', () => this._canvas.setMode(axis, sel.value))
249
339
  return sel
250
340
  }
251
341
 
252
342
  private _download() {
253
- if (!this._decoded) return
254
- const bytes = toGuiBytes(this._decoded.pkg)
343
+ const bytes = this._bytes ?? pack({ xml: this._markup, assets: {} })
255
344
  const name = (this.getAttribute('src')?.split('/').pop() || 'design.gui').replace(/\.guix$/, '.gui')
256
345
  const url = URL.createObjectURL(new Blob([bytes as unknown as BlobPart], { type: 'application/octet-stream' }))
257
346
  const a = document.createElement('a')
package/src/index.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * @dotgui/embed — render .gui files anywhere in the browser.
3
3
  *
4
- * A thin layer over @dotgui/kit's renderer. One element:
4
+ * A thin player over `@dotgui/render`'s `<gui-canvas>`: the Rust renderer,
5
+ * compiled to WebAssembly. One element:
5
6
  *
6
7
  * <gui-embed src="x.gui"></gui-embed> external file
7
8
  * <gui-embed> inline file (parser-safe)
@@ -14,15 +15,16 @@
14
15
  * The CDN build (`gui-embed.js`) calls `install()` automatically. When importing
15
16
  * as a module, call `install()` (or `defineGuiEmbed()`) yourself.
16
17
  */
17
- export { GuiEmbedElement, defineGuiEmbed } from './gui-embed'
18
- export { fetchGui, decodeBytes, decodeMarkup, type Decoded } from './decode'
19
- export { detectModes, switchableAxes, type ModeAxis } from './modes'
20
-
18
+ import '@dotgui/render/canvas'
21
19
  import { defineGuiEmbed } from './gui-embed'
22
20
 
21
+ export { GuiEmbedElement, defineGuiEmbed } from './gui-embed'
22
+ export { GuiCanvas, config } from '@dotgui/render/canvas'
23
+ export type { ModeAxis, GuiPage, RenderDetail } from '@dotgui/render/canvas'
24
+
23
25
  let installed = false
24
26
 
25
- /** Register the `<gui-embed>` custom element. Idempotent. */
27
+ /** Register the `<gui-embed>` custom element (and `<gui-canvas>`). Idempotent. */
26
28
  export function install() {
27
29
  if (installed || typeof window === 'undefined') return
28
30
  installed = true
package/src/decode.ts DELETED
@@ -1,60 +0,0 @@
1
- /**
2
- * Decode .gui / .guix bytes into renderable input.
3
- *
4
- * The kit owns unzip + .guix/assets discovery (`unpack`); here we only turn the
5
- * decoded asset bytes into browser `blob:` URLs the renderer can resolve. This
6
- * mirrors the playground / gui-app decode path so rendering behaves identically.
7
- */
8
- import { unpack, pack, type GuiPackage } from '@dotgui/kit/package'
9
-
10
- export interface Decoded {
11
- /** The .guix markup (XML, `<gui>` root). */
12
- xml: string
13
- /** assetMap keyed by package path, e.g. "assets/hero.webp" -> blob: URL. */
14
- assetMap: Record<string, string>
15
- /** The in-memory package (used for download). */
16
- pkg: GuiPackage
17
- }
18
-
19
- function mimeForExt(ext: string): string {
20
- if (ext === 'svg') return 'image/svg+xml'
21
- if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg'
22
- return `image/${ext}`
23
- }
24
-
25
- /** Decode raw .gui (ZIP) or .guix (XML) bytes into xml + a blob: asset map. */
26
- export function decodeBytes(bytes: Uint8Array): Decoded {
27
- const pkg = unpack(bytes)
28
- const assetMap: Record<string, string> = {}
29
- for (const [name, fileBytes] of Object.entries(pkg.assets)) {
30
- const ext = name.split('.').pop() || 'png'
31
- const blob = new Blob([fileBytes as unknown as BlobPart], { type: mimeForExt(ext) })
32
- assetMap[name] = URL.createObjectURL(blob)
33
- }
34
- return { xml: pkg.xml, assetMap, pkg }
35
- }
36
-
37
- /** Build a Decoded from inline .guix markup (no assets). */
38
- export function decodeMarkup(xml: string): Decoded {
39
- return { xml, assetMap: {}, pkg: { xml, assets: {} } }
40
- }
41
-
42
- /** Fetch a .gui / .guix from a URL and decode it. */
43
- export async function fetchGui(src: string): Promise<Decoded> {
44
- const res = await fetch(src)
45
- if (!res.ok) throw new Error(`gui-embed: failed to fetch "${src}" (${res.status})`)
46
- const buf = new Uint8Array(await res.arrayBuffer())
47
- return decodeBytes(buf)
48
- }
49
-
50
- /** Re-pack a decoded package into .gui (ZIP) bytes for download. */
51
- export function toGuiBytes(pkg: GuiPackage): Uint8Array {
52
- return pack(pkg)
53
- }
54
-
55
- /** Release any blob: URLs created for an asset map. */
56
- export function revokeAssets(assetMap: Record<string, string>) {
57
- for (const url of Object.values(assetMap)) {
58
- if (url.startsWith('blob:')) URL.revokeObjectURL(url)
59
- }
60
- }
package/src/modes.ts DELETED
@@ -1,26 +0,0 @@
1
- /**
2
- * Mode detection — reuse the kit parser so the embed knows exactly which token
3
- * mode axes (RFC-0037) a file declares. Drives the optional mode switcher: it
4
- * only renders when an axis has more than one value.
5
- */
6
- import { parseXml } from '@dotgui/kit/parser'
7
-
8
- export interface ModeAxis {
9
- values: string[]
10
- default: string
11
- }
12
-
13
- /** Declared mode axes for a .guix string, keyed by axis name. Empty when none. */
14
- export function detectModes(xml: string): Record<string, ModeAxis> {
15
- try {
16
- const parsed = parseXml(xml)
17
- return parsed?.modes ?? {}
18
- } catch {
19
- return {}
20
- }
21
- }
22
-
23
- /** Axes worth showing a switcher for (more than one value). */
24
- export function switchableAxes(modes: Record<string, ModeAxis>): string[] {
25
- return Object.keys(modes).filter((axis) => modes[axis].values.length > 1)
26
- }