@wwwares/keycaps 0.0.0-stage → 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/dist/index.js ADDED
@@ -0,0 +1,1236 @@
1
+ import { createContext, forwardRef, useContext, useLayoutEffect, useRef } from "react";
2
+ import { jsx } from "react/jsx-runtime";
3
+ // src/config.ts
4
+ const PROFILES = [
5
+ "cherry",
6
+ "oem",
7
+ "sa",
8
+ "dsa",
9
+ "xda"
10
+ ];
11
+ const MATERIALS = ["pbt", "abs"];
12
+ /** Legends drawn as vector icons rather than text. The order matches the glyph ids in keycap.frag. */
13
+ const LEGEND_ICONS = {
14
+ "⌫": "Backspace",
15
+ "⇥": "Tab",
16
+ "⇪": "Caps Lock",
17
+ "↵": "Enter",
18
+ "⇧": "Shift",
19
+ "␣": "Space",
20
+ "⌃": "Control",
21
+ "⌥": "Alt",
22
+ "◆": "Super",
23
+ "≡": "Menu"
24
+ };
25
+ const DEFAULT_KEYCAP = {
26
+ profile: "cherry",
27
+ row: 3,
28
+ width: 1,
29
+ material: "pbt",
30
+ translucency: 0,
31
+ legend: "",
32
+ legendFont: "Inter, 'Helvetica Neue', Arial, sans-serif",
33
+ legendColor: "",
34
+ colors: [
35
+ "#2fd23b",
36
+ "#5bdb62",
37
+ "#cdf3c9"
38
+ ],
39
+ hue: 0,
40
+ saturation: 1,
41
+ brightness: 1,
42
+ spread: .45,
43
+ swirl: 0,
44
+ swirlScale: .35,
45
+ swirlDetail: 4,
46
+ swirlWarp: 0,
47
+ swirlFlow: .1,
48
+ spin: 0,
49
+ swirlAngle: 70,
50
+ shimmer: 0,
51
+ twinkle: true,
52
+ glitterColor: "",
53
+ pattern: 0,
54
+ shine: 0,
55
+ yellowing: 0,
56
+ angle: 315,
57
+ shadow: 0
58
+ };
59
+ const SWIRL_RECIPES = {
60
+ Clouds: {
61
+ swirl: .55,
62
+ swirlScale: .2,
63
+ swirlDetail: 3,
64
+ swirlWarp: 0,
65
+ swirlFlow: .15,
66
+ spin: .5
67
+ },
68
+ Marble: {
69
+ swirl: .6,
70
+ swirlScale: .45,
71
+ swirlDetail: 5,
72
+ swirlWarp: .55,
73
+ swirlFlow: .05,
74
+ spin: .35
75
+ },
76
+ Liquid: {
77
+ swirl: .75,
78
+ swirlScale: .3,
79
+ swirlDetail: 3,
80
+ swirlWarp: .9,
81
+ swirlFlow: .35,
82
+ spin: .2
83
+ },
84
+ Nebula: {
85
+ swirl: .9,
86
+ swirlScale: .55,
87
+ swirlDetail: 5,
88
+ swirlWarp: .35,
89
+ swirlFlow: .2,
90
+ spin: .8
91
+ },
92
+ Blobs: {
93
+ swirl: .7,
94
+ swirlScale: .1,
95
+ swirlDetail: 1,
96
+ swirlWarp: .2,
97
+ swirlFlow: .3,
98
+ spin: .6
99
+ }
100
+ };
101
+ const pbt = (colors) => ({
102
+ material: "pbt",
103
+ colors
104
+ });
105
+ const abs = (colors) => ({
106
+ material: "abs",
107
+ colors
108
+ });
109
+ const jelly = (colors) => ({
110
+ material: "abs",
111
+ translucency: 1,
112
+ colors
113
+ });
114
+ const swirled = (colors, recipe, extra) => ({
115
+ material: "abs",
116
+ translucency: .3,
117
+ colors,
118
+ ...SWIRL_RECIPES[recipe],
119
+ ...extra
120
+ });
121
+ const KEYCAP_PRESETS = {
122
+ mint: pbt([
123
+ "#2fd23b",
124
+ "#5bdb62",
125
+ "#cdf3c9"
126
+ ]),
127
+ ember: pbt([
128
+ "#ff5a1f",
129
+ "#ff8a3d",
130
+ "#ffd9b8"
131
+ ]),
132
+ sky: pbt([
133
+ "#1e8bff",
134
+ "#4fa8ff",
135
+ "#cfe6ff"
136
+ ]),
137
+ lilac: pbt([
138
+ "#8b5cf6",
139
+ "#a98bfa",
140
+ "#e6dcff"
141
+ ]),
142
+ rose: pbt([
143
+ "#f43f7a",
144
+ "#f7779f",
145
+ "#ffd6e3"
146
+ ]),
147
+ lemon: pbt([
148
+ "#f2b705",
149
+ "#ffd43b",
150
+ "#fff4c2"
151
+ ]),
152
+ bone: pbt([
153
+ "#e9e3d6",
154
+ "#f3efe6",
155
+ "#ffffff"
156
+ ]),
157
+ graphite: abs([
158
+ "#4b5260",
159
+ "#374151",
160
+ "#1b1f27"
161
+ ]),
162
+ obsidian: abs([
163
+ "#26262c",
164
+ "#16161c",
165
+ "#000000"
166
+ ]),
167
+ cherry: abs([
168
+ "#ff4d5e",
169
+ "#d0102a",
170
+ "#4a0010"
171
+ ]),
172
+ ocean: abs([
173
+ "#3b82f6",
174
+ "#1d4ed8",
175
+ "#0b1f5c"
176
+ ]),
177
+ aquaJelly: jelly([
178
+ "#1460d6",
179
+ "#3a92fa",
180
+ "#a6e6ff"
181
+ ]),
182
+ grapeJelly: jelly([
183
+ "#4e169a",
184
+ "#9a5cf0",
185
+ "#e6ceff"
186
+ ]),
187
+ limeJelly: jelly([
188
+ "#3a8c00",
189
+ "#8ad81c",
190
+ "#eaffa8"
191
+ ]),
192
+ tangerineJelly: jelly([
193
+ "#c24a00",
194
+ "#ff8a1f",
195
+ "#ffe0a8"
196
+ ]),
197
+ aurora: swirled([
198
+ "#13c8a0",
199
+ "#3b82f6",
200
+ "#c4b5fd"
201
+ ], "Nebula"),
202
+ sunset: swirled([
203
+ "#ff3d77",
204
+ "#ff8a3d",
205
+ "#ffe08a"
206
+ ], "Liquid"),
207
+ marble: swirled([
208
+ "#f3f0ea",
209
+ "#c9c4bb",
210
+ "#3a3a3f"
211
+ ], "Marble"),
212
+ galaxy: swirled([
213
+ "#120a2a",
214
+ "#4b2bd1",
215
+ "#e3d6ff"
216
+ ], "Nebula", { shimmer: .35 })
217
+ };
218
+ /** Fills in defaults under the preset and the given fields. Fields set to `undefined` are ignored. */
219
+ function resolveConfig({ preset, frozen, ...fields }) {
220
+ const defined = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== void 0));
221
+ return {
222
+ ...DEFAULT_KEYCAP,
223
+ ...preset && KEYCAP_PRESETS[preset],
224
+ ...defined
225
+ };
226
+ }
227
+ const isAnimated = (c) => c.swirl > 0 && (c.spin !== 0 || c.swirlFlow > 0) || c.shimmer > 0 && c.twinkle;
228
+ // src/color.ts
229
+ const clamp = (v, lo = 0, hi = 1) => Math.min(hi, Math.max(lo, v));
230
+ /** Parses `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()` into 0-255 channels. Alpha is dropped. */
231
+ function parseColor(input) {
232
+ const s = input.trim();
233
+ if (s.startsWith("#")) {
234
+ let hex = s.slice(1);
235
+ if (hex.length === 3 || hex.length === 4) hex = Array.from(hex.slice(0, 3), (c) => c + c).join("");
236
+ const n = parseInt(hex.slice(0, 6), 16);
237
+ return Number.isNaN(n) || hex.length < 6 ? null : [
238
+ n >> 16 & 255,
239
+ n >> 8 & 255,
240
+ n & 255
241
+ ];
242
+ }
243
+ const m = s.match(/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i);
244
+ return m ? [
245
+ +m[1],
246
+ +m[2],
247
+ +m[3]
248
+ ] : null;
249
+ }
250
+ const toHex = (rgb) => "#" + rgb.map((c) => Math.round(clamp(c, 0, 255)).toString(16).padStart(2, "0")).join("");
251
+ const lerp = (a, b, t) => [
252
+ a[0] + (b[0] - a[0]) * t,
253
+ a[1] + (b[1] - a[1]) * t,
254
+ a[2] + (b[2] - a[2]) * t
255
+ ];
256
+ /** Hue in degrees, saturation and lightness 0 to 1. */
257
+ function rgbToHsl([r, g, b]) {
258
+ r /= 255;
259
+ g /= 255;
260
+ b /= 255;
261
+ const max = Math.max(r, g, b);
262
+ const min = Math.min(r, g, b);
263
+ const l = (max + min) / 2;
264
+ if (max === min) return [
265
+ 0,
266
+ 0,
267
+ l
268
+ ];
269
+ const d = max - min;
270
+ const s = l > .5 ? d / (2 - max - min) : d / (max + min);
271
+ return [
272
+ (max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4) * 60,
273
+ s,
274
+ l
275
+ ];
276
+ }
277
+ function hslToRgb([h, s, l]) {
278
+ h = (h % 360 + 360) % 360;
279
+ const k = (n) => (n + h / 30) % 12;
280
+ const a = s * Math.min(l, 1 - l);
281
+ const f = (n) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
282
+ return [
283
+ f(0) * 255,
284
+ f(8) * 255,
285
+ f(4) * 255
286
+ ];
287
+ }
288
+ const WHITE = [
289
+ 255,
290
+ 255,
291
+ 255
292
+ ];
293
+ /** A single colour becomes a ramp of a deeper shade, the colour itself and a pale tint. */
294
+ function expandColor(color) {
295
+ const rgb = parseColor(color);
296
+ if (!rgb) return [
297
+ color,
298
+ color,
299
+ color
300
+ ];
301
+ const [h, s, l] = rgbToHsl(rgb);
302
+ return [
303
+ toHex(hslToRgb([
304
+ h,
305
+ clamp(s * 1.06),
306
+ clamp(l * .9)
307
+ ])),
308
+ toHex(rgb),
309
+ toHex(lerp(hslToRgb([
310
+ h + 8,
311
+ clamp(s * 1.1),
312
+ l
313
+ ]), WHITE, .66))
314
+ ];
315
+ }
316
+ const GREY = [
317
+ 128,
318
+ 128,
319
+ 128
320
+ ];
321
+ /** The dye ramp as two to four RGB stops, with hue, saturation and brightness applied. */
322
+ function resolveStops(c) {
323
+ const colors = c.colors.length ? c.colors.slice(0, 4) : DEFAULT_KEYCAP.colors;
324
+ return (colors.length === 1 ? expandColor(colors[0]) : colors).map((color) => {
325
+ const rgb = parseColor(color) ?? GREY;
326
+ if (c.hue === 0 && c.saturation === 1 && c.brightness === 1) return rgb;
327
+ const [h, s, l] = rgbToHsl(rgb);
328
+ return hslToRgb([
329
+ h + c.hue,
330
+ clamp(s * c.saturation),
331
+ l
332
+ ]).map((v) => v * c.brightness);
333
+ });
334
+ }
335
+ // src/math.ts
336
+ const IDENTITY_QUAT = [
337
+ 0,
338
+ 0,
339
+ 0,
340
+ 1
341
+ ];
342
+ const IDENTITY_MAT3 = new Float32Array([
343
+ 1,
344
+ 0,
345
+ 0,
346
+ 0,
347
+ 1,
348
+ 0,
349
+ 0,
350
+ 0,
351
+ 1
352
+ ]);
353
+ /** Mulberry32: a small seeded PRNG returning values in [0, 1). */
354
+ function mulberry32(seed) {
355
+ let s = seed >>> 0;
356
+ return () => {
357
+ s = s + 1831565813 >>> 0;
358
+ let n = s;
359
+ n = Math.imul(n ^ n >>> 15, n | 1);
360
+ n ^= n + Math.imul(n ^ n >>> 7, n | 61);
361
+ return ((n ^ n >>> 14) >>> 0) / 4294967296;
362
+ };
363
+ }
364
+ const quatMul = (a, b) => [
365
+ a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
366
+ a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
367
+ a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
368
+ a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]
369
+ ];
370
+ function quatNormalize(q) {
371
+ const len = Math.hypot(...q) || 1;
372
+ return [
373
+ q[0] / len,
374
+ q[1] / len,
375
+ q[2] / len,
376
+ q[3] / len
377
+ ];
378
+ }
379
+ /** Rotation by `angle` radians about the axis (x, y, z), which need not be normalised. */
380
+ function quatFromAxisAngle(x, y, z, angle) {
381
+ const len = Math.hypot(x, y, z);
382
+ if (len < 1e-9 || Math.abs(angle) < 1e-9) return IDENTITY_QUAT;
383
+ const s = Math.sin(angle / 2) / len;
384
+ return [
385
+ x * s,
386
+ y * s,
387
+ z * s,
388
+ Math.cos(angle / 2)
389
+ ];
390
+ }
391
+ /** Column-major matrix of the inverse rotation, since the shader turns the camera rays rather than the cap. */
392
+ function quatToMat3([x, y, z, w]) {
393
+ x = -x;
394
+ y = -y;
395
+ z = -z;
396
+ return new Float32Array([
397
+ 1 - 2 * (y * y + z * z),
398
+ 2 * (x * y + z * w),
399
+ 2 * (x * z - y * w),
400
+ 2 * (x * y - z * w),
401
+ 1 - 2 * (x * x + z * z),
402
+ 2 * (y * z + x * w),
403
+ 2 * (x * z + y * w),
404
+ 2 * (y * z - x * w),
405
+ 1 - 2 * (x * x + y * y)
406
+ ]);
407
+ }
408
+ /** Column-major rotation by `angle` radians about the unit axis (x, y, z). */
409
+ function axisAngleMat3(angle, [x, y, z]) {
410
+ const c = Math.cos(angle);
411
+ const s = Math.sin(angle);
412
+ const t = 1 - c;
413
+ return new Float32Array([
414
+ c + x * x * t,
415
+ y * x * t + z * s,
416
+ z * x * t - y * s,
417
+ x * y * t - z * s,
418
+ c + y * y * t,
419
+ z * y * t + x * s,
420
+ x * z * t + y * s,
421
+ y * z * t - x * s,
422
+ c + z * z * t
423
+ ]);
424
+ }
425
+ function normalize(v) {
426
+ const len = Math.hypot(...v);
427
+ return [
428
+ v[0] / len,
429
+ v[1] / len,
430
+ v[2] / len
431
+ ];
432
+ }
433
+ // src/params.ts
434
+ const SILVER = [
435
+ 196,
436
+ 201,
437
+ 210
438
+ ];
439
+ const ICONS = Object.keys(LEGEND_ICONS);
440
+ const toLinear = (c) => [
441
+ (c[0] / 255) ** 2.2,
442
+ (c[1] / 255) ** 2.2,
443
+ (c[2] / 255) ** 2.2
444
+ ];
445
+ /** Near-black on light caps, warm white on dark ones. */
446
+ const contrastTone = ([r, g, b]) => .299 * r + .587 * g + .114 * b > 150 ? [
447
+ 33,
448
+ 34,
449
+ 38
450
+ ] : [
451
+ 244,
452
+ 242,
453
+ 236
454
+ ];
455
+ function prepare(options) {
456
+ const c = resolveConfig(options);
457
+ const stops = resolveStops(c);
458
+ const n = stops.length;
459
+ const exp = Math.log(clamp(c.spread, .05, .95)) / Math.log(.5);
460
+ const at = (i) => (i / (n - 1)) ** exp;
461
+ const stop = (i) => stops[Math.min(i, n - 1)];
462
+ const rand = mulberry32(Math.floor(c.pattern) * 2654435761);
463
+ const legendColor = c.legendColor && parseColor(c.legendColor) || contrastTone(stops[Math.min(1, n - 1)]);
464
+ const legend = c.legend.trim();
465
+ const legendIcon = ICONS.indexOf(legend) + 1;
466
+ const flake = c.glitterColor && parseColor(c.glitterColor) || (legend ? legendColor : SILVER);
467
+ const angle = c.swirlAngle * Math.PI / 180;
468
+ const dir = c.spin < 0 ? -1 : 1;
469
+ return {
470
+ config: c,
471
+ stops: [
472
+ stop(0),
473
+ stop(1),
474
+ stop(2),
475
+ stop(3)
476
+ ],
477
+ pos: n === 4 ? [
478
+ 0,
479
+ at(1),
480
+ at(2),
481
+ 1
482
+ ] : n === 3 ? [
483
+ 0,
484
+ at(1),
485
+ 1,
486
+ 1
487
+ ] : [
488
+ 0,
489
+ 1,
490
+ 1,
491
+ 1
492
+ ],
493
+ pattern: c.pattern ? [
494
+ rand() * 60,
495
+ rand() * 60,
496
+ rand() * 60
497
+ ] : [
498
+ 0,
499
+ 0,
500
+ 0
501
+ ],
502
+ profile: Math.max(0, PROFILES.indexOf(c.profile)),
503
+ legendIcon,
504
+ legendText: legendIcon ? "" : legend,
505
+ legendHeight: [...legend].length > 1 ? 6.5 : 11,
506
+ legendColor,
507
+ flakeColor: toLinear(flake),
508
+ axis: normalize([
509
+ .45 * Math.cos(angle),
510
+ 1,
511
+ .45 * Math.sin(angle)
512
+ ]),
513
+ flowDir: normalize([
514
+ Math.cos(angle) * dir,
515
+ .2,
516
+ Math.sin(angle) * dir
517
+ ]),
518
+ animated: !options.frozen && isAnimated(c)
519
+ };
520
+ }
521
+ /**
522
+ * Width-to-height ratio of a cap's tile. A keycap of a given `size` is `size` tall and
523
+ * `size * keycapAspect(width)` wide.
524
+ */
525
+ function keycapAspect(width) {
526
+ const units = Math.max(width, 1);
527
+ const mm = units * 19.05 - .85;
528
+ const yaw = .42 / Math.sqrt(units);
529
+ return Math.max(1, (mm * Math.cos(yaw) + 18.2 * Math.sin(yaw)) / (24 * (1 + .06 * (units - 1))));
530
+ }
531
+ // src/keycap.frag
532
+ var keycap_default = "precision highp float;\nuniform vec2 u_size, u_origin, u_L;\nuniform vec3 u_c0, u_c1, u_c2, u_c3, u_pattern, u_flowDir;\nuniform vec4 u_pos;\nuniform float u_time, u_swirl, u_sScale, u_sDetail, u_sWarp, u_sFlow, u_shine, u_yellow, u_mat, u_shimmer, u_twinkle;\nuniform float u_shadow, u_trans, u_prof, u_row, u_kw, u_eng, u_legOn, u_legW, u_legH;\nuniform vec3 u_legCol, u_flakeCol;\nuniform vec4 u_leg;\nuniform sampler2D u_legTex;\nuniform mat3 u_drag, u_auto;\n\nfloat hash3(vec3 p){ p = fract(p * 0.3183099 + 0.1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); }\nfloat noise(vec3 x){\n vec3 i = floor(x); vec3 f = fract(x); f = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix(hash3(i), hash3(i + vec3(1,0,0)), f.x), mix(hash3(i + vec3(0,1,0)), hash3(i + vec3(1,1,0)), f.x), f.y),\n mix(mix(hash3(i + vec3(0,0,1)), hash3(i + vec3(1,0,1)), f.x), mix(hash3(i + vec3(0,1,1)), hash3(i + vec3(1,1,1)), f.x), f.y), f.z);\n}\nfloat fbm(vec3 p){ float a = 0.5, s = 0.0; for (int i = 0; i < 4; i++){ s += a * noise(p); p = p * 2.03 + vec3(1.7, 9.2, 3.1); a *= 0.5; } return s; }\nfloat fbmN(vec3 p, float oct){\n float a = 0.5, s = 0.0, norm = 0.0;\n for (int i = 0; i < 5; i++){\n if (float(i) >= oct) break;\n s += a * noise(p); norm += a; p = p * 2.03 + vec3(1.7, 9.2, 3.1); a *= 0.5;\n }\n return s / norm;\n}\n\nvec3 ramp(float t){\n t = clamp(t, 0.0, 1.0);\n if (t <= u_pos.y) return mix(u_c0, u_c1, clamp((t - u_pos.x) / max(u_pos.y - u_pos.x, 1e-4), 0.0, 1.0));\n if (t <= u_pos.z) return mix(u_c1, u_c2, clamp((t - u_pos.y) / max(u_pos.z - u_pos.y, 1e-4), 0.0, 1.0));\n return mix(u_c2, u_c3, clamp((t - u_pos.z) / max(u_pos.w - u_pos.z, 1e-4), 0.0, 1.0));\n}\n\n\n// A keycap as a signed distance field, in millimetres. Origin at the centre of the base, y up,\n// +z toward the typist. Profiles set height per row, top size, tilt, edge rounding and dish;\n// u_kw is the width in units (1u = 19.05mm pitch). Dimensions are close approximations.\nfloat K_h, K_tilt, K_round, K_depth, K_sph, K_back;\nvec2 K_base, K_top;\n\nvoid keySetup(){\n float row = clamp(u_row, 1.0, 4.0);\n vec4 H; vec4 T; vec2 top;\n if (u_prof < 0.5) { // Cherry: low, cylindrical, sculpted\n H = vec4(9.4, 7.9, 7.4, 8.2); T = vec4(-0.16, -0.08, -0.02, 0.10);\n K_round = 0.6; K_depth = 0.6; K_sph = 0.0; top = vec2(6.35, 6.9); K_back = 0.45;\n } else if (u_prof < 1.5) { // OEM: taller, cylindrical, sculpted\n H = vec4(11.6, 9.8, 9.2, 9.8); T = vec4(-0.2, -0.1, -0.03, 0.12);\n K_round = 0.5; K_depth = 0.5; K_sph = 0.0; top = vec2(6.3, 7.0); K_back = 0.6;\n } else if (u_prof < 2.5) { // SA: tall, spherical, very round\n H = vec4(14.9, 12.9, 11.9, 13.0); T = vec4(-0.24, -0.1, 0.0, 0.14);\n K_round = 1.8; K_depth = 1.2; K_sph = 1.0; top = vec2(6.1, 6.1); K_back = 0.3;\n } else if (u_prof < 3.5) { // DSA: low, uniform, spherical\n H = vec4(7.6); T = vec4(0.0);\n K_round = 1.1; K_depth = 0.9; K_sph = 1.0; top = vec2(6.35, 6.35); K_back = 0.0;\n } else { // XDA: uniform, wide flat top, shallow spherical\n H = vec4(9.1); T = vec4(0.0);\n K_round = 1.0; K_depth = 0.7; K_sph = 1.0; top = vec2(7.6, 7.6); K_back = 0.0;\n }\n K_h = row < 1.5 ? H.x : row < 2.5 ? H.y : row < 3.5 ? H.z : H.w;\n K_tilt = row < 1.5 ? T.x : row < 2.5 ? T.y : row < 3.5 ? T.z : T.w;\n float W = max(u_kw, 1.0) * 19.05 - 0.85;\n K_base = vec2(W * 0.5, 9.1);\n K_top = vec2(K_base.x - (9.1 - top.x), top.y);\n}\n\nfloat smax(float a, float b, float k){ float h = clamp(0.5 + 0.5 * (a - b) / k, 0.0, 1.0); return mix(b, a, h) + k * h * (1.0 - h); }\n\n/** Outer surface: tapered rounded box, rounded top edge, dish. No base, so the inside stays open. */\nfloat keyOuter(vec3 p){\n float ty = p.y - p.z * K_tilt;\n float t = clamp(p.y / K_h, 0.0, 1.0);\n vec2 hs = mix(K_base, K_top, t);\n float rr = mix(0.8, 1.4 + K_round * 0.5, t);\n vec2 c = vec2(0.0, -K_back * t);\n vec2 q = abs(p.xz - c) - hs + rr;\n float side = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - rr;\n float d = smax(side, ty - K_h, K_round);\n float dish;\n if (K_sph > 0.5) {\n // spherical dish, stretched into a capsule along x on wider keys\n float R = (K_top.y * K_top.y + K_depth * K_depth) / (2.0 * K_depth);\n vec3 dp = vec3(max(abs(p.x) - (K_top.x - K_top.y), 0.0), ty - (K_h + R - K_depth), p.z + K_back);\n dish = R - length(dp);\n } else {\n // cylindrical dish: axis front-to-back, concave left-to-right\n float R = (K_top.x * K_top.x + K_depth * K_depth) / (2.0 * K_depth);\n dish = R - length(vec2(p.x, ty - (K_h + R - K_depth)));\n }\n return smax(d, dish, 0.4);\n}\n\nfloat crossCut(vec2 p){ return min(max(abs(p.x) - 2.05, abs(p.y) - 0.62), max(abs(p.x) - 0.62, abs(p.y) - 2.05)); }\n\n/** MX stem: a 5.5mm post hanging from the inside of the top, with the + socket cut into it. */\nfloat stemAt(vec3 p){\n // the post meets the cavity ceiling, which follows the row tilt, so it never pokes through the dish\n float ty = p.y - p.z * K_tilt;\n float s = max(length(p.xz) - 2.75, max(ty - (K_h - K_depth - 1.3), 0.8 - p.y));\n return max(s, -max(crossCut(p.xz), p.y - 4.6));\n}\n\n/** Inside of the shell: the walls moved in 1.3mm, with a flat ceiling below the deepest point of the dish. */\nfloat keyCavity(vec3 p){\n float ty = p.y - p.z * K_tilt;\n float t = clamp(p.y / K_h, 0.0, 1.0);\n vec2 hs = mix(K_base, K_top, t) - 1.3;\n float rr = max(mix(0.8, 1.4 + K_round * 0.5, t) - 1.3, 0.3);\n vec2 q = abs(p.xz - vec2(0.0, -K_back * t)) - hs + rr;\n float side = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - rr;\n return smax(side, ty - (K_h - K_depth - 1.5), 0.6);\n}\n\n// Engraving glyphs, in mm on the dish. x right, y toward the back of the key (reads as \"up\").\nfloat sdSeg(vec2 p, vec2 a, vec2 b){ vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0); return length(pa - ba * h); }\n/** Closed outline through 7 points. */\nfloat sdPoly7(vec2 p, vec2 a, vec2 b, vec2 c, vec2 d, vec2 e, vec2 f, vec2 g){\n return min(min(min(sdSeg(p, a, b), sdSeg(p, b, c)), min(sdSeg(p, c, d), sdSeg(p, d, e))), min(min(sdSeg(p, e, f), sdSeg(p, f, g)), sdSeg(p, g, a)));\n}\n/** Vector icons for modifier legends, ~6mm across. Index matches LEGEND_ICONS + 1. */\nfloat glyph(vec2 p){\n float id = u_eng, w = 0.36;\n if (id < 0.5) return 1e3;\n if (id < 1.5) // backspace\n return min(sdSeg(p, vec2(-2.8, 0.0), vec2(2.8, 0.0)), min(sdSeg(p, vec2(-2.8, 0.0), vec2(-1.4, 1.35)), sdSeg(p, vec2(-2.8, 0.0), vec2(-1.4, -1.35)))) - w;\n if (id < 2.5) // tab\n return min(min(sdSeg(p, vec2(-2.8, 0.0), vec2(2.2, 0.0)), sdSeg(p, vec2(2.8, -1.5), vec2(2.8, 1.5))),\n min(sdSeg(p, vec2(2.2, 0.0), vec2(0.9, 1.25)), sdSeg(p, vec2(2.2, 0.0), vec2(0.9, -1.25)))) - w;\n if (id < 3.5) // caps lock\n return min(sdPoly7(p, vec2(0.0, 2.7), vec2(-2.4, 0.3), vec2(-1.1, 0.3), vec2(-1.1, -1.0), vec2(1.1, -1.0), vec2(1.1, 0.3), vec2(2.4, 0.3)),\n sdSeg(p, vec2(-1.1, -2.3), vec2(1.1, -2.3))) - w * 0.85;\n if (id < 4.5) // enter\n return min(min(sdSeg(p, vec2(2.5, 2.3), vec2(2.5, -0.6)), sdSeg(p, vec2(2.5, -0.6), vec2(-2.5, -0.6))),\n min(sdSeg(p, vec2(-2.5, -0.6), vec2(-1.25, 0.65)), sdSeg(p, vec2(-2.5, -0.6), vec2(-1.25, -1.85)))) - w;\n if (id < 5.5) // shift\n return sdPoly7(p, vec2(0.0, 2.8), vec2(-2.6, 0.2), vec2(-1.2, 0.2), vec2(-1.2, -2.4), vec2(1.2, -2.4), vec2(1.2, 0.2), vec2(2.6, 0.2)) - w * 0.85;\n if (id < 6.5) // space\n return min(sdSeg(p, vec2(-3.6, -0.6), vec2(3.6, -0.6)),\n min(sdSeg(p, vec2(-3.6, -0.6), vec2(-3.6, 0.8)), sdSeg(p, vec2(3.6, -0.6), vec2(3.6, 0.8)))) - w;\n if (id < 7.5) // control\n return min(sdSeg(p, vec2(-2.2, -0.8), vec2(0.0, 1.4)), sdSeg(p, vec2(0.0, 1.4), vec2(2.2, -0.8))) - w;\n if (id < 8.5) // alt / option\n return min(min(sdSeg(p, vec2(-2.8, 1.4), vec2(-1.0, 1.4)), sdSeg(p, vec2(-1.0, 1.4), vec2(1.0, -1.4))),\n min(sdSeg(p, vec2(1.0, -1.4), vec2(2.8, -1.4)), sdSeg(p, vec2(0.7, 1.4), vec2(2.8, 1.4)))) - w;\n if (id < 9.5) { vec2 q = abs(p); return (q.x + q.y - 2.6) * 0.7071; } // super\n return min(sdSeg(p, vec2(-2.4, 1.5), vec2(2.4, 1.5)), // menu\n min(sdSeg(p, vec2(-2.4, 0.0), vec2(2.4, 0.0)), sdSeg(p, vec2(-2.4, -1.5), vec2(2.4, -1.5)))) - w;\n}\nvec2 glyphUV(vec3 p){ return vec2(p.x, -(p.z + K_back)); }\n\n// Text legends come from a signed-distance atlas: each cell is 4:1, LEG_H mm tall at full size,\n// distances stored as 128 + 8 * px. u_legH is the cell height in mm (letters big, words smaller,\n// like real sets); long words shrink further to fit the key's top.\nfloat legendSD(vec2 g){\n float H = u_legH * min(1.0, (2.0 * K_top.x - 4.0) / (u_legW * u_legH));\n vec2 uv = vec2(g.x / (4.0 * H) + 0.5, 0.5 - g.y / H);\n if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return 2.0;\n float b = texture2D(u_legTex, u_leg.xy + uv * u_leg.zw).a;\n return (b * 255.0 - 128.0) / 8.0 * (H / 64.0);\n}\nbool lettered(){ return u_eng > 0.5 || u_legOn > 0.5; }\n/** Distance to the legend's edge at a point on the key; icons scaled up a touch to read at small sizes. */\nfloat legendDist(vec3 p){ vec2 g = glyphUV(p); return u_legOn > 0.5 ? legendSD(g) : glyph(g / 1.2) * 1.2; }\n\nfloat sdKey(vec3 p){\n // The cavity and stems sit inside the outer hull, so away from it the hull is the distance and\n // most march steps skip the rest.\n float hull = max(keyOuter(p), -p.y);\n if (hull > 0.5) return hull;\n float d = max(hull, -keyCavity(p)); // hollow shell, open at the bottom\n d = min(d, stemAt(p));\n if (u_kw >= 1.99) { // stabilizer stems on 2u and up\n float sx = u_kw >= 6.0 ? 50.0 : 11.9;\n d = min(d, stemAt(vec3(abs(p.x) - sx, p.y, p.z)));\n }\n return d;\n}\n\nvec3 keyNormal(vec3 p){\n const vec2 k = vec2(1.0, -1.0);\n float e = 0.02;\n return normalize(k.xyy * sdKey(p + k.xyy * e) + k.yyx * sdKey(p + k.yyx * e) +\n k.yxy * sdKey(p + k.yxy * e) + k.xxx * sdKey(p + k.xxx * e));\n}\n\n\nvec3 acesK(vec3 x){ return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); }\n\nvoid main(){\n keySetup();\n vec2 frag = gl_FragCoord.xy - u_origin;\n // Aspect-correct tile coordinates: y in -1..1, x in -aspect..aspect.\n float aspect = u_size.x / u_size.y;\n vec2 p = (frag / u_size.y) * 2.0 - vec2(aspect, 1.0);\n float px = 2.0 / u_size.y;\n\n // Fixed 3/4 product-shot camera, orthographic, framed to the profile's height.\n float kw = max(u_kw, 1.0);\n float yaw = 0.42 / sqrt(kw), pitch = 0.58; // wider keys are seen more from the front\n vec3 toCam = vec3(sin(yaw) * cos(pitch), sin(pitch), cos(yaw) * cos(pitch));\n vec3 rgt = normalize(cross(-toCam, vec3(0.0, 1.0, 0.0)));\n vec3 upv = cross(rgt, -toCam);\n vec3 target = vec3(0.0, K_h * 0.48, 0.0);\n float S = (9.6 + K_h * 0.54) * (1.0 + 0.06 * (kw - 1.0));\n // Rays are built in view space and turned by the drag, so the cap turns under fixed lights.\n vec3 rov = u_drag * vec3(p.x * S, p.y * S, 40.0);\n vec3 rdv = u_drag * vec3(0.0, 0.0, -1.0);\n vec3 ro = target + rgt * rov.x + upv * rov.y + toCam * rov.z;\n vec3 rd = normalize(rgt * rdv.x + upv * rdv.y + toCam * rdv.z);\n\n float pxW = px * S;\n // The key's bounding box, padded for the anti-aliased edge. Rays that miss it, like those in the\n // tile's empty corners, skip the march, and the rest stop where they leave it.\n vec3 pad = vec3(0.5 + pxW * 2.0);\n vec3 boxLo = vec3(-K_base.x, 0.0, -K_base.y - K_back) - pad;\n vec3 boxHi = vec3(K_base.x, K_h + abs(K_tilt) * (K_base.y + K_back), K_base.y) + pad;\n vec3 inv = 1.0 / mix(rd, vec3(1e-6), step(abs(rd), vec3(1e-6)));\n vec3 s0 = (boxLo - ro) * inv, s1 = (boxHi - ro) * inv;\n vec3 sNear = min(s0, s1), sFar = max(s0, s1);\n float tExit = min(min(sFar.x, sFar.y), sFar.z);\n float tEnd = max(max(sNear.x, sNear.y), sNear.z) > tExit ? -1.0 : tExit;\n float t = max(40.0 - K_base.x - 12.0, 0.0), dmin = 1e9, tmin = t;\n bool hit = false;\n for (int i = 0; i < 120; i++) {\n if (t > tEnd) break;\n float d = sdKey(ro + rd * t) * 0.85;\n if (d < dmin) { dmin = d; tmin = t; }\n if (d < 0.004) { hit = true; break; }\n t += max(d, 0.01);\n }\n if (!hit && dmin < pxW * 2.0) {\n // Near miss: re-sample around the closest approach for a clean anti-aliased silhouette.\n float t0 = tmin;\n for (int k = 0; k < 9; k++) {\n float tt = t0 + (float(k) - 4.0) * 0.25;\n float d = sdKey(ro + rd * tt) * 0.85;\n if (d < dmin) { dmin = d; tmin = tt; }\n }\n }\n float cover = hit ? 1.0 : clamp(1.0 - dmin / (pxW * 0.8), 0.0, 1.0);\n\n // Soft contact shadow on an invisible floor, in screen space so it stays put while dragging.\n vec2 sc = (p - vec2(0.02, -0.36)) / vec2(0.88 * aspect, 0.36);\n // clear plastic lets light through, so it casts a lighter shadow\n float shadowA = (1.0 - smoothstep(0.35, 1.0, length(sc))) * 0.6 * u_shadow * (1.0 - 0.7 * clamp(u_trans, 0.0, 1.0));\n if (cover <= 0.0) { gl_FragColor = vec4(0.0, 0.0, 0.0, shadowA); return; }\n\n vec3 pos = ro + rd * (hit ? t : tmin);\n vec3 nTrue = keyNormal(pos);\n vec3 nw = nTrue;\n // Silhouette pixels that just miss, and the thin bottom rim, take a side-like normal.\n if (!hit || pos.y < 0.3) nw = normalize(vec3(nw.x, max(nw.y, 0.05), nw.z));\n // View-space normal (undoing the drag) so lights and studio stay fixed to the camera.\n vec3 n = vec3(dot(nw, rgt), dot(nw, upv), dot(nw, toCam)) * u_drag;\n vec3 V = vec3(0.0, 0.0, 1.0);\n vec3 upW = vec3(0.0, cos(pitch), sin(pitch)); // the room's \"up\", fixed to the camera\n float ao = clamp(0.35 + 0.65 * sdKey(pos + nTrue * 0.8) / 0.8, 0.0, 1.0);\n ao *= clamp(0.3 + 0.7 * sdKey(pos + nTrue * 2.2) / 2.2, 0.0, 1.0);\n\n // Colour: the dye, swirled through the plastic.\n float swirlT = 0.0;\n if (u_swirl > 0.0) {\n vec3 sp = u_auto * (pos / 4.5) * (0.6 + u_sScale * 3.4) + u_pattern + u_flowDir * (u_time * u_sFlow * 0.4);\n if (u_sWarp > 0.0) {\n vec3 wv = vec3(fbmN(sp, 3.0), fbmN(sp + vec3(5.2, 1.3, 2.8), 3.0), fbmN(sp + vec3(1.7, 9.2, 4.1), 3.0)) - 0.5;\n sp += wv * u_sWarp * 3.0;\n }\n swirlT = u_swirl * (fbmN(sp, u_sDetail) - 0.5) * 2.0;\n }\n vec3 dye = ramp(0.42 + swirlT);\n // Doubleshot legend: a second plastic moulded through the cap, flush with the top. It's dyed\n // differently but is the same material, so yellowing, shine and texture below apply to it too.\n // Anti-aliased over about a pixel so the edge doesn't sparkle.\n float legend = 0.0;\n if (lettered() && pos.y > K_h - 2.5) legend = 1.0 - smoothstep(-pxW * 0.6, pxW * 0.6, legendDist(pos));\n dye = mix(dye, u_legCol, legend);\n // Yellowing: old ABS and resin drift toward amber.\n // (dark plastics barely show it)\n dye = mix(dye, dye * vec3(1.0, 0.88, 0.58) + vec3(0.07, 0.045, 0.0), u_yellow * (0.25 + 0.75 * smoothstep(0.1, 0.6, dot(dye, vec3(0.299, 0.587, 0.114)))));\n\n // Wear: a polished oval where the fingertip rests, centred on the dish, a touch toward the\n // front, with a soft ragged edge. Its size is fixed; more wear makes it more pronounced.\n // Scratches come in at high wear.\n float topness = smoothstep(0.55, 0.9, nw.y) * step(K_h - 1.0, pos.y);\n float shine = 0.0, lines = 0.0;\n if (u_shine > 0.0) {\n vec3 wp = pos * 0.32 + u_pattern * 0.37;\n vec2 tg = glyphUV(pos);\n vec2 off = (u_pattern.xy / 60.0 - 0.5) * 1.4 + vec2(0.0, -0.7); // each key's own spot\n float wide = u_kw >= 6.0 ? 4.0 : 1.0 + 0.2 * (min(u_kw, 2.75) - 1.0); // longer on long keys\n vec2 rad = vec2(4.0, 3.5) * vec2(wide, 1.0);\n float edge = (fbm(vec3(tg * 0.45, 2.0) + u_pattern) - 0.5) * 0.5;\n float blob = 1.0 - smoothstep(0.45, 1.05, length((tg - off) / rad) + edge);\n shine = topness * blob * u_shine;\n float ridge = abs(noise(vec3(pos.x * 2.4, pos.z * 0.5, pos.y) + u_pattern.zxy) - 0.5);\n lines = (1.0 - smoothstep(0.0, 0.02 + px * 1.5, ridge)) * smoothstep(0.4, 0.65, fbm(wp * 2.0 + 7.7))\n * topness * clamp(u_shine * 1.4 - 0.4, 0.0, 1.0) * 0.4 * (0.02 / (0.02 + 1.5 * px));\n vec3 g = vec3(dot(dye, vec3(0.299, 0.587, 0.114)));\n dye = mix(dye, mix(g, dye, 0.7), shine * 0.35);\n }\n\n vec3 albedo = pow(max(dye, 0.002), vec3(2.2));\n // Material. ABS (GMK-style): a fine moulded texture, fairly matte; wear polishes the texture away\n // in the shine spot. PBT: smooth and silky, a soft even sheen, no visible grain.\n float tex = u_mat * (1.0 - shine * 0.95);\n float grainN = (noise(pos * 7.0 + u_pattern) - 0.5) * 0.7 + (noise(pos * 2.6 + u_pattern.yzx) - 0.5) * 0.5;\n albedo *= 1.0 + grainN * tex * 0.2;\n\n\n float trans = clamp(u_trans, 0.0, 1.0) * (1.0 - legend); // light scatters through; the legend plastic is opaque\n float rough = mix(0.44, 0.56, u_mat) + grainN * tex * 0.18; // texture breaks up ABS's sheen\n float baseRough = rough;\n rough = mix(rough, mix(0.32, 0.16, u_mat), shine); // worn tops: PBT a touch glossier, ABS polished slick\n\n vec3 L = normalize(vec3(u_L * 0.85, 0.85));\n float ndl = max(dot(n, L), 0.0);\n float hemi = 0.5 + 0.5 * dot(n, upW);\n vec3 diff = albedo * (mix(vec3(0.14), vec3(0.5), hemi) * ao + ndl * 1.15 * mix(0.55, 1.0, ao));\n float nv = max(dot(n, V), 0.0);\n // Translucent plastics: softer, lighter, glowing at thin edges.\n diff = mix(diff, albedo * (0.6 + 0.55 * hemi) * (0.6 + 0.4 * ao), trans * 0.55);\n diff += albedo * trans * pow(1.0 - nv, 2.2) * 0.9 * ao;\n\n vec3 H = normalize(L + V);\n // highlight shapes keep the material's spread; wear (lower rough) only strengthens them\n float sp = mix(10.0, 200.0, 1.0 - baseRough);\n vec3 spec = vec3(pow(max(dot(n, H), 0.0), sp) * mix(0.08, 0.7, 1.0 - rough) * ndl);\n vec3 R = reflect(-V, n);\n vec3 S1 = normalize(vec3(u_L * 0.7, 0.75));\n float box = smoothstep(0.8 - baseRough * 0.35, 0.97, dot(R, S1)) * smoothstep(0.0, 0.25, dot(R, upW));\n float F = 0.04 + (max(1.0 - rough, 0.04) - 0.04) * pow(1.0 - nv, 5.0);\n vec3 env = vec3(0.04 + 0.16 * clamp(0.5 + 0.5 * dot(R, upW), 0.0, 1.0) + box * mix(0.3, 1.1, 1.0 - rough));\n vec3 col = diff + spec * ao + env * F * ao;\n\n // Clear plastic is really see-through: whatever the element sits on shows through, dimmed and\n // tinted by how much plastic the ray crosses. The cap's own light (scatter in the dyed plastic,\n // reflections, inner-wall lines) is added on top, and alpha lets the page through.\n float see = 0.0; // 0 opaque to 1 fully see-through\n if (trans > 0.01 && hit) {\n float tq = t + 0.05;\n float depth = 0.0, edges = 0.0;\n bool inside = true;\n for (int i = 0; i < 48; i++) {\n if (tq > tEnd) break; // past the key, nothing left to cross\n vec3 q = ro + rd * tq;\n float d = sdKey(q);\n depth += clamp(0.5 - d / 0.45, 0.0, 1.0) * 0.45; // partial steps at surfaces, so no banding\n // Crossing an inner surface: walls met at a grazing angle catch the light as a faint line,\n // which is what shows the hollow and its walls inside a clear cap.\n if ((d < 0.0) != inside) {\n inside = d < 0.0;\n float g = 1.0 - abs(dot(keyNormal(q), rd));\n edges += g * g * g;\n }\n tq += 0.45;\n }\n vec3 sigma = (1.0 - albedo) * 0.95 + 0.03; // dyed plastic soaks up its opposite colours\n vec3 T = exp(-depth * sigma); // how much of what's behind gets through\n float Ta = dot(T, vec3(1.0 / 3.0));\n vec3 body = albedo * (0.3 + 0.45 * hemi) * (1.0 - Ta) * 1.25; // light scattered back by the dye\n vec3 tintT = max(T - Ta, 0.0) * 0.55; // the colour cast on what shows through\n vec3 glass = body + tintT + spec * ao + env * F * ao + vec3(min(edges, 1.5) * 0.13);\n col = mix(col, glass, trans);\n see = trans * Ta * 0.92;\n }\n // Ceiling light, mirrored by the top of the key: smooth ABS catches it, worn tops catch it most.\n vec3 C = normalize(vec3(u_L.x * 0.25, 0.92, -0.4));\n // the reflection keeps the material's spread; wear only makes it stronger\n float gl = 1.0 - rough;\n col += vec3(pow(max(dot(R, C), 0.0), mix(3.0, 40.0, 1.0 - baseRough)) * (gl * gl * gl * 0.55 + shine * mix(0.04, 0.16, u_mat))) * ao;\n\n // Glitter: flakes suspended in the plastic, big enough to see at preview sizes. Each reads as a\n // bright speck and catches the light at its own angle (and twinkles, if allowed).\n if (u_shimmer > 0.0) {\n vec3 gp = pos * 2.6;\n vec3 cell = floor(gp);\n float seed = hash3(cell + u_pattern);\n if (seed > 1.0 - u_shimmer * 0.6) {\n vec3 fn = normalize(vec3(hash3(cell + 1.3), hash3(cell + 2.7), hash3(cell + 4.1)) - 0.5);\n float tw = mix(0.8, 0.6 + 0.4 * sin(u_time * 3.0 + seed * 40.0), u_twinkle);\n vec3 fr = fract(gp) - 0.5 - (vec3(hash3(cell + 5.0), hash3(cell + 6.0), hash3(cell + 7.0)) - 0.5) * 0.4;\n float aa = pxW * 2.6;\n float disc = 1.0 - smoothstep(0.2 - aa, 0.2 + aa, length(fr));\n float glint = pow(max(dot(reflect(-V, normalize(n + fn * 0.7)), L), 0.0), 18.0) * tw;\n // flakes in their own colour (the legend's, or silver); the glint stays white\n col = mix(col, col * 0.35 + u_flakeCol * (0.75 + 0.45 * tw), disc * 0.8) + vec3(glint * disc * 1.8) * ao;\n }\n }\n\n col = pow(acesK(col * 1.05), vec3(1.0 / 2.2));\n col = mix(col, vec3(1.0), lines);\n // Premultiplied: the cap's own light, with alpha leaving room for the page to show through a\n // clear cap (and its shadow beneath). Alpha never drops below the light, so it stays valid.\n col = min(col, vec3(1.0)) * cover;\n float capA = cover * (1.0 - see);\n float a = max(capA + shadowA * (1.0 - capA), max(col.r, max(col.g, col.b)));\n gl_FragColor = vec4(col, a);\n}\n";
533
+ // src/legends.ts
534
+ const ATLAS = 1024;
535
+ const CELL_W = 256;
536
+ const CELL_H = 64;
537
+ const COLS = ATLAS / CELL_W;
538
+ const CAPACITY = COLS * (ATLAS / CELL_H);
539
+ const INF = 0x56bc75e2d63100000;
540
+ /**
541
+ * Text legends rendered into a shared alpha texture as signed distance fields, one 4:1 cell per
542
+ * font and string. Distances are stored as 128 + 8 * px so the shader can anti-alias the edge at
543
+ * any size. When the atlas fills up it starts over, and cells are redrawn on their next use.
544
+ */
545
+ var LegendAtlas = class {
546
+ cells = /* @__PURE__ */ new Map();
547
+ next = 0;
548
+ cv = document.createElement("canvas");
549
+ ctx;
550
+ pending = /* @__PURE__ */ new Set();
551
+ tex = null;
552
+ onFontLoad;
553
+ /** `onFontLoad` runs when a font that was missing at draw time arrives, so legends can redraw. */
554
+ constructor(onFontLoad) {
555
+ this.onFontLoad = onFontLoad;
556
+ this.cv.width = CELL_W;
557
+ this.cv.height = CELL_H;
558
+ this.ctx = this.cv.getContext("2d", { willReadFrequently: true });
559
+ }
560
+ init(gl) {
561
+ this.reset();
562
+ this.tex = gl.createTexture();
563
+ gl.bindTexture(gl.TEXTURE_2D, this.tex);
564
+ const blank = new Uint8Array(ATLAS * ATLAS).fill(255);
565
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, ATLAS, ATLAS, 0, gl.ALPHA, gl.UNSIGNED_BYTE, blank);
566
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
567
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
568
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
569
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
570
+ }
571
+ get(gl, text, font) {
572
+ const key = font + "\0" + text;
573
+ let cell = this.cells.get(key);
574
+ if (!cell) {
575
+ if (this.next >= CAPACITY) this.reset();
576
+ const i = this.next++;
577
+ cell = {
578
+ i,
579
+ w: this.draw(gl, text, font, i)
580
+ };
581
+ this.cells.set(key, cell);
582
+ }
583
+ return {
584
+ rect: [
585
+ cell.i % COLS * CELL_W / ATLAS,
586
+ Math.floor(cell.i / COLS) * CELL_H / ATLAS,
587
+ CELL_W / ATLAS,
588
+ CELL_H / ATLAS
589
+ ],
590
+ w: cell.w
591
+ };
592
+ }
593
+ reset() {
594
+ this.cells.clear();
595
+ this.next = 0;
596
+ }
597
+ draw(gl, text, family, index) {
598
+ const { ctx } = this;
599
+ let size = 44;
600
+ const font = () => `600 ${size}px ${family}`;
601
+ ctx.font = font();
602
+ if (document.fonts && !document.fonts.check(font(), text) && !this.pending.has(family)) {
603
+ this.pending.add(family);
604
+ document.fonts.load(font(), text).then(() => {
605
+ this.reset();
606
+ this.onFontLoad();
607
+ }, () => {});
608
+ }
609
+ let m = ctx.measureText(text);
610
+ let width = m.actualBoundingBoxLeft + m.actualBoundingBoxRight;
611
+ const room = 220;
612
+ if (width > room) {
613
+ size *= room / width;
614
+ ctx.font = font();
615
+ m = ctx.measureText(text);
616
+ width = m.actualBoundingBoxLeft + m.actualBoundingBoxRight;
617
+ }
618
+ const capHeight = ctx.measureText("H").actualBoundingBoxAscent;
619
+ ctx.clearRect(0, 0, CELL_W, CELL_H);
620
+ ctx.fillStyle = "#fff";
621
+ ctx.textBaseline = "alphabetic";
622
+ ctx.textAlign = "left";
623
+ ctx.fillText(text, CELL_W / 2 - (m.actualBoundingBoxRight - m.actualBoundingBoxLeft) / 2, CELL_H / 2 + capHeight / 2);
624
+ const alpha = ctx.getImageData(0, 0, CELL_W, CELL_H).data;
625
+ const n = CELL_W * CELL_H;
626
+ const outside = new Float64Array(n);
627
+ const inside = new Float64Array(n);
628
+ for (let i = 0; i < n; i++) {
629
+ const a = alpha[i * 4 + 3] / 255;
630
+ if (a >= 1) inside[i] = INF;
631
+ else if (a <= 0) outside[i] = INF;
632
+ else {
633
+ const d = .5 - a;
634
+ outside[i] = d > 0 ? d * d : 0;
635
+ inside[i] = d < 0 ? d * d : 0;
636
+ }
637
+ }
638
+ const len = Math.max(CELL_W, CELL_H);
639
+ const f = new Float64Array(len);
640
+ const v = new Uint16Array(len);
641
+ const z = /* @__PURE__ */ new Float64Array(257);
642
+ for (const grid of [outside, inside]) {
643
+ for (let x = 0; x < CELL_W; x++) edt1d(grid, x, CELL_W, CELL_H, f, v, z);
644
+ for (let y = 0; y < CELL_H; y++) edt1d(grid, y * CELL_W, 1, CELL_W, f, v, z);
645
+ }
646
+ const sdf = new Uint8Array(n);
647
+ for (let i = 0; i < n; i++) sdf[i] = Math.max(0, Math.min(255, Math.round(128 + (Math.sqrt(outside[i]) - Math.sqrt(inside[i])) * 8)));
648
+ gl.bindTexture(gl.TEXTURE_2D, this.tex);
649
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
650
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, index % COLS * CELL_W, Math.floor(index / COLS) * CELL_H, CELL_W, CELL_H, gl.ALPHA, gl.UNSIGNED_BYTE, sdf);
651
+ return width / CELL_H;
652
+ }
653
+ };
654
+ /**
655
+ * One pass of the Felzenszwalb-Huttenlocher squared distance transform over `n` values of `grid`
656
+ * starting at `offset`, `stride` apart. `f`, `v` and `z` are scratch buffers.
657
+ */
658
+ function edt1d(grid, offset, stride, n, f, v, z) {
659
+ v[0] = 0;
660
+ z[0] = -0x56bc75e2d63100000;
661
+ z[1] = INF;
662
+ f[0] = grid[offset];
663
+ for (let q = 1, k = 0, s = 0; q < n; q++) {
664
+ f[q] = grid[offset + q * stride];
665
+ const q2 = q * q;
666
+ do {
667
+ const r = v[k];
668
+ s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2;
669
+ } while (s <= z[k] && --k > -1);
670
+ k++;
671
+ v[k] = q;
672
+ z[k] = s;
673
+ z[k + 1] = INF;
674
+ }
675
+ for (let q = 0, k = 0; q < n; q++) {
676
+ while (z[k + 1] < q) k++;
677
+ const r = v[k];
678
+ const d = q - r;
679
+ grid[offset + q * stride] = f[r] + d * d;
680
+ }
681
+ }
682
+ // src/spin.ts
683
+ const createSpin = () => ({
684
+ q: IDENTITY_QUAT,
685
+ w: [
686
+ 0,
687
+ 0,
688
+ 0
689
+ ],
690
+ stir: 0,
691
+ energy: 0,
692
+ dragging: false,
693
+ last: 0
694
+ });
695
+ const isSpinning = (s) => s.dragging || Math.hypot(...s.w) > .02 || 1 - Math.abs(s.q[3]) > 1e-5 || Math.abs(s.stir) > .001 || s.energy > .001;
696
+ const scale = (v, k) => [
697
+ v[0] * k,
698
+ v[1] * k,
699
+ v[2] * k
700
+ ];
701
+ function dragStart(s, now) {
702
+ s.dragging = true;
703
+ s.last = now;
704
+ }
705
+ /** Turns the cap by a pointer movement of (dx, dy) pixels over a cap of the given radius. */
706
+ function dragBy(s, dx, dy, radius, now) {
707
+ const dist = Math.hypot(dx, dy);
708
+ if (dist < .01) return;
709
+ const angle = dist / Math.max(radius, 1);
710
+ const ax = dy / dist;
711
+ const ay = dx / dist;
712
+ s.q = quatNormalize(quatMul(quatFromAxisAngle(ax, ay, 0, angle), s.q));
713
+ const dt = Math.max((now - s.last) / 1e3, 1 / 240);
714
+ const k = Math.min(1, dt * 18);
715
+ s.w = [
716
+ s.w[0] + (ax * angle / dt - s.w[0]) * k,
717
+ s.w[1] + (ay * angle / dt - s.w[1]) * k,
718
+ 0
719
+ ];
720
+ s.last = now;
721
+ }
722
+ function dragEnd(s, now) {
723
+ s.dragging = false;
724
+ if (now - s.last > 80) s.w = [
725
+ 0,
726
+ 0,
727
+ 0
728
+ ];
729
+ s.last = now;
730
+ }
731
+ function stepSpin(s, now) {
732
+ const dt = Math.min(Math.max((now - s.last) / 1e3, 0), .05);
733
+ s.last = now;
734
+ const speed = Math.hypot(...s.w);
735
+ s.energy += (Math.min(speed / 6, 1) - s.energy) * Math.min(1, dt * (speed > s.energy * 6 ? 8 : 1.6));
736
+ if (s.dragging) {
737
+ s.stir += speed * dt * .25;
738
+ s.w = scale(s.w, Math.exp(-4 * dt));
739
+ return;
740
+ }
741
+ if (speed > 1e-4) {
742
+ s.q = quatNormalize(quatMul(quatFromAxisAngle(...s.w, speed * dt), s.q));
743
+ s.stir += speed * dt * .25;
744
+ s.w = scale(s.w, Math.exp(-2.2 * dt));
745
+ }
746
+ const settle = 1 - Math.exp(-dt * 3.2 * (1 - Math.min(speed / 3, 1)));
747
+ const q = s.q[3] < 0 ? [
748
+ -s.q[0],
749
+ -s.q[1],
750
+ -s.q[2],
751
+ -s.q[3]
752
+ ] : s.q;
753
+ const keep = 1 - settle;
754
+ s.q = quatNormalize([
755
+ q[0] * keep,
756
+ q[1] * keep,
757
+ q[2] * keep,
758
+ q[3] + (1 - q[3]) * settle
759
+ ]);
760
+ s.stir *= 1 - settle * .8;
761
+ if (!isSpinning(s)) Object.assign(s, {
762
+ q: IDENTITY_QUAT,
763
+ w: [
764
+ 0,
765
+ 0,
766
+ 0
767
+ ],
768
+ stir: 0,
769
+ energy: 0
770
+ });
771
+ }
772
+ // src/renderer.ts
773
+ const vertexSource = "attribute vec2 a; void main(){ gl_Position = vec4(a, 0.0, 1.0); }";
774
+ const UNIFORMS = [
775
+ "u_size",
776
+ "u_origin",
777
+ "u_L",
778
+ "u_c0",
779
+ "u_c1",
780
+ "u_c2",
781
+ "u_c3",
782
+ "u_pattern",
783
+ "u_flowDir",
784
+ "u_pos",
785
+ "u_time",
786
+ "u_swirl",
787
+ "u_sScale",
788
+ "u_sDetail",
789
+ "u_sWarp",
790
+ "u_sFlow",
791
+ "u_shine",
792
+ "u_yellow",
793
+ "u_mat",
794
+ "u_shimmer",
795
+ "u_twinkle",
796
+ "u_flakeCol",
797
+ "u_shadow",
798
+ "u_trans",
799
+ "u_prof",
800
+ "u_row",
801
+ "u_kw",
802
+ "u_eng",
803
+ "u_legOn",
804
+ "u_legW",
805
+ "u_legH",
806
+ "u_leg",
807
+ "u_legCol",
808
+ "u_drag",
809
+ "u_auto"
810
+ ];
811
+ /** Largest shared canvas dimension. Caps bigger than this on screen are clipped. */
812
+ const MAX_SIZE = 2048;
813
+ /** Rendered pixels per frame within which moving caps are supersampled too. */
814
+ const SUPERSAMPLE_BUDGET = 1e6;
815
+ /**
816
+ * Browsers cap the number of live WebGL contexts, so every keycap on the page shares one. Each
817
+ * frame the caps that need drawing are packed as tiles into the shared canvas, rendered, and
818
+ * copied into each cap's own 2D canvas. Still caps are drawn once and only redrawn when their
819
+ * config or size changes, or while they spin. Caps scrolled out of view are skipped.
820
+ *
821
+ * Tiles reach the caps through a 2D staging canvas. Some browsers, Firefox among them, read the
822
+ * whole WebGL buffer back from the GPU on every `drawImage` from it, so it is copied out once per
823
+ * batch rather than once per cap.
824
+ */
825
+ var Renderer = class {
826
+ canvas = document.createElement("canvas");
827
+ staging = document.createElement("canvas");
828
+ stagingCtx = this.staging.getContext("2d");
829
+ gl = null;
830
+ loc = {};
831
+ instances = /* @__PURE__ */ new Set();
832
+ byEl = /* @__PURE__ */ new Map();
833
+ /** Caps added since the last microtask draw. */
834
+ fresh = /* @__PURE__ */ new Set();
835
+ raf = 0;
836
+ lost = false;
837
+ legends = new LegendAtlas(() => this.invalidate());
838
+ io;
839
+ ro;
840
+ constructor() {
841
+ this.canvas.addEventListener("webglcontextlost", (e) => {
842
+ e.preventDefault();
843
+ this.lost = true;
844
+ for (const inst of this.instances) inst.onReady(false);
845
+ });
846
+ this.canvas.addEventListener("webglcontextrestored", () => {
847
+ this.lost = false;
848
+ this.setup();
849
+ for (const inst of this.instances) inst.drawn = false;
850
+ this.invalidate();
851
+ });
852
+ if (!this.setup()) throw new Error("WebGL unavailable");
853
+ this.io = new IntersectionObserver((entries) => {
854
+ for (const e of entries) {
855
+ const inst = this.byEl.get(e.target);
856
+ if (!inst) continue;
857
+ inst.visible = e.isIntersecting;
858
+ if (inst.visible) this.kick();
859
+ }
860
+ }, { rootMargin: "64px" });
861
+ this.ro = new ResizeObserver((entries) => {
862
+ for (const e of entries) {
863
+ const inst = this.byEl.get(e.target);
864
+ if (!inst) continue;
865
+ const { inlineSize, blockSize } = e.borderBoxSize[0];
866
+ if (inlineSize === inst.width && blockSize === inst.height) continue;
867
+ inst.width = inlineSize;
868
+ inst.height = blockSize;
869
+ inst.dirty = true;
870
+ }
871
+ this.kick();
872
+ });
873
+ }
874
+ add(inst) {
875
+ this.instances.add(inst);
876
+ this.byEl.set(inst.el, inst);
877
+ this.io.observe(inst.el);
878
+ this.ro.observe(inst.el);
879
+ this.kick();
880
+ if (this.lost) inst.onReady(false);
881
+ else if (this.fresh.add(inst).size === 1) queueMicrotask(this.drawFresh);
882
+ }
883
+ remove(inst) {
884
+ this.instances.delete(inst);
885
+ this.fresh.delete(inst);
886
+ this.byEl.delete(inst.el);
887
+ this.io.unobserve(inst.el);
888
+ this.ro.unobserve(inst.el);
889
+ }
890
+ kick() {
891
+ this.raf ||= requestAnimationFrame(this.frame);
892
+ }
893
+ invalidate() {
894
+ for (const inst of this.instances) inst.dirty = true;
895
+ this.kick();
896
+ }
897
+ setup() {
898
+ const gl = this.gl ??= this.canvas.getContext("webgl", {
899
+ premultipliedAlpha: true,
900
+ preserveDrawingBuffer: true,
901
+ antialias: false,
902
+ alpha: true
903
+ });
904
+ if (!gl) return false;
905
+ const compile = (type, source) => {
906
+ const shader = gl.createShader(type);
907
+ gl.shaderSource(shader, source);
908
+ gl.compileShader(shader);
909
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS) && !gl.isContextLost()) throw new Error(gl.getShaderInfoLog(shader) || "keycap shader failed to compile");
910
+ return shader;
911
+ };
912
+ const program = gl.createProgram();
913
+ gl.attachShader(program, compile(gl.VERTEX_SHADER, vertexSource));
914
+ gl.attachShader(program, compile(gl.FRAGMENT_SHADER, keycap_default));
915
+ gl.linkProgram(program);
916
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return false;
917
+ gl.useProgram(program);
918
+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
919
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
920
+ -1,
921
+ -1,
922
+ 1,
923
+ -1,
924
+ -1,
925
+ 1,
926
+ 1,
927
+ 1
928
+ ]), gl.STATIC_DRAW);
929
+ const a = gl.getAttribLocation(program, "a");
930
+ gl.enableVertexAttribArray(a);
931
+ gl.vertexAttribPointer(a, 2, gl.FLOAT, false, 0, 0);
932
+ for (const name of UNIFORMS) this.loc[name] = gl.getUniformLocation(program, name);
933
+ this.legends.init(gl);
934
+ gl.clearColor(0, 0, 0, 0);
935
+ return true;
936
+ }
937
+ frame = (now) => {
938
+ this.raf = 0;
939
+ if (this.draw(this.instances, now)) this.kick();
940
+ };
941
+ /** Draws new caps before the browser paints. The frame loop started by `add` keeps animated ones going. */
942
+ drawFresh = () => {
943
+ const insts = [...this.fresh];
944
+ this.fresh.clear();
945
+ this.draw(insts, performance.now());
946
+ };
947
+ /** Draws the caps in `insts` that need it. Returns whether any of them need another frame. */
948
+ draw(insts, now) {
949
+ const gl = this.gl;
950
+ if (!gl || this.lost || gl.isContextLost()) return false;
951
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
952
+ let again = false;
953
+ const jobs = [];
954
+ for (const inst of insts) {
955
+ if (!inst.visible || inst.width === 0) continue;
956
+ const spinning = isSpinning(inst.spin);
957
+ if (inst.params.animated || spinning) again = true;
958
+ if (!inst.params.animated && !inst.dirty && !spinning) continue;
959
+ if (spinning) stepSpin(inst.spin, now);
960
+ inst.dirty = spinning;
961
+ const w = Math.max(1, Math.round(inst.width * dpr));
962
+ const h = Math.max(1, Math.round(inst.height * dpr));
963
+ jobs.push({
964
+ inst,
965
+ w,
966
+ h,
967
+ rw: w,
968
+ rh: h,
969
+ moving: inst.params.animated || spinning
970
+ });
971
+ }
972
+ const movingPx = jobs.reduce((n, j) => j.moving ? n + j.w * j.h * 4 : n, 0);
973
+ for (const job of jobs) {
974
+ if (job.moving && movingPx > SUPERSAMPLE_BUDGET) continue;
975
+ if (Math.max(job.w, job.h) * 2 > MAX_SIZE) continue;
976
+ job.rw = job.w * 2;
977
+ job.rh = job.h * 2;
978
+ }
979
+ const { canvas, staging, stagingCtx } = this;
980
+ const width = jobs.some((j) => j.rw > 1024) ? MAX_SIZE : 1024;
981
+ let next = 0;
982
+ while (next < jobs.length) {
983
+ const placed = [];
984
+ let cx = 0;
985
+ let cy = 0;
986
+ let shelf = 0;
987
+ for (; next < jobs.length; next++) {
988
+ const job = jobs[next];
989
+ if (cx + job.rw > width) {
990
+ cx = 0;
991
+ cy += shelf;
992
+ shelf = 0;
993
+ }
994
+ if (cy + job.rh > MAX_SIZE && placed.length) break;
995
+ placed.push({
996
+ job,
997
+ x: cx,
998
+ y: cy
999
+ });
1000
+ cx += job.rw;
1001
+ shelf = Math.max(shelf, job.rh);
1002
+ }
1003
+ const height = Math.min(MAX_SIZE, Math.ceil((cy + shelf) / 128) * 128);
1004
+ if (canvas.width !== width || canvas.height !== height) {
1005
+ canvas.width = staging.width = width;
1006
+ canvas.height = staging.height = height;
1007
+ }
1008
+ gl.viewport(0, 0, width, height);
1009
+ gl.clear(gl.COLOR_BUFFER_BIT);
1010
+ for (const { job, x, y } of placed) this.drawTile(gl, job, x, y, (now - job.inst.born) / 1e3);
1011
+ stagingCtx.clearRect(0, 0, width, height);
1012
+ stagingCtx.drawImage(canvas, 0, 0);
1013
+ for (const { job, x, y } of placed) {
1014
+ const { inst, w, h, rw, rh } = job;
1015
+ if (inst.canvas.width !== w || inst.canvas.height !== h) {
1016
+ inst.canvas.width = w;
1017
+ inst.canvas.height = h;
1018
+ }
1019
+ inst.ctx.clearRect(0, 0, w, h);
1020
+ inst.ctx.drawImage(staging, x, height - y - rh, rw, rh, 0, 0, w, h);
1021
+ if (!inst.drawn) {
1022
+ inst.drawn = true;
1023
+ inst.onReady(true);
1024
+ }
1025
+ }
1026
+ }
1027
+ return again;
1028
+ }
1029
+ drawTile(gl, job, x, y, age) {
1030
+ const { loc } = this;
1031
+ const p = job.inst.params;
1032
+ const c = p.config;
1033
+ const spin = job.inst.spin;
1034
+ const time = p.animated ? age : 0;
1035
+ const light = c.angle * Math.PI / 180;
1036
+ const energy = c.swirl > 0 ? spin.energy : 0;
1037
+ const f1 = (name, v) => gl.uniform1f(loc[name], v);
1038
+ const rgb = (name, v) => gl.uniform3f(loc[name], v[0] / 255, v[1] / 255, v[2] / 255);
1039
+ gl.viewport(x, y, job.rw, job.rh);
1040
+ gl.uniform2f(loc.u_size, job.rw, job.rh);
1041
+ gl.uniform2f(loc.u_origin, x, y);
1042
+ gl.uniform2f(loc.u_L, Math.sin(light), Math.cos(light));
1043
+ rgb("u_c0", p.stops[0]);
1044
+ rgb("u_c1", p.stops[1]);
1045
+ rgb("u_c2", p.stops[2]);
1046
+ rgb("u_c3", p.stops[3]);
1047
+ gl.uniform3fv(loc.u_pattern, p.pattern);
1048
+ gl.uniform3fv(loc.u_flowDir, p.flowDir);
1049
+ gl.uniform4fv(loc.u_pos, p.pos);
1050
+ f1("u_time", time + spin.stir);
1051
+ f1("u_swirl", Math.min(1, c.swirl + energy * .2));
1052
+ f1("u_sScale", c.swirlScale);
1053
+ f1("u_sDetail", Math.max(1, Math.min(5, Math.round(c.swirlDetail))));
1054
+ f1("u_sWarp", c.swirlWarp + energy * .6);
1055
+ f1("u_sFlow", c.swirlFlow);
1056
+ f1("u_shine", c.shine);
1057
+ f1("u_yellow", c.yellowing);
1058
+ f1("u_mat", c.material === "abs" ? 1 : 0);
1059
+ f1("u_shimmer", c.shimmer);
1060
+ f1("u_twinkle", c.twinkle ? 1 : 0);
1061
+ f1("u_shadow", c.shadow);
1062
+ f1("u_trans", c.translucency);
1063
+ f1("u_prof", p.profile);
1064
+ f1("u_eng", p.legendIcon);
1065
+ f1("u_legOn", p.legendText ? 1 : 0);
1066
+ if (p.legendText) {
1067
+ const cell = this.legends.get(gl, p.legendText, c.legendFont);
1068
+ gl.uniform4fv(loc.u_leg, cell.rect);
1069
+ f1("u_legW", Math.max(cell.w, .01));
1070
+ f1("u_legH", p.legendHeight);
1071
+ }
1072
+ rgb("u_legCol", p.legendColor);
1073
+ gl.uniform3fv(loc.u_flakeCol, p.flakeColor);
1074
+ f1("u_row", c.row);
1075
+ f1("u_kw", c.width);
1076
+ gl.uniformMatrix3fv(loc.u_drag, false, spin.q === IDENTITY_QUAT ? IDENTITY_MAT3 : quatToMat3(spin.q));
1077
+ gl.uniformMatrix3fv(loc.u_auto, false, axisAngleMat3(time * c.spin, p.axis));
1078
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
1079
+ }
1080
+ };
1081
+ let shared;
1082
+ /** The page's shared renderer, or null when WebGL is unavailable. */
1083
+ function getRenderer() {
1084
+ if (typeof window === "undefined") return null;
1085
+ if (shared === void 0) try {
1086
+ shared = new Renderer();
1087
+ } catch (e) {
1088
+ console.warn("keycaps: WebGL renderer unavailable, showing fallbacks.", e);
1089
+ shared = null;
1090
+ }
1091
+ return shared;
1092
+ }
1093
+ const isWebGLAvailable = () => getRenderer() !== null;
1094
+ // src/mount.ts
1095
+ /** Shown while the WebGL context is lost and when WebGL is unavailable. */
1096
+ const FALLBACK = "var(--keycap-fallback, #d4d4d4)";
1097
+ /**
1098
+ * Renders a keycap into `host`, filling its box. The host needs a non-static position. The first
1099
+ * draw happens in a microtask, so a cap mounted before paint appears in that same paint.
1100
+ */
1101
+ function mountKeycap(host, options, { spinnable = false } = {}) {
1102
+ const canvas = document.createElement("canvas");
1103
+ canvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;border-radius:18%";
1104
+ host.append(canvas);
1105
+ const renderer = getRenderer();
1106
+ if (!renderer) {
1107
+ canvas.style.background = FALLBACK;
1108
+ return {
1109
+ update() {},
1110
+ destroy: () => canvas.remove()
1111
+ };
1112
+ }
1113
+ const ctx = canvas.getContext("2d");
1114
+ const { width, height } = host.getBoundingClientRect();
1115
+ const inst = {
1116
+ el: host,
1117
+ canvas,
1118
+ ctx,
1119
+ params: prepare(options),
1120
+ width,
1121
+ height,
1122
+ visible: true,
1123
+ dirty: true,
1124
+ drawn: false,
1125
+ born: performance.now(),
1126
+ spin: createSpin(),
1127
+ onReady: (ready) => {
1128
+ if (!ready) ctx.clearRect(0, 0, canvas.width, canvas.height);
1129
+ canvas.style.background = ready ? "" : FALLBACK;
1130
+ }
1131
+ };
1132
+ renderer.add(inst);
1133
+ let pointer = null;
1134
+ const down = (e) => {
1135
+ host.setPointerCapture(e.pointerId);
1136
+ pointer = {
1137
+ x: e.clientX,
1138
+ y: e.clientY,
1139
+ id: e.pointerId
1140
+ };
1141
+ dragStart(inst.spin, performance.now());
1142
+ renderer.kick();
1143
+ };
1144
+ const move = (e) => {
1145
+ if (pointer?.id !== e.pointerId) return;
1146
+ const radius = host.getBoundingClientRect().width / 2;
1147
+ dragBy(inst.spin, e.clientX - pointer.x, e.clientY - pointer.y, radius, performance.now());
1148
+ pointer.x = e.clientX;
1149
+ pointer.y = e.clientY;
1150
+ renderer.kick();
1151
+ };
1152
+ const up = (e) => {
1153
+ if (pointer?.id !== e.pointerId) return;
1154
+ pointer = null;
1155
+ dragEnd(inst.spin, performance.now());
1156
+ renderer.kick();
1157
+ };
1158
+ const listeners = new AbortController();
1159
+ if (spinnable) {
1160
+ const { signal } = listeners;
1161
+ host.addEventListener("pointerdown", down, { signal });
1162
+ host.addEventListener("pointermove", move, { signal });
1163
+ host.addEventListener("pointerup", up, { signal });
1164
+ host.addEventListener("pointercancel", up, { signal });
1165
+ }
1166
+ return {
1167
+ update(next) {
1168
+ inst.params = prepare(next);
1169
+ inst.dirty = true;
1170
+ renderer.kick();
1171
+ },
1172
+ destroy() {
1173
+ renderer.remove(inst);
1174
+ listeners.abort();
1175
+ canvas.remove();
1176
+ }
1177
+ };
1178
+ }
1179
+ // src/keycap.tsx
1180
+ /** Config shared by every `Keycap` below it. A `preset` or props on the cap override it. */
1181
+ const KeycapDefaults = createContext({});
1182
+ const CONFIG_KEYS = new Set(Object.keys(DEFAULT_KEYCAP));
1183
+ const Keycap = forwardRef(function Keycap({ size = 48, preset, label, frozen = false, spinnable = false, style, ...rest }, ref) {
1184
+ const defaults = useContext(KeycapDefaults);
1185
+ const fields = {};
1186
+ const attrs = {};
1187
+ for (const [k, v] of Object.entries(rest)) if (!CONFIG_KEYS.has(k)) attrs[k] = v;
1188
+ else if (v !== void 0) fields[k] = v;
1189
+ const options = {
1190
+ ...defaults,
1191
+ ...preset && KEYCAP_PRESETS[preset],
1192
+ ...fields,
1193
+ frozen
1194
+ };
1195
+ const key = JSON.stringify(options);
1196
+ const host = useRef(null);
1197
+ const handle = useRef(null);
1198
+ useLayoutEffect(() => {
1199
+ const h = mountKeycap(host.current, {}, { spinnable });
1200
+ handle.current = h;
1201
+ return () => {
1202
+ h.destroy();
1203
+ handle.current = null;
1204
+ };
1205
+ }, [spinnable]);
1206
+ useLayoutEffect(() => handle.current?.update(JSON.parse(key)), [key, spinnable]);
1207
+ const setHost = (node) => {
1208
+ host.current = node;
1209
+ if (typeof ref === "function") ref(node);
1210
+ else if (ref) ref.current = node;
1211
+ };
1212
+ return /* @__PURE__ */ jsx("span", {
1213
+ ref: setHost,
1214
+ role: label ? "img" : void 0,
1215
+ "aria-label": label,
1216
+ "aria-hidden": label ? void 0 : true,
1217
+ ...attrs,
1218
+ style: {
1219
+ position: "relative",
1220
+ display: "inline-block",
1221
+ flexShrink: 0,
1222
+ verticalAlign: "middle",
1223
+ width: `${keycapAspect(options.width ?? 1)}em`,
1224
+ height: "1em",
1225
+ fontSize: size,
1226
+ lineHeight: 0,
1227
+ ...spinnable && {
1228
+ touchAction: "none",
1229
+ cursor: "grab",
1230
+ userSelect: "none"
1231
+ },
1232
+ ...style
1233
+ }
1234
+ });
1235
+ });
1236
+ export { DEFAULT_KEYCAP, KEYCAP_PRESETS, Keycap, KeycapDefaults, LEGEND_ICONS, MATERIALS, PROFILES, SWIRL_RECIPES, isWebGLAvailable, keycapAspect };