-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglide_v20.html
More file actions
1926 lines (1717 loc) · 180 KB
/
Copy pathglide_v20.html
File metadata and controls
1926 lines (1717 loc) · 180 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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en" class="oled">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GLIDE — Graphical Layout & Intent Definition Editor</title>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
app: {
base: 'var(--bg-base)', surface: 'var(--bg-surface)', panel: 'var(--bg-panel)', card: 'var(--bg-card)',
border: 'var(--border-subtle)', borderHighlight: 'var(--border-highlight)',
text: 'var(--text-main)', textMuted: 'var(--text-muted)',
accent: 'var(--accent-primary)', accentHover: 'var(--accent-hover)', accentGhost: 'var(--accent-ghost)'
}
},
fontFamily: { sans: ['Inter', 'sans-serif'], mono: ['JetBrains Mono', 'monospace'] },
transitionTimingFunction: { 'premium': 'cubic-bezier(0.4, 0, 0.2, 1)' }
}
}
}
</script>
<style>
:root {
--bg-base: #f3f4f6; --bg-surface: #ffffff; --bg-panel: #e5e7eb; --bg-card: #f9fafb;
--border-subtle: rgba(0,0,0,0.1); --border-highlight: rgba(0,0,0,0.25);
--text-main: #111827; --text-muted: #6b7280;
--accent-primary: #e55f2e; --accent-hover: #c9531f; --accent-ghost: rgba(229, 95, 46, 0.1);
--key-grad-top: #ffffff; --key-grad-bot: #e5e7eb;
--key-border: #d1d5db; --key-shadow: rgba(0,0,0,0.15); --canvas-dot: rgba(0,0,0,0.1);
}
.dark {
--bg-base: #111111; --bg-surface: #1a1a1a; --bg-panel: #222222; --bg-card: #2a2a2a;
--border-subtle: rgba(255,255,255,0.1); --border-highlight: rgba(255,255,255,0.3);
--text-main: #ffffff; --text-muted: #9ca3af;
--accent-primary: #e55f2e; --accent-hover: #c9531f; --accent-ghost: rgba(229, 95, 46, 0.15);
--key-grad-top: #333333; --key-grad-bot: #222222;
--key-border: #444444; --key-shadow: rgba(0,0,0,0.5); --canvas-dot: rgba(255,255,255,0.08);
}
.oled {
--bg-base: #000000; --bg-surface: #050505; --bg-panel: #0a0a0a; --bg-card: #111111;
--border-subtle: rgba(255,255,255,0.05); --border-highlight: rgba(255,255,255,0.25);
--text-main: #ffffff; --text-muted: #6b7280;
--accent-primary: #e55f2e; --accent-hover: #c9531f; --accent-ghost: rgba(229, 95, 46, 0.1);
--key-grad-top: #2a2a2a; --key-grad-bot: #1e1e1e;
--key-border: #111111; --key-shadow: rgba(0,0,0,0.6); --canvas-dot: rgba(255,255,255,0.06);
}
*, *::before, *::after { box-sizing: border-box; }
body { background-color: var(--bg-base); color: var(--text-main); overflow: hidden; margin: 0; transition: background-color 0.3s ease, color 0.3s ease; }
.canvas-container { background-color: var(--bg-base); background-image: radial-gradient(circle, var(--canvas-dot) 1px, transparent 1px); background-size: 32px 32px; cursor: grab; overflow: hidden; transition: background-color 0.3s ease; }
.canvas-container:active { cursor: grabbing; }
.p-key-outer { position: absolute; cursor: pointer; z-index: 1; user-select: none; transition: transform 0.15s ease; }
.p-key-outer.is-touchpad { cursor: not-allowed !important; }
.p-key-outer:not(.is-touchpad):hover { z-index: 20; }
.p-key-outer.selected { z-index: 30; }
.p-key-outer.combo-highlight { z-index: 25; }
.p-key {
width: 100%; height: 100%; border-radius: 6px;
display: flex; flex-direction: column; align-items: center; justify-content: center;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
background: linear-gradient(180deg, var(--key-grad-top) 0%, var(--key-grad-bot) 100%);
border: 1px solid var(--key-border);
box-shadow: inset 0 1px 0 rgba(255,255,255,0.08), inset 0 -2px 0 var(--key-shadow), 0 3px 5px var(--key-shadow);
padding: 4px; text-align: center; overflow: hidden; color: var(--text-main);
}
.p-key.is-round { border-radius: 50%; }
.p-key:not(.is-touchpad):active { transform: scale(0.96) translateY(1px); box-shadow: inset 0 2px 4px var(--key-shadow); filter: brightness(0.9); }
.p-key:not(.is-touchpad):hover {
transform: scale(1.05) translateY(-2px);
border-color: var(--border-highlight); filter: brightness(1.1);
box-shadow: inset 0 1px 0 rgba(255,255,255,0.1), inset 0 -2px 0 var(--key-shadow), 0 8px 18px rgba(0,0,0,0.5);
}
.p-key.selected {
border: 3px solid var(--accent-primary) !important;
box-shadow: inset 0 0 15px rgba(229, 95, 46, 0.2), 0 12px 35px rgba(229, 95, 46, 0.5) !important;
transform: scale(1.08) translateY(-2px);
}
.p-key.combo-selected {
border: 2px solid var(--accent-primary) !important;
background: var(--accent-primary) !important;
color: #ffffff !important;
box-shadow: 0 4px 20px rgba(229, 95, 46, 0.5) !important;
transform: translateY(-1px) scale(1.04);
}
.p-key.drag-source { opacity: 0.35; transform: scale(0.95); }
.p-key.drag-over { box-shadow: 0 0 0 3px var(--bg-base), 0 0 0 5px var(--accent-primary) !important; border-style: dashed !important; transform: scale(1.08); }
.kc-grid { width: 100%; height: 100%; position: relative; display: flex; flex-direction: column; align-items: center; justify-content: center; pointer-events: none; overflow: hidden; padding: 2px; box-sizing: border-box; }
.kc-main {
font-weight: 700; font-size: 11px; color: inherit; line-height: 1.1; z-index: 2; text-align: center;
width: 100%; word-break: break-all; overflow: hidden; text-overflow: ellipsis;
display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical;
}
.kc-tl {
position: absolute; top: 1px; left: 3px; font-size: 8px; opacity: 0.85; font-weight: 700; color: var(--accent-primary);
max-width: 70%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: left;
}
.kc-tr { position: absolute; top: 1px; right: 3px; font-size: 9px; opacity: 0.7; }
.kc-custom {
display: flex; align-items: center; justify-content: center; text-align: center;
width: 100%; max-height: 100%; font-size: 9px; font-weight: 600; line-height: 1.1;
word-break: break-all; overflow: hidden; text-overflow: ellipsis;
display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical;
}
.palette-btn { min-width: calc(48px * var(--btn-scale, 1)); height: calc(48px * var(--btn-scale, 1)); background-color: var(--bg-surface); border-radius: 8px; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(12px * var(--btn-scale, 1)); font-weight: 600; color: var(--text-main); cursor: pointer; transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); padding: 4px; border: 1px solid var(--border-subtle); line-height: 1.2; }
.palette-btn:hover { transform: translateY(-1px); background-color: var(--bg-panel); border-color: var(--border-highlight); box-shadow: 0 4px 12px var(--key-shadow); }
.btn-active { background-color: var(--accent-primary) !important; border-color: var(--accent-primary) !important; color: #ffffff !important; box-shadow: 0 0 12px var(--accent-ghost) !important; }
.btn-active:hover { background-color: var(--accent-hover) !important; border-color: var(--accent-hover) !important; transform: translateY(-1px); }
.btn-active-hollow { background-color: var(--accent-ghost) !important; border-color: var(--accent-primary) !important; color: var(--accent-primary) !important; box-shadow: 0 0 12px var(--accent-ghost) !important; }
.btn-active-hollow:hover { background-color: var(--border-highlight) !important; transform: translateY(-1px); }
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border-highlight); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
</style>
</head>
<body>
<div id="root" class="h-screen w-screen flex overflow-hidden text-app-text bg-app-base transition-colors duration-300"></div>
<script type="text/babel">
const { useState, useEffect, useMemo, useCallback, memo, useRef } = React;
const KEY_UNIT = 70; const KEY_SIZE = 62;
const GLOVE80_TOTAL_WIDTH = 18; const GO60_TOTAL_WIDTH = 17;
const SLOT_LABELS = { tap: 'Primary Action', shiftTap: 'Shift Action', hold: 'Hold Action', doubleTap: 'Double-Tap Action', label: 'Custom Key Text' };
const SLOT_LINK_LABELS = { shiftTap: 'when tapped with Shift', hold: 'when held', doubleTap: 'when double-tapped', label: 'add text label to the key' };
const LAYER_POINTER_BEHAVIORS = new Set(['&mo', '&to', '&tog', '&sl', '<', '&layer']);
const detectOs = () => { const platform = navigator.userAgent.toLowerCase(); if (platform.includes('mac')) return 'mac'; if (platform.includes('linux')) return 'linux'; return 'win'; };
function mirrorSpecialKey(k, totalWidth) {
const w = k.w || 1; const mirrored = { ...k, x: totalWidth - k.x - w };
if (k.r !== undefined) mirrored.r = -k.r;
if (k.rx !== undefined) mirrored.rx = totalWidth - k.rx;
return mirrored;
}
const GLOVE80_THUMB_A_LEFT = [{x:6.4,y:4,r:20,rx:4,ry:4}, {x:7.8,y:3.3,r:30,rx:4,ry:3.3}, {x:10.1,y:1.5,r:45,rx:4,ry:1.5}];
const GLOVE80_THUMB_B_LEFT = [{x:5.3,y:5.4,r:15,rx:4,ry:5.4}, {x:6.6,y:5,r:25,rx:4,ry:5}, {x:9,y:3.2,r:45,rx:4,ry:3.2}];
const GO60_THUMB_LEFT = [{x:4,y:4.25,r:15,rx:4.5,ry:9}, {x:4,y:4.25,r:30,rx:4.5,ry:9}, {x:4,y:4.25,r:45,rx:4.5,ry:9}];
const GO60_ROUND_LEFT = {x:6.5,y:2.2,w:1.8,h:1.8,isRound:1};
const GLOVE80_GEO_RAW = [
{x:0,y:0.5},{x:1,y:0.5},{x:2,y:0},{x:3,y:0},{x:4,y:0},{x:13,y:0},{x:14,y:0},{x:15,y:0},{x:16,y:0.5},{x:17,y:0.5},
{x:0,y:1.5},{x:1,y:1.5},{x:2,y:1},{x:3,y:1},{x:4,y:1},{x:5,y:1},{x:12,y:1},{x:13,y:1},{x:14,y:1},{x:15,y:1},{x:16,y:1.5},{x:17,y:1.5},
{x:0,y:2.5},{x:1,y:2.5},{x:2,y:2},{x:3,y:2},{x:4,y:2},{x:5,y:2},{x:12,y:2},{x:13,y:2},{x:14,y:2},{x:15,y:2},{x:16,y:2.5},{x:17,y:2.5},
{x:0,y:3.5},{x:1,y:3.5},{x:2,y:3},{x:3,y:3},{x:4,y:3},{x:5,y:3},{x:12,y:3},{x:13,y:3},{x:14,y:3},{x:15,y:3},{x:16,y:3.5},{x:17,y:3.5},
{x:0,y:4.5},{x:1,y:4.5},{x:2,y:4},{x:3,y:4},{x:4,y:4},{x:5,y:4}, ...GLOVE80_THUMB_A_LEFT, ...[...GLOVE80_THUMB_A_LEFT].reverse().map(k => mirrorSpecialKey(k, GLOVE80_TOTAL_WIDTH)),
{x:12,y:4},{x:13,y:4},{x:14,y:4},{x:15,y:4},{x:16,y:4.5},{x:17,y:4.5},
{x:0,y:5.5},{x:1,y:5.5},{x:2,y:5},{x:3,y:5},{x:4,y:5}, ...GLOVE80_THUMB_B_LEFT, ...[...GLOVE80_THUMB_B_LEFT].reverse().map(k => mirrorSpecialKey(k, GLOVE80_TOTAL_WIDTH)),
{x:13,y:5},{x:14,y:5},{x:15,y:5},{x:16,y:5.5},{x:17,y:5.5}
];
const GO60_GEO_RAW = [
{x:0,y:0.9},{x:1,y:0.9},{x:2,y:0.25},{x:3,y:0},{x:4,y:0.15},{x:5,y:0.25},{x:11,y:0.25},{x:12,y:0.15},{x:13,y:0},{x:14,y:0.25},{x:15,y:0.9},{x:16,y:0.9},
{x:0,y:1.9},{x:1,y:1.9},{x:2,y:1.25},{x:3,y:1},{x:4,y:1.15},{x:5,y:1.25},{x:11,y:1.25},{x:12,y:1.15},{x:13,y:1},{x:14,y:1.25},{x:15,y:1.9},{x:16,y:1.9},
{x:0,y:2.9},{x:1,y:2.9},{x:2,y:2.25},{x:3,y:2},{x:4,y:2.15},{x:5,y:2.25},{x:11,y:2.25},{x:12,y:2.15},{x:13,y:2},{x:14,y:2.25},{x:15,y:2.9},{x:16,y:2.9},
{x:0,y:3.9},{x:1,y:3.9},{x:2,y:3.25},{x:3,y:3},{x:4,y:3.15},{x:5,y:3.25},{x:11,y:3.25},{x:12,y:3.15},{x:13,y:3},{x:14,y:3.25},{x:15,y:3.9},{x:16,y:3.9},
{x:2,y:4.25},{x:3,y:4},{x:4,y:4.15},{x:12,y:4.15},{x:13,y:4},{x:14,y:4.25}, ...GO60_THUMB_LEFT, ...[...GO60_THUMB_LEFT].reverse().map(k => mirrorSpecialKey(k, GO60_TOTAL_WIDTH)),
GO60_ROUND_LEFT, mirrorSpecialKey(GO60_ROUND_LEFT, GO60_TOTAL_WIDTH)
];
const GUTTER = (KEY_UNIT - KEY_SIZE) / 2;
function convertGeo(rawGeo) {
return rawGeo.map(k => {
const wUnits = k.w || 1, hUnits = k.h || 1;
const cellLeft = k.x * KEY_UNIT, cellTop = k.y * KEY_UNIT;
const w = wUnits * KEY_UNIT - (KEY_UNIT - KEY_SIZE); const h = hUnits * KEY_UNIT - (KEY_UNIT - KEY_SIZE);
const out = { x: cellLeft + GUTTER, y: cellTop + GUTTER, w, h, isRound: !!k.isRound };
if (k.r) {
out.r = k.r;
const pivotX = (k.rx !== undefined ? k.rx : k.x) * KEY_UNIT; const pivotY = (k.ry !== undefined ? k.ry : k.y) * KEY_UNIT;
const originX = pivotX - (cellLeft + GUTTER); const originY = pivotY - (cellTop + GUTTER);
out.o = `${originX.toFixed(1)}px ${originY.toFixed(1)}px`;
}
return out;
});
}
const GLOVE80_GEO = convertGeo(GLOVE80_GEO_RAW);
const GO60_GEO = convertGeo(GO60_GEO_RAW);
function computeGeoBounds(geo) {
let minX = Infinity, minY = Infinity, maxX = 0, maxY = 0;
geo.forEach(k => {
minX = Math.min(minX, k.x); minY = Math.min(minY, k.y);
maxX = Math.max(maxX, k.x + (k.w || KEY_SIZE));
maxY = Math.max(maxY, k.y + (k.h || KEY_SIZE) + (k.r ? 40 : 0));
});
return { w: maxX - minX + 20, h: maxY - minY + 20, minX: minX - 10, minY: minY - 10 };
}
const MiniKeyboardMap = memo(({ geo, selectedKeys = [], onKeyToggle, readonly = false }) => {
const bounds = useMemo(() => computeGeoBounds(geo), [geo]);
const containerRef = useRef(null);
const [scale, setScale] = useState(0.2);
useEffect(() => {
if (containerRef.current) {
const rect = containerRef.current.getBoundingClientRect();
const scaleX = (rect.width - 20) / bounds.w;
const scaleY = (rect.height - 20) / bounds.h;
setScale(Math.min(scaleX, scaleY, 0.35));
}
}, [bounds]);
return (
<div ref={containerRef} className="relative overflow-hidden flex items-center justify-center rounded-xl w-full h-[140px] bg-app-panel/30 border border-app-borderHighlight shadow-inner">
<div className="relative" style={{ width: bounds.w * scale, height: bounds.h * scale }}>
{geo.map((k, i) => {
const isSel = selectedKeys.includes(i);
return (
<div key={i} onClick={(e) => { e.stopPropagation(); if (!readonly && onKeyToggle) onKeyToggle(i); }}
style={{
position: 'absolute',
left: (k.x - bounds.minX) * scale,
top: (k.y - bounds.minY) * scale,
width: (k.w || KEY_SIZE) * scale,
height: (k.h || KEY_SIZE) * scale,
transform: k.r ? `rotate(${k.r}deg)` : 'none',
transformOrigin: k.o ? k.o.split(' ').map(val => parseFloat(val) * scale + 'px').join(' ') : 'center',
backgroundColor: isSel ? 'var(--accent-primary)' : 'var(--bg-surface)',
border: `${Math.max(1, 1.5 * scale)}px solid ${isSel ? 'var(--accent-primary)' : 'var(--text-muted)'}`,
borderRadius: k.isRound ? '50%' : `${6 * scale}px`,
cursor: readonly ? 'default' : 'pointer',
opacity: isSel ? 1 : 0.4,
boxShadow: isSel ? '0 5px 15px rgba(229, 95, 46, 0.4)' : 'none'
}}
/>
)
})}
</div>
</div>
);
});
// The Omni-Shift Engine: Protects Keycaps & Combos during Layer changes.
const shiftLayerPointers = (config, shiftType, targetIdx, newIdx = null) => {
const remapVal = (val) => {
if (shiftType === 'insert') return val >= targetIdx ? val + 1 : val;
if (shiftType === 'delete') {
if (val === targetIdx) return -1;
return val > targetIdx ? val - 1 : val;
}
if (shiftType === 'move') {
if (val === targetIdx) return newIdx;
if (targetIdx < newIdx && val > targetIdx && val <= newIdx) return val - 1;
if (targetIdx > newIdx && val >= newIdx && val < targetIdx) return val + 1;
return val;
}
return val;
};
config.layers.forEach(layer => {
(layer || []).forEach(binding => {
if (!binding || !LAYER_POINTER_BEHAVIORS.has(binding.value)) return;
const p = binding.params?.[0];
if (!p || p.value === undefined || p.value === null) return;
let val = parseInt(p.value, 10);
if (isNaN(val)) return;
let newVal = remapVal(val);
if (newVal === -1) {
binding.value = '&none'; binding.params = [];
} else {
p.value = typeof p.value === 'string' ? String(newVal) : newVal;
}
});
});
if (config.combos) {
config.combos.forEach(combo => {
if (!combo.layers) return;
combo.layers = [...new Set(combo.layers.map(remapVal).filter(v => v !== -1))];
});
}
};
const GLOVE80_NAMES = {
0: "LH C6R1", 1: "LH C5R1", 2: "LH C4R1", 3: "LH C3R1", 4: "LH C2R1", 10: "LH C6R2", 11: "LH C5R2", 12: "LH C4R2", 13: "LH C3R2", 14: "LH C2R2", 15: "LH C1R2", 22: "LH C6R3", 23: "LH C5R3", 24: "LH C4R3", 25: "LH C3R3", 26: "LH C2R3", 27: "LH C1R3", 34: "LH C6R4", 35: "LH C5R4", 36: "LH C4R4", 37: "LH C3R4", 38: "LH C2R4", 39: "LH C1R4", 46: "LH C6R5", 47: "LH C5R5", 48: "LH C4R5", 49: "LH C3R5", 50: "LH C2R5", 51: "LH C1R5", 64: "LH C6R6", 65: "LH C5R6", 66: "LH C4R6", 67: "LH C3R6", 68: "LH C2R6", 52: "LH T1", 53: "LH T2", 54: "LH T3", 69: "LH T4", 70: "LH T5", 71: "LH T6",
5: "RH C2R1", 6: "RH C3R1", 7: "RH C4R1", 8: "RH C5R1", 9: "RH C6R1", 16: "RH C1R2", 17: "RH C2R2", 18: "RH C3R2", 19: "RH C4R2", 20: "RH C5R2", 21: "RH C6R2", 28: "RH C1R3", 29: "RH C2R3", 30: "RH C3R3", 31: "RH C4R3", 32: "RH C5R3", 33: "RH C6R3", 40: "RH C1R4", 41: "RH C2R4", 42: "RH C3R4", 43: "RH C4R4", 44: "RH C5R4", 45: "RH C6R4", 58: "RH C1R5", 59: "RH C2R5", 60: "RH C3R5", 61: "RH C4R5", 62: "RH C5R5", 63: "RH C6R5", 75: "RH C2R6", 76: "RH C3R6", 77: "RH C4R6", 78: "RH C5R6", 79: "RH C6R6", 55: "RH T3", 56: "RH T2", 57: "RH T1", 72: "RH T6", 73: "RH T5", 74: "RH T4"
};
const GO60_NAMES = {
0: "LH C6R1", 1: "LH C5R1", 2: "LH C4R1", 3: "LH C3R1", 4: "LH C2R1", 5: "LH C1R1", 12: "LH C6R2", 13: "LH C5R2", 14: "LH C4R2", 15: "LH C3R2", 16: "LH C2R2", 17: "LH C1R2", 24: "LH C6R3", 25: "LH C5R3", 26: "LH C4R3", 27: "LH C3R3", 28: "LH C2R3", 29: "LH C1R3", 36: "LH C6R4", 37: "LH C5R4", 38: "LH C4R4", 39: "LH C3R4", 40: "LH C2R4", 41: "LH C1R4", 48: "LH C4R5", 49: "LH C3R5", 50: "LH C2R5", 54: "LH T1", 55: "LH T2", 56: "LH T3",
6: "RH C1R1", 7: "RH C2R1", 8: "RH C3R1", 9: "RH C4R1", 10: "RH C5R1", 11: "RH C6R1", 18: "RH C1R2", 19: "RH C2R2", 20: "RH C3R2", 21: "RH C4R2", 22: "RH C5R2", 23: "RH C6R2", 30: "RH C1R3", 31: "RH C2R3", 32: "RH C3R3", 33: "RH C4R3", 34: "RH C5R3", 35: "RH C6R3", 42: "RH C1R4", 43: "RH C2R4", 44: "RH C3R4", 45: "RH C4R4", 46: "RH C5R4", 47: "RH C6R4", 51: "RH C2R5", 52: "RH C3R5", 53: "RH C4R5", 57: "RH T3", 58: "RH T2", 59: "RH T1"
};
const getLogicalName = (index, kbType) => { return ((kbType || '').toLowerCase() === 'go60' ? GO60_NAMES : GLOVE80_NAMES)[index] || index; };
const PALETTE_DATA = {
Basic: [
{ category: "Letters", items: [ { label: 'A', code: 'A' }, { label: 'B', code: 'B' }, { label: 'C', code: 'C' }, { label: 'D', code: 'D' }, { label: 'E', code: 'E' }, { label: 'F', code: 'F' }, { label: 'G', code: 'G' }, { label: 'H', code: 'H' }, { label: 'I', code: 'I' }, { label: 'J', code: 'J' }, { label: 'K', code: 'K' }, { label: 'L', code: 'L' }, { label: 'M', code: 'M' }, { label: 'N', code: 'N' }, { label: 'O', code: 'O' }, { label: 'P', code: 'P' }, { label: 'Q', code: 'Q' }, { label: 'R', code: 'R' }, { label: 'S', code: 'S' }, { label: 'T', code: 'T' }, { label: 'U', code: 'U' }, { label: 'V', code: 'V' }, { label: 'W', code: 'W' }, { label: 'X', code: 'X' }, { label: 'Y', code: 'Y' }, { label: 'Z', code: 'Z' } ] },
{ category: "Numbers", items: [ { top: '!', bottom: '1', code: 'N1' }, { top: '@', bottom: '2', code: 'N2' }, { top: '#', bottom: '3', code: 'N3' }, { top: '$', bottom: '4', code: 'N4' }, { top: '%', bottom: '5', code: 'N5' }, { top: '^', bottom: '6', code: 'N6' }, { top: '&', bottom: '7', code: 'N7' }, { top: '*', bottom: '8', code: 'N8' }, { top: '(', bottom: '9', code: 'N9' }, { top: ')', bottom: '0', code: 'N0' } ] },
{ category: "Symbols", items: [ { top: '_', bottom: '-', code: 'MINUS' }, { top: '+', bottom: '=', code: 'EQUAL' }, { top: '~', bottom: '`', code: 'GRAVE' }, { top: '{', bottom: '[', code: 'LBKT' }, { top: '}', bottom: ']', code: 'RBKT' }, { top: '|', bottom: '\\', code: 'BSLH' }, { top: ':', bottom: ';', code: 'SEMI' }, { top: '"', bottom: "'", code: 'SQT' }, { top: '<', bottom: ',', code: 'COMMA' }, { top: '>', bottom: '.', code: 'DOT' }, { top: '?', bottom: '/', code: 'FSLH' }, { label: '=', code: 'KP_EQUAL' }, { label: ',', code: 'KP_COMMA' }, { label: '÷', code: 'KP_DIVIDE' }, { label: '×', code: 'KP_MULTIPLY' }, { label: '-', code: 'KP_MINUS' }, { label: '+', code: 'KP_PLUS' }, { label: '.', code: 'KP_DOT' }, { label: '&', code: 'AMPS' } ] },
{ category: "Modifiers", items: [ { code: 'LSHFT' }, { code: 'RSHFT' }, { code: 'LCTRL' }, { code: 'RCTRL' }, { code: 'LALT' }, { code: 'RALT' }, { code: 'LGUI' }, { code: 'RGUI' } ] },
{ category: "Control", items: [ { label: '▽', type: '&trans' }, { label: '∅ None', type: '&none' }, { label: 'F1', code: 'F1' }, { label: 'F2', code: 'F2' }, { label: 'F3', code: 'F3' }, { label: 'F4', code: 'F4' }, { label: 'F5', code: 'F5' }, { label: 'F6', code: 'F6' }, { label: 'F7', code: 'F7' }, { label: 'F8', code: 'F8' }, { label: 'F9', code: 'F9' }, { label: 'F10', code: 'F10' }, { label: 'F11', code: 'F11' }, { label: 'F12', code: 'F12' }, { label: 'Caps Lock', code: 'CAPS' }, { label: 'Tab', code: 'TAB' }, { label: 'Backspace', code: 'BSPC' }, { label: 'Enter', code: 'RET' }, { label: 'Space', code: 'SPACE' }, { label: 'Ins', code: 'INS' }, { label: 'Del', code: 'DEL' }, { label: 'Home', code: 'HOME' }, { label: 'End', code: 'END' }, { label: 'PgUp', code: 'PG_UP' }, { label: 'PgDn', code: 'PG_DN' }, { label: 'Esc', code: 'ESC' }, { label: 'Print', code: 'PRINTSCREEN' }, { label: 'Scroll', code: 'SLCK' }, { label: 'Pause', code: 'PAUSE_BREAK' }, { label: 'RApp', code: 'K_APP' }, { label: 'N.ent', code: 'KP_ENTER' }, { label: 'N.Lck', code: 'KP_NUM' } ] }
],
Media: [ { category: "Media & Editing", items: [{ label: 'Vol -', code: 'C_VOL_DN' }, { label: 'Vol +', code: 'C_VOL_UP' }, { label: 'Mute', code: 'C_MUTE' }, { label: 'Play', code: 'C_PP' }, { label: 'Mstp', code: 'C_STOP' }, { label: 'Prvs', code: 'C_PREV' }, { label: 'Next', code: 'C_NEXT' }, { label: 'Rewind', code: 'C_RW' }, { label: 'Mffd', code: 'C_FF' }, { label: 'Select', code: 'C_AL_SEL_TASK' }, { label: 'Eject', code: 'C_EJECT' }] } ],
SpecialKeys: [
{ category: "General Special", items: [ { label: 'Nuhs', code: 'NON_US_HASH' }, { label: 'Nubs', code: 'NON_US_BSLH' }, { label: 'Ro', code: 'INT3' }, { label: '¥', code: 'INT1' }, { label: '無変換', code: 'INT5' }, { label: '漢字', code: 'INT4' }, { label: '한영', code: 'LANG1' }, { label: '変換', code: 'INT4' }, { label: 'かな', code: 'INT2' }, { label: 'Esc `', code: 'GRAVE' }, { label: '(', type: '&kp', param1: 'LPAR' }, { label: ')', type: '&kp', param1: 'RPAR' }, { label: 'SftEnt', type: '&kp', param1: 'RET' }, { label: 'Reset', type: '&sys_reset' }, { label: 'Boot', type: '&bootloader' }, { label: 'F13', code: 'F13' }, { label: 'F14', code: 'F14' }, { label: 'F15', code: 'F15' }, { label: 'F16', code: 'F16' }, { label: 'F17', code: 'F17' }, { label: 'F18', code: 'F18' }, { label: 'F19', code: 'F19' }, { label: 'Mouse ↑', type: '&mmv', param1: 'MOVE_UP' }, { label: 'Mouse ↓', type: '&mmv', param1: 'MOVE_DOWN' }, { label: 'Mouse ←', type: '&mmv', param1: 'MOVE_LEFT' }, { label: 'Mouse →', type: '&mmv', param1: 'MOVE_RIGHT' }, { label: 'Mouse Btn1', type: '&mkp', param1: 'MB1' }, { label: 'Mouse Btn2', type: '&mkp', param1: 'MB2' }, { label: 'Mouse Btn3', type: '&mkp', param1: 'MB3' }, { label: 'Magic', type: '&magic' } ] }
],
Custom: [
{ category: "System & Connectivity", items: [ { label: 'BTH1', type: '&bt', param1: 'BT_SEL', param2: 0 }, { label: 'BTH2', type: '&bt', param1: 'BT_SEL', param2: 1 }, { label: 'BTH3', type: '&bt', param1: 'BT_SEL', param2: 2 }, { label: '2.4G', type: '&out', param1: 'OUT_USB' }, { label: 'Batt', type: '&ext_power', param1: 'EP_TOG' }, { label: 'BT Clr', type: '&bt', param1: 'BT_CLR' }, { label: 'PROF1', type: '&none' }, { label: 'PROF2', type: '&none' }, { label: 'PROF3', type: '&none' }, { label: 'Any', type: 'Custom', param1: '' } ] }
]
};
const FLAT_GRID_TABS = ['Basic', 'Media', 'SpecialKeys', 'Custom'];
function searchAcrossAllPalette(query) {
if (!query.trim()) return []; const results = []; const q = query.trim().toLowerCase();
FLAT_GRID_TABS.forEach(tabName => { const sections = PALETTE_DATA[tabName] || []; sections.forEach(section => { const matched = section.items.filter(item => [item.label, item.top, item.bottom, item.code].filter(Boolean).join(' ').toLowerCase().includes(q)); if (matched.length > 0) results.push({ tabName, category: section.category, items: matched }); }); }); return results;
}
const ALL_PALETTE_SECTIONS = [...PALETTE_DATA.Basic, ...PALETTE_DATA.Media, ...PALETTE_DATA.SpecialKeys, ...PALETTE_DATA.Custom];
const MOD_ARM_ORDER = ['LC', 'RC', 'LA', 'RA', 'LS', 'RS', 'LG', 'RG'];
const MOD_BASES = [
{ base: 'C', mac: '⌃', win: 'Ctrl', linux: 'Ctrl', nameMac: 'Control', nameWin: 'Control', nameLinux: 'Control' },
{ base: 'A', mac: '⌥', win: 'Alt', linux: 'Alt', nameMac: 'Option', nameWin: 'Alt', nameLinux: 'Alt' },
{ base: 'S', mac: '⇧', win: '⇧', linux: '⇧', nameMac: 'Shift', nameWin: 'Shift', nameLinux: 'Shift' },
{ base: 'G', mac: '⌘', win: '⊞', linux: '❖', nameMac: 'Command', nameWin: 'Windows', nameLinux: 'Super' }
];
const RAW_MOD_CODES = new Set(['LSHFT', 'RSHFT', 'LCTRL', 'RCTRL', 'LALT', 'RALT', 'LGUI', 'RGUI', 'MOD_LSFT', 'MOD_RSFT']);
const KEY_COLOR_PRESETS = ['#e5484d', '#f76b15', '#f5d90a', '#46a758', '#12a594', '#0091ff', '#8e4ec6', '#e93d82'];
const ZMK_MAP = { BSPC:'⌫', RET:'↵', PG_DN:'PgDn', PG_UP:'PgUp', UP:'↑', DOWN:'↓', LEFT:'←', RIGHT:'→', ESC:'Esc', TAB:'Tab', MINUS:'-', EQUAL:'=', GRAVE:'`', BSLH:'\\', SEMI:';', SQT:"'", FSLH:'/', LBKT:'[', RBKT:']', COMMA:',', DOT:'.', SPACE:'␣', C_VOL_DN:'Vol -', C_VOL_UP:'Vol +', C_MUTE:'Mute', C_PP:'Play', C_NEXT:'Next', C_PREV:'Prev', KP_EQUAL:'=', KP_COMMA:',', KP_DIVIDE:'÷', KP_MULTIPLY:'×', KP_MINUS:'-', KP_PLUS:'+', KP_DOT:'.', NON_US_HASH:'Nuhs', NON_US_BSLH:'Nubs' };
const MOD_WRAPPER_TO_FULL = { LS: 'LSHFT', RS: 'RSHFT', LC: 'LCTRL', RC: 'RCTRL', LA: 'LALT', RA: 'RALT', LG: 'LGUI', RG: 'RGUI' };
const FULL_TO_MOD_WRAPPER = Object.fromEntries(Object.entries(MOD_WRAPPER_TO_FULL).map(([k, v]) => [v, k]));
function unwrapModChain(node) {
const mods = [];
while (node && typeof node === 'object' && MOD_WRAPPER_TO_FULL[node.value] && node.params?.[0]) { mods.push(MOD_WRAPPER_TO_FULL[node.value]); node = node.params[0]; }
const keyVal = (node && typeof node === 'object') ? node.value : node; return { mods, keyVal };
}
function composeKeycodeParam(baseCode, modCodes) {
let node = { value: baseCode, params: [] };
for (let i = modCodes.length - 1; i >= 0; i--) node = { value: modCodes[i], params: [node] };
return node;
}
const runGC = (newConfig) => {
const usedNames = new Set();
const extractNames = (node) => {
if (!node) return;
if (typeof node === 'object') {
if (node.value && typeof node.value === 'string' && (node.value.startsWith('&ht_auto_') || node.value.startsWith('&td_') || node.value.startsWith('&mm_auto_'))) usedNames.add(node.value);
if (Array.isArray(node.params)) node.params.forEach(extractNames); if (Array.isArray(node.bindings)) node.bindings.forEach(extractNames); if (Array.isArray(node.cases)) node.cases.forEach(c => extractNames(c.binding));
}
};
newConfig.layers?.forEach(layer => layer.forEach(extractNames)); newConfig.combos?.forEach(combo => extractNames(combo.binding));
let size;
do {
size = usedNames.size;
['holdTaps', 'tapDances', 'modMorphs'].forEach(arrKey => {
(newConfig[arrKey] || []).forEach(beh => {
if (usedNames.has(beh.name)) {
if (beh.bindings) beh.bindings.forEach(b => { if (typeof b === 'object') extractNames(b); else if (typeof b === 'string' && (b.startsWith('&ht_auto_') || b.startsWith('&td_') || b.startsWith('&mm_auto_'))) usedNames.add(b); });
if (beh.cases) beh.cases.forEach(c => extractNames(c.binding));
}
});
});
} while (usedNames.size > size);
if (newConfig.holdTaps) newConfig.holdTaps = newConfig.holdTaps.filter(h => !h.name.startsWith('&ht_auto_') || usedNames.has(h.name));
if (newConfig.tapDances) newConfig.tapDances = newConfig.tapDances.filter(t => !t.name.startsWith('&td_') || usedNames.has(t.name));
if (newConfig.modMorphs) newConfig.modMorphs = newConfig.modMorphs.filter(m => !m.name.startsWith('&mm_auto_') || usedNames.has(m.name));
if (newConfig.holdTaps && newConfig.holdTaps.length === 0) delete newConfig.holdTaps; if (newConfig.tapDances && newConfig.tapDances.length === 0) delete newConfig.tapDances; if (newConfig.modMorphs && newConfig.modMorphs.length === 0) delete newConfig.modMorphs;
return newConfig;
};
const parseModMorph = (binding, config) => {
if (!binding || binding.value === '&none') return { tap: null, shiftTap: null };
if (binding.value.startsWith('&mm_auto_')) { const mm = (config?.modMorphs || []).find(m => m.name === binding.value); if (mm && mm.cases && mm.cases.length >= 2) return { tap: mm.cases[0].binding, shiftTap: mm.cases[1].binding }; }
return { tap: binding, shiftTap: null };
};
const parseHoldTap = (binding, config) => {
if (!binding || binding.value === '&none') return { tap: null, hold: null };
if (binding.value === '&mt') return { hold: { value: binding.params?.[0]?.value }, tap: { value: '&kp', params: [binding.params?.[1]] } };
if (binding.value === '<') return { hold: { value: '&mo', params: [binding.params?.[0]] }, tap: { value: '&kp', params: [binding.params?.[1]] } };
if (binding.value.startsWith('&ht_auto_')) {
const ht = (config?.holdTaps || []).find(h => h.name === binding.value);
if (ht && ht.bindings && ht.bindings.length >= 2) {
let pIdx = 0;
const reconstruct = (val) => { const needsP = ['&kp', '&mo', '&to', '&tog', '&sl', '&layer'].includes(val); if (needsP && binding.params?.[pIdx]) return { value: val, params: [binding.params[pIdx++]] }; return { value: val }; };
return { hold: reconstruct(ht.bindings[0]), tap: reconstruct(ht.bindings[1]) };
}
}
return { tap: binding, hold: null };
};
const parseSlots = (binding, config) => {
let slots = { tap: null, shiftTap: null, hold: null, doubleTap: null };
if (!binding || binding.value === '&none') return slots;
let primaryBinding = binding; let secondaryBinding = null;
if (primaryBinding.value.startsWith('&td_')) { const td = (config?.tapDances || []).find(t => t.name === primaryBinding.value); if (td && td.bindings && td.bindings.length >= 2) { primaryBinding = td.bindings[0]; secondaryBinding = td.bindings[1]; } }
const pHT = parseHoldTap(primaryBinding, config); slots.hold = pHT.hold;
const pMM = parseModMorph(pHT.tap, config); slots.tap = pMM.tap; slots.shiftTap = pMM.shiftTap;
slots.doubleTap = secondaryBinding; return slots;
};
const makeModMorph = (tap, shiftTap, configRef) => {
if (!shiftTap || shiftTap.value === '&none') return tap; if (!tap || tap.value === '&none') return shiftTap;
const tName = tap.params?.[0]?.value || tap.value.replace('&',''); const stName = shiftTap.params?.[0]?.value || shiftTap.value.replace('&',''); const mmName = `&mm_auto_${tName}_${stName}`;
if (!configRef.modMorphs) configRef.modMorphs = [];
if (!configRef.modMorphs.find(m => m.name === mmName)) configRef.modMorphs.push({ name: mmName, cases: [ { binding: tap, mods: [], keepMods: [] }, { binding: shiftTap, mods: ["MOD_LSFT", "MOD_RSFT"], keepMods: [] } ] });
return { value: mmName };
};
const makeHoldTap = (tap, hold, configRef, forceCustom = false) => {
if (!tap && !hold) return null; if (tap && !hold) return tap; if (!tap && hold) return hold;
const holdVal = hold.value; const tapVal = tap.value;
const isLayer = holdVal === '&mo' || holdVal === '&to' || holdVal === '&tog' || holdVal === '&sl' || holdVal === '&layer';
const isMod = RAW_MOD_CODES.has(holdVal) || ['LCTRL','RCTRL','LSHFT','RSHFT','LALT','RALT','LGUI','RGUI'].includes(holdVal);
if (!forceCustom && (tapVal === '&kp' || tapVal.startsWith('&mac'))) {
if (tapVal === '&kp') { if (isLayer) return { value: '<', params: [hold.params?.[0] || {value: 0}, tap.params[0]] }; if (isMod) return { value: '&mt', params: [{value: holdVal}, tap.params[0]] }; }
}
const hName = hold.params?.[0]?.value || holdVal.replace('&',''); const tName = tap.params?.[0]?.value || tapVal.replace('&',''); const htName = `&ht_auto_${hName}_${tName}`;
if (!configRef.holdTaps) configRef.holdTaps = [];
if (!configRef.holdTaps.find(h => h.name === htName)) configRef.holdTaps.push({ name: htName, bindings: [holdVal, tapVal], tappingTermMs: 200, flavor: "tap-preferred", quickTapMs: -1, requirePriorIdleMs: 0, retroTap: false, holdTriggerOnRelease: false });
let params = []; if (hold.params) params.push(...hold.params); if (tap.params) params.push(...tap.params);
return { value: htName, params };
};
function buildBindingAndConfig(slots, currentConfig, forceCustomHold = false) {
let newConfig = structuredClone(currentConfig);
const primaryTap = makeModMorph(slots.tap, slots.shiftTap, newConfig);
const primary = makeHoldTap(primaryTap, slots.hold, newConfig, forceCustomHold);
const secondary = slots.doubleTap && slots.doubleTap.value !== '&none' ? slots.doubleTap : null;
if (!primary && !secondary) return { newBinding: { value: '&none' }, newConfig };
if (primary && !secondary) return { newBinding: primary, newConfig };
if (!primary && secondary) return { newBinding: secondary, newConfig };
const tName = primary.params?.[0]?.value || primary.value.replace('&',''); const dtName = secondary.params?.[0]?.value || secondary.value.replace('&',''); const tdName = `&td_auto_${tName}_${dtName}`;
if (!newConfig.tapDances) newConfig.tapDances = [];
if (!newConfig.tapDances.find(t => t.name === tdName)) newConfig.tapDances.push({ name: tdName, tappingTermMs: 200, bindings: [primary, secondary] });
return { newBinding: { value: tdName }, newConfig };
}
const getContrastColor = (hexcolor) => {
if (!hexcolor) return '#ffffff';
let cleanHex = hexcolor.replace("#", "");
if (cleanHex.length === 3) cleanHex = cleanHex.split('').map(c => c+c).join('');
const r = parseInt(cleanHex.substr(0,2),16); const g = parseInt(cleanHex.substr(2,2),16); const b = parseInt(cleanHex.substr(4,2),16);
return (((r*299)+(g*587)+(b*114))/1000 >= 128) ? '#000000' : '#ffffff';
};
const formatKeycode = (val, osMode) => {
if (!val || val === 'none' || val === '&none') return '';
const normalized = String(val).toUpperCase().replace('&', '');
const isMac = osMode === 'mac'; const isLinux = osMode === 'linux'; const isRight = normalized.startsWith('R');
let sym = '';
if (normalized.endsWith('GUI')) sym = isMac ? '⌘' : (isLinux ? '❖' : '⊞');
else if (normalized.endsWith('CTRL')) sym = isMac ? '⌃' : 'Ctrl';
else if (normalized.endsWith('ALT')) sym = isMac ? '⌥' : 'Alt';
else if (normalized.endsWith('SHFT')) sym = '⇧';
if (sym) return sym + (isRight ? 'ᴿ' : '');
if (ZMK_MAP[normalized]) return ZMK_MAP[normalized];
if (normalized.length === 2 && normalized.startsWith('N') && '0123456789'.includes(normalized[1])) return normalized[1];
return normalized;
};
const formatParam = (p, layerNames) => {
if (p === '' || p === undefined || p === null) return '';
const pStr = String(p);
if (/^\d+$/.test(pStr)) {
let dName = layerNames[parseInt(pStr)] || `L${pStr}`;
return dName.length > 5 ? dName.substring(0, 4) + '..' : dName;
}
return pStr;
};
const formatParamFull = (p, layerNames) => {
if (p === '' || p === undefined || p === null) return '';
const pStr = String(p);
if (/^\d+$/.test(pStr)) return layerNames[parseInt(pStr)] || `Layer ${pStr}`;
return pStr;
};
const escapeHtml = (str) => String(str ?? '').replace(/[&<>"']/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"', "'":''' }[c]));
const getBeautifulLabel = (binding, osMode, hasCustomBg, config, layerNames) => {
if (!binding) return '';
const cc = (colorStr) => hasCustomBg ? 'text-inherit' : colorStr;
if (binding.decoration && binding.decoration.label) {
const lbl = binding.decoration.label;
return `<div class="kc-grid"><span class="kc-custom ${cc('text-app-text')}">${escapeHtml(lbl)}</span></div>`;
}
let val = binding.value; if (!val || val === '&none' || val === 'none') return '';
const renderStructured = (main, tl = '', icon = '') => {
return `<div class="kc-grid">
${tl ? `<span class="kc-tl ${cc('text-app-accent')}">${escapeHtml(tl)}</span>` : ''}
${icon ? `<span class="kc-tr ${cc('text-app-textMuted')}">${icon}</span>` : ''}
<span class="kc-main ${cc('text-app-text')}">${escapeHtml(main)}</span>
</div>`;
};
if (val === '&trans') return `<div class="kc-grid"><span class="text-[18px] font-bold ${cc('text-app-textMuted')}">▽</span></div>`;
if (val === 'Custom') return renderStructured(binding.params?.[0]?.value || 'Custom', '', '⚙️');
if (val.startsWith('&ht_auto_')) {
const ht = config?.holdTaps?.find(h => h.name === val);
if (ht && ht.bindings) return renderStructured(formatKeycode(ht.bindings[1], osMode), formatKeycode(ht.bindings[0], osMode), '⏱️');
}
if (val.startsWith('&mm_auto_')) {
const mm = config?.modMorphs?.find(m => m.name === val);
if (mm && mm.cases) return renderStructured(formatKeycode(mm.cases[0].binding.value, osMode), '⇧'+formatKeycode(mm.cases[1].binding.value, osMode), '🔤');
}
if (val.startsWith('&td_')) {
const td = config?.tapDances?.find(t => t.name === val);
if (td && td.bindings) return renderStructured(formatKeycode(td.bindings[0].value, osMode), formatKeycode(td.bindings[1].value, osMode), '🔀');
}
let p1 = binding.params?.[0]?.value ?? ''; let p2 = binding.params?.[1]?.value ?? '';
let combinedParams = [formatParam(p1, layerNames), formatParam(p2, layerNames)].filter(x => x).join(' ');
if (val === '&kp') {
if (p1 && MOD_WRAPPER_TO_FULL[p1] && binding.params[0].params) {
const { mods, keyVal } = unwrapModChain(binding.params[0]);
const modSymbols = mods.map(m => formatKeycode(m, osMode)).join('+');
return renderStructured(formatKeycode(keyVal, osMode), modSymbols);
}
return renderStructured(combinedParams ? formatKeycode(combinedParams, osMode) : '');
}
if (val === '&mo' || val === '&tog' || val === '&to' || val === '&sl' || val === '&layer') {
let icon = val === '&mo' || val === '&layer' ? '⭕' : (val === '&tog' ? '🔁' : (val === '&to' ? '➡️' : '📌'));
return `<div class="kc-grid"><span class="kc-main ${cc('text-app-accent')}">${escapeHtml(formatParam(p1, layerNames))}</span><span class="kc-tr ${cc('text-app-textMuted')}">${icon}</span></div>`;
}
if (val === '&mt') return renderStructured(formatKeycode(p2, osMode), formatKeycode(p1, osMode), '⏱️');
if (val === '<') return renderStructured(formatKeycode(p2, osMode), formatParam(p1, layerNames), '⏱️');
if (val === '&bt') return renderStructured(`BT ${String(p1).replace('BT_','')}`, '', '📶');
if (val === '&out') return renderStructured(String(p1).replace('OUT_',''), '', '🔌');
if (val === '&rgb_ug') return renderStructured(`RGB ${String(p1).replace('RGB_','')}`, '', '💡');
if (val === '&ext_power') return renderStructured(`PWR ${String(p1).replace('EP_','')}`, '', '🔋');
if (val === '&magic') return renderStructured(`Magic`, '', '✨');
if (val === '&sk') return renderStructured(combinedParams ? formatKeycode(combinedParams, osMode) : '', '', '📌');
if (val.startsWith('&mac')) return renderStructured(val.replace('&',''), '', '⚡');
return renderStructured(combinedParams, val.replace('&', ''));
};
const paletteLabel = (item, osMode) => {
if (item.code && RAW_MOD_CODES.has(item.code)) return <span className="key-center">{formatKeycode(item.code, osMode)}</span>;
return <span className="key-center">{item.label}</span>;
};
const describeBinding = (binding, osMode, layerNames = []) => {
if (!binding || !binding.value || binding.value === '&none' || binding.value === 'none') return 'Empty';
if (binding.value === '&trans') return 'Transparent';
const val = binding.value; const p1 = binding.params?.[0]?.value; const p2 = binding.params?.[1]?.value;
if (RAW_MOD_CODES.has(val)) return formatKeycode(val, osMode);
if (val === '&kp') {
if (p1 && MOD_WRAPPER_TO_FULL[p1] && binding.params[0].params) {
const { mods, keyVal } = unwrapModChain(binding.params[0]);
return mods.map(m => formatKeycode(m, osMode)).join(' + ') + ' + ' + formatKeycode(keyVal, osMode);
}
return p1 ? formatKeycode(String(p1), osMode) : '&kp';
}
const lName = formatParamFull(p1, layerNames);
if (val === '&mo' || val === '&layer') return `Momentary ${lName}`; if (val === '&tog') return `Toggle ${lName}`; if (val === '&to') return `Switch to ${lName}`; if (val === '&sl') return `Sticky Layer ${lName}`; if (val === '<') return `Layer-Tap (${lName})`;
if (val === 'Custom') return p1 ? String(p1) : 'Custom';
if (val === '&bt') return `Bluetooth: ${p1} ${p2 ?? ''}`; if (val === '&out') return `Output: ${p1}`; if (val === '&rgb_ug') return `RGB: ${p1}`;
if (val === '&magic') return `Magic Action`;
if (val === '&sk') {
let combinedFallback = [formatParamFull(p1, layerNames), formatParamFull(p2, layerNames)].filter(x => x).join(' ');
return `Sticky Key: ${formatKeycode(combinedFallback, osMode)}`;
}
if (val.startsWith('&ht_auto_')) return val.replace('&ht_auto_', '').split('_').map(s => formatKeycode(s, osMode)).join(' + ');
if (val.startsWith('&td_')) return val.replace('&td_', '').replace('auto_', '').split('_').map(s => formatKeycode(s, osMode)).join(' / ');
if (val.startsWith('&mm_auto_')) return val.replace('&mm_auto_', '').split('_').map(s => formatKeycode(s, osMode)).join(' / Shift+');
let combinedFallback = [formatParamFull(p1, layerNames), formatParamFull(p2, layerNames)].filter(x => x).join(' ');
if (val.startsWith('&')) return val.replace('&', '') + (combinedFallback ? ` ${combinedFallback}` : '');
return val;
};
const getModSymbol = (code, os) => {
const isMac = os === 'mac'; const isLinux = os === 'linux'; const isRight = code.startsWith('R');
let sym = '';
if (code.endsWith('C')) sym = isMac ? '⌃' : 'Ctrl'; else if (code.endsWith('A')) sym = isMac ? '⌥' : 'Alt'; else if (code.endsWith('S')) sym = '⇧'; else if (code.endsWith('G')) sym = isMac ? '⌘' : (isLinux ? '❖' : '⊞');
return <span className="flex items-start justify-center w-full"><span>{sym}</span>{isRight && <sup className="text-[7px] -ml-0.5 mt-0.5 opacity-70">R</sup>}</span>;
};
const KeyComponent = memo(({ index, geo, binding, isSelected, isComboSelected, isZenMode, onSelect, osMode, onContextMenu, onKeyMouseDown, isDragSource, isDragOver, showLeds, isTouchpad, config, layerNames }) => {
const renderBlank = isZenMode && !isComboSelected;
const hasCustomBg = !renderBlank && showLeds && !isTouchpad && binding?.value !== '&trans' && binding?.value !== '&none' && binding?.decoration?.background;
const labelHtml = renderBlank ? '' : getBeautifulLabel(binding, osMode, hasCustomBg, config, layerNames);
const outerStyle = { left: `${geo.x}px`, top: `${geo.y}px`, width: `${geo.w || KEY_SIZE}px`, height: `${geo.h || KEY_SIZE}px`, transform: geo.r ? `rotate(${geo.r}deg)` : 'none', transformOrigin: geo.o || 'center' };
const innerStyle = {};
if (hasCustomBg) { innerStyle.background = binding.decoration.background; innerStyle.borderColor = binding.decoration.background; innerStyle.color = getContrastColor(binding.decoration.background); }
if (renderBlank) { innerStyle.background = 'transparent'; innerStyle.border = '2px dashed var(--border-highlight)'; innerStyle.color = 'var(--text-muted)'; innerStyle.opacity = '0.6'; }
return (
<div className={`p-key-outer ${isSelected ? 'selected' : ''} ${isComboSelected ? 'combo-highlight' : ''} ${isDragOver ? 'drag-over' : ''} ${isTouchpad ? 'is-touchpad' : ''}`} style={outerStyle} data-key-idx={index} onClick={(e) => { e.stopPropagation(); if (!isTouchpad) onSelect(index); }} onContextMenu={(e) => { if (!isTouchpad) onContextMenu(e, index); }} onMouseDown={(e) => { if (!isTouchpad) onKeyMouseDown(e, index); }}>
<div className={`p-key ${hasCustomBg ? 'has-bg' : ''} ${isDragSource ? 'drag-source' : ''} ${isDragOver ? 'drag-over' : ''} ${geo.isRound ? 'is-round' : ''} ${isComboSelected ? 'combo-selected' : ''}`} style={innerStyle}>
{!isTouchpad && labelHtml ? <div dangerouslySetInnerHTML={{ __html: labelHtml }} className="w-full h-full flex items-center justify-center relative overflow-hidden" /> : null}
</div>
</div>
);
});
const KeyboardContainer = ({ keyboardGeo, activeLayerBindings, selectedKey, onSelectKey, scale, setScale, osMode, onContextAction, clipboard, styleClipboard, onSwapKeys, showLeds, undo, redo, handleExport, undoDisabled, redoDisabled, hasConfig, isGo60, onOpenSettings, config, isZenMode, selectedComboKeys, layerNames, stopZenMode }) => {
const containerRef = useRef(null);
const [autoFitScale, setAutoFitScale] = useState(1);
const [pan, setPan] = useState({ x: 0, y: 0 });
const [isDragging, setIsDragging] = useState(false);
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
const [contextMenu, setContextMenu] = useState(null);
const [dragSourceIdx, setDragSourceIdx] = useState(null);
const [dragOverIdx, setDragOverIdx] = useState(null);
const bounds = useMemo(() => {
let maxX = 0, maxY = 0;
keyboardGeo.forEach(k => { maxX = Math.max(maxX, k.x + (k.w || KEY_SIZE)); const extraHeight = k.r ? 60 : 0; maxY = Math.max(maxY, k.y + (k.h || KEY_SIZE) + extraHeight); });
return { w: maxX + 40, h: maxY + 40 };
}, [keyboardGeo]);
useEffect(() => {
const el = containerRef.current; if (!el) return;
const compute = () => {
const { width, height } = el.getBoundingClientRect(); if (width === 0 || height === 0) return;
const fit = Math.min(width / bounds.w, height / bounds.h) * 0.95;
setAutoFitScale(Math.max(0.2, Math.min(fit, 2))); setPan({ x: 0, y: 0 });
};
const timer = setTimeout(compute, 20); const ro = new ResizeObserver(compute); ro.observe(el);
return () => { clearTimeout(timer); ro.disconnect(); };
}, [keyboardGeo, bounds]);
const effectiveScale = autoFitScale * scale;
const handleMouseDown = (e) => { if(e.target.closest('.p-key')) return; setIsDragging(true); setDragStart({ x: e.clientX - pan.x, y: e.clientY - pan.y }); };
const handleMouseMove = (e) => { if(!isDragging) return; setPan({ x: e.clientX - dragStart.x, y: e.clientY - dragStart.y }); };
const handleMouseUp = () => setIsDragging(false);
const handleKeyMouseDown = (e, index) => {
if (isZenMode || e.button !== 0 || (isGo60 && (index === 60 || index === 61))) return;
const startX = e.clientX, startY = e.clientY; let dragging = false;
const onMove = (e2) => {
const dx = e2.clientX - startX, dy = e2.clientY - startY;
if (!dragging && Math.hypot(dx, dy) > 6) { dragging = true; setDragSourceIdx(index); }
if (dragging) {
const el = document.elementFromPoint(e2.clientX, e2.clientY)?.closest('[data-key-idx]');
const overIdx = el ? parseInt(el.dataset.keyIdx, 10) : null;
if (isGo60 && (overIdx === 60 || overIdx === 61)) setDragOverIdx(null); else setDragOverIdx(overIdx !== index ? overIdx : null);
}
};
const onUp = (e2) => {
document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onUp);
if (dragging) {
const el = document.elementFromPoint(e2.clientX, e2.clientY)?.closest('[data-key-idx]');
const targetIdx = el ? parseInt(el.dataset.keyIdx, 10) : null;
if (targetIdx !== null && targetIdx !== index && (!isGo60 || (targetIdx !== 60 && targetIdx !== 61))) onSwapKeys(index, targetIdx);
}
setDragSourceIdx(null); setDragOverIdx(null);
};
document.addEventListener('mousemove', onMove); document.addEventListener('mouseup', onUp);
};
const openContextMenu = (e, index) => { e.preventDefault(); e.stopPropagation(); if (isZenMode || (isGo60 && (index === 60 || index === 61))) return; onSelectKey(index); setContextMenu({ x: e.clientX, y: e.clientY, keyIndex: index }); };
const closeContextMenu = () => setContextMenu(null);
const runContextAction = (action) => { if (contextMenu) onContextAction(action, contextMenu.keyIndex); closeContextMenu(); };
const handlePasteDock = (e) => { e.stopPropagation(); if(selectedKey !== null) onContextAction('paste', selectedKey); };
return (
<div ref={containerRef} className={`canvas-container absolute inset-0 flex items-center justify-center ${isZenMode ? 'bg-app-panel/50' : ''}`} onMouseDown={handleMouseDown} onMouseMove={handleMouseMove} onMouseUp={handleMouseUp} onMouseLeave={handleMouseUp} onClick={() => { if(!isZenMode) onSelectKey(null); closeContextMenu(); }}>
<div className="absolute top-6 left-1/2 -translate-x-1/2 flex items-center gap-3 z-30 pointer-events-auto backdrop-blur-xl bg-app-card/80 border border-app-borderHighlight px-4 py-2 rounded-2xl shadow-2xl transition-all">
{isZenMode ? (
<div className="flex items-center gap-2 text-xs font-semibold text-app-text">
<span className="w-2 h-2 rounded-full bg-app-accent animate-pulse"></span>
<span className="text-app-text font-bold pr-2">Focus Mode: Click keys to toggle</span>
<span className="text-app-textMuted bg-app-surface px-2 py-0.5 rounded border border-app-borderHighlight">{selectedComboKeys.length} keys active</span>
<div className="w-px h-4 bg-app-borderHighlight mx-1"></div>
<button onClick={stopZenMode} className="bg-emerald-500 text-white font-bold px-3 py-1 rounded-lg hover:bg-emerald-600 transition-colors shadow-sm">Done Editing</button>
</div>
) : clipboard ? (
<div className="flex items-center gap-2 text-xs font-semibold text-app-text">
<span className="text-app-textMuted font-mono">Clipboard:</span>
<span className="px-2 py-0.5 bg-app-surface border border-app-borderHighlight rounded font-mono text-app-accent truncate max-w-[120px]">{describeBinding(clipboard, osMode, layerNames)}</span>
<div className="w-px h-4 bg-app-borderHighlight mx-1"></div>
<button onClick={handlePasteDock} disabled={selectedKey === null} className="px-2.5 py-1 bg-app-accent text-white rounded-lg hover:bg-app-accentHover disabled:opacity-30 transition-colors font-bold text-[11px] shadow-sm" title="Select a key to paste">Paste</button>
<button onClick={(e) => { e.stopPropagation(); onContextAction('clearClipboard', null); }} className="p-1 text-app-textMuted hover:text-red-400 hover:bg-red-500/10 rounded transition-colors" title="Clear Clipboard">🗑️</button>
</div>
) : (
<span className="text-[11px] text-app-textMuted font-medium tracking-wide">Click a key to edit • Right-click for options • Drag to swap</span>
)}
</div>
<div className="absolute top-6 right-6 flex items-start gap-4 pointer-events-none z-30">
<div className="flex items-center gap-1 pointer-events-auto backdrop-blur-xl bg-app-card/70 border border-app-borderHighlight p-1.5 rounded-2xl shadow-2xl">
<button onClick={undo} disabled={undoDisabled} className={`p-2 rounded-xl flex items-center justify-center w-9 h-9 transition-all ${!undoDisabled ? 'text-app-text hover:bg-white/10 hover:-translate-y-px' : 'text-app-textMuted opacity-50 cursor-not-allowed'}`} title="Undo"><svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 10h10a5 5 0 015 5v1m-15-6l4-4m-4 4l4 4"></path></svg></button>
<button onClick={redo} disabled={redoDisabled} className={`p-2 rounded-xl flex items-center justify-center w-9 h-9 transition-all ${!redoDisabled ? 'text-app-text hover:bg-white/10 hover:-translate-y-px' : 'text-app-textMuted opacity-50 cursor-not-allowed'}`} title="Redo"><svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 10H11a5 5 0 00-5 5v1m15-6l-4-4m4 4l-4 4"></path></svg></button>
<div className="w-px h-6 bg-app-borderHighlight mx-2"></div>
<button onClick={onOpenSettings} className="p-2 rounded-xl flex items-center justify-center w-9 h-9 transition-all text-app-text hover:bg-white/10 hover:-translate-y-px" title="Settings"><svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path></svg></button>
<div className="w-px h-6 bg-app-borderHighlight mx-2"></div>
{hasConfig && <button onClick={handleExport} className="btn-active text-xs font-bold px-5 py-2 rounded-xl transition-all shadow-lg border-none hover:-translate-y-px">Export</button>}
</div>
</div>
<div className="absolute bottom-6 right-6 flex items-center gap-2 backdrop-blur-xl bg-app-card/70 border border-app-borderHighlight p-1.5 rounded-full shadow-2xl z-20">
<button onClick={(e) => { e.stopPropagation(); setScale(s => Math.max(s - 0.1, 0.4)); }} className="text-app-textMuted hover:text-app-text p-1.5 hover:-translate-y-px transition-transform"><svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M20 12H4"></path></svg></button>
<button onClick={(e) => { e.stopPropagation(); setScale(1); setPan({x:0,y:0}); }} className="text-[11px] font-mono font-bold w-12 text-center text-app-text hover:text-app-text transition-colors" title="Reset to auto-fit">{Math.round(effectiveScale * 100)}%</button>
<button onClick={(e) => { e.stopPropagation(); setScale(s => Math.min(s + 0.1, 2)); }} className="text-app-textMuted hover:text-app-text p-1.5 hover:-translate-y-px transition-transform"><svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4"></path></svg></button>
</div>
<div className="relative origin-center" style={{ width: `${bounds.w}px`, height: `${bounds.h}px`, transform: `translate(${pan.x}px, ${pan.y}px) scale(${effectiveScale})` }}>
{keyboardGeo.map((geo, index) => {
const isTouchpad = isGo60 && (index === 60 || index === 61);
const isSelected = !isZenMode && selectedKey === index;
const isComboSel = isZenMode && selectedComboKeys.includes(index);
return <KeyComponent key={`matrix-key-${index}`} index={index} geo={geo} binding={activeLayerBindings[index] || { value: '&none' }} isSelected={isSelected} isComboSelected={isComboSel} isZenMode={isZenMode} onSelect={onSelectKey} osMode={osMode} onContextMenu={openContextMenu} onKeyMouseDown={handleKeyMouseDown} isDragSource={dragSourceIdx === index} isDragOver={dragOverIdx === index} showLeds={showLeds} isTouchpad={isTouchpad} config={config} layerNames={layerNames} />;
})}
</div>
{contextMenu && (
<div className="fixed z-50 bg-app-panel border border-app-borderHighlight rounded-xl shadow-2xl py-1.5 min-w-[180px] text-xs font-bold" style={{ left: contextMenu.x, top: contextMenu.y }} onClick={(e) => e.stopPropagation()}>
<button className="w-full text-left px-5 py-2.5 hover:bg-white/10 transition-colors flex items-center gap-2" onClick={() => runContextAction('copy')}><span>📋</span> Copy Action</button>
<button className={`w-full text-left px-5 py-2.5 transition-colors flex items-center gap-2 ${clipboard ? 'hover:bg-white/10' : 'text-app-textMuted cursor-not-allowed'}`} onClick={() => clipboard && runContextAction('paste')}><span>📥</span> Paste Action</button>
<div className="my-1 border-t border-app-borderHighlight"></div>
<button className="w-full text-left px-5 py-2.5 hover:bg-white/10 transition-colors flex items-center gap-2" onClick={() => runContextAction('copyStyle')}><span>🎨</span> Copy LED Color</button>
<button className={`w-full text-left px-5 py-2.5 transition-colors flex items-center gap-2 ${styleClipboard?.background ? 'hover:bg-white/10' : 'text-app-textMuted cursor-not-allowed'}`} onClick={() => styleClipboard?.background && runContextAction('pasteStyle')}><span>🖌️</span> Paste LED Color</button>
<div className="my-1 border-t border-app-borderHighlight"></div>
<button className="w-full text-left px-5 py-2.5 hover:bg-white/10 transition-colors flex items-center gap-2" onClick={() => runContextAction('clear')}><span>🗑️</span> Clear Key</button>
</div>
)}
</div>
);
};
const App = () => {
const [config, setConfig] = useState(null);
const [activeLayer, setActiveLayer] = useState(0);
const [selectedKey, setSelectedKey] = useState(null);
const [themeClass, setThemeClass] = useState(() => localStorage.getItem('glide_theme') || 'oled');
const [layoutMode, setLayoutMode] = useState(() => localStorage.getItem('glide_layout') || 'bottom');
const [osSetting, setOsSetting] = useState(() => localStorage.getItem('glide_os') || 'auto');
const [showSettings, setShowSettings] = useState(false);
const effectiveOs = useMemo(() => osSetting === 'auto' ? detectOs() : osSetting, [osSetting]);
useEffect(() => { document.documentElement.className = themeClass; localStorage.setItem('glide_theme', themeClass); }, [themeClass]);
useEffect(() => { localStorage.setItem('glide_layout', layoutMode); }, [layoutMode]);
useEffect(() => { localStorage.setItem('glide_os', osSetting); }, [osSetting]);
const [activeVerticalTab, setActiveVerticalTab] = useState('Keymap');
const [activeActionSlot, setActiveActionSlot] = useState('tap');
const [activeConfigSlot, setActiveConfigSlot] = useState(null);
const [manuallyAddedSlots, setManuallyAddedSlots] = useState(new Set());
const [showLeds, setShowLeds] = useState(true);
const [paletteSearch, setPaletteSearch] = useState('');
const [advancedSearch, setAdvancedSearch] = useState('');
const [advancedCategory, setAdvancedCategory] = useState('All');
const [targetLayerIdx, setTargetLayerIdx] = useState(0);
const [armedMods, setArmedMods] = useState(new Set());
const [bgHexInput, setBgHexInput] = useState('');
const [modSide, setModSide] = useState('L');
const [draggedLayerIdx, setDraggedLayerIdx] = useState(null);
const [dragOverLayerIdx, setDragOverLayerIdx] = useState(null);
const [panelSize, setPanelSize] = useState(() => layoutMode === 'right' ? 480 : 380);
const rightResizeStateRef = useRef(null);
const [leftPanelSize, setLeftPanelSize] = useState(() => parseInt(localStorage.getItem('glide_left_layout')) || 240);
const leftResizeStateRef = useRef(null);
useEffect(() => { localStorage.setItem('glide_left_layout', leftPanelSize); }, [leftPanelSize]);
const [leftNavMode, setLeftNavMode] = useState('Layers'); // Layers or Combos
const [selectedComboKeys, setSelectedComboKeys] = useState([]);
const [editingComboIdx, setEditingComboIdx] = useState(null);
const [showComboSettings, setShowComboSettings] = useState(false);
// Zen Mode triggers solely by editing a combo, independent of right tab selection.
const isZenMode = editingComboIdx !== null;
useEffect(() => {
setBgHexInput(''); setActiveActionSlot('tap'); setActiveConfigSlot(null); setManuallyAddedSlots(new Set());
if (!isZenMode) { setShowComboSettings(false); }
}, [selectedKey, activeLayer, isZenMode]);
const handleCanvasKeySelect = useCallback((idx) => {
if (idx === null) { setSelectedKey(null); return; }
if (isZenMode) {
if (editingComboIdx !== null && config) {
const newConfig = structuredClone(config);
const c = newConfig.combos[editingComboIdx];
const keyArray = c.keyPositions || c.key_positions || [];
if (keyArray.includes(idx)) {
c.keyPositions = keyArray.filter(k => k !== idx);
} else {
c.keyPositions = [...keyArray, idx];
}
c.key_positions = c.keyPositions;
pushHistory(newConfig);
setSelectedComboKeys(c.keyPositions);
}
} else {
setSelectedKey(idx);
}
}, [isZenMode, editingComboIdx, config]);
const [canvasScale, setCanvasScale] = useState(1.0);
const [toast, setToast] = useState(null);
const [isFetchingTemplate, setIsFetchingTemplate] = useState(false);
const [clipboard, setClipboard] = useState(null);
const [styleClipboard, setStyleClipboard] = useState(null);
const [renamingLayerIdx, setRenamingLayerIdx] = useState(null);
const [renameValue, setRenameValue] = useState('');
const handleRightResizeStart = (e) => {
e.preventDefault(); const isRight = layoutMode === 'right'; rightResizeStateRef.current = { start: isRight ? e.clientX : e.clientY, startSize: panelSize };
const onMove = (e2) => {
const delta = isRight ? (rightResizeStateRef.current.start - e2.clientX) : (rightResizeStateRef.current.start - e2.clientY);
const maxAllowed = isRight ? window.innerWidth * 0.6 : window.innerHeight * 0.8; const minAllowed = isRight ? 340 : 220;
setPanelSize(Math.max(minAllowed, Math.min(rightResizeStateRef.current.startSize + delta, maxAllowed)));
};
const onUp = () => { document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onUp); };
document.addEventListener('mousemove', onMove); document.addEventListener('mouseup', onUp);
};
const handleLeftResizeStart = (e) => {
e.preventDefault(); leftResizeStateRef.current = { start: e.clientX, startSize: leftPanelSize };
const onMove = (e2) => {
const delta = e2.clientX - leftResizeStateRef.current.start;
setLeftPanelSize(Math.max(200, Math.min(leftResizeStateRef.current.startSize + delta, window.innerWidth * 0.4)));
};
const onUp = () => { document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onUp); };
document.addEventListener('mousemove', onMove); document.addEventListener('mouseup', onUp);
};
const [jsonStr, setJsonStr] = useState(""); const [jsonError, setJsonError] = useState("");
const [undoStack, setUndoStack] = useState([]); const [redoStack, setRedoStack] = useState([]);
const isGo60 = config?.keyboard?.toLowerCase() === 'go60';
const keyboardGeo = useMemo(() => {
if (!config) return []; if (isGo60) return GO60_GEO; if (config.keyboard?.toLowerCase() === 'glove80') return GLOVE80_GEO;
return (config.layers?.[0]?.length || 0 > 0 && config.layers?.[0]?.length <= 65) ? GO60_GEO : GLOVE80_GEO;
}, [config, isGo60]);
const layerNames = useMemo(() => {
if (!config) return [];
return config.layer_names || config.layers?.map((_, i) => `Layer ${i}`) || [];
}, [config]);
useEffect(() => { if (config && activeLayer >= config.layers.length) setActiveLayer(Math.max(0, config.layers.length - 1)); }, [config]);
const currentLayerBindings = useMemo(() => config?.layers?.[activeLayer] || [], [config, activeLayer]);
const currentBinding = useMemo(() => {
if (editingComboIdx !== null && config?.combos) return config.combos[editingComboIdx]?.binding || { value: '&none' };
if (selectedKey !== null && config) return currentLayerBindings[selectedKey];
return null;
}, [selectedKey, currentLayerBindings, editingComboIdx, config]);
const parsedSlots = useMemo(() => parseSlots(currentBinding, config), [currentBinding, config]);
const usedLayoutColors = useMemo(() => {
if (!config || !Array.isArray(config.layers)) return [];
const seen = new Set(); const presetSet = new Set(KEY_COLOR_PRESETS.map(c => c.toLowerCase()));
config.layers.forEach(layer => (layer || []).forEach(b => { if (b?.decoration?.background && !presetSet.has(b.decoration.background.toLowerCase())) seen.add(b.decoration.background.toLowerCase()); }));
return Array.from(seen);
}, [config]);
const customBehaviors = useMemo(() => {
if (!config) return [];
const list = [];
if (Array.isArray(config.macros)) { config.macros.forEach(m => list.push({ label: m.name.replace('&', ''), type: m.name, cat: 'Macro' })); }
if (Array.isArray(config.holdTaps)) { config.holdTaps.filter(b => !b.name.startsWith('&ht_auto_')).forEach(b => list.push({ label: b.name.replace('&', ''), type: b.name, cat: 'Hold-Tap' })); }
if (Array.isArray(config.tapDances)) { config.tapDances.filter(b => !b.name.startsWith('&td_')).forEach(b => list.push({ label: b.name.replace('&', ''), type: b.name, cat: 'Tap-Dance' })); }
if (Array.isArray(config.modMorphs)) { config.modMorphs.filter(b => !b.name.startsWith('&mm_auto_')).forEach(b => list.push({ label: b.name.replace('&', ''), type: b.name, cat: 'Mod-Morph' })); }
if (Array.isArray(config.stickyKeys)) { config.stickyKeys.filter(b => !b.name.startsWith('&sk_auto_')).forEach(b => list.push({ label: b.name.replace('&', ''), type: b.name, cat: 'Sticky-Key' })); }
return list;
}, [config]);
const filteredBehaviors = useMemo(() => {
let res = customBehaviors;
if (advancedCategory !== 'All') res = res.filter(b => b.cat === advancedCategory);
if (advancedSearch.trim()) {
const q = advancedSearch.toLowerCase();
res = res.filter(b => b.label.toLowerCase().includes(q) || b.cat.toLowerCase().includes(q));
}
return res.sort((a, b) => a.label.localeCompare(b.label));
}, [customBehaviors, advancedSearch, advancedCategory]);
useEffect(() => { if (activeVerticalTab === 'JSON' && config && (selectedKey !== null || editingComboIdx !== null)) { setJsonStr(JSON.stringify(currentBinding || {value: "&none"}, null, 2)); setJsonError(""); } }, [selectedKey, editingComboIdx, config, activeVerticalTab, currentBinding]);
const pushHistory = useCallback((newConfig) => {
const cleanedConfig = runGC(newConfig); setUndoStack(prev => [...prev.slice(-99), structuredClone(config)]); setRedoStack([]); setConfig(cleanedConfig);
}, [config]);
const undo = () => { if (undoStack.length === 0) return; const prevConfig = undoStack[undoStack.length - 1]; setRedoStack(prev => [...prev, structuredClone(config)]); setUndoStack(prev => prev.slice(0, -1)); setConfig(prevConfig); };
const redo = () => { if (redoStack.length === 0) return; const nextConfig = redoStack[redoStack.length - 1]; setUndoStack(prev => [...prev, structuredClone(config)]); setRedoStack(prev => prev.slice(0, -1)); setConfig(nextConfig); };
const showToast = useCallback((message, kind = 'default') => { setToast({ message, kind, id: Date.now() }); }, []);
useEffect(() => { if (!toast) return; const t = setTimeout(() => setToast(null), 2200); return () => clearTimeout(t); }, [toast]);
const loadLayoutData = (parsed, sourceLabel) => {
let data = parsed?.keymap !== undefined ? parsed.keymap : parsed; if (!data || !Array.isArray(data.layers)) throw new Error('Missing a "layers" array');
setConfig(data); setActiveLayer(0); setSelectedKey(null); setEditingComboIdx(null); setLeftNavMode('Layers'); setUndoStack([]); setRedoStack([]); setCanvasScale(1.0); showToast(`Loaded ${sourceLabel}`);
};
const handleFileUpload = (e) => {
const file = e.target.files[0]; if (!file) return; const reader = new FileReader();
reader.onload = (event) => { try { loadLayoutData(JSON.parse(event.target.result), `"${file.name}"`); } catch (err) { showToast(`Couldn't read file — ${err.message}`, 'error'); } };
reader.readAsText(file); e.target.value = '';
};
const fetchTemplate = async (type) => {
setIsFetchingTemplate(true);
try {
const response = await fetch(type === 'glove80' ? 'https://gist.githubusercontent.com/moosylog/a71d65a4b2de4215d7e226449f3cadb2/raw/ee1661e9adbe197285b50ef0bd8997f6a80e795c/Glove80_default.json' : 'https://gist.githubusercontent.com/moosylog/a71d65a4b2de4215d7e226449f3cadb2/raw/ee1661e9adbe197285b50ef0bd8997f6a80e795c/Go60_default.json');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
let text = await response.text(); text = text.trim(); if (!text.startsWith('{') && !text.startsWith('[')) text = text.substring(text.indexOf('{'));
loadLayoutData(JSON.parse(text), type === 'glove80' ? 'Glove80 template' : 'Go60 template');
} catch (err) { showToast(`Couldn't fetch template — ${err.message}`, 'error'); } finally { setIsFetchingTemplate(false); }
};
const handleExport = () => {
if (!config) return; const anchor = document.createElement('a'); anchor.href = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(config, null, 2)); anchor.download = `layout_${config.keyboard || 'custom'}.json`;
document.body.appendChild(anchor); anchor.click(); anchor.remove(); showToast('Layout exported');
};
const assignAction = (item) => {
if (!config || (selectedKey === null && editingComboIdx === null)) return;
let newSlotBinding = { value: '&none' };
if (item.code) {
const activeMods = (!RAW_MOD_CODES.has(item.code) && armedMods.size > 0) ? MOD_ARM_ORDER.filter(m => armedMods.has(m)) : [];
newSlotBinding = { value: '&kp', params: [ composeKeycodeParam(item.code, activeMods) ] };
} else if (item.type) {
newSlotBinding = { value: item.type };
if (item.param1 !== undefined) { newSlotBinding.params = [{ value: item.param1, params: [] }]; if (item.param2 !== undefined) newSlotBinding.params.push({ value: item.param2, params: [] }); }
}
const newSlots = { ...parsedSlots, [activeActionSlot]: newSlotBinding };
let { newBinding, newConfig } = buildBindingAndConfig(newSlots, config, false);
if (currentBinding?.decoration) newBinding.decoration = currentBinding.decoration;
if (editingComboIdx !== null) {
if (!newConfig.combos) newConfig.combos = [];
newConfig.combos[editingComboIdx].binding = newBinding;
} else {
newConfig.layers[activeLayer][selectedKey] = newBinding;
}
pushHistory(newConfig);
if (armedMods.size > 0) setArmedMods(new Set());
};
const assignLayerTap = (layerIdx) => {
if (!config || (selectedKey === null && editingComboIdx === null)) return;
const newSlots = { ...parsedSlots, hold: { value: '&mo', params: [{value: layerIdx}] } };
let { newBinding, newConfig } = buildBindingAndConfig(newSlots, config, false);
if (currentBinding?.decoration) newBinding.decoration = currentBinding.decoration;
if (editingComboIdx !== null) { newConfig.combos[editingComboIdx].binding = newBinding; }
else { newConfig.layers[activeLayer][selectedKey] = newBinding; }