-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2349 lines (2060 loc) · 82.4 KB
/
app.js
File metadata and controls
2349 lines (2060 loc) · 82.4 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
// Runs the Python generator in the browser via Pyodide.
// This site is intended for GitHub Pages hosting (no backend).
import { loadPyodide } from "https://cdn.jsdelivr.net/pyodide/v0.25.1/full/pyodide.mjs";
const APP_VERSION = "0.7";
const LANG_STORAGE_KEY = "cardboxgen.lang";
let currentLang = "en";
let dict = null;
function getPath(obj, key) {
if (!obj) return null;
return key.split(".").reduce((acc, part) => (acc && typeof acc === "object" ? acc[part] : null), obj);
}
function t(key, vars = null) {
const raw = getPath(dict, key);
const base = typeof raw === "string" ? raw : key;
if (!vars) return base;
return base.replace(/\{\{(\w+)\}\}/g, (_, name) => (vars[name] ?? ""));
}
function tFromDict(d, key, vars = null) {
const raw = getPath(d, key);
const base = typeof raw === "string" ? raw : key;
if (!vars) return base;
return base.replace(/\{\{(\w+)\}\}/g, (_, name) => (vars[name] ?? ""));
}
const i18nCache = new Map();
async function getI18nDict(lang) {
const safeLang = ["en", "zh-Hant", "zh-Hans"].includes(lang) ? lang : "en";
if (i18nCache.has(safeLang)) return i18nCache.get(safeLang);
const resp = await fetch(`./i18n/${safeLang}.json`, { cache: "no-store" });
if (!resp.ok) throw new Error(`Failed to load i18n: ${resp.status}`);
const d = await resp.json();
i18nCache.set(safeLang, d);
return d;
}
async function loadLanguage(lang) {
const safeLang = ["en", "zh-Hant", "zh-Hans"].includes(lang) ? lang : "en";
const resp = await fetch(`./i18n/${safeLang}.json`, { cache: "no-store" });
if (!resp.ok) throw new Error(`Failed to load i18n: ${resp.status}`);
dict = await resp.json();
i18nCache.set(safeLang, dict);
currentLang = safeLang;
localStorage.setItem(LANG_STORAGE_KEY, safeLang);
document.documentElement.lang = safeLang.startsWith("zh") ? "zh" : "en";
applyTranslations();
rebuildHelpContent();
rebuildFaqData();
buildHelpDrawer();
buildFaqDrawer();
decorateHelpIcons();
}
function detectInitialLanguage() {
const saved = localStorage.getItem(LANG_STORAGE_KEY);
if (saved) return saved;
const nav = (navigator.language || "en").toLowerCase();
if (nav.startsWith("zh")) {
// Heuristic: treat zh-tw/hk/mo as Hant, else Hans.
if (nav.includes("tw") || nav.includes("hk") || nav.includes("mo") || nav.includes("hant")) return "zh-Hant";
return "zh-Hans";
}
return "en";
}
function applyTranslations() {
document.querySelectorAll("[data-i18n]").forEach((el) => {
const key = el.getAttribute("data-i18n");
const val = t(key);
if (val && val !== key) el.textContent = val;
});
document.querySelectorAll("[data-i18n-placeholder]").forEach((el) => {
const key = el.getAttribute("data-i18n-placeholder");
const val = t(key);
if (val && val !== key) el.setAttribute("placeholder", val);
});
}
const els = {
langSelect: document.getElementById("langSelect"),
helpDrawerBtn: document.getElementById("helpDrawerBtn"),
helpDrawer: document.getElementById("helpDrawer"),
helpDrawerClose: document.getElementById("helpDrawerClose"),
helpDrawerBody: document.getElementById("helpDrawerBody"),
helpSearch: document.getElementById("helpSearch"),
faqDrawerBtn: document.getElementById("faqDrawerBtn"),
faqDrawer: document.getElementById("faqDrawer"),
faqDrawerClose: document.getElementById("faqDrawerClose"),
faqDrawerBody: document.getElementById("faqDrawerBody"),
faqSearch: document.getElementById("faqSearch"),
drawerOverlay: document.getElementById("drawerOverlay"),
popover: document.getElementById("popover"),
controlsToggle: document.getElementById("controlsToggle"),
controlsPanel: document.getElementById("controlsPanel"),
mobileGenerate: document.getElementById("mobileGenerate"),
mobileBundle: document.getElementById("mobileBundle"),
studentMode: document.getElementById("studentMode"),
wizard: document.getElementById("wizard"),
// v0.6 Step 1 — Client & context
clientContext: document.getElementById("clientContext"),
problemStatement: document.getElementById("problemStatement"),
constraintNoCoins: document.getElementById("constraintNoCoins"),
constraintNoLiquids: document.getElementById("constraintNoLiquids"),
constraintPersonalUse: document.getElementById("constraintPersonalUse"),
constraintChecks: document.querySelectorAll("#constraintNoCoins, #constraintNoLiquids, #constraintPersonalUse"),
dispenseType: document.getElementById("dispenseType"),
dispenseTargetType: document.getElementById("dispenseTargetType"),
storageTarget: document.getElementById("storageTarget"),
dispenseTarget: document.getElementById("dispenseTarget"),
// v0.6 Step 2 — Requirements
irregularShape: document.getElementById("irregularShape"),
metricJam: document.getElementById("metricJam"),
metricConsistency: document.getElementById("metricConsistency"),
metricRefill: document.getElementById("metricRefill"),
metricDurability: document.getElementById("metricDurability"),
successMetrics: document.querySelectorAll("#metricJam, #metricConsistency, #metricRefill, #metricDurability"),
// v0.6 Step 3 — Recommendation + justification
mechanismRecs: document.getElementById("mechanismRecs"),
mechanismJustification: document.getElementById("mechanismJustification"),
mechanism: document.getElementById("mechanism"),
// v0.5 Student item inputs
cardWidth: document.getElementById("cardWidth"),
cardHeight: document.getElementById("cardHeight"),
cardThickness: document.getElementById("cardThickness"),
capacityCards: document.getElementById("capacityCards"),
maxPieceSize: document.getElementById("maxPieceSize"),
// v0.5 mechanism params
dividerBays: document.getElementById("dividerBays"),
axleDiameter: document.getElementById("axleDiameter"),
hopperHeight: document.getElementById("hopperHeight"),
depthLayersTotal: document.getElementById("depthLayersTotal"),
wheelLayers: document.getElementById("wheelLayers"),
screwDiameter: document.getElementById("screwDiameter"),
screwMargin: document.getElementById("screwMargin"),
addFeet: document.getElementById("addFeet"),
preset: document.getElementById("preset"),
dimMode: document.getElementById("dimMode"),
innerWidth: document.getElementById("innerWidth"),
innerDepth: document.getElementById("innerDepth"),
innerHeight: document.getElementById("innerHeight"),
thickness: document.getElementById("thickness"),
fit: document.getElementById("fit"),
fitReadout: document.getElementById("fitReadout"),
sizeReadout: document.getElementById("sizeReadout"),
kerf: document.getElementById("kerf"),
clearance: document.getElementById("clearance"),
jointRule: document.getElementById("jointRule"),
fingerWidth: document.getElementById("fingerWidth"),
minFingers: document.getElementById("minFingers"),
sheetWidth: document.getElementById("sheetWidth"),
marginMm: document.getElementById("marginMm"),
paddingMm: document.getElementById("paddingMm"),
strokeMm: document.getElementById("strokeMm"),
labels: document.getElementById("labels"),
frontHeight: document.getElementById("frontHeight"),
scoop: document.getElementById("scoop"),
scoopRadius: document.getElementById("scoopRadius"),
scoopDepth: document.getElementById("scoopDepth"),
windowMargin: document.getElementById("windowMargin"),
btnGenerate: document.getElementById("btnGenerate"),
btnBundle: document.getElementById("btnBundle"),
status: document.getElementById("status"),
exportHint: document.getElementById("exportHint"),
preview: document.getElementById("preview"),
warnings: document.getElementById("warnings"),
// v0.6 Step 4 — Reasoning + export
reasoningInternal: document.getElementById("reasoningInternal"),
reasoningExternal: document.getElementById("reasoningExternal"),
reasoningOpenings: document.getElementById("reasoningOpenings"),
rampAngle: document.getElementById("rampAngle"),
step1Badge: document.getElementById("step1Badge"),
step2Badge: document.getElementById("step2Badge"),
step3Badge: document.getElementById("step3Badge"),
step4Badge: document.getElementById("step4Badge"),
zoomOut: document.getElementById("zoomOut"),
zoomIn: document.getElementById("zoomIn"),
fitView: document.getElementById("fitView"),
showCut: document.getElementById("showCut"),
showLabels: document.getElementById("showLabels"),
};
function setStatus(msg) {
els.status.textContent = msg;
}
function setStatusKey(key, vars = null) {
setStatus(t(key, vars));
}
function hasBlockingErrors() {
return (pythonWarnings || []).some((w) => String(w?.severity || "").toLowerCase() === "error");
}
function updateExportUi() {
const blocked = hasBlockingErrors();
const canExport = !!lastSvg && !blocked;
if (els.exportHint) {
if (blocked) {
els.exportHint.hidden = false;
els.exportHint.textContent = t("status.fixErrorsToExport");
} else {
els.exportHint.hidden = true;
els.exportHint.textContent = "";
}
}
if (els.btnBundle) els.btnBundle.disabled = !canExport;
if (els.mobileBundle) els.mobileBundle.disabled = !canExport;
}
function num(el, fallback = null) {
const v = el.value.trim();
if (v === "") return fallback;
const n = Number(v);
return Number.isFinite(n) ? n : fallback;
}
function escapeHtml(s) {
const str = String(s ?? "");
return str.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
}
function escapeHtmlWithBreaks(s) {
return escapeHtml(s).replaceAll("\n", "<br>");
}
let pyodide = null;
let lastSvg = null;
let lastParams = null;
let lastMeta = null;
let lastDownloadFilename = null;
let lastDownloadUrl = null;
let pythonWarnings = [];
let autoFitNextRender = true;
let lastRenderedTemplateId = null;
let lastDerived = null;
let lastAutoMechanism = null;
let studentMechanismManuallyChosen = false;
const FIT_PRESETS = [0.0, 0.1, 0.2];
const HELP_CATEGORY_ORDER = [
"Project",
"Dimensions",
"Laser fit",
"Tabs",
"Layout",
"Preset options",
"Export",
"Troubleshooting",
];
const HELP_CATEGORY_BY_KEY = {
clientContext: "Project",
problemStatement: "Project",
constraints: "Project",
dispenseType: "Project",
dispenseTargetType: "Project",
irregularShape: "Project",
successMetrics: "Project",
cardWidth: "Project",
cardHeight: "Project",
capacityCards: "Project",
maxPieceSize: "Project",
storageTarget: "Project",
dispenseTarget: "Project",
mechanism: "Project",
mechanismJustification: "Project",
preset: "Project",
dimensionMode: "Dimensions",
innerWidth: "Dimensions",
innerDepth: "Dimensions",
innerHeight: "Dimensions",
thickness: "Dimensions",
fit: "Laser fit",
kerf: "Laser fit",
clearance: "Laser fit",
fingerWidth: "Laser fit",
minTabs: "Laser fit",
holdingTabs: "Tabs",
tabWidth: "Tabs",
sheetWidth: "Layout",
margin: "Layout",
padding: "Layout",
stroke: "Layout",
labelsToggle: "Layout",
lid: "Layout",
frontHeight: "Preset options",
scoop: "Preset options",
scoopRadius: "Preset options",
scoopDepth: "Preset options",
slotWidth: "Preset options",
slotHeight: "Preset options",
slotY: "Preset options",
dividerBays: "Preset options",
pocketCount: "Preset options",
axleDiameter: "Preset options",
rampCount: "Preset options",
hopperHeight: "Preset options",
depthLayersTotal: "Preset options",
wheelLayers: "Preset options",
screwDiameter: "Preset options",
screwMargin: "Preset options",
addFeet: "Preset options",
troubleshooting: "Troubleshooting",
};
let helpContent = {};
const DEFAULT_FAQ_DATA = {
Project: [
{
q: "Internal vs external dimensions — which should I use?",
a: "Use Internal when you care about the space that must fit your items. Use External when you must match an outside footprint. Dimension mode converts for you using material thickness.",
links: ["dimensionMode", "thickness"],
},
{
q: "How do I size W/D/H from a storage target and dispense target?",
a: "Start with the item’s real size. Add a little clearance so items don’t jam. Decide the storage stack height and the dispense opening separately; then choose a mechanism/preset that matches the behavior you want.",
links: ["storageTarget", "dispenseTarget", "mechanism", "preset"],
},
{
q: "Which mechanism should I choose for flowing vs stacking items?",
a: "Stacking is for flat items (cards/tiles) and is more predictable. Flowing is only for dry solids that can pour; it’s not recommended for cards.",
links: ["dispenseType", "mechanism"],
},
],
"Laser fit": [
{
q: "What is kerf? Why does it matter?",
a: "Kerf is the width of material removed by the laser cut. If you ignore it, tabs/slots won’t match the real cut size, and joints can become too tight or too loose.",
links: ["kerf"],
},
{
q: "What is joint clearance? Tight vs loose symptoms",
a: "Clearance controls how easily joints assemble. Too tight: hard to press together, material may tear. Too loose: wobbly joints and gaps. Adjust in small steps (e.g. 0.05mm).",
links: ["clearance", "fit"],
},
{
q: "My joints are too tight / too loose — what do I change?",
a: "Too tight: increase Joint clearance a little, or verify kerf with the Fit Test. Too loose: decrease Joint clearance. Keep thickness correct.",
links: ["clearance", "kerf", "thickness"],
},
],
Preview: [
{
q: "Why preview scale looks wrong / how to check mm scale",
a: "The preview is for layout and sanity-checking. Always verify in your laser software that units are mm and that a known dimension matches (e.g. inner width). Use the Fit button to zoom to the drawing.",
links: ["innerWidth"],
},
{
q: "Preview/export troubleshooting",
a: "If your laser software changes size on import, confirm SVG units, viewBox handling, and any DPI import setting. Then measure a known dimension.",
links: [],
},
],
};
let faqData = DEFAULT_FAQ_DATA;
function arr(v) {
return Array.isArray(v) ? v : [];
}
function rebuildHelpContent() {
const helpObj = getPath(dict, "help") || {};
const out = {};
Object.keys(helpObj).forEach((k) => {
const base = getPath(dict, `help.${k}`) || {};
out[k] = {
key: k,
category: HELP_CATEGORY_BY_KEY[k] || "Other",
title: base.title || k,
short: base.short || "",
meaning: base.meaning || base.what || "",
decide: arr(base.decide),
typical: arr(base.typical),
pitfalls: arr(base.pitfalls),
wrong: arr(base.wrong),
example: base.example || "",
};
});
if (!out.troubleshooting) {
out.troubleshooting = {
key: "troubleshooting",
category: "Troubleshooting",
title: t("faqUi.troubleshootingTitle"),
short: t("faqUi.troubleshootingShort"),
meaning: "",
decide: [],
typical: [],
pitfalls: [],
wrong: [],
example: "",
};
}
helpContent = out;
}
function rebuildFaqData() {
const fromDict = getPath(dict, "faq");
if (fromDict && typeof fromDict === "object") {
faqData = fromDict;
return;
}
faqData = DEFAULT_FAQ_DATA;
}
function computeDerived() {
const thickness = num(els.thickness, 3);
const kerf = num(els.kerf, 0.2);
const c = num(els.clearance, 0.1);
const drawnSlot = thickness + c - kerf;
const expectedFinalSlot = thickness + c;
els.jointRule.textContent = t("readouts.jointRule", { drawn: drawnSlot.toFixed(2), final: expectedFinalSlot.toFixed(2) });
const rawW = num(els.innerWidth, 135);
const rawD = num(els.innerDepth, 90);
const rawH = num(els.innerHeight, 225);
let internal = { w: rawW, d: rawD, h: rawH };
let external = { w: rawW, d: rawD, h: rawH };
if (els.dimMode.value === "internal") {
internal = { w: rawW, d: rawD, h: rawH };
external = { w: rawW + 2 * thickness, d: rawD + 2 * thickness, h: rawH + thickness };
els.sizeReadout.textContent = t("readouts.computedExternal", {
w: external.w.toFixed(1),
d: external.d.toFixed(1),
h: external.h.toFixed(1),
});
} else {
external = { w: rawW, d: rawD, h: rawH };
internal = { w: rawW - 2 * thickness, d: rawD - 2 * thickness, h: rawH - thickness };
els.sizeReadout.textContent = t("readouts.computedInternal", {
w: internal.w.toFixed(1),
d: internal.d.toFixed(1),
h: internal.h.toFixed(1),
});
}
lastDerived = {
thickness,
kerf,
clearance: c,
joint_rule: {
drawn_slot_depth: drawnSlot,
expected_final_slot_depth: expectedFinalSlot,
},
internal,
external,
openings: null,
};
if (els.reasoningInternal) {
els.reasoningInternal.textContent = t("readouts.derivedInternal", {
w: internal.w.toFixed(1),
d: internal.d.toFixed(1),
h: internal.h.toFixed(1),
});
}
if (els.reasoningExternal) {
els.reasoningExternal.textContent = t("readouts.derivedExternal", {
w: external.w.toFixed(1),
d: external.d.toFixed(1),
h: external.h.toFixed(1),
});
}
if (els.reasoningOpenings) els.reasoningOpenings.textContent = "";
updateStepBadges();
renderWarnings();
}
function setFitPreset(index) {
const i = Math.max(0, Math.min(2, Number(index)));
const c = FIT_PRESETS[i];
els.fit.value = String(i);
els.clearance.value = c.toFixed(2);
els.fitReadout.textContent = i === 0 ? t("fit.tight") : i === 1 ? t("fit.normal") : t("fit.loose");
computeDerived();
}
function setStudentMode(on) {
const enabled = !!on;
els.wizard.hidden = !enabled;
// In student mode, keep Advanced collapsed by default.
const adv = document.getElementById("advanced");
if (adv) adv.open = !enabled;
if (!enabled) {
studentMechanismManuallyChosen = false;
lastAutoMechanism = null;
}
setStudentItemUi();
rebuildMechanismRecommendations();
updateStepBadges();
}
function setStudentItemUi() {
const itemType = els.dispenseType?.value ?? "stacking";
const stacking = itemType !== "flowing";
document.getElementById("studentStackingSizeRow")?.toggleAttribute("hidden", !stacking);
document.getElementById("studentStackingSizeRow2")?.toggleAttribute("hidden", !stacking);
document.getElementById("studentStackingThicknessRow")?.toggleAttribute("hidden", !stacking);
document.getElementById("studentStackingCapacityRow")?.toggleAttribute("hidden", !stacking);
document.getElementById("studentFlowingSizeRow")?.toggleAttribute("hidden", stacking);
document.getElementById("studentFlowingFlagsRow")?.toggleAttribute("hidden", stacking);
}
function chooseMechanismFromStudentInputs() {
return recommendMechanismsFromStudentInputs()[0]?.id ?? "tray_open_front";
}
function recommendMechanismsFromStudentInputs() {
const itemType = els.dispenseType?.value ?? "stacking";
const target = els.dispenseTargetType?.value ?? "";
const irregular = !!els.irregularShape?.checked;
const storage = String(els.storageTarget?.value ?? "").toLowerCase();
const problem = String(els.problemStatement?.value ?? "").toLowerCase();
const wantsVisibility = /(window|visible|see|inventory|display)/i.test(`${storage} ${problem}`);
const out = [];
const push = (id, reasonKey) => out.push({ id, reasonKey });
if (itemType === "flowing") {
// v0.7: controlled portioning via layered rotary wheel candy machine.
push(
"candy_machine_rotary_layered",
target === "counted" && !irregular ? "recs.reason.flowingCounted" : "recs.reason.flowingPortions"
);
if (wantsVisibility) push("window_front", "recs.reason.visibility");
push("tray_open_front", "recs.reason.fallbackPrototype");
return out.slice(0, 3);
}
// Stacking (cards / flat items)
if (target === "one") {
push("card_shoe", "recs.reason.stackingOne");
if (wantsVisibility) push("window_front", "recs.reason.visibility");
push("tray_open_front", "recs.reason.stackingGrab");
return out;
}
if (target === "multi") {
push("divider_rack", "recs.reason.stackingMulti");
if (wantsVisibility) push("window_front", "recs.reason.visibility");
push("tray_open_front", "recs.reason.stackingGrab");
push("card_shoe", "recs.reason.stackingOne");
return out;
}
// grab / default
push("tray_open_front", "recs.reason.stackingGrab");
if (wantsVisibility) push("window_front", "recs.reason.visibility");
push("card_shoe", "recs.reason.stackingOne");
push("divider_rack", "recs.reason.stackingMulti");
return out;
}
function rebuildMechanismRecommendations() {
if (!els.mechanismRecs) return;
if (!els.studentMode?.checked) {
els.mechanismRecs.textContent = "";
return;
}
const recs = recommendMechanismsFromStudentInputs();
if (!recs.length) {
els.mechanismRecs.textContent = "";
return;
}
const chosen = chooseMechanismFromStudentInputs();
const chosenReasonKey = recs.find((r) => r.id === chosen)?.reasonKey || recs[0]?.reasonKey || "";
const chosenName = t(`options.mechanism.${chosen}`);
const chosenReason = chosenReasonKey ? t(chosenReasonKey) : "";
const html =
`<div><strong>${escapeHtml(t("recs.title"))}</strong></div>` +
`<ol>` +
recs
.map((r) => {
const name = t(`options.mechanism.${r.id}`);
const reason = r.reasonKey ? t(r.reasonKey) : "";
return `<li><strong>${escapeHtml(name)}</strong>${reason ? ` — ${escapeHtml(reason)}` : ""}</li>`;
})
.join("") +
`</ol>` +
`<div class="hint"><strong>${escapeHtml(t("recs.selectedTitle"))}</strong> ${escapeHtml(chosenName)}${chosenReason ? ` — ${escapeHtml(chosenReason)}` : ""}</div>`;
els.mechanismRecs.innerHTML = html;
}
function applyStudentAutoDesign() {
if (!els.studentMode?.checked) return;
rebuildMechanismRecommendations();
const chosen = chooseMechanismFromStudentInputs();
if (!studentMechanismManuallyChosen) {
if (els.mechanism && els.mechanism.value !== chosen) els.mechanism.value = chosen;
lastAutoMechanism = chosen;
}
// Mechanism choice always drives preset (course-friendly: one concept → one template).
const mech = els.mechanism?.value ?? chosen;
if (els.preset && els.preset.value !== mech) els.preset.value = mech;
// Always design around internal dimensions for item-fit.
if (els.dimMode) els.dimMode.value = "internal";
const t = num(els.thickness, 3);
const itemType = els.dispenseType?.value ?? "stacking";
if (itemType === "flowing") {
const s = Math.max(5, num(els.maxPieceSize, 18));
// Simple, safe-ish default hopper/cavity sizes.
els.innerWidth.value = String(Math.round(Math.max(80, s * 5)));
els.innerDepth.value = String(Math.round(Math.max(80, s * 5)));
els.innerHeight.value = String(Math.round(Math.max(120, s * 7)));
// Candy machine defaults.
if (els.axleDiameter) els.axleDiameter.value = String(3.2);
if (els.hopperHeight) els.hopperHeight.value = String(Math.round(Math.max(70, s * 6)));
if (els.depthLayersTotal) els.depthLayersTotal.value = String(8);
if (els.wheelLayers) els.wheelLayers.value = String(3);
if (els.screwDiameter) els.screwDiameter.value = String(3.2);
if (els.screwMargin) els.screwMargin.value = String(6);
if (els.addFeet) els.addFeet.checked = false;
} else {
const cw = Math.max(10, num(els.cardWidth, 63));
const ch = Math.max(10, num(els.cardHeight, 88));
const ct = Math.max(0.08, num(els.cardThickness, 0.35));
const cap = Math.max(1, Math.floor(num(els.capacityCards, 60)));
const sideClear = 1.0;
const backClear = 2.0;
const topClear = 3.0;
// Stack height estimate from thickness.
const stackH = cap * ct;
const w = cw + 2 * sideClear;
const d = ch + backClear;
const h = Math.max(25, stackH + topClear);
els.innerWidth.value = String((Math.round(w * 10) / 10).toFixed(1));
els.innerDepth.value = String((Math.round(d * 10) / 10).toFixed(1));
els.innerHeight.value = String((Math.round(h * 10) / 10).toFixed(1));
if (chosen === "card_shoe") {
if (els.rampAngle) els.rampAngle.value = String(12);
}
}
// Keep divider bays in sync with student multi-category intent.
if (mech === "divider_rack" && els.dividerBays) {
els.dividerBays.value = String(Math.max(2, Math.floor(num(els.dividerBays, 3))));
}
computeDerived();
}
let autoGenTimer = null;
function scheduleStudentAutoGenerate() {
if (!els.studentMode?.checked) return;
if (autoGenTimer) clearTimeout(autoGenTimer);
autoGenTimer = setTimeout(async () => {
autoGenTimer = null;
try {
applyStudentAutoDesign();
await generateSvg();
} catch (e) {
console.error(e);
}
}, 120);
}
async function init() {
setStatusKey("status.loadingPyodide");
pyodide = await loadPyodide({});
setStatusKey("status.loadingModule");
const resp = await fetch("./cardboxgen_v0_7_templates.py", { cache: "no-store" });
if (!resp.ok) throw new Error(`Failed to load Python module: ${resp.status}`);
const code = await resp.text();
// Write into the virtual FS and import as a module so it doesn't run the CLI.
pyodide.FS.writeFile("cardboxgen_v0_7_templates.py", code);
await pyodide.runPythonAsync(`import importlib\ntmpl = importlib.import_module('cardboxgen_v0_7_templates')`);
els.btnGenerate.disabled = false;
els.btnBundle.disabled = false;
els.btnGenerate.textContent = t("actions.generate");
if (els.mobileGenerate) els.mobileGenerate.disabled = false;
if (els.mobileBundle) els.mobileBundle.disabled = false;
// Show something useful immediately on first load.
try {
await generateSvg();
} catch (e) {
console.error(e);
setStatus(`${t("status.ready")} (${e?.message ?? e})`);
}
}
function updateStepBadges() {
const inStudent = !!els.studentMode?.checked;
const nonEmpty = (v) => String(v ?? "").trim().length > 0;
const countChecked = (nodes) => Array.from(nodes || []).filter((n) => !!n?.checked).length;
// Step 1: context + constraints acknowledgement.
const contextOk = nonEmpty(els.clientContext?.value) && nonEmpty(els.problemStatement?.value);
const constraintsOk = countChecked(els.constraintChecks) >= 2;
const step1Complete = !inStudent || (contextOk && constraintsOk);
// Step 2: requirements.
const itemType = els.dispenseType?.value ?? "stacking";
const dispTarget = els.dispenseTargetType?.value ?? "";
const stackingOk =
Number(num(els.cardWidth, 0)) > 0 && Number(num(els.cardHeight, 0)) > 0 && Number(num(els.capacityCards, 0)) > 0;
const flowingOk = Number(num(els.maxPieceSize, 0)) > 0;
const itemOk = !!dispTarget && (itemType === "flowing" ? flowingOk : stackingOk);
const storageOk = nonEmpty(els.storageTarget?.value);
const metricsOk = countChecked(els.successMetrics) >= 2;
const step2Complete = !inStudent || (step1Complete && itemOk && storageOk && metricsOk);
// Step 3: mechanism choice + justification.
const mechOk = nonEmpty(els.mechanism?.value);
const justificationOk = String(els.mechanismJustification?.value ?? "").trim().length >= 20;
const step3Complete = !inStudent || (step2Complete && mechOk && justificationOk);
// Step 4: fabrication setup + review.
const thicknessSet = nonEmpty(els.thickness?.value);
const kerfKnown = nonEmpty(els.kerf?.value);
const hasCut = !!lastSvg;
const hasErrors = hasBlockingErrors();
const step4Complete = !inStudent || (step3Complete && thicknessSet && kerfKnown && hasCut && !hasErrors);
if (els.step1Badge) els.step1Badge.textContent = step1Complete ? t("steps.complete") : t("steps.incomplete");
if (els.step2Badge) els.step2Badge.textContent = step2Complete ? t("steps.complete") : t("steps.incomplete");
if (els.step3Badge) els.step3Badge.textContent = step3Complete ? t("steps.complete") : t("steps.incomplete");
if (els.step4Badge) els.step4Badge.textContent = step4Complete ? t("steps.complete") : t("steps.incomplete");
if (els.btnBundle) els.btnBundle.disabled = hasErrors || !lastSvg || (inStudent ? !step4Complete : false);
if (els.mobileBundle) els.mobileBundle.disabled = hasErrors || !lastSvg || (inStudent ? !step4Complete : false);
updateExportUi();
}
function collectUiWarningKeys(p) {
const keys = [];
if (p.kerf >= p.thickness) keys.push("warnings.kerfTooBig");
// Heuristic: for ~3mm stock, >0.4mm clearance is usually overly loose.
if (p.thickness <= 3.5 && p.fit_clearance > 0.4) keys.push("warnings.clearanceLarge");
if ((p.min_fingers ?? 3) < 3) keys.push("warnings.minTabs");
// v0.6 coach layer: deterministic design review + requirements quality checks.
const inStudent = !!els.studentMode?.checked;
// Quality checks: keep these non-blocking (warnings only).
const hasNumber = (s) => /\d/.test(String(s || ""));
const seemsVague = (s) => {
const txt = String(s || "").trim().toLowerCase();
if (!txt) return false;
return /\b(a\s*lot|some|nice|better|maybe|around|stuff|things?)\b/.test(txt);
};
if (inStudent) {
const cc = String(els.clientContext?.value ?? "").trim();
const ps = String(els.problemStatement?.value ?? "").trim();
const st = String(els.storageTarget?.value ?? "").trim();
const dt = String(els.dispenseTarget?.value ?? "").trim();
if (cc && (cc.length < 8 || seemsVague(cc))) keys.push("warnings.vagueClientContext");
if (ps && (ps.length < 12 || seemsVague(ps))) keys.push("warnings.vagueProblemStatement");
if (st && !hasNumber(st)) keys.push("warnings.vagueStorageTarget");
if (dt && (dt.length < 8 || seemsVague(dt))) keys.push("warnings.vagueDispenseTarget");
}
// Design review heuristics (mechanism-aware where possible).
const itemType = els.dispenseType?.value ?? "stacking";
const irregular = !!els.irregularShape?.checked;
if (itemType === "flowing" && Number.isFinite(p.max_piece) && p.max_piece > 0) {
const funnel = Math.min(p.inner_w, p.inner_d);
const ratio = funnel / p.max_piece;
const threshold = irregular ? 5.0 : 4.0;
if (ratio > 0 && ratio < threshold) keys.push("warnings.flowingBridgingRisk");
}
if (Number.isFinite(p.inner_h) && p.inner_h >= 200 && p.thickness <= 3.2) {
keys.push("warnings.tallWallsFlexRisk");
}
if (Number.isFinite(p.gap) && p.gap > 0 && p.gap < 6) {
keys.push("warnings.paddingTooSmall");
}
return keys;
}
const UI_WARNING_HELP_KEY = {
"warnings.kerfTooBig": "kerf",
"warnings.clearanceLarge": "clearance",
"warnings.minTabs": "minTabs",
"warnings.vagueClientContext": "clientContext",
"warnings.vagueProblemStatement": "problemStatement",
"warnings.vagueStorageTarget": "storageTarget",
"warnings.vagueDispenseTarget": "dispenseTarget",
"warnings.flowingBridgingRisk": "maxPieceSize",
"warnings.tallWallsFlexRisk": "innerHeight",
"warnings.paddingTooSmall": "padding",
};
function renderWarnings() {
const p = buildParams();
const uiKeys = collectUiWarningKeys(p);
const uiWarnings = uiKeys.map((k) => ({ text: t(k), helpKey: UI_WARNING_HELP_KEY[k] || null }));
const allPython = Array.isArray(pythonWarnings) ? pythonWarnings : [];
const pyWarnings = allPython
.map((w) => {
const sev = String(w?.severity || "warn").toLowerCase();
const code = String(w?.code || "").trim();
const msg = String(w?.message || "").trim();
const fix = String(w?.fix || "").trim();
return { severity: sev, code, message: msg, fix };
})
.filter((w) => w.message);
const pyErrors = pyWarnings.filter((w) => w.severity === "error");
const pyWarns = pyWarnings.filter((w) => w.severity === "warn");
const pyInfos = pyWarnings.filter((w) => w.severity === "info");
const hasAny = uiWarnings.length || pyWarnings.length;
if (!hasAny) {
els.warnings.hidden = true;
els.warnings.innerHTML = "";
return;
}
const uiList = uiWarnings.length
? `<div class="warnBlock"><strong>${escapeHtml(t("warnings.title"))}</strong><ul>${uiWarnings
.map((w) => {
const link = w.helpKey
? ` <a href="#" data-open-help="${escapeHtml(String(w.helpKey))}">${escapeHtml(t("mode.help"))}</a>`
: "";
return `<li>${escapeHtmlWithBreaks(String(w.text))}${link}</li>`;
})
.join("")}</ul></div>`
: "";
const renderPyItem = (w) => {
const code = w.code ? ` <code>${escapeHtml(w.code)}</code>` : "";
const fix = w.fix ? `<div class="hint">${escapeHtml(t("warnings.fix"))}: ${escapeHtmlWithBreaks(w.fix)}</div>` : "";
return `<li><strong>${escapeHtml(w.severity.toUpperCase())}</strong>${code}: ${escapeHtmlWithBreaks(w.message)}${fix}</li>`;
};
const pyList = pyWarnings.length
? `<div class="warnBlock"><strong>${escapeHtml(t("warnings.title"))}</strong>` +
(pyErrors.length ? `<div class="hint">${escapeHtml(t("warnings.blocking"))}</div><ul>${pyErrors.map(renderPyItem).join("")}</ul>` : "") +
(pyWarns.length ? `<ul>${pyWarns.map(renderPyItem).join("")}</ul>` : "") +
(pyInfos.length ? `<ul>${pyInfos.map(renderPyItem).join("")}</ul>` : "") +
`</div>`
: "";
els.warnings.hidden = false;
els.warnings.innerHTML = uiList + pyList;
updateExportUi();
}
function buildParams() {
const inStudent = !!els.studentMode?.checked;
const templateId = String((inStudent ? els.mechanism?.value : els.preset?.value) || "tray_open_front").trim();
const dimMode = els.dimMode?.value || "internal";
let innerW = num(els.innerWidth, 135);
let innerD = num(els.innerDepth, 90);
let innerH = num(els.innerHeight, 80);
const thickness = num(els.thickness, 3);
// If user entered external sizes, convert to internal before sending to generator.
if (dimMode === "external") {
innerW = innerW - 2 * thickness;
innerD = innerD - 2 * thickness;
innerH = innerH - thickness;
}
return {
template_id: templateId,
// Fabrication
thickness,
kerf: num(els.kerf, 0.2),
fit_clearance: num(els.clearance, 0.1),
finger_w: num(els.fingerWidth, null),
min_fingers: num(els.minFingers, 3),
// Layout / styling
max_row_width: num(els.sheetWidth, 340),
gap: num(els.paddingMm, 12),
stroke_mm: num(els.strokeMm, 0.2),
labels: !!els.labels?.checked,
// Common box/tray sizes
inner_w: innerW,
inner_d: innerD,
inner_h: innerH,
// tray_open_front
front_h: num(els.frontHeight, 30),
scoop: !!els.scoop?.checked,
scoop_r: num(els.scoopRadius, 22),
scoop_depth: num(els.scoopDepth, 16),
// divider_rack
divider_count: num(els.dividerBays, 3),
// window_front
window_margin: num(els.windowMargin, 12),
// card_shoe
card_w: num(els.cardWidth, 63),
card_h: num(els.cardHeight, 88),
card_t: num(els.cardThickness, 0.35),
capacity: num(els.capacityCards, 60),
ramp_angle_deg: num(els.rampAngle, 12),
// rotary_wheel
max_piece: num(els.maxPieceSize, 18),
irregular: !!els.irregularShape?.checked,
axle_d: num(els.axleDiameter, 3.2),
// candy_machine_rotary_layered
hopper_h: num(els.hopperHeight, 90),
depth_layers_total: num(els.depthLayersTotal, 8),
wheel_layers: num(els.wheelLayers, 3),
screw_d: num(els.screwDiameter, 3.2),
screw_margin: num(els.screwMargin, 6),
add_feet: !!els.addFeet?.checked,
};
}
async function generateSvg() {
els.preview.textContent = "";
pythonWarnings = [];
lastMeta = null;
renderWarnings();
const p = buildParams();
setStatusKey("status.generatingSvg");
// Send parameters to Python.
pyodide.globals.set("p_json", JSON.stringify(p));
const resultJson = await pyodide.runPythonAsync(`
import json
from cardboxgen_v0_7_templates import generate_svg
params = json.loads(p_json)
template_id = params.pop('template_id', None)
out = generate_svg(template_id, params)
json.dumps(out, ensure_ascii=False)
`);