forked from clickysteve/dmg-darkroom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
6880 lines (6075 loc) · 279 KB
/
Copy pathapp.js
File metadata and controls
6880 lines (6075 loc) · 279 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
/**
* app.js — MugDump renderer
*
* Dependencies (loaded via script tags before this file):
* - gbcam.js → window.GBCam
* - palettes.js → window.PALETTES, window.paletteToRGB
*/
const APP_VERSION = '0.10'; // keep in sync with package.json "version" and the other app.js copy
// ── Border frames ─────────────────────────────────────────────────────────────
const BORDER_FRAMES = [
{ id: 'int-frame-0', label: '1' },
{ id: 'int-frame-1', label: '2' },
{ id: 'int-frame-2', label: '3' },
{ id: 'int-frame-3', label: '4' },
{ id: 'int-frame-4', label: '5' },
{ id: 'int-frame-5', label: '6' },
{ id: 'int-frame-6', label: '7' },
{ id: 'int-frame-7', label: '8' },
{ id: 'int-frame-8', label: '9' },
{ id: 'int-frame-9', label: '10' },
{ id: 'int-frame-10', label: '11' },
{ id: 'int-frame-11', label: '12' },
{ id: 'int-frame-12', label: '13' },
{ id: 'int-frame-13', label: '14' },
{ id: 'int-frame-14', label: '15' },
{ id: 'int-frame-15', label: '16' },
{ id: 'int-frame-16', label: '17' },
{ id: 'int-frame-17', label: '18' },
{ id: 'jp-frame-0', label: 'JP 1' },
{ id: 'jp-frame-1', label: 'JP 2' },
{ id: 'jp-frame-6', label: 'JP 3' },
];
const _borderImageCache = {}; // id → HTMLImageElement (loaded)
function preloadBorderImages() {
BORDER_FRAMES.forEach(({ id }) => {
const img = new Image();
img.onload = () => { _borderImageCache[id] = img; };
img.onerror = () => console.warn(`Border frame not found: ${id}`);
img.src = `frames/${id}.png`;
});
}
/**
* Returns a 160×144 canvas with border pixels colorized to the given palette.
* Photo area (x 16-143, y 16-127) remains transparent.
* Returns null if the image hasn't loaded yet.
*/
function getColorizedBorderCanvas(borderId, palette) {
const img = _borderImageCache[borderId];
if (!img) return null;
const raw = document.createElement('canvas');
raw.width = 160;
raw.height = 144;
const rawCtx = raw.getContext('2d', { willReadFrequently: true });
rawCtx.drawImage(img, 0, 0);
const imageData = rawCtx.getImageData(0, 0, 160, 144);
const d = imageData.data;
const rgb = window.paletteToRGB(palette); // [[r,g,b]×4] — index 0=lightest, 3=darkest
// Photo window bounds in the 160×144 frame (pixels here stay transparent so the photo shows through)
const PX1 = 16, PX2 = 143, PY1 = 16, PY2 = 127;
for (let i = 0; i < d.length; i += 4) {
if (d[i + 3] === 0) {
// Transparent pixel — check whether it's the photo window or a border area
const pidx = i / 4;
const px = pidx % 160;
const py = Math.floor(pidx / 160);
if (px >= PX1 && px <= PX2 && py >= PY1 && py <= PY2) {
// Inside photo window — leave transparent so the photo beneath shows through
continue;
}
// Outside photo window (e.g. film-strip perforations): fill with darkest palette colour
// so they look the same in exports as they do in the preview (dark page background).
const [pr, pg, pb] = rgb[3];
d[i] = pr; d[i + 1] = pg; d[i + 2] = pb; d[i + 3] = 255;
continue;
}
// Non-transparent border pixel — colorize based on brightness
const R = d[i];
const gbIdx = Math.min(3, Math.max(0, Math.round((255 - R) * 3 / 255)));
const [pr, pg, pb] = rgb[gbIdx];
d[i] = pr; d[i + 1] = pg; d[i + 2] = pb; d[i + 3] = 255;
}
rawCtx.putImageData(imageData, 0, 0);
return raw;
}
/**
* Render a photo with an optional GB Camera border frame.
* Falls through to renderPhotoWithTransform when borderId is 'none'.
* When a border is active the canvas becomes 160×144×scale.
* eff must contain { palette, borderId }.
*/
function renderPhotoWithBorder(ctx, photo, eff, scale, idx) {
const borderEnabled = eff.borderEnabled && eff.borderId;
const borderId = borderEnabled ? eff.borderId : 'none';
if (borderId === 'none') {
renderPhotoWithTransform(ctx, photo, eff.palette, scale, idx);
return;
}
const BW = 160 * scale;
const BH = 144 * scale;
const OX = 16 * scale;
const OY = 16 * scale;
ctx.canvas.width = BW;
ctx.canvas.height = BH;
ctx.clearRect(0, 0, BW, BH);
// Draw photo (with any transform) into the photo area slot
const tmpPhoto = document.createElement('canvas');
const tmpCtx = tmpPhoto.getContext('2d');
renderPhotoWithTransform(tmpCtx, photo, eff.palette, scale, idx);
ctx.drawImage(tmpPhoto, OX, OY);
// Overlay colorised border (transparent centre reveals photo)
const borderBase = getColorizedBorderCanvas(borderId, eff.palette);
if (borderBase) {
ctx.imageSmoothingEnabled = false;
ctx.drawImage(borderBase, 0, 0, BW, BH);
}
}
/**
* Full render pipeline for a photo: composite → effects → tone.
* Handles both 'full' scope (effects apply to border+photo) and
* 'photo' scope (effects applied to photo area only before border composite).
*
* Replaces the pattern: renderPhotoWithBorder + applyActiveEffects + applyToneAdjustments
* at every call site.
*
* opts.thumbMode — omit THUMBNAIL_SKIP_FILTERS (for grid thumbnails)
* opts.forExport — pass forExport=true to effects/tone functions
*/
function renderPhotoComplete(ctx, photo, eff, scale, idx, opts = {}) {
const { thumbMode = false, forExport = false } = opts;
const borderEnabled = eff.borderEnabled && eff.borderId;
const photoScopeOnly = eff.filterScope === 'photo' && borderEnabled;
// Build the filter set (thumbnail mode skips slow filters)
let filtersToApply = eff.activeFilters;
if (thumbMode && filtersToApply.size > 0) {
filtersToApply = new Set([...filtersToApply].filter(id => !THUMBNAIL_SKIP_FILTERS.has(id)));
}
if (photoScopeOnly) {
// Photo-scope: apply effects+tone to the raw 128×112 photo canvas,
// then composite it behind a clean border.
const BW = 160 * scale;
const BH = 144 * scale;
ctx.canvas.width = BW;
ctx.canvas.height = BH;
ctx.clearRect(0, 0, BW, BH);
const tmpPhoto = document.createElement('canvas');
const tmpCtx = tmpPhoto.getContext('2d', { willReadFrequently: true });
renderPhotoWithTransform(tmpCtx, photo, eff.palette, scale, idx);
const PW = tmpPhoto.width;
const PH = tmpPhoto.height;
if (filtersToApply.size > 0) {
applyActiveEffects(tmpCtx, PW, PH, scale, eff.filterIntensity, eff.filterVariant,
eff.filterParams, filtersToApply, forExport, idx);
}
applyToneAdjustments(tmpCtx, PW, PH, eff, forExport);
ctx.drawImage(tmpPhoto, 16 * scale, 16 * scale);
const borderBase = getColorizedBorderCanvas(eff.borderId, eff.palette);
if (borderBase) {
ctx.imageSmoothingEnabled = false;
ctx.drawImage(borderBase, 0, 0, BW, BH);
}
} else {
// Full-scope (default): render photo+border composite first,
// then apply effects+tone to the full canvas.
renderPhotoWithBorder(ctx, photo, eff, scale, idx);
const W = ctx.canvas.width;
const H = ctx.canvas.height;
if (filtersToApply.size > 0) {
applyActiveEffects(ctx, W, H, scale, eff.filterIntensity, eff.filterVariant,
eff.filterParams, filtersToApply, forExport, idx);
}
applyToneAdjustments(ctx, W, H, eff, forExport);
}
}
// ── Color picker helpers ───────────────────────────────────────────────────
function hexToHsl(hex) {
const r = parseInt(hex.slice(1,3), 16) / 255;
const g = parseInt(hex.slice(3,5), 16) / 255;
const b = parseInt(hex.slice(5,7), 16) / 255;
const max = Math.max(r,g,b), min = Math.min(r,g,b);
let h = 0, s = 0;
const l = (max + min) / 2;
if (max !== min) {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
case g: h = ((b - r) / d + 2) / 6; break;
case b: h = ((r - g) / d + 4) / 6; break;
}
}
return [Math.round(h * 360), Math.round(s * 100), Math.round(l * 100)];
}
function hslToHex(h, s, l) {
h /= 360; s /= 100; l /= 100;
let r, g, b;
if (s === 0) {
r = g = b = l;
} else {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1; if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
};
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return '#' + [r, g, b].map(x => Math.round(x * 255).toString(16).padStart(2, '0')).join('');
}
let _colorPickerPanel = null;
function openColorPicker(anchorEl, initialHex, onChange) {
if (_colorPickerPanel) { _colorPickerPanel.remove(); _colorPickerPanel = null; }
let [h, s, l] = hexToHsl(initialHex || '#888888');
const panel = document.createElement('div');
panel.className = 'color-picker-panel';
_colorPickerPanel = panel;
const preview = document.createElement('div');
preview.className = 'cp-preview';
preview.style.background = initialHex;
panel.appendChild(preview);
const hexInput = document.createElement('input');
hexInput.type = 'text';
hexInput.className = 'cp-hex-input';
hexInput.value = initialHex.toUpperCase();
hexInput.maxLength = 7;
function update() {
const hex = hslToHex(h, s, l);
preview.style.background = hex;
hexInput.value = hex.toUpperCase();
onChange(hex);
}
function makeRow(labelTxt, val, min, max, onSliderChange) {
const row = document.createElement('div');
row.className = 'cp-slider-row';
const lbl = document.createElement('span');
lbl.className = 'cp-slider-label';
lbl.textContent = labelTxt;
const sl = document.createElement('input');
sl.type = 'range'; sl.min = min; sl.max = max; sl.step = 1; sl.value = val;
const valEl = document.createElement('span');
valEl.className = 'cp-slider-val';
valEl.textContent = Math.round(val);
sl.addEventListener('input', () => {
valEl.textContent = sl.value;
onSliderChange(parseFloat(sl.value));
});
row.appendChild(lbl); row.appendChild(sl); row.appendChild(valEl);
return row;
}
panel.appendChild(makeRow('H', h, 0, 360, v => { h = v; update(); }));
panel.appendChild(makeRow('S', s, 0, 100, v => { s = v; update(); }));
panel.appendChild(makeRow('L', l, 0, 100, v => { l = v; update(); }));
hexInput.addEventListener('change', () => {
const v = hexInput.value.trim();
if (/^#[0-9a-fA-F]{6}$/.test(v)) {
[h, s, l] = hexToHsl(v);
update();
}
});
panel.appendChild(hexInput);
document.body.appendChild(panel);
const rect = anchorEl.getBoundingClientRect();
panel.style.left = `${Math.min(rect.left, window.innerWidth - 230)}px`;
panel.style.top = `${Math.min(rect.bottom + 4, window.innerHeight - 250)}px`;
setTimeout(() => {
function closeHandler(e) {
if (!panel.contains(e.target) && e.target !== anchorEl) {
panel.remove();
if (_colorPickerPanel === panel) _colorPickerPanel = null;
document.removeEventListener('mousedown', closeHandler);
}
}
document.addEventListener('mousedown', closeHandler);
}, 0);
}
/** Wraps a hidden <input type=color> with a visible swatch button that opens
* the custom picker. Pass the className for the swatch button. */
function attachColorPickerToInput(input, swatchClass = 'color-swatch-btn') {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = swatchClass;
btn.style.background = input.value;
input.parentNode.insertBefore(btn, input);
btn.addEventListener('click', e => {
e.stopPropagation();
openColorPicker(btn, input.value, hex => {
btn.style.background = hex;
input.value = hex;
input.dispatchEvent(new Event('input', { bubbles: true }));
});
});
// Keep swatch in sync if input is updated programmatically
const origDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
Object.defineProperty(input, '_cpBtn', { value: btn, writable: true });
return btn;
}
// Sync a swatch button to a new value (called when controls are reset/synced)
function syncColorSwatchBtn(input, hex) {
if (input._cpBtn) input._cpBtn.style.background = hex;
}
const THUMB_SCALE = 4; // grid thumbnails rendered at 4× — fixed scale
// Pixel-dense effects that look garbled / shift on mouseover at thumbnail scale.
// These are skipped during grid repaint — they'll still apply in solo/export views.
const THUMBNAIL_SKIP_FILTERS = new Set(); // all filters render in thumbnails (4× scale is sufficient)
// ── Filter definitions (single source of truth for UI + defaults) ─────────
const FILTER_DEFS = [
{ id: 'crt', label: 'CRT Scanlines', params: [
{ type: 'seg', key: 'variant', label: 'Scanlines', def: 'medium', stateKey: 'filterVariant', opts: [['fine','Fine'],['medium','Medium'],['thick','Thick'],['wide','Wide']] },
{ type: 'seg', key: 'curve', label: 'Screen shape', def: 'none', opts: [['none','Flat'],['mild','Mild'],['strong','Strong']] },
{ type: 'range', key: 'mix', label: 'Mix', def: 100, min: 0, max: 100, step: 1, fmt: v => `${v}%` },
]},
{ id: 'lcd', label: 'LCD', params: [
{ type: 'range', key: 'subpixel', label: 'Sub-pixel tint', def: 30, min: 0, max: 80, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'bleed', label: 'Backlight bleed', def: 0, min: 0, max: 80, step: 1, fmt: v => `${v}%` },
]},
{ id: 'glow', label: 'Phosphor Glow', params: [
{ type: 'range', key: 'intensity', label: 'Intensity', def: 80, min: 0, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'blur', label: 'Bloom radius', def: 110, min: 0, max: 300, step: 5, fmt: v => `${v}%` },
{ type: 'seg', key: 'phosphor', label: 'Phosphor colour', def: 'none', opts: [['none','None'],['green','Green'],['amber','Amber'],['blue','Blue']] },
]},
{ id: 'vignette', label: 'Vignette', params: [
{ type: 'range', key: 'falloff', label: 'Intensity', def: 50, min: 0, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'shape', label: 'Shape', def: 0, min: 0, max: 100, step: 1, fmt: v => v <= 5 ? 'Round' : v >= 95 ? 'Square' : `${v}%` },
]},
{ id: 'halftone', label: 'Halftone', params: [
{ type: 'range', key: 'radius', label: 'Dot size', def: 38, min: 10, max: 70, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'darkness', label: 'Darkness', def: 35, min: 0, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'seg', key: 'shape', label: 'Dot shape', def: 'circle', opts: [['circle','Round'],['square','Square'],['diamond','Diamond']] },
]},
{ id: 'dot', label: 'Dot Matrix', params: [
{ type: 'range', key: 'radius', label: 'Dot size', def: 44, min: 20, max: 80, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'halation', label: 'Halation', def: 0, min: 0, max: 80, step: 1, fmt: v => `${v}%` },
]},
{ id: 'chroma', label: 'Chromatic Aberration', params: [
{ type: 'range', key: 'shiftH', label: 'Horizontal shift', def: 75, min: 0, max: 500, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'shiftV', label: 'Vertical shift', def: 0, min: 0, max: 500, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'shiftR', label: 'Radial shift', def: 0, min: -500, max: 500, step: 1, fmt: v => `${v}%` },
]},
{ id: 'grid', label: 'Pixel Grid', params: [
{ type: 'range', key: 'opacity', label: 'Grid opacity', def: 30, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'weight', label: 'Line weight', def: 1, min: 1, max: 5, step: 0.5, fmt: v => `${v}px` },
]},
{ id: 'jitter', label: 'Scanline Jitter', params: [
{ type: 'range', key: 'amount', label: 'Jitter amount', def: 40, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'frequency', label: 'Frequency', def: 50, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
]},
{ id: 'noise', label: 'Noise / Static', params: [
{ type: 'range', key: 'amount', label: 'Amount', def: 40, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'seg', key: 'type', label: 'Type', def: 'film', opts: [['film','Film'],['static','Static'],['bands','Bands']] },
]},
{ id: 'ghosting', label: 'VHS Ghosting', params: [
{ type: 'range', key: 'offset', label: 'Echo offset', def: 60, min: 1, max: 150, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'fade', label: 'Echo fade', def: 70, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
]},
{ id: 'pixsort', label: 'Pixel Sort', params: [
{ type: 'range', key: 'threshold', label: 'Threshold', def: 50, min: 0, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'seg', key: 'direction', label: 'Direction', def: 'down', opts: [['down','Down'],['up','Up'],['right','Right'],['left','Left']] },
]},
{ id: 'blkglitch', label: 'Block Glitch', params: [
{ type: 'range', key: 'shift', label: 'Shift amount', def: 40, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'density', label: 'Block count', def: 30, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'size', label: 'Block height', def: 20, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'maxheight', label: 'Max height', def: 30, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
]},
{ id: 'wavewarp', label: 'Wave Warp', params: [
{ type: 'range', key: 'amplitude', label: 'Amplitude', def: 30, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'frequency', label: 'Frequency', def: 40, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
]},
{ id: 'zoomblur', label: 'Zoom Blur', params: [
{ type: 'range', key: 'amount', label: 'Amount', def: 30, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
]},
{ id: 'bayer', label: 'Bayer Dithering', params: [
{ type: 'range', key: 'levels', label: 'Color levels', def: 4, min: 2, max: 8, step: 1, fmt: v => `${v}` },
]},
{ id: 'floyd', label: 'Floyd-Steinberg', params: [
{ type: 'range', key: 'levels', label: 'Levels', def: 2, min: 2, max: 8, step: 1, fmt: v => `${v}` },
]},
{ id: 'interlace', label: 'Interlace', params: [
{ type: 'range', key: 'intensity', label: 'Intensity', def: 60, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
]},
{ id: 'chswap', label: 'Channel Swap', params: [
{ type: 'seg', key: 'mode', label: 'Mode', def: 'rgb', opts: [['rgb','RGB'],['rbg','RBG'],['grb','GRB'],['gbr','GBR'],['brg','BRG'],['bgr','BGR']] },
]},
{ id: 'rgbplanes', label: 'RGB Planes', params: [
{ type: 'range', key: 'shift', label: 'Channel split', def: 50, min: 1, max: 300, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'scatter', label: 'Row scatter', def: 40, min: 0, max: 100, step: 1, fmt: v => `${v}%` },
]},
{ id: 'colcorrupt', label: 'Color Corrupt', params: [
{ type: 'range', key: 'density', label: 'Density', def: 35, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
{ type: 'range', key: 'strength', label: 'Strength', def: 65, min: 1, max: 100, step: 1, fmt: v => `${v}%` },
]},
];
// ── Effect families ─────────────────────────────────────────────────────────
// Pixel-perfect keeps the crisp GB look; Retro softens like a screen; Glitch
// deliberately distorts. Pixel-perfect is open by default, the others collapsed.
const FX_GROUP_ORDER = ['crisp', 'retro', 'glitch'];
const FX_GROUP_LABELS = { crisp: 'Pixel-perfect', retro: 'Retro display', glitch: 'Glitch & corrupt' };
const FX_FILTER_GROUP = {
grid: 'crisp', dot: 'crisp', halftone: 'crisp', bayer: 'crisp', floyd: 'crisp', chswap: 'crisp',
crt: 'retro', lcd: 'retro', glow: 'retro', vignette: 'retro', interlace: 'retro',
chroma: 'glitch', noise: 'glitch', ghosting: 'glitch', jitter: 'glitch', zoomblur: 'glitch',
pixsort: 'glitch', blkglitch: 'glitch', wavewarp: 'glitch', rgbplanes: 'glitch', colcorrupt: 'glitch',
};
const FX_COLLAPSE_KEY = 'mugdump:fxgroups';
function getCollapsedFxGroups() {
const stored = localStorage.getItem(FX_COLLAPSE_KEY);
if (stored === null) return new Set(['retro', 'glitch']); // default: only Pixel-perfect open
try { return new Set(JSON.parse(stored)); } catch (_) { return new Set(['retro', 'glitch']); }
}
function setFxGroupCollapsed(g, collapsed) {
const set = getCollapsedFxGroups();
if (collapsed) set.add(g); else set.delete(g);
try { localStorage.setItem(FX_COLLAPSE_KEY, JSON.stringify([...set])); } catch (_) {}
}
function makeFxGroupHeader(g, collapsed) {
const h = document.createElement('div');
h.className = 'fi-group-header' + (collapsed ? ' collapsed' : '');
h.dataset.group = g;
const chevron = document.createElement('span');
chevron.className = 'fi-group-chevron';
chevron.textContent = '▾';
const label = document.createElement('span');
label.className = 'fi-group-label';
label.textContent = FX_GROUP_LABELS[g] || g;
const dot = document.createElement('span');
dot.className = 'fi-group-dot';
dot.title = 'An effect in this group is active';
h.appendChild(chevron); h.appendChild(label); h.appendChild(dot);
h.addEventListener('click', () => {
const nowCollapsed = !h.classList.contains('collapsed');
h.classList.toggle('collapsed', nowCollapsed);
setFxGroupCollapsed(g, nowCollapsed);
document.querySelectorAll(`#filter-accordion .fi-item[data-group="${g}"]`)
.forEach(it => { it.style.display = nowCollapsed ? 'none' : ''; });
});
return h;
}
function buildDefaultFilterParams() {
const out = {};
for (const fd of FILTER_DEFS) {
out[fd.id] = {};
for (const p of fd.params) {
if (p.stateKey) continue; // handled in state directly (e.g. filterVariant)
out[fd.id][p.key] = p.def;
}
}
return out;
}
// ── State ──────────────────────────────────────────────────────────────────
const state = {
sav: null, // raw Uint8Array of the loaded .sav
photos: [], // parsed photo objects from GBCam.parseSav
activeCount: 0,
filename: null,
filePath: null,
selectedIndex: null, // currently selected photo index (0–29)
palette: PALETTES.dmg,
exportScale: 20,
exportFormat: 'png', // 'png' | 'gif'
exportFilter: 'none', // legacy single-filter field; kept for backwards compat with old .gbcp files
filterIntensity: 1.0, // 0.0–1.0
filterVariant: 'medium', // crt only: 'fine'|'medium'|'thick'|'wide'
filterParams: buildDefaultFilterParams(), // per-filter granular parameters (see FILTER_DEFS)
photoTransforms: {}, // { photoIndex: { rotate: 0, flipH: false, flipV: false } }
hideEmpty: false, // whether to collapse empty grid slots
presentationMode: false, // fullscreen presentation overlay active
gifMode: false, // are we in GIF selection mode?
gifSelection: new Set(), // photo indices in the sequence (for O(1) grid highlight)
gifFrameOrder: [], // [{photoIndex, paletteId}] — ordered frame list
gifPaletteScope: null, // null=global; number=frame order index being re-palettted
gifDelay: 250, // ms per frame
gifLoop: 'infinite', // 'infinite' | 'once' | 'bounce'
activeFilters: new Set(), // active filter names for stackable effects
sectionEnabled: { exposure: false, splitTone: false, effects: false }, // per-section on/off (off by default)
effectsPreviewMode: false, // toggle before/after for effects; false = effects visible (normal rendering)
filterOrder: ['crt', 'lcd', 'grid', 'vignette', 'halftone', 'dot', 'glow', 'chroma', 'jitter', 'noise', 'ghosting', 'pixsort', 'blkglitch', 'wavewarp', 'zoomblur', 'bayer', 'floyd', 'interlace', 'chswap', 'rgbplanes', 'colcorrupt'],
gifPreviewTimer: null, // setInterval handle for live GIF preview
lightboxOpen: false, // lightbox overlay visible
viewMode: 'grid', // 'grid' | 'solo'
applyScope: 'all', // 'all' | 'photo' — whether controls write to global or this photo
photoSettings: {}, // { [photoIndex]: { paletteId?, exportFilter?, filterIntensity?, filterVariant?, filterParams?, brightness?, contrast?, toneIntensity?, shadowColor?, highlightColor?, toneBalance? } }
// Tone adjustments
brightness: 0, // -100 to +100
contrast: 0, // -100 to +100
toneIntensity: 0, // 0–100 (split toning strength)
shadowColor: '#0033aa',
highlightColor: '#ff8800',
toneBalance: 0, // -100 (more shadow) to +100 (more highlight)
selectedPhotos: new Set(), // indices of currently selected photos (multi)
lastSelectedIndex: null, // last clicked photo index, for shift-range
focusedFilter: null, // which filter's param panel is open
effectClipboard: null, // copied effect settings for paste
borderId: 'int-frame-0', // global border frame id
borderEnabled: false, // global border on/off
filterScope: 'full', // 'full' = filters apply to border+photo; 'photo' = photo area only
};
// ── DOM refs ───────────────────────────────────────────────────────────────
const dom = {
app: document.getElementById('app'),
welcome: document.getElementById('welcome'),
main: document.getElementById('main'),
photoGrid: document.getElementById('photo-grid'),
gridPanel: document.getElementById('grid-panel'),
detailEmpty: document.getElementById('detail-empty'),
exportControls: document.getElementById('export-controls'),
gifPreviewWrap: document.getElementById('gif-preview-wrap'),
gifPreviewCanvas:document.getElementById('gif-preview-canvas'),
gifPreviewInfo: document.getElementById('gif-preview-info'),
lbOverlay: document.getElementById('lightbox-overlay'),
lbCanvas: document.getElementById('lb-canvas'),
lbLabel: document.getElementById('lb-label'),
lbMeta: document.getElementById('lb-meta'),
soloView: document.getElementById('solo-view'),
soloCanvas: document.getElementById('solo-canvas'),
soloLabel: document.getElementById('solo-label'),
soloMeta: document.getElementById('solo-meta'),
gifToolbar: document.getElementById('gif-toolbar'),
gifFrameStrip: document.getElementById('gif-frame-strip'),
gifFrameList: document.getElementById('gif-frame-list'),
gifFrameEmpty: document.getElementById('gif-frame-empty'),
gifCount: document.getElementById('gif-count'),
gifDelay: document.getElementById('gif-delay'),
gifDelayVal: document.getElementById('gif-delay-val'),
statusText: document.getElementById('status-text'),
statusDot: document.getElementById('status-dot'),
pocketModal: document.getElementById('pocket-modal'),
pocketSaveList: document.getElementById('pocket-save-list'),
pocketConfirm: document.getElementById('pocket-confirm'),
toast: document.getElementById('toast'),
dropOverlay: document.getElementById('drop-overlay'),
presentationOverlay:document.getElementById('presentation-overlay'),
presCanvas: document.getElementById('pres-canvas'),
presLabel: document.getElementById('pres-label'),
presClose: document.getElementById('pres-close'),
presPrev: document.getElementById('pres-prev'),
presNext: document.getElementById('pres-next'),
};
// ── Toast ───────────────────────────────────────────────────────────────────
let toastTimer;
function showToast(msg) {
dom.toast.textContent = msg;
dom.toast.classList.add('visible');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => dom.toast.classList.remove('visible'), 2500);
}
// ── Per-photo settings helpers ─────────────────────────────────────────────
/** Returns a merged settings object for rendering photo at `index`.
* Per-photo overrides take precedence over global state. */
function getEffectiveSettings(index) {
const ps = state.photoSettings[index];
if (!ps) {
return {
palette: state.palette,
exportFilter: state.exportFilter,
filterIntensity:state.filterIntensity,
filterVariant: state.filterVariant,
filterParams: state.filterParams,
activeFilters: new Set(state.activeFilters),
brightness: state.brightness,
contrast: state.contrast,
toneIntensity: state.toneIntensity,
shadowColor: state.shadowColor,
highlightColor: state.highlightColor,
toneBalance: state.toneBalance,
borderId: state.borderId,
borderEnabled: state.borderEnabled,
filterScope: state.filterScope,
};
}
return {
palette: ps.paletteId ? (PALETTES[ps.paletteId] || state.palette) : state.palette,
exportFilter: ps.exportFilter ?? state.exportFilter,
filterIntensity:ps.filterIntensity ?? state.filterIntensity,
filterVariant: ps.filterVariant ?? state.filterVariant,
filterParams: ps.filterParams ?? state.filterParams,
activeFilters: ps.activeFilters ? new Set(ps.activeFilters) : new Set(state.activeFilters),
brightness: ps.brightness ?? state.brightness,
contrast: ps.contrast ?? state.contrast,
toneIntensity: ps.toneIntensity ?? state.toneIntensity,
shadowColor: ps.shadowColor ?? state.shadowColor,
highlightColor: ps.highlightColor ?? state.highlightColor,
toneBalance: ps.toneBalance ?? state.toneBalance,
borderId: ps.borderId ?? state.borderId,
borderEnabled: ps.borderEnabled ?? state.borderEnabled,
filterScope: state.filterScope, // always global (not per-photo)
};
}
/** Write a setting to the selected photos' per-photo overrides, or globally if nothing is selected. */
function setScopedSetting(key, value) {
const targets = state.selectedPhotos.size > 0 ? [...state.selectedPhotos] : null;
if (targets) {
for (const idx of targets) {
if (!state.photoSettings[idx]) state.photoSettings[idx] = {};
state.photoSettings[idx][key] = value;
}
} else {
state[key] = value;
}
}
/** Returns the filterParams object for the current scope. Per-photo when a photo is selected, global otherwise. */
function getWritableFilterParams(filter) {
const idx = state.selectedPhotos.size > 0 ? [...state.selectedPhotos][0] : state.selectedIndex;
if (idx !== null && idx !== undefined) {
if (!state.photoSettings[idx]) state.photoSettings[idx] = {};
if (!state.photoSettings[idx].filterParams) {
state.photoSettings[idx].filterParams = JSON.parse(JSON.stringify(state.filterParams));
}
const fp = state.photoSettings[idx].filterParams;
if (!fp[filter]) fp[filter] = {};
return fp[filter];
}
if (!state.filterParams[filter]) state.filterParams[filter] = {};
return state.filterParams[filter];
}
/** True when photo at `index` has any per-photo setting override. */
function hasPhotoOverride(index) {
const ps = state.photoSettings[index];
if (!ps) return false;
return Object.keys(ps).some(k => ps[k] !== undefined && (k !== 'filterParams' || Object.keys(ps[k]).length > 0));
}
/** Remove all per-photo overrides for `index`. */
function clearPhotoOverride(index) {
delete state.photoSettings[index];
}
/** Deselect all photos and clear visual state. */
function deselectAll() {
state.selectedPhotos.clear();
state.selectedIndex = null;
state.lastSelectedIndex = null;
dom.photoGrid.querySelectorAll('.photo-slot').forEach(el => {
el.classList.remove('selected', 'multi-selected');
});
updateSidebarPreview();
}
/** Clear edits on selected photos — removes tone, exposure, and filter overrides
* but preserves each photo's palette choice. Requires at least one photo selected. */
function clearEdits() {
const targets = state.selectedPhotos.size > 0 ? [...state.selectedPhotos] : null;
if (!targets) {
showToast('Select a photo first');
return;
}
pushUndo();
for (const idx of targets) {
// Preserve per-photo palette id; clear everything else
const savedPaletteId = state.photoSettings[idx]?.paletteId;
delete state.photoSettings[idx];
if (savedPaletteId) {
state.photoSettings[idx] = { paletteId: savedPaletteId };
}
delete state.photoTransforms[idx];
repaintGridSlot(idx);
}
if (state.viewMode === 'solo' && state.selectedIndex !== null) renderSoloView(state.selectedIndex);
if (state.lightboxOpen && state.selectedIndex !== null) renderLightbox(state.selectedIndex);
if (state.selectedIndex !== null) syncControlsToEffectiveSettings(state.selectedIndex);
updateFilterUI();
_refreshFilterParamPanel();
const n = targets.length;
showToast(`Cleared edits on ${n} photo${n > 1 ? 's' : ''}`);
updateSidebarPreview();
}
// Legacy alias (kept so any remaining references don't throw)
const resetAllEdits = clearEdits;
/** Returns the palette id that should be shown as "active" in the picker. */
function getDisplayPaletteId() {
if (state.selectedIndex !== null) {
return getEffectiveSettings(state.selectedIndex).palette?.id || state.palette.id;
}
return state.palette.id;
}
/** Sync all right-panel controls to reflect the effective settings for `index`.
* Called when scope='photo' and the selected photo changes, or scope toggles. */
function syncControlsToEffectiveSettings(index) {
if (index === null || index === undefined) return;
const eff = getEffectiveSettings(index);
// Palette picker button
updatePalettePickerBtn(eff.palette);
// Picker list active state
const effPalId = eff.palette?.id;
document.querySelectorAll('.pal-item').forEach(item => {
item.classList.toggle('active', item.dataset.palette === effPalId);
});
updateCurrentPalettePin();
// Sync filter accordion checkboxes + param values
syncFilterAccordion(eff);
// Tone controls
const bEl = document.getElementById('tone-brightness');
const bVal = document.getElementById('tone-brightness-val');
if (bEl) bEl.value = eff.brightness;
if (bVal) bVal.textContent = eff.brightness > 0 ? `+${eff.brightness}` : String(eff.brightness);
const cEl = document.getElementById('tone-contrast');
const cVal = document.getElementById('tone-contrast-val');
if (cEl) cEl.value = eff.contrast;
if (cVal) cVal.textContent = eff.contrast > 0 ? `+${eff.contrast}` : String(eff.contrast);
const tiEl = document.getElementById('tone-intensity');
const tiVal = document.getElementById('tone-intensity-val');
if (tiEl) tiEl.value = eff.toneIntensity;
if (tiVal) tiVal.textContent = `${eff.toneIntensity}%`;
const scEl = document.getElementById('tone-shadow-color');
if (scEl) { scEl.value = eff.shadowColor; syncColorSwatchBtn(scEl, eff.shadowColor); }
const hcEl = document.getElementById('tone-highlight-color');
if (hcEl) { hcEl.value = eff.highlightColor; syncColorSwatchBtn(hcEl, eff.highlightColor); }
const balEl = document.getElementById('tone-balance');
const balVal = document.getElementById('tone-balance-val');
if (balEl) balEl.value = eff.toneBalance;
if (balVal) balVal.textContent = eff.toneBalance > 0 ? `+${eff.toneBalance}` : String(eff.toneBalance);
// Border picker + checkbox
const borderCb = document.getElementById('border-enabled-check');
if (borderCb) borderCb.checked = eff.borderEnabled ?? false;
document.querySelectorAll('.border-frame-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.frameId === eff.borderId);
});
}
// ── Status bar ─────────────────────────────────────────────────────────────
function setStatus(text, active = false) {
dom.statusText.textContent = text;
dom.statusDot.className = 'status-dot' + (active ? ' green' : '');
}
// ── Load SAV ───────────────────────────────────────────────────────────────
// Accept a 131072-byte GB Camera save as-is, or extract the 128 KB cart RAM from a
// Pocket savestate (.sta) by locating the management-block "Magic" echo/primary pair
// (echo at cart-RAM 0x10D2, primary 0xFE later). Returns an ArrayBuffer or null.
function coerceGbCamSave(arrayBuffer) {
const buf = new Uint8Array(arrayBuffer);
if (buf.length === 131072) return arrayBuffer;
const isMagic = (p) => buf[p] === 0x4D && buf[p+1] === 0x61 && buf[p+2] === 0x67 && buf[p+3] === 0x69 && buf[p+4] === 0x63; // "Magic"
for (let i = 0x10D2; i + 0xFE + 5 <= buf.length; i++) {
if (isMagic(i) && isMagic(i + 0xFE)) { // echo + primary pair = the management block
const base = i - 0x10D2; // cart RAM offset 0
if (base < 0) continue;
const out = new Uint8Array(131072).fill(0xFF);
out.set(buf.subarray(base, Math.min(buf.length, base + 131072)), 0);
return out.buffer;
}
}
return null; // no GB Camera cart RAM found inside
}
async function loadSavFile(result) {
if (!result || result.error) {
if (result?.error) showToast(`⚠ ${result.error}`);
return;
}
const { buffer, name, path: filePath } = result;
const camBuf = coerceGbCamSave(buffer);
if (!camBuf) {
showToast(`⚠ Unexpected file (${buffer.byteLength} bytes): expected a 131072-byte GB Camera save, or a savestate (.sta) containing one.`);
return;
}
const { photos, activeCount, sav } = GBCam.parseSav(camBuf);
state.sav = sav;
state.photos = photos;
state.activeCount = activeCount;
state.filename = name;
state.filePath = filePath || null;
state.selectedIndex = null;
state.gifMode = false;
state.gifSelection.clear();
state.photoTransforms = {}; // reset transforms on new file load
state.photoSettings = {}; // reset per-photo overrides on new file load
if (filePath) saveLastSavPath(filePath);
renderGrid();
showMainView();
updateExportSelectedBtn();
setStatus(`${name} — ${activeCount} photo${activeCount !== 1 ? 's' : ''} found`, true);
}
// ── Photo transforms ────────────────────────────────────────────────────────
/** Get (or default-initialise) the transform for a photo index */
function getTransform(idx) {
if (!state.photoTransforms[idx]) {
state.photoTransforms[idx] = { rotate: 0, flipH: false, flipV: false };
}
return state.photoTransforms[idx];
}
function hasTransform(idx) {
const t = state.photoTransforms[idx];
return t && (t.rotate !== 0 || t.flipH || t.flipV);
}
/**
* Render a photo onto ctx with transform applied.
* Adjusts ctx.canvas dimensions to match the post-rotation output size.
*/
function renderPhotoWithTransform(ctx, photo, palette, scale, idx) {
const t = getTransform(idx);
const sw = GBCam.PHOTO_WIDTH * scale;
const sh = GBCam.PHOTO_HEIGHT * scale;
if (!t.rotate && !t.flipH && !t.flipV) {
ctx.canvas.width = sw;
ctx.canvas.height = sh;
GBCam.renderToCanvas(ctx, photo.pixels, palette, scale);
return;
}
const rotated = (t.rotate === 90 || t.rotate === 270);
const dw = rotated ? sh : sw;
const dh = rotated ? sw : sh;
const tmp = Object.assign(document.createElement('canvas'), { width: sw, height: sh });
GBCam.renderToCanvas(tmp.getContext('2d'), photo.pixels, palette, scale);
ctx.canvas.width = dw;
ctx.canvas.height = dh;
ctx.save();
ctx.translate(dw / 2, dh / 2);
if (t.flipH) ctx.scale(-1, 1);
if (t.flipV) ctx.scale( 1, -1);
ctx.rotate(t.rotate * Math.PI / 180);
ctx.drawImage(tmp, -sw / 2, -sh / 2);
ctx.restore();
}
function applyTransformAction(idx, action) {
const t = getTransform(idx);
if (action === 'rotate-cw') { t.rotate = (t.rotate + 90) % 360; }
if (action === 'rotate-ccw') { t.rotate = (t.rotate + 270) % 360; }
if (action === 'flip-h') { t.flipH = !t.flipH; }
if (action === 'flip-v') { t.flipV = !t.flipV; }
if (action === 'reset-transform') { t.rotate = 0; t.flipH = false; t.flipV = false; }
}
// ── Views ───────────────────────────────────────────────────────────────────
function showMainView() {
dom.welcome.classList.add('hidden');
dom.main.style.display = 'flex';
// Reveal file-only titlebar buttons (Export .sav, Save Project)
dom.app.classList.add('has-file');
}
function resetToWelcome() {
// Clear loaded file state
state.sav = null;
state.photos = [];
state.activeCount = 0;
state.filename = null;
state.filePath = null;
state.selectedIndex = null;
state.photoSettings = {};
state.gifMode = false;
state.gifSelection = new Set();
state.gifFrameOrder = [];
state.lightboxOpen = false;
state.viewMode = 'grid';
// Return to welcome screen
dom.main.style.display = 'none';
dom.welcome.classList.remove('hidden');
dom.app.classList.remove('has-file');
// Clear grid
if (dom.photoGrid) dom.photoGrid.innerHTML = '';
}
// ── Grid ────────────────────────────────────────────────────────────────────
function renderGrid() {
dom.photoGrid.innerHTML = '';
for (const photo of state.photos) {
const slot = document.createElement('div');
slot.className = 'photo-slot' + (photo.isEmpty ? ' empty' : '');
slot.dataset.index = photo.index;
// Slot number badge
const num = document.createElement('span');
num.className = 'slot-num';
num.textContent = String(photo.index + 1).padStart(2, '0');
slot.appendChild(num);
if (photo.isEmpty) {
const placeholder = document.createElement('div');
placeholder.className = 'empty-placeholder';
placeholder.textContent = '—';
slot.appendChild(placeholder);
} else {
// Canvas thumbnail — rendered at THUMB_SCALE (4×) for filter clarity
const canvas = document.createElement('canvas');
const effThumb = getEffectiveSettings(photo.index);
const hasBorderThumb = effThumb.borderEnabled && effThumb.borderId;
canvas.width = (hasBorderThumb ? 160 : GBCam.PHOTO_WIDTH) * THUMB_SCALE;
canvas.height = (hasBorderThumb ? 144 : GBCam.PHOTO_HEIGHT) * THUMB_SCALE;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
renderPhotoComplete(ctx, photo, effThumb, THUMB_SCALE, photo.index, { thumbMode: true });
slot.appendChild(canvas);
// GIF selection (invisible div for event delegation; frame number via data attr)
const check = document.createElement('div');
check.className = 'gif-check';
check.addEventListener('click', (e) => {
e.stopPropagation();
toggleGifSelection(photo.index, slot);
});
slot.appendChild(check);
slot.addEventListener('click', (e) => selectPhoto(photo.index, e));
slot.addEventListener('dblclick', (e) => {
selectPhoto(photo.index, e);
enterSoloMode();
});
}
dom.photoGrid.appendChild(slot);
}
// Apply selected state
if (state.selectedIndex !== null) {
const el = dom.photoGrid.querySelector(`[data-index="${state.selectedIndex}"]`);
if (el) el.classList.add('selected');