@stacksjs/components 0.2.919 → 0.2.921

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,145 @@
1
+ // src/ui/render-surface/render-surface.ts
2
+ var RENDER_SURFACE_MAX_SIDE = 8192;
3
+ var root = globalThis;
4
+ function canvases() {
5
+ root.__stxRenderSurfaces ??= new Map;
6
+ return root.__stxRenderSurfaces;
7
+ }
8
+ function surfaceError(code, message) {
9
+ return Object.assign(new Error(message), { code });
10
+ }
11
+ function onNativeScreen() {
12
+ return Boolean(root.stx?._host?.isNative);
13
+ }
14
+ function renderSurfaceHost() {
15
+ if (onNativeScreen()) {
16
+ const present = root.craft?.renderSurface?.present;
17
+ return typeof present === "function" && root.craft?.capabilities?.renderSurface === true ? "native" : "none";
18
+ }
19
+ if (typeof document === "undefined")
20
+ return "none";
21
+ return "canvas";
22
+ }
23
+ function checkFrame(surface, pixels, width, height) {
24
+ if (typeof surface !== "string" || !surface)
25
+ throw new TypeError("presentFrame needs the surface's name");
26
+ if (!(pixels instanceof Uint32Array))
27
+ throw new TypeError("presentFrame takes a Uint32Array of 0xAARRGGBB words");
28
+ for (const [side, value] of [["width", width], ["height", height]]) {
29
+ if (!Number.isInteger(value) || value < 1 || value > RENDER_SURFACE_MAX_SIDE)
30
+ throw new TypeError(`presentFrame's ${side} must be a whole number from 1 to ${RENDER_SURFACE_MAX_SIDE}, not ${value}`);
31
+ }
32
+ if (pixels.length !== width * height)
33
+ throw new TypeError(`presentFrame was given ${pixels.length} words for a ${width} x ${height} frame (${width * height})`);
34
+ }
35
+ function presentFrame(surface, pixels, width, height) {
36
+ if (onNativeScreen()) {
37
+ const host = root.craft?.renderSurface;
38
+ if (!host || typeof host.present !== "function")
39
+ throw surfaceError("UNAVAILABLE", "This device cannot draw a RenderSurface");
40
+ return host.present(surface, pixels, width, height);
41
+ }
42
+ checkFrame(surface, pixels, width, height);
43
+ const target = canvases().get(surface);
44
+ if (!target)
45
+ throw surfaceError("NOT_FOUND", `No RenderSurface named "${surface}" is on the page`);
46
+ drawToCanvas(target, pixels, width, height);
47
+ return true;
48
+ }
49
+ function drawToCanvas(target, pixels, width, height) {
50
+ const { canvas, context, opaque } = target;
51
+ if (canvas.width !== width)
52
+ canvas.width = width;
53
+ if (canvas.height !== height)
54
+ canvas.height = height;
55
+ if (!target.image || target.image.width !== width || target.image.height !== height)
56
+ target.image = context.createImageData(width, height);
57
+ const bytes = target.image.data;
58
+ for (let i = 0, j = 0;i < pixels.length; i++, j += 4) {
59
+ const word = pixels[i];
60
+ let a = word >>> 24;
61
+ let r = word >>> 16 & 255;
62
+ let g = word >>> 8 & 255;
63
+ let b = word & 255;
64
+ if (opaque) {
65
+ a = 255;
66
+ } else if (a > 0 && a < 255) {
67
+ r = Math.min(255, Math.round(r * 255 / a));
68
+ g = Math.min(255, Math.round(g * 255 / a));
69
+ b = Math.min(255, Math.round(b * 255 / a));
70
+ }
71
+ bytes[j] = r;
72
+ bytes[j + 1] = g;
73
+ bytes[j + 2] = b;
74
+ bytes[j + 3] = a;
75
+ }
76
+ context.putImageData(target.image, 0, 0);
77
+ }
78
+ function claimCanvasSurface(surface, canvas, options = {}) {
79
+ if (canvases().has(surface))
80
+ return { error: { surface, code: "DUPLICATE", message: `Another RenderSurface named "${surface}" is already on the page` } };
81
+ let context = null;
82
+ try {
83
+ context = canvas.getContext("2d", { alpha: options.opaque === false });
84
+ } catch {
85
+ context = null;
86
+ }
87
+ if (!context)
88
+ return { error: { surface, code: "UNAVAILABLE", message: "This browser cannot draw a RenderSurface: it has no 2D canvas" } };
89
+ const entry = { canvas, context, opaque: options.opaque !== false, image: null };
90
+ canvases().set(surface, entry);
91
+ return {
92
+ release: () => {
93
+ if (canvases().get(surface) === entry)
94
+ canvases().delete(surface);
95
+ }
96
+ };
97
+ }
98
+ function startRenderLoop(surface, draw, options = {}) {
99
+ const frame = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (callback) => setTimeout(() => callback(Date.now()), 16);
100
+ let ended = false;
101
+ let waiting = false;
102
+ const tick = (time) => {
103
+ if (ended)
104
+ return;
105
+ if (!waiting) {
106
+ try {
107
+ const next = draw(time);
108
+ if (next && !presentFrame(surface, next.pixels, next.width, next.height))
109
+ waiting = true;
110
+ } catch (error) {
111
+ ended = true;
112
+ if (error?.code === "NOT_FOUND")
113
+ return;
114
+ if (options.onError)
115
+ options.onError(error);
116
+ else
117
+ throw error;
118
+ return;
119
+ }
120
+ }
121
+ frame(tick);
122
+ };
123
+ frame(tick);
124
+ return {
125
+ stop: () => {
126
+ ended = true;
127
+ },
128
+ wake: () => {
129
+ waiting = false;
130
+ },
131
+ get waiting() {
132
+ return waiting;
133
+ },
134
+ get ended() {
135
+ return ended;
136
+ }
137
+ };
138
+ }
139
+ export {
140
+ RENDER_SURFACE_MAX_SIDE,
141
+ claimCanvasSurface,
142
+ presentFrame,
143
+ renderSurfaceHost,
144
+ startRenderLoop
145
+ };
@@ -0,0 +1,45 @@
1
+ import type { DefineComponent } from '@stacksjs/stx';
2
+ declare const __dtsx_component__: __DtsxStxComponentType;
3
+ /*
4
+ * <RenderSurface>: a box shared TypeScript draws into, frame by frame, with
5
+ * no WebView (stacksjs/stx#2108, craft-native/craft#578).
6
+ *
7
+ * <RenderSurface class="flex-1" filter="nearest"
8
+ * @ready="loop = startRenderLoop($event.surface, paint)"
9
+ * @restored="loop.wake()" @error="report($event)" />
10
+ *
11
+ * On a native screen it is the host's RenderSurface, drawn with Metal; in a
12
+ * browser it is a <canvas>. Frames go in through `presentFrame` or
13
+ * `startRenderLoop` from `@stacksjs/components/render-surface`, by the name
14
+ * `ready` carries.
15
+ *
16
+ * Props:
17
+ * - `surface`: the name frames are given to. Unique on the screen; when it is
18
+ * left out each instance gets its own. A second live surface of a name
19
+ * already taken stays blank and reports `DUPLICATE`.
20
+ * - `filter`: `nearest` (the default, for pixel art) or `linear`, used when a
21
+ * frame's size differs from the box's pixels.
22
+ * - `opaque`: true by default. A surface that is not opaque takes
23
+ * premultiplied alpha.
24
+ * - `label`: what a screen reader says for it.
25
+ * - `unavailableText`: what shows in its place where nothing can draw one.
26
+ *
27
+ * Events:
28
+ * - `ready` the first time it has a size, then `resize` on each change, both
29
+ * `{ surface, width, height, scale, pixelWidth, pixelHeight }`;
30
+ * - `lost` (`{ surface, reason }`) when the app goes to the background on a
31
+ * phone, and `restored` (the metrics again) when it returns: nothing is
32
+ * kept across a loss, so draw a whole frame again;
33
+ * - `error` with `{ surface, code, message }`: `UNAVAILABLE` where this device
34
+ * cannot draw one (the box then says so rather than staying blank), or
35
+ * `DUPLICATE`.
36
+ */
37
+ export declare const surface: unknown;
38
+ export declare const filter: boolean;
39
+ export declare const opaque: unknown;
40
+ export declare const className: unknown;
41
+ export declare const label: unknown;
42
+ export declare const unavailableText: unknown;
43
+ declare const unavailable: ReturnType<typeof state>;
44
+ declare type __DtsxStxComponentType = DefineComponent<{ surface?: string, filter?: unknown, opaque?: unknown, className?: unknown, class?: string, label?: string, unavailableText?: string }> & { readonly __stxEmits?: ["ready", "resize", "lost", "restored", "error"], readonly __stxExposed?: { surface: unknown, unavailable: typeof unavailable } }
45
+ export default __dtsx_component__;
@@ -0,0 +1,17 @@
1
+ export type { RenderFrame, RenderLoop, RenderSurfaceError, RenderSurfaceFilter, RenderSurfaceHost, RenderSurfaceMetrics } from './render-surface';
2
+ /** A box shared TypeScript draws into, frame by frame (stacksjs/stx#2108). */
3
+ export declare interface RenderSurfaceProps {
4
+ surface?: string
5
+ filter?: 'nearest' | 'linear'
6
+ opaque?: boolean
7
+ label?: string
8
+ unavailableText?: string
9
+ className?: string
10
+ onReady?: (detail: import('./render-surface').RenderSurfaceMetrics) => void
11
+ onResize?: (detail: import('./render-surface').RenderSurfaceMetrics) => void
12
+ onLost?: (detail: { surface: string, reason: string }) => void
13
+ onRestored?: (detail: import('./render-surface').RenderSurfaceMetrics) => void
14
+ onError?: (detail: import('./render-surface').RenderSurfaceError) => void
15
+ }
16
+ export { default as RenderSurface } from './RenderSurface';
17
+ export { presentFrame, RENDER_SURFACE_MAX_SIDE, renderSurfaceHost, startRenderLoop } from './render-surface';
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Where a frame would go on this page: `native` on a screen whose host has a
3
+ * Metal GPU, `canvas` in a browser, `none` on a native host without the
4
+ * capability. Read before mounting to decide whether to offer a surface.
5
+ */
6
+ export declare function renderSurfaceHost(): RenderSurfaceHost;
7
+ /**
8
+ * Draw one frame. True when the surface took it; false while it is not ready
9
+ * or is lost (wait for `ready` or `restored`, then draw a whole frame again:
10
+ * nothing is kept across a loss). Throws a TypeError for a wrong array or
11
+ * size, and an Error whose `code` is NOT_FOUND for a name no mounted surface
12
+ * holds (from its removal on) or UNAVAILABLE where nothing can draw one.
13
+ */
14
+ export declare function presentFrame(surface: string, pixels: Uint32Array, width: number, height: number): boolean;
15
+ /**
16
+ * The component's half in a browser: put a canvas under a name, or say why
17
+ * not. One live surface per name, as on a native screen: a second answers
18
+ * DUPLICATE and the first keeps drawing.
19
+ */
20
+ export declare function claimCanvasSurface(surface: string, canvas: HTMLCanvasElement, options?: { opaque?: boolean }): { release: () => void } | { error: RenderSurfaceError };
21
+ /**
22
+ * Draw on every display frame. `draw` returns the frame to show, or nothing
23
+ * to skip one. While the surface answers false (not ready yet, or lost) the
24
+ * loop draws nothing until `wake()`. Its surface being removed ends it
25
+ * quietly: that is how a loop learns its screen went. Any other error ends
26
+ * it and goes to `onError`, or is thrown when there is none.
27
+ */
28
+ export declare function startRenderLoop(surface: string, draw: (time: number) => RenderFrame | null | undefined | void, options?: { onError?: (error: unknown) => void }): RenderLoop;
29
+ /** The largest frame, in pixels a side, that a host takes. */
30
+ export declare const RENDER_SURFACE_MAX_SIDE: 8192;
31
+ /** What `ready`, `resize` and `restored` carry: the box in points, and in pixels. */
32
+ export declare interface RenderSurfaceMetrics {
33
+ surface: string
34
+ width: number
35
+ height: number
36
+ scale: number
37
+ pixelWidth: number
38
+ pixelHeight: number
39
+ }
40
+ /** What `error` carries. `UNAVAILABLE`: this device cannot draw one. `DUPLICATE`: the name is taken. */
41
+ export declare interface RenderSurfaceError {
42
+ surface: string
43
+ code: 'UNAVAILABLE' | 'DUPLICATE' | string
44
+ message: string
45
+ }
46
+ declare interface CanvasSurface {
47
+ canvas: HTMLCanvasElement
48
+ context: CanvasRenderingContext2D
49
+ opaque: boolean
50
+ image: ImageData | null
51
+ }
52
+ declare interface NativeRenderSurface {
53
+ present: (surface: string, pixels: Uint32Array, width: number, height: number) => boolean
54
+ }
55
+ export declare interface RenderFrame {
56
+ pixels: Uint32Array
57
+ width: number
58
+ height: number
59
+ }
60
+ export declare interface RenderLoop {
61
+ stop: () => void
62
+ wake: () => void
63
+ readonly waiting: boolean
64
+ readonly ended: boolean
65
+ }
66
+ /**
67
+ * Frames for a `<RenderSurface>`: a box shared TypeScript draws into, frame
68
+ * by frame, the same on a phone and in a browser (stacksjs/stx#2108).
69
+ *
70
+ * A frame is `width * height` 0xAARRGGBB words, row by row: what a CPU
71
+ * graphics core produces. On a native screen `presentFrame` hands them to the
72
+ * host's own `craft.renderSurface.present`, which copies them where the script
73
+ * runs and draws them with Metal (craft-native/craft#578). In a browser the
74
+ * component's `<canvas>` takes them. Either way the frame is scaled to the
75
+ * box, `nearest` or `linear`, so a game can draw below the display's
76
+ * resolution.
77
+ *
78
+ * import { startRenderLoop } from '@stacksjs/components/render-surface'
79
+ *
80
+ * <RenderSurface class="flex-1" @ready="loop = startRenderLoop($event.surface, paint)"
81
+ * @restored="loop.wake()" @error="report($event)" />
82
+ *
83
+ * This module never defines `craft.renderSurface`. The host installs it
84
+ * before the screen's script runs, and it is a function rather than a
85
+ * message: a frame sent as a message would be serialized on every frame.
86
+ */
87
+ export type RenderSurfaceFilter = 'nearest' | 'linear';
88
+ /** Where a frame goes: the host's surface, a canvas, or nowhere. */
89
+ export type RenderSurfaceHost = 'native' | 'canvas' | 'none';
90
+ declare type AnyGlobal = typeof globalThis & {
91
+ craft?: { renderSurface?: NativeRenderSurface, capabilities?: Record<string, boolean> }
92
+ stx?: { _host?: { isNative?: boolean } }
93
+ __stxRenderSurfaces?: Map<string, CanvasSurface>
94
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/components",
3
3
  "type": "module",
4
- "version": "0.2.919",
4
+ "version": "0.2.921",
5
5
  "description": "A modern component library built with STX, featuring headwind utility classes and TypeScript syntax highlighting.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -47,6 +47,11 @@
47
47
  "bun": "./stx-plugin.ts",
48
48
  "import": "./stx-plugin.ts"
49
49
  },
50
+ "./render-surface": {
51
+ "types": "./dist/ui/render-surface/render-surface.d.ts",
52
+ "bun": "./dist/render-surface/render-surface.js",
53
+ "import": "./dist/render-surface/render-surface.js"
54
+ },
50
55
  "./biometric": {
51
56
  "types": "./dist/ui/auth/biometric.d.ts",
52
57
  "bun": "./dist/biometric/biometric.js",
@@ -134,8 +139,8 @@
134
139
  "dependencies": {
135
140
  "@iconify-json/f7": "^1.2.2",
136
141
  "@stacksjs/ts-css": "^0.3.11",
137
- "@stacksjs/stx": "0.2.919",
138
- "bun-plugin-stx": "0.2.919",
142
+ "@stacksjs/stx": "0.2.921",
143
+ "bun-plugin-stx": "0.2.921",
139
144
  "ts-syntax-highlighter": "^0.2.20",
140
145
  "ts-video-player": "^0.1.11"
141
146
  },
package/src/index.ts CHANGED
@@ -60,6 +60,7 @@ export * from './ui/preview-frame'
60
60
  export * from './ui/progress'
61
61
  export * from './ui/radio'
62
62
  export * from './ui/radio-group'
63
+ export * from './ui/render-surface'
63
64
  export * from './ui/segmented-control'
64
65
  export * from './ui/select'
65
66
  export * from './ui/settings'
@@ -0,0 +1,69 @@
1
+ # RenderSurface
2
+
3
+ A box shared TypeScript draws into, frame by frame, with no WebView
4
+ (stacksjs/stx#2108). On a native screen it is the host's RenderSurface, drawn
5
+ with Metal (craft-native/craft#578); in a browser it is a `<canvas>`. The same
6
+ page and the same drawing code serve both.
7
+
8
+ ```html
9
+ <script client>
10
+ import { startRenderLoop } from '@stacksjs/components/render-surface'
11
+
12
+ let loop = null
13
+ const frame = new Uint32Array(320 * 180) // 0xAARRGGBB, row by row
14
+
15
+ function start(event) {
16
+ loop = startRenderLoop(event.surface, () => {
17
+ paint(frame) // the game's own CPU renderer
18
+ return { pixels: frame, width: 320, height: 180 }
19
+ })
20
+ }
21
+ </script>
22
+
23
+ <RenderSurface class="flex-1" filter="nearest" label="Map"
24
+ @ready="start($event)" @restored="loop.wake()" @error="report($event)" />
25
+ ```
26
+
27
+ ## Props
28
+
29
+ | Prop | Default | |
30
+ | --- | --- | --- |
31
+ | `surface` | one per instance | The name frames are given to, unique on the screen. |
32
+ | `filter` | `nearest` | How a frame of another size is scaled: `nearest` keeps pixel art crisp, `linear` smooths. |
33
+ | `opaque` | `true` | A surface that is not opaque takes premultiplied alpha. |
34
+ | `label` | | What a screen reader says for it. |
35
+ | `unavailableText` | "This device cannot draw this view." | Shown in its place where nothing can draw one. |
36
+
37
+ ## Events
38
+
39
+ - `ready` the first time it has a size, then `resize` on each change:
40
+ `{ surface, width, height, scale, pixelWidth, pixelHeight }` (points, then pixels).
41
+ - `lost` (`{ surface, reason }`) when a phone's app goes to the background, and
42
+ `restored` (the metrics) when it returns. Nothing is kept across a loss:
43
+ draw a whole frame again.
44
+ - `error` with `{ surface, code, message }`: `UNAVAILABLE` where the device
45
+ cannot draw one (the box then says so instead of staying blank), or
46
+ `DUPLICATE` when another live surface already has the name. That one stays
47
+ blank and the first keeps drawing.
48
+
49
+ ## Drawing
50
+
51
+ From `@stacksjs/components/render-surface`:
52
+
53
+ - `presentFrame(surface, pixels, width, height)` draws one frame of
54
+ `width * height` 0xAARRGGBB words, scaled to the box. A frame can be any size
55
+ up to 8192 pixels a side. It answers `true`, or `false` while the surface is
56
+ not ready or is lost. It throws a `TypeError` for a wrong array or size, and
57
+ an Error with `code` set to `NOT_FOUND` (no mounted surface has that name,
58
+ from its removal on) or `UNAVAILABLE`.
59
+ - `startRenderLoop(surface, draw, { onError })` draws on every display frame.
60
+ It waits after a `false` until `wake()`, call that from `ready` and
61
+ `restored`. The surface's removal ends it quietly.
62
+ - `renderSurfaceHost()` says where frames would go: `native`, `canvas`, or
63
+ `none`. Read it before mounting to decide whether to offer a surface.
64
+
65
+ On a phone, frames go to the host's own `craft.renderSurface.present`, which
66
+ copies the words where the script runs. It is a function, not a message, so a
67
+ frame is never serialized; stx never defines or replaces it.
68
+
69
+ Android has no RenderSurface yet (craft-native/craft#393).
@@ -0,0 +1,137 @@
1
+ <script server>
2
+ /*
3
+ * <RenderSurface>: a box shared TypeScript draws into, frame by frame, with
4
+ * no WebView (stacksjs/stx#2108, craft-native/craft#578).
5
+ *
6
+ * <RenderSurface class="flex-1" filter="nearest"
7
+ * @ready="loop = startRenderLoop($event.surface, paint)"
8
+ * @restored="loop.wake()" @error="report($event)" />
9
+ *
10
+ * On a native screen it is the host's RenderSurface, drawn with Metal; in a
11
+ * browser it is a <canvas>. Frames go in through `presentFrame` or
12
+ * `startRenderLoop` from `@stacksjs/components/render-surface`, by the name
13
+ * `ready` carries.
14
+ *
15
+ * Props:
16
+ * - `surface`: the name frames are given to. Unique on the screen; when it is
17
+ * left out each instance gets its own. A second live surface of a name
18
+ * already taken stays blank and reports `DUPLICATE`.
19
+ * - `filter`: `nearest` (the default, for pixel art) or `linear`, used when a
20
+ * frame's size differs from the box's pixels.
21
+ * - `opaque`: true by default. A surface that is not opaque takes
22
+ * premultiplied alpha.
23
+ * - `label`: what a screen reader says for it.
24
+ * - `unavailableText`: what shows in its place where nothing can draw one.
25
+ *
26
+ * Events:
27
+ * - `ready` the first time it has a size, then `resize` on each change, both
28
+ * `{ surface, width, height, scale, pixelWidth, pixelHeight }`;
29
+ * - `lost` (`{ surface, reason }`) when the app goes to the background on a
30
+ * phone, and `restored` (the metrics again) when it returns: nothing is
31
+ * kept across a loss, so draw a whole frame again;
32
+ * - `error` with `{ surface, code, message }`: `UNAVAILABLE` where this device
33
+ * cannot draw one (the box then says so rather than staying blank), or
34
+ * `DUPLICATE`.
35
+ */
36
+ export const surface = $props.surface || `surface-${$uid}`
37
+ export const filter = $props.filter === 'linear' ? 'linear' : 'nearest'
38
+ export const opaque = $bool($props.opaque, true)
39
+ export const className = $props.className || $props.class || ''
40
+ export const label = $props.label || ''
41
+ export const unavailableText = $props.unavailableText || 'This device cannot draw this view.'
42
+ </script>
43
+
44
+ <script client>
45
+ import { claimCanvasSurface, renderSurfaceHost } from './render-surface'
46
+
47
+ const emit = defineEmits(['ready', 'resize', 'lost', 'restored', 'error'])
48
+ const name = {{ surface }}
49
+ const filter = {{ filter }}
50
+ const opaque = {{ opaque }}
51
+ const nativeHost = !!window.stx._host.isNative
52
+ const canvasRef = useRef('canvasRef')
53
+ const unavailable = state(false)
54
+ let claim = null
55
+ let observer = null
56
+ let sized = false
57
+
58
+ // A host event carries its payload as nativeEvent; the shared runtime may
59
+ // also hand it over as it is.
60
+ function payload(event) {
61
+ return (event && event.nativeEvent) || event || {}
62
+ }
63
+
64
+ function metrics(event) {
65
+ const m = payload(event)
66
+ return { surface: name, width: m.width, height: m.height, scale: m.scale, pixelWidth: m.pixelWidth, pixelHeight: m.pixelHeight }
67
+ }
68
+
69
+ function fail(error) {
70
+ if (error.code === 'UNAVAILABLE') unavailable.set(true)
71
+ // Reported, never swallowed: a DUPLICATE is a page mistake, and the box
72
+ // stays blank until it is fixed.
73
+ emit('error', { surface: name, code: String(error.code || 'ERROR'), message: String(error.message || '') })
74
+ }
75
+
76
+ function hostReady(event) { emit('ready', metrics(event)) }
77
+ function hostResize(event) { emit('resize', metrics(event)) }
78
+ function hostLost(event) { emit('lost', { surface: name, reason: String(payload(event).reason || 'background') }) }
79
+ function hostRestored(event) { emit('restored', metrics(event)) }
80
+ function hostError(event) { fail(payload(event)) }
81
+
82
+ // A browser has no surface events of its own. The canvas's size stands in
83
+ // for them: its first size is `ready`, each change after it `resize`.
84
+ function measure() {
85
+ const canvas = canvasRef.value
86
+ if (!canvas || !claim || claim.error) return
87
+ const box = canvas.getBoundingClientRect()
88
+ if (box.width <= 0 || box.height <= 0) return
89
+ const scale = window.devicePixelRatio || 1
90
+ const detail = { surface: name, width: box.width, height: box.height, scale, pixelWidth: Math.round(box.width * scale), pixelHeight: Math.round(box.height * scale) }
91
+ emit(sized ? 'resize' : 'ready', detail)
92
+ sized = true
93
+ }
94
+
95
+ onMount(() => {
96
+ // Per mount: an :if can take the surface away and bring it back with the
97
+ // same setup, and coming back is a new surface with a ready of its own.
98
+ sized = false
99
+ if (nativeHost) {
100
+ // The host also says UNAVAILABLE once at mount; knowing it here shows the
101
+ // fallback without waiting for that.
102
+ if (renderSurfaceHost() === 'none') unavailable.set(true)
103
+ return
104
+ }
105
+ const canvas = canvasRef.value
106
+ if (!canvas) return
107
+ canvas.style.imageRendering = filter === 'nearest' ? 'pixelated' : 'auto'
108
+ claim = claimCanvasSurface(name, canvas, { opaque })
109
+ if (claim.error) { fail(claim.error); return }
110
+ // The observer's first answer, after layout, is the ready. Measured here
111
+ // instead, a surface mounted again under an :if said ready before the
112
+ // page's listener was back on it, and the page never heard.
113
+ if (typeof ResizeObserver === 'function') {
114
+ observer = new ResizeObserver(() => measure())
115
+ observer.observe(canvas)
116
+ }
117
+ else setTimeout(measure, 0)
118
+ })
119
+
120
+ onDestroy(() => {
121
+ sized = false
122
+ if (observer) observer.disconnect()
123
+ observer = null
124
+ if (claim && claim.release) claim.release()
125
+ claim = null
126
+ })
127
+
128
+ defineExpose({ surface: name, unavailable })
129
+ </script>
130
+
131
+ {{-- data-stx-layout-root: a phone has no display:contents, so the scope around
132
+ this root is a real box there, and an unsized one left the surface 0
133
+ points wide in a row: the host never said ready. --}}
134
+ <div class="relative flex flex-col min-h-0 min-w-0 {{ className }}" data-render-surface data-stx-layout-root>
135
+ <canvas data-native="RenderSurface" ref="canvasRef" surface="{{ surface }}" filter="{{ filter }}" :opaque="{{ opaque }}" role="img" @if(label) aria-label="{{ label }}" @endif class="flex-1 block w-full min-h-0 min-w-0" @ready="hostReady($event)" @resize="hostResize($event)" @lost="hostLost($event)" @restored="hostRestored($event)" @error="hostError($event)"></canvas>
136
+ <div :show="unavailable()" role="status" class="absolute inset-0 flex items-center justify-center p-4 text-center text-sm text-fg-muted">{{ unavailableText }}</div>
137
+ </div>
@@ -0,0 +1,27 @@
1
+ export { default as RenderSurface } from './RenderSurface.stx'
2
+ export type { RenderFrame, RenderLoop, RenderSurfaceError, RenderSurfaceFilter, RenderSurfaceHost, RenderSurfaceMetrics } from './render-surface'
3
+ export { presentFrame, RENDER_SURFACE_MAX_SIDE, renderSurfaceHost, startRenderLoop } from './render-surface'
4
+
5
+ /** A box shared TypeScript draws into, frame by frame (stacksjs/stx#2108). */
6
+ export interface RenderSurfaceProps {
7
+ /** The name frames are given to. Unique on the screen; each instance gets its own when it is left out. */
8
+ surface?: string
9
+ /** How a frame of another size is scaled to the box. */
10
+ filter?: 'nearest' | 'linear'
11
+ /** True by default. A surface that is not opaque takes premultiplied alpha. */
12
+ opaque?: boolean
13
+ /** What a screen reader says for it. */
14
+ label?: string
15
+ /** What shows in its place where nothing can draw one. */
16
+ unavailableText?: string
17
+ className?: string
18
+ /** The first size in a window. */
19
+ onReady?: (detail: import('./render-surface').RenderSurfaceMetrics) => void
20
+ onResize?: (detail: import('./render-surface').RenderSurfaceMetrics) => void
21
+ /** The app went to the background on a phone; nothing is kept. */
22
+ onLost?: (detail: { surface: string, reason: string }) => void
23
+ /** Back from a loss: draw a whole frame again. */
24
+ onRestored?: (detail: import('./render-surface').RenderSurfaceMetrics) => void
25
+ /** `UNAVAILABLE` or `DUPLICATE`. */
26
+ onError?: (detail: import('./render-surface').RenderSurfaceError) => void
27
+ }