-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
753 lines (646 loc) · 26.4 KB
/
script.js
File metadata and controls
753 lines (646 loc) · 26.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
const QUOTES = [
{ text: "Science is simply common sense at its best.", author: "Thomas Huxley" },
{ text: "The important thing is not to stop questioning.", author: "Albert Einstein" },
{ text: "Somewhere, something incredible is waiting to be known.", author: "Carl Sagan" },
{ text: "Research is formalized curiosity.", author: "Zora Neale Hurston" },
{ text: "What we know is a drop, what we don't know is an ocean.", author: "Isaac Newton" },
{ text: "Every brilliant experiment, like every great work of art, starts with an act of imagination.", author: "Jonah Lehrer" },
{ text: "Science is organized knowledge.", author: "Herbert Spencer" },
{ text: "Experiment is the sole judge of scientific truth.", author: "Richard Feynman" }
];
let elements = [];
let dropBuffer = [];
let initialUnlocked = [];
const MAX_DROP = 6; // limit to avoid UI overflow
const infoBox = document.getElementById("infoBox");
const DROP_ZONE_DEFAULT_TEXT = "Drop or tap elements here";
let dropZoneEl = null;
const HISTORY_KEY = "combineHistory";
const MAX_HISTORY = 50;
const FILTER_KEY = "elementFilters";
const TUTORIAL_KEY = "tutorialSeen";
let historyEntries = [];
let filterState = {
query: "",
block: "all",
showUnlocked: true,
showLocked: true
};
document.addEventListener("DOMContentLoaded", () => {
// Fade out splash after 2s
setTimeout(() => {
const opening = document.getElementById("openingAnimation");
if(opening){
opening.classList.add("hidden");
// Remove after transition ends
opening.addEventListener("transitionend", () => opening.remove());
}
}, 2500);
});
function showInfo(el) {
const e = elements.find(x => x.name === el.dataset.name);
if (!e) return;
infoBox.innerHTML = `<strong>${e.name}</strong><br>${e.info || "No description available."}`;
const rect = el.getBoundingClientRect();
infoBox.style.top = `${rect.bottom + window.scrollY + 5}px`;
infoBox.style.left = `${rect.left + window.scrollX}px`;
infoBox.style.opacity = 1;
}
function hideInfo() { infoBox.style.opacity = 0; }
function addHover(el, e) {
el.addEventListener("mouseenter", () => showInfo(el));
el.addEventListener("mouseleave", hideInfo);
}
document.getElementById("revealAllBtn").addEventListener("click", () => {
elements.forEach(e => e.unlocked = true);
renderElements();
saveProgress();
});
function showDropZoneDefault(target = dropZoneEl) {
if (!target) return;
target.dataset.state = "empty";
target.innerHTML = DROP_ZONE_DEFAULT_TEXT;
}
function runOnceAnimation(node, className) {
if (!node) return;
node.classList.remove(className);
// force reflow so animation can restart
void node.offsetWidth;
node.classList.add(className);
node.addEventListener("animationend", () => node.classList.remove(className), { once: true });
}
function createDropClone(elementData) {
const safeName = typeof CSS !== "undefined" && typeof CSS.escape === "function"
? CSS.escape(elementData.name)
: elementData.name.replace(/"/g, '\\"');
const orig = document.querySelector(`.element[data-name="${safeName}"]`);
const clone = orig ? orig.cloneNode(true) : document.createElement("div");
if (!orig) {
const blockClass = elementData.block ? (elementData.block === "none" ? "none-block" : `${elementData.block}-block`) : "";
clone.className = `element ${blockClass}`.trim();
const displayLabel = elementData.symbol || elementData.name || "";
if (blockClass === "none-block" && displayLabel.length > 3) clone.classList.add("long-label");
clone.textContent = displayLabel;
}
clone.classList.remove("locked");
clone.classList.remove("newly-unlocked");
clone.classList.add("drop-element");
clone.style.cursor = "default";
clone.draggable = false;
return clone;
}
function addElementToBuffer(elementData, sourceNode = null) {
if (!elementData || dropBuffer.length >= MAX_DROP || !dropZoneEl) return;
if (dropZoneEl.dataset.state !== "active") {
dropZoneEl.innerHTML = "";
dropZoneEl.dataset.state = "active";
}
dropBuffer.push(elementData);
const clone = createDropClone(elementData);
dropZoneEl.appendChild(clone);
runOnceAnimation(dropZoneEl, "dropzone-pulse");
runOnceAnimation(clone, "buffer-pop");
if (sourceNode) runOnceAnimation(sourceNode, "touch-pulse");
updateDropZone(dropZoneEl);
}
function attachElementInteractions(div, elementData) {
div.draggable = true;
div.addEventListener("dragstart", ev => ev.dataTransfer.setData("text/plain", elementData.name));
let touchStart = null;
div.addEventListener("touchstart", evt => {
if (evt.touches.length !== 1) { touchStart = null; return; }
const touch = evt.touches[0];
touchStart = { x: touch.clientX, y: touch.clientY };
}, { passive: true });
div.addEventListener("touchend", evt => {
if (!touchStart) return;
if (!dropZoneEl) { touchStart = null; return; }
if (!evt.changedTouches || evt.changedTouches.length === 0) { touchStart = null; return; }
const touch = evt.changedTouches[0];
const dx = Math.abs(touch.clientX - touchStart.x);
const dy = Math.abs(touch.clientY - touchStart.y);
touchStart = null;
if (dx > 15 || dy > 15) return; // allow scrolling/dragging
evt.preventDefault();
addElementToBuffer(elementData, div);
}, { passive: false });
div.addEventListener("touchcancel", () => { touchStart = null; });
}
function initQuoteCarousel() {
const quoteText = document.getElementById("quoteText");
const quoteAuthor = document.getElementById("quoteAuthor");
if (!quoteText || !quoteAuthor || QUOTES.length === 0) return;
let index = 0;
const applyQuote = () => {
const { text, author } = QUOTES[index];
quoteText.textContent = `"${text}"`;
quoteAuthor.textContent = author;
index = (index + 1) % QUOTES.length;
};
applyQuote();
setInterval(() => {
quoteText.style.opacity = 0;
quoteAuthor.style.opacity = 0;
setTimeout(() => {
applyQuote();
quoteText.style.opacity = 1;
quoteAuthor.style.opacity = 1;
}, 300);
}, 6000);
}
function loadElementsData() {
if (window.ELEMENTS_DATA && Array.isArray(window.ELEMENTS_DATA.elements)) {
return Promise.resolve(window.ELEMENTS_DATA);
}
return fetch("media/elements.json").then(response => {
if (!response.ok) {
throw new Error(`Failed to load elements data: ${response.status}`);
}
return response.json();
});
}
function loadFilterState() {
const saved = localStorage.getItem(FILTER_KEY);
if (!saved) return;
try {
const parsed = JSON.parse(saved);
filterState = { ...filterState, ...parsed };
} catch (err) {
console.warn("Failed to parse saved filters.", err);
}
}
function isTutorialOpen() {
const overlay = document.getElementById("tutorialOverlay");
return overlay && !overlay.hidden;
}
function showTutorial() {
const overlay = document.getElementById("tutorialOverlay");
if (!overlay) return;
overlay.hidden = false;
overlay.setAttribute("aria-hidden", "false");
document.body.classList.add("tutorial-open");
}
function hideTutorial({ markSeen = true } = {}) {
const overlay = document.getElementById("tutorialOverlay");
if (!overlay) return;
overlay.hidden = true;
overlay.setAttribute("aria-hidden", "true");
document.body.classList.remove("tutorial-open");
if (markSeen) localStorage.setItem(TUTORIAL_KEY, "true");
}
function maybeShowTutorial() {
const seen = localStorage.getItem(TUTORIAL_KEY);
if (!seen) showTutorial();
}
function saveFilterState() {
localStorage.setItem(FILTER_KEY, JSON.stringify(filterState));
}
function syncFilterControls() {
const searchInput = document.getElementById("elementSearch");
const blockFilter = document.getElementById("blockFilter");
const showUnlocked = document.getElementById("showUnlocked");
const showLocked = document.getElementById("showLocked");
if (searchInput) searchInput.value = filterState.query;
if (blockFilter) blockFilter.value = filterState.block;
if (showUnlocked) showUnlocked.checked = filterState.showUnlocked;
if (showLocked) showLocked.checked = filterState.showLocked;
}
function matchesFilter(elementData) {
const query = filterState.query.trim().toLowerCase();
const name = (elementData.name || "").toLowerCase();
const symbol = (elementData.symbol || "").toLowerCase();
const matchesQuery = !query || name.includes(query) || symbol.includes(query);
const matchesBlock = filterState.block === "all" || elementData.block === filterState.block;
const matchesUnlockState = (elementData.unlocked && filterState.showUnlocked) || (!elementData.unlocked && filterState.showLocked);
return matchesQuery && matchesBlock && matchesUnlockState;
}
function updateStatusCounts(matchCount) {
const matchEl = document.getElementById("matchCount");
const progressEl = document.getElementById("progressCount");
if (matchEl) matchEl.textContent = `Showing ${matchCount} / ${elements.length}`;
if (progressEl) {
const unlocked = elements.filter(e => e.unlocked).length;
progressEl.textContent = `Unlocked ${unlocked} / ${elements.length}`;
}
}
function renderElements() {
const container = document.getElementById("periodicGrid");
if (!container) return;
const fragment = document.createDocumentFragment();
const usedCells = new Set();
let matchCount = 0;
const minPeriods = Array(19).fill(null);
elements.forEach(el => {
const col = Number(el.group);
const period = Number(el.period);
if (Number.isNaN(col) || Number.isNaN(period) || col < 1 || col > 18) return;
if (minPeriods[col] === null || period < minPeriods[col]) minPeriods[col] = period;
});
// For each column, find the first (smallest) period where an element exists.
// Place the column number in the last empty cell before that element by
// rendering the header at gridRow = minPeriod (note: element gridRow = period + 1).
for (let c = 1; c <= 18; c++) {
// compute min period for this column among all elements (use Number coercion)
const headerRow = Math.max(1, minPeriods[c] || 1);
const header = document.createElement("div");
header.className = "column-header";
header.style.gridColumn = c;
header.style.gridRow = headerRow; // place above the first element in this column
header.textContent = c;
fragment.appendChild(header);
}
// Add grid spacers (these refer to period rows). Because we keep a header
// position relative to periods, spacers that separate blocks shift to 9 and 12.
for (let i = 1; i <= 18; i++) {
[9, 12].forEach(row => {
const spacer = document.createElement("div");
spacer.className = "grid-spacer";
spacer.style.gridColumn = i;
spacer.style.gridRow = row;
fragment.appendChild(spacer);
});
}
elements
.forEach(e => {
if (!matchesFilter(e)) return;
matchCount += 1;
const cellKey = `${e.period}-${e.group}`;
if (usedCells.has(cellKey)) {
console.warn(`Duplicate cell: ${e.name} at period ${e.period}, group ${e.group}`);
return; // skip or adjust
}
usedCells.add(cellKey);
const div = document.createElement("div");
// map block (s,p,d,f,none) to a CSS class like 's-block'
const blockClass = e.block ? (e.block === "none" ? "none-block" : `${e.block}-block`) : "";
div.className = `element ${blockClass}${!e.unlocked ? " locked" : ""}`;
// if this is a 'none' block and the displayed label is long, add a helper class
const displayLabel = e.symbol || e.name || "";
if (blockClass === 'none-block' && displayLabel.length > 3) {
div.classList.add('long-label');
}
// shift elements down by 1 to account for the header row
div.style.gridColumn = e.group;
div.style.gridRow = (Number(e.period) || 0) + 1;
div.textContent = e.unlocked ? e.symbol : "?";
if (e.unlocked) {
div.dataset.name = e.name;
attachElementInteractions(div, e);
addHover(div, e);
}
fragment.appendChild(div);
});
container.replaceChildren(fragment);
updateStatusCounts(matchCount);
}
function unlockElement(name) {
const e = elements.find(x => x.name === name);
if(e && !e.unlocked){
e.unlocked = true;
saveProgress();
renderElements();
const el = document.querySelector(`.element[data-name="${e.name}"]`);
if(el){ el.classList.add("newly-unlocked"); setTimeout(()=>el.classList.remove("newly-unlocked"),1600); }
}
}
function saveProgress() {
localStorage.setItem("unlockedElements", JSON.stringify(elements.filter(e=>e.unlocked).map(e=>e.name)));
}
function resetProgress() {
localStorage.removeItem("unlockedElements");
elements.forEach(e=>e.unlocked=initialUnlocked.includes(e.name));
renderElements();
const dz = document.getElementById("dropZone");
if (dz) showDropZoneDefault(dz);
const info = document.getElementById("infoBox");
if (info) info.innerHTML = "";
const combineBtn = document.getElementById("combineBtn"); if(combineBtn) combineBtn.style.display="none";
dropBuffer=[];
}
window.resetProgress=resetProgress;
function updateDropZone(dropZone){
const prev=dropZone.querySelector(".placeholder"); if(prev) prev.remove();
if(dropBuffer.length>=1){
const ph=document.createElement("div");
ph.className="placeholder";
ph.textContent = dropBuffer.length===1 ? "+ ____" : `+ ${dropBuffer.length-1} more`;
dropZone.appendChild(ph);
}
const combineBtn=document.getElementById("combineBtn");
if(combineBtn) combineBtn.style.display=(dropBuffer.length>=2?"inline-block":"none");
}
function combineElements(buffer, dropZone){
dropZone.innerHTML = "";
dropZone.dataset.state = "active";
// Show dropped elements visually
buffer.forEach(e => {
const d = document.createElement("div");
const blockClass = e.block ? (e.block === "none" ? "none-block" : `${e.block}-block`) : "";
d.className = `element drop-element ${blockClass}`;
const displayLabel = e.symbol || e.name || "";
if (blockClass === 'none-block' && displayLabel.length > 3) d.classList.add('long-label');
d.textContent = e.symbol;
d.title = `${e.name} (${e.block})`;
d.draggable = false;
dropZone.appendChild(d);
});
// Determine combination result
let current = buffer[0];
let failed = false;
let finalElement = null;
for (let i = 1; i < buffer.length; i++) {
const next = buffer[i];
const resName = (current.combinations && current.combinations[next.name]) ||
(next.combinations && next.combinations[current.name]) || null;
if (!resName) { failed = true; break; }
const resElement = elements.find(x => x.name === resName);
if (!resElement) { failed = true; break; }
current = resElement;
}
if (!failed) finalElement = current;
recordHistory({
inputs: buffer.map(item => item.name),
result: failed || !finalElement ? "No reaction" : finalElement.name,
success: !failed && !!finalElement,
timestamp: Date.now()
});
// Particle explosion
const dzRect = dropZone.getBoundingClientRect();
const particleCount = Math.min(80, 60 + (buffer.length - 2) * 8);
const particleDistance = 110 + (buffer.length - 2) * 24;
const speed = 2;
for (let i = 0; i < particleCount; i++) {
const p = document.createElement("div");
p.className = `particle ${failed ? "fail" : "success"}`;
if (failed) {
// Randomly choose red/orange/yellow
const colors = ["#ff3838","#ff9933","#ffdd00"];
const color = colors[Math.floor(Math.random() * colors.length)];
p.style.color = color;
p.style.backgroundColor = color;
p.style.animation = `flyParticle ${speed}s ease forwards`;
}
// Random direction within distance scaled by buffer length
const angle = Math.random() * 2 * Math.PI;
const distance = particleDistance * Math.random();
const x = Math.cos(angle) * distance;
const y = Math.sin(angle) * distance;
p.style.setProperty("--x", `${x}px`);
p.style.setProperty("--y", `${y}px`);
// Center position
p.style.left = `${dzRect.width / 2}px`;
p.style.top = `${dzRect.height / 2}px`;
p.style.animation = `flyParticle 0.8s ease forwards`;
dropZone.appendChild(p);
setTimeout(() => p.remove(), 800);
}
// Shake body if failed
if (failed) {
document.body.classList.add("shake");
setTimeout(() => document.body.classList.remove("shake"), 500);
}
// Optional feedback text scaled by elements
const msgDiv = document.createElement("div");
msgDiv.textContent = !failed ? "✔ New Element Discovered!" : "❌ No Reaction";
msgDiv.style.textShadow = !failed ? "" : "2px 2px 0 white, -2px -2px 0 white, 2px -2px 0 white, -2px 2px 0 white";
msgDiv.className = !failed ? "explosion-success" : "explosion-fail";
msgDiv.style.transform = `scale(${1 + 0.2 * (buffer.length - 2)})`;
msgDiv.style.left = `${dzRect.width/2 - 50}px`;
msgDiv.style.top = `${dzRect.height/2 - 25}px`;
dropZone.appendChild(msgDiv);
// Clear drop zone after animation
setTimeout(() => {
msgDiv.remove();
if (!failed && finalElement) unlockElement(finalElement.name);
showDropZoneDefault(dropZone);
const btn = document.getElementById("combineBtn");
if (btn) btn.style.display = "none";
}, 1200);
dropBuffer = [];
}
function spawnParticles(dropZone, type = "success", elementCount = 2) {
const dzRect = dropZone.getBoundingClientRect();
// Base particle count, scale with number of elements
const count = 50 + (elementCount - 2) * 30; // 10 for 2 elements, +5 for each extra
for (let i = 0; i < count; i++) {
const p = document.createElement("div");
p.className = `particle ${type}`;
// Random X/Y movement
const x = (Math.random() - 0.9) * 50 * elementCount; // scale distance by elementCount
const y = (Math.random() - 0.9) * 50 * elementCount;
p.style.setProperty("--x", `${x}px`);
p.style.setProperty("--y", `${y}px`);
// Position at center
p.style.left = `${dzRect.width / 2}px`;
p.style.top = `${dzRect.height / 2}px`;
// Animate
p.style.animation = `flyParticle 0.8s ease forwards`;
dropZone.appendChild(p);
// Remove after animation
setTimeout(() => p.remove(), 800);
}
}
function loadHistory() {
const saved = localStorage.getItem(HISTORY_KEY);
if (!saved) return;
try {
const parsed = JSON.parse(saved);
if (Array.isArray(parsed)) historyEntries = parsed;
} catch (err) {
console.warn("Failed to parse history.", err);
}
}
function saveHistory() {
localStorage.setItem(HISTORY_KEY, JSON.stringify(historyEntries));
}
function recordHistory(entry) {
historyEntries.unshift(entry);
if (historyEntries.length > MAX_HISTORY) {
historyEntries = historyEntries.slice(0, MAX_HISTORY);
}
saveHistory();
renderHistory();
}
function renderHistory() {
const list = document.getElementById("historyList");
if (!list) return;
list.innerHTML = "";
if (!historyEntries.length) {
const empty = document.createElement("li");
empty.className = "history-empty";
empty.textContent = "No combinations yet.";
list.appendChild(empty);
return;
}
historyEntries.forEach(entry => {
const li = document.createElement("li");
li.className = entry.success ? "history-item success" : "history-item fail";
const inputs = document.createElement("span");
inputs.className = "history-inputs";
inputs.textContent = entry.inputs.join(" + ");
const arrow = document.createElement("span");
arrow.className = "history-arrow";
arrow.textContent = "→";
const result = document.createElement("span");
result.className = "history-result";
result.textContent = entry.result;
const time = document.createElement("span");
time.className = "history-time";
const date = new Date(entry.timestamp);
time.textContent = date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
li.appendChild(inputs);
li.appendChild(arrow);
li.appendChild(result);
li.appendChild(time);
list.appendChild(li);
});
}
document.addEventListener("DOMContentLoaded",()=>{
setTimeout(()=>{ const ov=document.getElementById("openingAnimation"); if(ov) {ov.style.opacity=0; setTimeout(()=>ov.remove(),600); }},2000);
initQuoteCarousel();
loadFilterState();
syncFilterControls();
loadHistory();
renderHistory();
loadElementsData()
.then(d => {
elements = d.elements;
initialUnlocked = elements.filter(e => e.unlocked).map(e => e.name);
const saved = JSON.parse(localStorage.getItem("unlockedElements")) || [];
elements.forEach(e => { if (saved.includes(e.name)) e.unlocked = true; });
renderElements();
})
.catch(err => {
console.error("Elements data failed to load.", err);
});
const tutorialBtn = document.getElementById("tutorialBtn");
const closeTutorialBtn = document.getElementById("closeTutorialBtn");
const tutorialOverlay = document.getElementById("tutorialOverlay");
if (tutorialBtn) {
tutorialBtn.addEventListener("click", () => showTutorial());
}
if (closeTutorialBtn) {
closeTutorialBtn.addEventListener("click", () => hideTutorial());
}
if (tutorialOverlay) {
tutorialOverlay.addEventListener("click", event => {
if (event.target === tutorialOverlay) hideTutorial();
});
}
maybeShowTutorial();
const searchInput = document.getElementById("elementSearch");
const blockFilter = document.getElementById("blockFilter");
const showUnlocked = document.getElementById("showUnlocked");
const showLocked = document.getElementById("showLocked");
const clearFiltersBtn = document.getElementById("clearFiltersBtn");
const shortcutHelpBtn = document.getElementById("shortcutHelpBtn");
const shortcutHelp = document.getElementById("shortcutHelp");
const debounce = (fn, delay = 200) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
};
if (searchInput) {
searchInput.addEventListener("input", debounce(event => {
filterState.query = event.target.value || "";
saveFilterState();
renderElements();
}));
}
if (blockFilter) {
blockFilter.addEventListener("change", event => {
filterState.block = event.target.value;
saveFilterState();
renderElements();
});
}
if (showUnlocked) {
showUnlocked.addEventListener("change", event => {
filterState.showUnlocked = event.target.checked;
saveFilterState();
renderElements();
});
}
if (showLocked) {
showLocked.addEventListener("change", event => {
filterState.showLocked = event.target.checked;
saveFilterState();
renderElements();
});
}
if (clearFiltersBtn) {
clearFiltersBtn.addEventListener("click", () => {
filterState = { query: "", block: "all", showUnlocked: true, showLocked: true };
saveFilterState();
syncFilterControls();
renderElements();
});
}
if (shortcutHelpBtn && shortcutHelp) {
shortcutHelpBtn.addEventListener("click", () => {
shortcutHelp.hidden = !shortcutHelp.hidden;
});
}
const clearHistoryBtn = document.getElementById("clearHistoryBtn");
if (clearHistoryBtn) {
clearHistoryBtn.addEventListener("click", () => {
historyEntries = [];
saveHistory();
renderHistory();
});
}
dropZoneEl=document.getElementById("dropZone");
if(!dropZoneEl) return;
showDropZoneDefault(dropZoneEl);
dropZoneEl.addEventListener("dragover",e=>{ e.preventDefault(); dropZoneEl.classList.add("hover"); });
dropZoneEl.addEventListener("dragleave",()=>dropZoneEl.classList.remove("hover"));
dropZoneEl.addEventListener("drop",e=>{
e.preventDefault(); dropZoneEl.classList.remove("hover");
const name=e.dataTransfer.getData("text/plain");
const el=elements.find(x=>x.name===name);
addElementToBuffer(el);
});
const combineBtn=document.getElementById("combineBtn");
if(combineBtn){ combineBtn.style.display="none"; combineBtn.addEventListener("click",()=>{ if(dropBuffer.length<2) return alert("Drop two or more elements to combine!"); combineElements(dropBuffer,dropZoneEl);}); }
const isTypingTarget = target => {
if (!target) return false;
const tag = target.tagName;
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";
};
document.addEventListener("keydown", event => {
if (isTutorialOpen()) {
if (event.key === "Escape") {
hideTutorial();
}
return;
}
if (isTypingTarget(event.target)) {
if (event.key === "Escape" && searchInput) {
searchInput.value = "";
filterState.query = "";
saveFilterState();
renderElements();
searchInput.blur();
}
return;
}
if (event.key === "Enter" && dropBuffer.length >= 2) {
event.preventDefault();
combineElements(dropBuffer, dropZoneEl);
}
if ((event.key === "r" || event.key === "R") && typeof resetProgress === "function") {
resetProgress();
}
if ((event.key === "f" || event.key === "F") && searchInput) {
searchInput.focus();
}
if (event.key === "Escape" && searchInput) {
searchInput.value = "";
filterState.query = "";
saveFilterState();
renderElements();
}
});
});