-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
979 lines (928 loc) · 56.6 KB
/
Copy pathapp.js
File metadata and controls
979 lines (928 loc) · 56.6 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
(() => {
const API_BASE = "http://127.0.0.1:37845";
const EFFECT_NAMES = { static: "静态常亮", blink: "闪烁", breathe: "呼吸" };
const SPEED_NAMES = ["极慢", "慢速", "中速", "快速", "极快"];
const TRIGGER_MODE_NAMES = { off: "关闭", feedback: "连续阻力", weapon: "枪械断点" };
const MAPPING_SCHEMA_VERSION = 3;
const CODEX_STICK_MAPPINGS = {
left_stick_up: ["ControlLeft", "ShiftLeft", "BracketLeft"],
left_stick_down: ["ControlLeft", "ShiftLeft", "BracketRight"],
};
const LEGACY_CODEX_STICK_MAPPINGS = {
left_stick_up: [
["ControlLeft", "PageUp"],
["ControlLeft", "ShiftLeft", "Minus"],
],
left_stick_down: [["ControlLeft", "PageDown"]],
};
const DEFAULT_TRIGGERS = {
left: { mode: "off", start: 3, end: 6, strength: 5 },
right: { mode: "weapon", start: 3, end: 6, strength: 5 },
};
const DEFAULT_TOUCHPAD_GESTURES = { enabled: true, threshold: 320, muteOnSwitch: false };
const HAS_SAVED_TOUCHPAD_GESTURES = Boolean(localStorage.getItem("vibeHubTouchpadGestures"));
const savedTouchpadGestures = () => {
try {
const saved = JSON.parse(localStorage.getItem("vibeHubTouchpadGestures") || "null");
return saved && typeof saved.enabled === "boolean"
? { enabled: saved.enabled, threshold: Number(saved.threshold) || 320, muteOnSwitch: Boolean(saved.muteOnSwitch) }
: { ...DEFAULT_TOUCHPAD_GESTURES };
} catch { return { ...DEFAULT_TOUCHPAD_GESTURES }; }
};
const HAS_SAVED_TRIGGERS = Boolean(localStorage.getItem("vibeHubTriggers"));
const savedTriggers = () => {
try {
const saved = JSON.parse(localStorage.getItem("vibeHubTriggers") || "null");
return saved?.left && saved?.right ? saved : structuredClone(DEFAULT_TRIGGERS);
} catch { return structuredClone(DEFAULT_TRIGGERS); }
};
const CODEX_STATUS_META = {
approval: { label: "待审批", light: "黄灯闪烁" },
working: { label: "工作中", light: "红色呼吸" },
idle: { label: "空闲", light: "绿灯常亮" },
};
const OFFICIAL_PLAYER_MASKS = [0x04, 0x0a, 0x15, 0x1b, 0x1f];
const PLAYER_LED_GROUPS = [[0, 4], [1, 3], [2]];
const MODIFIER_ORDER = ["ControlLeft", "ControlRight", "ShiftLeft", "ShiftRight", "AltLeft", "AltRight", "MetaLeft", "MetaRight"];
const MODIFIER_CODES = new Set(MODIFIER_ORDER);
const NAMED_KEY_CODES = new Set([
"Backspace", "Tab", "Enter", "Pause", "CapsLock", "Escape", "Space", "PageUp", "PageDown", "End", "Home",
"ArrowLeft", "ArrowUp", "ArrowRight", "ArrowDown", "PrintScreen", "Insert", "Delete", "ContextMenu", "NumLock", "ScrollLock",
"Semicolon", "Equal", "Comma", "Minus", "Period", "Slash", "Backquote", "BracketLeft", "Backslash", "BracketRight", "Quote",
"NumpadMultiply", "NumpadAdd", "NumpadSubtract", "NumpadDecimal", "NumpadDivide", "NumpadEnter",
...MODIFIER_ORDER,
]);
const isSupportedKeyCode = (code) => NAMED_KEY_CODES.has(code) || /^Key[A-Z]$/.test(code) || /^Digit[0-9]$/.test(code) || /^F(?:[1-9]|1[0-2])$/.test(code) || /^Numpad[0-9]$/.test(code);
const BUTTONS = [
{ id: "cross", label: "叉键", symbol: "×", group: "face", groupLabel: "主按键" },
{ id: "circle", label: "圆键", symbol: "○", group: "face", groupLabel: "主按键" },
{ id: "square", label: "方块键", symbol: "□", group: "face", groupLabel: "主按键" },
{ id: "triangle", label: "三角键", symbol: "△", group: "face", groupLabel: "主按键" },
{ id: "dpad_up", label: "方向上", symbol: "↑", group: "control", groupLabel: "方向与肩键" },
{ id: "dpad_right", label: "方向右", symbol: "→", group: "control", groupLabel: "方向与肩键" },
{ id: "dpad_down", label: "方向下", symbol: "↓", group: "control", groupLabel: "方向与肩键" },
{ id: "dpad_left", label: "方向左", symbol: "←", group: "control", groupLabel: "方向与肩键" },
{ id: "l1", label: "L1", symbol: "L1", group: "control", groupLabel: "方向与肩键" },
{ id: "r1", label: "R1", symbol: "R1", group: "control", groupLabel: "方向与肩键" },
{ id: "l2", label: "L2", symbol: "L2", group: "control", groupLabel: "方向与肩键" },
{ id: "r2", label: "R2", symbol: "R2", group: "control", groupLabel: "方向与肩键" },
{ id: "l3", label: "左摇杆按下", symbol: "L3", group: "control", groupLabel: "方向与肩键" },
{ id: "r3", label: "右摇杆按下", symbol: "R3", group: "control", groupLabel: "方向与肩键" },
{ id: "left_stick_up", label: "左摇杆上", symbol: "L↑", group: "stick", groupLabel: "摇杆方向" },
{ id: "left_stick_right", label: "左摇杆右", symbol: "L→", group: "stick", groupLabel: "摇杆方向" },
{ id: "left_stick_down", label: "左摇杆下", symbol: "L↓", group: "stick", groupLabel: "摇杆方向" },
{ id: "left_stick_left", label: "左摇杆左", symbol: "L←", group: "stick", groupLabel: "摇杆方向" },
{ id: "right_stick_up", label: "右摇杆上", symbol: "R↑", group: "stick", groupLabel: "摇杆方向" },
{ id: "right_stick_right", label: "右摇杆右", symbol: "R→", group: "stick", groupLabel: "摇杆方向" },
{ id: "right_stick_down", label: "右摇杆下", symbol: "R↓", group: "stick", groupLabel: "摇杆方向" },
{ id: "right_stick_left", label: "右摇杆左", symbol: "R←", group: "stick", groupLabel: "摇杆方向" },
{ id: "create", label: "Create", symbol: "CR", group: "system", groupLabel: "系统按键" },
{ id: "options", label: "Options", symbol: "OP", group: "system", groupLabel: "系统按键" },
{ id: "touchpad", label: "触摸板按下", symbol: "TP", group: "system", groupLabel: "系统按键" },
{ id: "ps", label: "PS 键", symbol: "PS", group: "system", groupLabel: "系统按键" },
{ id: "mute", label: "麦克风键", symbol: "MIC", group: "system", groupLabel: "系统按键" },
];
const PRESETS = {
vibe: {
cross: ["Enter"], circle: ["Escape"], square: ["ControlLeft", "KeyS"], triangle: ["ControlLeft", "ShiftLeft", "KeyP"],
dpad_up: ["ArrowUp"], dpad_right: ["ArrowRight"], dpad_down: ["ArrowDown"], dpad_left: ["ArrowLeft"],
l1: ["ControlLeft", "KeyZ"], r1: ["ControlLeft", "ShiftLeft", "KeyZ"], l2: ["ControlLeft", "KeyF"], r2: ["ControlLeft", "Enter"],
l3: ["ControlLeft", "Backquote"], r3: ["F5"], create: ["ControlLeft", "KeyK"], options: ["ControlLeft", "ShiftLeft", "KeyP"],
touchpad: ["Tab"], ps: ["MetaLeft"], mute: ["ControlLeft", "Slash"],
...CODEX_STICK_MAPPINGS,
},
navigation: {
cross: ["Enter"], circle: ["Escape"], square: ["Tab"], triangle: ["Space"],
dpad_up: ["ArrowUp"], dpad_right: ["ArrowRight"], dpad_down: ["ArrowDown"], dpad_left: ["ArrowLeft"],
l1: ["PageUp"], r1: ["PageDown"], l2: ["ControlLeft", "KeyW"], r2: ["ControlLeft", "KeyL"],
l3: ["Home"], r3: ["End"], create: ["AltLeft", "ArrowLeft"], options: ["AltLeft", "ArrowRight"],
touchpad: ["ControlLeft", "KeyT"], ps: ["MetaLeft"], mute: ["ControlLeft", "KeyL"],
},
blank: {},
};
const KEY_LABELS = {
ControlLeft: "Ctrl", ControlRight: "Ctrl(R)", ShiftLeft: "Shift", ShiftRight: "Shift(R)", AltLeft: "Alt", AltRight: "AltGr",
MetaLeft: "Win", MetaRight: "Win(R)", Enter: "Enter", Escape: "Esc", Space: "Space", Tab: "Tab", Backspace: "Backspace",
ArrowUp: "↑", ArrowRight: "→", ArrowDown: "↓", ArrowLeft: "←", PageUp: "PageUp", PageDown: "PageDown",
Backquote: "`", Slash: "/", Semicolon: ";", Quote: "'", Comma: ",", Period: ".", Minus: "-", Equal: "=",
BracketLeft: "[", BracketRight: "]", Backslash: "\\", Delete: "Delete", Insert: "Insert", Home: "Home", End: "End",
};
const DISPATCH_LABELS = {
touchpad_swipe_left: "触摸板左滑",
touchpad_swipe_right: "触摸板右滑",
};
const state = {
serviceOnline: false,
controllerConnected: false,
mappingEnabled: false,
profile: localStorage.getItem("vibeHubProfile") || "vibe",
mappings: {},
touchpadGestures: savedTouchpadGestures(),
touchpadGesturesLoaded: false,
filter: "all",
captureButton: null,
captureCodes: [],
captureRequestVersion: 0,
capturePollTimer: 0,
hoveredTwin: null,
remoteLoaded: false,
statusRequestPending: false,
lastReconnectAttempt: 0,
lastDispatchAt: 0,
lastInjectionError: null,
color: "#38DDB2",
brightness: 100,
players: [false, false, true, false, false],
effect: "static",
speed: 3,
codex: { enabled: true, available: false, state: "idle", profile: null },
triggers: savedTriggers(),
triggersLoaded: false,
restoreSavedTriggers: HAS_SAVED_TRIGGERS,
triggerPositions: { left: 0, right: 0 },
};
const $ = (selector) => document.querySelector(selector);
const $$ = (selector) => [...document.querySelectorAll(selector)];
const elements = {
connectionDot: $("#connectionDot"), connectionLabel: $("#connectionLabel"), mappingToggle: $("#mappingToggle"), mappingToggleLabel: $("#mappingToggleLabel"),
deviceName: $("#deviceName"), deviceId: $("#deviceId"), transport: $("#transportValue"), reportCount: $("#reportCount"), reportAge: $("#reportAge"), dispatchCount: $("#dispatchCount"),
reconnect: $("#reconnectButton"), serviceDot: $("#serviceDot"), serviceState: $("#serviceState"), inputBadge: $("#inputBadge"),
profile: $("#profileSelect"), resetProfile: $("#resetProfileButton"), mappingList: $("#mappingList"), mappingCount: $("#mappingCount"),
pressedButtons: $("#pressedButtons"), leftAxis: $("#leftAxisValue"), rightAxis: $("#rightAxisValue"), trigger: $("#triggerValue"),
touchpadPosition: $("#touchpadPosition"), touchpadGestureToggle: $("#touchpadGestureToggle"), touchpadGestureState: $("#touchpadGestureState"),
touchpadGestureThreshold: $("#touchpadGestureThreshold"), touchpadGestureThresholdOutput: $("#touchpadGestureThresholdOutput"),
touchpadMuteToggle: $("#touchpadMuteToggle"),
touchpadDriverLeft: $("#touchpadDriverLeft"), touchpadDriverRight: $("#touchpadDriverRight"),
touchpadLiveBadge: $("#touchpadLiveBadge"), touchpadLiveCoordinates: $("#touchpadLiveCoordinates"), touchpadSurface: $("#touchpadSurface"),
touchpadCursor: $("#touchpadCursor"), touchpadGestureDelta: $("#touchpadGestureDelta"), touchpadLastGesture: $("#touchpadLastGesture"),
leftStick: $("#leftStick"), rightStick: $("#rightStick"), activity: $("#activityMessage"), activityTime: $("#activityTime"),
twinReadout: $("#twinReadout"), twinButtonName: $("#twinButtonName"), twinMappingValue: $("#twinMappingValue"),
lightOutputBadge: $("#lightOutputBadge"), effectTitle: $("#effectTitle"), colorChip: $("#colorChip"), lightPreview: $("#lightPreview"),
previewPlayers: $("#previewPlayers"), telemetryHex: $("#telemetryHex"), telemetryRgb: $("#telemetryRgb"), telemetryMask: $("#telemetryMask"),
colorWheel: $("#colorWheel"), hex: $("#hexInput"), red: $("#redInput"), green: $("#greenInput"), blue: $("#blueInput"),
brightness: $("#brightness"), brightnessOutput: $("#brightnessOutput"), speed: $("#speed"), speedOutput: $("#speedOutput"),
playerOutput: $("#playerOutput"), playerLeds: $("#playerLeds"), apply: $("#applyButton"), turnOff: $("#turnOffButton"),
codexStatusToggle: $("#codexStatusToggle"), codexStateDot: $("#codexStateDot"), codexStateLabel: $("#codexStateLabel"), codexStateMeta: $("#codexStateMeta"),
triggerOutputBadge: $("#triggerOutputBadge"), applyTriggers: $("#applyTriggersButton"), disableTriggers: $("#disableTriggersButton"), triggerGunPreset: $("#triggerGunPreset"),
dialog: $("#messageDialog"), dialogEyebrow: $("#dialogEyebrow"), dialogTitle: $("#dialogTitle"), dialogMessage: $("#dialogMessage"), dialogClose: $("#dialogCloseButton"),
};
const cloneMappings = (mappings) => Object.fromEntries(Object.entries(mappings).map(([button, codes]) => [button, [...codes]]));
const clampByte = (value) => Math.max(0, Math.min(255, Number.parseInt(value, 10) || 0));
const timestamp = () => new Intl.DateTimeFormat("zh-CN", { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }).format(new Date());
const playerMask = () => state.players.reduce((mask, on, index) => mask | (on ? 1 << index : 0), 0);
const rgbFromHex = (hex) => {
const match = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(String(hex).trim());
return match ? [parseInt(match[1], 16), parseInt(match[2], 16), parseInt(match[3], 16)] : null;
};
const hexFromRgb = (rgb) => `#${rgb.map((value) => clampByte(value).toString(16).padStart(2, "0")).join("").toUpperCase()}`;
const hsvToRgb = (hue, saturation, value = 1) => {
const chroma = value * saturation;
const section = hue / 60;
const second = chroma * (1 - Math.abs((section % 2) - 1));
const channels = [[chroma, second, 0], [second, chroma, 0], [0, chroma, second], [0, second, chroma], [second, 0, chroma], [chroma, 0, second]][Math.floor(section) % 6];
const match = value - chroma;
return channels.map((channel) => Math.round((channel + match) * 255));
};
const rgbToHsv = ([red, green, blue]) => {
const [r, g, b] = [red, green, blue].map((channel) => channel / 255);
const max = Math.max(r, g, b); const min = Math.min(r, g, b); const delta = max - min;
let hue = 0;
if (delta) hue = ((max === r ? (g - b) / delta : max === g ? 2 + (b - r) / delta : 4 + (r - g) / delta) * 60 + 360) % 360;
return [hue, max === 0 ? 0 : delta / max, max];
};
function setActivity(message) {
elements.activity.textContent = message;
elements.activityTime.textContent = timestamp();
}
function showDialog(title, message, eyebrow = "VIBECODING HUB") {
elements.dialogEyebrow.textContent = eyebrow;
elements.dialogTitle.textContent = title;
elements.dialogMessage.textContent = message;
if (!elements.dialog.open) elements.dialog.showModal();
}
function formatShortcut(codes) {
return codes?.length ? codes.map((code) => KEY_LABELS[code] || code.replace(/^Key/, "").replace(/^Digit/, "")).join(" + ") : "未映射";
}
function formatTwinShortcut(codes) {
return codes?.length ? codes.map((code) => KEY_LABELS[code] || code.replace(/^Key/, "").replace(/^Digit/, "")).join("+") : "—";
}
function updateTwinMappings() {
$$("[data-map-for]").forEach((label) => {
const buttonId = label.dataset.mapFor;
const button = BUTTONS.find((item) => item.id === buttonId);
const codes = state.mappings[buttonId] || [];
label.textContent = formatTwinShortcut(codes);
label.title = formatShortcut(codes);
const node = label.closest(".twin-node");
node.classList.toggle("is-capturing", state.captureButton === buttonId);
node.setAttribute("aria-label", `${button?.label || buttonId},${state.captureButton === buttonId ? "等待录入" : formatShortcut(codes)}`);
});
if (state.hoveredTwin) showTwinReadout(state.hoveredTwin, false);
}
function showTwinReadout(buttonId, live = false) {
const button = BUTTONS.find((item) => item.id === buttonId);
if (!button) return;
elements.twinButtonName.textContent = button.label;
elements.twinMappingValue.textContent = formatShortcut(state.mappings[buttonId] || []);
elements.twinReadout.classList.toggle("is-live", live);
}
function clearTwinReadout() {
elements.twinButtonName.textContent = "等待输入";
elements.twinMappingValue.textContent = "—";
elements.twinReadout.classList.remove("is-live");
}
function savedProfiles() {
try {
const saved = JSON.parse(localStorage.getItem("vibeHubMappings") || "{}");
const savedSchema = Number(localStorage.getItem("vibeHubMappingSchema") || 0);
if (savedSchema < MAPPING_SCHEMA_VERSION) {
if (saved.vibe) {
Object.entries(CODEX_STICK_MAPPINGS).forEach(([input, codes]) => {
const current = saved.vibe[input];
const legacyMappings = LEGACY_CODEX_STICK_MAPPINGS[input] || [];
const isLegacyDefault = legacyMappings.some((legacy) =>
Array.isArray(current)
&& current.length === legacy.length
&& current.every((code, index) => code === legacy[index])
);
if (!(input in saved.vibe) || isLegacyDefault) saved.vibe[input] = [...codes];
});
localStorage.setItem("vibeHubMappings", JSON.stringify(saved));
}
localStorage.setItem("vibeHubMappingSchema", String(MAPPING_SCHEMA_VERSION));
}
return saved;
} catch { return {}; }
}
function loadProfile(profile) {
const saved = savedProfiles();
state.profile = profile in PRESETS ? profile : "vibe";
state.mappings = cloneMappings(saved[state.profile] || PRESETS[state.profile]);
elements.profile.value = state.profile;
localStorage.setItem("vibeHubProfile", state.profile);
renderMappings();
}
function saveProfile() {
const saved = savedProfiles();
saved[state.profile] = cloneMappings(state.mappings);
localStorage.setItem("vibeHubMappings", JSON.stringify(saved));
}
function renderMappings() {
const groups = ["face", "control", "stick", "system"];
const fragment = document.createDocumentFragment();
let mapped = 0;
BUTTONS.forEach((button) => { if (state.mappings[button.id]?.length) mapped += 1; });
elements.mappingCount.textContent = `${mapped} / ${BUTTONS.length}`;
groups.forEach((group) => {
if (state.filter !== "all" && state.filter !== group) return;
const groupButtons = BUTTONS.filter((button) => button.group === group);
const heading = document.createElement("div");
heading.className = "mapping-group-title";
heading.textContent = groupButtons[0].groupLabel.toUpperCase();
fragment.append(heading);
groupButtons.forEach((button) => {
const row = document.createElement("div");
row.className = "mapping-row";
row.classList.toggle("is-overridden", button.id === "touchpad" && state.touchpadGestures.enabled);
const codes = state.mappings[button.id] || [];
const capturing = state.captureButton === button.id;
row.innerHTML = `<div class="controller-key-label"><span class="controller-key-symbol">${button.symbol}</span><span>${button.label}</span></div><button class="shortcut-button${codes.length ? "" : " is-empty"}${capturing ? " is-capturing" : ""}" type="button" data-capture="${button.id}">${capturing ? (state.captureCodes.length ? formatShortcut(state.captureCodes) : "请按键…") : formatShortcut(codes)}</button><button class="clear-mapping" type="button" data-clear="${button.id}" title="清除映射" aria-label="清除 ${button.label} 映射">×</button>`;
fragment.append(row);
});
});
elements.mappingList.replaceChildren(fragment);
updateTwinMappings();
}
function renderTouchpadGestures(live = {}, axes = {}, touchpadPressed = false) {
elements.touchpadGestureToggle.checked = state.touchpadGestures.enabled;
elements.touchpadMuteToggle.checked = state.touchpadGestures.muteOnSwitch;
elements.touchpadGestureThreshold.value = state.touchpadGestures.threshold;
elements.touchpadGestureThresholdOutput.textContent = `${state.touchpadGestures.threshold} px`;
updateRange(elements.touchpadGestureThreshold);
const driverReady = Boolean(live.driverAvailable);
const driverLabel = driverReady ? "虚拟 HID 在线" : "等待 HID 驱动";
elements.touchpadDriverLeft.textContent = driverLabel;
elements.touchpadDriverRight.textContent = driverLabel;
const lastGesture = !driverReady ? "需要虚拟 HID 驱动" : live.lastGesture === "left" ? "左滑已触发" : live.lastGesture === "right" ? "右滑已触发" : "待机";
elements.touchpadGestureState.textContent = live.active ? "追踪中" : lastGesture;
elements.touchpadGestureState.classList.toggle("is-live", Boolean(live.active));
const touchActive = Boolean(axes.touchActive);
const touchX = Number(axes.touchX || 0); const touchY = Number(axes.touchY || 0);
elements.touchpadLiveBadge.textContent = live.active ? "手势追踪中" : touchActive ? "触点在线" : "等待触点";
elements.touchpadLiveBadge.classList.toggle("is-live", touchActive);
elements.touchpadLiveBadge.classList.toggle("is-active", Boolean(live.active));
elements.touchpadLiveCoordinates.textContent = touchActive ? `${touchX} / ${touchY}` : "— / —";
elements.touchpadCursor.classList.toggle("is-visible", touchActive);
elements.touchpadCursor.style.setProperty("--touch-x", `${Math.max(0, Math.min(100, touchX / 1919 * 100))}%`);
elements.touchpadCursor.style.setProperty("--touch-y", `${Math.max(0, Math.min(100, touchY / 1079 * 100))}%`);
elements.touchpadSurface.classList.toggle("is-pressed", touchpadPressed);
elements.touchpadSurface.classList.toggle("is-tracking", Boolean(live.active));
const delta = live.startX == null || live.currentX == null ? 0 : Number(live.currentX) - Number(live.startX);
elements.touchpadGestureDelta.textContent = `${delta > 0 ? "+" : ""}${delta} px`;
elements.touchpadLastGesture.textContent = live.lastGesture === "left" ? "左滑" : live.lastGesture === "right" ? "右滑" : "—";
}
function setServiceState(online) {
state.serviceOnline = online;
elements.serviceDot.classList.toggle("is-online", online);
elements.serviceState.textContent = online ? "本地服务在线" : "本地服务离线";
if (!online) {
state.controllerConnected = false;
elements.connectionDot.classList.remove("is-online");
elements.connectionLabel.textContent = "本地服务未连接";
elements.transport.textContent = "USB / 等待";
elements.inputBadge.textContent = "等待输入";
elements.inputBadge.classList.remove("is-live");
}
}
function updateInputStatus(input) {
state.controllerConnected = Boolean(input.connected);
state.mappingEnabled = Boolean(input.enabled);
elements.mappingToggle.checked = state.mappingEnabled;
elements.mappingToggleLabel.textContent = state.mappingEnabled ? "运行中" : "已停用";
elements.connectionDot.classList.toggle("is-online", state.controllerConnected);
elements.connectionLabel.textContent = state.controllerConnected ? "DualSense 已连接" : "等待 DualSense";
elements.deviceName.textContent = state.controllerConnected ? "DualSense Wireless Controller" : "DualSense";
elements.deviceId.textContent = `054C / ${input.productId || "----"}`;
elements.transport.textContent = state.controllerConnected ? "USB / HID" : "USB / 等待";
elements.reportCount.textContent = Number(input.reports || 0).toLocaleString("zh-CN");
elements.dispatchCount.textContent = Number(input.dispatchCount || 0).toLocaleString("zh-CN");
elements.reportAge.textContent = input.reportAgeMs == null ? "-- ms" : `${Math.min(input.reportAgeMs, 9999)} ms`;
const dispatchAt = Number(input.lastDispatchAt || 0);
if (dispatchAt > state.lastDispatchAt) {
state.lastDispatchAt = dispatchAt;
const button = BUTTONS.find((item) => item.id === input.lastDispatchedButton);
const label = button?.label || DISPATCH_LABELS[input.lastDispatchedButton] || input.lastDispatchedButton;
const nativeTouchGesture = input.lastDispatchedButton?.startsWith("touchpad_swipe_")
&& input.touchpadGestures?.switchMode === "touch-injection";
setActivity(nativeTouchGesture ? `${label} → Windows 原生四指手势已注入` : `${label} → ${formatShortcut(input.lastShortcut)} 已派发`);
}
if (input.lastInjectionError && input.lastInjectionError !== state.lastInjectionError) {
state.lastInjectionError = input.lastInjectionError;
setActivity(`按键映射注入失败:${input.lastInjectionError}`);
} else if (!input.lastInjectionError) {
state.lastInjectionError = null;
}
if (input.touchpadGestures?.switchError && input.touchpadGestures.switchError !== state.lastInjectionError) {
state.lastInjectionError = input.touchpadGestures.switchError;
setActivity(input.touchpadGestures.switchMode === "driver-required"
? "原生四指手势需要虚拟 HID 精密触控板驱动"
: `触摸手势注入失败:${input.touchpadGestures.switchError}`);
}
const pressed = new Set(input.pressed || []);
$$("#controllerVisual [data-button]").forEach((element) => element.classList.toggle("is-pressed", pressed.has(element.dataset.button)));
const names = BUTTONS.filter((button) => pressed.has(button.id)).map((button) => button.label);
elements.pressedButtons.textContent = names.length ? names.join(" / ") : "—";
elements.inputBadge.textContent = pressed.size ? `${pressed.size} 个按键` : state.controllerConnected ? "输入在线" : "等待输入";
elements.inputBadge.classList.toggle("is-live", state.controllerConnected);
const activeTwinButton = BUTTONS.find((button) => pressed.has(button.id));
if (activeTwinButton) showTwinReadout(activeTwinButton.id, true);
else if (state.hoveredTwin) showTwinReadout(state.hoveredTwin, false);
else clearTwinReadout();
const axes = input.axes || {};
const lx = Number(axes.leftX || 0); const ly = Number(axes.leftY || 0); const rx = Number(axes.rightX || 0); const ry = Number(axes.rightY || 0);
elements.leftAxis.textContent = `${lx.toFixed(2)} / ${ly.toFixed(2)}`;
elements.rightAxis.textContent = `${rx.toFixed(2)} / ${ry.toFixed(2)}`;
elements.trigger.textContent = `${Math.round(Number(axes.leftTrigger || 0) * 100)}% / ${Math.round(Number(axes.rightTrigger || 0) * 100)}%`;
elements.touchpadPosition.textContent = axes.touchActive ? `${axes.touchX} / ${axes.touchY}` : "—";
state.triggerPositions.left = Number(axes.leftTrigger || 0);
state.triggerPositions.right = Number(axes.rightTrigger || 0);
updateTriggerPositions();
elements.leftStick.style.transform = `translate(${lx * 7}px, ${ly * 7}px)`;
elements.rightStick.style.transform = `translate(${rx * 7}px, ${ry * 7}px)`;
if (!state.remoteLoaded && input.enabled && input.mappings && Object.keys(input.mappings).length) {
state.remoteLoaded = true;
state.mappings = cloneMappings(input.mappings);
renderMappings();
}
if (!state.touchpadGesturesLoaded && input.touchpadGestures) {
state.touchpadGesturesLoaded = true;
if (!HAS_SAVED_TOUCHPAD_GESTURES) {
state.touchpadGestures = {
enabled: Boolean(input.touchpadGestures.enabled),
threshold: Number(input.touchpadGestures.threshold) || DEFAULT_TOUCHPAD_GESTURES.threshold,
muteOnSwitch: Boolean(input.touchpadGestures.muteOnSwitch),
};
}
renderMappings();
}
renderTouchpadGestures(input.touchpadGestures || {}, axes, pressed.has("touchpad"));
}
async function checkBridge(showFailure = false) {
state.lastReconnectAttempt = Date.now();
try {
const response = await fetch(`${API_BASE}/health`, { cache: "no-store" });
const payload = await response.json();
setServiceState(true);
if (payload.input) updateInputStatus(payload.input);
if (payload.codex) updateCodexStatus(payload.codex);
if (payload.triggers) updateTriggerStatus(payload.triggers);
setActivity(payload.ready ? "DualSense 桥接通道已就绪" : "本地服务在线,等待 USB 手柄");
return true;
} catch (error) {
if (showFailure) console.warn(error);
setServiceState(false);
setActivity("本地桥接服务未响应");
if (showFailure) showDialog("本地服务未连接", "请启动 bridge.py,再点击重新检测。按键映射需要本地服务在后台运行。", "LOCAL BRIDGE");
return false;
}
}
async function pollStatus() {
if (state.statusRequestPending) return;
if (!state.serviceOnline) {
if (Date.now() - state.lastReconnectAttempt > 1800) await checkBridge(false);
return;
}
state.statusRequestPending = true;
try {
const response = await fetch(`${API_BASE}/api/status`, { cache: "no-store" });
if (!response.ok) throw new Error(`status ${response.status}`);
const payload = await response.json();
updateInputStatus(payload.input);
if (payload.codex) updateCodexStatus(payload.codex);
if (payload.triggers) updateTriggerStatus(payload.triggers);
} catch (error) {
setServiceState(false);
} finally {
state.statusRequestPending = false;
}
}
async function syncMapping(enabled = state.mappingEnabled) {
if (!state.serviceOnline && !(await checkBridge(false))) {
throw new Error("bridge offline");
}
const response = await fetch(`${API_BASE}/api/mapping`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ enabled, mappings: state.mappings, touchpadGestures: state.touchpadGestures }),
});
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || `mapping ${response.status}`);
updateInputStatus(payload.input);
return payload.input;
}
let mappingSyncTimer = 0;
function queueMappingSync() {
if (!state.mappingEnabled) return;
clearTimeout(mappingSyncTimer);
mappingSyncTimer = setTimeout(() => syncMapping(true).catch((error) => {
console.error(error); setActivity("映射配置同步失败");
}), 160);
}
async function requestKeyCapture(action) {
if (!state.serviceOnline && !(await checkBridge(false))) throw new Error("bridge offline");
const response = await fetch(`${API_BASE}/api/key-capture`, {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action }),
});
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || `key capture ${response.status}`);
return payload.keyCapture;
}
function stopCapturePolling() {
clearTimeout(state.capturePollTimer);
state.capturePollTimer = 0;
}
function cancelCapture({ notifyBridge = true } = {}) {
const wasCapturing = Boolean(state.captureButton);
state.captureRequestVersion += 1;
stopCapturePolling();
state.captureButton = null;
state.captureCodes = [];
renderMappings();
if (wasCapturing && notifyBridge) requestKeyCapture("cancel").catch(() => {});
}
async function pollKeyCapture(version) {
if (!state.captureButton || version !== state.captureRequestVersion) return;
try {
const capture = await requestKeyCapture("poll");
if (!state.captureButton || version !== state.captureRequestVersion) return;
if (Array.isArray(capture.result) && capture.result.length) {
completeCaptureCodes(capture.result);
return;
}
if (capture.lastError) {
const label = BUTTONS.find((button) => button.id === state.captureButton)?.label || state.captureButton;
cancelCapture({ notifyBridge: false });
setActivity(`${label} 热键录入超时,映射未改变`);
return;
}
if (!capture.active && !capture.blocking) {
cancelCapture({ notifyBridge: false });
setActivity("安全热键录入已结束,映射未改变");
return;
}
state.capturePollTimer = setTimeout(() => pollKeyCapture(version), 45);
} catch (error) {
console.error(error);
if (state.captureButton && version === state.captureRequestVersion) {
cancelCapture({ notifyBridge: false });
setActivity("安全热键录入已中断,映射未改变");
}
}
}
async function startCapture(button) {
if (state.captureButton) {
cancelCapture({ notifyBridge: false });
try { await requestKeyCapture("cancel"); } catch (error) { console.warn(error); }
}
state.captureButton = button;
state.captureCodes = [];
renderMappings();
const version = ++state.captureRequestVersion;
try {
await requestKeyCapture("start");
if (!state.captureButton || version !== state.captureRequestVersion) return;
setActivity("安全热键录入已启用,按下组合键");
pollKeyCapture(version);
} catch (error) {
console.error(error);
if (!state.captureButton || version !== state.captureRequestVersion) return;
cancelCapture({ notifyBridge: false });
showDialog("无法开始安全录入", "键盘拦截服务没有启动,未写入映射。请重启本地 Bridge 后重试。", "KEY CAPTURE");
}
}
function completeCaptureCodes(codes) {
if (!state.captureButton) return;
const buttonId = state.captureButton;
state.mappings[buttonId] = [...new Set(codes)];
const label = BUTTONS.find((button) => button.id === buttonId)?.label || buttonId;
state.captureRequestVersion += 1;
stopCapturePolling();
state.captureButton = null;
state.captureCodes = [];
saveProfile();
renderMappings();
queueMappingSync();
setActivity(`${label} 已映射为 ${formatShortcut(state.mappings[buttonId])}`);
}
function setColor(hex) {
const rgb = rgbFromHex(hex);
if (!rgb) return false;
state.color = hexFromRgb(rgb);
updateLightingPreview();
return true;
}
function updateRange(input) {
const percent = (Number(input.value) - Number(input.min)) / (Number(input.max) - Number(input.min)) * 100;
input.style.background = `linear-gradient(90deg, var(--mint) 0%, var(--mint) ${percent}%, #465154 ${percent}%, #465154 100%)`;
}
function triggerElements(side) {
const prefix = side === "left" ? "left" : "right";
return {
control: $(`[data-trigger-control="${side}"]`),
preview: $(`[data-trigger-preview="${side}"]`),
modeLabel: $(`#${prefix}TriggerModeLabel`),
summary: $(`#${prefix}TriggerSummary`),
start: $(`#${prefix}TriggerStart`),
startOutput: $(`#${prefix}TriggerStartOutput`),
end: $(`#${prefix}TriggerEnd`),
endOutput: $(`#${prefix}TriggerEndOutput`),
strength: $(`#${prefix}TriggerStrength`),
strengthOutput: $(`#${prefix}TriggerStrengthOutput`),
current: $(`#${prefix}TriggerCurrent`),
};
}
function normalizeTriggerUi(side) {
const config = state.triggers[side];
if (config.mode === "weapon") {
config.start = Math.max(2, Math.min(7, config.start));
config.end = Math.max(config.start + 1, Math.min(8, config.end));
} else {
config.start = Math.max(0, Math.min(9, config.start));
config.end = Math.max(config.start + 1, Math.min(9, config.end));
}
config.strength = Math.max(1, Math.min(8, config.strength));
}
function renderTriggerSide(side) {
normalizeTriggerUi(side);
const config = state.triggers[side];
const ui = triggerElements(side);
ui.control.dataset.mode = config.mode;
ui.preview.dataset.mode = config.mode;
ui.preview.style.setProperty("--trigger-start", `${config.start * 10}%`);
ui.preview.style.setProperty("--trigger-end", `${config.end * 10}%`);
ui.modeLabel.textContent = TRIGGER_MODE_NAMES[config.mode];
ui.summary.textContent = config.mode === "off" ? "关闭" : `${config.start * 10}% · ${config.strength}/8`;
ui.start.min = config.mode === "weapon" ? 2 : 0;
ui.start.max = config.mode === "weapon" ? 7 : 9;
ui.end.max = config.mode === "weapon" ? 8 : 9;
ui.start.value = config.start;
ui.end.value = config.end;
ui.strength.value = config.strength;
ui.startOutput.value = `${config.start * 10}%`;
ui.endOutput.value = `${config.end * 10}%`;
ui.strengthOutput.value = `${config.strength} / 8`;
[ui.start, ui.end, ui.strength].forEach(updateRange);
$$(`[data-trigger-side="${side}"]`).forEach((button) => button.classList.toggle("is-active", button.dataset.triggerMode === config.mode));
}
function renderTriggers() {
renderTriggerSide("left");
renderTriggerSide("right");
updateTriggerPositions();
localStorage.setItem("vibeHubTriggers", JSON.stringify(state.triggers));
}
function updateTriggerPositions() {
["left", "right"].forEach((side) => {
const position = Math.max(0, Math.min(1, state.triggerPositions[side] || 0));
triggerElements(side).preview.style.setProperty("--trigger-current", `${position * 100}%`);
});
}
function updateTriggerStatus(triggers) {
if (!state.triggersLoaded && triggers.left && triggers.right) {
state.triggersLoaded = true;
if (state.restoreSavedTriggers) {
state.restoreSavedTriggers = false;
setTimeout(() => sendTriggers().catch((error) => {
console.error(error);
elements.triggerOutputBadge.textContent = "同步失败";
}), 0);
} else {
state.triggers = {
left: { ...state.triggers.left, ...triggers.left },
right: { ...state.triggers.right, ...triggers.right },
};
}
renderTriggers();
}
elements.triggerOutputBadge.textContent = triggers.lastError ? "输出失败" : triggers.available ? "效果在线" : "等待输出";
elements.triggerOutputBadge.classList.toggle("is-live", Boolean(triggers.available && !triggers.lastError));
}
async function sendTriggers({ silent = false } = {}) {
if (!state.serviceOnline && !(await checkBridge(false))) throw new Error("bridge offline");
const response = await fetch(`${API_BASE}/api/triggers`, {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(state.triggers),
});
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || `triggers ${response.status}`);
updateTriggerStatus(payload.triggers);
if (!silent) setActivity(`自适应扳机已应用:L2 ${TRIGGER_MODE_NAMES[state.triggers.left.mode]} / R2 ${TRIGGER_MODE_NAMES[state.triggers.right.mode]}`);
}
let triggerSyncTimer = 0;
let triggerSyncVersion = 0;
function queueTriggerSync() {
const version = ++triggerSyncVersion;
clearTimeout(triggerSyncTimer);
localStorage.setItem("vibeHubTriggers", JSON.stringify(state.triggers));
elements.triggerOutputBadge.textContent = "正在同步";
triggerSyncTimer = setTimeout(() => sendTriggers({ silent: true }).then(() => {
if (version === triggerSyncVersion) elements.triggerOutputBadge.textContent = "实时生效";
}).catch((error) => {
console.error(error);
if (version === triggerSyncVersion) elements.triggerOutputBadge.textContent = "同步失败";
}), 100);
}
function renderColorWheel() {
const canvas = elements.colorWheel; const context = canvas.getContext("2d"); const size = canvas.width; const center = size / 2; const radius = center - 4;
const pixels = context.createImageData(size, size);
for (let y = 0; y < size; y += 1) for (let x = 0; x < size; x += 1) {
const dx = x - center; const dy = y - center; const distance = Math.hypot(dx, dy); const offset = (y * size + x) * 4;
if (distance > radius) continue;
const hue = (Math.atan2(dy, dx) * 180 / Math.PI + 450) % 360; const rgb = hsvToRgb(hue, distance / radius);
pixels.data[offset] = rgb[0]; pixels.data[offset + 1] = rgb[1]; pixels.data[offset + 2] = rgb[2]; pixels.data[offset + 3] = 255;
}
context.clearRect(0, 0, size, size); context.putImageData(pixels, 0, 0);
const [hue, saturation] = rgbToHsv(rgbFromHex(state.color)); const radians = (hue - 90) * Math.PI / 180;
const markerX = center + Math.cos(radians) * saturation * radius; const markerY = center + Math.sin(radians) * saturation * radius;
context.beginPath(); context.arc(markerX, markerY, 6, 0, Math.PI * 2); context.strokeStyle = "#fff"; context.lineWidth = 2.5; context.stroke();
context.beginPath(); context.arc(markerX, markerY, 8.5, 0, Math.PI * 2); context.strokeStyle = "rgba(10,14,16,.82)"; context.lineWidth = 1.5; context.stroke();
}
function renderLightingOutput({ rgb, effect, speed, mask, title }) {
document.documentElement.style.setProperty("--light-rgb", rgb.join(", "));
const color = hexFromRgb(rgb);
elements.telemetryHex.textContent = color; elements.telemetryRgb.textContent = rgb.join(" / "); elements.telemetryMask.textContent = `0x${mask.toString(16).padStart(2, "0").toUpperCase()}`;
elements.colorChip.style.background = color; elements.colorChip.style.boxShadow = `0 0 13px rgba(${rgb.join(",")},.65)`;
elements.effectTitle.textContent = title || EFFECT_NAMES[effect]; elements.lightPreview.classList.toggle("is-breathe", effect === "breathe"); elements.lightPreview.classList.toggle("is-blink", effect === "blink");
elements.lightPreview.style.setProperty("--effect-duration", `${5.5 - speed * .55}s`);
[...elements.previewPlayers.children].forEach((light, index) => light.classList.toggle("is-on", Boolean(mask & (1 << index))));
$$(".player-lights-preview i").forEach((light, index) => light.classList.toggle("is-on", Boolean(mask & (1 << index))));
}
function updateLightingPreview() {
const rgb = rgbFromHex(state.color);
renderLightingOutput({ rgb, effect: state.effect, speed: state.speed, mask: playerMask() });
elements.hex.value = state.color; [elements.red.value, elements.green.value, elements.blue.value] = rgb;
elements.brightness.value = state.brightness; elements.brightnessOutput.value = `${state.brightness}%`; updateRange(elements.brightness);
elements.speed.value = state.speed; elements.speedOutput.value = SPEED_NAMES[state.speed - 1]; updateRange(elements.speed);
$$("#effectControls button").forEach((button) => button.classList.toggle("is-active", button.dataset.effect === state.effect));
$$(".swatch").forEach((button) => button.classList.toggle("is-selected", button.dataset.color === state.color));
$$("#playerLeds button").forEach((button, index) => button.classList.toggle("is-on", state.players[index]));
const player = OFFICIAL_PLAYER_MASKS.indexOf(playerMask()); elements.playerOutput.value = player >= 0 ? `P${player + 1}` : "自定义";
$$("#playerPresets button").forEach((button) => button.classList.toggle("is-active", Number(button.dataset.player) === player + 1));
renderColorWheel();
}
function updateCodexStatus(codex) {
const previousEnabled = state.codex.enabled;
const previousState = state.codex.state;
state.codex = { ...state.codex, ...codex };
const enabled = Boolean(state.codex.enabled);
const statusMeta = CODEX_STATUS_META[state.codex.state] || CODEX_STATUS_META.idle;
elements.codexStatusToggle.checked = enabled;
$(".light-controls-panel").classList.toggle("is-codex-linked", enabled);
$$(".manual-light-control input, .manual-light-control button").forEach((control) => { control.disabled = enabled; });
elements.colorWheel.tabIndex = enabled ? -1 : 0;
elements.colorWheel.setAttribute("aria-disabled", String(enabled));
$$("[data-codex-state]").forEach((row) => row.classList.toggle("is-active", row.dataset.codexState === state.codex.state));
elements.codexStateDot.className = `state-light state-light-${state.codex.state}`;
elements.codexStateLabel.textContent = enabled ? `${statusMeta.label} · ${statusMeta.light}` : "手动灯光控制";
if (!enabled) elements.codexStateMeta.textContent = "Codex 联动已停用";
else if (state.codex.lastError) elements.codexStateMeta.textContent = "手柄输出重试中";
else if (!state.codex.available) elements.codexStateMeta.textContent = "等待 Codex 本机状态";
else {
const latency = Number.isFinite(Number(state.codex.hookLatencyMs)) ? ` · Hook ${state.codex.hookLatencyMs} ms` : "";
elements.codexStateMeta.textContent = `待审批 ${state.codex.pendingRequests || 0} · 任务 ${state.codex.inflightTurns || 0}${latency}`;
}
elements.lightOutputBadge.textContent = enabled ? `Codex · ${statusMeta.label}` : "手动控制";
elements.lightOutputBadge.classList.toggle("is-live", enabled);
elements.lightOutputBadge.classList.toggle("is-active", enabled && state.codex.state === "approval");
if (enabled && state.codex.profile?.lightbar) {
const profile = state.codex.profile;
const rgb = [profile.lightbar.red, profile.lightbar.green, profile.lightbar.blue];
renderLightingOutput({ rgb, effect: profile.effect, speed: profile.speed, mask: profile.playerLeds, title: `${statusMeta.label} · ${statusMeta.light}` });
} else if (previousEnabled && !enabled) {
updateLightingPreview();
}
if (enabled && previousState !== state.codex.state) setActivity(`Codex ${statusMeta.label},状态灯切换为${statusMeta.light}`);
}
async function configureCodexLighting(enabled) {
if (!state.serviceOnline && !(await checkBridge(false))) throw new Error("bridge offline");
const response = await fetch(`${API_BASE}/api/codex-lighting`, {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled }),
});
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || `codex lighting ${response.status}`);
updateCodexStatus(payload.codex);
}
function lightingPayload(off = false) {
const [red, green, blue] = rgbFromHex(state.color);
return { lightbar: { red, green, blue, brightness: off ? 0 : state.brightness }, playerLeds: playerMask(), effect: off ? "static" : state.effect, speed: state.speed };
}
async function sendLighting({ off = false, silent = false } = {}) {
if (!state.serviceOnline && !(await checkBridge(false))) {
if (!silent) showDialog("状态灯不可用", "本地桥接服务未启动。请先运行 bridge.py。", "STATUS LIGHT");
return false;
}
try {
const response = await fetch(`${API_BASE}/api/lighting`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(lightingPayload(off)) });
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || `lighting ${response.status}`);
elements.lightOutputBadge.textContent = off ? "已关闭" : "已应用"; elements.lightOutputBadge.classList.toggle("is-live", !off);
if (!silent) setActivity(off ? "状态灯已关闭" : `${state.color} / ${EFFECT_NAMES[state.effect]} 已应用`);
return true;
} catch (error) {
console.error(error); elements.lightOutputBadge.textContent = "输出失败"; elements.lightOutputBadge.classList.remove("is-live");
if (!silent) showDialog("状态灯输出失败", "确认 DualSense 已通过 USB 连接,且没有被其他手柄工具独占。", "STATUS LIGHT");
return false;
}
}
function pickColor(event) {
const bounds = elements.colorWheel.getBoundingClientRect(); const center = elements.colorWheel.width / 2; const radius = center - 4;
const dx = (event.clientX - bounds.left) * elements.colorWheel.width / bounds.width - center; const dy = (event.clientY - bounds.top) * elements.colorWheel.height / bounds.height - center;
const distance = Math.min(Math.hypot(dx, dy), radius); const hue = (Math.atan2(dy, dx) * 180 / Math.PI + 450) % 360;
setColor(hexFromRgb(hsvToRgb(hue, distance / radius)));
}
$$(".nav-item").forEach((button) => button.addEventListener("click", () => {
$$(".nav-item").forEach((item) => item.classList.toggle("is-active", item === button));
$$(".view").forEach((view) => view.classList.toggle("is-active", view.id === `${button.dataset.view}View`));
$(".main-stage").scrollTop = 0;
window.scrollTo(0, 0);
}));
elements.reconnect.addEventListener("click", () => checkBridge(true));
elements.mappingToggle.addEventListener("change", async () => {
const enabled = elements.mappingToggle.checked;
elements.mappingToggle.disabled = true;
try {
await syncMapping(enabled);
setActivity(enabled ? "键盘映射已启用" : "键盘映射已停用");
} catch (error) {
console.error(error); elements.mappingToggle.checked = state.mappingEnabled;
showDialog("无法切换映射", "本地桥接服务没有响应。请启动 bridge.py 后重试。", "KEY MAPPING");
} finally { elements.mappingToggle.disabled = false; }
});
elements.profile.addEventListener("change", () => { loadProfile(elements.profile.value); saveProfile(); queueMappingSync(); setActivity(`已切换到 ${elements.profile.selectedOptions[0].textContent}`); });
elements.resetProfile.addEventListener("click", () => {
const saved = savedProfiles(); delete saved[state.profile]; localStorage.setItem("vibeHubMappings", JSON.stringify(saved)); loadProfile(state.profile); queueMappingSync(); setActivity("当前配置已恢复预设");
});
elements.touchpadGestureToggle.addEventListener("change", () => {
state.touchpadGestures.enabled = elements.touchpadGestureToggle.checked;
localStorage.setItem("vibeHubTouchpadGestures", JSON.stringify(state.touchpadGestures));
renderTouchpadGestures();
renderMappings();
queueMappingSync();
setActivity(state.touchpadGestures.enabled ? "触摸板桌面手势已启用" : "触摸板按键映射已恢复");
});
elements.touchpadGestureThreshold.addEventListener("input", () => {
state.touchpadGestures.threshold = Number(elements.touchpadGestureThreshold.value);
localStorage.setItem("vibeHubTouchpadGestures", JSON.stringify(state.touchpadGestures));
renderTouchpadGestures();
queueMappingSync();
});
elements.touchpadMuteToggle.addEventListener("change", () => {
state.touchpadGestures.muteOnSwitch = elements.touchpadMuteToggle.checked;
localStorage.setItem("vibeHubTouchpadGestures", JSON.stringify(state.touchpadGestures));
renderTouchpadGestures();
queueMappingSync();
setActivity(state.touchpadGestures.muteOnSwitch ? "桌面切换静音已启用" : "桌面切换静音已停用");
});
$$(".mapping-filter button").forEach((button) => button.addEventListener("click", () => { state.filter = button.dataset.filter; $$(".mapping-filter button").forEach((item) => item.classList.toggle("is-active", item === button)); renderMappings(); }));
elements.mappingList.addEventListener("click", (event) => {
const capture = event.target.closest("[data-capture]"); const clear = event.target.closest("[data-clear]");
if (capture) startCapture(capture.dataset.capture);
if (clear) { delete state.mappings[clear.dataset.clear]; cancelCapture(); saveProfile(); renderMappings(); queueMappingSync(); setActivity("映射已清除"); }
});
$("#controllerVisual").addEventListener("click", (event) => {
const node = event.target.closest(".twin-node[data-button]");
if (!node) return;
state.filter = "all";
$$(".mapping-filter button").forEach((button) => button.classList.toggle("is-active", button.dataset.filter === "all"));
showTwinReadout(node.dataset.button, false);
startCapture(node.dataset.button);
const label = BUTTONS.find((button) => button.id === node.dataset.button)?.label || node.dataset.button;
setActivity(`${label} 等待键盘输入`);
});
$("#controllerVisual").addEventListener("pointerover", (event) => {
const node = event.target.closest(".twin-node[data-button]");
if (!node) return;
state.hoveredTwin = node.dataset.button;
showTwinReadout(node.dataset.button, node.classList.contains("is-pressed"));
});
$("#controllerVisual").addEventListener("pointerout", (event) => {
const node = event.target.closest(".twin-node[data-button]");
const nextNode = event.relatedTarget?.closest?.(".twin-node[data-button]");
if (!node || nextNode === node) return;
state.hoveredTwin = nextNode?.dataset.button || null;
if (nextNode) showTwinReadout(nextNode.dataset.button, nextNode.classList.contains("is-pressed"));
else if (!$("#controllerVisual .twin-node.is-pressed")) clearTwinReadout();
});
window.addEventListener("keydown", (event) => {
if (!state.captureButton) return;
event.preventDefault(); event.stopPropagation();
}, true);
window.addEventListener("keyup", (event) => {
if (!state.captureButton) return;
event.preventDefault(); event.stopPropagation();
}, true);
window.addEventListener("beforeunload", () => { if (state.captureButton) requestKeyCapture("cancel").catch(() => {}); });
elements.hex.addEventListener("change", () => { if (!setColor(elements.hex.value)) { elements.hex.value = state.color; setActivity("颜色格式应为 #RRGGBB"); } });
[elements.red, elements.green, elements.blue].forEach((input) => input.addEventListener("input", () => setColor(hexFromRgb([elements.red.value, elements.green.value, elements.blue.value]))));
elements.colorWheel.addEventListener("pointerdown", (event) => { elements.colorWheel.setPointerCapture(event.pointerId); pickColor(event); });
elements.colorWheel.addEventListener("pointermove", (event) => { if (event.buttons) pickColor(event); });
elements.colorWheel.addEventListener("keydown", (event) => {
const [hue, saturation] = rgbToHsv(rgbFromHex(state.color)); const step = event.shiftKey ? 15 : 4; const saturationStep = event.shiftKey ? .12 : .04;
const nextHue = event.key === "ArrowLeft" ? hue - step : event.key === "ArrowRight" ? hue + step : hue;
const nextSaturation = event.key === "ArrowDown" ? saturation - saturationStep : event.key === "ArrowUp" ? saturation + saturationStep : saturation;
if (nextHue === hue && nextSaturation === saturation) return; event.preventDefault(); setColor(hexFromRgb(hsvToRgb((nextHue + 360) % 360, Math.max(0, Math.min(1, nextSaturation)))));
});
$$(".swatch").forEach((button) => button.addEventListener("click", () => setColor(button.dataset.color)));
elements.brightness.addEventListener("input", () => { state.brightness = Number(elements.brightness.value); updateLightingPreview(); });
elements.speed.addEventListener("input", () => { state.speed = Number(elements.speed.value); updateLightingPreview(); });
$$("#effectControls button").forEach((button) => button.addEventListener("click", () => { state.effect = button.dataset.effect; updateLightingPreview(); }));
$("#playerPresets").addEventListener("click", (event) => { const button = event.target.closest("[data-player]"); if (!button) return; const mask = OFFICIAL_PLAYER_MASKS[Number(button.dataset.player) - 1]; state.players = state.players.map((_on, index) => Boolean(mask & (1 << index))); updateLightingPreview(); });
elements.playerLeds.addEventListener("click", (event) => { const button = event.target.closest("[data-index]"); if (!button) return; const index = Number(button.dataset.index); const group = PLAYER_LED_GROUPS.find((indices) => indices.includes(index)); const next = !state.players[group[0]]; group.forEach((led) => { state.players[led] = next; }); updateLightingPreview(); });
elements.apply.addEventListener("click", () => sendLighting()); elements.turnOff.addEventListener("click", () => sendLighting({ off: true }));
elements.codexStatusToggle.addEventListener("change", async () => {
const enabled = elements.codexStatusToggle.checked;
elements.codexStatusToggle.disabled = true;
try {
await configureCodexLighting(enabled);
setActivity(enabled ? "Codex 状态灯联动已启用" : "Codex 状态灯联动已停用,可使用手动灯控");
} catch (error) {
console.error(error); elements.codexStatusToggle.checked = state.codex.enabled;
showDialog("无法切换 Codex 联动", "本地桥接服务没有响应,请确认 bridge.py 正在运行。", "CODEX STATUS");
} finally { elements.codexStatusToggle.disabled = false; }
});
$$("[data-trigger-side][data-trigger-mode]").forEach((button) => button.addEventListener("click", () => {
state.triggers[button.dataset.triggerSide].mode = button.dataset.triggerMode;
renderTriggers();
queueTriggerSync();
}));
["left", "right"].forEach((side) => {
const ui = triggerElements(side);
ui.start.addEventListener("input", () => { state.triggers[side].start = Number(ui.start.value); renderTriggerSide(side); queueTriggerSync(); });
ui.end.addEventListener("input", () => { state.triggers[side].end = Number(ui.end.value); renderTriggerSide(side); queueTriggerSync(); });
ui.strength.addEventListener("input", () => { state.triggers[side].strength = Number(ui.strength.value); renderTriggerSide(side); queueTriggerSync(); });
});
elements.triggerGunPreset.addEventListener("click", () => {
state.triggers.left = { mode: "weapon", start: 3, end: 6, strength: 5 };
state.triggers.right = { mode: "weapon", start: 3, end: 6, strength: 5 };
renderTriggers();
queueTriggerSync();
});
elements.disableTriggers.addEventListener("click", async () => {
state.triggers.left.mode = "off";
state.triggers.right.mode = "off";
renderTriggers();
try { await sendTriggers(); } catch (error) { console.error(error); showDialog("无法关闭扳机效果", "请确认 DualSense 已通过 USB 连接,且桥接服务正在运行。", "ADAPTIVE TRIGGERS"); }
});
elements.applyTriggers.addEventListener("click", async () => {
clearTimeout(triggerSyncTimer);
triggerSyncVersion += 1;
elements.applyTriggers.disabled = true;
try { await sendTriggers(); } catch (error) { console.error(error); showDialog("扳机效果应用失败", "请确认 DualSense 已通过 USB 连接,且没有被其他手柄软件占用。", "ADAPTIVE TRIGGERS"); }
finally { elements.applyTriggers.disabled = false; }
});
elements.dialogClose.addEventListener("click", () => elements.dialog.close());
loadProfile(state.profile);
renderTouchpadGestures();
updateLightingPreview();
renderTriggers();
setActivity("HUB 已就绪");
checkBridge(false);
setInterval(pollStatus, 120);
})();