-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
785 lines (721 loc) · 25.8 KB
/
app.js
File metadata and controls
785 lines (721 loc) · 25.8 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
// App wiring: DOM init, event delegation, splitter, copy/download/reset
function copyOutput() {
const txt = getOutputText() || "";
navigator.clipboard.writeText(txt)
.then(() => flashButton(el("copyBtn")))
.catch(() => flashButton(el("copyBtn"), { error: true }));
}
function downloadOutput() {
const txt = getOutputText() || "";
const blob = new Blob([txt], { type: "application/json;charset=utf-8" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
// Filename: config_YYYY-MM-DD_HH-MM-SS.json
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hours = String(now.getHours()).padStart(2, "0");
const minutes = String(now.getMinutes()).padStart(2, "0");
const seconds = String(now.getSeconds()).padStart(2, "0");
const filename = `config_${year}-${month}-${day}_${hours}-${minutes}-${seconds}.json`;
a.download = filename;
a.click();
URL.revokeObjectURL(a.href);
flashButton(el("downloadBtn"));
}
function resetAll() {
el("maxPerSession").value = 100;
el("maxPerDay").value = 100;
el("minIntervalSec").value = 1;
el("slidingConfigSec").value = 1800;
const sendRadios = document.querySelectorAll("input[type='radio'][data-f='sendInappShowError']");
sendRadios.forEach((x) => { x.checked = x.value === "true"; });
el("inappsRoot").innerHTML = "";
addInapp();
updateInappDeleteButtonsState();
setOutputDirty(false);
scheduleGenerate();
}
function armResetButton() {
const btn = el("resetBtn");
if (!btn) return;
// Reset requires double-click within 2 seconds
resetArmedUntil = Date.now() + 2000;
btn.dataset.origText = btn.dataset.origText || btn.textContent;
btn.textContent = "Reset all?";
btn.classList.add("danger");
if (resetArmTimer) window.clearTimeout(resetArmTimer);
resetArmTimer = window.setTimeout(() => {
resetArmTimer = null;
resetArmedUntil = 0;
btn.textContent = btn.dataset.origText || "Reset";
}, 2000);
}
function handleResetClick(btn) {
const now = Date.now();
if (now < resetArmedUntil) {
if (resetArmTimer) window.clearTimeout(resetArmTimer);
resetArmTimer = null;
resetArmedUntil = 0;
const orig = btn.dataset.origText || "Reset";
resetAll();
btn.textContent = orig;
flashButton(btn);
return;
}
armResetButton();
flashButton(btn, { error: true });
}
function initCodeMirror() {
if (!window.CodeMirror) return;
cmEditor = window.CodeMirror(el("output"), {
value: "",
mode: "application/json",
theme: "default",
lineNumbers: true,
foldGutter: true,
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
matchBrackets: true,
tabSize: 2,
indentUnit: 2,
viewportMargin: 50,
extraKeys: {
"Ctrl-F": "findPersistent",
"Cmd-F": "findPersistent",
"Ctrl-G": "jumpToLine",
"Cmd-G": "jumpToLine",
"Shift-Ctrl-F": "findPersistent",
"Shift-Cmd-F": "findPersistent",
},
});
cmEditor.on("change", () => {
if (suppressOutputInput) {
// IMPORTANT:
// During auto-generation we call CodeMirror.setValue(), which triggers "change".
// `suppressOutputInput` prevents that programmatic update from:
// - flipping the editor into "manual JSON edits" mode
// - showing manual-only UI
// At the same time we must keep `lastGeneratedText` in sync with what CM actually holds.
const cur = cmEditor.getValue() || "";
lastGeneratedText = cur;
outputDirty = false;
setOutputDirty(false);
return;
}
const cur = cmEditor.getValue() || "";
const isDifferentFromGenerated = cur !== (lastGeneratedText || "");
// One-way flow:
// Once user edits JSON, we stay in manual mode until "Reset JSON to dropdowns".
if (!outputDirty && isDifferentFromGenerated) setOutputDirty(true);
if (outputDirty) {
try {
JSON.parse(cur);
setEditorStatus("", { error: false });
highlightJsonError(null, cur);
showEditorError("");
} catch (e) {
setEditorStatus("", { error: false });
highlightJsonError(e, cur);
showEditorError(`Invalid JSON: ${String(e?.message || e)}`);
}
} else {
setEditorStatus("", { error: false });
highlightJsonError(null, cur);
showEditorError("");
}
scheduleGenerate();
scheduleJsonNavUpdate();
updateScrollShadows();
});
cmEditor.on("scroll", () => {
updateScrollShadows();
});
setOutputDirty(false);
}
function initSplitter() {
const splitter = el("splitter");
const grid = el("mainGrid");
let drag = null;
const minLeftPx = 440;
const minLeftRatio = 0.28;
const minRight = 360;
let userResized = false;
if (!splitter || !grid) return;
const getSplitW = () =>
Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--splitW")) || 6;
const getGap = () => 12;
const computeBounds = () => {
const gridRect = grid.getBoundingClientRect();
const available = Math.max(0, gridRect.width - getSplitW() - getGap() * 2);
const minLeft = Math.max(minLeftPx, available * minLeftRatio);
const maxLeft = Math.max(minLeft, available - minRight);
return { available, minLeft, maxLeft };
};
const setLeftW = (px) => {
document.documentElement.style.setProperty("--leftW", `${Math.round(px)}px`);
};
splitter.addEventListener("mousedown", (e) => {
e.preventDefault();
const leftRect = grid.querySelector(".panelLeft")?.getBoundingClientRect();
if (!leftRect) return;
userResized = true;
drag = { startX: e.clientX, startW: leftRect.width };
splitter.classList.add("dragging");
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
});
window.addEventListener("mousemove", (e) => {
if (!drag) return;
const dx = e.clientX - drag.startX;
const { minLeft, maxLeft } = computeBounds();
const next = clamp(drag.startW + dx, minLeft, maxLeft);
setLeftW(next);
});
window.addEventListener("mouseup", () => {
if (!drag) return;
drag = null;
splitter.classList.remove("dragging");
document.body.style.cursor = "";
document.body.style.userSelect = "";
});
const applyAuto = () => {
if (window.matchMedia("(max-width: 980px)").matches) return;
const { available, minLeft, maxLeft } = computeBounds();
const desired = available * 0.30;
setLeftW(clamp(desired, minLeft, maxLeft));
};
const clampCurrent = () => {
if (window.matchMedia("(max-width: 980px)").matches) return;
const { minLeft, maxLeft } = computeBounds();
const cur = Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--leftW")) || minLeft;
setLeftW(clamp(cur, minLeft, maxLeft));
};
let autoApplied = false;
requestAnimationFrame(() => {
if (!userResized) {
applyAuto();
autoApplied = true;
} else {
clampCurrent();
}
});
window.addEventListener("resize", () => {
if (!userResized) {
if (!autoApplied) {
applyAuto();
autoApplied = true;
} else {
clampCurrent();
}
} else {
clampCurrent();
}
});
}
let ignoreNextInappToggleClick = false;
function setupInappReorder() {
const root = el("inappsRoot");
const scroller = document.querySelector(".panelLeft .panelScroll") || root;
if (!root) return;
let draggingCard = null;
let placeholder = null;
let pointerId = null;
let offsetX = 0;
let offsetY = 0;
const getCardsInRoot = () =>
Array.from(root.querySelectorAll(".inappCard")).filter((x) => x !== draggingCard);
const ensurePlaceholder = (card) => {
if (placeholder) return placeholder;
placeholder = document.createElement("div");
placeholder.className = "inappDragPlaceholder";
const rect = card.getBoundingClientRect();
placeholder.style.height = `${rect.height}px`;
return placeholder;
};
const flip = (mutate) => {
const items = getCardsInRoot();
const first = new Map(items.map((n) => [n, n.getBoundingClientRect()]));
mutate();
const last = new Map(items.map((n) => [n, n.getBoundingClientRect()]));
items.forEach((n) => {
const a = first.get(n);
const b = last.get(n);
if (!a || !b) return;
const dx = a.left - b.left;
const dy = a.top - b.top;
if (!dx && !dy) return;
n.style.transition = "transform 0s";
n.style.transform = `translate(${dx}px, ${dy}px)`;
requestAnimationFrame(() => {
n.style.transition = "transform 160ms ease";
n.style.transform = "";
window.setTimeout(() => {
n.style.transition = "";
}, 200);
});
});
};
const positionDragged = (e) => {
if (!draggingCard) return;
draggingCard.style.left = `${e.clientX - offsetX}px`;
draggingCard.style.top = `${e.clientY - offsetY}px`;
};
const maybeAutoscroll = (e) => {
const elScroll = scroller;
if (!elScroll) return;
const r = elScroll.getBoundingClientRect();
const y = e.clientY;
const pad = 48;
const maxSpeed = 18;
let delta = 0;
if (y < r.top + pad) delta = -maxSpeed * ((r.top + pad - y) / pad);
else if (y > r.bottom - pad) delta = maxSpeed * ((y - (r.bottom - pad)) / pad);
if (delta) elScroll.scrollTop += delta;
};
const movePlaceholderToPointer = (e) => {
if (!placeholder) return;
const cards = getCardsInRoot().filter((c) => c && c !== placeholder);
const y = e.clientY;
let before = null;
for (const c of cards) {
const r = c.getBoundingClientRect();
const mid = r.top + r.height / 2;
if (y < mid) {
before = c;
break;
}
}
if (before) {
if (placeholder.nextSibling !== before) {
flip(() => root.insertBefore(placeholder, before));
}
} else {
const last = cards[cards.length - 1] || null;
if (!last) return;
if (placeholder.previousSibling !== last) {
flip(() => root.appendChild(placeholder));
}
}
};
const cleanup = () => {
window.removeEventListener("pointermove", onMove, true);
window.removeEventListener("pointerup", onUp, true);
window.removeEventListener("pointercancel", onUp, true);
pointerId = null;
};
const onMove = (e) => {
if (!draggingCard) return;
if (pointerId != null && e.pointerId !== pointerId) return;
positionDragged(e);
maybeAutoscroll(e);
movePlaceholderToPointer(e);
e.preventDefault();
};
const onUp = (e) => {
if (!draggingCard) return;
if (pointerId != null && e.pointerId !== pointerId) return;
cleanup();
const card = draggingCard;
const ph = placeholder;
draggingCard = null;
placeholder = null;
card.classList.remove("dragging");
card.style.position = "";
card.style.left = "";
card.style.top = "";
card.style.width = "";
card.style.zIndex = "";
card.style.pointerEvents = "";
if (ph && ph.parentNode) {
ph.parentNode.insertBefore(card, ph);
ph.remove();
} else {
root.appendChild(card);
}
ignoreNextInappToggleClick = true;
scheduleGenerate();
};
root.addEventListener("pointerdown", (e) => {
const handle = e.target.closest(".dragHandle");
if (!handle) return;
const card = handle.closest(".inappCard");
if (!card) return;
e.preventDefault();
e.stopPropagation();
draggingCard = card;
pointerId = e.pointerId;
try { handle.setPointerCapture(pointerId); } catch {}
const rect = card.getBoundingClientRect();
offsetX = e.clientX - rect.left;
offsetY = e.clientY - rect.top;
const ph = ensurePlaceholder(card);
root.insertBefore(ph, card);
card.classList.add("dragging");
card.style.position = "fixed";
card.style.left = `${rect.left}px`;
card.style.top = `${rect.top}px`;
card.style.width = `${rect.width}px`;
card.style.zIndex = "9999";
card.style.pointerEvents = "none";
window.addEventListener("pointermove", onMove, true);
window.addEventListener("pointerup", onUp, true);
window.addEventListener("pointercancel", onUp, true);
}, true);
}
function handleInappsRootClick(e) {
if (ignoreNextInappToggleClick) {
ignoreNextInappToggleClick = false;
// Suppress only card toggle, not action buttons
const isInteractive = e.target.closest("button, input, select, textarea, a, label");
const isActionBtn = !!e.target.closest("button[data-action]");
if (!isInteractive) {
e.preventDefault();
e.stopPropagation();
return;
}
}
const card = e.target.closest(".inappCard");
if (!card) return;
const btn = e.target.closest("button[data-action]");
if (btn) {
e.preventDefault();
e.stopPropagation();
const action = btn.dataset.action;
if (action === "delete") {
const cards = getInappCards();
if (cards.length <= 1) return;
card.remove();
updateInappDeleteButtonsState();
scheduleGenerate();
flashButton(btn);
return;
}
if (action === "duplicate") {
addInapp({ duplicateFromCard: card });
flashButton(btn);
return;
}
if (action === "open_image") {
const url = card.querySelector("[data-f='imageUrl']")?.value;
const ok = openUrlMaybe(url);
flashButton(btn, { error: !ok });
return;
}
if (action === "open_redirect") {
const url = card.querySelector("[data-f='redirectUrl']")?.value;
const ok = openUrlMaybe(url);
flashButton(btn, { error: !ok });
return;
}
if (action === "auto_image") {
const id = getInappId(card);
const img = card.querySelector("[data-f='imageUrl']");
if (img) {
img.dataset.auto = "true";
img.value = pickImage(id, { targetingLabel: targetingLabelFromCard(card), formLabel: formLabelFromCard(card) });
}
scheduleGenerate();
flashButton(btn);
return;
}
if (action === "auto_redirect") {
const id = getInappId(card);
const r = card.querySelector("[data-f='redirectUrl']");
if (r) {
r.dataset.auto = "true";
r.value = pickRedirect(id);
}
scheduleGenerate();
flashButton(btn);
return;
}
if (action === "random_close") {
randomizeCloseButton(card);
scheduleGenerate();
flashButton(btn);
return;
}
if (action === "add_targeting") {
addTargetingItem(card);
flashButton(btn);
return;
}
if (action === "remove_targeting") {
const item = btn.closest(".targetingItem");
removeTargetingItem(card, item);
flashButton(btn);
return;
}
if (action === "reset_targeting") {
const item = btn.closest(".targetingItem");
resetTargetingItem(card, item);
flashButton(btn);
return;
}
if (action === "copy_hint") {
const raw = btn.dataset.copyText || "";
const txt = decodeURIComponent(raw);
navigator.clipboard.writeText(txt)
.then(() => flashButton(btn))
.catch(() => flashButton(btn, { error: true }));
return;
}
if (action === "toggle_close") {
ensureInappHiddenDefaults(card);
const next = card.dataset.closeHidden === "true" ? "false" : "true";
card.dataset.closeHidden = next;
updateCardVisibility(card);
scheduleGenerate();
flashButton(btn);
return;
}
return;
}
// Click on non-interactive area toggles card open/close
const isInteractive = e.target.closest("button, input, select, textarea, a, label");
if (!isInteractive) {
const summary = card.querySelector("summary");
if (summary) {
if (e.target === summary || summary.contains(e.target)) {
e.preventDefault();
card.open = !card.open;
} else if (e.target === card) {
card.open = !card.open;
}
}
}
}
function handleDocumentInput(e) {
if (e.target && e.target.id === "output") return;
if (e.target.closest(".inappCard")) {
if (e.target.matches("[data-f='imageUrl']")) e.target.dataset.auto = "false";
if (e.target.matches("[data-f='redirectUrl']")) e.target.dataset.auto = "false";
if (e.target.matches("[data-f='payload']")) e.target.dataset.auto = "false";
const card = e.target.closest(".inappCard");
updateCardVisibility(card);
}
scheduleGenerate();
}
function handleDocumentChange(e) {
if (e.target.closest(".inappCard")) {
if (e.target.matches("[data-f='targeting']")) {
const card = e.target.closest(".inappCard");
applySdkAutofillForTargeting(card);
updateTargetingControls(card);
}
if (e.target.matches("input[type='radio'][data-f='targetingMode']")) {
const card = e.target.closest(".inappCard");
card.dataset.targetingMode = e.target.value === "or" ? "or" : "and";
updateTargetingControls(card);
updateCardVisibility(card);
}
if (e.target.matches("[data-f='payloadMode']")) {
const card = e.target.closest(".inappCard");
const id = getInappId(card);
const ta = card?.querySelector("[data-f='payload']");
const wasJson = card.classList.contains("payloadIsJson");
const sel = e.target;
const opt = sel?.selectedOptions?.[0] || null;
const prevPresetId = String(card?.dataset?.payloadPreset || "");
const presetId = opt?.dataset?.preset ? String(opt.dataset.preset) : "";
if (presetId) {
card.dataset.payloadPreset = presetId;
applySdkAutofillForPayloadPreset(card, presetId);
const txt = getPayloadPresetText(presetId);
if (ta && txt) {
ta.dataset.auto = "false";
ta.value = txt;
ta.style.height = "auto";
ta.style.height = `${ta.scrollHeight}px`;
}
} else if (ta && e.target.value === "json") {
card.dataset.payloadPreset = "";
if (prevPresetId) applySdkAutofillForTargeting(card);
ta.dataset.auto = "true";
ta.value = defaultPayloadJson();
ta.style.height = "auto";
ta.style.height = `${ta.scrollHeight}px`;
} else if (ta && e.target.value === "string") {
card.dataset.payloadPreset = "";
if (prevPresetId) applySdkAutofillForTargeting(card);
ta.dataset.auto = "true";
ta.value = randomPromoCode(id);
ta.style.height = "auto";
ta.style.height = `${ta.scrollHeight}px`;
} else if (ta && (ta.dataset.auto === "true" || !String(ta.value || "").trim())) {
ta.dataset.auto = "true";
ta.value = wasJson ? defaultPayloadJson() : randomPromoCode(id);
}
}
if (e.target.matches("[data-f='visitKind']")) {
const item = e.target.closest(".targetingItem");
const valNode = item?.querySelector("[data-f='visitValue']");
if (valNode) {
const cur = String(valNode.value || "").trim();
const kind = e.target.value;
const shouldSet = !cur || cur === "1" || cur === "100";
if (shouldSet) valNode.value = kind === "gte" ? "1" : "100";
}
}
updateCardVisibility(e.target.closest(".inappCard"));
}
scheduleGenerate();
}
// Helper: auto-select radio when user clicks/focuses on associated input field
function setupRadioAutoSelect(inputSelector, radioSelector, targetValue, modeCheck) {
const handler = (e) => {
const input = e.target.closest?.(inputSelector);
if (!input) return;
const card = input.closest(".inappCard");
if (!card) return;
const mode = card.querySelector(`input[type='radio'][data-f='${radioSelector}']:checked`)?.value || modeCheck;
if (mode === targetValue) return;
const radio = card.querySelector(`input[type='radio'][data-f='${radioSelector}'][value='${targetValue}']`);
if (radio) radio.checked = true;
updateCardVisibility(card);
scheduleGenerate();
};
document.addEventListener("pointerdown", handler, true);
document.addEventListener("focusin", handler, true);
}
document.addEventListener("DOMContentLoaded", () => {
// Prevent scroll on overflow:clip containers (safety net for CSS contain+clip)
const _lockTargets = [
document.documentElement,
document.body,
el("mainGrid"),
document.querySelector(".panelLeft"),
document.querySelector(".panelRight"),
el("output"),
].filter(Boolean);
const lockScroll = function() { this.scrollTop = 0; this.scrollLeft = 0; };
_lockTargets.forEach(function(n) { n.addEventListener("scroll", lockScroll); });
// Per-frame scroll lock
(function _rafLock() {
for (var i = 0; i < _lockTargets.length; i++) {
var n = _lockTargets[i];
if (n.scrollTop !== 0) n.scrollTop = 0;
if (n.scrollLeft !== 0) n.scrollLeft = 0;
}
requestAnimationFrame(_rafLock);
})();
// Prevent native focus-scroll inside left panel
var panelLeft = document.querySelector(".panelLeft");
if (panelLeft) {
panelLeft.addEventListener("focusin", function() {
for (var i = 0; i < _lockTargets.length; i++) {
_lockTargets[i].scrollTop = 0;
_lockTargets[i].scrollLeft = 0;
}
}, false);
panelLeft.addEventListener("mousedown", function(e) {
var inp = e.target.closest("input, select, textarea");
if (!inp) return;
Promise.resolve().then(function() {
try { inp.focus({ preventScroll: true }); } catch(_) {}
for (var i = 0; i < _lockTargets.length; i++) {
_lockTargets[i].scrollTop = 0;
_lockTargets[i].scrollLeft = 0;
}
});
}, false);
}
el("addInappBtn").addEventListener("click", (e) => { addInapp(); flashButton(e.currentTarget); });
el("copyBtn").addEventListener("click", () => { copyOutput(); });
el("downloadBtn").addEventListener("click", () => { downloadOutput(); });
el("resetBtn").addEventListener("click", (e) => { handleResetClick(e.currentTarget); });
initCodeMirror();
el("formatJsonBtn").addEventListener("click", () => formatJson());
el("regenerateJsonBtn").addEventListener("click", (e) => {
setOutputDirty(false);
generateConfig();
flashButton(e.currentTarget);
});
el("inappsRoot").addEventListener("click", handleInappsRootClick);
setupInappReorder();
// Prevent accidental card toggle after resizing a textarea
el("inappsRoot").addEventListener("mousedown", (e) => {
const ta = e.target.closest("textarea");
if (!ta) return;
const startH = ta.offsetHeight;
const startW = ta.offsetWidth;
const onUp = () => {
window.removeEventListener("mouseup", onUp, true);
if (ta.offsetHeight !== startH || ta.offsetWidth !== startW) {
ignoreNextInappToggleClick = true;
}
};
window.addEventListener("mouseup", onUp, true);
}, true);
// Forbid "e/E" in number inputs (scientific notation)
document.addEventListener("keydown", (e) => {
const t = e.target;
if (!(t instanceof HTMLInputElement)) return;
if (t.type !== "number") return;
if (e.key === "e" || e.key === "E") e.preventDefault();
});
initSplitter();
document.addEventListener("input", handleDocumentInput);
document.addEventListener("change", handleDocumentChange);
// Auto-select delay radio when clicking/focusing seconds input
setupRadioAutoSelect(".delaySecInput", "delayMode", "sec", "null");
// Auto-select frequency radio when clicking/focusing seconds input
setupRadioAutoSelect(".freqSecInput", "frequency", "periodic_seconds", "lifetime_once");
// // --- DIAGNOSTIC OVERLAY (uncomment to debug scroll/resize issues) ---
// (function() {
// var box = document.createElement("div");
// box.id = "_diagOverlay";
// box.style.cssText = "position:fixed;top:4px;right:4px;z-index:99999;" +
// "background:rgba(0,0,0,0.85);color:#0f0;font:10px/1.4 monospace;" +
// "padding:6px 8px;border-radius:6px;pointer-events:none;max-width:340px;" +
// "white-space:pre;opacity:0.9;";
// document.body.appendChild(box);
// var _lastSizes = {}, _diagLog = [], MAX_LOG = 8;
// function addLog(msg) { _diagLog.push(msg); if (_diagLog.length > MAX_LOG) _diagLog.shift(); }
// var diagTargets = [
// { label: "mainGrid", node: el("mainGrid") },
// { label: "panelLeft", node: document.querySelector(".panelLeft") },
// { label: "panelRight", node: document.querySelector(".panelRight") },
// { label: "output", node: el("output") },
// ];
// var ro = new ResizeObserver(function(entries) {
// for (var i = 0; i < entries.length; i++) {
// var entry = entries[i], label = "";
// for (var j = 0; j < diagTargets.length; j++) {
// if (diagTargets[j].node === entry.target) { label = diagTargets[j].label; break; }
// }
// var h = Math.round(entry.contentRect.height), key = label + "_h", prev = _lastSizes[key];
// if (prev !== undefined && prev !== h) addLog("[RSZ] " + label + " " + prev + "→" + h + "px");
// _lastSizes[key] = h;
// }
// });
// diagTargets.forEach(function(d) { if (d.node) ro.observe(d.node); });
// _lockTargets.forEach(function(n) {
// n.addEventListener("scroll", function() {
// if (n.scrollTop !== 0) addLog("[SCR] " + (n.id || n.tagName) + " sT=" + n.scrollTop);
// }, true);
// });
// (function renderDiag() {
// var ps = document.querySelector(".panelLeft .panelScroll");
// var csEl = null;
// try { csEl = document.querySelector(".CodeMirror-scroll"); } catch(_) {}
// var lines = [
// "html.sT=" + document.documentElement.scrollTop,
// "body.sT=" + document.body.scrollTop,
// "grid.sT=" + (el("mainGrid")?.scrollTop || 0),
// "pL.sT=" + (document.querySelector(".panelLeft")?.scrollTop || 0),
// "pR.sT=" + (document.querySelector(".panelRight")?.scrollTop || 0),
// "out.sT=" + (el("output")?.scrollTop || 0),
// "pScroll.sT=" + (ps ? ps.scrollTop : "?"),
// "cmScr.sT=" + (csEl ? csEl.scrollTop : "?"), "---",
// ];
// if (_diagLog.length) lines = lines.concat(_diagLog);
// else lines.push("(no anomalies)");
// box.textContent = lines.join("\n");
// requestAnimationFrame(renderDiag);
// })();
// })();
resetAll();
setOutputDirty(false);
});