-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2167 lines (2026 loc) · 96.5 KB
/
Copy pathapp.js
File metadata and controls
2167 lines (2026 loc) · 96.5 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
// projectMM Web UI — all logic in one hand-maintained file per CLAUDE.md.
// Loaded as <script type="module"> so it can import the shared install-picker
// component used by both the device UI (here, OTA flash) and the GitHub Pages
// installer (first flash via Web Serial). Module loading is deferred by
// default; entry-point is the WS init at the bottom — no ordering surprises.
import { installPicker } from "/install-picker.js";
import { preview } from "/preview3d.js";
// Sections (top to bottom):
// 1. State + storage
// 2. WebSocket (with keepalive, visibility pause, bfcache, exponential backoff)
// 3. REST helpers + module mutations
// 4. Render pipeline: render() → renderNav() → renderCards() → createCard() → createControl()
// 5. State patching (no-rebuild contract): updateValues() + updateModuleControls()
// 6. Type picker
// 7. Drag-to-reorder (HTML5 DnD on desktop; touchstart-gated on mobile)
// (3D WebGL preview lives in preview3d.js — imported as `preview`)
// 8. Status bar wiring (device name, sys stats, theme, reboot)
// 9. Boot
//
// Load-bearing invariants:
// - dragTs[mid:key] cooldown: ignore WS pushes for a control the user has touched
// in the last 1s. Prevents slider snap-back during drag.
// - ctrl.hidden: skip rendering hidden controls (plan-10 feature). Persistence still
// loads them — toggling visibility doesn't lose state.
// - No-rebuild contract: WS state updates patch values in place via querySelector.
// We only rebuild the DOM on structural changes (add/delete/move) and explicit
// select-driven onBuildControls rebuilds.
// ---------------------------------------------------------------------------
// 1. State + storage
// ---------------------------------------------------------------------------
let state = null;
let selectedModule = null;
let availableTypes = []; // populated from GET /api/types after first connection
let ws = null;
let wsRetryMs = 500; // exponential backoff: 500 → 1000 → 2000 → 4000 → 5000
let wsHeartbeat = null;
let wsPaused = false; // gated by document.visibilityState
const dragTimers = {}; // per-control debounce timers (clearTimeout handles)
const dragTs = {}; // per-control last-touched timestamp (ms)
// Control types whose value the user can edit — updateModuleControls suppresses a
// WS state push for one of these while the user is mid-edit (see dragTs). The
// read-only types (display/display-int/time/progress) and the composite `list`
// are absent on purpose: they always reflect the latest push.
const EDITABLE_CONTROL_TYPES = new Set(
["uint8", "uint16", "int16", "pin", "bool", "text", "password", "select", "ipv4"]);
const TIMING_MODES = ["fps", "ms"];
// localStorage keys per ui.md
const LS_SELECTED = "mm_selectedRoot";
const LS_THEME = "mm_theme";
const LS_TIMING = "mm_timing_mode";
// One-release migration for the old key from the pre-spec UI
function lsRead(key, legacyKey, defaultVal) {
const v = localStorage.getItem(key);
if (v !== null) return v;
if (legacyKey) {
const legacy = localStorage.getItem(legacyKey);
if (legacy !== null) return legacy;
}
return defaultVal;
}
let timingMode = lsRead(LS_TIMING, null, "fps");
let theme = lsRead(LS_THEME, null, "dark");
// ---------------------------------------------------------------------------
// 2. WebSocket
// ---------------------------------------------------------------------------
function connectWs() {
if (ws) {
try { ws.close(); } catch {}
ws = null;
}
const url = `ws://${location.host}/ws`;
ws = new WebSocket(url);
ws.binaryType = "arraybuffer";
ws.onopen = () => {
wsRetryMs = 500; // reset backoff
setWsDot(true);
// Keepalive ping every 25s — Safari kills idle WebSockets otherwise
clearInterval(wsHeartbeat);
wsHeartbeat = setInterval(() => {
if (ws && ws.readyState === WebSocket.OPEN) ws.send("ping");
}, 25000);
};
ws.onmessage = (e) => {
if (wsPaused) return;
if (e.data instanceof ArrayBuffer) {
preview.onBinaryMessage(e.data);
return;
}
try {
const data = JSON.parse(e.data);
state = data;
updateValues();
} catch {
// ignore malformed messages
}
};
ws.onclose = () => {
setWsDot(false);
clearInterval(wsHeartbeat);
wsHeartbeat = null;
// Exponential backoff with 5s ceiling
setTimeout(connectWs, wsRetryMs);
wsRetryMs = Math.min(wsRetryMs * 2, 5000);
};
ws.onerror = () => { /* onclose will fire next */ };
}
function setWsDot(connected) {
const dot = document.getElementById("ws-dot");
if (!dot) return;
dot.className = connected ? "ws-dot connected" : "ws-dot disconnected";
}
// Visibility / bfcache hooks
document.addEventListener("visibilitychange", () => {
wsPaused = (document.visibilityState === "hidden");
});
window.addEventListener("pageshow", (e) => {
if (e.persisted) {
// Safari restored from bfcache: re-establish state
wsPaused = false;
if (!ws || ws.readyState !== WebSocket.OPEN) connectWs();
}
});
// ---------------------------------------------------------------------------
// 3. REST helpers + module mutations
// ---------------------------------------------------------------------------
async function init() {
applyTheme(theme);
setupStatusBarButtons();
try {
const resp = await fetch("/api/state");
state = await resp.json();
const savedSel = lsRead(LS_SELECTED, "mm.selectedModule", null);
if (state.modules && state.modules.length > 0) {
const exists = savedSel && state.modules.some(m => m.name === savedSel);
selectedModule = exists ? savedSel : state.modules[0].name;
}
renderNav();
renderCards();
updateStatusBar();
// /api/types arrived in plan-11; fetch in parallel. When it arrives, re-render
// so reset-to-default buttons (whose defaults come from this payload) appear.
fetch("/api/types").then(r => r.json()).then(j => {
availableTypes = j.types || [];
if (state) renderCards();
}).catch(() => {});
} catch (err) {
document.getElementById("main").textContent = "Error: " + err.message;
}
connectWs();
preview.init();
preview.setupLayout();
}
async function sendControl(moduleName, controlName, value) {
// Best-effort by design — failures are not retried here. Non-ok responses +
// network errors are logged to console so a user with devtools open can see
// what went wrong (e.g. a control value the device-side validator rejected).
try {
const res = await fetch("/api/control", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({module: moduleName, control: controlName, value: value})
});
if (!res.ok) {
console.warn(`[control] POST ${moduleName}.${controlName} failed (status=${res.status})`);
}
} catch (e) {
console.warn(`[control] POST ${moduleName}.${controlName} failed (error=${e && e.message ? e.message : e})`);
}
}
async function refetchState() {
try {
const r = await fetch("/api/state");
state = await r.json();
renderNav();
renderCards();
} catch {}
}
async function addModule(type, parentName) {
if (!type) return;
const body = {type: type};
if (parentName) body.parent_id = parentName;
await fetch("/api/modules", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body)
});
refetchState();
}
async function deleteModule(name) {
await fetch("/api/modules/" + encodeURIComponent(name), {method: "DELETE"});
refetchState();
}
// move to absolute index (0..siblings.length-1). Called from drag-and-drop.
async function moveModuleTo(name, toIndex) {
await fetch("/api/modules/" + encodeURIComponent(name) + "/move", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({to: toIndex})
});
refetchState();
}
// swap a module for another type at the same position. The replacement starts
// with its own default control values — a clean swap, not a value carry-over.
async function replaceModule(name, newType) {
if (!newType) return;
await fetch("/api/modules/" + encodeURIComponent(name) + "/replace", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({type: newType})
});
refetchState();
}
async function rebootDevice() {
try {
await fetch("/api/reboot", {method: "POST"});
} catch { /* connection may drop mid-response — that's the device restarting */ }
// WS will reconnect on its own via onclose backoff
}
// ---------------------------------------------------------------------------
// 4. Render pipeline
// ---------------------------------------------------------------------------
function renderNav() {
const nav = document.getElementById("nav");
if (!nav || !state) return;
nav.innerHTML = "";
// One entry per root module. Clicking selects that root — only the selected
// root's card subtree is rendered (one root visible at a time).
const list = document.createElement("div");
list.className = "nav-list";
for (const mod of state.modules) {
const item = document.createElement("button");
item.type = "button";
item.className = "nav-item";
item.textContent = mod.name;
item.dataset.module = mod.name;
if (mod.name === selectedModule) item.classList.add("active");
item.addEventListener("click", () => selectModule(mod.name));
list.appendChild(item);
}
nav.appendChild(list);
nav.appendChild(buildNavFooter());
}
// Footer pinned to the bottom of the side nav: copyright + social links.
function buildNavFooter() {
const footer = document.createElement("footer");
footer.className = "nav-footer";
const links = document.createElement("div");
links.className = "nav-social";
const SOCIAL = [
["GitHub", "https://github.com/MoonModules/projectMM",
"M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 0 0 7.86 10.92c.58.1.79-.25.79-.56v-2c-3.2.7-3.88-1.54-3.88-1.54-.53-1.34-1.3-1.7-1.3-1.7-1.06-.72.08-.71.08-.71 1.17.08 1.79 1.2 1.79 1.2 1.04 1.79 2.73 1.27 3.4.97.1-.76.41-1.27.74-1.56-2.55-.29-5.24-1.28-5.24-5.69 0-1.26.45-2.29 1.19-3.1-.12-.29-.52-1.46.11-3.05 0 0 .97-.31 3.18 1.18a11 11 0 0 1 5.8 0c2.2-1.49 3.17-1.18 3.17-1.18.63 1.59.23 2.76.11 3.05.74.81 1.19 1.84 1.19 3.1 0 4.42-2.69 5.39-5.25 5.68.42.36.8 1.08.8 2.18v3.23c0 .31.21.67.8.56A11.5 11.5 0 0 0 23.5 12C23.5 5.65 18.35.5 12 .5Z"],
["Discord", "https://discord.gg/TC8NSUSCdV",
"M20.32 4.37A19.8 19.8 0 0 0 15.45 2.9a13.6 13.6 0 0 0-.62 1.27 18.3 18.3 0 0 0-5.67 0A13 13 0 0 0 8.54 2.9 19.7 19.7 0 0 0 3.67 4.37C.57 8.96-.27 13.44.15 17.85a19.9 19.9 0 0 0 6 3.03c.49-.66.92-1.36 1.29-2.1-.71-.27-1.39-.6-2.03-.99.17-.12.34-.25.5-.38a14.2 14.2 0 0 0 12.18 0c.16.13.33.26.5.38-.64.39-1.32.72-2.03.99.37.74.8 1.44 1.29 2.1a19.8 19.8 0 0 0 6-3.03c.5-5.1-.85-9.55-3.58-13.48ZM8.02 15.13c-1.18 0-2.15-1.08-2.15-2.41 0-1.33.95-2.42 2.15-2.42 1.2 0 2.17 1.1 2.15 2.42 0 1.33-.95 2.41-2.15 2.41Zm7.96 0c-1.18 0-2.15-1.08-2.15-2.41 0-1.33.95-2.42 2.15-2.42 1.2 0 2.17 1.1 2.15 2.42 0 1.33-.95 2.41-2.15 2.41Z"],
["Reddit", "https://reddit.com/r/moonmodules",
"M22 12c0-1.1-.9-2-2-2-.55 0-1.04.22-1.4.58a9.8 9.8 0 0 0-5.1-1.55l.87-4.1 2.85.6a1.5 1.5 0 1 0 .15-1l-3.18-.67a.5.5 0 0 0-.59.38l-.97 4.57a9.8 9.8 0 0 0-5.16 1.55A2 2 0 1 0 4 13.66a3.9 3.9 0 0 0-.05.6c0 3.3 3.86 5.98 8.62 5.98 4.76 0 8.62-2.68 8.62-5.98 0-.2-.02-.4-.05-.6.53-.36.86-.96.86-1.66ZM8 13.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Zm8.32 4.07c-1.04 1.04-3.02 1.12-3.6 1.12-.58 0-2.57-.08-3.6-1.12a.4.4 0 0 1 .56-.56c.65.65 2.05.88 3.04.88.99 0 2.39-.23 3.04-.88a.4.4 0 0 1 .56.56ZM16 15a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3Z"],
["YouTube", "https://www.youtube.com/@MoonModulesLighting",
"M23.5 6.5a3 3 0 0 0-2.12-2.12C19.5 3.87 12 3.87 12 3.87s-7.5 0-9.38.51A3 3 0 0 0 .5 6.5C0 8.38 0 12 0 12s0 3.62.5 5.5a3 3 0 0 0 2.12 2.12c1.88.51 9.38.51 9.38.51s7.5 0 9.38-.51a3 3 0 0 0 2.12-2.12C24 15.62 24 12 24 12s0-3.62-.5-5.5ZM9.6 15.6V8.4l6.2 3.6-6.2 3.6Z"],
];
for (const [name, url, path] of SOCIAL) {
const a = document.createElement("a");
a.href = url;
a.target = "_blank";
a.rel = "noopener";
a.title = name;
a.setAttribute("aria-label", name);
a.innerHTML = `<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="${path}"/></svg>`;
links.appendChild(a);
}
footer.appendChild(links);
// Diagnostic bundle download. Fetches /api/state + /api/system from
// the *same* origin we're on (the device itself) — sidesteps Chrome's
// mixed-content blocker that prevents the install page (HTTPS Pages)
// from doing the same fetch against the device (HTTP LAN). Output is
// a single JSON blob the user can attach to a bug report.
const diag = document.createElement("a");
diag.href = "#";
diag.className = "nav-diag-link";
diag.textContent = "Download diagnostics";
diag.addEventListener("click", async (ev) => {
ev.preventDefault();
try {
const [stateResp, systemResp] = await Promise.all([
fetch("/api/state"),
fetch("/api/system"),
]);
const [stateJson, systemJson] = await Promise.all([
stateResp.json(),
systemResp.json(),
]);
const bundle = {
capturedAt: new Date().toISOString(),
origin: location.origin,
state: stateJson,
system: systemJson,
};
const blob = new Blob([JSON.stringify(bundle, null, 2)],
{ type: "application/json" });
// Devicename comes from system.deviceName if present, else
// falls back to the hostname (e.g. "MM-BD3C.local") so the
// filename is still useful when SystemModule's wire shape
// doesn't include the name field.
const devName = (systemJson && systemJson.deviceName)
|| location.hostname || "device";
const fname = `projectMM-diag-${devName}-${Date.now()}.json`;
const a = document.createElement("a");
const blobUrl = URL.createObjectURL(blob);
a.href = blobUrl;
a.download = fname;
a.click();
// Defer the revoke so the browser has time to start the download.
// Revoking immediately after click() is technically race-safe on
// recent Chrome / Firefox (the click navigation is synchronous)
// but Safari has been observed dropping downloads under a fast
// revoke. A few seconds is the canonical workaround.
setTimeout(() => URL.revokeObjectURL(blobUrl), 4000);
} catch (e) {
alert(`Diagnostic capture failed: ${e && e.message ? e.message : e}`);
}
});
footer.appendChild(diag);
const copy = document.createElement("div");
copy.className = "nav-copyright";
copy.textContent = `© ${new Date().getFullYear()} MoonModules`;
footer.appendChild(copy);
return footer;
}
function selectModule(name) {
selectedModule = name;
localStorage.setItem(LS_SELECTED, name);
document.querySelectorAll(".nav-item").forEach((el) => {
el.classList.toggle("active", el.dataset.module === name);
});
renderCards();
closeNavDrawer();
}
function findModule(name, modules) {
if (!modules) modules = state.modules;
for (const m of modules) {
if (m.name === name) return m;
if (m.children) {
const found = findModule(name, m.children);
if (found) return found;
}
}
return null;
}
function renderCards() {
const main = document.getElementById("main");
if (!main || !state) return;
main.innerHTML = "";
// One root visible at a time: render only the selected root's subtree.
// Falls back to the first root if the selection is missing or stale.
let root = selectedModule ? findModule(selectedModule) : null;
if (!root && state.modules.length > 0) {
root = state.modules[0];
selectedModule = root.name;
}
if (root) renderModuleTree(root, main, 0);
}
function renderModuleTree(mod, parentEl, depth) {
const { card, childrenEl } = createCard(mod, depth);
parentEl.appendChild(card);
// Children render inside this card's .card-children wrapper, not as flat
// siblings. childrenEl is null for modules that don't accept children.
if (childrenEl && mod.children && mod.children.length > 0) {
for (const child of mod.children) {
renderModuleTree(child, childrenEl, depth + 1);
}
}
}
function createCard(mod, depth) {
const card = document.createElement("div");
card.className = "card";
card.dataset.module = mod.name;
card.dataset.depth = String(depth);
// -- Title row: [enabled?] [name] [stats] [actions] --
const title = document.createElement("div");
title.className = "card-title";
// The enabled toggle is built here but appended later — it joins the
// right-hand action cluster (next to ✎ × ?) rather than sitting at the start
// of the row, for visual grouping with the other per-card controls.
// Rendered as a <button> styled as a 26×26 rounded box (matching .card-btn);
// showing ✓ when on, blank when off. Stores its checked state in
// data-checked so updateValues can sync from WS pushes. A native <input>
// would not match the other buttons' frame and corner radius.
const enabled = document.createElement("button");
enabled.type = "button";
enabled.className = "module-enabled";
enabled.dataset.mid = mod.name;
enabled.dataset.key = "enabled";
enabled.setAttribute("aria-pressed", "true");
enabled.title = "Enable / disable";
const setEnabledUi = (on) => {
enabled.dataset.checked = on ? "true" : "false";
enabled.textContent = "⏻";
enabled.classList.toggle("module-enabled--off", !on);
enabled.setAttribute("aria-pressed", on ? "true" : "false");
card.classList.toggle("card--disabled", !on);
};
setEnabledUi(mod.enabled === undefined ? true : !!mod.enabled);
enabled.addEventListener("click", () => {
const next = enabled.dataset.checked !== "true";
setEnabledUi(next);
// Stamp dragTs so a WS state push older than this click can't revert
// the toggle before the server has acknowledged. updateValues reads
// dragTs[mod.name + ":enabled"] on line ~952 and suppresses stale
// patches within the 1s cooldown.
dragTs[mod.name + ":enabled"] = Date.now();
sendControl(mod.name, "enabled", next);
});
const name = document.createElement("span");
name.className = "card-name";
name.textContent = mod.name;
title.appendChild(name);
// Emoji tags (role + curated) shown after the name — same set used by the
// type picker's chip filter, so visual identity is consistent across views.
const emoji = emojiTagsForMod(mod);
if (emoji) {
const emojiEl = document.createElement("span");
emojiEl.className = "card-name-emoji";
emojiEl.textContent = emoji;
title.appendChild(emojiEl);
}
// Flex spacer so the name stays left and everything else groups on the right.
const spacer = document.createElement("span");
spacer.className = "card-spacer";
title.appendChild(spacer);
// fps/ms toggle on the stats line — global mode, single click cycles all cards
const stats = document.createElement("span");
stats.className = "card-stats";
stats.dataset.mid = mod.name;
stats.dataset.key = "stats";
stats.title = formatStatsTitle(mod);
stats.textContent = formatStats(mod);
stats.addEventListener("click", () => {
const idx = TIMING_MODES.indexOf(timingMode);
timingMode = TIMING_MODES[(idx + 1) % TIMING_MODES.length];
localStorage.setItem(LS_TIMING, timingMode);
// Refresh every card's stats line in place — no full re-render needed
document.querySelectorAll(".card-stats[data-mid]").forEach(s => {
const m = findModule(s.dataset.mid);
if (m) { s.textContent = formatStats(m); s.title = formatStatsTitle(m); }
});
});
title.appendChild(stats);
// Enable checkbox joins the right-hand action cluster, before ✎/×.
title.appendChild(enabled);
// Delete / replace buttons for user-managed children (any role a container
// accepts, minus modules that opted out via userEditable=false). Top-level
// modules are fixed in main.cpp; code-wired children declare userEditable
// false or carry a role no container accepts. See isUserEditableChild.
if (isUserEditableChild(mod, depth)) {
const actions = createActionButtons(mod);
title.appendChild(actions);
}
// Help link → the module's spec page on GitHub, at the far right of the row.
// docPath comes from /api/types (relative to docs/moonmodules/); omitted if none.
const docPath = docPathForType(mod.type);
if (docPath) {
const help = document.createElement("a");
help.className = "card-help";
help.textContent = "?";
help.title = "Open module documentation";
help.target = "_blank";
help.rel = "noopener";
help.href = "https://github.com/MoonModules/projectMM/blob/main/docs/moonmodules/" + docPath;
title.appendChild(help);
}
card.appendChild(title);
// -- Controls --
// Child-hosting modules deeper in the tree (Layers, Layer, Drivers, Layouts)
// collapse their own controls so the children are the focus by default.
// Modules that merely host a code-wired child (Network → Improv) keep their
// controls expanded — the parent's settings are the main point, the code-wired
// child is informational. Leaf modules render controls inline (no wrapper).
// EXCEPTION: a top-level module (depth 0 — the selected root, e.g. System,
// Network) never collapses its own controls, even though it accepts children
// (System hosts peripherals). It's the card the user is looking at, so its
// settings should be visible, not hidden behind a "controls" disclosure.
const hasVisibleControls = mod.controls && mod.controls.some(c => !c.hidden);
const wrapInDetails = depth > 0 && acceptsNewChildren(mod) && hasVisibleControls;
const controlsHost = wrapInDetails ? (() => {
const d = document.createElement("details");
d.className = "card-controls-collapse";
const s = document.createElement("summary");
s.textContent = "controls";
d.appendChild(s);
card.appendChild(d);
return d;
})() : card;
if (mod.status) {
const row = document.createElement("div");
row.className = "control-row";
row.dataset.statusMid = mod.name;
const label = document.createElement("span");
label.className = "control-label";
label.textContent = "status";
const val = document.createElement("span");
val.className = "status-value";
val.dataset.sev = mod.severity || "status";
val.textContent = mod.status;
row.appendChild(label);
row.appendChild(val);
controlsHost.appendChild(row);
}
if (mod.controls) {
for (const ctrl of mod.controls) {
if (ctrl.hidden) continue; // plan-10 hidden flag (still respected)
const row = createControl(mod.name, mod.type, ctrl);
if (row) controlsHost.appendChild(row);
}
}
// FirmwareUpdate card hosts the shared install picker. Mount once per
// card-build. The picker reads SystemModule.firmware (already in
// /api/state) to filter to OTA-compatible releases. On install, the
// device fetches the binary via /api/firmware/url — no browser CORS in
// the data path. See docs/architecture.md § Firmware vs board.
if (mod.type === "FirmwareUpdateModule") {
const ownFirmwareKey = (() => {
// The `firmware` variant key is this module's own control now (moved here from
// SystemModule), so read it straight off mod — no cross-module lookup.
const fwCtrl = (mod.controls || []).find(c => c.name === "firmware");
return fwCtrl && fwCtrl.value ? fwCtrl.value : null;
})();
const mount = document.createElement("div");
mount.className = "install-picker-host";
controlsHost.appendChild(mount);
installPicker.init({
container: mount,
ownFirmwareKey,
// Device already knows its deviceModel (SystemModule) — picker is for
// releases + firmware compatibility only. Showing a board picker
// here would invite the user to mis-narrow the firmware list.
enableBoardPicker: false,
onInstall: async (_firmware, _manifestUrl, binaryUrl) => {
const res = await fetch("/api/firmware/url", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url: binaryUrl }),
});
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try {
const j = await res.json();
if (j.error) msg = j.error;
} catch (_) { /* non-JSON error response */ }
throw new Error(msg);
}
},
});
}
// -- Children block + footer --
// The .card-children wrapper lives inside this card so the parent's border
// encloses its children; renderModuleTree recurses into it. The "+ add module"
// footer only appears on parents that accept user-created children — a parent
// hosting only code-wired children (e.g. Network → Improv) renders the
// children block but no add button.
let childrenEl = null;
if (hasNestedChildren(mod)) {
childrenEl = document.createElement("div");
childrenEl.className = "card-children";
childrenEl.dataset.depth = String(depth + 1);
card.appendChild(childrenEl);
if (acceptsNewChildren(mod)) {
// -- Footer: + add module --
const footer = document.createElement("div");
footer.className = "card-footer";
const addBtn = document.createElement("button");
addBtn.className = "add-btn";
addBtn.textContent = "+ add module";
addBtn.addEventListener("click", () => {
// Hide the button while the picker is open (the picker takes its
// place); restore it once the picker is removed (cancel/create/Esc).
addBtn.style.display = "none";
openTypePicker(mod, footer);
const obs = new MutationObserver(() => {
if (!footer.querySelector(".type-picker")) {
addBtn.style.display = "";
obs.disconnect();
}
});
obs.observe(footer, {childList: true});
});
footer.appendChild(addBtn);
card.appendChild(footer);
}
}
// -- Drag-to-reorder (HTML5 DnD on desktop; touchstart-gated on mobile) --
// Same gate as the delete/replace buttons: a user-managed child is also
// reorderable within its parent.
if (isUserEditableChild(mod, depth)) {
attachDragHandlers(card, mod);
}
return { card, childrenEl };
}
// Wire a button as a press-twice confirm: the first click arms it (adds the
// `armed` class, optional armed label/title), a second click runs `onConfirm`.
// Disarms after 3s or when the pointer leaves. Used by the delete and reboot
// buttons — no browser confirm() popup. `armedText` is optional (delete swaps
// × → ✓; reboot keeps its glyph). The pre-arm title is captured live so a
// title updated elsewhere (e.g. reboot's crashed-state text) restores correctly.
function armPressTwice(btn, onConfirm, opts = {}) {
let armed = false;
let disarmTimer = null;
let savedText = "";
let savedTitle = "";
const disarm = () => {
armed = false;
btn.classList.remove("armed");
if (opts.armedText !== undefined) btn.textContent = savedText;
btn.title = savedTitle;
if (disarmTimer) { clearTimeout(disarmTimer); disarmTimer = null; }
};
btn.addEventListener("click", () => {
// Disarm before running the action so a stray second click can't fire
// it twice (e.g. two /api/reboot requests).
if (armed) { disarm(); onConfirm(); return; }
armed = true;
savedText = btn.textContent;
savedTitle = btn.title;
btn.classList.add("armed");
if (opts.armedText !== undefined) btn.textContent = opts.armedText;
if (opts.armedTitle !== undefined) btn.title = opts.armedTitle;
disarmTimer = setTimeout(disarm, 3000);
});
btn.addEventListener("mouseleave", disarm);
}
// Compact byte formatter — "B" under 1 KB, "KB" otherwise (one decimal under 10 KB).
function fmtBytes(n) {
if (n < 1024) return n + "B";
const k = n / 1024;
return (k < 10 ? k.toFixed(1) : Math.round(k)) + "KB";
}
// Stats line: timing (🕒, fps or µs/ms per the global toggle) + memory
// (🧠 static, plus "+ dynamic" only when the module allocated heap).
// Timing is omitted entirely when the module has no measured loop time.
function formatStats(mod) {
const us = (mod.loopTimeUs !== undefined) ? mod.loopTimeUs : 0;
let timing = "";
if (us > 0) {
if (timingMode === "fps") {
const fps = Math.round(1_000_000 / us);
timing = "🕒 " + (fps >= 1000 ? Math.round(fps / 1000) + "K fps" : fps + " fps");
} else {
timing = "🕒 " + (us < 1000 ? us + " µs" : (us / 1000).toFixed(2) + " ms");
}
}
const stat = mod.classSize || 0;
const dyn = mod.dynamicBytes || 0;
const mem = "🧠 " + fmtBytes(stat) + (dyn > 0 ? " + " + fmtBytes(dyn) : "");
// Status chip: emitted by the engine when a module has something to say.
// Severity picks the emoji — ℹ️ neutral (Eth: 192.168.1.210), ⚠️ degraded
// (buffer reduced), ❌ error (No network). Tooltip carries the full text.
const sev = mod.severity || "status";
const sevEmoji = sev === "error" ? "❌" : sev === "warning" ? "⚠️" : "ℹ️";
const statusChip = mod.status ? " " + sevEmoji : "";
const head = timing ? timing + " " + mem : mem;
return head + statusChip;
}
function formatStatsTitle(mod) {
return "Click to toggle fps/ms";
}
function createActionButtons(mod) {
const wrap = document.createElement("span");
wrap.className = "card-actions";
// Reorder is drag-and-drop only (works on desktop and mobile). The whole
// card body is the drag source; the controls region excludes itself via
// the mousedown gate in attachDragHandlers. No up/down buttons, no
// dedicated drag handle.
const replaceBtn = document.createElement("button");
replaceBtn.className = "card-btn";
replaceBtn.textContent = "✎";
replaceBtn.title = "Replace with another type";
replaceBtn.addEventListener("click", () => {
// Anchor the picker to the card so it drops below the card content,
// not inside the cramped 26px action-button row.
openReplacePicker(mod, replaceBtn.closest(".card"));
});
wrap.appendChild(replaceBtn);
// Delete: press × once to arm, again to confirm — see armPressTwice.
const delBtn = document.createElement("button");
delBtn.className = "card-btn card-btn-del";
delBtn.textContent = "×";
delBtn.title = "Delete";
armPressTwice(delBtn, () => deleteModule(mod.name),
{armedText: "✓", armedTitle: "Click again to delete"});
wrap.appendChild(delBtn);
return wrap;
}
function findParent(childName) {
function walk(node, modules) {
for (const m of modules) {
if (m === node) return null; // shouldn't happen, defensive
if (m.children && m.children.some(c => c.name === childName)) return m;
if (m.children) {
const p = walk(node, m.children);
if (p) return p;
}
}
return null;
}
return walk(null, state.modules);
}
// Whether this module renders any nested children at all (a "+ add module"
// button included if it also accepts new ones via the UI). True whenever the
// module has at least one child today OR is one of the light-pipeline
// containers that users can add to. This lets code-wired children (e.g.
// ImprovProvisioning under Network) render without making the parent UI-addable.
function hasNestedChildren(mod) {
return (mod.children && mod.children.length > 0) || acceptsNewChildren(mod);
}
// Roles this parent accepts as user-added children, from the device's
// `acceptsChildRoles` (per-type in /api/types — e.g. Layer → "effect,modifier").
// Domain-neutral: the UI no longer hardcodes which module types are containers;
// the device declares it via MoonModule::acceptsChildRoles(). "" → [] (accepts
// none), which is also the default for modules whose type isn't loaded yet.
function rolesAcceptedBy(parentMod) {
const t = availableTypes.find(t => t.name === parentMod.type);
const csv = (t && t.acceptsChildRoles) ? t.acceptsChildRoles : "";
return csv ? csv.split(",") : [];
}
// Whether the "+ add module" affordance applies — derived from acceptsChildRoles
// being non-empty, so there's a single source of truth (no separate list).
function acceptsNewChildren(mod) {
return rolesAcceptedBy(mod).length > 0;
}
// The set of child roles ANY loaded type accepts — the union of every type's
// acceptsChildRoles. A module is "user-managed as a child" iff its role is in
// this set, which is how the UI decides to show delete/replace/drag without
// hardcoding role names. Code-wired children (ImprovProvisioning,
// — roles no container declares) correctly fall outside it.
function allAcceptedChildRoles() {
const roles = new Set();
for (const t of availableTypes) {
const csv = t.acceptsChildRoles || "";
if (csv) csv.split(",").forEach(r => roles.add(r));
}
return roles;
}
// Whether the UI shows delete / replace / drag for this module. True when it's
// a nested module (depth > 0) whose role is one some container accepts AND it
// hasn't opted out via the device's userEditable=false (e.g. PreviewDriver).
// Replaces the old hardcoded `role === "effect" || "modifier"` gate — now any
// add-accepted role (driver, layout, …) is editable, and the child itself can
// veto via userEditable.
//
// We test mod.role against the UNION of all containers' acceptsChildRoles, not
// against this module's specific parent. That's exact while the role→container
// mapping is 1:1 (effect→Layer, driver→Drivers, layout→Layouts, layer→Layers) —
// a child of an add-accepted role is always under the one container that
// accepts it. If a role ever becomes accepted by more than one container, this
// would need the parent threaded in to scope the check to the actual parent.
function isUserEditableChild(mod, depth) {
return depth > 0
&& mod.userEditable !== false
&& allAcceptedChildRoles().has(mod.role);
}
// ---------------------------------------------------------------------------
// Control rendering (9 types per ui.md)
// ---------------------------------------------------------------------------
// Look up the factory default for a given module type's control. Returns undefined when
// the type isn't in /api/types yet or the control has no default (display/progress).
function defaultFor(moduleType, ctrlName) {
if (!moduleType) return undefined;
const t = availableTypes.find(t => t.name === moduleType);
if (!t || !t.defaults) return undefined;
return t.defaults[ctrlName];
}
// The module type's spec-page path (relative to docs/moonmodules/), from /api/types.
// Returns "" when the type isn't loaded yet or declares no doc path.
function docPathForType(moduleType) {
if (!moduleType) return "";
const t = availableTypes.find(t => t.name === moduleType);
return (t && t.docPath) ? t.docPath : "";
}
// Curated emoji string for a live module — its role emoji plus the type's
// `tags` from /api/types, deduplicated, in role-first order. "" if the type
// isn't loaded yet. Used on the card title and in the type picker.
function emojiTagsForMod(mod) {
if (!mod) return "";
const t = availableTypes.find(t => t.name === mod.type) || {role: mod.role, tags: ""};
return emojiTagsFor(t).join("");
}
function createControl(moduleName, moduleType, ctrl) {
const row = document.createElement("div");
row.className = "control-row";
row.dataset.key = ctrl.name;
const label = document.createElement("label");
label.className = "control-label";
label.textContent = ctrl.name;
row.appendChild(label);
const key = moduleName + ":" + ctrl.name;
const def = defaultFor(moduleType, ctrl.name);
switch (ctrl.type) {
case "uint8": {
const input = document.createElement("input");
input.type = "range";
input.min = ctrl.min ?? 0;
input.max = ctrl.max ?? 255;
input.value = ctrl.value ?? 0;
input.dataset.mid = moduleName;
input.dataset.key = ctrl.name;
const numInput = document.createElement("input");
numInput.type = "number";
numInput.className = "control-value-input";
numInput.min = input.min;
numInput.max = input.max;
numInput.value = input.value;
input.addEventListener("input", () => {
dragTs[key] = Date.now();
numInput.value = input.value;
debounceSend(key, 150, () => sendControl(moduleName, ctrl.name, parseInt(input.value)));
});
numInput.addEventListener("input", () => {
dragTs[key] = Date.now(); // stamp so a WS push can't revert what's being typed
const v = Math.max(Number(input.min), Math.min(Number(input.max), parseInt(numInput.value) || 0));
input.value = v;
debounceSend(key, 500, () => sendControl(moduleName, ctrl.name, v));
});
row.appendChild(input);
row.appendChild(numInput);
appendResetButton(row, moduleName, ctrl, def, () => {
input.value = def;
numInput.value = def;
});
break;
}
case "uint16": {
// Bounded (server sent an explicit max below the type ceiling) →
// slider, like uint8/int16. Unbounded (max == 65535, the default for
// port/universe-style values with no natural range) → plain number.
const uMin = Number(ctrl.min ?? 0);
const uMax = Number(ctrl.max ?? 65535);
if (uMax < 65535) {
const input = document.createElement("input");
input.type = "range";
input.min = uMin;
input.max = uMax;
input.value = Math.max(uMin, Math.min(uMax, Number(ctrl.value ?? 0)));
input.dataset.mid = moduleName;
input.dataset.key = ctrl.name;
const numInput = document.createElement("input");
numInput.type = "number";
numInput.className = "control-value-input";
numInput.min = uMin;
numInput.max = uMax;
numInput.value = input.value;
input.addEventListener("input", () => {
dragTs[key] = Date.now();
numInput.value = input.value;
debounceSend(key, 150, () => sendControl(moduleName, ctrl.name, parseInt(input.value)));
});
numInput.addEventListener("input", () => {
dragTs[key] = Date.now(); // stamp so a WS push can't revert what's being typed
const v = Math.max(uMin, Math.min(uMax, parseInt(numInput.value) || 0));
input.value = v;
debounceSend(key, 150, () => sendControl(moduleName, ctrl.name, v));
});
row.appendChild(input);
row.appendChild(numInput);
appendResetButton(row, moduleName, ctrl, def, () => {
input.value = def; numInput.value = def;
});
} else {
const input = document.createElement("input");
input.type = "number";
input.value = ctrl.value ?? 0;
input.dataset.mid = moduleName;
input.dataset.key = ctrl.name;
input.addEventListener("input", () => {
dragTs[key] = Date.now();
// Sanitise: empty/garbage → 0, clamp into the uint16 range so a
// NaN or out-of-range value never reaches the device.
let v = parseInt(input.value, 10);
if (Number.isNaN(v)) v = 0;
v = Math.max(0, Math.min(65535, v));
debounceSend(key, 500, () => sendControl(moduleName, ctrl.name, v));
});
row.appendChild(input);
appendResetButton(row, moduleName, ctrl, def, () => { input.value = def; });
}
break;
}
case "pin": {
// A GPIO pin: plain number input, never a slider (a pin has no range to
// drag). −1 = unused. ctrl.min/max are the valid-GPIO span used only to
// clamp the typed value before sending.
const pMin = Number(ctrl.min ?? -1);
const pMax = Number(ctrl.max ?? 52);
const input = document.createElement("input");
input.type = "number";
input.min = pMin;
input.max = pMax;
input.value = ctrl.value ?? -1;
input.dataset.mid = moduleName;
input.dataset.key = ctrl.name;
input.addEventListener("input", () => {
dragTs[key] = Date.now();
let v = parseInt(input.value, 10);
if (Number.isNaN(v)) v = -1;
v = Math.max(pMin, Math.min(pMax, v));
debounceSend(key, 500, () => sendControl(moduleName, ctrl.name, v));
});
row.appendChild(input);
appendResetButton(row, moduleName, ctrl, def, () => { input.value = def; });
break;
}
case "int16": {
// ctrl.min/ctrl.max are always present (server sends them). Sentinel
// values INT16_MIN (-32768) / INT16_MAX (32767) mean "unbounded" —
// fall back to the percentage range used by Layer start/end controls.
const rawMin = Number(ctrl.min ?? -32768);
const rawMax = Number(ctrl.max ?? 32767);
const min = rawMin <= -32768 ? -100 : rawMin;
const max = rawMax >= 32767 ? 200 : rawMax;
const raw = Number(ctrl.value ?? 0);
const clamped = Math.max(min, Math.min(max, raw));
const input = document.createElement("input");
input.type = "range";
input.min = min;
input.max = max;
input.value = clamped;
input.dataset.mid = moduleName;