Repository navigation
Expand file tree
/
Copy pathquadknob.js
More file actions
827 lines (760 loc) · 65.9 KB
/
Copy pathquadknob.js
File metadata and controls
827 lines (760 loc) · 65.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
// Generated by build.mjs from src/quadknob.js and figures/. Do not edit.
// Quadknob: four knobs to dial values in by eye, after the OP-1. One dependency-free custom element, <quadknob-panel>.
// Build with `node build.mjs`, which inlines the figures from ./figures into ../quadknob.js.
const FIGURES = {"color":"<style>\n body { display: flex; align-items: center; justify-content: center; padding: 16px }\n svg { width: 100%; height: 100%; max-width: 480px; overflow: visible }\n</style>\n<!--\n Paint shop: a can of the colour, mixed from four things on the shelf. A lamp for lightness, a squeezed tube for\n chroma, a colour wheel for hue and a jar filling up for alpha, each outlined in the colour of its knob.\n-->\n<svg id=\"figure\" viewBox=\"0 0 400 230\" role=\"img\" aria-label=\"A can of paint and what it is mixed from\"></svg>\n<script>\n const RANGES = { lightness: [0, 1], chroma: [0, 0.4], hue: [0, 360], alpha: [0, 1] }\n const svg = document.getElementById('figure')\n const range = (name) => { const param = bench.params.find((item) => item.name === name); return param ? [param.min, param.max] : RANGES[name] }\n const share = (name, value) => { const [min, max] = range(name); return (value - min) / (max - min) }\n const ink = (name) => bench.lane(name) ? bench.color(name) : 'var(--dim)'\n const line = 'stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" fill=\"none\"'\n\n bench.on(({ lightness: l = 0.7, chroma: c = 0.15, hue: h = 250, alpha: a = 1 }) => {\n const paint = `oklch(${l} ${c} ${h} / ${a})`\n const solid = `oklch(${l} ${c} ${h})`\n\n // The can: an open tin full of paint, a drip running over the rim.\n const can = `\n <defs><pattern id=\"check\" width=\"10\" height=\"10\" patternUnits=\"userSpaceOnUse\">\n <rect width=\"5\" height=\"5\" fill=\"var(--line)\" /><rect x=\"5\" y=\"5\" width=\"5\" height=\"5\" fill=\"var(--line)\" />\n </pattern></defs>\n <path d=\"M150,70v110a50,14 0 0 0 100,0V70\" fill=\"url(#check)\" opacity=\"0.5\" />\n <path d=\"M150,70v110a50,14 0 0 0 100,0V70\" fill=\"${paint}\" />\n <ellipse cx=\"200\" cy=\"70\" rx=\"50\" ry=\"14\" fill=\"${solid}\" stroke=\"var(--fg)\" stroke-width=\"1.5\" />\n <path d=\"M150,70v110a50,14 0 0 0 100,0V70\" ${line} stroke=\"var(--fg)\" />\n <path d=\"M232,80q2,14 0,24a4,4 0 0 0 8,0q-2,-10 0,-26\" fill=\"${solid}\" stroke=\"var(--fg)\" stroke-width=\"1.5\" />\n <path d=\"M150,70q0,-48 50,-48t50,48\" ${line} stroke=\"var(--fg)\" stroke-dasharray=\"2 4\" />\n <rect x=\"168\" y=\"118\" width=\"64\" height=\"30\" rx=\"4\" fill=\"var(--bg)\" stroke=\"var(--fg)\" stroke-width=\"1.5\" />\n <path d=\"M178,128h44M178,138h28\" ${line} stroke=\"var(--dim)\" />`\n\n // Lightness: a lamp, its rays as long as the colour is light.\n const rays = Array.from({ length: 8 }, (_, i) => {\n const angle = (i / 8) * Math.PI * 2, inner = 22, outer = 22 + 4 + share('lightness', l) * 18\n return `<line x1=\"${Math.cos(angle) * inner}\" y1=\"${Math.sin(angle) * inner}\" x2=\"${Math.cos(angle) * outer}\" y2=\"${Math.sin(angle) * outer}\" />`\n }).join('')\n const lamp = `<g transform=\"translate(60,62)\" ${line} stroke=\"${ink('lightness')}\">\n <path d=\"M-10,8a14,14 0 1 1 20,0v8h-20z\" /><path d=\"M-7,20h14M-5,24h10\" />${rays}</g>`\n\n // Chroma: a tube of paint, rolled up from the end as more is squeezed out.\n const squeezed = share('chroma', c)\n const body = 66 - squeezed * 40\n const blob = 3 + squeezed * 10\n const tube = `<g transform=\"translate(22,170)\" ${line} stroke=\"${ink('chroma')}\">\n <path d=\"M0,-12h${body}l14,6v12l-14,6h-${body}z\" />\n <path d=\"M${body + 14},-4h6v8h-6\" />\n ${Array.from({ length: Math.round(squeezed * 4) }, (_, i) => `<path d=\"M${-2 - i * 4},-12v24\" />`).join('')}\n <circle cx=\"${body + 26 + blob}\" cy=\"0\" r=\"${blob}\" fill=\"${solid}\" />\n </g>`\n\n // Hue: a colour wheel with its needle on the hue.\n const wheel = Array.from({ length: 24 }, (_, i) => {\n const from = (i / 24) * Math.PI * 2 - Math.PI / 2, to = ((i + 1) / 24) * Math.PI * 2 - Math.PI / 2\n const p = (angle, r) => `${Math.cos(angle) * r},${Math.sin(angle) * r}`\n return `<path d=\"M${p(from, 24)}A24,24 0 0 1 ${p(to, 24)}L${p(to, 34)}A34,34 0 0 0 ${p(from, 34)}Z\" fill=\"oklch(${l} ${c} ${(i / 24) * 360})\" />`\n }).join('')\n const needle = (h / 360) * Math.PI * 2 - Math.PI / 2\n const hueWheel = `<g transform=\"translate(340,62)\">\n ${wheel}\n <circle r=\"34\" fill=\"none\" stroke=\"var(--fg)\" stroke-width=\"1.5\" /><circle r=\"24\" fill=\"none\" stroke=\"var(--fg)\" stroke-width=\"1.5\" />\n <line x1=\"0\" y1=\"0\" x2=\"${Math.cos(needle) * 40}\" y2=\"${Math.sin(needle) * 40}\" stroke=\"${ink('hue')}\" stroke-width=\"2.5\" stroke-linecap=\"round\" />\n <circle r=\"4\" fill=\"${ink('hue')}\" />\n </g>`\n\n // Alpha: a jar that fills with the colour as it gets more opaque.\n const level = share('alpha', a) * 52\n const jar = `<g transform=\"translate(316,134)\">\n <rect x=\"2\" y=\"${70 - level}\" width=\"44\" height=\"${level}\" fill=\"${solid}\" />\n <path d=\"M0,8h48v62a6,6 0 0 1 -6,6h-36a6,6 0 0 1 -6,-6z M-3,0h54v8h-54z\" ${line} stroke=\"${ink('alpha')}\" />\n </g>`\n\n svg.innerHTML = `\n <line x1=\"0\" y1=\"${210}\" x2=\"400\" y2=\"${210}\" stroke=\"var(--line)\" stroke-width=\"1.5\" />\n ${can}${lamp}${tube}${hueWheel}${jar}`\n })\n</script>\n","curve":"<style>\n body { display: flex; align-items: center; justify-content: center; padding: 16px }\n svg { width: 100%; height: 100%; max-width: 420px; overflow: visible }\n</style>\n<!--\n Marble run: the easing curve is a ramp on stilts. A marble rides it in eased time, and a flag climbs its pole with\n the progress. Each handle's x and y are guides in the colours of their knobs.\n-->\n<svg id=\"figure\" viewBox=\"-30 -80 330 340\" role=\"img\" aria-label=\"A marble on an easing ramp\"></svg>\n<script>\n const S = 200, DURATION = 1600, PAUSE = 400\n const svg = document.getElementById('figure')\n const px = (x) => x * S, py = (y) => S - y * S\n let curve = { x1: 0.25, y1: 0.1, x2: 0.25, y2: 1 }\n\n // The point on the bezier at parameter s, and the eased progress at time t (solving x(s) = t by bisection).\n const bezier = (s, a, b) => 3 * (1 - s) ** 2 * s * a + 3 * (1 - s) * s ** 2 * b + s ** 3\n function ease(t) {\n let low = 0, high = 1\n for (let i = 0; i < 30; i++) {\n const mid = (low + high) / 2\n if (bezier(mid, curve.x1, curve.x2) < t) low = mid\n else high = mid\n }\n return bezier((low + high) / 2, curve.y1, curve.y2)\n }\n\n bench.on((values) => {\n curve = { ...curve, ...values }\n const { x1, y1, x2, y2 } = curve\n const guide = (name, x, y, vertical) => bench.lane(name)\n ? `<line x1=\"${px(vertical ? x : 0)}\" y1=\"${py(vertical ? 0 : y)}\" x2=\"${px(x)}\" y2=\"${py(y)}\" stroke=\"${bench.color(name)}\" stroke-width=\"1.5\" stroke-dasharray=\"3 3\" />`\n : ''\n const path = `M${px(0)},${py(0)}C${px(x1)},${py(y1)} ${px(x2)},${py(y2)} ${px(1)},${py(1)}`\n // Stilts from the ramp down to the ground, every tenth of the way.\n const stilts = Array.from({ length: 9 }, (_, i) => {\n const t = (i + 1) / 10, y = ease(t)\n return `<line x1=\"${px(t)}\" y1=\"${py(Math.max(0, Math.min(1, y)))}\" x2=\"${px(t)}\" y2=\"${S + 8}\" stroke=\"var(--line)\" />`\n }).join('')\n svg.innerHTML = `\n <line x1=\"-20\" y1=\"${S + 8}\" x2=\"${S + 60}\" y2=\"${S + 8}\" stroke=\"var(--line)\" stroke-width=\"1.5\" />\n ${stilts}\n ${guide('x1', x1, y1, true)}${guide('y1', x1, y1, false)}${guide('x2', x2, y2, true)}${guide('y2', x2, y2, false)}\n <line x1=\"${px(0)}\" y1=\"${py(0)}\" x2=\"${px(x1)}\" y2=\"${py(y1)}\" stroke=\"var(--dim)\" />\n <line x1=\"${px(1)}\" y1=\"${py(1)}\" x2=\"${px(x2)}\" y2=\"${py(y2)}\" stroke=\"var(--dim)\" />\n <path d=\"${path}\" fill=\"none\" stroke=\"var(--fg)\" stroke-width=\"4\" stroke-linecap=\"round\" />\n <path d=\"${path}\" fill=\"none\" stroke=\"var(--bg)\" stroke-width=\"1.5\" stroke-linecap=\"round\" />\n <circle cx=\"${px(x1)}\" cy=\"${py(y1)}\" r=\"4\" fill=\"var(--bg)\" stroke=\"var(--fg)\" stroke-width=\"1.5\" />\n <circle cx=\"${px(x2)}\" cy=\"${py(y2)}\" r=\"4\" fill=\"var(--bg)\" stroke=\"var(--fg)\" stroke-width=\"1.5\" />\n <line x1=\"${S + 40}\" y1=\"${S + 8}\" x2=\"${S + 40}\" y2=\"${py(1) - 6}\" stroke=\"var(--fg)\" stroke-width=\"1.5\" />\n <path id=\"flag\" d=\"M0,0h18l-5,6l5,6h-18z\" fill=\"none\" stroke=\"var(--fg)\" stroke-width=\"1.5\" stroke-linejoin=\"round\" />\n <circle id=\"marble\" r=\"7\" fill=\"var(--bg)\" stroke=\"var(--fg)\" stroke-width=\"1.5\" />\n <path id=\"shine\" d=\"M-3,-2a4,4 0 0 1 3,-3\" fill=\"none\" stroke=\"var(--fg)\" stroke-width=\"1.5\" stroke-linecap=\"round\" />`\n })\n\n // Down and up again: the marble runs the curve forwards, rests, then rolls back.\n function frame(now) {\n const cycle = now % (2 * (DURATION + PAUSE))\n const leg = cycle < DURATION + PAUSE ? cycle : cycle - DURATION - PAUSE\n const forward = cycle < DURATION + PAUSE\n const t = Math.min(1, leg / DURATION)\n const time = forward ? t : 1 - t\n const progress = ease(time)\n const marble = document.getElementById('marble'), shine = document.getElementById('shine'), flag = document.getElementById('flag')\n if (marble) {\n const x = px(time), y = py(progress) - 9\n marble.setAttribute('transform', `translate(${x},${y})`)\n shine.setAttribute('transform', `translate(${x},${y})`)\n flag.setAttribute('transform', `translate(${S + 40},${py(progress) - 6})`)\n }\n requestAnimationFrame(frame)\n }\n requestAnimationFrame(frame)\n</script>\n","frame":"<style>\n /* True size when there is room, scaled down to fit the frame's width or height when there is not. */\n body { display: flex; align-items: center; justify-content: center; padding: 16px }\n svg { width: 100%; height: 100%; overflow: visible }\n</style>\n<!--\n Gallery: two framed pictures on a wall. The frame's corners are the radius, its mat the padding, its moulding the\n border and the space between the two frames the gap, each drawn in the colour of the knob that turns it.\n-->\n<svg id=\"figure\" role=\"img\" aria-label=\"Two framed pictures on a wall\"></svg>\n<script>\n const DEFAULTS = { radius: 8, padding: 16, border: 1, gap: 8 }\n const PICTURE = { width: 88, height: 64 }\n const svg = document.getElementById('figure')\n const bound = (name) => bench.params.some((param) => param.name === name)\n const color = (name, fallback = 'var(--line)') => bound(name) ? bench.color(name) : fallback\n\n const roundRect = (x, y, w, h, r) => {\n r = Math.max(0, Math.min(r, w / 2, h / 2))\n return `M${x + r},${y}H${x + w - r}A${r},${r} 0 0 1 ${x + w},${y + r}V${y + h - r}A${r},${r} 0 0 1 ${x + w - r},${y + h}`\n + `H${x + r}A${r},${r} 0 0 1 ${x},${y + h - r}V${y + r}A${r},${r} 0 0 1 ${x + r},${y}Z`\n }\n // The four corners of a box, where its radius shows.\n const corners = (x, y, w, h, r) => {\n const k = Math.max(r, 6)\n return `M${x},${y + k}V${y + r}A${r},${r} 0 0 1 ${x + r},${y}H${x + k}`\n + `M${x + w - k},${y}H${x + w - r}A${r},${r} 0 0 1 ${x + w},${y + r}V${y + k}`\n + `M${x + w},${y + h - k}V${y + h - r}A${r},${r} 0 0 1 ${x + w - r},${y + h}H${x + w - k}`\n + `M${x + k},${y + h}H${x + r}A${r},${r} 0 0 1 ${x},${y + h - r}V${y + h - k}`\n }\n // The pictures themselves stay neutral: a mountain under the sun, and a flower in a pot.\n const mountain = (x, y, w, h) => `\n <circle cx=\"${x + w * 0.74}\" cy=\"${y + h * 0.3}\" r=\"${h * 0.11}\" fill=\"none\" stroke=\"var(--dim)\" stroke-width=\"1.5\" />\n <path d=\"M${x},${y + h}L${x + w * 0.32},${y + h * 0.42}L${x + w * 0.5},${y + h * 0.68}L${x + w * 0.66},${y + h * 0.5}L${x + w},${y + h}\"\n fill=\"none\" stroke=\"var(--dim)\" stroke-width=\"1.5\" stroke-linejoin=\"round\" />`\n const flower = (x, y, w, h) => {\n const cx = x + w / 2, top = y + h * 0.3\n const petals = [0, 72, 144, 216, 288].map((a) => {\n const r = a * Math.PI / 180\n return `<circle cx=\"${cx + Math.cos(r) * 6}\" cy=\"${top + Math.sin(r) * 6}\" r=\"4.5\" fill=\"none\" stroke=\"var(--dim)\" stroke-width=\"1.5\" />`\n }).join('')\n return `${petals}<circle cx=\"${cx}\" cy=\"${top}\" r=\"2.5\" fill=\"var(--dim)\" />\n <path d=\"M${cx},${top + 10}V${y + h * 0.72}M${cx},${y + h * 0.58}q8,-6 12,-2\" fill=\"none\" stroke=\"var(--dim)\" stroke-width=\"1.5\" />\n <path d=\"M${cx - 11},${y + h * 0.72}h22l-3,${h * 0.2}h-16z\" fill=\"none\" stroke=\"var(--dim)\" stroke-width=\"1.5\" stroke-linejoin=\"round\" />`\n }\n\n bench.on((values) => {\n const v = { ...DEFAULTS, ...values }\n const outerW = PICTURE.width + 2 * (v.padding + v.border), outerH = PICTURE.height + 2 * (v.padding + v.border)\n const rail = 12, hang = 26, margin = 12\n const top = rail + hang, floor = top + outerH + 30\n const width = margin * 2 + outerW * 2 + v.gap\n svg.setAttribute('viewBox', `0 0 ${width} ${floor + 6}`)\n // At most true size: the drawing never grows past the pixels it describes.\n svg.style.maxWidth = `${width}px`\n svg.style.maxHeight = `${floor + 6}px`\n\n const frame = (x, picture) => {\n const r = Math.min(v.radius, outerH / 2), b = v.border, p = v.padding\n const inner = b + p\n return `\n <path d=\"M${x + outerW / 2},${rail}L${x + outerW * 0.2},${top}M${x + outerW / 2},${rail}L${x + outerW * 0.8},${top}\" stroke=\"var(--dim)\" stroke-width=\"1\" fill=\"none\" />\n <circle cx=\"${x + outerW / 2}\" cy=\"${rail}\" r=\"2.5\" fill=\"var(--fg)\" />\n <path d=\"${roundRect(x, top, outerW, outerH, r)}\" fill=\"color-mix(in oklab, var(--fg) 5%, transparent)\" />\n ${bound('padding') ? `<path d=\"${roundRect(x + b, top + b, outerW - 2 * b, outerH - 2 * b, r - b)} ${roundRect(x + inner, top + inner, PICTURE.width, PICTURE.height, r - inner)}\"\n fill-rule=\"evenodd\" fill=\"url(#padding-hatch)\" />` : ''}\n <path d=\"${roundRect(x + inner, top + inner, PICTURE.width, PICTURE.height, Math.max(0, r - inner))}\" fill=\"none\" stroke=\"var(--line)\" />\n ${picture(x + inner + 8, top + inner + 6, PICTURE.width - 16, PICTURE.height - 12)}\n ${b > 0 ? `<path d=\"${roundRect(x + b / 2, top + b / 2, outerW - b, outerH - b, r - b / 2)}\" fill=\"none\" stroke=\"${color('border', 'var(--fg)')}\" stroke-width=\"${b}\" />` : ''}\n ${bound('radius') ? `<path d=\"${corners(x, top, outerW, outerH, r)}\" fill=\"none\" stroke=\"${bench.color('radius')}\" stroke-width=\"2\" stroke-linecap=\"round\" />` : ''}`\n }\n const left = margin, right = margin + outerW + v.gap\n // The gap, measured like on a plan: a dimension line between the frames, at true width.\n const gapY = top + outerH + 14\n // Transparent pinstripes mark the measured mat, without painting over the specimen.\n svg.innerHTML = `\n ${bound('padding') ? `<defs><pattern id=\"padding-hatch\" width=\"6\" height=\"6\" patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\">\n <path d=\"M0.5,0V6\" fill=\"none\" stroke=\"${bench.color('padding')}\" stroke-width=\"0.75\" stroke-opacity=\"0.65\" />\n </pattern></defs>` : ''}\n <line x1=\"0\" y1=\"${rail}\" x2=\"${width}\" y2=\"${rail}\" stroke=\"var(--line)\" stroke-width=\"1.5\" />\n <line x1=\"0\" y1=\"${floor}\" x2=\"${width}\" y2=\"${floor}\" stroke=\"var(--line)\" stroke-width=\"1.5\" />\n ${frame(left, mountain)}\n ${frame(right, flower)}\n ${bound('gap') ? `<path d=\"M${left + outerW},${gapY - 5}v10M${right},${gapY - 5}v10M${left + outerW},${gapY}H${right}\"\n stroke=\"${bench.color('gap')}\" stroke-width=\"1.5\" fill=\"none\" />` : ''}`\n })\n</script>\n","grid":"<style>\n body { padding: 24px; overflow: auto }\n #container { box-sizing: border-box; border-top: 2px solid; padding-top: 16px }\n #grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, var(--minimum-size)), 1fr)); background: repeating-linear-gradient(135deg, var(--gap-ink) 0 0.75px, transparent 0.75px 6px) }\n .card { position: relative; height: 88px; background: var(--bg); border: 1px solid; border-radius: 4px }\n .card::before { content: ''; position: absolute; left: 0; bottom: 10px; width: var(--minimum-mark); border-top: 2px solid var(--minimum-ink) }\n .card::after { content: ''; position: absolute; inset: 16px 20% 32px; border: 1px solid var(--line); border-radius: 2px }\n</style>\n<div id=\"container\" role=\"img\" aria-label=\"Wrapping card grid with minimum-width marks\"><div id=\"grid\"></div></div>\n<script>\n const container = document.getElementById('container'), grid = document.getElementById('grid')\n const color = (name) => bench.params.some((p) => p.name === name) ? bench.color(name) : 'var(--line)'\n bench.on((values) => {\n const v = { width: 560, minimum: 160, gap: 16, count: 6, ...values }\n container.style.width = `${v.width}px`\n container.style.borderColor = color('width')\n grid.style.setProperty('--minimum-size', `${v.minimum}px`)\n grid.style.setProperty('--minimum-mark', `${Math.min(v.minimum, v.width)}px`)\n grid.style.setProperty('--minimum-ink', color('minimum'))\n grid.style.setProperty('--gap-ink', `color-mix(in oklab, ${color('gap')} 65%, transparent)`)\n grid.style.gap = `${v.gap}px`\n // Keep the DOM stable for changes other than count.\n while (grid.children.length > v.count) grid.lastElementChild.remove()\n while (grid.children.length < v.count) {\n const card = document.createElement('div')\n card.className = 'card'\n grid.append(card)\n }\n for (const card of grid.children) card.style.borderColor = color('count')\n })\n</script>\n","motion":"<style>\n body { display: grid; place-items: center; padding: 16px; overflow: auto }\n svg { width: 100%; max-width: 600px; height: auto; flex: none }\n</style>\n<svg viewBox=\"0 0 600 240\" role=\"img\" aria-label=\"Repeating tile entry and exit above a duration and delay timeline\">\n <path d=\"M300,44v112\" stroke=\"var(--line)\" stroke-dasharray=\"3 4\"/>\n <path id=\"travel\" fill=\"none\"/>\n <rect id=\"tile\" x=\"268\" y=\"64\" width=\"64\" height=\"64\" rx=\"8\" fill=\"var(--bg)\" stroke-width=\"2\"/>\n <g id=\"timeline\"></g>\n <path id=\"playhead\" d=\"M0,186v20\" stroke=\"var(--fg)\" stroke-width=\"2\"/>\n</svg>\n<script>\n const tile = document.getElementById('tile'), travel = document.getElementById('travel')\n const timeline = document.getElementById('timeline'), playhead = document.getElementById('playhead')\n const color = (name) => bench.params.some((p) => p.name === name) ? bench.color(name) : 'var(--line)'\n const curves = { linear: [0, 0, 1, 1], ease: [0.25, 0.1, 0.25, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }\n const bezier = (t, a, b) => 3 * (1 - t) ** 2 * t * a + 3 * (1 - t) * t ** 2 * b + t ** 3\n let v = { duration: 600, delay: 200, distance: 120, easing: 'ease-out' }, start = null\n function ease(t) {\n if (t <= 0 || t >= 1) return t\n const [x1, y1, x2, y2] = curves[v.easing] || curves.linear\n let lo = 0, hi = 1\n for (let i = 0; i < 24; i++) {\n const mid = (lo + hi) / 2\n if (bezier(mid, x1, x2) < t) lo = mid\n else hi = mid\n }\n return bezier((lo + hi) / 2, y1, y2)\n }\n bench.on((values) => {\n v = { duration: 600, delay: 200, distance: 120, easing: 'ease-out', ...values }\n start = null\n travel.setAttribute('d', `M${300 - v.distance},148v8M${300 + v.distance},148v8M${300 - v.distance},152H${300 + v.distance}`)\n travel.setAttribute('stroke', color('distance'))\n tile.setAttribute('stroke', color('easing'))\n const leg = v.delay + v.duration + 400, total = leg * 2\n let time = 0\n // Time spans are area measurements; keep the tile and neutral rest spans as actual fills.\n const hatches = `<defs>${['delay', 'duration'].map((name) => `<pattern id=\"${name}-hatch\" width=\"6\" height=\"6\" patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\">\n <path d=\"M0.5,0V6\" fill=\"none\" stroke=\"${color(name)}\" stroke-width=\"0.75\" stroke-opacity=\"0.65\" />\n </pattern>`).join('')}</defs>`\n timeline.innerHTML = hatches + [v.delay, v.duration, 400, v.delay, v.duration, 400].map((ms, i) => {\n const x = 140 + time / total * 320\n time += ms\n const ink = i % 3 === 0 ? 'url(#delay-hatch)' : i % 3 === 1 ? 'url(#duration-hatch)' : 'var(--line)'\n return `<rect x=\"${x}\" y=\"192\" width=\"${ms / total * 320}\" height=\"8\" fill=\"${ink}\"/>`\n }).join('')\n })\n function frame(now) {\n if (start === null) start = now\n const leg = v.delay + v.duration + 400, cycle = (now - start) % (leg * 2)\n const entry = cycle < leg, time = cycle % leg\n const p = ease(Math.max(0, Math.min(1, (time - v.delay) / v.duration)))\n tile.setAttribute('transform', `translate(${entry ? -v.distance * (1 - p) : v.distance * p},0)`)\n tile.setAttribute('opacity', entry ? p : 1 - p)\n playhead.setAttribute('transform', `translate(${140 + cycle / (leg * 2) * 320},0)`)\n requestAnimationFrame(frame)\n }\n requestAnimationFrame(frame)\n</script>\n","shadow":"<style>\n /* The surface fills the frame, with the tile in its middle at true size, so it fits any width without scaling. */\n body { padding: 16px }\n #surface { position: relative; width: 100%; height: 100%; overflow: hidden; background: color-mix(in oklab, var(--fg) 8%, var(--bg)); border: 1px solid var(--line); border-radius: 8px }\n #tile { position: absolute; width: 120px; height: 100px; border-radius: 8px; background: var(--bg); border: 1px solid var(--dim) }\n #tile::after { content: ''; position: absolute; inset: 26px; border-top: 2px solid var(--line); border-bottom: 2px solid var(--line) }\n svg { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none }\n</style>\n<div id=\"surface\" role=\"img\" aria-label=\"Raised tile casting an adjustable shadow with offset, blur and spread guides\"><div id=\"tile\"></div><svg id=\"guides\"></svg></div>\n<script>\n const surface = document.getElementById('surface'), tile = document.getElementById('tile'), guides = document.getElementById('guides')\n const bound = (name) => bench.params.some((p) => p.name === name)\n function draw(values) {\n const v = { x: 12, y: 16, blur: 24, spread: 0, ...values }\n const cx = Math.round(surface.clientWidth / 2), cy = Math.round(surface.clientHeight / 2)\n const left = cx - 60, top = cy - 50\n tile.style.left = `${left}px`\n tile.style.top = `${top}px`\n tile.style.boxShadow = `${v.x}px ${v.y}px ${v.blur}px ${v.spread}px rgb(0 0 0 / 0.32)`\n const x = cx + v.x, y = cy + v.y\n guides.innerHTML = `\n ${bound('x') ? `<path d=\"M${cx},${top - 28}v8M${x},${top - 28}v8M${cx},${top - 24}H${x}\" fill=\"none\" stroke=\"${bench.color('x')}\"/>` : ''}\n ${bound('y') ? `<path d=\"M${left - 24},${cy}h8M${left - 24},${y}h8M${left - 20},${cy}V${y}\" fill=\"none\" stroke=\"${bench.color('y')}\"/>` : ''}\n ${bound('blur') ? `<circle cx=\"${x}\" cy=\"${y}\" r=\"${v.blur}\" fill=\"none\" stroke=\"${bench.color('blur')}\" stroke-dasharray=\"2 4\"/>` : ''}\n ${bound('spread') ? `<rect x=\"${left + v.x - v.spread}\" y=\"${top + v.y - v.spread}\" width=\"${120 + 2 * v.spread}\" height=\"${100 + 2 * v.spread}\" rx=\"${Math.max(0, 8 + v.spread)}\" fill=\"none\" stroke=\"${bench.color('spread')}\" stroke-dasharray=\"5 4\"/>` : ''}`\n }\n bench.on(draw)\n addEventListener('resize', () => draw(bench.values))\n</script>\n","type":"<style>\n body { display: flex; align-items: center; justify-content: center; padding: 16px }\n .machine { display: flex; flex-direction: column; align-items: center; width: 100%; max-width: 380px; max-height: 100% }\n /* The sheet: real text in the chosen face, set at true size. */\n .paper { position: relative; width: 82%; flex: 0 1 190px; min-height: 60px; overflow: hidden; padding: 14px 16px 0 30px;\n background: color-mix(in oklab, var(--bg) 90%, var(--fg)); border: 1.5px solid var(--fg); border-bottom: 0; color: var(--fg) }\n .paper p { margin: 0; overflow-wrap: anywhere }\n .guides { position: absolute; inset: 14px 0 0 0; pointer-events: none }\n .size { position: absolute; left: 10px; top: 14px; width: 8px; border: 2px solid; border-right: 0 }\n svg { width: 100%; flex: none; overflow: visible }\n</style>\n<!--\n Typewriter: a sheet of specimen text in the chosen face. The typewheel stands for the family, the bracket in the\n margin for the size, the line guides on the sheet for the leading, and the ink ribbon thickens with the weight; each\n in the colour of its knob.\n-->\n<div class=\"machine\" role=\"img\" aria-label=\"A typewriter with a sheet of specimen text\">\n <div class=\"paper\" id=\"paper\">\n <div class=\"guides\" id=\"guides\"></div>\n <div class=\"size\" id=\"size\"></div>\n <p>Hamburgefonstiv</p>\n <p>The quick brown fox jumps over the lazy dog.</p>\n <p>0123456789 & ?! (a/b) — “quote”</p>\n </div>\n <svg id=\"body\" viewBox=\"0 0 340 128\"></svg>\n</div>\n<script>\n const paper = document.getElementById('paper'), guides = document.getElementById('guides'), size = document.getElementById('size'), body = document.getElementById('body')\n const ink = (name) => bench.lane(name) ? bench.color(name) : 'var(--dim)'\n const line = 'stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" fill=\"none\"'\n\n bench.on(({ family = 'Iowan Old Style', size: px = 18, leading = 1.4, weight = 400 }) => {\n paper.style.font = `${weight} ${px}px/${leading} \"${family}\", serif`\n // A bracket as tall as the type size, and a guide on every baseline, one leading apart.\n size.style.height = `${px}px`\n size.style.borderColor = ink('size')\n size.style.display = bench.lane('size') ? '' : 'none'\n const pitch = px * leading\n guides.style.background = bench.lane('leading')\n ? `repeating-linear-gradient(to bottom, transparent 0 ${pitch - 1}px, color-mix(in oklab, ${bench.color('leading')} 55%, transparent) ${pitch - 1}px ${pitch}px)`\n : 'none'\n\n // The machine: platen, typewheel, ribbon, carriage lever, keys.\n const spokes = Array.from({ length: 12 }, (_, i) => {\n const a = (i / 12) * Math.PI * 2\n return `<line x1=\"${Math.cos(a) * 4}\" y1=\"${Math.sin(a) * 4}\" x2=\"${Math.cos(a) * 13}\" y2=\"${Math.sin(a) * 13}\" />`\n }).join('')\n // Heavier type, a thicker ribbon of ink.\n const ribbon = 1 + ((weight - 100) / 800) * 7\n // The carriage lever lifts higher for wider line spacing.\n const lever = -20 - Math.min(1, Math.max(0, (leading - 0.9) / 1.5)) * 45\n const keys = [[10, 26], [9, 41], [8, 56]].map(([count, y], row) => Array.from({ length: count }, (_, i) =>\n `<circle cx=\"${170 - (count - 1) * 12 + i * 24 + row * 4}\" cy=\"${y + 52}\" r=\"7\" />`).join('')).join('')\n body.innerHTML = `\n <g ${line} stroke=\"var(--fg)\">\n <rect x=\"14\" y=\"0\" width=\"312\" height=\"16\" rx=\"8\" />\n <circle cx=\"8\" cy=\"8\" r=\"6\" /><circle cx=\"332\" cy=\"8\" r=\"6\" />\n <path d=\"M40,22h260l26,96h-312z\" />\n <path d=\"M110,22v8h120v-8\" />\n <rect x=\"120\" y=\"116\" width=\"100\" height=\"0\" />\n </g>\n <g ${line} stroke=\"var(--dim)\">${keys}<rect x=\"110\" y=\"122\" width=\"120\" height=\"0\" /><path d=\"M110,118h120\" /></g>\n <g transform=\"translate(14,8) rotate(${lever})\" ${line} stroke=\"${ink('leading')}\"><path d=\"M0,0h-34\" /><circle cx=\"-38\" cy=\"0\" r=\"4\" /></g>\n <g transform=\"translate(170,46)\" ${line} stroke=\"${ink('family')}\"><circle r=\"15\" />${spokes}<circle r=\"3\" /></g>\n <g ${line} stroke=\"${ink('weight')}\">\n <circle cx=\"96\" cy=\"46\" r=\"11\" /><circle cx=\"244\" cy=\"46\" r=\"11\" />\n <path d=\"M107,46H155M185,46H233\" stroke-width=\"${ribbon}\" stroke-linecap=\"butt\" />\n </g>`\n })\n</script>\n"}
const LANES = ['blue', 'green', 'white', 'orange']
const KEYS = [['y', 'h'], ['u', 'j'], ['i', 'k'], ['o', 'l']]
/** Each lane's MIDI control change number, on any channel: an AKAI LPD8's top row on its first program. */
const MIDI_CC = [1, 2, 3, 4]
// The dial sweeps 270°, from 7:30 to 4:30, like a hardware encoder's travel.
const SWEEP = 270
const START = 135
// Pixels of drag per detent: a finger travels further than a mouse. Scrolling builds up, by distance.
const DRAG_STEP = 6
const TOUCH_STEP = 4
const WHEEL_STEP = 40
// The post's default click, fixed here: a short band-passed noise burst mixed with a falling triangle blip.
const DEFAULT_CLICK = Object.freeze({ pitch: 2400, decay: 18, noise: 0.6, volume: 0.35 })
const MIN_GAP = 0.018
let context
let noiseBuffer
let last = 0
function audio() {
if (!('AudioContext' in window)) return undefined
context ??= new AudioContext()
if (!noiseBuffer) {
noiseBuffer = context.createBuffer(1, Math.ceil(context.sampleRate * 0.25), context.sampleRate)
const data = noiseBuffer.getChannelData(0)
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1
}
if (context.state === 'suspended') void context.resume()
return context
}
function click() {
const { pitch, decay, noise, volume } = DEFAULT_CLICK
const ctx = audio()
if (!ctx || ctx.state !== 'running') return
const now = ctx.currentTime
// Shared by every panel: a fast wheel or MIDI sweep must not pile up clicks.
if (now - last < MIN_GAP) return
last = now
const length = decay / 1000
const out = ctx.createGain()
out.gain.setValueAtTime(0.0001, now)
out.gain.exponentialRampToValueAtTime(volume, now + 0.0015)
out.gain.exponentialRampToValueAtTime(0.0001, now + 0.0015 + length)
out.connect(ctx.destination)
const source = ctx.createBufferSource()
source.buffer = noiseBuffer
const band = ctx.createBiquadFilter()
band.type = 'bandpass'
band.frequency.value = pitch
band.Q.value = 1.5
const noiseLevel = ctx.createGain()
noiseLevel.gain.value = noise * 2.5
source.connect(band).connect(noiseLevel).connect(out)
source.start(now)
source.stop(now + length + 0.01)
const osc = ctx.createOscillator()
osc.type = 'triangle'
osc.frequency.setValueAtTime(pitch, now)
osc.frequency.exponentialRampToValueAtTime(pitch * 0.5, now + length)
const toneLevel = ctx.createGain()
toneLevel.gain.value = 1 - noise
osc.connect(toneLevel).connect(out)
osc.start(now)
osc.stop(now + length + 0.01)
}
function clickAfterRender() {
// Safari needs the wake-up inside the gesture, not the frame callback.
audio()
requestAnimationFrame(click)
}
/** The pointer leaves the knob during a drag; don't let it select the surrounding page. */
function holdSelection(hold) {
const root = document.documentElement.style
root.userSelect = hold ? 'none' : ''
root.setProperty('-webkit-user-select', hold ? 'none' : '')
if (hold) window.getSelection()?.removeAllRanges()
}
// Tailwind's scales, so a knob steps through the values the code already uses. `token` is how the code writes one.
const stops = (entries) => entries.map(([label, value]) => ({ label, value }))
const SCALES = {
radius: { token: 'rounded-{label}', unit: 'px', stops: stops([['none', 0], ['xs', 2], ['sm', 4], ['md', 6], ['lg', 8], ['xl', 12], ['2xl', 16], ['3xl', 24], ['4xl', 32]]) },
spacing: { token: '{label}', unit: 'px', stops: stops([['0', 0], ['0.5', 2], ['1', 4], ['1.5', 6], ['2', 8], ['2.5', 10], ['3', 12], ['4', 16], ['5', 20], ['6', 24], ['8', 32], ['10', 40], ['12', 48], ['16', 64], ['20', 80], ['24', 96]]) },
text: { token: 'text-{label}', unit: 'px', stops: stops([['xs', 12], ['sm', 14], ['base', 16], ['lg', 18], ['xl', 20], ['2xl', 24], ['3xl', 30], ['4xl', 36], ['5xl', 48], ['6xl', 60]]) },
leading: { token: 'leading-{label}', unit: '', stops: stops([['none', 1], ['tight', 1.25], ['snug', 1.375], ['normal', 1.5], ['relaxed', 1.625], ['loose', 2]]) },
'font-weight': { token: 'font-{label}', unit: '', stops: stops([['thin', 100], ['extralight', 200], ['light', 300], ['normal', 400], ['medium', 500], ['semibold', 600], ['bold', 700], ['extrabold', 800], ['black', 900]]) },
tracking: { token: 'tracking-{label}', unit: 'em', stops: stops([['tighter', -0.05], ['tight', -0.025], ['normal', 0], ['wide', 0.025], ['wider', 0.05], ['widest', 0.1]]) },
}
// ---- Model: params, values and how a knob turns them ----
/** Fill in a param's defaults: its scale's stops and token, a range around them, a step. */
function normalize(input) {
const param = { ...input }
param.label ??= param.name
if (param.options) param.type ??= 'choice'
param.type ??= 'number'
if (param.type !== 'number') return param
const scale = typeof param.stops === 'string' ? param.stops : param.scale
if (scale) {
const known = SCALES[scale]
if (!known) throw new Error(`quadknob: unknown scale "${scale}" (${Object.keys(SCALES).join(', ')})`)
param.stops = typeof param.stops === 'string' || !param.stops ? known.stops : param.stops
param.token ??= known.token
param.unit ??= known.unit
}
if (Array.isArray(param.stops)) {
param.stops = param.stops.map((stop) => typeof stop === 'number' ? { label: String(stop), value: stop } : stop)
.sort((a, b) => a.value - b.value)
param.min ??= param.stops[0].value
param.max ??= param.stops.at(-1).value
}
param.min ??= 0
param.max ??= 100
param.step ??= 1
return param
}
function defaultValue(param) {
if (param.type === 'choice') return param.default ?? param.options[0]
const value = param.default ?? param.min
return param.stops ? nearestStop(param.stops, value).value : value
}
function snap(param, value) {
const stepped = param.min + Math.round((value - param.min) / param.step) * param.step
// Round away float noise from the step arithmetic, e.g. 0.1 + 0.2.
const decimals = (String(param.step).split('.')[1] ?? '').length
return Math.min(param.max, Math.max(param.min, Number(stepped.toFixed(decimals))))
}
function coerce(param, value) {
if (param.type === 'choice') return param.options.includes(value) ? value : defaultValue(param)
const number = Number(value)
if (!Number.isFinite(number)) return defaultValue(param)
return stopAt(param, number)?.value ?? snap(param, number)
}
const nearestStop = (stops, value) => stops.reduce((best, stop) => Math.abs(stop.value - value) < Math.abs(best.value - value) ? stop : best)
const stopAt = (param, value) => param.stops?.find((stop) => Math.abs(stop.value - Number(value)) < 1e-6)
/** The value `detents` stops on from `value`. Off the scale, the first detent lands on the next stop that way. */
function turnStops(list, value, detents) {
const on = list.findIndex((stop) => Math.abs(stop.value - value) < 1e-6)
const from = on !== -1 ? on
: detents > 0 ? list.findIndex((stop) => stop.value > value) - 1
: list.findLastIndex((stop) => stop.value < value) + 1
const index = from === -2 ? list.length - 1 : from
return list[Math.min(list.length - 1, Math.max(0, index + detents))].value
}
/** Turn a knob by `detents`: numbers by steps, or by stops unless turned `free`; choices by options. */
function turn(param, value, detents, free = false) {
if (param.type === 'choice') {
const index = Math.max(0, param.options.indexOf(value))
return param.options[Math.min(param.options.length - 1, Math.max(0, index + detents))]
}
return param.stops && !free ? turnStops(param.stops, Number(value), detents) : snap(param, Number(value) + detents * param.step)
}
/** How far through its range a value is, from 0 to 1. Stops sit evenly round the dial. */
function position(param, value) {
if (param.type === 'choice') return param.options.length < 2 ? 0 : param.options.indexOf(value) / (param.options.length - 1)
const v = Number(value)
if (param.stops) {
const list = param.stops
if (list.length < 2 || v <= list[0].value) return 0
const next = list.findIndex((stop) => stop.value >= v)
if (next === -1) return 1
const low = list[next - 1], high = list[next]
return (next - 1 + (v - low.value) / (high.value - low.value)) / (list.length - 1)
}
return param.max === param.min ? 0 : (v - param.min) / (param.max - param.min)
}
/** The value at `t` (0 to 1): the inverse of `position`, for absolute MIDI knobs. */
function fromPosition(param, t) {
t = Math.min(1, Math.max(0, t))
if (param.type === 'choice') return param.options[Math.round(t * (param.options.length - 1))]
if (param.stops) return param.stops[Math.round(t * (param.stops.length - 1))].value
return snap(param, param.min + t * (param.max - param.min))
}
/** The value as a knob shows it: a token by its short name, a value off the scale in brackets, like Tailwind's. */
function formatValue(param, value) {
if (param.type === 'choice') return String(value)
if (param.stops) return stopAt(param, value)?.label ?? `[${value}${param.unit ?? ''}]`
return `${value}${param.unit ?? ''}`
}
/** The value as the agent reads it: a token as the code writes it with its value, like "rounded-lg (8px)". */
function tokenValue(param, value) {
if (param.type === 'choice' || !param.stops) return formatValue(param, value)
const stop = stopAt(param, value)
const raw = `${value}${param.unit ?? ''}`
return stop ? `${(param.token ?? '{label}').replaceAll('{label}', stop.label)} (${raw})` : `${raw}, off the scale`
}
// ---- Controls: lane keys, MIDI shared by every panel on the page ----
function laneTurn(key) {
for (const [lane, [up, down]] of KEYS.entries()) {
if (key === up) return { lane, detents: 1 }
if (key === down) return { lane, detents: -1 }
if (key === up.toUpperCase()) return { lane, detents: 10 }
if (key === down.toUpperCase()) return { lane, detents: -10 }
}
}
// Within a step of the 0–127 range counts as reaching the value.
const PICKUP_TOLERANCE = 1.5 / 127
/** Soft takeover: an absolute knob takes over only once it reaches the value, or passes it between two messages. */
function picksUp(current, next, last) {
if (Math.abs(next - current) <= PICKUP_TOLERANCE) return true
return last !== undefined && Math.sign(last - current) !== Math.sign(next - current)
}
const midi = {
access: undefined,
status: 'off',
owner: undefined,
panels: new Set(),
checked: false,
emit() { for (const panel of midi.panels) panel.renderMidi() },
listen() {
for (const input of midi.access?.inputs.values() ?? []) {
input.onmidimessage = (event) => {
const data = event.data
if (!data || data.length < 3 || (data[0] & 0xf0) !== 0xb0) return
const lane = MIDI_CC.indexOf(data[1])
if (lane !== -1) midi.owner?.midiControl(lane, data[2] / 127)
}
}
midi.emit()
},
async connect() {
if (!navigator.requestMIDIAccess) { midi.status = 'unsupported'; return midi.emit() }
try {
midi.access = await navigator.requestMIDIAccess()
midi.access.onstatechange = midi.listen
midi.status = 'on'
midi.listen()
} catch {
midi.status = 'denied'
midi.emit()
}
},
/** Connect without asking when the visitor granted MIDI before: browsers prompt for it, so otherwise wait for a click. */
connectIfGranted() {
if (midi.checked) return
midi.checked = true
if (!navigator.requestMIDIAccess) { midi.status = 'unsupported'; return midi.emit() }
navigator.permissions?.query({ name: 'midi' }).then((result) => { if (result.state === 'granted') midi.connect() }).catch(() => {})
},
claim(panel) {
if (midi.owner === panel) return
midi.owner = panel
midi.emit()
},
}
// ---- Drawing ----
const svg = (tag, attrs) => `<${tag} ${Object.entries(attrs).map(([k, v]) => `${k}="${v}"`).join(' ')}/>`
const point = (cx, cy, r, angle) => [cx + r * Math.cos(angle * Math.PI / 180), cy + r * Math.sin(angle * Math.PI / 180)]
function arc(cx, cy, r, from, to) {
const [x1, y1] = point(cx, cy, r, from), [x2, y2] = point(cx, cy, r, to)
return `M${x1},${y1}A${r},${r} 0 ${to - from > 180 ? 1 : 0} 1 ${x2},${y2}`
}
const escape = (text) => String(text).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c])
function dial(t, hardware) {
const angle = START + t * SWEEP
return `<svg viewBox="0 0 40 40" aria-hidden="true">
${svg('path', { d: arc(20, 20, 16, START, START + SWEEP), fill: 'none', stroke: 'var(--qk-line)', 'stroke-width': 2, 'stroke-linecap': 'round' })}
${t > 0 ? svg('path', { d: arc(20, 20, 16, START, angle), fill: 'none', stroke: 'currentColor', 'stroke-width': 2, 'stroke-linecap': 'round' }) : ''}
${svg('circle', { cx: 20, cy: 20, r: 10, fill: 'none', stroke: 'currentColor', 'stroke-width': 1.5 })}
${hardware !== undefined ? svg('circle', { cx: point(20, 20, 16, START + hardware * SWEEP)[0], cy: point(20, 20, 16, START + hardware * SWEEP)[1], r: 2.5, fill: 'var(--qk-dim)' }) : ''}
${svg('line', { x1: point(20, 20, 4, angle)[0], y1: point(20, 20, 4, angle)[1], x2: point(20, 20, 10, angle)[0], y2: point(20, 20, 10, angle)[1], stroke: 'currentColor', 'stroke-width': 2, 'stroke-linecap': 'round' })}
</svg>`
}
/** The value drawn large around a finger turning a knob, as the finger hides the knob. Lives on the page, not the panel. */
const touchRing = {
element: undefined,
show(x, y, color, label, shown, t) {
const R = 64, size = R * 2 + 16, c = size / 2
if (!touchRing.element) {
touchRing.element = document.body.appendChild(document.createElement('div'))
touchRing.element.setAttribute('aria-hidden', 'true')
}
const el = touchRing.element
el.setAttribute('style', `position:fixed;z-index:2147483647;pointer-events:none;left:${x - c}px;top:${y - c}px;width:${size}px;height:${size}px;color:${color};font-family:ui-monospace,SFMono-Regular,Menlo,monospace`)
const angle = START + t * SWEEP
const [dx, dy] = point(c, c, R, angle)
el.innerHTML = `<svg viewBox="0 0 ${size} ${size}" style="position:absolute;inset:0;overflow:visible">
${svg('circle', { cx: c, cy: c, r: R + 8, fill: 'rgb(255 255 255 / 0.75)' })}
${svg('path', { d: arc(c, c, R, START, START + SWEEP), fill: 'none', stroke: 'rgb(0 0 0 / 0.15)', 'stroke-width': 6, 'stroke-linecap': 'round' })}
${t > 0 ? svg('path', { d: arc(c, c, R, START, angle), fill: 'none', stroke: 'currentColor', 'stroke-width': 6, 'stroke-linecap': 'round' }) : ''}
${svg('circle', { cx: dx, cy: dy, r: 7, fill: 'currentColor', stroke: 'white', 'stroke-width': 2 })}
</svg>
<div style="position:absolute;bottom:100%;left:50%;transform:translateX(-50%);margin-bottom:4px;padding:4px 10px;border-radius:6px;background:rgb(255 255 255 / 0.92);box-shadow:0 2px 12px rgb(0 0 0 / 0.15);text-align:center;white-space:nowrap">
<div style="font-size:11px;color:#57606a">${escape(label)}</div>
<div style="font-size:20px;line-height:1.2;font-weight:300;color:#1b1f24">${escape(shown)}</div>
</div>`
},
hide() { touchRing.element?.remove(); touchRing.element = undefined },
}
// ---- Figures: a little drawing of what each knob does, in a sandboxed frame ----
// Runs inside the figure document. Defines `bench` (and `quadknob`), synced with the panel; values mirror as CSS variables.
function prelude(initial) {
let state = initial
const listeners = []
const root = document.documentElement
const lane = (name) => state.params.find((param) => param.name === name)?.lane
function apply() {
for (const [name, color] of Object.entries(state.colors)) root.style.setProperty(`--${name}`, color)
for (const [name, font] of Object.entries(state.fonts)) root.style.setProperty(`--font-${name}`, font)
for (const param of state.params) root.style.setProperty(`--${param.name}-color`, state.colors[param.lane])
for (const [name, value] of Object.entries(state.values)) {
if (typeof value !== 'string') root.style.setProperty(`--${name}`, String(Number(value)))
}
Object.assign(window.bench, { values: state.values, before: state.before, params: state.params })
for (const listener of listeners) listener(state.values)
}
window.bench = window.quadknob = {
values: state.values,
before: state.before,
params: state.params,
lane,
color: (name) => state.colors[lane(name)] ?? state.colors.fg,
on(listener) {
listeners.push(listener)
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => listener(state.values), { once: true })
else listener(state.values)
},
}
apply()
addEventListener('message', (event) => {
if (event.source !== parent || event.data?.type !== 'state') return
state = event.data.state
apply()
})
}
const FIGURE_BASE = '*{box-sizing:border-box}html,body{margin:0;height:100%;background:transparent;'
+ 'color:var(--fg);font:13px/1.4 var(--font-mono);font-variant-numeric:tabular-nums}'
// ---- The element ----
const STYLE = `
:host {
--qk-bg: #ffffff; --qk-surface: #f7f7f5; --qk-fg: #1b1f24; --qk-dim: #6a737d; --qk-line: #d9d9d3;
--qk-blue: oklch(0.52 0.29 241); --qk-green: oklch(0.59 0.305 156); --qk-white: #111111; --qk-orange: oklch(0.65 0.23 43);
--qk-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--qk-figure-height: 240px;
display: block; color: var(--qk-dim); font: 12px/1.4 var(--qk-mono); -webkit-tap-highlight-color: transparent;
}
@media (prefers-color-scheme: dark) {
:host(:not([theme="light"])) {
--qk-bg: #17191c; --qk-surface: #1e2125; --qk-fg: #e9ecef; --qk-dim: #9aa3ad; --qk-line: #343a40;
--qk-blue: oklch(0.57 0.3 258); --qk-green: oklch(0.62 0.21 156); --qk-white: oklch(0.92 0.005 250); --qk-orange: oklch(0.65 0.2 40);
}
}
:host([theme="dark"]) {
--qk-bg: #17191c; --qk-surface: #1e2125; --qk-fg: #e9ecef; --qk-dim: #9aa3ad; --qk-line: #343a40;
--qk-blue: oklch(0.57 0.3 258); --qk-green: oklch(0.62 0.21 156); --qk-white: oklch(0.92 0.005 250); --qk-orange: oklch(0.65 0.2 40);
}
:host([floating]) { position: fixed; z-index: 2147483646; right: 16px; bottom: 16px; width: min(440px, calc(100vw - 32px)); }
:host([hidden]) { display: none; }
* { box-sizing: border-box; }
[hidden] { display: none !important; }
.panel { position: relative; overflow: hidden; border: 1px solid var(--qk-line); border-radius: 10px; background: var(--qk-bg); outline: none; }
/* A fat ring while the keyboard is in the panel, so it's clear which panel the lane keys turn. */
.panel:has(:focus-visible), .panel:focus-visible { outline: 3px solid var(--qk-fg); outline-offset: 4px; }
:host([floating]) .panel { box-shadow: 0 12px 40px rgb(0 0 0 / 0.18); }
.head { display: flex; align-items: center; gap: 8px; padding: 6px 12px; border-bottom: 1px solid var(--qk-line); background: var(--qk-surface); color: var(--qk-fg); }
.head .title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.stage { position: relative; height: var(--qk-figure-height); border-bottom: 1px solid var(--qk-line); background: var(--qk-surface); }
.stage iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; margin: 0; }
.before { position: absolute; top: 8px; left: 12px; padding: 1px 6px; border-radius: 3px; background: var(--qk-fg); color: var(--qk-bg); }
.knobs { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); }
.knob { display: flex; flex-direction: column; align-items: center; gap: 4px; min-width: 0; padding: 14px 6px; cursor: ns-resize; touch-action: none; user-select: none; -webkit-user-select: none; outline: none; }
.knob:focus-visible { background: var(--qk-surface); }
.knob svg { width: 40px; height: 40px; flex: none; }
.knob .label { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--qk-dim); font-size: 11px; }
.knob .label .raw { opacity: 0.7; }
.knob .value { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--qk-fg); font-size: 22px; font-weight: 300; line-height: 1; font-variant-numeric: tabular-nums; }
.knob .value.long { font-size: 15px; line-height: 22px; }
.knob.empty { cursor: default; color: var(--qk-line); }
.knob.empty .value { color: var(--qk-line); }
.keys { display: flex; gap: 2px; }
kbd { display: inline-flex; align-items: center; justify-content: center; min-width: 16px; height: 16px; padding: 0 4px; border: 1px solid var(--qk-line); border-radius: 3px; background: var(--qk-bg); color: var(--qk-dim); font: 10px/1 var(--qk-mono); }
:host([compact]) .knob { flex-direction: row; justify-content: flex-start; gap: 8px; padding: 8px 10px; }
:host([compact]) .knob svg { width: 32px; height: 32px; }
:host([compact]) .knob .text { display: flex; min-width: 0; flex-direction: column; gap: 3px; }
:host([compact]) .knob .value { font-size: 16px; }
:host([compact]) .knob .value.long { font-size: 13px; line-height: 16px; }
:host([compact]) .keys { display: none; }
.text { display: contents; }
.blue { color: var(--qk-blue); } .green { color: var(--qk-green); } .white { color: var(--qk-white); } .orange { color: var(--qk-orange); }
.foot { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 14px; padding: 7px 12px; border-top: 1px solid var(--qk-line); }
.foot .hints { flex: 1; display: inline-flex; flex-wrap: wrap; align-items: center; gap: 3px; min-width: 0; }
button { padding: 0; border: 0; background: none; color: var(--qk-dim); font: inherit; cursor: pointer; }
button:hover { color: var(--qk-fg); }
button.midi.off { text-decoration: underline dotted; text-underline-offset: 2px; }
button.done { padding: 3px 10px; border: 1px solid var(--qk-line); border-radius: 5px; background: var(--qk-bg); color: var(--qk-fg); }
button.done:hover { background: var(--qk-surface); }
.copied { flex-basis: 100%; }
.copied textarea { width: 100%; margin-top: 4px; padding: 6px; border: 1px solid var(--qk-line); border-radius: 4px; background: var(--qk-surface); color: var(--qk-fg); font: 11px/1.4 var(--qk-mono); resize: vertical; }
.touch-hint { display: none; }
@media (max-width: 639px) {
.knobs { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.keys, .foot .key-hints { display: none; }
.touch-hint { display: inline; }
/* Floating over a phone screen: a short figure and compact knobs, so the page stays visible. */
:host([floating]) { right: 8px; bottom: 8px; width: calc(100vw - 16px); }
:host([floating]) .stage { height: min(var(--qk-figure-height), 22vh); }
:host([floating]) .knob { flex-direction: row; justify-content: flex-start; gap: 8px; padding: 8px 10px; }
:host([floating]) .knob svg { width: 32px; height: 32px; }
:host([floating]) .knob .text { display: flex; min-width: 0; flex-direction: column; gap: 3px; }
:host([floating]) .knob .value { font-size: 16px; }
}
`
let panels = 0
class QuadknobPanel extends HTMLElement {
static observedAttributes = ['params', 'values', 'css', 'target', 'figure', 'label']
#params = []
#values = {}
#before = {}
#peek = false
#pickups = []
#hardware = []
#figure = undefined
#frame = undefined
#loaded = false
#style = undefined
#applied = []
#id = ++panels
constructor() {
super()
this.attachShadow({ mode: 'open' }).innerHTML = `<style>${STYLE}</style>
<div class="panel" part="panel" tabindex="-1" role="group">
<div class="head" part="head" hidden><span class="title"></span></div>
<div class="stage" part="stage" hidden></div>
<div class="knobs" part="knobs"></div>
<div class="foot" part="foot">
<span class="hints">
<span class="touch-hint">Drag a knob up or down.</span>
<span class="key-hints"><kbd>y</kbd><kbd>h</kbd> … <kbd>o</kbd><kbd>l</kbd> turn, hold <kbd>Space</kbd> for before<span class="alt-hint">, <kbd>⌥</kbd> between tokens</span></span>
</span>
<button type="button" class="midi"></button>
<button type="button" class="done" part="done">Done</button>
</div>
</div>`
const root = this.shadowRoot
this.$ = (selector) => root.querySelector(selector)
const panel = this.$('.panel')
panel.addEventListener('keydown', (event) => this.#keydown(event))
panel.addEventListener('keyup', (event) => { if (event.key === ' ') this.#setPeek(false) })
panel.addEventListener('focusout', (event) => { if (!panel.contains(event.relatedTarget)) this.#setPeek(false) })
panel.addEventListener('pointerdown', () => midi.claim(this), true)
panel.addEventListener('focusin', () => midi.claim(this))
panel.addEventListener('click', () => {
// Safari doesn't focus clicked buttons. A click anywhere still gives this panel the lane keys.
if (!panel.contains(root.activeElement)) panel.focus({ preventScroll: true })
})
this.$('.done').addEventListener('click', () => this.done())
this.$('.midi').addEventListener('click', () => {
midi.claim(this)
if (midi.status === 'off') midi.connect()
})
}
connectedCallback() {
midi.panels.add(this)
if (!midi.owner) midi.owner = this
midi.connectIfGranted()
if (!this.#params.length && this.hasAttribute('params')) this.#readParams()
this.#readFigure()
this.#render()
}
disconnectedCallback() {
midi.panels.delete(this)
if (midi.owner === this) { midi.owner = midi.panels.values().next().value; midi.emit() }
this.#style?.remove()
this.#style = undefined
this.#clearTarget()
touchRing.hide()
}
attributeChangedCallback(name) {
if (!this.isConnected) return
if (name === 'params') this.#readParams()
else if (name === 'values') this.values = JSON.parse(this.getAttribute('values') || '{}')
else if (name === 'figure') this.#readFigure()
this.#render()
}
/** Up to four params, in lane order: blue, green, white, orange. */
get params() { return this.#params }
set params(list) {
if (list.length > 4) throw new Error('quadknob: four knobs, no more')
this.#params = list.map(normalize)
const initial = this.hasAttribute('values') ? JSON.parse(this.getAttribute('values') || '{}') : {}
this.#values = Object.fromEntries(this.#params.map((param) => [param.name, param.name in initial ? coerce(param, initial[param.name]) : defaultValue(param)]))
this.#before = { ...this.#values }
this.#pickups = []
this.#hardware = []
this.#loaded = false
this.#figure = undefined
if (this.isConnected) { this.#readFigure(); this.#render() }
}
get values() { return { ...this.#values } }
set values(values) {
for (const param of this.#params) if (param.name in values) this.#values[param.name] = coerce(param, values[param.name])
this.#update()
}
/** What Done copies: the label, then each knob's value as the code writes it. */
get summary() {
const list = this.#params.map((param) => `${param.label} ${tokenValue(param, this.#values[param.name])}`).join(', ')
const label = this.getAttribute('label')
return label ? `${label}: ${list}` : list
}
async done() {
const summary = this.summary
this.dispatchEvent(new CustomEvent('quadknob-done', { detail: { values: this.values, summary }, bubbles: true, composed: true }))
const foot = this.$('.foot')
foot.querySelector('.copied')?.remove()
const note = document.createElement('span')
note.className = 'copied'
try {
await navigator.clipboard.writeText(summary)
note.textContent = 'Copied. Paste it to your agent.'
} catch {
// No clipboard (an insecure page, or no permission): show it to copy by hand.
note.innerHTML = 'Copy this to your agent:<textarea rows="2" readonly></textarea>'
note.querySelector('textarea').value = summary
setTimeout(() => note.querySelector('textarea').select())
}
foot.append(note)
this.$('.done').textContent = 'Copied'
setTimeout(() => { this.$('.done').textContent = 'Done' }, 1500)
}
#readParams() {
try {
this.params = JSON.parse(this.getAttribute('params') || '[]')
} catch (error) {
console.error('quadknob: params must be JSON', error)
}
}
#readFigure() {
const template = this.querySelector('template')
const name = this.getAttribute('figure')
const figure = template ? template.innerHTML : name && name !== 'none' ? FIGURES[name] : undefined
if (name && name !== 'none' && !template && !figure) console.error(`quadknob: no figure "${name}" (${Object.keys(FIGURES).join(', ')})`)
if (figure === this.#figure) return
this.#figure = figure
const stage = this.$('.stage')
stage.hidden = !figure
stage.replaceChildren()
this.#frame = undefined
this.#loaded = false
if (!figure) return
const frame = document.createElement('iframe')
frame.setAttribute('sandbox', 'allow-scripts')
frame.setAttribute('title', this.getAttribute('label') || 'Figure')
const initial = JSON.stringify(this.#figureState()).replace(/</g, '\\u003c')
frame.srcdoc = `<!doctype html><meta charset="utf-8"><style>${FIGURE_BASE}</style>`
+ `<script>(${prelude})(${initial})<\/script>${figure}`
frame.addEventListener('load', () => { this.#loaded = true; this.#update() })
stage.append(frame)
this.#frame = frame
}
#figureState() {
const style = getComputedStyle(this)
const read = (name) => style.getPropertyValue(`--qk-${name}`).trim()
return {
values: this.#shown(),
before: this.#before,
params: this.#params.map((param, index) => ({ ...param, lane: LANES[index] })),
colors: { fg: read('fg'), bg: read('bg'), dim: read('dim'), line: read('line'), blue: read('blue'), green: read('green'), white: read('white'), orange: read('orange') },
fonts: { mono: read('mono'), sans: 'system-ui, -apple-system, "Segoe UI", sans-serif' },
}
}
#shown() { return this.#peek ? this.#before : this.#values }
#render() {
const label = this.getAttribute('label')
this.$('.head').hidden = !label
this.$('.title').textContent = label ?? ''
this.$('.alt-hint').hidden = !this.#params.some((param) => param.stops)
const knobs = this.$('.knobs')
knobs.replaceChildren(...LANES.map((lane, index) => this.#knob(lane, index)))
this.renderMidi()
this.#update()
}
#knob(lane, index) {
const param = this.#params[index]
const el = document.createElement('div')
el.className = `knob ${lane}${param ? '' : ' empty'}`
el.dataset.lane = lane
if (!param) {
el.setAttribute('aria-hidden', 'true')
el.innerHTML = `<svg viewBox="0 0 40 40">${svg('circle', { cx: 20, cy: 20, r: 14, fill: 'none', stroke: 'currentColor', 'stroke-dasharray': '2 3' })}</svg><span class="text"><span class="label"> </span><span class="value">—</span></span>`
return el
}
el.setAttribute('role', 'slider')
el.tabIndex = 0
el.setAttribute('aria-label', param.label)
if (param.type === 'number') {
el.setAttribute('aria-valuemin', param.min)
el.setAttribute('aria-valuemax', param.max)
}
el.innerHTML = `<span class="dial"></span><span class="text"><span class="label"></span><span class="value"></span></span>
<span class="keys"><kbd>${KEYS[index][0]}</kbd><kbd>${KEYS[index][1]}</kbd></span>`
el.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return
event.preventDefault()
this.#turn(index, (event.key === 'ArrowUp' ? 1 : -1) * (event.shiftKey ? 10 : 1), event.altKey)
})
let wheel = 0
el.addEventListener('wheel', (event) => {
event.preventDefault()
// Line-mode wheels (most mice) report lines, not pixels: one line is one detent. Reversing starts afresh.
const delta = -(event.deltaMode === WheelEvent.DOM_DELTA_LINE ? event.deltaY * WHEEL_STEP : event.deltaY)
if (Math.sign(delta) !== Math.sign(wheel)) wheel = 0
wheel += delta
const detents = Math.trunc(wheel / WHEEL_STEP)
if (!detents) return
wheel -= detents * WHEEL_STEP
this.#turn(index, detents * (event.shiftKey ? 10 : 1), event.altKey)
}, { passive: false })
let drag
const ring = (event) => {
if (!drag?.touch) return
const value = this.#shown()[param.name]
touchRing.show(event.clientX, event.clientY, getComputedStyle(el).color, param.label, formatValue(param, value), position(param, value))
}
el.addEventListener('pointerdown', (event) => {
el.setPointerCapture(event.pointerId)
const touch = event.pointerType !== 'mouse'
drag = { y: event.clientY, detents: 0, step: touch ? TOUCH_STEP : DRAG_STEP, touch, x: event.clientX }
holdSelection(true)
ring(event)
})
el.addEventListener('pointermove', (event) => {
if (!drag) return
const detents = Math.trunc((drag.y - event.clientY) / drag.step)
if (detents !== drag.detents) {
this.#turn(index, (detents - drag.detents) * (event.shiftKey ? 10 : 1), event.altKey)
drag.detents = detents
}
ring(event)
})
el.addEventListener('lostpointercapture', () => {
drag = undefined
touchRing.hide()
holdSelection(false)
})
return el
}
/** Redraw the knobs and figure, and apply the values to the page. */
#update() {
const shown = this.#shown()
this.$('.knobs').querySelectorAll('.knob').forEach((el, index) => {
const param = this.#params[index]
if (!param) return
const value = shown[param.name]
const text = formatValue(param, value)
const raw = stopAt(param, value) && `${value}${param.unit ?? ''}`
el.querySelector('.dial').innerHTML = dial(position(param, value), this.#hardware[index])
el.querySelector('.label').innerHTML = `${escape(param.label)}${raw ? `<span class="raw"> · ${escape(raw)}</span>` : ''}`
const valueEl = el.querySelector('.value')
valueEl.textContent = text
valueEl.classList.toggle('long', text.length > 5)
el.setAttribute('aria-valuetext', raw ? `${text}, ${raw}` : text)
if (param.type === 'number') el.setAttribute('aria-valuenow', value)
})
let before = this.$('.before')
if (this.#peek && !before) {
before = Object.assign(document.createElement('span'), { className: 'before', textContent: 'Before' })
;(this.#figure ? this.$('.stage') : this.$('.panel')).append(before)
} else if (!this.#peek) before?.remove()
if (this.#frame && this.#loaded) this.#frame.contentWindow.postMessage({ type: 'state', state: this.#figureState() }, '*')
this.#apply(shown)
}
/**
* Apply values to the page: through the `css` template, with `{name}` replaced by each raw value, or else as custom
* properties, `--name: value` with its unit, on the `target` elements (the page's root by default).
*/
#apply(values) {
const css = this.getAttribute('css')
if (css) {
this.#style ??= document.head.appendChild(document.createElement('style'))
this.#style.dataset.quadknob = this.getAttribute('label') || String(this.#id)
this.#style.textContent = this.#params.reduce((text, param) => text.replaceAll(`{${param.name}}`, String(values[param.name])), css)
}
if (!css || this.hasAttribute('target')) {
this.#clearTarget()
const selector = this.getAttribute('target')
this.#applied = selector ? [...document.querySelectorAll(selector)] : [document.documentElement]
for (const el of this.#applied) {
for (const param of this.#params) {
const value = values[param.name]
el.style.setProperty(`--${param.name}`, param.type === 'number' ? `${value}${param.unit ?? ''}` : String(value))
}
}
}
this.dispatchEvent(new CustomEvent('quadknob-change', { detail: { values: { ...values } }, bubbles: true, composed: true }))
}
#clearTarget() {
for (const el of this.#applied) for (const param of this.#params) el.style.removeProperty(`--${param.name}`)
this.#applied = []
}
#turn(lane, detents, free = false) {
const param = this.#params[lane]
if (!param) return
this.#release(lane)
const next = turn(param, this.#values[param.name], detents, free)
if (next === this.#values[param.name]) return
clickAfterRender()
this.#values[param.name] = next
if (this.#peek) this.#peek = false
this.#update()
}
#release(lane) { this.#pickups[lane] = { picked: false, mine: new Set() } }
midiControl(lane, at) {
const param = this.#params[lane]
if (!param || this.#peek) return
const pickup = this.#pickups[lane] ??= { picked: false, mine: new Set() }
if (pickup.picked && !pickup.mine.has(this.#values[param.name])) Object.assign(pickup, { picked: false, mine: new Set() })
if (!pickup.picked && !picksUp(position(param, this.#values[param.name]), at, pickup.last)) {
pickup.last = at
this.#hardware[lane] = at
return this.#update()
}
const next = fromPosition(param, at)
Object.assign(pickup, { picked: true, last: at })
pickup.mine.add(next)
this.#hardware[lane] = undefined
if (next !== this.#values[param.name]) clickAfterRender()
this.#values[param.name] = next
this.#update()
}
renderMidi() {
const button = this.$('.midi')
button.className = `midi ${midi.status}`
button.disabled = midi.status === 'unsupported' || midi.status === 'denied'
button.title = 'Knobs on MIDI CC 1–4, any channel, like an AKAI LPD8’s top row'
const inputs = midi.access ? midi.access.inputs.size : 0
button.textContent = {
off: 'Connect MIDI',
unsupported: 'No MIDI here',
denied: 'MIDI not allowed',
on: inputs === 0 ? 'MIDI: plug in' : midi.owner === this ? 'MIDI: here' : 'MIDI: use here',
}[midi.status]
}
#setPeek(on) {
if (this.#peek === on) return
this.#peek = on
this.#update()
}
#keydown(event) {
if (event.ctrlKey || event.metaKey || event.isComposing) return
if (event.target instanceof HTMLTextAreaElement) return
if (event.key === 'Escape') {
this.shadowRoot.activeElement?.blur()
return
}
if (event.altKey) {
// Alt changes what a letter types on a Mac, so read the key's position instead.
const letter = /^Key([A-Z])$/.exec(event.code)?.[1]
const free = letter && laneTurn(event.shiftKey ? letter : letter.toLowerCase())
if (free) { event.preventDefault(); this.#turn(free.lane, free.detents, true) }
return
}
const target = laneTurn(event.key)
const onButton = event.composedPath()[0] instanceof HTMLButtonElement
if (target) { event.preventDefault(); this.#turn(target.lane, target.detents) }
else if (event.key === ' ' && !onButton) { event.preventDefault(); this.#setPeek(true) }
else if (event.key === 'Enter' && !onButton) { event.preventDefault(); this.done() }
}
}
if (!customElements.get('quadknob-panel')) customElements.define('quadknob-panel', QuadknobPanel)
export { QuadknobPanel, SCALES }