-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjigsaw.html
More file actions
1755 lines (1613 loc) · 81.8 KB
/
jigsaw.html
File metadata and controls
1755 lines (1613 loc) · 81.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover" />
<link rel="manifest" href="manifest.webmanifest" />
<meta name="application-name" content="IdleGames" />
<script src="assets/js/pwa.js" defer></script>
<!-- Navigation/status bar color on Android; updated dynamically by JS -->
<meta name="theme-color" content="#0f1320" id="theme-color" />
<title>Jigsaw Puzzle</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<style>
:root {
--bg: #0f1320;
--panel: #151a2b;
--text: #e6f0ff;
--muted: #9bb3d1;
--accent: #4fc3f7;
--accent-2: #7c4dff;
--shadow: rgba(0, 0, 0, 0.35);
/* Start color for page background gradient */
--bg-start: #1a2240;
/* Let UA components adapt; overridden by explicit theme below */
color-scheme: dark light;
}
:root[data-theme="dark"] { color-scheme: dark; }
/* Light theme overrides */
:root[data-theme="light"] {
--bg: #b9b9b9;
--panel: #ffffff;
--text: #0c1630;
--muted: #51627a;
--accent: #1ea0e6;
--accent-2: #6a4cff;
--shadow: rgba(0, 0, 0, 0.18);
/* Brighter, fresh start for light-mode gradient */
--bg-start: #ebebeb;
/* ~#3f3 */
color-scheme: light;
}
/* System preference when no explicit theme set */
@media (prefers-color-scheme: light) {
:root:not([data-theme]) {
--bg: #b9b9b9;
--panel: #ffffff;
--text: #0c1630;
--muted: #51627a;
--accent: #1ea0e6;
--accent-2: #6a4cff;
--shadow: rgba(0, 0, 0, 0.18);
--bg-start: #ebebeb;
color-scheme: light;
}
}
* {
box-sizing: border-box;
}
html,
body {
height: 100%;
}
html { background-color: var(--bg); }
body {
margin: 0;
background: radial-gradient(1200px 800px at 10% 10%, var(--bg-start) 0%, var(--bg) 60%);
color: var(--text);
font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, sans-serif;
overflow: hidden;
/* we manage panning/zoom inside */
touch-action: none;
/* we provide custom pan/zoom/drag */
/* Prevent long-press text selection/callout */
-webkit-user-select: none;
user-select: none;
-webkit-touch-callout: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
/* Extend under system UI (notches/gesture areas) */
padding-top: env(safe-area-inset-top);
padding-right: env(safe-area-inset-right);
padding-bottom: env(safe-area-inset-bottom);
padding-left: env(safe-area-inset-left);
}
/* Floating action buttons */
.fab-stack {
position: absolute;
top: 12px;
right: 12px;
display: flex;
flex-direction: column;
gap: 10px;
z-index: 12;
}
.hud {
position: fixed; /* anchor to visual viewport */
bottom: 12px;
left: 12px;
right: 12px;
display: flex;
justify-content: space-between;
pointer-events: none;
}
@supports (bottom: calc(12px + env(safe-area-inset-bottom))) {
.hud { bottom: calc(12px + env(safe-area-inset-bottom)); }
.hud { left: calc(12px + env(safe-area-inset-left)); right: calc(12px + env(safe-area-inset-right)); }
}
.fab {
width: 46px;
height: 46px;
border-radius: 50%;
background: color-mix(in oklab, var(--panel) 88%, black 0%);
border: 1px solid rgba(255, 255, 255, 0.12);
box-shadow: 0 8px 24px var(--shadow);
display: grid;
place-items: center;
color: var(--text);
cursor: pointer;
outline: none;
-webkit-user-select: none; user-select: none; -webkit-touch-callout: none;
}
.fab:hover {
filter: brightness(1.05);
}
.fab:active {
transform: translateY(1px);
}
.fab.active {
box-shadow: 0 0 0 2px color-mix(in oklab, var(--accent) 55%, transparent), 0 8px 20px var(--shadow);
}
.fab svg {
width: 22px;
height: 22px;
fill: currentColor;
}
.stage {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
/* also honor safe area so content isn't obscured */
padding-top: env(safe-area-inset-top);
padding-right: env(safe-area-inset-right);
padding-bottom: env(safe-area-inset-bottom);
padding-left: env(safe-area-inset-left);
overflow: hidden;
}
svg {
width: 100%;
height: 100%;
display: block;
touch-action: none;
/* Prefer speed over crispness during motion */
shape-rendering: optimizeSpeed;
}
#bg {
fill: transparent;
pointer-events: all;
}
.piece {
cursor: grab;
}
.piece:active {
cursor: grabbing;
}
.outline {
fill: none;
stroke: rgba(255, 255, 255, 0.14);
stroke-width: 1;
}
.highlight {
filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.35));
}
/* Disable heavy effects on pieces while dragging a group */
.piece.no-effects {
filter: none !important;
}
.piece.no-effects .edge-shade {
display: none !important;
}
.piece.no-effects .highlight {
filter: none !important;
}
/* Motion mode: globally disable heavy effects during pan/zoom for perf */
.motion .piece { filter: none !important; }
.motion .piece .edge-shade { display: none !important; }
.motion .piece .highlight { filter: none !important; }
/* .hud absolute version removed; using fixed-position .hud defined above */
.badge {
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.1);
padding: 8px 12px;
border-radius: 999px;
font-size: 12px;
color: var(--muted);
-webkit-user-select: none; user-select: none; -webkit-touch-callout: none;
}
/* Edge shading visuals */
.edge-shade {
fill: none;
pointer-events: none;
vector-effect: non-scaling-stroke;
stroke-linecap: round;
stroke-linejoin: round;
}
.edge-highlight {
stroke: rgba(255, 255, 255, 0.7);
stroke-width: 2.2;
}
.edge-shadow {
stroke: rgba(0, 0, 0, 0.45);
stroke-width: 2.2;
}
.win {
position: absolute;
inset: 0;
display: none;
align-items: center;
justify-content: center;
backdrop-filter: blur(4px);
background: rgba(10, 14, 25, 0.35);
z-index: 20;
-webkit-user-select: none; user-select: none; -webkit-touch-callout: none;
}
.win .panel {
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.12);
padding: 18px 22px;
border-radius: 14px;
box-shadow: 0 12px 30px var(--shadow);
text-align: center;
}
.win .panel h2 {
margin: 0 0 8px 0;
}
/* Import modal */
.modal {
position: absolute;
inset: 0;
display: none;
align-items: center;
justify-content: center;
backdrop-filter: blur(4px);
background: rgba(10, 14, 25, 0.45);
z-index: 20;
-webkit-user-select: none; user-select: none; -webkit-touch-callout: none;
}
.modal .panel {
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.12);
padding: 20px 22px;
border-radius: 14px;
box-shadow: 0 12px 30px var(--shadow);
width: min(92vw, 560px);
color: var(--text);
}
.modal .panel h3 {
margin: 0 0 12px 0;
}
.modal .grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 12px;
margin-top: 12px;
}
.modal label {
display: block;
font-size: 13px;
color: var(--muted);
margin: 6px 0;
}
.modal input[type="number"],
.modal input[type="file"] {
width: 100%;
background: var(--panel);
color: var(--text);
border: 1px solid color-mix(in oklab, var(--text) 12%, transparent);
border-radius: 10px;
padding: 10px 12px;
font-size: 18px;
/* Re-enable selection and callouts for inputs */
-webkit-user-select: text; user-select: text; -webkit-touch-callout: default;
caret-color: var(--accent);
}
/* Inputs adapt to current theme via CSS variables; no hard-coded light/dark overrides needed */
/* Input focus uses theme accent */
.modal input[type="number"]:focus,
.modal input[type="file"]:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent) 35%, transparent);
}
/* Themed file selection button (cross-browser) */
.modal input[type="file"]::file-selector-button,
.modal input[type="file"]::-webkit-file-upload-button {
background: linear-gradient(135deg, var(--accent) 0%, var(--accent-2) 100%);
color: #fff;
border: none;
border-radius: 8px;
padding: 8px 12px;
margin-right: 10px;
cursor: pointer;
font-size: 14px;
box-shadow: 0 4px 10px rgba(79, 195, 247, 0.25);
transition: filter 120ms ease, box-shadow 120ms ease;
}
.modal input[type="file"]::file-selector-button:hover,
.modal input[type="file"]::-webkit-file-upload-button:hover {
filter: saturate(1.05) brightness(1.03);
}
.modal input[type="file"]::file-selector-button:active,
.modal input[type="file"]::-webkit-file-upload-button:active {
filter: saturate(0.98) brightness(0.98);
}
.modal input[type="file"]:focus-visible::file-selector-button,
.modal input[type="file"]:focus-visible::-webkit-file-upload-button {
outline: none;
box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent) 55%, transparent), 0 6px 14px rgba(79, 195, 247, 0.25);
}
.modal .actions {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 16px;
}
.btn {
background: var(--panel);
color: var(--text);
border: 1px solid color-mix(in oklab, var(--text) 12%, transparent);
border-radius: 10px;
padding: 10px 14px;
font-size: 14px;
cursor: pointer;
transition: filter 120ms ease, box-shadow 120ms ease, background-color 120ms ease;
}
.btn:hover { filter: brightness(1.06); }
.btn:active { filter: brightness(0.98); }
.btn:focus-visible {
outline: none;
box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent) 45%, transparent);
}
.btn.primary {
background: linear-gradient(135deg, var(--accent) 0%, var(--accent-2) 100%);
border: none;
font-weight: 700;
letter-spacing: 0.2px;
box-shadow: 0 6px 16px rgba(79, 195, 247, 0.35);
}
.btn.primary:hover { filter: saturate(1.05) brightness(1.03); }
.btn.primary:active { filter: saturate(0.98) brightness(0.98); }
.btn.primary:focus-visible {
outline: none;
box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent) 55%, transparent), 0 8px 18px rgba(79, 195, 247, 0.35);
}
</style>
</head>
<body>
<div class="fab-stack">
<button id="btnImport" class="fab" title="Import image" aria-label="Import image">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path
d="M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2Zm0 2v9.59l-3.3-3.3a1 1 0 0 0-1.4 0L9 16l-2.3-2.3a1 1 0 0 0-1.4 0L5 14.99V5h14ZM7.5 8.5A1.5 1.5 0 1 0 9 7a1.5 1.5 0 0 0-1.5 1.5Z" />
</svg>
</button>
<button id="btnFit" class="fab" title="Fit view" aria-label="Fit view">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path
d="M7 3H3v4h2V5h2V3Zm14 0h-4v2h2v2h2V3ZM3 17v4h4v-2H5v-2H3Zm16 2h-2v2h4v-4h-2v2ZM7 11h2v2H7v-2Zm4 0h2v2h-2v-2Zm4 0h2v2h-2v-2Z" />
</svg>
</button>
<button id="btnFull" class="fab" title="Enter fullscreen" aria-label="Toggle fullscreen">
<svg id="iconFull" viewBox="0 0 24 24" aria-hidden="true">
<path d="M8 3H3v5h2V5h3V3Zm13 0h-5v2h3v3h2V3ZM3 21h5v-2H5v-3H3v5Zm18-5h-2v3h-3v2h5v-5Z" />
</svg>
</button>
<button id="btnTheme" class="fab" title="Theme: System" aria-label="Cycle theme">
<svg id="iconTheme" viewBox="0 0 24 24" aria-hidden="true">
<path d="M12 3a9 9 0 1 0 9 9c0-.34-.02-.68-.06-1.01A7 7 0 0 1 12 3Z" />
</svg>
</button>
<button id="btnGather" class="fab" title="Nudge loose pieces" aria-label="Bring loose pieces into view">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M12 5a1 1 0 0 1 1 1v3.59l1.29-1.3a1 1 0 0 1 1.42 1.42l-3 3a1 1 0 0 1-1.42 0l-3-3a1 1 0 1 1 1.42-1.42L11 9.59V6a1 1 0 0 1 1-1Zm0 14a1 1 0 0 0 1-1v-3.59l1.29 1.3a1 1 0 1 0 1.42-1.42l-3-3a1 1 0 0 0-1.42 0l-3 3a1 1 0 1 0 1.42 1.42L11 14.41V18a1 1 0 0 0 1 1Zm-7-5a1 1 0 0 0 1-1v-2h3a1 1 0 0 0 0-2H6V8a1 1 0 0 0-2 0v8a1 1 0 0 0 1 1Zm13 0a1 1 0 0 1-1-1v-2h-3a1 1 0 0 1 0-2h3V8a1 1 0 0 1 2 0v8a1 1 0 0 1-1 1Z" />
</svg>
</button>
</div>
<div class="stage">
<svg id="svg" xmlns="http://www.w3.org/2000/svg">
<defs id="defs"></defs>
<g id="world">
<rect id="bg" x="-5000" y="-5000" width="10000" height="10000"></rect>
<g id="pieces"></g>
<!-- Overlay for interactive hints (near-snap glow) above pieces -->
<g id="hints" style="pointer-events:none"></g>
</g>
</svg>
<div class="hud">
<div class="badge" id="status">0 / 0 joined</div>
<div class="badge" id="zoomLabel">100%</div>
</div>
<div class="win" id="win">
<div class="panel">
<h2>🎉 Puzzle Complete!</h2>
<div style="margin-bottom:10px;color:var(--muted)">Pinch or scroll to view your masterpiece.</div>
<button id="closeWin" class="btn primary">Close</button>
</div>
</div>
<!-- Import modal -->
<div class="modal" id="importModal" role="dialog" aria-modal="true" aria-labelledby="importTitle">
<div class="panel">
<h3 id="importTitle">Import Image</h3>
<div class="form">
<label>Image file
<input id="impFile" type="file" accept="image/*" />
</label>
<div class="grid">
<div>
<label>Rows</label>
<input id="impRows" type="number" inputmode="numeric" min="2" max="50" step="1" value="4" />
</div>
<div>
<label>Cols</label>
<input id="impCols" type="number" inputmode="numeric" min="2" max="50" step="1" value="6" />
</div>
<div>
<label>Snap</label>
<input id="impSnap" type="number" inputmode="numeric" min="2" max="100" step="1"
value="12" />
</div>
</div>
<div class="actions">
<button id="impCancel" class="btn">Cancel</button>
<button id="impBegin" class="btn primary">Begin</button>
</div>
</div>
</div>
</div>
</div>
<script>
(function () {
'use strict';
// --- State ---
const svg = document.getElementById('svg');
const world = document.getElementById('world');
const defs = document.getElementById('defs');
const piecesLayer = document.getElementById('pieces');
const hintsLayer = document.getElementById('hints');
const statusEl = document.getElementById('status');
const zoomLabel = document.getElementById('zoomLabel');
const winEl = document.getElementById('win');
const closeWin = document.getElementById('closeWin');
const importModal = document.getElementById('importModal');
const impFile = document.getElementById('impFile');
const impRows = document.getElementById('impRows');
const impCols = document.getElementById('impCols');
const impSnap = document.getElementById('impSnap');
const impBegin = document.getElementById('impBegin');
const impCancel = document.getElementById('impCancel');
const btnImport = document.getElementById('btnImport');
const btnFit = document.getElementById('btnFit');
const btnFull = document.getElementById('btnFull');
const iconFull = document.getElementById('iconFull');
const btnTheme = document.getElementById('btnTheme');
const iconTheme = document.getElementById('iconTheme');
const btnGather = document.getElementById('btnGather');
let imgHref = null;
let imgW = 0, imgH = 0;
let rows = 4, cols = 6;
let snapTol = 12;
let scale = 1, tx = 0, ty = 0; // world transform
const minScale = 0.05, maxScale = 4;
const TOUCH_DRAG_OFFSET_PX = 56; // keep piece above finger by ~56px in screen space
// current puzzle metrics
let cellW = 0, cellH = 0, edgeTabRMax = 0;
// Flattened final image (after completion)
let flattened = null; // { x, y }
const rng = (seed) => () => (seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296;
// Edge params shared between neighboring pieces
let hEdges = []; // horizontal edges [r][c] r:0..rows, c:0..cols-1
let vEdges = []; // vertical edges [r][c] r:0..rows-1, c:0..cols
// Pieces and groups
let pieces = []; // {id, r,c, pathD, clipId, g, groupId, anchor:[x,y]}
let groups = new Map(); // groupId -> {id, members:Set<pieceId>, g, x,y}
let nextGroupId = 1;
// Active interactions
const pointers = new Map(); // id -> {x,y, sx,sy}
let dragging = null; // {groupId, dx, dy}
let pinching = null; // {startDist, startScale, startTx, startTy, startCenter}
let panning = null; // background pan via right mouse or space?
let dragAnimId = 0; // rAF id for drag
let dragNext = null; // {gid, x, y}
let glowState = null; // { gid }
let glowRAF = 0; // rAF id for glow
let glowDirtyGid = null; // group id requesting glow update
// Cache of side path data per piece and side to avoid recompute during dragging
const sidePathCache = new Map(); // key: `${id}:${side}` -> pathD
let viewRAF = 0; // rAF for coalescing pan/zoom transforms
let pendingView = null; // { s, tx, ty }
let motionTimeout = 0; // timer to remove motion class after pan/zoom settles
// Gather assist
let gatherRAF = 0;
let gatherActive = false;
let gatherUntil = 0;
let gatherLast = 0;
// --- UI wiring ---
closeWin.addEventListener('click', () => { winEl.style.display = 'none'; });
// Import modal controls
btnImport.addEventListener('click', () => {
impRows.value = rows; impCols.value = cols; impSnap.value = snapTol;
impFile.value = '';
importModal.style.display = 'flex';
// Autofocus file input for quick action
setTimeout(() => impFile && impFile.focus && impFile.focus(), 0);
});
impCancel.addEventListener('click', () => { importModal.style.display = 'none'; });
impBegin.addEventListener('click', async () => {
// Read values
rows = clamp(int(impRows.value, rows), 2, 50);
cols = clamp(int(impCols.value, cols), 2, 50);
snapTol = clamp(int(impSnap.value, snapTol), 2, 100);
const f = impFile.files && impFile.files[0];
if (f) {
try {
const href = await readFileAsDataURL(f);
const dim = await getImageSize(href);
imgHref = href; imgW = dim.w; imgH = dim.h;
} catch (err) { console.error('Failed to load image', err); }
}
if (!imgHref) { // ensure there's an image
const placeholder = createGradientImage(1024, 768);
imgHref = placeholder.href; imgW = placeholder.w; imgH = placeholder.h;
}
importModal.style.display = 'none';
initPuzzle();
});
// Fullscreen toggle
function updateFullIcon() {
if (document.fullscreenElement) {
iconFull.innerHTML = '<path d="M9 7H7v2H5v2h4V7Zm10 2h-2V7h-2v4h4V9ZM7 15H5v2h2v2h2v-4H7Zm12 0h-4v4h2v-2h2v-2Z"/>'; // exit-ish
btnFull.title = 'Exit fullscreen';
} else {
iconFull.innerHTML = '<path d="M8 3H3v5h2V5h3V3Zm13 0h-5v2h3v3h2V3ZM3 21h5v-2H5v-3H3v5Zm18-5h-2v3h-3v2h5v-5Z"/>';
btnFull.title = 'Enter fullscreen';
}
}
updateFullIcon();
btnFull.addEventListener('click', async () => {
try {
if (!document.fullscreenElement) {
const el = document.documentElement;
if (el.requestFullscreen) {
// Some browsers support an option to hide system UI
const opts = { navigationUI: 'hide' };
try { await el.requestFullscreen(opts); }
catch { await el.requestFullscreen(); }
}
}
else { await document.exitFullscreen(); }
} catch (err) { console.warn('Fullscreen error', err); }
});
document.addEventListener('fullscreenchange', updateFullIcon);
// Theme cycle: system -> light -> dark -> system
const THEME_KEY = 'puzzle-theme-mode';
let themeMode = (localStorage.getItem(THEME_KEY) || 'system');
function applyTheme(mode) {
themeMode = mode;
if (mode === 'light') document.documentElement.setAttribute('data-theme', 'light');
else if (mode === 'dark') document.documentElement.setAttribute('data-theme', 'dark');
else document.documentElement.removeAttribute('data-theme');
localStorage.setItem(THEME_KEY, themeMode);
// Update Android nav bar color to match theme
try {
const meta = document.querySelector('meta[name="theme-color"]');
if (meta) {
let color;
if (mode === 'light') color = '#ffffff';
else if (mode === 'dark') color = '#0f1320';
else {
// system: pick by media query
const dark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
color = dark ? '#0f1320' : '#ffffff';
}
meta.setAttribute('content', color);
}
} catch (_) { }
// Update icon
if (mode === 'system') {
iconTheme.innerHTML = '<path d="M12 3a9 9 0 1 0 9 9c0-.34-.02-.68-.06-1.01A7 7 0 0 1 12 3Z"/>';
btnTheme.title = 'Theme: System';
} else if (mode === 'light') {
iconTheme.innerHTML = '<path d="M6.76 4.84 5.34 3.42 3.92 4.84 5.34 6.26 6.76 4.84Zm10.48 0 1.42-1.42 1.42 1.42-1.42 1.42-1.42-1.42ZM12 5a7 7 0 1 1 0 14 7 7 0 0 1 0-14Zm0-4h1v3h-1V1ZM1 11h3v1H1v-1Zm19 0h3v1h-3v-1ZM12 20h1v3h-1v-3Zm-6.66-.24L3.92 21.18 5.34 22.6l1.42-1.42-1.42-1.42Zm13.32 0 1.42 1.42-1.42 1.42-1.42-1.42 1.42-1.42Z"/>';
btnTheme.title = 'Theme: Light';
} else {
iconTheme.innerHTML = '<path d="M9.37 5.51A7 7 0 1 0 18.5 14.63 8 8 0 1 1 9.37 5.5Z"/>';
btnTheme.title = 'Theme: Dark';
}
}
applyTheme(themeMode);
btnTheme.addEventListener('click', () => {
const next = themeMode === 'system' ? 'light' : (themeMode === 'light' ? 'dark' : 'system');
applyTheme(next);
});
// If in system mode, react to live system theme changes to keep nav bar in sync
if (window.matchMedia) {
const mq = window.matchMedia('(prefers-color-scheme: dark)');
mq.addEventListener && mq.addEventListener('change', () => { if (themeMode === 'system') applyTheme('system'); });
}
// Fit View button
btnFit.addEventListener('click', () => {
fitView(getContentBounds());
});
btnGather.addEventListener('click', () => {
if (flattened || !groups || !groups.size) return;
activateGatherAssist();
});
// Modal UX: backdrop click and Escape to cancel
importModal.addEventListener('click', (e) => { if (e.target === importModal) importModal.style.display = 'none'; });
window.addEventListener('keydown', (e) => { if (e.key === 'Escape' && importModal.style.display === 'flex') importModal.style.display = 'none'; });
// --- Helpers ---
function int(v, d = 0) { const n = parseInt(v, 10); return Number.isFinite(n) ? n : d; }
function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
function lerp(a, b, t) { return a + (b - a) * t; }
function readFileAsDataURL(file) {
return new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onerror = reject; fr.onload = () => resolve(fr.result);
fr.readAsDataURL(file);
});
}
function getImageSize(href) {
return new Promise((resolve, reject) => {
const im = new Image();
im.onload = () => resolve({ w: im.naturalWidth, h: im.naturalHeight });
im.onerror = reject; im.src = href;
});
}
function setWorldTransform(ns, ntx, nty) {
// Coalesce transforms to next frame
pendingView = { s: clamp(ns, minScale, maxScale), tx: ntx, ty: nty };
if (!viewRAF) {
// Enter motion mode to reduce effects during heavy panning/zooming
document.body.classList.add('motion');
viewRAF = requestAnimationFrame(() => {
viewRAF = 0;
if (!pendingView) return;
scale = pendingView.s; tx = pendingView.tx; ty = pendingView.ty;
world.setAttribute('transform', `translate(${tx},${ty}) scale(${scale})`);
zoomLabel.textContent = Math.round(scale * 100) + '%';
pendingView = null;
// Debounce exit from motion mode shortly after last update
if (motionTimeout) clearTimeout(motionTimeout);
motionTimeout = setTimeout(() => { document.body.classList.remove('motion'); }, 80);
});
}
}
function screenToWorld(pt) {
const rect = svg.getBoundingClientRect();
const x = (pt.x - rect.left - tx) / scale;
const y = (pt.y - rect.top - ty) / scale;
return { x, y };
}
function worldToScreen(pt) {
const rect = svg.getBoundingClientRect();
return { x: pt.x * scale + tx + rect.left, y: pt.y * scale + ty + rect.top };
}
function getVisibleWorldRect() {
const rect = svg.getBoundingClientRect();
const tl = screenToWorld({ x: rect.left, y: rect.top });
const br = screenToWorld({ x: rect.right, y: rect.bottom });
const tr = screenToWorld({ x: rect.right, y: rect.top });
const bl = screenToWorld({ x: rect.left, y: rect.bottom });
return {
minX: Math.min(tl.x, br.x, tr.x, bl.x),
minY: Math.min(tl.y, br.y, tr.y, bl.y),
maxX: Math.max(tl.x, br.x, tr.x, bl.x),
maxY: Math.max(tl.y, br.y, tr.y, bl.y)
};
}
function expandRect(rect, amount) {
if (!rect) return null;
return {
minX: rect.minX - amount,
minY: rect.minY - amount,
maxX: rect.maxX + amount,
maxY: rect.maxY + amount
};
}
function rectsOverlap(a, b) {
if (!a || !b) return false;
return !(a.maxX < b.minX || a.minX > b.maxX || a.maxY < b.minY || a.minY > b.maxY);
}
function shiftRect(rect, dx, dy) {
if (!rect) return null;
return {
minX: rect.minX + dx,
minY: rect.minY + dy,
maxX: rect.maxX + dx,
maxY: rect.maxY + dy
};
}
function rectCenter(rect) {
if (!rect) return { x: 0, y: 0 };
return { x: (rect.minX + rect.maxX) / 2, y: (rect.minY + rect.maxY) / 2 };
}
function nowMs() {
return (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
}
function separateRectPair(a, b, padding) {
if (!a || !b) return false;
const inflatedA = expandRect(a.bounds, padding);
const inflatedB = expandRect(b.bounds, padding);
if (!rectsOverlap(inflatedA, inflatedB)) return false;
const overlapX = Math.min(inflatedA.maxX, inflatedB.maxX) - Math.max(inflatedA.minX, inflatedB.minX);
const overlapY = Math.min(inflatedA.maxY, inflatedB.maxY) - Math.max(inflatedA.minY, inflatedB.minY);
if (overlapX <= 0 || overlapY <= 0) return false;
if (overlapX <= overlapY) {
const dir = (a.center.x <= b.center.x) ? -1 : 1;
const shift = overlapX / 2;
translateGroup(a.gr, a.bounds, dir * shift, 0);
translateGroup(b.gr, b.bounds, -dir * shift, 0);
} else {
const dir = (a.center.y <= b.center.y) ? -1 : 1;
const shift = overlapY / 2;
translateGroup(a.gr, a.bounds, 0, dir * shift);
translateGroup(b.gr, b.bounds, 0, -dir * shift);
}
a.center = rectCenter(a.bounds);
b.center = rectCenter(b.bounds);
return true;
}
function pushOutOfRect(entry, rect, padding) {
if (!entry || !rect) return false;
const inflated = expandRect(entry.bounds, padding);
if (!rectsOverlap(inflated, rect)) return false;
const overlapX = Math.min(inflated.maxX, rect.maxX) - Math.max(inflated.minX, rect.minX);
const overlapY = Math.min(inflated.maxY, rect.maxY) - Math.max(inflated.minY, rect.minY);
if (overlapX <= 0 || overlapY <= 0) return false;
if (overlapX <= overlapY) {
const dir = (entry.center.x <= (rect.minX + rect.maxX) / 2) ? -1 : 1;
const shift = overlapX + padding * 0.4;
translateGroup(entry.gr, entry.bounds, dir * shift, 0);
} else {
const dir = (entry.center.y <= (rect.minY + rect.maxY) / 2) ? -1 : 1;
const shift = overlapY + padding * 0.4;
translateGroup(entry.gr, entry.bounds, 0, dir * shift);
}
entry.center = rectCenter(entry.bounds);
return true;
}
function activateGatherAssist() {
const now = nowMs();
gatherUntil = now + 5000;
gatherLast = now;
gatherActive = true;
btnGather.classList.add('active');
if (!gatherRAF) {
gatherRAF = requestAnimationFrame(runGatherAssist);
}
}
function stopGatherAssist() {
gatherActive = false;
btnGather && btnGather.classList.remove('active');
if (gatherRAF) {
cancelAnimationFrame(gatherRAF);
gatherRAF = 0;
}
}
function runGatherAssist() {
if (!gatherActive) { gatherRAF = 0; return; }
const now = nowMs();
if (now >= gatherUntil || flattened || !groups || !groups.size) {
stopGatherAssist();
gatherRAF = 0;
return;
}
const dt = Math.max(1, now - gatherLast);
applyGatherStep(dt);
gatherLast = now;
gatherRAF = requestAnimationFrame(runGatherAssist);
}
function applyGatherStep(dtMs) {
if (flattened || !groups || !groups.size) return;
const visRect = getVisibleWorldRect();
const shrink = Math.max(40 / scale, Math.min(cellW, cellH) * 0.5);
const maxShrinkX = Math.max(0, (visRect.maxX - visRect.minX) / 2 - 1);
const maxShrinkY = Math.max(0, (visRect.maxY - visRect.minY) / 2 - 1);
const safeShrink = Math.min(shrink, maxShrinkX, maxShrinkY);
const innerRect = expandRect(visRect, -safeShrink);
const dtFactor = clamp(dtMs / 16, 0.5, 3);
const stepBase = Math.max(cellW, cellH) * 0.12;
const moveStep = stepBase * dtFactor;
const spacing = Math.max(cellW, cellH) * 0.45;
let mainGroup = null;
let maxSize = 0;
groups.forEach(gr => {
if (gr.members.size > maxSize) {
maxSize = gr.members.size;
mainGroup = gr;
}
});
const keepOut = (mainGroup && maxSize > 1) ? expandRect(getGroupBounds(mainGroup), Math.max(spacing, edgeTabRMax || 0)) : null;
const loose = [];
groups.forEach(gr => {
if (mainGroup && gr.id === mainGroup.id && maxSize > 1) return;
if (dragging && dragging.groupId === gr.id) return;
const bounds = getGroupBounds(gr);
if (!bounds) return;
const center = rectCenter(bounds);
const intersects = rectsOverlap(bounds, visRect);
if (!intersects) {
const targetX = clamp(center.x, innerRect.minX, innerRect.maxX);
const targetY = clamp(center.y, innerRect.minY, innerRect.maxY);
let dx = targetX - center.x;
let dy = targetY - center.y;
const dist = Math.hypot(dx, dy);
if (dist > 0.5) {
const mag = Math.min(dist, moveStep);
dx = (dx / dist) * mag;
dy = (dy / dist) * mag;
if (keepOut) {
const nextBounds = shiftRect(bounds, dx, dy);
if (rectsOverlap(nextBounds, keepOut)) {
const nextCenter = rectCenter(nextBounds);
const koCenter = rectCenter(keepOut);
let kdx = nextCenter.x - koCenter.x;
let kdy = nextCenter.y - koCenter.y;
const kdist = Math.hypot(kdx, kdy) || 1;
const push = spacing * 0.6;
dx += (kdx / kdist) * push;
dy += (kdy / kdist) * push;
}
}
translateGroup(gr, bounds, dx, dy);
}
}
loose.push({ gr, bounds, center: rectCenter(bounds) });
});
resolveLooseCollisions(loose, spacing, keepOut);
}
function translateGroup(gr, bounds, dx, dy) {
if (!dx && !dy) return;
setGroupTransform(gr.id, gr.x + dx, gr.y + dy);
bounds.minX += dx;
bounds.maxX += dx;
bounds.minY += dy;
bounds.maxY += dy;
}
function resolveLooseCollisions(entries, spacing, keepOut) {
const padding = Math.max(spacing * 0.4, Math.min(cellW, cellH) * 0.2);
const iterations = 8;
for (let iter = 0; iter < iterations; iter++) {
let movedAny = false;
for (let i = 0; i < entries.length; i++) {
const a = entries[i];
if (!a) continue;
for (let j = i + 1; j < entries.length; j++) {
const b = entries[j];
if (!b) continue;
if (separateRectPair(a, b, padding)) {
movedAny = true;
}
}
if (keepOut && pushOutOfRect(a, keepOut, padding)) {
movedAny = true;
}
}
if (!movedAny) break;
}
}
// --- Puzzle generation ---
function initPuzzle() {
stopGatherAssist();
// Reset layers/state
piecesLayer.innerHTML = '';
defs.innerHTML = '';
pieces = []; groups.clear(); nextGroupId = 1; winEl.style.display = 'none'; flattened = null;
// Clear any cached side paths from previous puzzle
sidePathCache.clear && sidePathCache.clear();
// Prepare edges
hEdges = Array.from({ length: rows + 1 }, () => Array(cols).fill(null));
vEdges = Array.from({ length: rows }, () => Array(cols + 1).fill(null));
const rnd = rng((rows * 73856093) ^ (cols * 19349663) ^ (Math.floor(imgW + imgH) >>> 0));
cellW = imgW / cols;
cellH = imgH / rows;
const base = Math.min(cellW, cellH);
// Reasonable tab sizes
const tabRMin = base * 0.10, tabRMax = base * 0.18;
edgeTabRMax = tabRMax;
const tabWMin = base * 0.20, tabWMax = base * 0.32;
for (let r = 0; r <= rows; r++) {
for (let c = 0; c < cols; c++) {
if (r === 0 || r === rows) {
hEdges[r][c] = { border: true, p0: { x: c * cellW, y: r * cellH }, p1: { x: (c + 1) * cellW, y: r * cellH } };
} else {
const dir = (rnd() < 0.5) ? 1 : -1; // +1 = bulge downward
const R = lerp(tabRMin, tabRMax, rnd());
const W = lerp(tabWMin, tabWMax, rnd());
const neck = 0.6 + rnd() * 0.3; // 0..1 softness
const p0 = { x: c * cellW, y: r * cellH };
const p1 = { x: (c + 1) * cellW, y: r * cellH };
const nodes = computeEdgeNodes(p0, p1, { dir, R, W, neck }, 'h');
hEdges[r][c] = { border: false, dir, R, W, neck, p0, p1, nodes };
}
}
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c <= cols; c++) {
if (c === 0 || c === cols) {
vEdges[r][c] = { border: true, p0: { x: c * cellW, y: r * cellH }, p1: { x: c * cellW, y: (r + 1) * cellH } };
} else {
const dir = (rnd() < 0.5) ? 1 : -1; // +1 = bulge right
const R = lerp(tabRMin, tabRMax, rnd());
const W = lerp(tabWMin, tabWMax, rnd());
const neck = 0.6 + rnd() * 0.3;
const p0 = { x: c * cellW, y: r * cellH };
const p1 = { x: c * cellW, y: (r + 1) * cellH };
const nodes = computeEdgeNodes(p0, p1, { dir, R, W, neck }, 'v');
vEdges[r][c] = { border: false, dir, R, W, neck, p0, p1, nodes };
}
}