-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1430 lines (1250 loc) · 40.4 KB
/
app.js
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
// poor man's jquery
const $ = document.querySelector.bind(document);
const $$ = (q, el) => Array.from((el || document).querySelectorAll(q));
let pixels, dropWidth, dropHeight;
const debounceRepaint = debounce(repaintPreview, 1000);
const history = [];
let undoStack = [];
let used = [];
let shiftDown = false;
let altDown = false;
let previewOk = false;
const piOver4 = Math.PI/4;
const magic = 'palette.brickadia.dev'.split('').map(p => p.charCodeAt(0));
// turn bytes into hex
const hexFromBytes = rgb => rgb.map(i => i.toString(16).padStart(2, '0')).join('');
// add a palette snapshot to history
// if you read this code and want to kill me, I understand
function snapshot() {
history.push($('#palette').innerHTML);
save();
debounceRepaint();
// remove entries over 1000
history.splice(1000);
undoStack = [];
}
// undo an undo
function redo() {
if (!undoStack.length) return;
const state = undoStack.pop();
history.push(state);
$('#palette').innerHTML = state;
save();
debounceRepaint();
}
// undo some history
function undo() {
if (history.length < 2) return;
const state = history.pop();
undoStack.push(state);
$('#palette').innerHTML = history[history.length - 1];
save();
debounceRepaint();
}
// get hex color at
const getHexAt = (x, y) => {
const off = (
dropWidth * Math.min(Math.max(y, 0), dropHeight - 1) +
Math.min(Math.max(x, 0), dropWidth - 1)
) * 4;
return [pixels[off], pixels[off+1], pixels[off+2]].map(i =>
i.toString(16).padStart(2, '0')).join('');
}
let rowColors = [];
let rowColors2D = [];
// draw the drag color select widget
function drawSelectLine([sX, sY]=[-1,-1], [eX, eY]=[-1,-1], dragSizeX=2, [e2X, e2Y]=[-1, -1], dragSizeY=1) {
if (!pixels) return;
// angle between start and end
let thetaX = Math.atan2(eY - sY, eX - sX);
// length between start and end
const lengthX = Math.hypot(sY - eY, sX - eX);
// size of line divided into chunks
const segmentX = lengthX / (dragSizeX - 1);
// if shift key is pressed, round angles to 45deg
if (shiftDown) {
thetaX = Math.round(thetaX/(piOver4))*(piOver4);
eX = sX + Math.cos(thetaX) * lengthX;
eY = sY + Math.sin(thetaX) * lengthX;
}
// same thing for the second drag
let thetaY = Math.atan2(e2Y - eY, e2X - eX);
let lengthY = Math.hypot(e2Y - eY, e2X - eX);
let segmentY = lengthY / (dragSizeY - 1);
// if shift key is pressed, round angles on y axis to 45deg
// these can't be done at the same time because thetaY/etc depend on the updated eX/eY
if (shiftDown && dragSizeY > 1) {
thetaY = Math.round(thetaY/(piOver4))*(piOver4);
e2X = eX + Math.cos(thetaY) * lengthY;
e2Y = eY + Math.sin(thetaY) * lengthY;
lengthY = Math.hypot(e2Y - eY, e2X - eX);
segmentY = lengthY / (dragSizeY - 1);
}
// size of the pin
const wedgeSize = 10;
// reset canvas
const overlay = $('#overlay');
const ctx = overlay.getContext('2d');
ctx.font = '14px \'Inconsolata\'';
ctx.fontWeight = 'bold';
ctx.strokeStyle = 'black';
ctx.lineWidth = 1;
ctx.clearRect(0, 0, dropWidth, dropHeight);
// colors used in the drag
rowColors = [];
rowColors2D = [];
if (lengthX < 10)
return;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
dropper.style.display = 'none';
const markerAt = (x, y, hex) => {
ctx.save();
ctx.translate(x, y -1.41 * wedgeSize / 2);
ctx.beginPath();
ctx.moveTo(0, 1.41 * wedgeSize / 2);
ctx.arc(0, -1.41 * wedgeSize / 2, 10, Math.PI, 0);
ctx.lineTo(0, 1.41 * wedgeSize / 2);
ctx.closePath();
ctx.fillStyle = '#' + hex;
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke();
ctx.fill();
ctx.lineWidth = 1;
const isDuplicate = used.includes(hex) || rowColors.includes(hex);
ctx.strokeStyle = isDuplicate ? '#f55' : 'white';
ctx.stroke();
// draw an X for duplicate colors
if (isDuplicate) {
ctx.translate(0, -1.14 * wedgeSize/2);
ctx.fillStyle = 'black'
ctx.fillText('x', 1, 1);
ctx.fillStyle = 'white'
ctx.fillText('x', 0, 0);
}
rowColors.push(hex);
rowColors2D[rowColors2D.length - 1].push(hex);
ctx.restore();
};
for (let j = 0; j < dragSizeY; j++) {
rowColors2D.push([]);
const offX = dragSizeY > 1 ? Math.round(Math.cos(thetaY) * j * segmentY + sX) : sX;
const offY = dragSizeY > 1 ? Math.round(Math.sin(thetaY) * j * segmentY + sY) : sY;
ctx.save();
ctx.translate(offX, offY);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(eX - sX, eY - sY);
ctx.closePath();
ctx.stroke();
for (let i = 0; i < dragSizeX; i++) {
const x = Math.round(Math.cos(thetaX) * i * segmentX);
const y = Math.round(Math.sin(thetaX) * i * segmentX);
if (dragSizeY > 1 && j === 0) {
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(
x + Math.round(Math.cos(thetaY) * lengthY),
y + Math.round(Math.sin(thetaY) * lengthY),
);
ctx.closePath();
ctx.stroke();
}
markerAt(x, y, getHexAt(x + offX, y + offY));
}
ctx.restore();
}
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
const text = 'Selection: ' + dragSizeX + (dragSizeY > 1 ? ' x ' + dragSizeY : '');
ctx.fillStyle = 'white'
ctx.fillText(text, 6, 6);
ctx.fillStyle = 'black'
ctx.fillText(text, 5, 5);
}
let dragging = false;
let dragSizeX = 2;
let dragSizeY = 1;
let was2D = false;
let startPos = [-1, -1]; // drag start position
let dragPosX = [-1, -1]; // first dimension dragging
let dragPosY = [-1, -1]; // second dimension dragging
// length of drag
const dragLength = () => Math.hypot(
startPos[1] - (dragSizeY > 1 ? dragPosY[1] : dragPosX[1]),
startPos[0] - (dragSizeY > 1 ? dragPosY[0] : dragPosX[0]),
);
// insert a list of colors
const insertColors = (colors, forceGroup) => {
const selected = $('.selected');
const hex = colors[0];
if (!selected || forceGroup) {
// create a new group if there is nothing currently selected
const group = createGroup([], colors.length !== 1);
for (const hex of colors)
group.appendChild(createColor(hex, true));
if (!forceGroup)
snapshot();
} else if (selected.classList.contains('group')) {
// add a new color to the group if a group is selected
for (const hex of colors)
selected.appendChild(createColor(hex, true));
snapshot();
// a color is selected but we're dragging - add after this color
} else if (selected.classList.contains('color') && colors.length > 1) {
colors.reverse();
for(const hex of colors)
selected.after(createColor(hex, true));
snapshot();
} else if (colors.length === 1 && selected.classList.contains('color') && selected.getAttribute('hex') !== hex) {
// update a color if a color is selected
selected.style.backgroundColor = '#' + hex;
selected.setAttribute('hex', hex);
snapshot();
}
}
window.onload = () => {
repaintPreview();
$('#downloadButton').onclick = savePreset;
$('#selector').style.display = 'none';
// hide the dropper on mouse leave
$('#selector').onmouseleave = e => {
const dropper = $('#dropper');
dropper.style.display = 'none';
document.body.style.overflow = 'auto';
drawSelectLine();
dragging = false;
};
$('#selector').onmousedown = e => {
altDown = e.altKey;
shiftDown = e.shiftKey;
const { layerX: x, layerY: y } = e;
if (!pixels) return;
// left button
if (e.button === 0) {
startPos = [x, y];
dragPosX = [x, y];
dragPosY = [-1, -1];
dragSizeY = 1;
dragging = true;
was2D = false;
}
// right button
if (e.button === 2 && dragging && dragLength() >= 10) {
if (dragSizeY > 1) {
dragPosY = [-1, -1];
dragSizeY = 1;
} else {
dragPosY = [x, y];
dragSizeY = 2;
was2D = true;
}
}
};
$('#selector').oncontextmenu = e => {
altDown = e.altKey;
shiftDown = e.shiftKey;
if (dragging && dragLength() >= 10) {
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
}
}
const resetCopy = debounce(() => $('.preview').classList.remove('copied'), 1000);
const resetDownload = debounce(() => $('.preview').classList.remove('saved'), 1000);
$('.preview').onclick = async e => {
if (shiftDown) {
await buildPaletteSave();
$('.preview').classList.add('saved');
resetDownload();
return;
}
try {
$('#testImg').toBlob(blob => {
navigator.clipboard.write([
new ClipboardItem({'image/png': blob})
]);
$('.preview').classList.add('copied');
resetCopy();
});
} catch (err) {
console.error('error getting image from canvas', err);
}
};
window.onwheel = e => {
altDown = e.altKey;
shiftDown = e.shiftKey;
if (dragging) {
if (dragSizeY > 1 && !altDown) {
dragSizeY = Math.min(Math.max(dragSizeY - Math.sign(e.deltaY), 2), 16);
} else {
dragSizeX = Math.min(Math.max(dragSizeX - Math.sign(e.deltaY), 2), 16);
if (altDown) {
dragSizeY = shiftDown ? dragSizeX : Math.max(Math.min(Math.floor(
Math.abs(dragPosY[0] - startPos[0])/
(Math.abs(dragPosY[1] - startPos[1]))*dragSizeX+1
), 16), 2);
}
}
drawSelectLine(startPos, dragPosX, dragSizeX, dragPosY, dragSizeY);
}
};
$('#selector').onmouseup = e => {
altDown = e.altKey;
shiftDown = e.shiftKey;
if (e.button === 0 && dragging && was2D) {
$('#selector').onclick(e);
}
};
// set the eyedrop color on hover
$('#selector').onmousemove = e => {
altDown = e.altKey;
shiftDown = e.shiftKey;
const { layerX: x, layerY: y } = e;
const dropper = $('#dropper');
if (dragging) {
if (altDown) {
if (shiftDown) {
const dx = (x - startPos[0]);
const dy = (y - startPos[1]);
const max = Math.max(Math.abs(dx), Math.abs(dy));
dragPosX = [startPos[0], startPos[1] + max * Math.sign(dy)]
dragPosY = [startPos[0] + max * Math.sign(dx), startPos[1] + max * Math.sign(dy)];
dragSizeY = dragSizeX;
} else {
dragPosX = [startPos[0], y]
dragPosY = [x, y];
dragSizeY = Math.max(Math.min(Math.floor(
Math.abs(dragPosY[0] - startPos[0])/
(Math.abs(dragPosY[1] - startPos[1]))*dragSizeX+1
), 16), 2);
}
} else {
if (dragSizeY > 1) {
dragPosY = [x, y];
drawSelectLine(startPos, dragPosX, dragSizeX, dragPosY, dragSizeY);
return;
} else {
dragPosX = [x, y];
}
}
if (dragLength() >= 10) {
drawSelectLine(startPos, dragPosX, dragSizeX, dragPosY, dragSizeY);
document.body.style.overflow = 'hidden';
return;
} else {
drawSelectLine();
document.body.style.overflow = 'flex';
}
}
if (!pixels) return;
const off = (dropWidth * y + x) * 4;
if ((pixels[off+3]) === 0) {
dropper.style.display = 'none';
return;
}
dropper.style.display = 'flex';
dropper.style.left = x + 'px';
dropper.style.top = y + 'px';
if (y < 40) {
dropper.style.transform = 'translate(-50%, 0)';
} else {
dropper.style.transform = 'translate(-50%, -100%)';
}
dropper.style.backgroundColor = `rgb(${pixels[off]}, ${pixels[off+1]}, ${pixels[off+2]})`;
const hex = getHexAt(x, y);
if (used.includes(hex))
dropper.innerHTML = '✓';
else
dropper.innerHTML = '';
};
// add the color on click
$('#selector').onclick = e => {
altDown = e.altKey;
shiftDown = e.shiftKey;
if (!pixels) return;
// handle drag color selectin
if (dragging) {
const length = Math.hypot(startPos[1] - dragPosX[1], startPos[0] - dragPosX[0]);
document.body.style.overflow = 'auto';
dragging = false;
// insert multiple colors if the drag is a success
if (length >= 10) {
if (rowColors2D.length > 1) {
for (const colors of rowColors2D) {
insertColors(colors, true);
}
snapshot();
} else {
insertColors(rowColors);
}
drawSelectLine([-1, -1], [-1, -1], 0);
return;
}
}
drawSelectLine([-1, -1], [-1, -1], 0);
const { layerX: x, layerY: y } = e;
const off = (dropWidth * y + x) * 4;
const hex = hexFromBytes([pixels[off], pixels[off+1], pixels[off+2]]);
if ((pixels[off+3]) === 0) return;
// insert an individual color
insertColors([hex]);
genFavicon('#' + hex);
};
$$('.images img').forEach(el => el.onclick = () => renderEyedropImage(el));
// allow dropping of files in
document.body.ondrop = async e => {
e.preventDefault();
e.stopPropagation();
if (e.dataTransfer.items) {
const item = e.dataTransfer.items[0];
const file = item.getAsFile();
if (!file) return;
if (item.type === 'text/plain' ||
file.name.match(/.(bp|pal|txt|gpl)$/i)
) {
try {
importText(await file.text());
} catch (err) {
console.warn('error parsing text', file, err);
}
}
if (item.type.startsWith('image/')) {
try {
importImage(file);
} catch (err) {
console.warn('error importing image', file, err);
}
}
}
};
document.body.ondragover = e => {
e.preventDefault();
e.stopPropagation();
};
try {
if (localStorage.temp) {
initPalette(JSON.parse(localStorage.temp));
} else {
initPalette();
}
} catch (e) {
console.warn('error parsing json', e);
initPalette();
}
snapshot();
};
// swap to elements in dom
function swapDom(a, b) {
const aParent = a.parentNode;
const bParent = b.parentNode;
const aHolder = document.createElement('div');
const bHolder = document.createElement('div');
aParent.replaceChild(aHolder, a);
bParent.replaceChild(bHolder, b);
aParent.replaceChild(b, aHolder);
bParent.replaceChild(a, bHolder);
}
// when you paste, render the image on the canvas
document.onpaste = e => {
const items = Array.from(e.clipboardData.items)
.filter(i => i.type.indexOf('image') === 0);
if (items.length > 0) {
importImage(items[0].getAsFile());
} else {
let pasteData = e.clipboardData.getData('Text');
importText(pasteData);
}
};
// get the color or group given a column and a row
const getSwatchAt = (col, row=-1) => {
const group = $$('.group')[col];
const colors = $$('.color', group);
return row > -1 && colors.length > row ?
colors[Math.min(row, colors.length - 1)]
: row == -2
? colors[colors.length - 1]
: group;
};
// get the position of a color/group
const getIndex = el => {
const groups = $$('.group');
// if the selected thing is a group, return -1 for the row
if (el.classList.contains('group')) return [groups.findIndex(e => e == el), -1];
// otherwise return the group and index
return [groups.findIndex(e => e == el.parentNode), $$('.color', el.parentNode).findIndex(e => e == el)];
};
// keybinds
document.onkeydown = e => {
const selected = $('.selected');
if (e.key === 'Shift') {
shiftDown = true;
}
if (e.key === 'Alt') {
altDown = true;
}
// if shift key is pressed, use swap instead of select
const modFn = e.shiftKey ? el => {
// if the swap would be illegal, do a select instead
if (el.classList.contains('group') && selected.classList.contains('color') ||
selected.classList.contains('group') && el.classList.contains('color'))
return select(el);
// swap the dom and save to history
swapDom(selected, el);
snapshot();
} : select;
// undo and redo on CTRL + Z
if (e.code === 'KeyZ' && e.ctrlKey) {
if (e.shiftKey)
redo()
else
undo();
save();
// rename group on r
} else if (e.code === 'KeyR' && !e.ctrlKey && !e.shiftKey) {
if (!selected || !selected.classList.contains('group')) return;
const name = prompt('Enter a column name', selected.getAttribute('name'));
if (name) {
selected.setAttribute('name', name);
snapshot();
}
// change palette description on shift R
} else if (e.code === 'KeyR' && !e.ctrlKey && e.shiftKey) {
const btn = $('#palette > .add');
const description = prompt('Enter a palette description', btn.getAttribute('description'));
if (description) {
btn.setAttribute('description', description);
snapshot();
}
} else if (e.code === 'KeyC' && !e.ctrlKey && !e.shiftKey) {
$('#colorPicker').value = '#' + (selected && selected.classList.contains('color')
? selected.getAttribute('hex')
: 'ffffff');
$('#colorPicker').onchange = e => {
insertColors([e.target.value.replace(/^#/, '')]);
$('#colorPicker').onchange = () => {};
};
$('#colorPicker').click();
// save on ctrl s
} else if (e.code === 'KeyS' && e.ctrlKey && e.shiftKey) {
e.preventDefault();
savePreset();
} else if ((e.code === 'KeyS' || e.code === 'KeyW') && e.ctrlKey) {
e.preventDefault(); // prevent annoying save popup
} else if (e.code === 'KeyW') {
// if nothing is selected, select the first group
if (!selected) return modFn(getSwatchAt(0));
const [col, row] = getIndex(selected);
const lastColor = getSwatchAt(col, -2);
// if the group is selected, select the last color
if ((row === -1 || row === 0 && e.shiftKey) && lastColor) {
modFn(lastColor);
// select the group if it's the first color
} else if (row === 0) {
modFn(getSwatchAt(col));
// otherwise select the previous color
} else {
modFn(getSwatchAt(col, row-1));
}
} else if (e.code === 'KeyS') {
const selected = $('.selected');
// if nothing is selected, select the first group
if (!selected) return modFn(getSwatchAt(0));
const [col, row] = getIndex(selected);
const firstColor = getSwatchAt(col, 0);
// if the group is selected, select the last color
if (row === -1 && firstColor) {
modFn(firstColor);
// otherwise select the previous color
} else {
// if there's no more colors in this group, select the group
if (row + 1 >= $$('.color', getSwatchAt(col)).length) {
modFn(getSwatchAt(col, e.shiftKey ? 0 : -1));
} else {
// otherwise select the next color
modFn(getSwatchAt(col, row+1));
}
}
} else if (e.code === 'KeyA' && !e.ctrlKey) {
// if nothing is selected, select the first group
if (!selected) return modFn(getSwatchAt(0));
// select the previous group + wrap around
const [col, row] = getIndex(selected);
const numGroups = $$('.group').length;
if (numGroups < 2) return;
modFn(getSwatchAt((col + numGroups - 1) % numGroups, row));
} else if (e.code === 'KeyD' && !e.ctrlKey) {
if (!selected) return modFn(getSwatchAt(0));
// select the next group + wrap around
const [col, row] = getIndex(selected);
const numGroups = $$('.group').length;
if (numGroups < 2) return;
modFn(getSwatchAt((col + 1) % numGroups, row));
// move color to the left
} else if (e.code === 'KeyA' && e.ctrlKey) {
e.preventDefault();
// if nothing is selected, ignore
if (!selected) return;
// select the previous group + wrap around
const [col, row] = getIndex(selected);
const numGroups = $$('.group').length;
if (numGroups < 2) return;
const el = getSwatchAt((col + numGroups - 1) % numGroups, row);
// ignore group movements
if (selected.classList.contains('group')) return;
// if the dest is a group, put the color in there
if (el.classList.contains('group')) {
el.appendChild(selected);
} else {
// move selected to the element
el.before(selected);
}
snapshot();
// move color to the right
} else if (e.code === 'KeyD' && e.ctrlKey) {
e.preventDefault();
if (!selected) return;
// select the next group + wrap around
const [col, row] = getIndex(selected);
const numGroups = $$('.group').length;
if (numGroups < 2) return;
const el = getSwatchAt((col + 1) % numGroups, row);
// ignore group movements
if (selected.classList.contains('group')) return;
// if the dest is a group, put the color in there
if (el.classList.contains('group')) {
el.appendChild(selected);
} else {
// move selected to the element
el.before(selected);
}
snapshot();
// insert a color in the group or after the existing swatch
} else if (e.code === 'KeyE' && !e.shiftKey) {
if (!selected) {
const group = createGroup([]);
group.appendChild(createColor('ffffff'));
snapshot();
return;
}
// if the dest is a group, put the color in there
if (selected.classList.contains('group')) {
selected.appendChild(createColor('ffffff'));
} else {
// move selected to the element
selected.after(createColor('ffffff'));
}
snapshot();
// delete everything
} else if (e.code === 'Delete' && e.shiftKey && e.ctrlKey) {
e.preventDefault();
initPalette();
snapshot();
// delete selected thing
} else if (e.code === 'Delete' && !e.shiftKey && !e.ctrlKey || e.code === 'KeyX' && e.shiftKey) {
if (!selected) return;
// delete a group, select previous group
if (selected.classList.contains('group')) {
if (selected.nextSibling && selected.nextSibling.classList.contains('group')) {
// select the next group
select(selected.nextSibling);
} else if (selected.previousSibling && selected.previousSibling.classList.contains('group')) {
// select the previous group
select(selected.previousSibling);
} else {
// select the first group
const groups = $$('.group').filter(g => g !== selected);
if (groups.length > 0)
select(groups[0]);
}
// delete a color, select previous color
} else if (selected.classList.contains('color')) {
// if the previous sibling is a color, select it
if (selected.nextSibling && selected.nextSibling.classList.contains('color'))
select(selected.nextSibling);
else if (selected.previousSibling && selected.previousSibling.classList.contains('color'))
select(selected.previousSibling);
else
// select the group instead
select(selected.parentNode);
}
selected.remove();
snapshot();
// delete whatever is selected
} else if (e.code === 'Space') {
e.preventDefault();
$$('.selected').forEach(e => e.classList.remove('selected'));
// next group/new group
} else if (e.key === 'Enter' || e.code === 'KeyE' && e.shiftKey) {
// nothing is selected - create a new group
if (!selected || selected.classList.contains('color')) {
createGroup([]);
snapshot();
// a group is selected
} else if (selected.classList.contains('group')) {
// if there is a next group, select it
if (selected.nextSibling) {
select(selected.nextSibling);
} else {
// otherwise create a new group
createGroup([]);
snapshot();
}
}
} else {
// debug key stuff
// console.log(e.key, e.code, e);
}
};
document.onkeyup = e => {
if (e.key === 'Shift') {
shiftDown = false;
}
if (e.key === 'Alt') {
altDown = false;
}
};
// save the preset as a .bp
function savePreset() {
if ($$('.color').length === 0) return;
const name = prompt('Enter a save name', localStorage.lastName || 'Generated');
if (typeof name === 'object') return;
localStorage.lastName = name;
$('#download').href = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(save(), 0, 2));
$('#download').download = name + '.bp';
$('#download').click();
}
// update the color selecting canvas with an image
function renderEyedropImage(image) {
// create the element
const canvas = $('#selector');
canvas.style.display = 'block';
const overlay = $('#overlay');
const ctx = canvas.getContext('2d');
const octx = overlay.getContext('2d');
const margin = 32;
// set the canvas size
canvas.style.width =
overlay.style.width = (
canvas.width = ctx.canvas.width =
overlay.width = octx.canvas.width =
dropWidth = (image.naturalWidth + margin * 2)
) + 'px';
canvas.style.height =
overlay.style.height = (
canvas.height = ctx.canvas.height =
overlay.height = octx.canvas.height =
dropHeight = (image.naturalHeight + margin * 2)
) + 'px';
$('.eyedrop-container').style.width = dropWidth + 18 + 'px';
$('.eyedrop-container').style.height = dropHeight + 18 + 'px';
// draw the image
ctx.drawImage(image, margin, margin);
const imageData = ctx.getImageData(0, 0, dropWidth, dropHeight);
pixels = imageData.data;
const offX = dropWidth - margin - 1;
const offY = dropHeight - margin - 1;
let isPreview = true;
for (let i = 0; i < magic.length/3; i++) {
const shift = ((offX - i) + (dropWidth * offY)) * 4;
if (
magic[i * 3 + 0] !== pixels[shift + 0] ||
magic[i * 3 + 1] !== pixels[shift + 1] ||
magic[i * 3 + 2] !== pixels[shift + 2])
isPreview = false;
}
// if this is a preview image, import it based on the mini palette in the corner
if (isPreview) {
const groups = [];
for (let x = 0; x < 16; x++) {
if (pixels[((offX - x) + (dropWidth * (offY - 1))) * 4 + 3] === 0) break;
groups.push([])
for (let y = 0; y < 16; y++) {
const shift = ((offX - x) + (dropWidth * (offY - y - 1))) * 4;
// if there is an alpha, end this group
if (pixels[shift + 3] === 0) break;
// add the color to the group
groups[groups.length - 1].push(linearRGB([
pixels[shift + 0], pixels[shift + 1], pixels[shift + 2]
]));
}
// remove empty group
if (groups[groups.length - 1].length === 0) groups.pop();
}
// importh the preview image
if (groups.length > 0) {
const data = {
description: 'Imported from palette.brickadia.dev preview',
groups: groups.map(gr => ({
colors: gr.map(([r,g,b]) =>
({r, g, b, a: 255}))
})),
}
initPalette(data);
snapshot();
}
}
$('.instructions').style.display = 'none';
}
// create + button
function addBtn() {
const elem = document.createElement('div');
elem.className = 'add button';
elem.innerText = '+';
return elem;
}
// select an element
function select(elem) {
if (!elem) return;
$$('.selected').forEach(e => e.classList.remove('selected'));
elem.classList.add('selected');
}
// create a color
function createColor(hex, ignoreSelect) {
const colorElem = document.createElement('div');
colorElem.className = 'color';
colorElem.setAttribute('hex', hex);
colorElem.style.backgroundColor = '#' + hex;
if (!ignoreSelect)
select(colorElem);
return colorElem;
}
// create a group
function createGroup(colors, ignoreSelect) {
const palette = $('#palette');
const group = document.createElement('div');
group.className = 'group';
group.setAttribute('name', 'Group ' + ($$('.group').length + 1));
const stub = document.createElement('div');
stub.className = 'stub button';
group.appendChild(stub);
group.appendChild(addBtn());
palette.appendChild(group);
if (!ignoreSelect)
select(group);
for (const {r: lR, g: lG, b: lB} of colors) {
const [r, g, b] = sRGB([lR, lG, lB]);
group.appendChild(createColor([r, g, b].map(i =>
i.toString(16).padStart(2, '0')).join(''), true));
}
return group;
}
// convert srgb to linear rgb
const linearRGB = rgba =>
rgba.map((c, i) => i === 3
? c
: Math.round(((c/255) > 0.04045 ? Math.pow((c/255) * (1.0 / 1.055) + 0.0521327, 2.4 ) : (c/255) * (1.0 / 12.92))*255)
);
// convert linear rgb to srgb
const sRGB = linear =>
linear.map((c, i) => i === 3
? c
: Math.round(((c/255) > 0.0031308
? 1.055 * Math.pow((c/255), 1/2.4) - 0.055
: c / 255 * 12.92)*255)
);
// save the palette to data
function save() {
used = [];
const data = {
// generate the preset file
formatVersion: '1',
presetVersion: '1',
type: 'ColorPalette',
data: {
description: $('#palette > .add').getAttribute('description') || 'Built with palette.brickadia.dev',
// populate columns
groups: $$('.group').map((c, columnIndex) => {
// convert colors to linear rgb from whatever format is thrown in
return {
name: c.getAttribute('name') || ('Group ' + (columnIndex + 1)),
colors: $$('.color', c).map(e => {
// a technique so cursed you will shit the bed (pulling rgb from hex)
let [sR, sG, sB] = e.style.backgroundColor.match(/[\d\.]+/g).map(Number);
// convert to hex
const hex = hexFromBytes([sR, sG, sB]);
used.push(hex);