-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.es-latest.js
16697 lines (13611 loc) · 380 KB
/
index.es-latest.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
'use strict';
//* TODO ---------------------- UI, menu: -------------------------------------
//* TODO: consistent UI colors (what blue, yellow, white, etc. means across the whole page).
//* TODO: checkbox/selectbox to sync clicked/all option/export actions in selected project onto all opened projects, where possible.
//* TODO: find zoom/scale of the screen/page before regenerating thumbnails.
//* TODO: options menu: add/remove/copy/edit colors and outlines, or all list(s), maybe in textarea.
//* TODO: options menu: buttons to show all or only relevant select boxes, global and per type header (parts, colors, etc).
//* TODO: <select multiple> <optgroup> <option>?</option> </optgroup> </select>.
//* TODO ---------------------- params: ---------------------------------------
//* TODO: keep all layer-name parameters single-word, if possible.
//* TODO: zoom format in filenames: [x1, x1.00, x100%].
//* TODO: outline: more methods.
//* TODO: wireframe rendering.
//* TODO: multiselect?
//* TODO: colors: fix empty folders like "listname [colors batch]" and "listname [colors] / name".
//* TODO: colors: add "name1,2,3,etc[gradient-map=N/N%=rgb-N-N-N/N%=next+rgb-N-N-N/avg|max|min|rgb]" to interpolate between selected given color values in given name order using given source RGB (or avg/max/min of them). If too many gradient points (number of names > 2 + number points), ignore leftover points. If too many names, distribute undefined points evenly in the last (top?) stretch of gradient. Autosort points by %value. Color value after percent may be used to insert given color value or calculate value dependent on next/previous point (cycle in passes until all are defined). 0/100% may be used for defining colors; use names for omitted. If no usable color names, do nothing.
//* TODO ---------------------- rendering: ------------------------------------
//* TODO: collage: fix stuck rendering of oversized collage.
//* TODO: collage: arrange joined images without using DOM, to avoid currently visible images moving to hidden container when saving collage.
//* TODO: clipping: fix hiding of clipping group with skipped/invisible/empty base layer.
//* TODO: blending: maybe skip creating base data copy, unless necessary (for transition back in passthrough folders).
//* TODO: blending: arithmetic emulation of all operations, not native to JS.
//* TODO: blending: arithmetic emulation of all operations in 16/32-bit (float?) until final result; optional with checkbox/selectbox.
//* TODO: blending: keep layer images as PNGs, create arrays for high-precision blending on demand, discard arrays when HQ mode is disabled.
//* TODO: encode: set RGB of zero-alpha pixels to average of all non-zero-alpha neighbour RGB values, ignoring alpha.
//* TODO: compose: for files without merged image data - render ignoring options, but respecting layer visibility properties. Or buttons to show embedded and/or rendered image regardless of options. Or add this as top-most option for any project, with or without options.
//* TODO: batch: to avoid bruteforcing global cross-products, build a tree-graph of selectable option dependency forks when loading a project. Make a graph from each separated root, but include unconditional [no-render] paths into each tree for color collections, etc.
//* TODO ---------------------- export: ---------------------------------------
//* TODO: save opened project as JSON (maybe name it BRA, Base64Raster, to open in JS drawpads).
//* TODO: save opened project as SVG (probably more complicated, but widespread).
//* TODO: save opened project as PSD (and PSB). Try https://github.com/Agamnentzar/ag-psd
//* TODO: save opened project as QRA/ORQ/QOJ (ORA with QOI instead of PNG, and maybe JSON instead of XML)?
//* TODO: save images: QOI, via asm.js? https://phoboslab.org/log/2021/11/qoi-fast-lossless-image-compression
//* TODO: save images: WebP, JPEG XL. https://bugs.chromium.org/p/chromium/issues/detail?id=170565#c77 - toDataURL/toBlob quality 1.0 = lossless.
//* TODO: make exported project files identically reproducible, if possible. Now works as long as source file, its mod.date and result layer tree are the same.
//* TODO: compatible PSD -> ORA layer mode/structure conversions; on load/save/both?
//* TODO ---------------------- other: ----------------------------------------
//* TODO: fix stuck loading of ORA with big PNGs while optimizing them all by UPNG.js.
//* TODO: fix stuck loading of PSD after failed PSB.
//* TODO: lazy-loading images (layers, merged, thumbnail) with ag-psd (seems impossible without reparsing whole file again).
//* TODO: don't add custom properties to objects of built-in types, if possible.
//* TODO: global job list for WIP cancelling instead of spaghetti-coded flag checks.
//* TODO: split JS files in a way that lets older browsers to use parts they can parse and execute (only show menu, or only load ORA, etc.).
//* TODO: split JS functionality into modules to reuse with drawpad, etc.
//* TODO: whole config in JSON-format?
//* ---------------------------------------------------------------------------
//* Config: defaults, do not change here, redefine in external config file *---
var exampleRootDir = ''
, exampleProjectFiles = []
, DEFAULT_ALPHA_MASK_PADDING = 1
, DEFAULT_ALPHA_MASK_THRESHOLD = 16
, DEFAULT_AUTOCROP = 'top-left/transparent'
, DEFAULT_COLLAGE_ALIGN = 'top-left'
, DEFAULT_COLLAGE_COLORS = [
'Transparent'
, 'White'
, 'Gray'
, 'Black'
, 'MidnightBlue'
, 'Teal'
, 'SteelBlue'
, 'LightSlateGray'
, 'DeepSkyBlue'
, 'LightBlue'
, 'LightGreen'
, 'LightYellow'
, 'Magenta'
]
, DEFAULT_COLLAGE_PADDING = 0 //* <- add variant to both inside and outside
, DEFAULT_COLLAGE_PADDING_INSIDE = 2
, DEFAULT_COLLAGE_PADDING_OUTSIDE = 1
, PAUSE_WORK_DURATION = 20
, PAUSE_WORK_INTERVAL = 200
, ORA_EXPORT_THUMBNAIL_SIZE = 256
, PREVIEW_SIZE = 80
, THUMBNAIL_SIZE = 20
, ZOOM_STEP_MAX_FACTOR = 2
//* If set to 0, use common setting from above:
, TAB_PREVIEW_SIZE = 0
, TAB_THUMBNAIL_SIZE = 0
, TAB_ZOOM_STEP_MAX_FACTOR = 0 //* <- scaling in one step is blocky, stepping by factor of 2 is blurry, 4 may be okay for 20px and less.
//* Any truthy/falsy value should work:
, ADD_BATCH_COUNT_ON_BUTTON = false //* <- if not, add separate text element.
, ADD_BATCH_COUNT_ON_NEW_LINE = false
, ADD_PAUSE_AT_INTERVALS = true //* <- let UI update when loading files, rendering images, counting batch combinations, etc.
, ADD_PAUSE_BEFORE_EACH_FOLDER = false //* <- can take ~1-5x longer than pause at intervals, but UI response is not very good.
, ADD_PAUSE_BEFORE_EACH_LAYER = false //* <- can take ~1.5-2x longer than pause at folders, but UI response does not improve much.
, ADD_WIP_TEXT_ROLL = false //* <- rotating stick symbol, does not look good in tabs
, ASK_BEFORE_EXIT_IF_OPENED_FILES = true //* <- this is annoying and would not be needed if big files could load fast.
, CACHE_UNALTERABLE_FOLDERS_MERGED = true //* <- not much opportunity if almost everything is recolored or passthrough.
, CACHE_UNALTERABLE_IMAGES_TRIMMED = false //* <- use less memory for kept bitmap, but more CPU for trimming; untrimmed images are compressed fast by canvas API when stored as PNG, but need more memory for empty areas when uncompressed for drawing.
, CLEAR_CANVAS_FOR_GC = true
, DEDUPLICATE_LOADED_IMAGES = false
, DOWNSCALE_BY_MAX_FACTOR_FIRST = true //* <- other way (starting with partial factor) is not better, probably worse.
, EXAMPLE_NOTICE = false //* <- show the warning near the list of files.
, FILE_NAME_ADD_PARAM_KEY = true
, FILE_NAME_OMIT_SINGLE_OPTIONS = true
, FILE_NAMING_SUMMARY_HEADER = true
, LAYER_IMAGES_FROM_BITMAP = true
, LAYER_IMAGES_PRELOAD_ALL = false
, LAYER_IMAGES_PRELOAD_USED = false
, LOCALIZED_CASE_BY_CROSS_COUNT = false //* <- determine word case by product of all numbers in args; if not, then by the last number.
, LOG_ACTIONS = false
, LOG_GROUPING = false //* <- becomes a mess with concurrent operations.
, LOG_TIMERS = false
, PNG_OPTIMIZE_ALL = false
, PNG_OPTIMIZE_COLOR_FILL = true //* <- convert into 3/4-byte RGB(A) array on load, compress with UPNG on save.
, PNG_OPTIMIZE_UNCOMPRESSED = true //* <- saved by Krita, relying only on ORA file ZIP compression instead; but in JS it's slow to unzip and bloats RAM storage; on the other hand, ORA files with recompressed PNGs may get bigger.
, PNG_USE_UPNG = true //* <- otherwise - canvas, which depends on browser implementation
, PNG_USE_UZIP = false //* <- otherwise - pako, which is good for all uses
, READ_FILE_CONTENT_TO_GET_TYPE = false //* <- this relies on the browser or the OS to magically determine file type.
, REQUIRE_NON_EMPTY_SELECTION = false //* <- buggy
, SAVE_ADDITIONAL_LAYER_NAMES = true //* <- verbose names for mask image layers, wrapper folders, etc. to store PSD features into ORA.
, SAVE_COLOR_AS_ONE_PIXEL_IMAGE = false //* <- and stretch by non-standard layer attributes; anyway, color fill is super-compressible in PNG even at full image size.
, SAVE_OPACITY_ROUNDED = false
, SAVE_ORA_CUSTOM_PROPERTIES = false
, SAVE_WITH_SELECTED_PRERENDER = true //* <- reuse dress-up image, because ora.js rendering is currently very basic.
, SORT_OPTION_LIST_NAMES = true
, SORT_OPTION_SECTION_NAMES = false
, START_WITH_BIG_TEXT = false
, START_WITH_FIXED_TAB_WIDTH = true
, START_WITH_OPEN_FIRST_MENU_TAB = true
, TAB_STATUS_TEXT = true
, TAB_THUMBNAIL_PRELOAD = true //* <- get merged prerendered image from the file before looking at layer tree.
, TAB_THUMBNAIL_TRIMMED = false //* <- more content may become visible, but will take more time and shift image alignment.
, TAB_THUMBNAIL_ZOOM = true
, TAB_THUMBNAIL_ZOOM_TRIMMED = false
, TAB_WIDTH_ONLY_GROW = true //* <- prevent tabs from shrinking and jumping between rows.
, TESTING = false //* <- dump more info into the console; several levels are possible.
, TESTING_PNG = false //* <- dump a PNG onto the page after converting from pixel data.
, TESTING_QOI = false //* <- compare encode to decode and average timings of repeated runs of various methods.
, TESTING_RENDER = false //* <- dump a PNG onto the page after each rendering operation.
, TESTING_RENDER_CACHE = false //* <- dump a PNG onto the page after each cached crop or merge.
, USE_CRITERIA_ARRAY = true
, USE_MINIFIED_JS = true //* <- currently only pako.
, USE_WORKERS = true //* <- not possible when page is opened from disk
, VERIFY_PARAM_COLOR_VS_LAYER_CONTENT = false
, ZERO_PERCENT_EQUALS_EMPTY = false
, ZIP_SKIP_DUPLICATE_FILENAMES = true
, ZIP_USE_ASM = false //* <- otherwise - pako, which is good for all uses
, ZIP_USE_CODECS = true //* <- asm or pako instead of zip.js own.
, ZIP_USE_ONE_FILE_WORKER = false //* <- concatenated bundle, which is not included in distribution by default.
//* Array/Map/Set/Object containers all work fine.
//* Set is the fastest in this case, tested in Firefox 56, Basilisk 2021.03.17 (Firefox 56-based) and Vivaldi 3.7.2218.55 (latest Chrome-based).
//* Map is 2nd fastest, but almost the same as Array/Object.
, PROJECT_BLOBS_CONTAINER_TYPE = Set
;
//* ---------------------------------------------------------------------------
//* Create type-checking functions, e.g. "isString()" or "isImageElement()":
//* Source: https://stackoverflow.com/a/17772086
[
'Array', //* <- matches anything with 'Array' at the end, e.g. 'Uint8Array'
'ArrayBuffer',
'Blob',
'CanvasElement',
'Date',
'Function', //* <- matches anything with 'Function' at the end, e.g. 'AsyncFunction'
'ImageData',
'ImageElement', //* <- matches anything with 'ImageElement' at the end, e.g. 'HTMLImageElement'
'Number',
'Promise',
'RegExp',
'SelectElement',
'String',
].forEach(
(typeName) => {
const functionName = 'is' + typeName;
if (typeof window[functionName] !== 'function') {
window[functionName] = (value) => (toString.call(value).slice(-1 - typeName.length, -1) === typeName);
}
}
);
//* ---------------------------------------------------------------------------
//* Create common utility functions before using them in config:
const getFlatArray = (
typeof Array.prototype.flat === 'function'
//* Modern way:
? (array, maxDepth) => Array.prototype.flat.call(array, isRealNumber(maxDepth) ? maxDepth : Infinity)
//* Legacy way:
: (array, maxDepth) => {
if (!isRealNumber(maxDepth)) {
maxDepth = Infinity;
}
let flatArray = [];
for (const value of array) {
if (isArray(value)) {
if (maxDepth > 0) {
flatArray = flatArray.concat(getFlatArray(value, maxDepth - 1));
} else {
flatArray = flatArray.concat(value);
}
} else {
flatArray.push(value);
}
}
return flatArray;
}
);
//* Config: internal, do not change *------------------------------------------
const CONFIG_FILE_PATH = 'config.js' //* <- declarations-only file to redefine any of the above variables
, FETCH_TEST_FILE_PATH = 'index.png' //* <- smallest local file to test loading from disk
, LS_NAMESPACE = 'spriteDressUp'
, LS_KEY_BIG_TEXT = LS_NAMESPACE + 'BigText'
, LS_KEY_FIXED_TAB_WIDTH = LS_NAMESPACE + 'FixedTabWidth'
, LANG_FALLBACK = 'en'
, LANG_IN_DOCUMENT = document.documentElement.lang
, LS = window.localStorage || localStorage
, URL = window.URL || window.webkitURL || URL
, RUNNING_FROM_DISK = isURLFromDisk('/')
, CAN_USE_WORKERS = (typeof Worker === 'function' && !RUNNING_FROM_DISK)
, pendingJobs = new Set()
, regLayerNameParamOrComment = new RegExp(
'^'
+ '([^/\\[(]*)' //* <- [1] layer identity names, e.g. "name1, name2"
+ '(' //* <- [2] block of logic for any of identity names
+ '/' //* <- virtual subfolder, e.g. "parent names [parent param] / child names [child param]"
+ '|' + '\\[([^\\]]*)(?:\\]|$)' //* <- [3] options, e.g. "name1 [param] name2"
+ '|' + '\\([^)]*(?:\\)|$)' //* <- throwaway text, e.g. "name1 (comment) name2"
+ ')'
+ '(.*?)' //* <- [4] remainder for next step
+ '$'
)
, regLayerNameToSkip = null //* <- old: /^(skip)$/i
, regSplitLayerNames = /[\/,]+/g
, regSplitParam = /[\s\r\n]+/g //* <- old: /[\s,_]+/g
, regTrimParam = getTrimReg('\\s\\r\\n,_')
, regTrimParamRadius = /^(px|at)+|(px|at)+$/ig
, regEndsWithNumPx = /^(?:(.*?)\W+)?(\d+)px$/i
, regColorCode = /^(?:(rgba?)\W*|(hex)\W*|(#))(\w.*?)$/i
, regLayerNameParamType = {
'skip' : /^(skip)$/i
, 'skip_render' : /^(skip|no)-(render)$/i
, 'check_order' : /^(?:(?:check|top|bottom)\W+)*(down|up)$/i //* <- switch for speed/complexity testing, not useful
, 'none' : /^(none)$/i
, 'if_only' : /^(if|in)$/i
, 'not' : /^(\!|not?)$/i
, 'any' : /^(\?|any|some)$/i
, 'copypaste' : /^(copy|paste(?:-(?:above|below))?)(?:\W(.*))?$/i
, 'color_code' : regColorCode
, 'colors' : /^(colou?r)s$/i
, 'parts' : /^(option|part|type)s$/i
, 'paddings' : /^(outline|pad[ding]*)$/i
, 'radius' : /^(.*?\d.*)px(?:\W(.*))?$/i
// , 'wireframe' : /^(?:wire\W*)?(frame|fill)$/i
, 'opacities' : /^(?:(?:opacit[yies]*)\W*)?(\d[^%]*)%(\d*)$/i
, 'zoom' : /^(?:(?:zoom|scale|x)\W*)(\d[^%]*)%(\d*)$/i
, 'side' : /^(front|back|reverse(?:\W(.*))?)$/i
, 'separate' : /^((?:separate|split)\w*)(?:-((e)?\w*))?(?:\W(.*))?$/i
, 'autocrop' : /^(autocrop)(?:\W(.*))?$/i
, 'collage' : /^(collage)(?:\W(.*))?$/i
, 'layout' : /^(?:(inline|rows)|(newline|columns))$/i
, 'batch' : /^(?:(single|no-batch)|(batch|batched))?$/i
, 'prefix' : /^(?:(prefix|prefixed)|(unprefixed|no-prefix))?$/i
, 'option' : /^(?:(omitable|(?:omit|no)-single(?:-name)?)|(unomitable|(?:add-|)single(?:-name)?))$/i
, 'naming_order' : /^((?:file-?)(?:name|naming)(?:-order))(?:\W(.*))?$/i
, 'multi_select' : /^(optional|required|x(\d[\d+-]*))$/i
, 'preselect' : /^(preselect|initial|(last))$/i
}
, regLayerBlendModePass = /^pass[-through]*$/i
, regLayerBlendModeAlpha = /^(source|destination|xor)(-\w+)?$/i
, regLayerBlendModeClip = /^(source|destination)-(atop)$/i
, regLayerBlendModeMask = /^(source|destination)-(in|out)$/i
, regLayerTypeSingleTrim = /s+$/i
, regSanitizeLayerName = /\([^\)]*\)|\[[^\]]*\]/g
, regSanitizeLayerComment = /[\(\)\[\]\{\}\<\>]+/g
, regSanitizeFileName = /[_\s\/\\:<>?*"]+/g
, regHMS = /(T\d+)-(\d+)-(\d+\D*)/
, regMultiDot = /\.\.+/g
, regNumDots = /[\d.]+/g
, regNaNOrDot = /[^\d.]+/g
, regNaN = /\D+/g
, regNonWord = /\W+/g //* <- "\w" includes underscore "_"
, regNonHex = /[^0-9a-f]+/gi
, regNonAlphaNum = /[^0-9a-z]+/gi
, regHasDigit = /\d/
, regSpace = /\s+/g
, regCommaSpace = /\,+\s*/g
, regTemplateVarName = /\{(\w+)\}/g
, regTrimBrackets = getTrimReg('\\(\\)\\[\\]\\{\\}\\<\\>')
, regTrimNaN = getTrimReg('\\D')
, regTrimNaNOrSign = getTrimReg('^\\d\\.+-')
, regTrimSpace = getTrimReg('\\s')
, regTrimSpaceOrComma = getTrimReg('\\s,')
, regTrimSpaceBeforeNewLine = /[^\S\r\n]*(\r\n|\r|\n)/g
, regTrimTailBrTags = /(\<br\/\>\s*)+$/gi
, matchClassButton = getCriteria('button')
, matchClassExampleFile = getCriteria('example-file', 'file')
, matchClassExampleFiles = getCriteria('example-file-type', 'example-files', 'files')
, matchClassLoaded = getCriteria('loaded')
, matchClassLoadedFile = getCriteria('loaded-file', 'file')
, matchClassMenuBar = getCriteria('menu-bar')
, matchClassOption = getCriteria('project-option', 'option')
, matchClassSection = getCriteria('section')
, matchClassSub = getCriteria('sub')
, regJSONstringify = {
'asFlatLine' : /^(data)$/i
, 'asFlatLines' : /^(layers)$/i
, 'skipByKey' : /^(channels|parent|sourceData\w*)$/i
, 'skipByKeyIfLong' : /^(imageData)$/i
, 'showFromTree' : /^(layers|name)$/i
}
const SPLIT_SEC = 60
, MIN_CHANNEL_VALUE = 0
, MAX_CHANNEL_VALUE = 255
, MAX_BATCH_PRECOUNT = 9999
, FLAG_FLIP_HORIZONTAL = 1
, FLAG_FLIP_VERTICAL = 2
, FLAG_EVENT_LISTENER_CAPTURE = {
'capture' : true,
'passive' : false,
}
, FLAG_EVENT_NO_DEFAULT = { 'preventDefault' : true }
, FLAG_EVENT_STOP_IMMEDIATE = { 'stopImmediatePropagation' : true }
, FLAG_EVENT_STOP_DEFAULT = {
'preventDefault' : true,
'stopImmediatePropagation' : true,
}
, FLAG_FILENAME_AS_KEY = { 'isForStorageKey' : true }
, FLAG_FILENAME_TO_SAVE = {
'checkSelectedValue' : true,
'skipDefaultPercent' : true,
}
, FLAG_FILENAME_TO_SAVE_HTML = {
'addColorsWithHTML' : true,
...FLAG_FILENAME_TO_SAVE,
}
, FLAG_JOIN_TEXT_FILTER = { 'filter' : true }
, FLAG_LAYER_PATH_TEXT = {
'includeSelf' : true,
'asText' : true,
}
, FLAG_PROJECT_SET_THUMBNAIL = { 'alsoSetThumbnail' : true }
, FLAG_RENDER_LAYER_COPY = { 'isCopyNeeded' : true }
, FLAG_RENDER_IGNORE_COLORS = { 'ignoreColors' : true }
, FLAG_SAVE_ALL = { 'saveToFile' : true }
, FLAG_SAVE_ZIP = { 'saveToZipFile' : true }
, FLAG_SHOW_JOIN = { 'asOneJoinedImage' : true }
, FLAG_SAVE_JOIN = {
'saveToFile' : true,
'asOneJoinedImage' : true,
}
, FLAG_TIME_LOG_FORMAT = { 'logFormat' : true }
, FLAG_TIME_FILENAME_FORMAT = { 'fileNameFormat' : true }
, DUMMY_EMPTY_ARRAY = Object.freeze( [] ) //* <- immutable, for skipping iteration on non-collectable results
, DUMMY_NULL_ARRAY = Object.freeze( [null] ) //* <- immutable, for cross-product combinations
, DUMMY_TEXT_ARRAY = Object.freeze( [''] )
, DEFAULT_COLOR_VALUE_ARRAY = Object.freeze( [0,0,0, MAX_CHANNEL_VALUE] )
, TRANSPARENT_COLOR_VALUE_ARRAY = Object.freeze( [0,0,0, MIN_CHANNEL_VALUE] )
, DUMMY_OPTION_PARAMS = Object.freeze({
'noOptionSwitches' : true,
'skipInFileNames' : true,
'preselect' : 'last',
})
, DUMMY_OPTIONAL_PARAMS = Object.freeze({
'optional' : true,
...DUMMY_OPTION_PARAMS,
})
, DUMMY_LAYER = Object.freeze({
'name' : 'dummy',
'names' : DUMMY_TEXT_ARRAY,
})
, LAYER_NAME_MASK_IMAGE = 'Mask image'
, LAYER_NAME_MASKED_CONTENT = 'Masked content'
, LAYER_NAME_CLIPPED_CONTENT = 'Clipped content' //* <- wrapper for layers with blending modes
, LAYER_NAME_CLIPPING_GROUP = 'Clipping group'
, FALSY_STRINGS = [
'0'
, 'no'
, 'none'
, 'null'
, 'false'
, 'hidden'
, 'disabled'
, 'undefined'
]
, DRAG_ORDER_PREFIX = 'drag-order:\n'
, BLOB_PREFIX = 'blob:'
, DATA_PREFIX = 'data:'
, TYPE_TEXT = 'text/plain'
, TYPE_IMAGE_PNG = 'image/png'
, TITLE_LINE_BREAK = ' \r\n'
, DOUBLE_LINE_BREAK = ' \r\n\r\n'
, WIP_TEXT_ROLL = '\\|/-'
, TIME_PARTS_YMD = ['FullYear', 'Month', 'Date']
, TIME_PARTS_HMS = ['Hours', 'Minutes', 'Seconds']
, QUERY_SELECTOR = {
'getElementsByClassName' : ['.', ''],
'getElementsByTagName' : ['', ''],
'getElementsByName' : ['*[name="', '"]'],
'getElementsByType' : ['*[type="', '"]'],
'getElementsById' : ['*[id="', '"]'],
}
, DEFAULT_MASK_FILL_COLOR = 'black'
, ISOLATE_ALL = 'isolate'
, ISOLATE_ALPHA = 'isolate-alpha'
, ISOLATE_AUTO = 'auto'
, ISOLATE_PASS = 'pass-through'
, BLEND_MODE_NORMAL = 'source-over'
, BLEND_MODE_CLIP = 'source-atop'
, BLEND_MODE_MASK = 'destination-in'
, BLEND_MODE_CUT = 'destination-out'
, BLEND_MODE_INVERT = 'source-out'
, BLEND_MODE_ADD = 'lighter'
, BLEND_MODE_PASS = 'pass'
, BLEND_MODE_FADE_IN = 'transition-in'
, BLEND_MODE_FADE_OUT = 'transition-out'
, BLEND_MODES_ALPHA_PREFIXES = ['source', 'destination', 'src', 'dst', 'xor']
//* Source: https://www.w3.org/TR/SVGCompositing/#comp-op-property
, BLEND_MODES_IN_SVG = [
'clear'
, 'src'
, 'dst'
, 'src-over'
, 'dst-over'
, 'src-in'
, 'dst-in'
, 'src-out'
, 'dst-out'
, 'src-atop'
, 'dst-atop'
, 'xor'
, 'plus'
, 'multiply'
, 'screen'
, 'overlay'
, 'darken'
, 'lighten'
, 'color-dodge'
, 'color-burn'
, 'hard-light'
, 'soft-light'
, 'difference'
, 'exclusion'
, 'inherit'
]
, BLEND_MODES_REMAP_TO_ORA = {
[ BLEND_MODE_ADD ] : 'svg:plus'
}
, BLEND_MODES_REPLACE_TO_ORA = [
['source', 'src']
, ['destination', 'dst']
, [new RegExp('^(' + BLEND_MODES_IN_SVG.join('|') + ')$', 'i'), 'svg:$1']
]
, BLEND_MODES_REPLACE = [
['src', 'source']
, ['dst', 'destination']
, ['liner', 'linear']
, [/^.*:/g] //* <- remove any "prefix:"
, [/[\s\/_-]+/g, '-'] //* <- normalize word separators to use only dashes
, [/^subs?tr[au]ct$/, 'subtract']
, [regLayerBlendModePass, BLEND_MODE_PASS]
]
, BLEND_MODES_REMAP = {
'normal' : BLEND_MODE_NORMAL
, 'add' : BLEND_MODE_ADD
, 'plus' : BLEND_MODE_ADD
, 'linear-dodge' : BLEND_MODE_ADD
//* From SAI2, remap according to PSD.js:
, 'burn' : 'color-burn'
, 'burn-dodge' : 'vivid-light'
, 'darken-color' : 'darker-color'
, 'dodge' : 'color-dodge'
, 'exclude' : 'exclusion'
, 'lighten-color' : 'lighter-color'
, 'shade' : 'linear-burn'
, 'shade-shine' : 'linear-light'
, 'shine' : BLEND_MODE_ADD
}
, BLEND_MODES_WITH_TS_VERSION = [
BLEND_MODE_ADD
, 'color-burn'
, 'color-dodge'
, 'difference'
, 'hard-mix'
, 'linear-burn'
, 'linear-dodge'
, 'linear-light'
, 'vivid-light'
]
//* Source: https://github.com/Braunbart/PSDLIB.js
, PSD_COLOR_MODES = [
'Bitmap'
, 'Grayscale'
, 'Indexed'
, 'RGB'
, 'CMYK'
, 'HSL'
, 'HSB'
, 'Multichannel'
, 'Duotone'
, 'Lab'
]
, OPEN_CLOSE = ['open', 'close']
, COLOR_LIST_NAMES = ['background']
, PARAM_KEYWORDS_AUTOCROP = ['transparent', 'topleft', 'topright', 'bottomleft', 'bottomright']
, PARAM_KEYWORDS_COLLAGE_ALIGN = ['topleft', 'topright', 'bottomleft', 'bottomright', 'top', 'bottom', 'left', 'right']
, PARAM_KEYWORDS_COLLAGE_PAD = ['border', 'padding']
, PARAM_KEYWORDS_PADDING_METHODS = ['max', 'min']
, PARAM_KEYWORDS_SET_VALUE_TO_NAME = ['preselect']
, PARAM_KEYWORDS_SET_VALUE_TO_TRUE = ['last', 'optional', 'required', 'no_prefix']
, PARAM_KEYWORDS_SHORTCUT_FOR_ALL = ['all', 'etc']
, PARAM_KEYWORDS_PASTE = ['paste', 'paste-above', 'paste-below']
, PARAM_OPTIONS_FOR_EACH_NAME = ['opacities', 'paddings']
, PARAM_OPTIONS_GLOBAL = ['autocrop', 'collage', 'separate', 'side', 'zoom']
, PARAM_OPTIONS_LOCAL = ['parts', 'colors', 'paddings', 'opacities']
, VIEW_SIDES = ['front', 'back']
, SEPARATE_NAMING_TYPES = ['equal', 'numbered']
, SEPARATE_PARAM_NAMES_DEFAULT = ['separate', 'split']
, SEPARATE_GROUP_NAME_DEFAULT = ''
, NAME_PARTS_SEPARATOR = ''
, NAME_PARTS_COLORED_CLASSES = ['selected-parts', 'list-name', 'option-name']
, NAME_PARTS_PERCENTAGES = ['zoom', 'opacities']
, NAME_PARTS_FOLDERS = ['parts', 'colors']
, NAME_PARTS_ORDER = ['separate', 'side', 'parts', 'colors', 'paddings', 'opacities', 'zoom', 'autocrop']
, NAME_PARTS_ORDER_PARAMS = [
'given',
'given-lists',
'given-options',
'given-sections',
'given-types',
'sort',
'sort-lists',
'sort-options',
'sort-sections',
'sort-types',
...NAME_PARTS_ORDER
]
, PARAM_OPTIONS_ADD_BY_DEFAULT = {
'collage' : ['no-batch', 'last', 'optional', 'collage']
, 'autocrop' : ['no-batch', 'last', 'optional', 'autocrop']
}
, SWITCH_LABEL_BY_CLASS = {
'batch-batched' : '[\u2E2C]'
, 'batch-single' : '[\u2E30]'
, 'layout-inline' : '[\u22EF]'
, 'layout-newline' : '[\u22EE]'
, 'option-omitable' : '[\u2212]'
, 'option-unomitable' : '[+]'
, 'prefix-prefixed' : '[=]'
, 'prefix-unprefixed' : '[o]'
}
, SWITCH_CLASS_BY_INDEX = ['unchecked', 'checked']
, SWITCH_NAMES_BY_TYPE = {
'batch' : ['single', 'batched']
, 'layout' : ['inline', 'newline']
, 'prefix' : ['prefixed', 'unprefixed']
, 'option' : ['omitable', 'unomitable']
}
, SWITCH_NAMES_DEFAULT = {
'batch' : 'batched'
, 'layout' : 'inline'
, 'prefix' : 'prefixed'
, 'option' : 'omitable'
}
, PROJECT_OPTION_GROUPS = [
{
'header' : 'option_header_collage',
'select' : {
'collage' : {
'align' : 'option_collage_align',
'background' : 'option_collage_background',
'border' : 'option_collage_border',
'padding' : 'option_collage_padding',
},
},
},
{
'header' : 'option_header_separate',
'select' : {
'separate' : {
'naming' : 'option_separate_naming',
'group' : 'option_separate_group',
'separate' : 'option_separate_part',
},
},
},
{
'header' : 'option_header_view',
'select' : {
'autocrop' : 'option_autocrop',
'zoom' : 'option_zoom',
'side' : 'option_side',
},
},
{
'parts' : 'option_header_parts',
'opacities' : 'option_header_opacities',
'paddings' : 'option_header_paddings',
'colors' : 'option_header_colors',
},
]
, EXAMPLE_CONTROLS = [
{
'download_all' : 'download_all',
'load_all' : 'open_example_all',
},
{
'stop' : 'stop',
},
]
, PROJECT_FILE_CONTROLS = [
'show_project_details',
]
, PROJECT_VIEW_CONTROLS = [
{
'header' : 'original_view_header',
'buttons' : {
'show_original_png' : '',
'save_original_png' : '',
// 'save_original_qoi' : '',
'save_original_ora' : '',
'save_original_ora_all_layers' : '',
'save_original_ora_used_layers' : '',
},
},
{
'header' : 'current_view_header',
'buttons' : {
'show_png' : '',
'save_png' : '',
'save_qoi' : '',
'save_ora' : '',
'save_ora_all_layers' : '',
'save_ora_used_layers' : '',
},
},
{
'header' : 'batch_view_header',
'buttons' : {
'batch' : {
'show_all_png' : 'show_png_batch',
'save_all_png' : 'save_png_batch',
'save_zip_png' : 'save_png_batch_zip',
'save_zip_qoi' : 'save_qoi_batch_zip',
},
'collage' : {
'show_join_png' : 'show_png_collage',
'save_join_png' : 'save_png_collage',
'save_join_qoi' : 'save_qoi_collage',
'stop' : 'stop',
},
// 'stop' : 'stop',
},
},
]
, PROJECT_HIDDEN_CONTROLS = [
{
'header' : 'reset_header',
'buttons' : {
'options_init' : {
'reset_options_to_init' : '',
'reset_options_to_empty' : '',
},
'options' : {
'reset_options_to_top' : '',
'reset_options_to_bottom' : '',
},
'batching' : {
'reset_switch_batch_to_batched' : '',
'reset_switch_batch_to_single' : '',
},
'batching_layout' : {
'reset_switch_layout_to_inline' : '',
'reset_switch_layout_to_newline' : '',
},
'naming_omit' : {
'reset_switch_option_to_unomitable' : '',
'reset_switch_option_to_omitable' : '',
},
'naming_prefix' : {
'reset_switch_prefix_to_prefixed' : '',
'reset_switch_prefix_to_unprefixed' : '',
},
},
},
]
, PROJECT_SAVE_ALL_BUTTON_NAMES = Object.keys(
PROJECT_VIEW_CONTROLS.find(
(v) => v.buttons.batch
).buttons.batch
)
, PROJECT_NAMING_BUTTON_NAMES = FILE_NAMING_SUMMARY_HEADER ? [
'saved_file_naming_sort',
'saved_file_naming_reset_to_default',
'saved_file_naming_reset_to_initial',
] : [
'saved_file_naming_change',
'saved_file_naming_sort',
'saved_file_naming_reset_to_default',
'saved_file_naming_reset_to_initial',
'saved_file_naming_close',
]
, PROJECT_NAMING_EVENT_HANDLERS = {
'dragstart' : onPanelDragStart,
'dragenter' : onPanelDragMove,
'drop' : onPanelDragMove,
}
, PROJECT_CONTROL_TAGNAMES = [
'button',
'select',
'input',
]
, IMAGE_FIT_CLASSES = [
'size-fit',
'size-full',
]
, IMAGE_GEOMETRY_KEYS = [
['top', 'y'],
['left', 'x'],
['width', 'w'],
['height', 'h'],
]
, VIRTUAL_FOLDER_TAKEOVER_PROPERTIES = {
'blendMode' : BLEND_MODE_NORMAL,
'isBlendModeTS' : false,
'isClipped' : false,
'clippingLayer' : null,
}
, IMAGE_DATA_KEYS_TO_LOAD = [
'toImage',
'loadImage',
'imgData',
'maskData',
'pixelData',
]
, CLEANUP_PROJECT_LAYERS_RECURSIVE_KEYS = ['layers']
, CLEANUP_PROJECT_LAYERS_MERGED_CACHE_KEYS = [
'mergedImage',
'mergedImageToRecolor',
]
, CLEANUP_PROJECT_AFTER_LOAD_KEYS = [
'loading',
// 'loadImage', //* <- keep for lazy-loading
'toPng',
]
, CLEANUP_PROJECT_IF_NOT_TESTING_KEYS = [
// 'blendModeOriginal', //* <- keep for saving
'blendModeOriginalAlpha',
'blendModeOriginalColor',
// 'nameOriginal', //* <- keep for saving
// 'sourceDataFile', //* <- keep for saving
'sourceDataNode',
'sourceData',
'pixelData',
'maskData',
// 'imgData', //* <- keep for lazy-loading
...CLEANUP_PROJECT_AFTER_LOAD_KEYS
]
, SAVE_PROJECT_FILE_TYPES = ['ora']
, SAVE_IMAGE_FILE_TYPES = ['png', 'qoi']
//* Config: internal, included scripts and loaders of project files *----------
const LIB_ROOT_DIR = 'lib/'
, LIB_FORMATS_DIR = LIB_ROOT_DIR + 'formats/'
, LIB_LANG_DIR = LIB_ROOT_DIR + 'localization/'
, LIB_UTIL_DIR = LIB_ROOT_DIR + 'util/'
, ZIP_FORMAT_DIR = LIB_FORMATS_DIR + 'zip/zip_js/'
, ZLIB_ASM_DIR = LIB_FORMATS_DIR + 'zlib/zlib-asm/v0.2.2/' //* <- last version supported by zip.js, ~ x2 faster than default
, ZLIB_PAKO_DIR = LIB_FORMATS_DIR + 'zlib/pako/v2.0.2/' //* <- good and fast enough for everything
;
//* External variable names, do not change *-----------------------------------
var PSD
, UPNG
, UZIP
, agPsd
, ora
, pako
, zip
, zlib
;
//* To be figured on the go *--------------------------------------------------
var LANG
, PSD_JS
, AG_PSD_FILE_READING_OPTIONS
, FILE_TYPE_LIBS
, FILE_TYPE_LOADERS
, ZIP_WORKER_SCRIPTS
, DEFAULT_COLLAGE
, PRELOAD_LAYER_IMAGES
, USE_ES5_JS
, USE_WORKERS_IF_CAN
, CompositionModule
, compositionFunctionNames
, canvasForTest
, ctxForTest
, draggedElement
, thumbnailPlaceholder
, isStopRequested
, isBatchWIP
, lastTimeProjectTabSelectedByUser = 0
, functionNameByBlendMode = {}
, rgbaCacheByColorName = {}
;
//* Config: internal, wrapped to be called after reading external config *-----
function initLibParams() {
USE_WORKERS_IF_CAN = (USE_WORKERS && CAN_USE_WORKERS);
const zlibCodecPNG = [PNG_USE_UZIP ? 'UZIP.js' : 'pako'];
const zlibCodecZIP = [ZIP_USE_ASM ? 'zlib-asm' : 'pako'];
const zipAllInOneFileName = 'z-worker-copy-all-in-one-file' + (
!ZIP_USE_CODECS
? ''
: ZIP_USE_ASM
? '-zlib-asm'
: USE_ES5_JS
? '-pako.es5'
: '-pako'
) + '.js';
const zipZlibCodecWrapper = (
ZIP_USE_ASM
? 'codecs-zlib-asm.js'
: 'codecs-pako.js'
);
const zlibPakoFileName = (
'pako'
+ (USE_ES5_JS ? '.es5' : '')
+ (USE_MINIFIED_JS ? '.min' : '')
+ '.js'
);
FILE_TYPE_LIBS = {
'zlib-asm' : {
//* Source: https://github.com/ukyo/zlib-asm
'varName' : 'zlib'
, 'dir' : ZLIB_ASM_DIR
, 'files' : ['zlib.js']
},
'pako' : {
//* Source: https://github.com/nodeca/pako
'varName' : 'pako'
, 'dir' : ZLIB_PAKO_DIR
, 'files' : [zlibPakoFileName]
},
'UZIP.js' : {
//* Source: https://github.com/photopea/UZIP.js
'varName' : 'UZIP'
, 'dir' : LIB_FORMATS_DIR + 'zlib/UZIP/'
, 'files' : ['UZIP.js']
, 'depends' : ['pako']
},
'UPNG.js' : {
//* Source: https://github.com/photopea/UPNG.js
'varName' : 'UPNG'
, 'dir' : LIB_FORMATS_DIR + 'png/UPNG/'
, 'files' : ['UPNG.js']
, 'depends' : zlibCodecPNG
},
'QOI.js' : {
//* Source: https://github.com/pfusik/qoi-ci
//* Note: swapped RGB channels order to match JS ImageData.
'varName' : 'QOIEncoder'
, 'dir' : LIB_FORMATS_DIR + 'qoi/qoi-ci/'
, 'files' : ['qoi-ci-1.1.1-mod-rgba-order.js']
},
'zip.js' : {