-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.html
More file actions
4512 lines (4154 loc) · 151 KB
/
Copy pathindex.html
File metadata and controls
4512 lines (4154 loc) · 151 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
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<meta name="Description" CONTENT="Draw and share simple games with your mouse or fingers!">
<link rel="icon" type="image/png" href="favicon.png">
<script src="FileSaver.js"></script>
<script src="flickgame_base.js"></script>
<script src="flickgame_vanilla.js"></script>
<script src="colorNames.js"></script>
<script src="flickgame_share.js"></script>
<script type="text/javascript">
const version = "2";
//either 'centered' or 'split'
var SWATCH_LAYOUT_VARIANT = 'split';
var gameLink = "www.flickgame.org"
var canvasIndex = 0;
var palette_name = "dawnbringer-16";
var background_color = "#000000";
var foreground_color = "#ffffff";
var canvasses = new Array();
var hyperlinks = new Array();
for (var i = 0; i < 16; i++){
hyperlinks[i] = new Array(16).fill(0);
}
var shareLinkInner = null;
function closeBurgerDialog() {
var d = document.getElementById('burger-dialog');
if (!d) return;
d.classList.remove('visible');
d.setAttribute('aria-hidden', 'true');
closePaletteSelector();
closeBackgroundColorPicker();
}
var FLICKGAME_STORAGE_KEY = "flickgame_editor_state";
// color math utilities are in flickgame_base.js: hexToRgb, rgbToLab, color_distance,
// nearest_color_index_in_palette, nearest_color_in_palette, contrastTextColor
// Pre-computed contrast colors for current palette (updated on palette change)
var paletteContrastColors = new Array(16);
function find_palette_transformation(palettea,paletteb){
//finds what colours in the second palette correspond most closely to those in the first palette - has to be a 1-1 mapping.
var mapping = {};
var colors_to_allocate = palettea.concat([]);
var colors_to_target = paletteb.concat([]);
while (colors_to_allocate.length > 0){
//from all the pairs of colors colors_to_allocate,paletteb, find the pair with the least distance.
var best_distance = Infinity;
var best_pair = null;
for (var i = 0; i < colors_to_allocate.length; i++){
for (var j = 0; j < colors_to_target.length; j++){
var distance = color_distance(colors_to_allocate[i], colors_to_target[j]);
if (distance < best_distance){
best_distance = distance;
best_pair = [colors_to_allocate[i], colors_to_target[j]];
}
}
}
//remove best_match from colors_to_allocate
colors_to_allocate.splice(colors_to_allocate.indexOf(best_pair[0]), 1);
colors_to_target.splice(colors_to_target.indexOf(best_pair[1]), 1);
mapping[palettea.indexOf(best_pair[0])] = paletteb.indexOf(best_pair[1]);
}
return mapping;
}
function apply_state_mapping(mapping){
for (var i = 0; i < canvasses.length; i++){
for (var j = 0; j < canvasses[i].length; j++){
canvasses[i][j] = mapping[canvasses[i][j]];
}
}
var old_hyperlinks = hyperlinks;
hyperlinks = new Array(16);
for (var page_idx = 0; page_idx < 16; page_idx++){
var page_links = new Array(16).fill(0);
var page_links_old = old_hyperlinks[page_idx];
if (page_links_old && Array.isArray(page_links_old)) {
for (var color_idx = 0; color_idx < page_links_old.length; color_idx++){
page_links[mapping[color_idx]] = page_links_old[color_idx];
}
}
hyperlinks[page_idx] = page_links;
}
}
function transform_state(palette_before, palette_after){
//need to transform canvasses and hyperlinks to the new palette.
var mapping = find_palette_transformation(palette_before, palette_after);
apply_state_mapping(mapping);
//transform background_color
var new_background_color = nearest_color_in_palette(palette_after, background_color);
changeBackgroundColor(new_background_color);
}
var background_colors = {};
//for each color-palette, find the darkest color and use it as the background color.
for (var paletteName in palettes) {
var palette = palettes[paletteName];
var darkest_color = nearest_color_in_palette(palette,"#000000");
background_colors[paletteName] = darkest_color;
}
var colorPalette = palettes[palette_name];
function set_color_palette(name,preserver_undo_state = true){
// if there is something on the undo stack, let's check if the previous one
// was a change of colour palette
// so that information doesn't get lost if you're changing palette rapidly
if (undoList.length > 0){
var previous_action = undoList[undoList.length - 1];
if (previous_action.palette_name !== palette_name){
var old_canvas_index = canvasIndex;
doUndo();
setLayer(old_canvas_index+1,false)
}
}
for (let i=0;i<bgColorSelectOptions.length;i++){
bgColorSelectOptions[i].textContent = colorNames[name][i];
}
for (let i=0;i<burgerBgSelectOptions.length;i++){
burgerBgSelectOptions[i].textContent = colorNames[name][i];
}
if (preserver_undo_state){
preserveUndoState();
}
transform_state(colorPalette, palettes[name]);
colorPalette = palettes[name];
updatePaletteRGB();
// Update color swatches and pre-compute contrast colors
for (var i = 0; i < 16; i++) {
document.documentElement.style.setProperty('--col' + i, colorPalette[i]);
paletteContrastColors[i] = contrastTextColor(colorPalette[i]);
bgColorSelectOptions[i].style.setProperty('--col' + i + '_fg', paletteContrastColors[i]);
}
var bgColorSelect = document.getElementById('bgColorSelect');
bgColorSelect.value = colorPalette.indexOf(background_color);
//need to set all the link-dropdowns to reflect the hyperlinks
setDropdowns();
set_modal_panel_selected_item(palette_name,name);
palette_name = name;
}
function revert_color_palette_to(p_name){
var old_palette = palettes[p_name];
var newer_palette = palettes[palette_name];
var mapping = find_palette_transformation(old_palette, newer_palette);
//invert the mapping
var inverted_mapping = {};
for (var key in mapping) {
inverted_mapping[mapping[key]] = key;
}
apply_state_mapping(inverted_mapping);
set_modal_panel_selected_item(palette_name,p_name);
palette_name = p_name;
colorPalette = palettes[p_name];
updatePaletteRGB();
// Update color swatches and contrast colors
for (var i = 0; i < 16; i++) {
document.documentElement.style.setProperty('--col' + i, colorPalette[i]);
paletteContrastColors[i] = contrastTextColor(colorPalette[i]);
}
// Set the background color properly
if (background_colors[p_name]) {
changeBackgroundColor(background_colors[p_name], false);
}
}
function applyPaletteModalNameStyle(nameDiv, name, isSelected) {
if (!nameDiv) return;
nameDiv.textContent = isSelected ? "[ " + name + " ]" : name;
nameDiv.classList.toggle('palette-modal-name-selected', !!isSelected);
}
function set_modal_panel_selected_item(from_name, to_name){
if (modal===null){
return;
}
var old_palette_index = Object.keys(palettes).indexOf(from_name);
var new_palette_index = Object.keys(palettes).indexOf(to_name);
let old_name_div = document.getElementById('palette_name_' + old_palette_index);
let new_name_div = document.getElementById('palette_name_' + new_palette_index);
applyPaletteModalNameStyle(old_name_div, from_name, false);
applyPaletteModalNameStyle(new_name_div, to_name, true);
}
var modal = null;
function closePaletteSelector(){
if (modal === null) return;
var palette_button = document.getElementById('palette_button');
if (palette_button) {
palette_button.style.filter = '';
palette_button.style.webkitFilter = '';
}
if (modal.parentNode) modal.parentNode.removeChild(modal);
modal = null;
}
function openPaletteSelector(evt){
if (modal !== null) {
closePaletteSelector();
return;
}
// Create a modal dialog
modal = document.createElement('div');
modal.className = 'palette-modal';
// Create grid container
var grid = document.createElement('div');
grid.style.display = 'grid';
grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(200px, 1fr))';
grid.style.gap = '10px';
// Add all palette previews
for (var paletteName in palettes) {
let currently_selected = paletteName === palette_name;
let paletteDiv = document.createElement('div');
paletteDiv.style.border = '1px solid var(--muted-foreground)';
paletteDiv.style.padding = '5px';
paletteDiv.style.cursor = 'pointer';
// Add palette name
let nameDiv = document.createElement('div');
nameDiv.className = 'palette-modal-name';
nameDiv.id = 'palette_name_' + Object.keys(palettes).indexOf(paletteName);
applyPaletteModalNameStyle(nameDiv, paletteName, currently_selected);
paletteDiv.appendChild(nameDiv);
// Add color previews
let colorsDiv = document.createElement('div');
colorsDiv.style.display = 'grid';
colorsDiv.style.gridTemplateColumns = 'repeat(8, 1fr)';
colorsDiv.style.gap = '2px';
palettes[paletteName].forEach(function(color) {
let colorDiv = document.createElement('div');
colorDiv.style.width = '100%';
colorDiv.style.paddingTop = '100%';
colorDiv.style.backgroundColor = color;
colorsDiv.appendChild(colorDiv);
});
paletteDiv.appendChild(colorsDiv);
// Add click handler with proper closure
(function(name) {
paletteDiv.onclick = function() {
if (name === palette_name){
return;
}
//update nameDiv for previous and new item
set_modal_panel_selected_item(palette_name, name);
set_color_palette(name);
setVisuals(true);
saveFlickgameState();
};
})(paletteName);
grid.appendChild(paletteDiv);
}
// Add elements to modal
modal.appendChild(grid);
// Add modal to body
document.body.appendChild(modal);
// Position relative to trigger button, clamped to window
var pad = 8;
var trigger = (evt && evt.currentTarget) ? evt.currentTarget : (document.getElementById('palette_button') || document.querySelector('a[onclick*="openPaletteSelector"]'));
var rect = trigger ? trigger.getBoundingClientRect() : { top: pad, left: pad, bottom: pad + 40, right: pad + 40 };
var mw = modal.offsetWidth;
var mh = modal.offsetHeight;
var winW = window.innerWidth;
var winH = window.innerHeight;
var gap = 4;
// Prefer below, then right-aligned with button; if doesn't fit, try above or shift horizontal
var top = rect.bottom + gap;
var left = Math.min(rect.left, winW - pad - mw);
if (left < pad) left = pad;
if (top + mh > winH - pad) {
top = rect.top - gap - mh;
if (top < pad) top = pad;
}
if (top + mh > winH - pad) {
modal.style.maxHeight = (winH - pad - top) + 'px';
}
modal.style.top = top + 'px';
modal.style.left = left + 'px';
//invert color of #palette_button using a transform
var palette_button = document.getElementById('palette_button');
if (palette_button) {
palette_button.style.filter = 'invert(1)';
palette_button.style.webkitFilter = 'invert(1)';
}
}
var colorElem = new Array();
var layerElem = new Array();
var colorIndex = getRandomInt(7, 16);
var brushButtonsElem = null;
var lastBrushSize = 5;
var thumbnailCanvas = new Array();
var thumbnailContext = new Array();
var pagePickerEl = null;
var pagePickerColorIdx = -1;
function exportClick() {
closeBurgerDialog();
FlickgameShare.downloadStandaloneHtml(stateToString(), 'flickgame.html').catch(function (err) {
alert(err && err.message ? err.message : 'Failed to build download');
});
}
function getAuthURL() {
return FlickgameShare.getAuthUrl();
}
function printUnauthorized() {
var authUrl = getAuthURL();
var toPrint = "<a target=\"_blank\" href=\"" + authUrl + "\">Log in with Github to share</a>";
var shareLink = document.getElementById("shareLink");
if (shareLink) shareLink.innerHTML = toPrint;
var burgerShare = document.getElementById("burger-share-result");
if (burgerShare) burgerShare.innerHTML = toPrint;
shareLinkInner = null;
}
function githubLogOut() {
window.localStorage.removeItem("oauth_access_token");
var authUrl = getAuthURL();
var toPrint = "Logged out of Github.";
var shareLink = document.getElementById("shareLink");
if (shareLink) shareLink.innerHTML = toPrint;
var burgerShare = document.getElementById("burger-share-result");
if (burgerShare) burgerShare.innerHTML = toPrint;
shareLinkInner = null;
}
function shareClick() {
FlickgameShare.shareStateAsGist(stateToString(), {
onUnauthorized: printUnauthorized,
onError: function (msg) { alert(msg); },
onSuccess: function (result) {
var url = FlickgameShare.resolvePlayUrl(result.playUrl);
var shareHtml = "<a target=\"_blank\" href=\"" + url + "\">↳" + result.id + "</a> " +
'<span class="share-inline-meta">(<a onclick="githubLogOut();" href="javascript:void(0);">log out of GitHub</a>)</span>';
var shareLink = document.getElementById("shareLink");
if (shareLink) { shareLink.innerHTML = shareHtml; shareLinkInner = shareLink.childNodes[0]; }
var burgerShare = document.getElementById("burger-share-result");
if (burgerShare) burgerShare.innerHTML = shareHtml;
}
});
lastDownTarget = canvas;
}
function RLE_encode(input) {
var encoding = [];
var prev, count, i;
for (count = 1, prev = input[0], i = 1; i < input.length; i++) {
if (input[i] != prev) {
encoding.push(count);
encoding.push(prev);
count = 1;
prev = input[i];
}
else
count++;
}
encoding.push(count);
encoding.push(prev);
return encoding;
}
function stateToString() {
var state = new Object();
state.gameLink = gameLink;
state.activeIndex = canvasIndex;
state.canvasses = new Array();
state.palette_name = palette_name;
state.background_color = background_color;
state.foreground_color = foreground_color;
state.version = version;
state.width = width;
state.height = height;
for (var i = 0; i < 16; i++) {
var canvas = canvasses[i];
var s = "";
for (var j = 0; j < width * height; j++) {
s += canvas[j].toString(16);
}
var pairs = RLE_encode(s);
state.canvasses.push(pairs);
}
state.hyperlinks = hyperlinks;
var result = JSON.stringify(state);
return result;
}
function applyEditorDimensions() {
if (visibleCanvas) {
visibleCanvas.width = width * zoomFactor;
visibleCanvas.height = height * zoomFactor;
/* Mobile: flex + max-width/max-height + width/height auto can pick a transient layout box
whose aspect does not match the bitmap during rotation. Pin logical aspect to game pixels. */
if (typeof isMobileLayout === 'function' && isMobileLayout()) {
visibleCanvas.style.aspectRatio = width + ' / ' + height;
} else {
visibleCanvas.style.aspectRatio = '';
}
}
for (var i = 0; i < 16; i++) {
if (thumbnailCanvas[i]) {
thumbnailCanvas[i].width = getThumbCols();
thumbnailCanvas[i].height = getThumbRows();
}
}
}
function resizeCanvassesTo(newWidth, newHeight) {
var oldWidth = width;
var oldHeight = height;
if (newWidth === oldWidth && newHeight === oldHeight) return;
var bgIdx = nearest_color_index_in_palette(colorPalette, background_color);
var copyW = Math.min(oldWidth, newWidth);
var copyH = Math.min(oldHeight, newHeight);
for (var i = 0; i < 16; i++) {
var oldCanvas = canvasses[i];
var newCanvas = new Uint8Array(newWidth * newHeight);
for (var j = 0; j < newWidth * newHeight; j++) newCanvas[j] = bgIdx;
for (var r = 0; r < copyH; r++) {
for (var c = 0; c < copyW; c++) {
newCanvas[c + newWidth * r] = oldCanvas[c + oldWidth * r];
}
}
canvasses[i] = newCanvas;
}
width = newWidth;
height = newHeight;
}
function updateMobileToolbarBottomScale() {
var toolbar = document.querySelector('.mobile-toolbar-bottom');
var content = document.querySelector('.mobile-toolbar-bottom-content');
var maxControlSize = 100;
var baseControlSize = 30;
if (!toolbar || !content) return;
content.style.setProperty('--mobile-toolbar-bottom-scale', '1');
if (!isMobileLayout()) return;
var toolbarStyle = window.getComputedStyle(toolbar);
var availableWidth = toolbar.clientWidth - parseFloat(toolbarStyle.paddingLeft) - parseFloat(toolbarStyle.paddingRight);
var availableHeight = toolbar.clientHeight - parseFloat(toolbarStyle.paddingTop) - parseFloat(toolbarStyle.paddingBottom);
var naturalWidth = content.scrollWidth;
var naturalHeight = content.scrollHeight;
if (availableWidth <= 0 || availableHeight <= 0 || naturalWidth <= 0 || naturalHeight <= 0) return;
var maxScale = maxControlSize / baseControlSize;
var scaleByWidth = availableWidth / naturalWidth;
var scaleByHeight = availableHeight / naturalHeight;
var scale = layoutMode === 'mobile-portrait'
? Math.min(maxScale, scaleByWidth)
: Math.min(maxScale, scaleByWidth, scaleByHeight);
content.style.setProperty('--mobile-toolbar-bottom-scale', scale);
}
var mobileCanvasSettleToken = 0;
function scheduleMobileCanvasSizeSettle() {
var token = ++mobileCanvasSettleToken;
var maxFrames = 14;
var frames = 0;
function step() {
if (token !== mobileCanvasSettleToken) return;
if (frames++ >= maxFrames) return;
updateMobileCanvasSize(true);
var c = document.getElementById('mobile-canvas-container');
if (!c || !visibleCanvas) return;
var r = c.getBoundingClientRect();
var vvW = window.visualViewport ? window.visualViewport.width : window.innerWidth;
var vvH = window.visualViewport ? window.visualViewport.height : window.innerHeight;
var stillOversized = r.width > 0 && r.height > 0 && ((r.width > vvW * 1.15) || (r.height > vvH * 1.15));
if (stillOversized) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
function updateMobileCanvasSize(fromSettle) {
if (fromSettle === undefined) fromSettle = false;
if (!isMobileLayout()) return;
var container = document.getElementById('mobile-canvas-container');
if (!container || !visibleCanvas) return;
var rect = container.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
var vvW = window.visualViewport ? window.visualViewport.width : window.innerWidth;
var vvH = window.visualViewport ? window.visualViewport.height : window.innerHeight;
var oversized = (rect.width > vvW * 1.15) || (rect.height > vvH * 1.15);
if (oversized) {
if (!fromSettle) scheduleMobileCanvasSizeSettle();
return;
}
var scaleW = rect.width / width;
var scaleH = rect.height / height;
var newZoom = Math.min(scaleW, scaleH);
if (newZoom <= 0) return;
if (newZoom !== zoomFactor) {
zoomFactor = newZoom;
if (typeof resetViewTransform === 'function') resetViewTransform();
applyEditorDimensions();
setVisuals(true);
}
updateMobileToolbarBottomScale();
}
function mobileFillCanvasSize() {
if (!isMobileLayout()) return;
var container = document.getElementById('mobile-canvas-container');
if (!container) return;
var rect = container.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
var MAX_DIM = 160;
var w, h;
if (rect.width >= rect.height) {
// Landscape container: width is the longest dimension
w = MAX_DIM;
h = Math.floor(MAX_DIM * (rect.height / rect.width));
} else {
// Portrait container: height is the longest dimension
h = MAX_DIM;
w = Math.floor(MAX_DIM * (rect.width / rect.height));
}
// Keep things drawable even for extreme aspect ratios
w = Math.max(50, w);
h = Math.max(50, h);
resizeCanvassesTo(w, h);
applyEditorDimensions();
setVisuals(true);
}
function stringToState(str, sourceTag) {
var state = JSON.parse(str);
var stateWidth = state.width !== undefined ? state.width : 160;
var stateHeight = state.height !== undefined ? state.height : 100;
width = stateWidth;
height = stateHeight;
gameLink = state.gameLink;
if (state.activeIndex === undefined){
state.activeIndex = 0;
}
if (state.activeIndex >= 16){
state.activeIndex = 0;
}
canvasIndex = state.activeIndex;
//if palette_name not defined, set it to dawnbringer-16
if (state.palette_name === undefined){
state.palette_name = "dawnbringer-16";
}
//if version not defined, then I need to do the pallette_fix
if (state.version === undefined){//only introduced version numbers in v2
upgrade_v1_to_v2(state);
}
set_modal_panel_selected_item(palette_name,state.palette_name);
palette_name = state.palette_name;
set_color_palette(palette_name);
foreground_color = state.foreground_color;
changeBackgroundColor(state.background_color);
canvasses = new Array();
//trim state.canvasses to 16
state.canvasses = state.canvasses.slice(0, 16);
for (var k = 0; k < state.canvasses.length; k++) {
var s = state.canvasses[k];
var ar = new Uint8Array(stateWidth * stateHeight);
var index = 0;
for (var i = 0; i < s.length; i += 2) {
var count = s[i];
var ch = s[i + 1];
for (var j = 0; j < count; j++) {
ar[index] = parseInt(ch, 16);
index++;
}
}
canvasses.push(ar);
}
hyperlinks = state.hyperlinks;
// Normalize untrusted/corrupt hyperlinks so malformed imports/shares can't throw during rendering.
if (!Array.isArray(hyperlinks)) hyperlinks = [];
for (var hn = 0; hn < 16; hn++) {
if (!Array.isArray(hyperlinks[hn])) hyperlinks[hn] = new Array(16).fill(0);
}
// Clear undo so we don't restore pre-load state (e.g. empty init) when undoing
undoList.length = 0;
if (visibleCanvas) applyEditorDimensions();
}
function saveFlickgameState() {
if (typeof window.localStorage !== "undefined") {
try {
window.localStorage.setItem(FLICKGAME_STORAGE_KEY, stateToString());
} catch (e) {}
}
}
function loadFlickgameState() {
if (typeof window.localStorage === "undefined") return null;
try {
return window.localStorage.getItem(FLICKGAME_STORAGE_KEY);
} catch (e) {
return null;
}
}
function confirmNewFlickgame() {
if (isProjectBlank()) {
newFlickgame();
return;
}
closeBurgerDialog();
var overlay = document.createElement('div');
overlay.className = 'burger-dialog visible';
overlay.id = 'confirm-new-dialog';
var box = document.createElement('div');
box.className = 'burger-dialog-content';
box.style.textAlign = 'center';
var msg = document.createElement('p');
msg.textContent = 'Start a new flickgame? Unsaved changes will be lost.';
msg.style.marginTop = '0';
var btnRow = document.createElement('div');
btnRow.style.cssText = 'display:flex;gap:12px;justify-content:center;margin-top:16px;';
var btnOk = document.createElement('button');
btnOk.className = 'burger-dialog-btn';
btnOk.textContent = 'New Flickgame';
btnOk.style.cssText = 'flex:1;';
var btnCancel = document.createElement('button');
btnCancel.className = 'burger-dialog-btn';
btnCancel.textContent = 'Cancel';
btnCancel.style.cssText = 'flex:1;';
function dismiss() { if (overlay.parentNode) overlay.parentNode.removeChild(overlay); }
btnOk.addEventListener('click', function() { dismiss(); newFlickgame(); });
btnCancel.addEventListener('click', dismiss);
overlay.addEventListener('click', function(e) { if (e.target === overlay) dismiss(); });
btnRow.appendChild(btnOk);
btnRow.appendChild(btnCancel);
box.appendChild(msg);
box.appendChild(btnRow);
overlay.appendChild(box);
document.body.appendChild(overlay);
}
function newFlickgame(keepPalette) {
closeBurgerDialog();
resetViewTransform();
var w, h;
if (isMobileLayout()) {
mobileFillCanvasSize();
w = width;
h = height;
} else {
w = 160;
h = 100;
}
var emptyCanvasRle = [w * h, "0"];
var chosenPalette, chosenBg, chosenFg;
if (keepPalette) {
chosenPalette = palette_name;
chosenBg = background_color;
chosenFg = foreground_color;
} else {
var palette_names = Object.keys(palettes);
chosenPalette = palette_names[Math.floor(Math.random() * palette_names.length)];
chosenBg = "#000000";
chosenFg = "#ffffff";
}
var emptyState = {
gameLink: gameLink,
activeIndex: 0,
width: w,
height: h,
canvasses: Array(16).fill(emptyCanvasRle),
palette_name: chosenPalette,
background_color: chosenBg,
foreground_color: chosenFg,
version: version,
hyperlinks: Array.from({length: 16}, function() { return new Array(16).fill(0); })
};
stringToState(JSON.stringify(emptyState), 'new-flickgame');
setVisuals(true);
setLayer(1);
setDropdowns();
saveFlickgameState();
requestAnimationFrame(function() {
if (isMobileLayout()) updateMobileCanvasSize();
else updateDesktopScale();
});
}
document.addEventListener("keydown", press);
document.addEventListener("keyup", release);
document.addEventListener("wheel", wheel, {passive: false});
// Prevent Safari pinch-to-zoom on the page (gesturestart is Safari-only)
document.addEventListener("gesturestart", function(e) { e.preventDefault(); });
// Prevent double-tap zoom
document.addEventListener("dblclick", function(e) { e.preventDefault(); });
var copyImage = null;
var copyLinks = null;
function press(evt) {
evt = evt || window.event;
updateCursor(evt);
if (evt.keyCode === 67) { //c
doCopy();
} else if (evt.keyCode === 86) { //v
doPaste();
} else if (evt.keyCode === 189 || evt.keyCode === 173) {//- minus
var idx = BRUSH_SIZES.indexOf(radius);
if (idx > 0) setRadius(BRUSH_SIZES[idx - 1]);
} else if (evt.keyCode === 187 || evt.keyCode === 61) {//+ plus
var idx = BRUSH_SIZES.indexOf(radius);
if (idx >= 0 && idx < BRUSH_SIZES.length - 1) setRadius(BRUSH_SIZES[idx + 1]);
} else if (evt.keyCode === 90) {//z
doUndo();
}
}
function wheel(evt) {
if (evt.ctrlKey) {
evt.preventDefault();
var factor = evt.deltaY > 0 ? 1 / 1.1 : 1.1;
var newScale = Math.max(VIEW_MIN_SCALE, Math.min(VIEW_MAX_SCALE, viewScale * factor));
if (newScale !== viewScale) {
var canvasRect = visibleCanvas.getBoundingClientRect();
var ow = visibleCanvas.offsetWidth;
var oh = visibleCanvas.offsetHeight;
var anchorX = canvasRect.width > 0 ? (evt.clientX - canvasRect.left) / canvasRect.width * ow : 0;
var anchorY = canvasRect.height > 0 ? (evt.clientY - canvasRect.top) / canvasRect.height * oh : 0;
viewOffsetX = viewOffsetX + anchorX * (viewScale - newScale);
viewOffsetY = viewOffsetY + anchorY * (viewScale - newScale);
viewScale = newScale;
clampViewOffset();
applyViewTransform();
}
return;
}
if (evt.target === visibleCanvas) {
evt.preventDefault();
viewOffsetX -= evt.deltaX;
viewOffsetY -= evt.deltaY;
clampViewOffset();
applyViewTransform();
return;
}
var idx = BRUSH_SIZES.indexOf(radius);
if (evt.deltaY < 0) {
if (idx >= 0 && idx < BRUSH_SIZES.length - 1) setRadius(BRUSH_SIZES[idx + 1]);
} else if (evt.deltaY > 0) {
if (idx > 0) setRadius(BRUSH_SIZES[idx - 1]);
}
}
function release(evt) {
updateCursor(evt);
}
function doUndo() {
if (undoList.length > 0) {
var dat = undoList.pop();
if (dat.palette_name!==palette_name){
revert_color_palette_to(dat.palette_name);
setVisuals(true);
setDropdowns();
showActionFeedback(['toolbar_undo', 'mobile-undo-btn'], 'Undo!');
return;
}
canvasses[dat.canvasIndex] = dat.canvasDat;
colorPalette = palettes[palette_name];
updatePaletteRGB();
if (background_color !== dat.background_color){
changeBackgroundColor(dat.background_color,false);
}
setLayer(dat.canvasIndex + 1,true);
saveFlickgameState();
showActionFeedback(['toolbar_undo', 'mobile-undo-btn'], 'Undo!');
if (shareLinkInner !== null) {
shareLinkInner.style.color = "gray";
}
}
}
function copyLayerImageToSystemClipboard() {
if (!visibleCanvas || !visibleCanvas.width || !navigator.clipboard || typeof ClipboardItem === 'undefined') {
return;
}
drawCanvasFast();
var out = document.createElement('canvas');
out.width = width;
out.height = height;
var octx = out.getContext('2d');
if (!octx) return;
octx.imageSmoothingEnabled = false;
octx.drawImage(visibleCanvas, 0, 0, visibleCanvas.width, visibleCanvas.height, 0, 0, width, height);
// Safari: clipboard.write must run in the same user-gesture turn as the click, not inside
// toBlob's callback (NotAllowedError). Pass Promise<Blob> into ClipboardItem so write() is sync.
try {
var pngPromise = new Promise(function(resolve, reject) {
out.toBlob(function(blob) {
if (!blob) reject(new Error('toBlob failed'));
else resolve(blob);
}, 'image/png');
});
navigator.clipboard.write([new ClipboardItem({ 'image/png': pngPromise })]).catch(function() {});
} catch (e) {}
}
function doCopy() {
copyImage = JSON.stringify(canvasses[canvasIndex])
copyLinks = JSON.stringify(hyperlinks[canvasIndex])
copyLayerImageToSystemClipboard();
showCopyFeedback();
updatePasteButtonState();
}
function showActionFeedback(ids, text) {
for (var i = 0; i < ids.length; i++) {
var el = document.getElementById(ids[i]);
if (!el) continue;
if (el.tagName === 'IMG') el = el.parentElement;
if (!el) continue;
el.style.position = 'relative';
var existing = el.querySelector('.action-feedback');
if (existing) existing.remove();
var label = document.createElement('span');
label.className = 'action-feedback';
label.textContent = text;
el.appendChild(label);
(function(l) {
setTimeout(function() { l.classList.add('fade-out'); }, 50);
setTimeout(function() { l.remove(); }, 1200);
})(label);
}
}
function showCopyFeedback() {
var thumbImg = document.getElementById('copy-thumb-img');
var desktopThumbImg = document.getElementById('desktop-copy-thumb-img');
if (thumbImg || desktopThumbImg) {
var thumbCanvas = document.createElement('canvas');
thumbCanvas.width = width;
thumbCanvas.height = height;
var ctx = thumbCanvas.getContext('2d');
var src = canvasses[canvasIndex];
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
ctx.fillStyle = colorPalette[src[i + width * j]];
ctx.fillRect(i, j, 1, 1);
}
}
var dataUrl = thumbCanvas.toDataURL();
if (thumbImg) thumbImg.setAttribute('href', dataUrl);
if (desktopThumbImg) desktopThumbImg.setAttribute('href', dataUrl);
}
showActionFeedback(['mobile-copy-btn', 'toolbar_copy'], 'Copied!');
}
function doPaste() {
if (copyImage !== null) {
preserveUndoState();
var ar = JSON.parse(copyImage);
var arui8 = new Uint8Array(width * height);
for (var i = 0; i < width * height; i++) {
arui8[i] = ar[i];
}
canvasses[canvasIndex] = arui8;
hyperlinks[canvasIndex] = JSON.parse(copyLinks);
setVisuals();
setDropdowns();
refreshPointerModeCursor();
saveFlickgameState();
showPasteFeedback();
}
}
function showPasteFeedback() {
showActionFeedback(['mobile-paste-btn', 'toolbar_paste'], 'Pasted!');
}
function updatePasteButtonState() {
var btn = document.getElementById('mobile-paste-btn');
if (!btn) return;
if (copyImage !== null) {
btn.disabled = false;
btn.classList.remove('disabled');
} else {
btn.disabled = true;
btn.classList.add('disabled');
}
}
function createSwatchElement(index) {
var a = document.createElement('a');
a.href = '#';
a.onclick = (function(n) { return function(e) { setColor(n, e); return false; }; })(index);
var d = document.createElement('div');
d.className = 'swatch-button unselected';
d.id = 'color_' + index;
var chip = document.createElement('span');
chip.className = 'swatch-chip';
d.appendChild(chip);
var arrow = document.createElement('span');
arrow.className = 'swatch-arrow';
arrow.setAttribute('aria-hidden', 'true');
d.appendChild(arrow);
var status = document.createElement('span');
status.className = 'swatch-status';
var icon = document.createElement('span');
icon.className = 'swatch-link-icon';
icon.setAttribute('aria-hidden', 'true');
status.appendChild(icon);
var label = document.createElement('span');
label.className = 'link-label';
status.appendChild(label);
d.appendChild(status);
a.appendChild(d);
return a;
}
function getUsedColorsOnCurrentPage() {
var used = new Set();
if (canvasses[canvasIndex]) {
var canvas = canvasses[canvasIndex];
for (var k = 0; k < canvas.length; k++) used.add(canvas[k]);
}
return used;
}
function renderSwatches() {
if (!colorElem.length) return;
var used = getUsedColorsOnCurrentPage();
for (var i = 0; i < 16; i++) {
var swatch = colorElem[i];
if (!swatch) continue;
var label = swatch.querySelector('.link-label');
var linkVal = hyperlinks[canvasIndex][i];
var usedOnCurrentPage = used.has(i);
var hasTarget = linkVal > 0;
var targetOffPage = hasTarget && !usedOnCurrentPage;
var contrastColor = paletteContrastColors[i];
var statusColor = SWATCH_LAYOUT_VARIANT === 'split' ? 'var(--foreground-color)' : contrastColor;
var labelColor = '';
swatch.classList.toggle('selected', i === colorIndex);
swatch.classList.toggle('unselected', i !== colorIndex);
swatch.classList.toggle('state-unused', !usedOnCurrentPage && !hasTarget);
swatch.classList.toggle('state-used', usedOnCurrentPage && !hasTarget);
swatch.classList.toggle('state-linked', usedOnCurrentPage && hasTarget);
swatch.classList.toggle('state-linked-offpage', targetOffPage);
swatch.style.color = statusColor;