-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathapp.js
More file actions
4812 lines (4305 loc) · 156 KB
/
app.js
File metadata and controls
4812 lines (4305 loc) · 156 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
let elements = [];
let screens = [];
let activeScreenId = null;
let selectedId = null;
let dispWidth = 240;
let dispHeight = 320;
let bgColor = "#000000";
let useSprite = false;
let zoomFactor = 0.75;
let snapToGrid = false;
let gridSize = 4;
let driverMode = "tft";
// Display settings state
let tftSettingsState = {
rotation: 0,
colorDepth: 16,
backlight: "none",
touch: "none"
};
let oledSettingsState = {
rotation: 0,
contrast: 127,
flipMode: "none",
fontMode: "transparent",
powerSave: "off"
};
let u8g2PresetId = "ssd1306_128x64_i2c_f";
const DEFAULT_U8G2_FONT = "u8g2_font_6x10_tf";
const DEFAULT_TFT_FONT = "1";
function getCurrentDriverMode() {
return String((displayDriverSelect && displayDriverSelect.value) || driverMode || "tft");
}
let history = [];
let historyIndex = -1;
let historyLocked = false;
const preview = document.getElementById("preview");
const displayInfo = document.getElementById("displayInfo");
const dispWidthInput = document.getElementById("dispWidth");
const dispHeightInput = document.getElementById("dispHeight");
const applyResBtn = document.getElementById("applyRes");
const bgColorInput = document.getElementById("bgColor");
const clearAllBtn = document.getElementById("clearAll");
const useSpriteCheckbox = document.getElementById("useSpriteCheckbox");
const snapCheckbox = document.getElementById("snapCheckbox");
const gridSizeInput = document.getElementById("gridSize");
const displayDriverSelect = document.getElementById("displayDriver");
const tftSettings = document.getElementById("tftSettings");
const oledSettings = document.getElementById("oledSettings");
// TFT settings elements
const tftRotation = document.getElementById("tftRotation");
const tftColorDepth = document.getElementById("tftColorDepth");
const tftBacklight = document.getElementById("tftBacklight");
const tftTouch = document.getElementById("tftTouch");
// OLED settings elements
const oledRotation = document.getElementById("oledRotation");
const oledContrast = document.getElementById("oledContrast");
const oledContrastValue = document.getElementById("oledContrastValue");
const oledFlipMode = document.getElementById("oledFlipMode");
const oledFontMode = document.getElementById("oledFontMode");
const oledPowerSave = document.getElementById("oledPowerSave");
const u8g2PresetSelect = document.getElementById("u8g2Preset");
const addButtons = document.querySelectorAll("[data-add]");
const addImageBtn = document.getElementById("addImageBtn");
const imageInput = document.getElementById("imageInput");
const imgCanvas = document.createElement("canvas");
const imgCtx = imgCanvas.getContext("2d");
const screenSelect = document.getElementById("screenSelect");
const addScreenBtn = document.getElementById("addScreenBtn");
const deleteScreenBtn = document.getElementById("deleteScreenBtn");
const screenFnNameInput = document.getElementById("screenFnName");
const noSelection = document.getElementById("noSelection");
const propsPanel = document.getElementById("propsPanel");
const elementTypePill = document.getElementById("elementTypePill");
const propX = document.getElementById("propX");
const propY = document.getElementById("propY");
const propW = document.getElementById("propW");
const propH = document.getElementById("propH");
const propText = document.getElementById("propText");
const propTextSize = document.getElementById("propTextSize");
const propValue = document.getElementById("propValue");
const propFillColor = document.getElementById("propFillColor");
const propStrokeColor = document.getElementById("propStrokeColor");
const propTextColor = document.getElementById("propTextColor");
const deleteElementBtn = document.getElementById("deleteElement");
const valueGroup = document.getElementById("valueGroup");
const textGroup = document.getElementById("textGroup");
const fontGroup = document.getElementById("fontGroup");
const propFont = document.getElementById("propFont");
const propFontLabel = document.getElementById("propFontLabel");
const actionGroup = document.getElementById("actionGroup");
const propAction = document.getElementById("propAction");
const propActionTarget = document.getElementById("propActionTarget");
const iconTintGroup = document.getElementById("iconTintGroup");
const propIconTintEnabled = document.getElementById("propIconTintEnabled");
const propIconTintColor = document.getElementById("propIconTintColor");
const alignLeftBtn = document.getElementById("alignLeftBtn");
const alignHCenterBtn = document.getElementById("alignHCenterBtn");
const alignRightBtn = document.getElementById("alignRightBtn");
const alignTopBtn = document.getElementById("alignTopBtn");
const alignVCenterBtn = document.getElementById("alignVCenterBtn");
const alignBottomBtn = document.getElementById("alignBottomBtn");
const codeOutput = document.getElementById("codeOutput");
const copyCodeBtn = document.getElementById("copyCode");
const themeToggle = document.getElementById("themeToggle");
const themeIcon = document.getElementById("themeIcon");
const undoBtn = document.getElementById("undoBtn");
const redoBtn = document.getElementById("redoBtn");
const duplicateBtn = document.getElementById("duplicateBtn");
const zoomSlider = document.getElementById("zoomSlider");
const exportJsonBtn = document.getElementById("exportJsonBtn");
const importJsonBtn = document.getElementById("importJsonBtn");
const importJsonInput = document.getElementById("importJsonInput");
const bgColorChips = document.querySelectorAll("[data-bg-color]");
const bgColorCustomBtn = document.getElementById("bgColorCustom");
// Sidebar extras: UI examples + icon list
const uiExamplesList = document.getElementById("uiExamplesList");
const uiExamplesTabTft = document.getElementById("uiExamplesTabTft");
const uiExamplesTabOled = document.getElementById("uiExamplesTabOled");
const uiExamplesPrevBtn = document.getElementById("uiExamplesPrevBtn");
const uiExamplesNextBtn = document.getElementById("uiExamplesNextBtn");
const uiExamplesPagePill = document.getElementById("uiExamplesPagePill");
const iconSearchInput = document.getElementById("iconSearch");
const clearIconSearchBtn = document.getElementById("clearIconSearch");
const iconGrid = document.getElementById("iconGrid");
const iconHint = document.getElementById("iconHint");
const exportIconsTftBtn = document.getElementById("exportIconsTftBtn");
const exportIconsU8g2Btn = document.getElementById("exportIconsU8g2Btn");
const iconSizeFilterSelect = document.getElementById("iconSizeFilter");
const iconCountPill = document.getElementById("iconCountPill");
const refreshIconsBtn = document.getElementById("refreshIconsBtn");
const iconPrevBtn = document.getElementById("iconPrevBtn");
const iconNextBtn = document.getElementById("iconNextBtn");
const iconPagePill = document.getElementById("iconPagePill");
// Embedded tools overlay (PixelForge / BitCanvas Studio)
const toolOverlay = document.getElementById("toolOverlay");
const toolOverlayPill = document.getElementById("toolOverlayPill");
const toolOverlayName = document.getElementById("toolOverlayName");
const toolOverlayClose = document.getElementById("toolOverlayClose");
const toolOverlayAction = document.getElementById("toolOverlayAction");
const toolOverlayOpenNewTab = document.getElementById("toolOverlayOpenNewTab");
const toolFramePixelForge = document.getElementById("toolFrame_pixelforge");
const toolFrameBitCanvas = document.getElementById("toolFrame_bitcanvas");
const toolSwitchButtons = document.querySelectorAll("[data-switch-tool]");
const EMBEDDED_TOOLS = {
pixelforge: {
label: "PixelForge (Image Converter)",
href: "tools/pixelforge/index.html"
},
bitcanvas: {
label: "BitCanvas Studio (Animation)",
href: "tools/bitcanvas-studio/index.html"
}
};
let activeEmbeddedToolKey = null;
let pendingToolAction = null; // "importImage" | "copyExport" | null
const loadedToolFrames = new Set(); // toolKey strings
// Right sidebar (settings + selected element)
const propertiesSidebar = document.querySelector(".properties");
const settingsScreensTitle = document.getElementById("settingsScreensTitle");
const selectedElementTitle = document.getElementById("selectedElementTitle");
function scrollPropertiesTo(targetEl) {
if (!propertiesSidebar || !targetEl) return;
const pr = propertiesSidebar.getBoundingClientRect();
const tr = targetEl.getBoundingClientRect();
const top = (tr.top - pr.top) + propertiesSidebar.scrollTop;
// Put the target right at the top (with a small padding)
propertiesSidebar.scrollTo({ top: Math.max(0, top - 8), behavior: "smooth" });
}
function scrollToScreensSettings() {
scrollPropertiesTo(settingsScreensTitle);
}
function scrollToSelectedElementSettings() {
scrollPropertiesTo(selectedElementTitle);
}
function getToolFrameEl(toolKey) {
if (toolKey === "pixelforge") return toolFramePixelForge;
if (toolKey === "bitcanvas") return toolFrameBitCanvas;
return null;
}
function hideAllToolFrames() {
[toolFramePixelForge, toolFrameBitCanvas].forEach((f) => {
if (f) f.classList.add("hidden");
});
}
function setActiveToolSwitchUI(toolKey) {
toolSwitchButtons.forEach((btn) => {
const key = btn.getAttribute("data-switch-tool");
const active = key === toolKey;
btn.classList.toggle("active", active);
btn.setAttribute("aria-selected", active ? "true" : "false");
});
}
function refreshEmbeddedToolHrefs() {
// Make right-click "Open in new tab" (and the overlay button) open the *embedded* themed variant.
document.querySelectorAll("[data-open-tool]").forEach((el) => {
const key = el.getAttribute("data-open-tool");
const tool = EMBEDDED_TOOLS[key];
if (!tool) return;
el.setAttribute("href", buildEmbeddedToolUrl(tool.href));
});
if (toolOverlayOpenNewTab && activeEmbeddedToolKey && EMBEDDED_TOOLS[activeEmbeddedToolKey]) {
toolOverlayOpenNewTab.href = buildEmbeddedToolUrl(EMBEDDED_TOOLS[activeEmbeddedToolKey].href);
}
}
function getCurrentDisplayKitTheme() {
return document.documentElement.getAttribute("data-theme")
|| localStorage.getItem("theme")
|| "dark";
}
function buildEmbeddedToolUrl(baseHref) {
const theme = getCurrentDisplayKitTheme();
try {
const u = new URL(baseHref, window.location.href);
u.searchParams.set("embed", "1");
u.searchParams.set("theme", theme);
return u.toString();
} catch {
// Fallback for edge cases: still try to pass params
const join = baseHref.includes("?") ? "&" : "?";
return `${baseHref}${join}embed=1&theme=${encodeURIComponent(theme)}`;
}
}
function syncEmbeddedToolTheme(theme) {
if (!toolOverlay) return;
// Sync to any loaded frames; this keeps them consistent even while hidden.
const frames = [toolFramePixelForge, toolFrameBitCanvas].filter(Boolean);
frames.forEach((frame) => {
try {
frame.contentWindow?.postMessage({ type: "displaykitTheme", theme }, "*");
} catch {
// ignore
}
});
}
function requestToolExport(toolKey) {
const frame = getToolFrameEl(toolKey);
if (!frame?.contentWindow) return;
try {
frame.contentWindow.postMessage({ type: "requestExport", tool: toolKey }, "*");
} catch {
// ignore
}
}
function setToolOverlayAction(toolKey) {
activeEmbeddedToolKey = toolKey;
pendingToolAction = null;
if (!toolOverlayAction) return;
if (toolKey === "pixelforge") {
toolOverlayAction.style.display = "inline-flex";
toolOverlayAction.textContent = "Import image to DisplayKit";
pendingToolAction = "importImage";
} else if (toolKey === "bitcanvas") {
toolOverlayAction.style.display = "inline-flex";
toolOverlayAction.textContent = "Copy export to clipboard";
pendingToolAction = "copyExport";
} else {
toolOverlayAction.style.display = "none";
toolOverlayAction.textContent = "Action";
}
}
function parsePixelForgeHeaderToRgb565(text) {
if (!text || typeof text !== "string") {
throw new Error("No export text received from PixelForge. Click Convert first.");
}
const widthMatch = text.match(/const\s+uint16_t\s+([A-Za-z0-9_]+)_width\s*=\s*(\d+)\s*;/);
const heightMatch = text.match(/const\s+uint16_t\s+([A-Za-z0-9_]+)_height\s*=\s*(\d+)\s*;/);
if (!widthMatch || !heightMatch) {
throw new Error("Couldn't find width/height in PixelForge export.");
}
const baseName = widthMatch[1];
const w = parseInt(widthMatch[2], 10);
const h = parseInt(heightMatch[2], 10);
if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) {
throw new Error("Invalid width/height in PixelForge export.");
}
// Prefer the base symbol if present; otherwise take the first uint16_t PROGMEM array.
const preferredRe = new RegExp(
`const\\s+uint16_t\\s+(${baseName}(?:_\\d+)?)\\s*\\[\\]\\s*PROGMEM\\s*=\\s*\\{([\\s\\S]*?)\\};`
);
let arrayMatch = text.match(preferredRe);
if (!arrayMatch) {
arrayMatch = text.match(/const\s+uint16_t\s+([A-Za-z0-9_]+)\s*\[\]\s*PROGMEM\s*=\s*\{([\s\S]*?)\};/);
}
if (!arrayMatch) {
throw new Error("Couldn't find a uint16_t RGB565 array in PixelForge export (TFT mode only).");
}
const symbol = arrayMatch[1];
const body = arrayMatch[2];
const hexes = body.match(/0x[0-9A-Fa-f]{1,4}/g) || [];
if (!hexes.length) {
throw new Error("No pixel data found in PixelForge export.");
}
const rgb565 = hexes.map((hx) => parseInt(hx, 16) & 0xffff);
return { symbol, baseName, w, h, rgb565 };
}
function rgb565ToDataUrl(w, h, rgb565) {
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext("2d");
const img = ctx.createImageData(w, h);
const d = img.data;
const total = Math.min(rgb565.length, w * h);
for (let p = 0; p < total; p++) {
const v = rgb565[p] & 0xffff;
const r5 = (v >> 11) & 0x1f;
const g6 = (v >> 5) & 0x3f;
const b5 = v & 0x1f;
const r = (r5 << 3) | (r5 >> 2);
const g = (g6 << 2) | (g6 >> 4);
const b = (b5 << 3) | (b5 >> 2);
const i = p * 4;
d[i] = r;
d[i + 1] = g;
d[i + 2] = b;
d[i + 3] = 255;
}
ctx.putImageData(img, 0, 0);
return canvas.toDataURL("image/png");
}
function importRgb565ImageToDisplayKit({ symbol, w, h, rgb565 }) {
if (!Array.isArray(rgb565) || !rgb565.length) {
throw new Error("No RGB565 data to import.");
}
const id = makeId();
const x = Math.max(0, Math.round((dispWidth - w) / 2));
const y = Math.max(0, Math.round((dispHeight - h) / 2));
const previewUrl = rgb565ToDataUrl(w, h, rgb565);
const el = {
id,
type: "image",
x,
y,
w,
h,
text: "",
textSize: 2,
fillColor: "#ffffff",
strokeColor: "#ffffff",
textColor: "#000000",
value: 0,
imageName: symbol || ("img_" + id.replace(/[^a-zA-Z0-9_]/g, "_")),
imageWidth: w,
imageHeight: h,
rgb565,
previewUrl,
font: getCurrentDriverMode() === "tft" ? DEFAULT_TFT_FONT : DEFAULT_U8G2_FONT
};
elements.push(el);
syncActiveScreenElements();
selectedId = id;
updatePreviewSize();
renderElements();
updatePropsInputs();
updateCode();
pushHistory();
}
function openEmbeddedTool(toolKey) {
if (!toolOverlay) return;
const tool = EMBEDDED_TOOLS[toolKey];
if (!tool) return;
const embeddedUrl = buildEmbeddedToolUrl(tool.href);
const frame = getToolFrameEl(toolKey);
if (!frame) return;
// Update header UI
if (toolOverlayPill) toolOverlayPill.textContent = "Tools";
if (toolOverlayOpenNewTab) toolOverlayOpenNewTab.href = embeddedUrl;
frame.title = tool.label;
// Keep tool state by loading each tool once and then only toggling visibility
if (!loadedToolFrames.has(toolKey)) {
frame.setAttribute("src", embeddedUrl);
loadedToolFrames.add(toolKey);
}
toolOverlay.classList.add("open");
toolOverlay.setAttribute("aria-hidden", "false");
document.documentElement.classList.add("tool-open");
setToolOverlayAction(toolKey);
setActiveToolSwitchUI(toolKey);
hideAllToolFrames();
frame.classList.remove("hidden");
// Ensure theme is synced even if the tool doesn't read query params
syncEmbeddedToolTheme(getCurrentDisplayKitTheme());
}
function closeEmbeddedTool() {
if (!toolOverlay) return;
toolOverlay.classList.remove("open");
toolOverlay.setAttribute("aria-hidden", "true");
document.documentElement.classList.remove("tool-open");
setToolOverlayAction(null);
setActiveToolSwitchUI(null);
}
// Intercept tool links and open inside the app overlay
document.querySelectorAll("[data-open-tool]").forEach((el) => {
el.addEventListener("click", (e) => {
e.preventDefault();
const key = el.getAttribute("data-open-tool");
openEmbeddedTool(key);
});
});
// Tool switcher tabs inside overlay
toolSwitchButtons.forEach((btn) => {
btn.addEventListener("click", () => {
const key = btn.getAttribute("data-switch-tool");
openEmbeddedTool(key);
});
});
// Ensure the default hrefs also point at the embedded/themed URLs
refreshEmbeddedToolHrefs();
if (toolOverlayClose) {
toolOverlayClose.addEventListener("click", closeEmbeddedTool);
}
if (toolOverlayAction) {
toolOverlayAction.addEventListener("click", () => {
if (!activeEmbeddedToolKey || !pendingToolAction) return;
requestToolExport(activeEmbeddedToolKey);
});
}
// Click outside the inner panel closes the overlay
if (toolOverlay) {
toolOverlay.addEventListener("mousedown", (e) => {
if (e.target === toolOverlay) {
closeEmbeddedTool();
}
});
}
if (toolFramePixelForge) {
toolFramePixelForge.addEventListener("load", () => {
syncEmbeddedToolTheme(getCurrentDisplayKitTheme());
});
}
if (toolFrameBitCanvas) {
toolFrameBitCanvas.addEventListener("load", () => {
syncEmbeddedToolTheme(getCurrentDisplayKitTheme());
});
}
// Receive exports from embedded tools
window.addEventListener("message", async (event) => {
const data = event && event.data;
if (!data || data.type !== "toolExport") return;
const tool = data.tool;
try {
if (tool === "pixelforge") {
const parsed = parsePixelForgeHeaderToRgb565(data.text || "");
importRgb565ImageToDisplayKit(parsed);
alert("Imported image into current screen.");
} else if (tool === "bitcanvas") {
const text = data.text || "";
if (!text.trim()) throw new Error("No export text found. Click an Export button in BitCanvas first.");
await navigator.clipboard.writeText(text);
alert("Copied BitCanvas export to clipboard.");
}
} catch (err) {
alert(err && err.message ? err.message : "Tool export failed.");
}
});
// ESC closes the overlay
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && toolOverlay && toolOverlay.classList.contains("open")) {
closeEmbeddedTool();
}
});
function getTheme() {
const saved = localStorage.getItem("theme");
if (saved) return saved;
return "dark";
}
function setTheme(theme) {
document.documentElement.setAttribute("data-theme", theme);
localStorage.setItem("theme", theme);
if (themeIcon) {
themeIcon.textContent = theme === "dark" ? "☀️" : "🌙";
}
syncEmbeddedToolTheme(theme);
refreshEmbeddedToolHrefs();
}
function toggleTheme() {
const currentTheme = getTheme();
const newTheme = currentTheme === "dark" ? "light" : "dark";
setTheme(newTheme);
}
const savedTheme = getTheme();
setTheme(savedTheme);
if (themeToggle) {
themeToggle.addEventListener("click", toggleTheme);
}
if (window.matchMedia) {
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => {
if (!localStorage.getItem("theme")) {
setTheme(e.matches ? "dark" : "light");
}
});
}
const U8G2_PRESETS = [
{
id: "ssd1306_128x64_i2c_f",
label: "SSD1306 128x64 I2C (F_HW_I2C)",
ctor: "U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, U8X8_PIN_NONE);"
},
{
id: "ssd1306_128x64_spi_f",
label: "SSD1306 128x64 SPI (F_4W_HW_SPI)",
ctor: "U8G2_SSD1306_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, 10, 9, 8);"
},
{
id: "sh1106_128x64_i2c_f",
label: "SH1106 128x64 I2C (F_HW_I2C)",
ctor: "U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, U8X8_PIN_NONE);"
},
{
id: "custom",
label: "Custom (edit manually in code)",
ctor: ""
}
];
const U8G2_FONTS = [
// Small / fixed-width fonts
"u8g2_font_4x6_tf",
"u8g2_font_5x7_tf",
"u8g2_font_5x8_tf",
"u8g2_font_6x10_tf",
"u8g2_font_6x12_tf",
"u8g2_font_6x13_tf",
"u8g2_font_7x13_tf",
"u8g2_font_7x14_tf",
"u8g2_font_8x13_tf",
"u8g2_font_8x13B_tf",
"u8g2_font_9x15B_tf",
"u8g2_font_9x18B_tf",
"u8g2_font_10x20_tf",
"u8g2_font_12x20_tf",
// Helvetica (Sans-serif) fonts
"u8g2_font_helvR08_tf",
"u8g2_font_helvR10_tf",
"u8g2_font_helvR12_tf",
"u8g2_font_helvR14_tf",
"u8g2_font_helvR18_tf",
"u8g2_font_helvR24_tf",
"u8g2_font_helvB08_tf",
"u8g2_font_helvB10_tf",
"u8g2_font_helvB12_tf",
"u8g2_font_helvB14_tf",
"u8g2_font_helvB18_tf",
"u8g2_font_helvB24_tf",
// Proportional fonts
"u8g2_font_profont10_mf",
"u8g2_font_profont12_mf",
"u8g2_font_profont15_mf",
"u8g2_font_profont17_mf",
"u8g2_font_profont22_mf",
"u8g2_font_profont29_mf",
"u8g2_font_t0_11b_mf",
"u8g2_font_t0_12b_mf",
"u8g2_font_t0_14b_mf",
"u8g2_font_t0_15b_mf",
"u8g2_font_t0_17b_mf",
"u8g2_font_t0_18b_mf",
"u8g2_font_t0_22b_mf",
// New Century Schoolbook (Serif)
"u8g2_font_ncenB08_tr",
"u8g2_font_ncenB10_tr",
"u8g2_font_ncenB12_tr",
"u8g2_font_ncenB14_tr",
"u8g2_font_ncenB18_tr",
"u8g2_font_ncenB24_tr",
"u8g2_font_ncenR08_tr",
"u8g2_font_ncenR10_tr",
"u8g2_font_ncenR12_tr",
"u8g2_font_ncenR14_tr",
"u8g2_font_ncenR18_tr",
"u8g2_font_ncenR24_tr",
// Times (Serif)
"u8g2_font_timR08_tr",
"u8g2_font_timR10_tr",
"u8g2_font_timR12_tr",
"u8g2_font_timR14_tr",
"u8g2_font_timR18_tr",
"u8g2_font_timR24_tr",
"u8g2_font_timB08_tr",
"u8g2_font_timB10_tr",
"u8g2_font_timB12_tr",
"u8g2_font_timB14_tr",
"u8g2_font_timB18_tr",
"u8g2_font_timB24_tr",
// Courier (Monospace)
"u8g2_font_courR08_tf",
"u8g2_font_courR10_tf",
"u8g2_font_courR12_tf",
"u8g2_font_courR14_tf",
"u8g2_font_courR18_tf",
"u8g2_font_courR24_tf",
"u8g2_font_courB08_tf",
"u8g2_font_courB10_tf",
"u8g2_font_courB12_tf",
"u8g2_font_courB14_tf",
"u8g2_font_courB18_tf",
"u8g2_font_courB24_tf",
// Logisoso fonts
"u8g2_font_logisoso16_tf",
"u8g2_font_logisoso18_tf",
"u8g2_font_logisoso20_tf",
"u8g2_font_logisoso22_tf",
"u8g2_font_logisoso24_tf",
"u8g2_font_logisoso26_tf",
"u8g2_font_logisoso28_tf",
"u8g2_font_logisoso30_tf",
"u8g2_font_logisoso32_tf",
"u8g2_font_logisoso34_tf",
"u8g2_font_logisoso38_tf",
"u8g2_font_logisoso42_tf",
"u8g2_font_logisoso46_tf",
"u8g2_font_logisoso50_tf",
"u8g2_font_logisoso54_tf",
"u8g2_font_logisoso58_tf",
"u8g2_font_logisoso62_tf",
// Special purpose fonts
"u8g2_font_8x8_mf",
"u8g2_font_inr16_mf",
"u8g2_font_inb16_mf",
"u8g2_font_inr19_mf",
"u8g2_font_inb19_mf",
"u8g2_font_inr21_mf",
"u8g2_font_inb21_mf",
"u8g2_font_inr24_mf",
"u8g2_font_inb24_mf",
"u8g2_font_inr27_mf",
"u8g2_font_inb27_mf",
"u8g2_font_inr30_mf",
"u8g2_font_inb30_mf",
"u8g2_font_inr33_mf",
"u8g2_font_inb33_mf",
"u8g2_font_inr38_mf",
"u8g2_font_inb38_mf",
"u8g2_font_inr42_mf",
"u8g2_font_inb42_mf",
"u8g2_font_inr46_mf",
"u8g2_font_inb46_mf",
"u8g2_font_inr49_mf",
"u8g2_font_inb49_mf",
"u8g2_font_inr53_mf",
"u8g2_font_inb53_mf",
// Symbols and special characters
"u8g2_font_unifont_t_symbols",
"u8g2_font_open_iconic_all_1x",
"u8g2_font_open_iconic_all_2x",
"u8g2_font_open_iconic_all_4x",
"u8g2_font_open_iconic_all_6x",
"u8g2_font_open_iconic_all_8x",
"u8g2_font_emoticons21_tr",
"u8g2_font_battery19_tn",
"u8g2_font_siji_t_6x10",
// Additional fonts
"u8g2_font_lubR08_tf",
"u8g2_font_lubR10_tf",
"u8g2_font_lubR12_tf",
"u8g2_font_lubR14_tf",
"u8g2_font_lubR18_tf",
"u8g2_font_lubR19_tf",
"u8g2_font_lubR24_tf",
"u8g2_font_lubB08_tf",
"u8g2_font_lubB10_tf",
"u8g2_font_lubB12_tf",
"u8g2_font_lubB14_tf",
"u8g2_font_lubB18_tf",
"u8g2_font_lubB19_tf",
"u8g2_font_lubB24_tf",
// Micro fonts
"u8g2_font_micro_mf",
"u8g2_font_micro_tr",
"u8g2_font_chroma48medium8_8r",
"u8g2_font_saikyosansbold8_8n",
"u8g2_font_torussansbold8_8r"
];
// TFT_eSPI built-in fonts (for setTextFont). Keep these driver-specific.
const TFT_ESPI_FONTS = [
// Built-in (setTextFont)
{ value: "1", label: "Built-in 1 (default)" },
{ value: "2", label: "Built-in 2" },
{ value: "3", label: "Built-in 3" },
{ value: "4", label: "Built-in 4" },
{ value: "5", label: "Built-in 5" },
{ value: "6", label: "Built-in 6" },
{ value: "7", label: "Built-in 7" },
{ value: "8", label: "Built-in 8" },
// FreeFonts (GFXFF) — requires TFT_eSPI configured with LOAD_GFXFF enabled.
// Value is the font symbol name (used as &<name> in generated code).
{ value: "FreeMono9pt7b", label: "FreeMono 9pt" },
{ value: "FreeMono12pt7b", label: "FreeMono 12pt" },
{ value: "FreeMono18pt7b", label: "FreeMono 18pt" },
{ value: "FreeMono24pt7b", label: "FreeMono 24pt" },
{ value: "FreeMonoBold9pt7b", label: "FreeMono Bold 9pt" },
{ value: "FreeMonoBold12pt7b", label: "FreeMono Bold 12pt" },
{ value: "FreeMonoBold18pt7b", label: "FreeMono Bold 18pt" },
{ value: "FreeMonoBold24pt7b", label: "FreeMono Bold 24pt" },
{ value: "FreeSans9pt7b", label: "FreeSans 9pt" },
{ value: "FreeSans12pt7b", label: "FreeSans 12pt" },
{ value: "FreeSans18pt7b", label: "FreeSans 18pt" },
{ value: "FreeSans24pt7b", label: "FreeSans 24pt" },
{ value: "FreeSansBold9pt7b", label: "FreeSans Bold 9pt" },
{ value: "FreeSansBold12pt7b", label: "FreeSans Bold 12pt" },
{ value: "FreeSansBold18pt7b", label: "FreeSans Bold 18pt" },
{ value: "FreeSansBold24pt7b", label: "FreeSans Bold 24pt" },
{ value: "FreeSerif9pt7b", label: "FreeSerif 9pt" },
{ value: "FreeSerif12pt7b", label: "FreeSerif 12pt" },
{ value: "FreeSerif18pt7b", label: "FreeSerif 18pt" },
{ value: "FreeSerif24pt7b", label: "FreeSerif 24pt" },
{ value: "FreeSerifBold9pt7b", label: "FreeSerif Bold 9pt" },
{ value: "FreeSerifBold12pt7b", label: "FreeSerif Bold 12pt" },
{ value: "FreeSerifBold18pt7b", label: "FreeSerif Bold 18pt" },
{ value: "FreeSerifBold24pt7b", label: "FreeSerif Bold 24pt" }
];
const TFT_FONT_VALUES = new Set(TFT_ESPI_FONTS.map((f) => f.value));
const U8G2_FONT_VALUES = new Set(U8G2_FONTS);
function sanitizeTftFontId(value) {
const v = String(value || "").trim();
return TFT_FONT_VALUES.has(v) ? v : DEFAULT_TFT_FONT;
}
function sanitizeU8g2FontName(value) {
const v = String(value || "").trim();
// Keep it strict so we don't generate invalid C++ identifiers.
if (U8G2_FONT_VALUES.has(v)) return v;
if (/^u8g2_font_[A-Za-z0-9_]+$/.test(v)) return v; // allow custom fonts user knows exist
return DEFAULT_U8G2_FONT;
}
function getElementFontForMode(el, mode) {
if (!el) return mode === "u8g2" ? DEFAULT_U8G2_FONT : DEFAULT_TFT_FONT;
if (mode === "u8g2") {
const candidate = el.u8g2Font || el.font;
return sanitizeU8g2FontName(candidate);
}
const candidate = el.tftFont || el.font;
return sanitizeTftFontId(candidate);
}
function setElementFontForMode(el, mode, value) {
if (!el) return;
if (mode === "u8g2") {
const v = sanitizeU8g2FontName(value);
el.u8g2Font = v;
el.font = v; // backwards compat
return;
}
const v = sanitizeTftFontId(value);
el.tftFont = v;
el.font = v; // backwards compat
}
function ensureElementFontFields(el) {
if (!el) return;
// Seed driver-specific fields from legacy el.font if possible.
if (!el.u8g2Font) {
if (typeof el.font === "string" && el.font.startsWith("u8g2_font_")) el.u8g2Font = el.font;
else el.u8g2Font = DEFAULT_U8G2_FONT;
}
if (!el.tftFont) {
if (TFT_FONT_VALUES.has(String(el.font))) el.tftFont = String(el.font);
else el.tftFont = DEFAULT_TFT_FONT;
}
// Keep legacy `font` valid for the active mode.
el.font = getElementFontForMode(el, driverMode);
}
function ensureAllElementsHaveFonts() {
(screens || []).forEach((scr) => {
(scr.elements || []).forEach((el) => ensureElementFontFields(el));
});
}
function makeId() {
return "el_" + Math.random().toString(36).substr(2, 9);
}
function deepCloneState() {
return JSON.parse(
JSON.stringify({
screens,
activeScreenId,
dispWidth,
dispHeight,
bgColor,
useSprite,
snapToGrid,
gridSize,
driverMode,
u8g2PresetId,
tftSettingsState,
oledSettingsState,
// Element transparency is handled per element, no global state needed
})
);
}
function applyStateSnapshot(snap) {
historyLocked = true;
screens = snap.screens || [];
activeScreenId = snap.activeScreenId || (screens[0] && screens[0].id) || null;
dispWidth = snap.dispWidth || 240;
dispHeight = snap.dispHeight || 320;
bgColor = snap.bgColor || "#000000";
useSprite = !!snap.useSprite;
snapToGrid = !!snap.snapToGrid;
gridSize = snap.gridSize || 4;
driverMode = snap.driverMode || "tft";
u8g2PresetId = snap.u8g2PresetId || "ssd1306_128x64_i2c_f";
ensureAllElementsHaveFonts();
initFontList();
tftSettingsState = snap.tftSettingsState || {
rotation: 0,
colorDepth: 16,
backlight: "none",
touch: "none"
};
oledSettingsState = snap.oledSettingsState || {
rotation: 0,
contrast: 127,
flipMode: "none",
fontMode: "transparent",
powerSave: "off"
};
dispWidthInput.value = dispWidth;
dispHeightInput.value = dispHeight;
bgColorInput.value = bgColor;
useSpriteCheckbox.checked = useSprite;
snapCheckbox.checked = snapToGrid;
gridSizeInput.value = gridSize;
displayDriverSelect.value = driverMode;
u8g2PresetSelect.value = u8g2PresetId;
refreshScreenUI();
if (activeScreenId && screens.some((s) => s.id === activeScreenId)) {
setActiveScreen(activeScreenId, false);
} else if (screens[0]) {
setActiveScreen(screens[0].id, false);
}
updateDisplaySettingsVisibility();
updatePreviewSize();
renderElements();
updatePropsInputs();
updateCode();
historyLocked = false;
}
function pushHistory() {
if (historyLocked) return;
const snap = deepCloneState();
history = history.slice(0, historyIndex + 1);
history.push(snap);
historyIndex = history.length - 1;
updateUndoRedoButtons();
}
function updateUndoRedoButtons() {
undoBtn.disabled = historyIndex <= 0;
redoBtn.disabled = historyIndex >= history.length - 1;
}
function hexToRgb(hex) {
// Remove # if present
hex = hex.replace(/^#/, '');
// Parse the hex value
let r, g, b;
if (hex.length === 3) {
// Short format (#RGB)
r = parseInt(hex.charAt(0) + hex.charAt(0), 16);
g = parseInt(hex.charAt(1) + hex.charAt(1), 16);
b = parseInt(hex.charAt(2) + hex.charAt(2), 16);
} else if (hex.length === 6) {
// Long format (#RRGGBB)
r = parseInt(hex.substr(0, 2), 16);
g = parseInt(hex.substr(2, 2), 16);
b = parseInt(hex.substr(4, 2), 16);
} else {
return null; // Invalid format
}
return { r, g, b };
}
function isLightColor(hex) {
const rgb = hexToRgb(hex || "#000000");
if (!rgb) return false;
// Perceived luminance (0..1)
const lum = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255;
return lum > 0.62;
}
function getContrastingColor(hex) {
return isLightColor(hex) ? "#111827" : "#FFFFFF";