@beetlebug/ztk 0.0.0-stage → 0.2.0-beta
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/LICENSE +24 -0
- package/NOTICE +18 -0
- package/README.md +100 -2
- package/licenses/LICENSE-Inter.txt +92 -0
- package/licenses/ztcl/LICENSE +24 -0
- package/licenses/ztcl/arm-optimized-routines.txt +249 -0
- package/licenses/ztcl/go-BSD-3-Clause.txt +27 -0
- package/licenses/ztcl/musl-MIT.txt +193 -0
- package/licenses/ztcl/tcl-license.txt +40 -0
- package/licenses/ztcl/zig-std-MIT.txt +21 -0
- package/package.json +42 -4
- package/ztk.d.ts +121 -0
- package/ztk.js +503 -0
- package/ztk.wasm +0 -0
package/ztk.js
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
// SPDX-License-Identifier: BSD-2-Clause
|
|
2
|
+
// The page side of ztk in a browser. It loads ztk.wasm, gives it the
|
|
3
|
+
// clock, the size, the scale (devicePixelRatio), the color scheme, the
|
|
4
|
+
// reduced motion setting, and the input of the canvas, and draws each
|
|
5
|
+
// scene with WebGL 2, or with the CPU renderer of ztk.wasm and a 2D
|
|
6
|
+
// context. mount() is the API for a page, and start() is the API under
|
|
7
|
+
// it. The shaders have the formulas of the CPU renderer
|
|
8
|
+
// (src/render/renderer.zig) and of src/render/shaders/quad.frag. A
|
|
9
|
+
// hidden text area gets the keyboard, so that text input and input
|
|
10
|
+
// methods work. A list of hidden elements with ARIA roles follows the
|
|
11
|
+
// widgets, from ztk_a11y.
|
|
12
|
+
|
|
13
|
+
const VS = `#version 300 es
|
|
14
|
+
layout(location=0) in vec4 a_rect;
|
|
15
|
+
layout(location=1) in vec4 a_clip;
|
|
16
|
+
layout(location=2) in vec4 a_radii;
|
|
17
|
+
layout(location=3) in vec4 a_border;
|
|
18
|
+
layout(location=4) in vec4 a_fill;
|
|
19
|
+
layout(location=5) in vec4 a_fill2;
|
|
20
|
+
layout(location=6) in vec4 a_border_color;
|
|
21
|
+
layout(location=7) in vec4 a_uv;
|
|
22
|
+
layout(location=8) in vec4 a_params;
|
|
23
|
+
layout(location=9) in uint a_kind;
|
|
24
|
+
uniform vec2 u_target;
|
|
25
|
+
flat out vec4 f_rect; flat out vec4 f_clip; flat out vec4 f_radii; flat out vec4 f_border;
|
|
26
|
+
flat out vec4 f_fill; flat out vec4 f_fill2; flat out vec4 f_border_color; flat out vec4 f_uv;
|
|
27
|
+
flat out vec4 f_params; flat out uint f_kind;
|
|
28
|
+
void main() {
|
|
29
|
+
float pad = 0.0;
|
|
30
|
+
if (a_kind == 0u) pad = 1.0;
|
|
31
|
+
if (a_kind == 1u) pad = max(a_params.z, 1.0) + 1.0;
|
|
32
|
+
vec2 lo = max(a_rect.xy - pad, a_clip.xy);
|
|
33
|
+
vec2 hi = min(a_rect.xy + a_rect.zw + pad, a_clip.xy + a_clip.zw);
|
|
34
|
+
hi = max(hi, lo);
|
|
35
|
+
vec2 corner = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1));
|
|
36
|
+
vec2 pos = mix(lo, hi, corner);
|
|
37
|
+
vec2 ndc = pos / u_target * 2.0 - 1.0;
|
|
38
|
+
gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
|
|
39
|
+
f_rect = a_rect; f_clip = a_clip; f_radii = a_radii; f_border = a_border; f_fill = a_fill;
|
|
40
|
+
f_fill2 = a_fill2; f_border_color = a_border_color; f_uv = a_uv; f_params = a_params; f_kind = a_kind;
|
|
41
|
+
}`;
|
|
42
|
+
|
|
43
|
+
const FS = `#version 300 es
|
|
44
|
+
precision highp float;
|
|
45
|
+
flat in vec4 f_rect; flat in vec4 f_clip; flat in vec4 f_radii; flat in vec4 f_border;
|
|
46
|
+
flat in vec4 f_fill; flat in vec4 f_fill2; flat in vec4 f_border_color; flat in vec4 f_uv;
|
|
47
|
+
flat in vec4 f_params; flat in uint f_kind;
|
|
48
|
+
uniform vec2 u_target;
|
|
49
|
+
uniform sampler2D u_atlas;
|
|
50
|
+
out vec4 out_color;
|
|
51
|
+
float clamp01(float x) { return clamp(x, 0.0, 1.0); }
|
|
52
|
+
float roundedDistance(vec2 p, vec4 rect, vec4 radii) {
|
|
53
|
+
float hw = rect.z * 0.5; float hh = rect.w * 0.5;
|
|
54
|
+
float dx = p.x - (rect.x + hw); float dy = p.y - (rect.y + hh);
|
|
55
|
+
float limit = min(hw, hh);
|
|
56
|
+
float r = dy < 0.0 ? (dx < 0.0 ? radii.x : radii.y) : (dx < 0.0 ? radii.w : radii.z);
|
|
57
|
+
r = min(r, limit);
|
|
58
|
+
float qx = abs(dx) - hw + r; float qy = abs(dy) - hh + r;
|
|
59
|
+
float mx = max(qx, 0.0); float my = max(qy, 0.0);
|
|
60
|
+
return min(max(qx, qy), 0.0) + sqrt(mx * mx + my * my) - r;
|
|
61
|
+
}
|
|
62
|
+
vec2 boxCoverage(vec2 p) {
|
|
63
|
+
float outer = clamp01(0.5 - roundedDistance(p, f_rect, f_radii));
|
|
64
|
+
float bt = f_border.x; float br = f_border.y; float bb = f_border.z; float bl = f_border.w;
|
|
65
|
+
if (bt == 0.0 && br == 0.0 && bb == 0.0 && bl == 0.0) return vec2(outer, 0.0);
|
|
66
|
+
vec4 ir = vec4(f_rect.x + bl, f_rect.y + bt, f_rect.z - bl - br, f_rect.w - bt - bb);
|
|
67
|
+
if (ir.z <= 0.0 || ir.w <= 0.0) return vec2(0.0, outer);
|
|
68
|
+
vec4 irad = vec4(max(f_radii.x - max(bt, bl), 0.0), max(f_radii.y - max(bt, br), 0.0),
|
|
69
|
+
max(f_radii.z - max(bb, br), 0.0), max(f_radii.w - max(bb, bl), 0.0));
|
|
70
|
+
float inner = clamp01(0.5 - roundedDistance(p, ir, irad));
|
|
71
|
+
return vec2(inner, max(outer - inner, 0.0));
|
|
72
|
+
}
|
|
73
|
+
float shadowCoverage(vec2 p) {
|
|
74
|
+
float d = roundedDistance(p, f_rect, f_radii);
|
|
75
|
+
float t = clamp01(0.5 - d / max(f_params.z, 1.0));
|
|
76
|
+
return t * t * (3.0 - 2.0 * t);
|
|
77
|
+
}
|
|
78
|
+
float gradientT(vec2 p) {
|
|
79
|
+
float dx = f_params.x; float dy = f_params.y;
|
|
80
|
+
float len = abs(f_rect.z * dx) + abs(f_rect.w * dy);
|
|
81
|
+
if (len <= 0.0) return 0.0;
|
|
82
|
+
return clamp01(((p.x - (f_rect.x + f_rect.z * 0.5)) * dx + (p.y - (f_rect.y + f_rect.w * 0.5)) * dy) / len + 0.5);
|
|
83
|
+
}
|
|
84
|
+
void main() {
|
|
85
|
+
vec2 p = vec2(gl_FragCoord.x, u_target.y - gl_FragCoord.y);
|
|
86
|
+
if (p.x < f_clip.x || p.y < f_clip.y || p.x >= f_clip.x + f_clip.z || p.y >= f_clip.y + f_clip.w) discard;
|
|
87
|
+
float opacity = f_params.w;
|
|
88
|
+
if (f_kind == 0u) {
|
|
89
|
+
vec2 c = boxCoverage(p);
|
|
90
|
+
vec4 col = (f_fill == f_fill2) ? f_fill : mix(f_fill, f_fill2, gradientT(p));
|
|
91
|
+
float fa = col.a * c.x * opacity;
|
|
92
|
+
float ba = f_border_color.a * c.y * opacity;
|
|
93
|
+
out_color = vec4(f_border_color.rgb * ba + col.rgb * fa * (1.0 - ba), 1.0 - (1.0 - fa) * (1.0 - ba));
|
|
94
|
+
} else if (f_kind == 1u) {
|
|
95
|
+
float a = f_fill.a * shadowCoverage(p) * opacity;
|
|
96
|
+
out_color = vec4(f_fill.rgb * a, a);
|
|
97
|
+
} else if (f_kind == 2u) {
|
|
98
|
+
ivec2 t = ivec2(f_uv.xy) + ivec2(floor(p)) - ivec2(f_rect.xy);
|
|
99
|
+
float a = f_fill.a * texelFetch(u_atlas, t, 0).r * opacity;
|
|
100
|
+
out_color = vec4(f_fill.rgb * a, a);
|
|
101
|
+
} else {
|
|
102
|
+
discard;
|
|
103
|
+
}
|
|
104
|
+
}`;
|
|
105
|
+
|
|
106
|
+
const QUAD_BYTES = 160;
|
|
107
|
+
const ATLAS = 1024;
|
|
108
|
+
|
|
109
|
+
const KEYS = {
|
|
110
|
+
Enter: "Return", Backspace: "BackSpace", Tab: "Tab", Escape: "Escape", Delete: "Delete",
|
|
111
|
+
ArrowLeft: "Left", ArrowRight: "Right", ArrowUp: "Up", ArrowDown: "Down", Home: "Home", End: "End",
|
|
112
|
+
PageUp: "Prior", PageDown: "Next", Insert: "Insert", Shift: "Shift_L", Control: "Control_L", Alt: "Alt_L",
|
|
113
|
+
F1: "F1", F2: "F2", F3: "F3", F4: "F4", F5: "F5", F6: "F6", F7: "F7", F8: "F8", F9: "F9", F10: "F10", F11: "F11", F12: "F12",
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
// The built-in modules of Node.js, through process.getBuiltinModule
|
|
118
|
+
// (Node.js 22.3 and later). The file has no `node:` import, so a
|
|
119
|
+
// bundler for the browser needs no shim.
|
|
120
|
+
function nodeModule(name) {
|
|
121
|
+
return globalThis.process?.getBuiltinModule?.(name);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/// The URL of the ztk.wasm file next to this file. Bundlers (Vite,
|
|
125
|
+
/// webpack 5) find it through the `new URL("./ztk.wasm", import.meta.url)`
|
|
126
|
+
/// form, and a CDN serves it from the folder of this file.
|
|
127
|
+
export function wasmURL() {
|
|
128
|
+
return new URL("./ztk.wasm", import.meta.url);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function compileFrom(u) {
|
|
132
|
+
const url = new URL(u, globalThis.location?.href);
|
|
133
|
+
const fs = nodeModule("node:fs/promises");
|
|
134
|
+
if (url.protocol === "file:" && fs) return WebAssembly.compile(await fs.readFile(url));
|
|
135
|
+
const res = await fetch(url);
|
|
136
|
+
if (!res.ok) throw new Error(`ztk.wasm: HTTP ${res.status}`);
|
|
137
|
+
if (WebAssembly.compileStreaming && res.headers.get("content-type") === "application/wasm") {
|
|
138
|
+
return WebAssembly.compileStreaming(res);
|
|
139
|
+
}
|
|
140
|
+
return WebAssembly.compile(await res.arrayBuffer());
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/// Compiles ztk.wasm one time for each URL. With no URL, it is the
|
|
144
|
+
/// ztk.wasm file next to this file.
|
|
145
|
+
const compiled = new Map();
|
|
146
|
+
export function compileModule(url) {
|
|
147
|
+
const u = String(url || wasmURL());
|
|
148
|
+
if (!compiled.has(u)) {
|
|
149
|
+
const p = compileFrom(u);
|
|
150
|
+
p.catch(() => compiled.delete(u));
|
|
151
|
+
compiled.set(u, p);
|
|
152
|
+
}
|
|
153
|
+
return compiled.get(u);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/// The renderers that this file has, in the order of "auto".
|
|
157
|
+
export const renderers = ["webgl2", "cpu"];
|
|
158
|
+
|
|
159
|
+
// The WebGL 2 renderer: the quads of the scene in one instanced draw.
|
|
160
|
+
function webgl2(canvas, ex) {
|
|
161
|
+
const gl = canvas.getContext("webgl2", { premultipliedAlpha: true, antialias: false, alpha: false, preserveDrawingBuffer: true });
|
|
162
|
+
if (!gl) return null;
|
|
163
|
+
const compile = (type, src) => {
|
|
164
|
+
const s = gl.createShader(type);
|
|
165
|
+
gl.shaderSource(s, src);
|
|
166
|
+
gl.compileShader(s);
|
|
167
|
+
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
|
|
168
|
+
return s;
|
|
169
|
+
};
|
|
170
|
+
const prog = gl.createProgram();
|
|
171
|
+
gl.attachShader(prog, compile(gl.VERTEX_SHADER, VS));
|
|
172
|
+
gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, FS));
|
|
173
|
+
gl.linkProgram(prog);
|
|
174
|
+
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog));
|
|
175
|
+
const vao = gl.createVertexArray();
|
|
176
|
+
gl.bindVertexArray(vao);
|
|
177
|
+
const buf = gl.createBuffer();
|
|
178
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
|
179
|
+
for (let i = 0; i < 9; i++) {
|
|
180
|
+
gl.enableVertexAttribArray(i);
|
|
181
|
+
gl.vertexAttribPointer(i, 4, gl.FLOAT, false, QUAD_BYTES, i * 16);
|
|
182
|
+
gl.vertexAttribDivisor(i, 1);
|
|
183
|
+
}
|
|
184
|
+
gl.enableVertexAttribArray(9);
|
|
185
|
+
gl.vertexAttribIPointer(9, 1, gl.UNSIGNED_INT, QUAD_BYTES, 144);
|
|
186
|
+
gl.vertexAttribDivisor(9, 1);
|
|
187
|
+
const tex = gl.createTexture();
|
|
188
|
+
gl.bindTexture(gl.TEXTURE_2D, tex);
|
|
189
|
+
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
|
|
190
|
+
gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, ATLAS, ATLAS, 0, gl.RED, gl.UNSIGNED_BYTE, null);
|
|
191
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
|
192
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
|
193
|
+
const uTarget = gl.getUniformLocation(prog, "u_target");
|
|
194
|
+
let atlasVersion = -1;
|
|
195
|
+
return {
|
|
196
|
+
name: "webgl2",
|
|
197
|
+
draw(n, w, h) {
|
|
198
|
+
const v = ex.ztk_atlas_version();
|
|
199
|
+
if (v !== atlasVersion) {
|
|
200
|
+
atlasVersion = v;
|
|
201
|
+
const p = ex.ztk_atlas();
|
|
202
|
+
if (p) gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, ATLAS, ATLAS, gl.RED, gl.UNSIGNED_BYTE, new Uint8Array(ex.memory.buffer, p, ATLAS * ATLAS));
|
|
203
|
+
}
|
|
204
|
+
const c = new Float32Array(ex.memory.buffer, ex.ztk_clear_color(), 4);
|
|
205
|
+
gl.viewport(0, 0, w, h);
|
|
206
|
+
gl.disable(gl.SCISSOR_TEST);
|
|
207
|
+
gl.clearColor(c[0], c[1], c[2], c[3]);
|
|
208
|
+
gl.clear(gl.COLOR_BUFFER_BIT);
|
|
209
|
+
if (n > 0) {
|
|
210
|
+
gl.useProgram(prog);
|
|
211
|
+
gl.bindVertexArray(vao);
|
|
212
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
|
213
|
+
gl.bufferData(gl.ARRAY_BUFFER, new Uint8Array(ex.memory.buffer, ex.ztk_quads(), n * QUAD_BYTES), gl.STREAM_DRAW);
|
|
214
|
+
gl.uniform2f(uTarget, w, h);
|
|
215
|
+
gl.enable(gl.BLEND);
|
|
216
|
+
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
|
|
217
|
+
gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, n);
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
destroy() {
|
|
221
|
+
gl.deleteBuffer(buf);
|
|
222
|
+
gl.deleteTexture(tex);
|
|
223
|
+
gl.deleteVertexArray(vao);
|
|
224
|
+
gl.deleteProgram(prog);
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// The CPU renderer: ztk.wasm draws each frame to an RGBA image (the
|
|
230
|
+
// renderer of src/render/cpu.zig), and a 2D context shows it.
|
|
231
|
+
function cpu(canvas, ex) {
|
|
232
|
+
const ctx = canvas.getContext("2d", { alpha: false });
|
|
233
|
+
if (!ctx) return null;
|
|
234
|
+
ex.ztk_cpu(true);
|
|
235
|
+
return {
|
|
236
|
+
name: "cpu",
|
|
237
|
+
draw(_n, w, h) {
|
|
238
|
+
const p = ex.ztk_image();
|
|
239
|
+
if (!p || w === 0 || h === 0) return;
|
|
240
|
+
const px = new Uint8ClampedArray(ex.memory.buffer, p, w * h * 4).slice();
|
|
241
|
+
ctx.putImageData(new ImageData(px, w, h), 0, 0);
|
|
242
|
+
},
|
|
243
|
+
destroy() {},
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/// Starts ztk.wasm on a canvas. `mount` is the API for a page. Options:
|
|
248
|
+
/// module or wasm (the module, or the URL of ztk.wasm), renderer ("auto",
|
|
249
|
+
/// "webgl2", "cpu", or "webgpu"), dark (true, false, or undefined for the
|
|
250
|
+
/// color scheme of the page), width and height (a fixed logical size),
|
|
251
|
+
/// scale (in place of devicePixelRatio), and log (gets the text of puts
|
|
252
|
+
/// and the errors).
|
|
253
|
+
export async function start(canvas, options = {}) {
|
|
254
|
+
const enc = new TextEncoder();
|
|
255
|
+
const dec = new TextDecoder();
|
|
256
|
+
let ex = null;
|
|
257
|
+
const log = options.log || ((t) => console.log(t));
|
|
258
|
+
const imports = {
|
|
259
|
+
env: {
|
|
260
|
+
ztk_now_ms: () => performance.now(),
|
|
261
|
+
ztk_print: (p, n) => log(dec.decode(new Uint8Array(ex.memory.buffer, p, n))),
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
// A page with several demos compiles the module one time and gives it as options.module.
|
|
265
|
+
const module = options.module || await compileModule(options.wasm);
|
|
266
|
+
const instance = await WebAssembly.instantiate(module, imports);
|
|
267
|
+
ex = instance.exports;
|
|
268
|
+
|
|
269
|
+
// Each listener of the page and of the canvas goes away with destroy().
|
|
270
|
+
const life = new AbortController();
|
|
271
|
+
const signal = life.signal;
|
|
272
|
+
const dark = matchMedia("(prefers-color-scheme: dark)");
|
|
273
|
+
const reduce = matchMedia("(prefers-reduced-motion: reduce)");
|
|
274
|
+
let forceDark = options.dark;
|
|
275
|
+
// The window of the script starts with the size of the element that
|
|
276
|
+
// holds the canvas, or with a fixed logical size (options.width and
|
|
277
|
+
// options.height) that the page shows at the size it gave the canvas.
|
|
278
|
+
// The toplevel then takes its own size, as in Tk (geometry propagation),
|
|
279
|
+
// so the canvas gets its CSS size from the scene after each frame:
|
|
280
|
+
// the scene width times k / scale, where k is the count of CSS pixels in
|
|
281
|
+
// one logical pixel. The backing store is the scene in device pixels.
|
|
282
|
+
// So the window keeps its aspect ratio and is sharp at each
|
|
283
|
+
// devicePixelRatio.
|
|
284
|
+
const fixed = Boolean(options.width && options.height);
|
|
285
|
+
const host = canvas.parentElement;
|
|
286
|
+
const size = () => {
|
|
287
|
+
if (fixed) return [options.width, options.height];
|
|
288
|
+
const r = host.getBoundingClientRect();
|
|
289
|
+
return [Math.max(1, Math.round(r.width)), Math.max(1, Math.round(r.height))];
|
|
290
|
+
};
|
|
291
|
+
let k = 1;
|
|
292
|
+
if (fixed) {
|
|
293
|
+
const r = canvas.getBoundingClientRect();
|
|
294
|
+
if (r.width > 0) k = r.width / options.width;
|
|
295
|
+
}
|
|
296
|
+
const scaleNow = () => options.scale || devicePixelRatio * k;
|
|
297
|
+
const [w0, h0] = size();
|
|
298
|
+
if (!ex.ztk_init(w0, h0, scaleNow(), forceDark ?? dark.matches, reduce.matches)) throw new Error("ztk_init failed");
|
|
299
|
+
dark.addEventListener("change", () => forceDark == null && ex.ztk_dark(dark.matches), { signal });
|
|
300
|
+
reduce.addEventListener("change", () => ex.ztk_reduce_motion(reduce.matches), { signal });
|
|
301
|
+
|
|
302
|
+
const withBytes = (text, f) => {
|
|
303
|
+
const b = enc.encode(text);
|
|
304
|
+
const p = ex.ztk_alloc(Math.max(b.length, 1));
|
|
305
|
+
new Uint8Array(ex.memory.buffer, p, b.length).set(b);
|
|
306
|
+
try { return f(p, b.length); } finally { ex.ztk_free(p, Math.max(b.length, 1)); }
|
|
307
|
+
};
|
|
308
|
+
const result = () => dec.decode(new Uint8Array(ex.memory.buffer, ex.ztk_result_ptr(), ex.ztk_result_len()));
|
|
309
|
+
const evalScript = (text) => {
|
|
310
|
+
const code = withBytes(text, (p, n) => ex.ztk_eval(p, n));
|
|
311
|
+
const r = result();
|
|
312
|
+
if (code !== 0) log("error: " + r);
|
|
313
|
+
return { ok: code === 0, result: r };
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
// The renderer. "auto" selects the first one that the browser has.
|
|
317
|
+
const want = options.renderer || "auto";
|
|
318
|
+
if (want === "webgpu") throw new Error("ztk: this version has no WebGPU renderer. Use \"auto\", \"webgl2\", or \"cpu\".");
|
|
319
|
+
const makers = { webgl2, cpu };
|
|
320
|
+
if (want !== "auto" && !makers[want]) throw new Error(`ztk: no renderer "${want}"`);
|
|
321
|
+
let renderer = null;
|
|
322
|
+
for (const name of want === "auto" ? renderers : [want]) {
|
|
323
|
+
renderer = makers[name](canvas, ex);
|
|
324
|
+
if (renderer || want !== "auto") break;
|
|
325
|
+
}
|
|
326
|
+
if (!renderer) throw new Error(want === "webgl2" ? "WebGL 2 is not available" : `ztk: the renderer "${want}" is not available`);
|
|
327
|
+
|
|
328
|
+
const draw = (n) => {
|
|
329
|
+
const w = ex.ztk_scene_width(), h = ex.ztk_scene_height();
|
|
330
|
+
if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
|
|
331
|
+
const sc = scaleNow();
|
|
332
|
+
const cw = `${(w * k) / sc}px`, ch = `${(h * k) / sc}px`;
|
|
333
|
+
if (canvas.style.width !== cw || canvas.style.height !== ch) { canvas.style.width = cw; canvas.style.height = ch; }
|
|
334
|
+
renderer.draw(n, w, h);
|
|
335
|
+
updateA11y();
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
// Input. A hidden text area holds the keyboard focus.
|
|
339
|
+
const on = (target, type, f) => target.addEventListener(type, f, { signal });
|
|
340
|
+
const input = document.createElement("textarea");
|
|
341
|
+
input.setAttribute("aria-hidden", "true");
|
|
342
|
+
input.style.cssText = "position:absolute;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none;";
|
|
343
|
+
canvas.parentElement.style.position ||= "relative";
|
|
344
|
+
canvas.parentElement.appendChild(input);
|
|
345
|
+
const pos = (e) => {
|
|
346
|
+
const r = canvas.getBoundingClientRect();
|
|
347
|
+
return [(e.clientX - r.left) / k, (e.clientY - r.top) / k];
|
|
348
|
+
};
|
|
349
|
+
const mods = (e) => ex.ztk_mods(e.shiftKey, e.ctrlKey || e.metaKey, e.altKey);
|
|
350
|
+
on(canvas, "pointermove", (e) => { mods(e); ex.ztk_pointer(...pos(e)); });
|
|
351
|
+
on(canvas, "pointerdown", (e) => {
|
|
352
|
+
mods(e); ex.ztk_pointer(...pos(e)); ex.ztk_button([1, 2, 3][e.button] || 1, true);
|
|
353
|
+
try { canvas.setPointerCapture(e.pointerId); } catch (_) { /* a synthetic event has no capture */ }
|
|
354
|
+
input.focus({ preventScroll: true }); e.preventDefault();
|
|
355
|
+
});
|
|
356
|
+
on(canvas, "pointerup", (e) => { mods(e); ex.ztk_pointer(...pos(e)); ex.ztk_button([1, 2, 3][e.button] || 1, false); });
|
|
357
|
+
on(canvas, "pointerleave", () => ex.ztk_leave());
|
|
358
|
+
on(canvas, "contextmenu", (e) => e.preventDefault());
|
|
359
|
+
let composing = false;
|
|
360
|
+
on(input, "compositionstart", () => { composing = true; });
|
|
361
|
+
on(input, "compositionend", (e) => { composing = false; withBytes(e.data || "", (p, n) => ex.ztk_text(p, n)); input.value = ""; });
|
|
362
|
+
on(input, "input", (e) => {
|
|
363
|
+
if (composing || e.isComposing) return;
|
|
364
|
+
if (input.value) withBytes(input.value, (p, n) => ex.ztk_text(p, n));
|
|
365
|
+
input.value = "";
|
|
366
|
+
});
|
|
367
|
+
const key = (e, down) => {
|
|
368
|
+
mods(e);
|
|
369
|
+
const name = KEYS[e.key];
|
|
370
|
+
if (!name) return;
|
|
371
|
+
withBytes(name, (p, n) => ex.ztk_key(p, n, down));
|
|
372
|
+
if (e.key === "Tab" || e.key.startsWith("Arrow") || e.key === "Backspace") e.preventDefault();
|
|
373
|
+
};
|
|
374
|
+
on(input, "keydown", (e) => key(e, true));
|
|
375
|
+
on(input, "keyup", (e) => key(e, false));
|
|
376
|
+
// A change of devicePixelRatio sends the new scale, so the next frame is
|
|
377
|
+
// drawn sharp at the new scale. A change of the size of the page does
|
|
378
|
+
// not resize the window: in Tk a toplevel keeps its own size, and a
|
|
379
|
+
// resize from the platform would stop its geometry propagation.
|
|
380
|
+
// resize() and mount({ size: "fill" }) resize the window.
|
|
381
|
+
const watchScale = () => {
|
|
382
|
+
const m = matchMedia(`(resolution: ${devicePixelRatio}dppx)`);
|
|
383
|
+
m.addEventListener("change", () => { ex.ztk_scale(scaleNow()); watchScale(); }, { once: true, signal });
|
|
384
|
+
};
|
|
385
|
+
watchScale();
|
|
386
|
+
|
|
387
|
+
// Accessibility: hidden elements with ARIA roles over the canvas.
|
|
388
|
+
const tree = document.createElement("div");
|
|
389
|
+
tree.style.cssText = "position:absolute;left:0;top:0;width:0;height:0;overflow:visible;pointer-events:none;";
|
|
390
|
+
canvas.parentElement.appendChild(tree);
|
|
391
|
+
const ARIA = { "button": "button", "check box": "checkbox", "radio button": "radio", "text field": "textbox", "label": "note", "slider": "slider", "group": "group", "window": "dialog" };
|
|
392
|
+
let lastA11y = "";
|
|
393
|
+
const updateA11y = () => {
|
|
394
|
+
const n = ex.ztk_a11y();
|
|
395
|
+
const text = dec.decode(new Uint8Array(ex.memory.buffer, ex.ztk_a11y_ptr(), n));
|
|
396
|
+
if (text === lastA11y) return;
|
|
397
|
+
lastA11y = text;
|
|
398
|
+
tree.replaceChildren(...JSON.parse(text).map((node) => {
|
|
399
|
+
const el = document.createElement("div");
|
|
400
|
+
el.setAttribute("role", ARIA[node.role] || "generic");
|
|
401
|
+
el.setAttribute("aria-label", node.name);
|
|
402
|
+
el.dataset.path = node.path;
|
|
403
|
+
if (node.role === "check box" || node.role === "radio button") el.setAttribute("aria-checked", String(node.selected));
|
|
404
|
+
if (node.disabled) el.setAttribute("aria-disabled", "true");
|
|
405
|
+
el.style.cssText = `position:absolute;left:${node.x}px;top:${node.y}px;width:${node.w}px;height:${node.h}px;opacity:0;`;
|
|
406
|
+
return el;
|
|
407
|
+
}));
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
let raf = 0;
|
|
411
|
+
const loop = (t) => {
|
|
412
|
+
const n = ex.ztk_frame(t);
|
|
413
|
+
if (n >= 0) draw(n);
|
|
414
|
+
raf = requestAnimationFrame(loop);
|
|
415
|
+
};
|
|
416
|
+
raf = requestAnimationFrame(loop);
|
|
417
|
+
const addFile = (name, text) => withBytes(name, (pn, nn) => withBytes(text, (pt, nt) => ex.ztk_add_file(pn, nn, pt, nt)));
|
|
418
|
+
const frame = (t) => {
|
|
419
|
+
if (signal.aborted) return -1;
|
|
420
|
+
const n = ex.ztk_frame(t);
|
|
421
|
+
if (n >= 0) draw(n);
|
|
422
|
+
return n;
|
|
423
|
+
};
|
|
424
|
+
// The window of the script gets a new logical size.
|
|
425
|
+
const resize = (w, h) => ex.ztk_resize(Math.max(1, Math.round(w)), Math.max(1, Math.round(h)), scaleNow());
|
|
426
|
+
// "dark", "light", or "auto" (the color scheme of the page).
|
|
427
|
+
const setTheme = (theme) => {
|
|
428
|
+
forceDark = theme === "dark" ? true : theme === "light" ? false : undefined;
|
|
429
|
+
ex.ztk_dark(forceDark ?? dark.matches);
|
|
430
|
+
};
|
|
431
|
+
const destroy = () => {
|
|
432
|
+
if (signal.aborted) return;
|
|
433
|
+
life.abort();
|
|
434
|
+
cancelAnimationFrame(raf);
|
|
435
|
+
renderer.destroy();
|
|
436
|
+
input.remove();
|
|
437
|
+
tree.remove();
|
|
438
|
+
};
|
|
439
|
+
return { eval: evalScript, exports: ex, frame, tree, addFile, canvas, resize, setTheme, destroy, renderer: renderer.name, signal };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/// Mounts a ztk app on an element. `el` is a canvas, or an element that
|
|
443
|
+
/// gets a new canvas. Options:
|
|
444
|
+
/// script Tcl text to run, after the files.
|
|
445
|
+
/// files { name: text } for `ztk::style load`, for example a style sheet.
|
|
446
|
+
/// theme "auto" (the default: the color scheme of the page), "light", or "dark".
|
|
447
|
+
/// size "auto" (the default: the size of the element at the start,
|
|
448
|
+
/// and then the size the window computes), "fill" (the window
|
|
449
|
+
/// follows the size of the element), or [width, height] in
|
|
450
|
+
/// logical pixels (the canvas shows the window at its CSS size).
|
|
451
|
+
/// renderer "auto" (the default), "webgl2", "cpu", or "webgpu".
|
|
452
|
+
/// scale The device pixels in one logical pixel. The default is devicePixelRatio.
|
|
453
|
+
/// module, wasm, log As for start().
|
|
454
|
+
/// A script error destroys the app and rejects with the error text.
|
|
455
|
+
export async function mount(el, options = {}) {
|
|
456
|
+
if (!el || typeof el.appendChild !== "function") throw new Error("ztk.mount: el must be an element");
|
|
457
|
+
const own = !(el instanceof HTMLCanvasElement);
|
|
458
|
+
const canvas = own ? document.createElement("canvas") : el;
|
|
459
|
+
const { size = "auto", theme = "auto" } = options;
|
|
460
|
+
if (own) {
|
|
461
|
+
// With "fill", the canvas has no part in the layout of the element,
|
|
462
|
+
// so the size of the element comes from the page only.
|
|
463
|
+
canvas.style.cssText = size === "fill" ? "display:block;touch-action:none;position:absolute;left:0;top:0;" : "display:block;touch-action:none;";
|
|
464
|
+
el.appendChild(canvas);
|
|
465
|
+
}
|
|
466
|
+
const opts = { module: options.module, wasm: options.wasm, log: options.log, scale: options.scale, renderer: options.renderer };
|
|
467
|
+
if (theme !== "auto") opts.dark = theme === "dark";
|
|
468
|
+
if (Array.isArray(size)) [opts.width, opts.height] = size;
|
|
469
|
+
else if (size && typeof size === "object") ({ width: opts.width, height: opts.height } = size);
|
|
470
|
+
let app;
|
|
471
|
+
try {
|
|
472
|
+
app = await start(canvas, opts);
|
|
473
|
+
} catch (e) {
|
|
474
|
+
if (own) canvas.remove();
|
|
475
|
+
throw e;
|
|
476
|
+
}
|
|
477
|
+
const destroy = app.destroy;
|
|
478
|
+
let observer = null;
|
|
479
|
+
if (size === "fill" && typeof ResizeObserver !== "undefined") {
|
|
480
|
+
observer = new ResizeObserver(([entry]) => {
|
|
481
|
+
const r = entry.contentRect;
|
|
482
|
+
if (r.width > 0 && r.height > 0) app.resize(r.width, r.height);
|
|
483
|
+
});
|
|
484
|
+
observer.observe(canvas.parentElement);
|
|
485
|
+
}
|
|
486
|
+
app.destroy = () => {
|
|
487
|
+
observer?.disconnect();
|
|
488
|
+
destroy();
|
|
489
|
+
if (own) canvas.remove();
|
|
490
|
+
};
|
|
491
|
+
for (const [name, text] of Object.entries(options.files || {})) app.addFile(name, text);
|
|
492
|
+
if (options.script != null) {
|
|
493
|
+
const r = app.eval(options.script);
|
|
494
|
+
if (!r.ok) {
|
|
495
|
+
app.destroy();
|
|
496
|
+
const err = new Error(r.result);
|
|
497
|
+
err.result = r;
|
|
498
|
+
throw err;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
app.frame(performance.now());
|
|
502
|
+
return app;
|
|
503
|
+
}
|
package/ztk.wasm
ADDED
|
Binary file
|