@dotgui/embed 0.1.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/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@dotgui/embed",
3
+ "version": "0.1.0",
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.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/gui-embed.esm.js",
8
+ "module": "./dist/gui-embed.esm.js",
9
+ "types": "./src/index.ts",
10
+ "unpkg": "./dist/gui-embed.js",
11
+ "jsdelivr": "./dist/gui-embed.js",
12
+ "exports": {
13
+ ".": "./src/index.ts"
14
+ },
15
+ "files": ["dist/", "src/", "README.md"],
16
+ "scripts": {
17
+ "build": "bun run build:cdn && bun run build:esm",
18
+ "build:cdn": "bun build ./src/auto.ts --outfile ./dist/gui-embed.js --format iife --minify",
19
+ "build:esm": "bun build ./src/index.ts --outfile ./dist/gui-embed.esm.js --format esm --minify",
20
+ "typecheck": "tsc --noEmit"
21
+ },
22
+ "keywords": ["dotgui", "gui", "embed", "web-component", "cdn", "renderer"],
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/dotgui/embed"
26
+ },
27
+ "dependencies": {
28
+ "@dotgui/kit": "^0.1.0"
29
+ },
30
+ "devDependencies": {
31
+ "bun-types": "latest",
32
+ "typescript": "^5.0.0"
33
+ }
34
+ }
package/src/auto.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * CDN entry — side-effecting. Loading this script auto-registers everything:
3
+ *
4
+ * <script src="https://cdn.dotgui.com/gui-embed.js"></script>
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).
8
+ */
9
+ import * as embed from './index'
10
+
11
+ embed.install()
12
+
13
+ // Expose the API on a global for non-module pages (and the prototype demo).
14
+ ;(globalThis as unknown as { GuiEmbed?: typeof embed }).GuiEmbed = embed
package/src/decode.ts ADDED
@@ -0,0 +1,60 @@
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
+ }
@@ -0,0 +1,269 @@
1
+ /**
2
+ * `<gui-embed>` — the host/player around a .gui file.
3
+ *
4
+ * It is NOT the format. The format vocabulary (`w`/`h` = the file's own size)
5
+ * lives on `<gui>`. Everything here is host vocabulary, expressed in CSS:
6
+ *
7
+ * <gui-embed style="width:100vw;height:100vh" zoom download copy mode-switch>
8
+ * <gui w="300" h="300"> … </gui>
9
+ * </gui-embed>
10
+ *
11
+ * <gui-embed src="hero.gui" style="width:400px;aspect-ratio:auto"></gui-embed>
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.
16
+ */
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'
26
+
27
+ const TAG = 'gui-embed'
28
+
29
+ export class GuiEmbedElement extends HTMLElement {
30
+ private _canvas!: HTMLDivElement
31
+ 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
+ private _ro: ResizeObserver | null = null
37
+ /** True once the user pans/zooms — stops auto-fit from snapping their view back. */
38
+ private _userZoomed = false
39
+
40
+ static get observedAttributes() {
41
+ return ['src']
42
+ }
43
+
44
+ connectedCallback() {
45
+ if (!this._canvas) this._build()
46
+ void this._load()
47
+ }
48
+
49
+ disconnectedCallback() {
50
+ this._ro?.disconnect()
51
+ this._ro = null
52
+ if (this._decoded) revokeAssets(this._decoded.assetMap)
53
+ this._decoded = null
54
+ }
55
+
56
+ attributeChangedCallback(name: string) {
57
+ if (name === 'src' && this._canvas) void this._load()
58
+ }
59
+
60
+ // ── DOM scaffold ──────────────────────────────────────────────────────────
61
+
62
+ private _build() {
63
+ const cs = getComputedStyle(this)
64
+ if (cs.position === 'static') this.style.position = 'relative'
65
+ if (cs.display === 'inline') this.style.display = 'block'
66
+ this.style.overflow = 'hidden'
67
+
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
71
+ // a dotgui surface" and stays behind the file. Toggle with `grid="false"`.
72
+ const dots = this.getAttribute('grid') !== 'false'
73
+ canvas.style.cssText = [
74
+ 'position:absolute;inset:0',
75
+ 'background-color:var(--gui-embed-bg, #fafaf8)',
76
+ dots
77
+ ? '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'
78
+ : '',
79
+ ]
80
+ .filter(Boolean)
81
+ .join(';')
82
+ this.appendChild(canvas)
83
+ this._canvas = canvas
84
+
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)
91
+ this._ro = new ResizeObserver(() => {
92
+ if (!this._userZoomed) this._zoomCtl?.(1)
93
+ })
94
+ this._ro.observe(this)
95
+
96
+ const bar = document.createElement('div')
97
+ bar.className = 'gui-embed-controls'
98
+ bar.style.cssText = [
99
+ 'position:absolute;top:8px;right:8px;z-index:2',
100
+ 'display:flex;gap:4px;padding:4px',
101
+ 'border-radius:8px;background:rgba(20,20,20,.55)',
102
+ 'backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)',
103
+ 'opacity:0;transition:opacity .15s ease',
104
+ ].join(';')
105
+ this.appendChild(bar)
106
+ this._bar = bar
107
+ this.addEventListener('pointerenter', () => (bar.style.opacity = '1'))
108
+ this.addEventListener('pointerleave', () => (bar.style.opacity = '0'))
109
+ }
110
+
111
+ // ── load + render ───────────────────────────────────────────────────────────
112
+
113
+ private async _load() {
114
+ try {
115
+ let decoded: Decoded
116
+ const src = this.getAttribute('src')
117
+ if (src) {
118
+ decoded = await fetchGui(src)
119
+ } else {
120
+ // Inline content lives in a <script type="application/gui"> child — raw
121
+ // text the HTML parser never mangles (so `<col>`/`<img>` survive).
122
+ const script = this.querySelector(':scope > script[type="application/gui"]')
123
+ if (!script) return
124
+ decoded = decodeMarkup(script.textContent ?? '')
125
+ }
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
+ this._buildControls()
137
+ } 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'
141
+ }
142
+ }
143
+
144
+ private _render() {
145
+ if (!this._decoded) return
146
+ const { xml, assetMap } = this._decoded
147
+ const interactive = this.getAttribute('zoom') !== 'false' // default on
148
+
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.
154
+ 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
+ }
168
+ }
169
+ requestAnimationFrame(() => {
170
+ this._zoomCtl = render(xml, this._canvas, assetMap, { zoom: interactive, mode: this._mode })
171
+ })
172
+ return
173
+ }
174
+
175
+ this._zoomCtl = render(xml, this._canvas, assetMap, { zoom: interactive, mode: this._mode })
176
+ }
177
+
178
+ /** Whether the canvas already has a usable height (fixed by CSS or aspect-ratio). */
179
+ private _hasHeight(): boolean {
180
+ if (this.style.height || this.style.aspectRatio) return true
181
+ const h = getComputedStyle(this).height
182
+ return !!h && h !== 'auto' && parseFloat(h) > 1
183
+ }
184
+
185
+ // ── controls ────────────────────────────────────────────────────────────────
186
+
187
+ private _buildControls() {
188
+ const bar = this._bar
189
+ bar.innerHTML = ''
190
+
191
+ if (this.getAttribute('zoom') !== 'false') {
192
+ bar.appendChild(this._btn('Fit', 'Reset zoom', () => this._zoomCtl?.(1)))
193
+ }
194
+
195
+ const axes = switchableAxes(this._modes)
196
+ if (this.hasAttribute('mode-switch') && axes.length) {
197
+ for (const axis of axes) bar.appendChild(this._modeSelect(axis))
198
+ }
199
+
200
+ if (this.hasAttribute('copy')) {
201
+ bar.appendChild(
202
+ this._btn('Copy', 'Copy .gui markup', async () => {
203
+ if (this._decoded) await navigator.clipboard.writeText(this._decoded.xml)
204
+ }),
205
+ )
206
+ }
207
+
208
+ if (this.hasAttribute('download')) {
209
+ bar.appendChild(this._btn('Download', 'Download .gui file', () => this._download()))
210
+ }
211
+
212
+ bar.style.display = bar.children.length ? 'flex' : 'none'
213
+ }
214
+
215
+ private _btn(label: string, title: string, onClick: () => void): HTMLButtonElement {
216
+ const b = document.createElement('button')
217
+ b.type = 'button'
218
+ b.textContent = label
219
+ 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(';')
224
+ b.addEventListener('pointerenter', () => (b.style.background = 'rgba(255,255,255,.18)'))
225
+ b.addEventListener('pointerleave', () => (b.style.background = 'transparent'))
226
+ b.addEventListener('click', onClick)
227
+ return b
228
+ }
229
+
230
+ private _modeSelect(axis: string): HTMLSelectElement {
231
+ const sel = document.createElement('select')
232
+ 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) {
238
+ const opt = document.createElement('option')
239
+ opt.value = value
240
+ opt.textContent = value
241
+ opt.style.color = '#000'
242
+ if (value === this._mode[axis]) opt.selected = true
243
+ sel.appendChild(opt)
244
+ }
245
+ sel.addEventListener('change', () => {
246
+ this._mode[axis] = sel.value
247
+ this._render() // re-render the active mode; renderer switches via tokens
248
+ })
249
+ return sel
250
+ }
251
+
252
+ private _download() {
253
+ if (!this._decoded) return
254
+ const bytes = toGuiBytes(this._decoded.pkg)
255
+ const name = (this.getAttribute('src')?.split('/').pop() || 'design.gui').replace(/\.guix$/, '.gui')
256
+ const url = URL.createObjectURL(new Blob([bytes as unknown as BlobPart], { type: 'application/octet-stream' }))
257
+ const a = document.createElement('a')
258
+ a.href = url
259
+ a.download = name.endsWith('.gui') ? name : name + '.gui'
260
+ a.click()
261
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
262
+ }
263
+ }
264
+
265
+ export function defineGuiEmbed() {
266
+ if (typeof customElements !== 'undefined' && !customElements.get(TAG)) {
267
+ customElements.define(TAG, GuiEmbedElement)
268
+ }
269
+ }
package/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @dotgui/embed — render .gui files anywhere in the browser.
3
+ *
4
+ * A thin layer over @dotgui/kit's renderer. One element:
5
+ *
6
+ * <gui-embed src="x.gui"></gui-embed> external file
7
+ * <gui-embed> inline file (parser-safe)
8
+ * <script type="application/gui"> … </script>
9
+ * </gui-embed>
10
+ *
11
+ * No chrome by default (a clean standalone render). Add booleans for the widget:
12
+ * `zoom` `download` `copy` `mode-switch` `grid`. Size with CSS.
13
+ *
14
+ * The CDN build (`gui-embed.js`) calls `install()` automatically. When importing
15
+ * as a module, call `install()` (or `defineGuiEmbed()`) yourself.
16
+ */
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
+
21
+ import { defineGuiEmbed } from './gui-embed'
22
+
23
+ let installed = false
24
+
25
+ /** Register the `<gui-embed>` custom element. Idempotent. */
26
+ export function install() {
27
+ if (installed || typeof window === 'undefined') return
28
+ installed = true
29
+ defineGuiEmbed()
30
+ }
package/src/modes.ts ADDED
@@ -0,0 +1,26 @@
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
+ }