This repository has been archived by the owner on Jun 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
2050 lines (2019 loc) · 99.3 KB
/
index.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
const { remote: app, ipcRenderer, remote: { dialog } } = require('electron');
const fs = require('fs-extra');
const trash = require('trash');
const path = require('path');
const imageSize = require('image-size');
const equals = function (a, other, callback = (x, y) => (x === y)) {
// Check the other object is of the same type
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(other)) {
return false;
}
if (a.length === (void 0) || a.length !== other.length) {
return false;
}
return Array.prototype.every.call(a, (x, i) => callback(a, other[i]));
};
ipcRenderer.on('syncMetadata', () => {
store.dispatch('syncMetadata');
ipcRenderer.send('metadataSynced');
});
/**
* Only run a function if it hasn't been run for wait milliseconds.
* @param {function} func - The function to run.
* @param {number} wait - How long to wait before executing the function.
* @param {boolean=} immediate - Rising edge? (probably not)
*/
function debounce (func, wait, immediate) { // credit david walsh
var timeout;
return function () {
var context = this; var args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
/**
* Convert from hex to HSL
* @param {string} H - the hex number to convert to HSL
*/
function hexToHSL (H) { // credit CSS Tricks
let r = 0; let g = 0; let b = 0;
if (H.length === 4) {
r = `0x${H[1]}${H[1]}`;
g = `0x${H[2]}${H[2]}`;
b = `0x${H[3]}${H[3]}`;
} else if (H.length === 7) {
r = `0x${H[1]}${H[2]}`;
g = `0x${H[3]}${H[4]}`;
b = `0x${H[5]}${H[6]}`;
}
r /= 255;
g /= 255;
b /= 255;
const cmin = Math.min(r, g, b);
const cmax = Math.max(r, g, b);
const delta = cmax - cmin;
let h = 0;
let s = 0;
let l = 0;
if (delta === 0) { h = 0; } else if (cmax === r) { h = ((g - b) / delta) % 6; } else if (cmax === g) { h = (b - r) / delta + 2; } else { h = (r - g) / delta + 4; }
h = Math.round(h * 60);
if (h < 0) { h += 360; }
l = (cmax + cmin) / 2;
s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
s = +(s * 100).toFixed(1);
l = +(l * 100).toFixed(1);
return [h, s, l];
}
/**
* Clamp the number (if n's below min, return min, and vice versa for max, otherwise return n)
* @param {number} min - The minimum
* @param {number} n - The number
* @param {number} max - The maximum
*/
const clamp = (min, n, max) => Math.max(Math.min(n, max), min);
/**
* Return a human file size (3GB, 2MB, etc) when given a number of bytes.
* @param {number} bytes - The raw number of bytes
* @param {boolean} si - If true, each level is 1000 of the previous (and use normal prefixes); if not, 1024 (and use kebi, mebi, gebi, etc prefixes)
* @param {number} dp - Degree of precision; # of decimals
*/
function humanFileSize (bytes, si = false, dp = 1) {
const thresh = si ? 1000 : 1024;
if (Math.abs(bytes) < thresh) {
return `${bytes} B`;
}
const units = si
? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
let u = -1;
const r = 10 ** dp;
do {
bytes /= thresh;
++u;
} while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);
return `${bytes.toFixed(dp)} ${units[u]}`;
}
/**
* The version, to be used wherever it's needed.
* @type {string}
* @constant
*/
const _version = '1.1.3';
document.title = `TagViewer ${_version}`;
let config = {}; let cache = {}; const safeMode = [false, false];
if (fs.existsSync(path.join(app.app.getPath('userData'), 'config.json'))) {
try {
config = fs.readJsonSync(path.join(app.app.getPath('userData'), 'config.json'));
} catch (e) {
dialog.showErrorBox('Error parsing config.json', `We've encountered an error while parsing the configuration file. If you've edited the file, please find the error and fix it. If not, this is an issue with TagViewer, that you should report on GitHub. Due to this error, changes to the configuration will not be saved until you either rectify the error or delete the configuration completely. The error is as follows: ${e.toString()}`);
safeMode[0] = true;
}
} else {
fs.writeJson(path.join(app.app.getPath('userData'), 'config.json'), {});
}
if (fs.existsSync(path.join(app.app.getPath('userData'), 'cache.json'))) {
try {
cache = fs.readJsonSync(path.join(app.app.getPath('userData'), 'cache.json'));
} catch (e) {
dialog.showErrorBox('Error parsing cache.json', `We've encountered an error while parsing the cache file. If you've edited the file, please find the error and fix it. If not, this is an issue with TagViewer, that you should report on GitHub. Due to this error, changes to the cache will not be saved until you either rectify the error or delete the cache completely. The error is as follows: ${e.toString()}`);
safeMode[1] = true;
}
} else {
fs.writeJson(path.join(app.app.getPath('userData'), 'config.json'), {});
}
if (!Object.prototype.hasOwnProperty.call(cache, 'openHistory')) cache.openHistory = [];
const setInterfaceTheme = theme => {
new Map(Object.assign(Object.entries({
'default-light': {
'--root-font': 'sans-serif',
'--main-background-color': '#fff',
'--secondary-background-color': '#f7f7f7',
'--tertiary-background-color': '#7f7f7f',
'--main-foreground-color': '#000',
'--main-foreground-color_disabled': 'darkgrey',
'--secondary-foreground-color': '#555', // used?
'--icon-color': '#111',
'--icon-color_disabled': 'darkgrey',
'--icon-hover-shadow-string': '0 0 3px 2px #0004',
'--link-color': '#3676e8',
'--focus-color': '#f0af2f',
'--error-color': '#ff5252'
},
'default-dark': {
'--root-font': 'sans-serif',
'--main-background-color': '#121212', // not true black!
'--secondary-background-color': '#1a1a1a',
'--tertiary-background-color': '#303030',
'--main-foreground-color': '#fffffff7',
'--main-foreground-color_disabled': '#ddddddf7',
'--secondary-foreground-color': '#a6a6a6',
'--icon-color': '#ffffff',
'--icon-color_disabled': '#ddddddf7',
'--icon-hover-shadow-string': '0 0 3px 2px #ffffffaa',
'--link-color': '#96c6e0f7',
'--focus-color': '#f0c37af7',
'--error-color': '#f77e7e'
}
}[theme]), config.themeOverrides ?? {})).forEach((value, key) => document.documentElement.style.setProperty(key, value));
try { document.getElementById('style-injector').remove(); } catch (e) { /* null check operator, where are you when I need you? */ }
const styleInjector = document.createElement('STYLE');
styleInjector.id = 'style-injector';
styleInjector.appendChild(document.createTextNode({
'default-light': '',
'default-dark': 'body > div #top-bar > button { outline: 0; }'
}[theme] + (config.themeInjections ?? '')));
document.body.appendChild(styleInjector);
};
if (Object.prototype.hasOwnProperty.call(config, 'theme') && config.theme !== 'default-light') setInterfaceTheme(config.theme);
/**
* An array in the format [type, options] describing a filter
* @typedef filterArray
* @type {array}
* @member {string} - The type of the filter ('tag', 'tagColor', etc)
* @member {object} - The options for the filter (dependent on the type)
*/
/**
* Apply the filters to the array
* @param {object[]} array - The array to apply the filters to
* @param {filterArray[]} filters - The array of filters
* @returns {object[]} - The filtered array
*/
const applyFilters = (array, filters) => {
for (const filter of filters) {
const filterFn = generateFilter(filter);
array = array.filter(el => filterFn(el));
}
return array;
};
/**
* Generate a function from a filter
* @param {filterArray} filter - The filter, in the format specified
* @returns {function(object): boolean} - A function to test whether an item matches the filter
*/
const generateFilter = filter => {
switch (filter[0]) { // type
case 'tag': // args: positive as Boolean, tag as String
if (filter[1].positive) { // either positive (require tag)
// |-> the number prefix
return n => n.tags.includes(filter[1].tag);
} else { // or not (exclude tag)
return n => !n.tags.includes(filter[1].tag);
}
case 'tagColor': // args: positive as Boolean, color as String in 6-digit lowercase hex format
if (filter[1].positive) {
return n => n.tags.map(el => store.state.tagviewerMeta.tagList[el][1]).includes(filter[1].color);
} else {
return n => !n.tags.map(el => store.state.tagviewerMeta.tagList[el][1]).includes(filter[1].color);
}
case 'propBoolean': // args: positive as Boolean for whether to need true or false, inclNoval for what do if it's not defined.
if (filter[1].positive) {
return n => (n.props[filter[1].prop] ?? !!filter[1].inclNoval);
} else {
return n => !(n.props[filter[1].prop] ?? !filter[1].inclNoval);
}
case 'propSize':
if (filter[1].condition === '=') {
return n => (n.size === parseInt(filter[1].val, 10));
}
if (filter[1].condition === '>') {
return n => (n.size > parseInt(filter[1].val, 10));
}
if (filter[1].condition === '<') {
return n => (n.size < parseInt(filter[1].val, 10));
}
if (filter[1].condition === '!=' || filter[1].condition === '≠') {
return n => (n.size !== parseInt(filter[1].val, 10));
}
if (filter[1].condition === '<=' || filter[1].condition === '≤') {
return n => (n.size <= parseInt(filter[1].val, 10));
}
if (filter[1].condition === '>=' || filter[1].condition === '≥') {
return n => (n.size >= parseInt(filter[1].val, 10));
}
break;
case 'propResolution':
if (filter[1].condition === '=') {
return n => ((n.resolution[0] !== -1 || filter[1].inclNoval) && n.resolution[0] === parseInt(filter[1].val[0], 10) && n.resolution[1] === parseInt(filter[1].val[1], 10));
}
if (filter[1].condition === '>') {
return n => ((n.resolution[0] !== -1 || filter[1].inclNoval) && n.resolution[0] * n.resolution[1] > parseInt(filter[1].val[0], 10) * parseInt(filter[1].val[1], 10)); // use total pixels
}
if (filter[1].condition === '<') {
return n => ((n.resolution[0] !== -1 || filter[1].inclNoval) && n.resolution[0] * n.resolution[1] < parseInt(filter[1].val[0], 10) * parseInt(filter[1].val[1], 10));
}
if (filter[1].condition === '!=' || filter[1].condition === '≠') {
return n => ((n.resolution[0] !== -1 || filter[1].inclNoval) && n.resolution[0] * n.resolution[1] !== parseInt(filter[1].val[0], 10) * parseInt(filter[1].val[1], 10));
}
if (filter[1].condition === '<=' || filter[1].condition === '≤') {
return n => ((n.resolution[0] !== -1 || filter[1].inclNoval) && n.resolution[0] * n.resolution[1] <= parseInt(filter[1].val[0], 10) * parseInt(filter[1].val[1], 10));
}
if (filter[1].condition === '>=' || filter[1].condition === '≥') {
return n => ((n.resolution[0] !== -1 || filter[1].inclNoval) && n.resolution[0] * n.resolution[1] >= parseInt(filter[1].val[0], 10) * parseInt(filter[1].val[1], 10));
}
break;
case 'propNumber': // args: condition as String representing comparison, prop as String for the prop, val as Number for the value (includes Size) (and this is also for numerics like Size, Dimension, and Duration since they're stored in one unit—bytes, millimeters, and seconds respectively)
if (filter[1].condition === '=') {
return n => ((n.props[filter[1].prop] ?? (filter[1].inclNoval ? filter[1].val : NaN)) === parseInt(filter[1].val, 10));
}
if (filter[1].condition === '>') {
return n => ((n.props[filter[1].prop] ?? (filter[1].inclNoval ? filter[1].val + 1 : NaN)) > parseInt(filter[1].val, 10));
}
if (filter[1].condition === '<') {
return n => ((n.props[filter[1].prop] ?? (filter[1].inclNoval ? filter[1].val - 1 : NaN)) < parseInt(filter[1].val, 10));
}
if (filter[1].condition === '!=' || filter[1].condition === '≠') {
return n => ((n.props[filter[1].prop] ?? (filter[1].inclNoval ? NaN : parseInt(filter[1].val, 10))) !== parseInt(filter[1].val, 10));
}
if (filter[1].condition === '<=' || filter[1].condition === '≤') {
return n => ((n.props[filter[1].prop] ?? (filter[1].inclNoval ? filter[1].val : NaN)) <= parseInt(filter[1].val, 10));
}
if (filter[1].condition === '>=' || filter[1].condition === '≥') {
return n => ((n.props[filter[1].prop] ?? (filter[1].inclNoval ? filter[1].val : NaN)) >= parseInt(filter[1].val, 10));
}
break;
case 'propString': // args: same but condition can only be = or !=, and val is a String (includes Title comparisons)
if (!filter[1].caseSensitive) {
if (filter[1].condition === '=') {
return n => ((filter[1].prop === 'Title' ? n.title.toLowerCase() : (n.props[filter[1].prop] ?? (filter[1].inclNoval ? filter[1].val : NaN))).toLowerCase() === filter[1].val.toLowerCase());
}
if (filter[1].condition === '!=' || filter[1].condition === '≠') {
return n => !((filter[1].prop === 'Title' ? n.title.toLowerCase() : (n.props[filter[1].prop] ?? (filter[1].inclNoval ? NaN : filter[1].val))) === filter[1].val.toLowerCase());
}
if (filter[1].condition === '{}' || filter[1].condition === 'includes') { // contains
return n => ((filter[1].prop === 'Title' ? n.title.toLowerCase() : (n.props[filter[1].prop] ?? (filter[1].inclNoval ? filter[1].val : ''))).includes(filter[1].val.toLowerCase()));
}
if (filter[1].condition === '!{' || filter[1].condition === "doesn't include") { // doesn't contain
return n => !((filter[1].prop === 'Title' ? n.title.toLowerCase() : (n.props[filter[1].prop] ?? (filter[1].inclNoval ? '' : filter[1].val))).includes(filter[1].val.toLowerCase()));
}
} else {
if (filter[1].condition === '=' || filter[1].condition === 'is same as') {
return n => ((filter[1].prop === 'Title' ? n.title : (n.props[filter[1].prop] ?? (filter[1].inclNoval ? filter[1].val : NaN))) === filter[1].val);
}
if (filter[1].condition === '!=' || filter[1].condition === 'is not same as') {
return n => !((filter[1].prop === 'Title' ? n.title : (n.props[filter[1].prop] ?? (filter[1].inclNoval ? NaN : filter[1].val))) === filter[1].val);
}
if (filter[1].condition === '{}' || filter[1].condition === 'includes') { // contains
return n => ((filter[1].prop === 'Title' ? n.title : (n.props[filter[1].prop] ?? (filter[1].inclNoval ? filter[1].val : ''))).includes(filter[1].val));
}
if (filter[1].condition === '!{' || filter[1].condition === "doesn't include") { // doesn't contain
return n => !((filter[1].prop === 'Title' ? n.title : (n.props[filter[1].prop] ?? (filter[1].inclNoval ? '' : filter[1].val))).includes(filter[1].val));
}
}
break;
case 'propList': // supports inclusions and exclusions only so far
if (filter[1].positive) { // no such thing as Noval for a list
return n => ((n.props[filter[1].prop] ?? ([])).includes(filter[1].val));
} else {
return n => !((n.props[filter[1].prop] ?? ([])).includes(filter[1].val));
}
}
};
/**
* Convert an array of filterArrays to a string to be used in the filter quake dialog.
* @param {filterArray[]} filters - the array of filters
* @returns {string} - the filters, stringified
*/
const stringifyFilter = filters => {
const ret = [];
for (const filter of filters) {
ret.push(`${(filter[1].positive ? '+' : '-') + { tag: 'tag', tagColor: 'color' }[filter[0]]}:${filter[1][{ tag: 'tag', tagColor: 'color' }[filter[0]]]}`); // TODO add properties
}
return ret.join(' ');
};
/**
* Remove quotes if they are present and matching
* @param {string} str - the string to check for quotes and remove if present and matching
* @returns {string} - the string stripped of quotes
*/
const removeQuotes = str => (str[0] === "'" && str.slice(-1) === "'") || (str[0] === '"' && str.slice(-1) === '"') ? str.slice(1, -1) : str;
/**
* Convert the string filter to a filterArray
* @param {string} param - the filter in string format
* @returns {filterArray} - the filter in filterArray format
* @throws {SyntaxError} If the syntax of the string is not correct
* @throws {ReferenceError} If a referenced tag, color, or prop is referenced as the wrong type or is nonexistent
*/
const convertFilter = param => {
if (!(['+', '-'].includes(param[0]))) throw new SyntaxError('A filter was specified without a sign (+ or -).');
const positive = param[0] === '+';
switch (param.substring(1, param.indexOf(':'))) {
case 'tag':
if (Object.prototype.hasOwnProperty.call(store.getters.tagLookup, param.substring(param.indexOf(':') + 1))) throw new ReferenceError('The tag specified does not exist in this TagSpace. You may need to check your spelling.');
return ['tag', { positive, tag: removeQuotes(param.substring(param.indexOf(':') + 1)), color: store.getters.tagLookup[param.substring(param.indexOf(':') + 1)] }];
case 'color':
if (Array.prototype.some.call(store.getters.tagviewerMeta.tagList, el => param.substring(param.indexOf(':') + 1) !== el[1])) throw new ReferenceError('The color specified does not belong to any tags in this TagSpace. Check that it matches exactly.');
return ['tagColor', { positive, color: param.substring(param.indexOf(':') + 1) }];
case 'prop':
{ let arglist = param.substring(param.indexOf(':') + 1).split(/<|>|=|<=|>=|!=|!{|{}/);
const propEntry = ['Title', 'Size', 'Resolution'].includes(arglist[0]) ? [arglist[0], { Title: 'String', Size: 'Size', Resolution: 'Resolution' }[arglist[0]]] : store.state.tagviewerMeta.propList.find(n => n[0] === arglist[0]);
if (typeof propEntry === 'undefined') throw new ReferenceError('The property specified does not exist in this TagSpace. You may need to check your spelling.');
if (propEntry[1] === 'Boolean') {
if (arglist.length > 1) throw new SyntaxError('A boolean property filter should not have a comparison.');
return ['propBoolean', { prop: arglist[0], positive, inclNoval: true }];
} else {
arglist.splice(1, 0, (param.substring(param.indexOf(':') + 1).match(/<|>|=|<=|>=|!=|!{|{}/)[0]));
if (arglist.length < 2) throw new SyntaxError('A property comparison was specified without a comparison operator ( <, >, =, <=, >=, !=, {}, or !{ ) present');
if (arglist.length > 2) arglist = [arglist[0], arglist[1], arglist.slice(2).join('')]; // if occurs, there's probably a comparison operator within the string
arglist[2] = removeQuotes(arglist[2]); // does nothing if there are no quotes.
if ((propEntry[1] === 'Number' && ['{}', '!{'].includes(arglist[1])) || (propEntry[1] === 'String' && ['<', '>', '>=', '<='].includes(arglist[1]))) throw new TypeError(`The comparison operator specified ("${arglist[1]}") does not match the type of the property specified ("${arglist[0]}" of type ${propEntry[1]}).`);
const computeOpposite = op => ({ '>': '<=', '<': '>=', '>=': '<', '<=': '>', '{}': '!{', '!{': '{}' }[op]);
const splitAt = (index, x) => [x.slice(0, index), x.slice(index)];
const fixType = (val, type) => (({
String: n => n.toString(),
Number: n => parseInt(n, 10),
Size: n =>
(([n, e]) =>
parseFloat(n) **
(10 * { b: 0, kb: 3, mb: 6, gb: 9, tb: 12 }[e.toLowerCase()])
)(
splitAt(
n.slice(-2, -1).toLowerCase() !== n.slice(-2, -1).toUpperCase() ? -2 : -1, n
)
),
Resolution: n => n.split('x').map(n => parseInt(n, 10))
}[type])(val));
return [`prop${propEntry[1]}`, { prop: arglist[0], condition: positive ? arglist[1] : computeOpposite(arglist[1]), val: fixType(arglist[2], propEntry[1]), inclNoval: true }]; // need to add inclNoval support
}
}
}
};
/**
* Split the full filter string into individual filter strings by spaces, respecting spaces in quotes.
* @param {string} str - the full filter string
* @returns {{err:boolean,value:string}} - the string split into individual filter strings
*/
const parseFilter = str => {
const params = str.split(/\s(?=[+-])(?![+-][A-Za-z0-9~!@#$%^&*()_=`{}[\]\\|;,.<>/?']+["])(?![+-][A-Za-z0-9~!@#$%^&*()_=`{}[\]\\|;,.<>/?"]+['])/); // all this just to allow + and - within a quoted string...
let ret = [];
try {
ret = Array.prototype.map.call(params, el => convertFilter(el));
} catch (e) {
return { err: true, value: e.toString() };
}
return { err: false, value: ret };
};
/**
* Similar to sortUsing, but only returns a number that represents how to sort the two items, used by Array.prototype.sort.
* @param {object} a - the first item to compare
* @param {object} b - the second item to compare
* @param {string} by - the name of a property to compare with
* @param {string} method - how to compare (A-Z or Z-A for string properties, for example)
* @returns {number} - the number to sort the items with Array.prototype.sort.
*/
const secondarySort = (a, b, by, method) => {
if (by === '' || method === '' || !vm.sortMethod2Options.includes(method)) { by = 'Title'; method = 'az'; }
switch (by) {
case 'Title':
if (method === 'az') return a.title.localeCompare(b.title);
if (method === 'za') return b.title.localeCompare(a.title);
break;
case 'Size':
if (method === '19') return a.size - b.size;
if (method === '91') return b.size - a.size;
break;
case 'Resolution':
if (method === '19') {
return !(!equals(a.resolution, [-1, -1]) || !equals(b.resolution, [-1, -1])) || (a.resolution[0] === b.resolution[0] && a.resolution[1] === b.resolution[1])
? a.title.localeCompare(b.title) // compare their titles (tertiary sort)
: !(!equals(a.resolution, [-1, -1]) && !equals(b.resolution, [-1, -1])) // if one has it but the other doesn't
? !equals(b.resolution, [-1, -1]) - !equals(a.resolution, [-1, -1]) // put the one with it first.
: a.resolution[0] * a.resolution[1] - b.resolution[0] * b.resolution[1]; // otherwise compare total pixels
}
if (method === '91') {
return !(!equals(a.resolution, [-1, -1]) || !equals(b.resolution, [-1, -1])) || (a.resolution[0] === b.resolution[0] && a.resolution[1] === b.resolution[1])
? a.title.localeCompare(b.title) // compare their titles (tertiary sort)
: !(!equals(a.resolution, [-1, -1]) && !equals(b.resolution, [-1, -1]))
? !equals(a.resolution, [-1, -1]) - !equals(b.resolution, [-1, -1])
: b.resolution[0] * b.resolution[1] - a.resolution[0] * a.resolution[1];
}
break;
default:
if (method === 'az') { // a, A, b, B, ... z, Z, noval
return !(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by] // if they both don't have the property OR if their value for the property is equal...
? a.title.localeCompare(b.title) // compare their titles (tertiary sort)
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by)) // otherwise, if one of them has the property but the other doesn't...
? Object.prototype.hasOwnProperty.call(b.props, by) - Object.prototype.hasOwnProperty.call(a.props, by) // put the one with the property first
: a.props[by].localeCompare(b.props[by]); // otherwise just compare the values.
}
if (method === 'za') { // z, Z, y, Y, ..., a, A, noval
return !(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by]
? a.title.localeCompare(b.title) // tertiary sort
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by))
? Object.prototype.hasOwnProperty.call(b.props, by) - Object.prototype.hasOwnProperty.call(a.props, by)
: b.props[by].localeCompare(a.props[by]);
}
if (method === '19') { // small, big, noval
return !(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by]
? a.title.localeCompare(b.title) // tertiary sort
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by))
? Object.prototype.hasOwnProperty.call(b.props, by) - Object.prototype.hasOwnProperty.call(a.props, by)
: a.props[by] - b.props[by];
}
if (method === '91') { // big, small, noval
return !(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by]
? a.title.localeCompare(b.title) // tertiary sort
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by))
? Object.prototype.hasOwnProperty.call(b.props, by) - Object.prototype.hasOwnProperty.call(a.props, by)
: b.props[by] - a.props[by];
}
if (method === 't') { // true, false, noval
return !(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by]
? a.title.localeCompare(b.title) // tertiary sort
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by))
? Object.prototype.hasOwnProperty.call(b.props, by) - Object.prototype.hasOwnProperty.call(a.props, by)
: b.props[by] - a.props[by];
}
if (method === 'f') { // false, true, noval
return !(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by]
? a.title.localeCompare(b.title) // tertiary sort
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by))
? Object.prototype.hasOwnProperty.call(b.props, by) - Object.prototype.hasOwnProperty.call(a.props, by)
: a.props[by] - b.props[by];
}
}
};
/**
* Sorts the array using the two properties and methods specified.
* @param {object[]} arr - the array to sort
* @param {string} by - what property to use to sort it
* @param {string} method - how to compare (a-z or z-a for string properties, for example)
* @param {string} by2 - the second property if the property matches between two items
* @param {string} method2 - how to compare
* @returns {object[]} - the sorted array
*/
const sortUsing = (arr, by, method, by2, method2) => {
switch (by) {
case 'Title':
if (method === 'az') return arr.concat().sort((a, b) => a.title.localeCompare(b.title)); // no secondary sort because titles can't be the same (or at least shouldn't be, may need to implement a check.)
if (method === 'za') return arr.concat().sort((a, b) => b.title.localeCompare(a.title));
break;
case 'Size':
if (method === '19') return arr.concat().sort((a, b) => a.size === b.size ? secondarySort(a, b, by2, method2) : a.size - b.size);
if (method === '91') return arr.concat().sort((a, b) => b.size === a.size ? secondarySort(b, a, by2, method2) : b.size - a.size);
break;
case 'Resolution':
if (method === '19') {
return arr.concat().sort((a, b) =>
!(!equals(a.resolution, [-1, -1]) || !equals(b.resolution, [-1, -1])) || (a.resolution[0] === b.resolution[0] && a.resolution[1] === b.resolution[1]) // if no resolution info is present, the array will be [-1, -1]. Use that instead of hasOwnProperty to check for presence.
? secondarySort(a, b, by2, method2) // if they both don't have it or if they're the same, use secondarySort
: !(!equals(a.resolution, [-1, -1]) && !equals(b.resolution, [-1, -1])) // if one has it but the other doesn't
? !equals(b.resolution, [-1, -1]) - !equals(a.resolution, [-1, -1]) // put the one with it first.
: a.resolution[0] * a.resolution[1] - b.resolution[0] * b.resolution[1] // otherwise compare total pixels
);
}
if (method === '91') {
return arr.concat().sort((a, b) => // same as above, but big goes before small
!(!equals(a.resolution, [-1, -1]) || !equals(b.resolution, [-1, -1])) || (a.resolution[0] === b.resolution[0] && a.resolution[1] === b.resolution[1])
? secondarySort(b, a, by2, method2)
: !(!equals(a.resolution, [-1, -1]) && !equals(b.resolution, [-1, -1]))
? !equals(a.resolution, [-1, -1]) - !equals(b.resolution, [-1, -1])
: b.resolution[0] * b.resolution[1] - a.resolution[0] * a.resolution[1]
);
}
break;
default:
if (method === 'az') { // a, A, b, B, ... z, Z, noval
return arr.concat().sort((a, b) => // concat with no args copies the array.
!(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by] // if they both don't have the property OR if their value for the property is equal...
? secondarySort(a, b, by2, method2) // compare using specified method or title
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by)) // otherwise, if one of them has the property but the other doesn't...
? Object.prototype.hasOwnProperty.call(b.props, by) - Object.prototype.hasOwnProperty.call(a.props, by) // put the one with the property first
: a.props[by].localeCompare(b.props[by]) // otherwise just compare the values.
);
}
if (method === 'za') { // z, Z, y, Y, ..., a, A, noval
return arr.concat().sort((b, a) => // switch order to easily reverse comparison! (see above for expl)
!(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by]
? secondarySort(b, a, by2, method2)
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by))
? Object.prototype.hasOwnProperty.call(a.props, by) - Object.prototype.hasOwnProperty.call(b.props, by) // order must be switched since the items without the property should still come after those with the property
: a.props[by].localeCompare(b.props[by])
);
}
if (method === '19') { // small, big, noval
return arr.concat().sort((a, b) => // see above for expl
!(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by]
? secondarySort(a, b, by2, method2)
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by))
? Object.prototype.hasOwnProperty.call(b.props, by) - Object.prototype.hasOwnProperty.call(a.props, by)
: a.props[by] - b.props[by]
);
}
if (method === '91') { // big, small, noval
return arr.concat().sort((b, a) => // same trick (see above for expl)
!(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by]
? secondarySort(b, a, by2, method2)
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by))
? Object.prototype.hasOwnProperty.call(a.props, by) - Object.prototype.hasOwnProperty.call(b.props, by) // as above, order must be switched since the items without the property should still come after those with the property
: a.props[by] - b.props[by]
);
}
if (method === 't') { // true, false, noval
return arr.concat().sort((a, b) => // see above for expl
!(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by]
? secondarySort(a, b, by2, method2)
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by))
? Object.prototype.hasOwnProperty.call(b.props, by) - Object.prototype.hasOwnProperty.call(a.props, by)
: b.props[by] - a.props[by]
);
}
if (method === 'f') { // false, true, noval
return arr.concat().sort((b, a) => // same trick (see above for expl)
!(Object.prototype.hasOwnProperty.call(a.props, by) || Object.prototype.hasOwnProperty.call(b.props, by)) || a.props[by] === b.props[by]
? secondarySort(b, a, by2, method2)
: !(Object.prototype.hasOwnProperty.call(a.props, by) && Object.prototype.hasOwnProperty.call(b.props, by))
? Object.prototype.hasOwnProperty.call(a.props, by) - Object.prototype.hasOwnProperty.call(b.props, by) // as above, order must be switched since the items without the property should still come after those with the property
: b.props[by] - a.props[by]
);
}
}
};
fs.ensureDirSync(app.app.getPath('userData')); // is this necessary? I guess it's good to ensure it.
/**
* Syncs the metadata for the TagSpace, waiting in the case of rapid requests.
*/
const debouncedSync = debounce(() => { store.dispatch('syncMetadata').then(() => { app.app.showExitPrompt = false; vm.showExitPrompt = false; }); }, 2000);
/**
* Syncs TagViewer's cache, waiting in the case of rapid requests.
*/
const debouncedCacheSync = debounce(() => { if (!safeMode[0]) fs.writeJSON(path.join(app.app.getPath('userData'), 'cache.json'), cache, { spaces: 2 }); }, 1400);
/**
* Syncs TagViewer's config, waiting in the case of rapid requests.
*/
const debouncedConfigSync = debounce(() => { if (!safeMode[1]) fs.writeJSON(path.join(app.app.getPath('userData'), 'config.json'), config, { spaces: 2 }); }, 1400);
if (Object.prototype.hasOwnProperty.call(config, 'navWidth')) {
((a, w) => {
a.style.width = `${w > 24 ? w : 0}px`; // the 24 and 12 must reflect the current padding!
a.style.paddingLeft = a.style.paddingRight = `${w > 24 ? 12 : Math.max(w / 2, 2)}px`;
a.style.color = w > 24 ? '' : `rgba(0,0,0,${Math.max((w - 10) * 0.05, 0)})`;
})(document.getElementById('nav'), config.navWidth);
}
interact('#nav').resizable({
edges: { right: true, left: false, top: false, bottom: false },
listeners: {
move (event) {
if (!(config.noSaveWidths ?? (false))) {
config.navWidth = Math.round(event.rect.width);
debouncedConfigSync();
}
event.target.style.width = `${event.rect.width > 24 ? event.rect.width : 0}px`; // the 24 and 12 must reflect the current padding!
event.target.style.paddingLeft = event.target.style.paddingRight = `${event.rect.width > 24 ? 12 : Math.max(event.rect.width / 2, 2)}px`;
event.target.style.color = event.rect.width > 24 ? '' : `rgba(0,0,0,${Math.max((event.rect.width - 10) * 0.05, 0)})`;
}
},
modifiers: [
interact.modifiers.restrict({
restriction: 'parent'
})
]
});
if (Object.prototype.hasOwnProperty.call(config, 'filtersWidth')) {
((a, w) => {
a.style.width = `${w > 24 ? w : 0}px`; // the 24 and 12 must reflect the current padding!
// a.style.paddingLeft = a.style.paddingRight = (w > 24 ? 12 : Math.max(w / 2, 2)) + 'px';
a.style.color = w > 24 ? '' : `rgba(0,0,0,${Math.max((w - 10) * 0.05, 0)})`;
if (a.children[1].children[0].tagName === 'UL') {
a.children[1].children[0].style.gridTemplateColumns = w > 290 ? 'auto 1fr' : 'auto';
a.children[1].children[0].style.rowGap = w > 290 ? '6px' : '0';
}
})(document.getElementById('filters-props'), config.filtersWidth);
}
interact('#filters-props').resizable({
edges: { right: false, left: true, top: false, bottom: false },
listeners: {
move (event) {
if (!(config.noSaveWidths ?? (false))) {
config.filtersWidth = Math.round(event.rect.width);
debouncedConfigSync();
}
event.target.style.width = `${event.rect.width > 24 ? event.rect.width : 0}px`; // the 24 and 12 must reflect the current padding!
// event.target.style.paddingLeft = event.target.style.paddingRight = (event.rect.width > 24 ? 12 : Math.max(event.rect.width / 2, 2)) + 'px';
event.target.style.color = event.rect.width > 24 ? '' : `rgba(0,0,0,${Math.max((event.rect.width - 10) * 0.05, 0)})`;
if (event.target.children[1].children[0].tagName === 'UL') {
event.target.children[1].children[0].style.gridTemplateColumns = event.rect.width > 290 ? 'auto 1fr' : 'auto';
event.target.children[1].children[0].style.rowGap = event.rect.width > 290 ? '6px' : '0';
}
}
},
modifiers: [
interact.modifiers.restrict({
restriction: 'parent'
})
]
});
/**
* A copy of the current index of the media within the files array in tagviewerMeta
* @type {number}
*/
let currentIndex = 1;
/**
* A copy of the current mediaNumber
* @type {number}
*/
let mediaNumberCopy = 1;
/**
* Circumvents the mediaNumber translation function when the mediaNumber actually changes
* @type {boolean}
*/
let mediaNumberActuallyChanged = false;
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
tagviewerMeta: {},
openDirectory: '',
mediaNumber: 1,
currentFilters: [],
itemProperties: []
},
getters: {
filtersActive: state => state.currentFilters.length > 0,
numOfFiles: (state, getters) => getters.currentFilesJSON.length,
currentFiles: (state, getters) => getters.currentFilesJSON.map(n => n._path), // the files that match the current filter ([] if no match or no filter or no open directory, [all files...] if no filter with open directory)
currentFilesJSON: (state, getters) => {
if (getters.tagspaceIsOpen) {
if (Object.keys(state.tagviewerMeta).length === 0 && state.tagviewerMeta.constructor === Object) { // should never be the case.
console.error('tagspaceIsOpen without tagviewerMeta.'); // store.commit('loadMetadata'); // needs to be a mutation since it's synchronous (the next instruction depends on its value.)
}
if (vm.sortBy !== 'Intrinsic' && vm.sortMethod !== '' && Array.prototype.some.call(vm.sortMethodOptions, el => vm.sortMethod === el.value)) {
const newValue = sortUsing(applyFilters(state.tagviewerMeta.files, state.currentFilters), vm.sortBy, vm.sortMethod, vm.sortBy2, vm.sortMethod2);
if (currentIndex !== null && newValue.some(el => el._index === currentIndex) && !mediaNumberActuallyChanged) store.dispatch('changeMediaNumberNoDeps', { abs: true, newVal: newValue.findIndex(el => el._index === currentIndex) + 1, currentFileJSON: newValue.length === 0 ? null : newValue[clamp(1, mediaNumberCopy, newValue.length) - 1], numOfFiles: newValue.length });
mediaNumberActuallyChanged = false;
return newValue;
} else {
const newValue = applyFilters(state.tagviewerMeta.files, state.currentFilters);
if (currentIndex !== null && newValue.some(el => el._index === currentIndex) && !mediaNumberActuallyChanged) store.dispatch('changeMediaNumberNoDeps', { abs: true, newVal: newValue.findIndex(el => el._index === currentIndex) + 1, currentFileJSON: newValue.length === 0 ? null : newValue[clamp(1, mediaNumberCopy, newValue.length) - 1], numOfFiles: newValue.length });
mediaNumberActuallyChanged = false;
return newValue;
}
} else {
return []; // no files if no open directory
}
},
currentFileJSON: (state, getters) => {
const newValue = Object.prototype.hasOwnProperty.call(getters.currentFilesJSON, state.mediaNumber - 1) ? getters.currentFilesJSON[state.mediaNumber - 1] : null;
currentIndex = newValue !== null && Object.prototype.hasOwnProperty.call(newValue, '_index') ? newValue._index : null;
return newValue;
},
tagspaceIsOpen: state => state.openDirectory !== '',
mediaIsOpen: (state, getters) => getters.tagspaceIsOpen && (getters.mediaPath !== '' || getters.filtersActive || state.tagviewerMeta.files.length === 0),
haveMediaOptions: (state, getters) => getters.mediaIsOpen && (getters.numOfFiles > 1 || getters.filtersActive),
mediaPath: (state, getters) => {
if (getters.tagspaceIsOpen && Array.prototype.hasOwnProperty.call(getters.currentFiles, state.mediaNumber - 1)) {
if (state.mediaNumber > 0 && state.mediaNumber <= getters.numOfFiles) store.commit('clampMediaNumber', getters.numOfFiles); // shouldn't have to do this!
return path.join(state.openDirectory, getters.currentFiles[state.mediaNumber - 1]);
} else {
return '';
}
},
mediaViewerType: (state, getters) => {
if (getters.mediaIsOpen) {
if (getters.currentFileJSON !== null) {
if (['.flac', '.mp4', '.webm', '.wav'].includes(path.extname(getters.mediaPath))) {
return 'video-viewer';
} else {
return 'image-viewer';
}
} else {
return 'no-media';
}
} else {
return '';
}
},
itemTags: (state, getters) => {
if (getters.currentFileJSON !== null) {
return Array.prototype.map.call(getters.currentFileJSON.tags, n => state.tagviewerMeta.tagList[n]);
} else {
return [];
}
},
offeredItemTags: (state, getters) => { try { return Array.prototype.filter.call(state.tagviewerMeta.tagList, el => !getters.itemTags.some(n => el[0] === n[0])); /* quack quack */ } catch (e) { return []; } }
},
actions: {
tagDeleted: (context, payload) => context.commit('tagDeleted', payload),
updateMetadata: (context, payload) => context.commit('updateMetadata', payload),
addMedia: (context, payload) => context.commit('addMedia', payload),
removeMedia: (context, index) => context.commit('removeMedia', { index, numOfFiles: context.getters.numOfFiles, mediaPath: context.getters.mediaPath }),
syncMetadata: context => fs.writeJSON(path.join(context.state.openDirectory, 'tagviewer.json'), context.state.tagviewerMeta, { spaces: 2 }), // returns a Promise
changeMediaNumber: (context, { newVal, abs }) => { context.commit('changeMediaNumber', { newVal: newVal, abs: abs, numOfFiles: context.getters.numOfFiles }); },
changeWorkingDirectory: (context, payload) => context.commit('changeWorkingDirectory', payload),
clampMediaNumber: context => context.commit('clampMediaNumber', context.getters.numOfFiles),
addFilter: (context, payload) => context.commit('addFilter', payload),
removeFilter: (context, payload) => context.commit('removeFilter', payload),
removeAllFilters: context => context.commit('removeAllFilters'),
updatePropMenu: context => context.commit('updatePropMenu', { mediaIsOpen: context.getters.mediaIsOpen, currentFileJSON: context.getters.currentFileJSON, mediaPath: context.getters.mediaPath }),
changeProperty: (context, { propName, newValue }) => context.commit('changeProperty', { propName, newValue, currentRealIndex: context.getters.currentFileJSON._index }),
removeTag: (context, payload) => context.commit('removeTag', { index: payload, currentRealIndex: context.getters.currentFileJSON._index }),
addTag: (context, payload) => context.commit('addTag', { tag: payload, currentRealIndex: context.getters.currentFileJSON._index }),
replaceFilter: (context, payload) => context.commit('replaceFilter', payload),
changeMediaNumberNoDeps: (context, payload) => context.commit('changeMediaNumberNoDeps', payload) // for compatibility when currentFilesJSON is undefined.
},
mutations: {
updateMetadata: function (state, newMeta) {
state.tagviewerMeta = newMeta;
app.app.showExitPrompt = true;
vm.showExitPrompt = true;
debouncedSync();
store.dispatch('updatePropMenu');
},
loadMetadata: function (state) { // should be called as-is since it needs to be synchronous.
try {
state.tagviewerMeta = fs.readJSONSync(path.join(state.openDirectory, 'tagviewer.json'));
} catch (err) {
dialog.showErrorBox('JSON was invalid.', `The JSON (at path: ${path.join(state.openDirectory, 'tagviewer.json')}) for this TagSpace is invalid. If you've edited the file, please fix any errors. If not, please report the issue on GitHub. TagViewer will now exit.\n\n(Specifically, the error that occured is as follows: ${err.toString()})`);
app.app.quit();
}
},
clampMediaNumber: function (state, payload) { // if commit-ing directly, pass the number of files through the payload
if (state.mediaNumber < 1 || state.mediaNumber > payload) {
state.mediaNumber = clamp(1, state.mediaNumber, payload);
store.dispatch('updatePropMenu');
} /* else {
state.mediaNumber = clamp(1, state.mediaNumber, payload);
} */ // nothing required, I believe
},
removeMedia: function (state, { index, mediaPath, numOfFiles }) { // payload is index, but note that it's the actual index (not the mediaNumber)
if (state.tagviewerMeta.files[index]._path === path.basename(mediaPath)) {
if (numOfFiles > 1) {
if (state.mediaNumber !== 1) { // if it is 1, we'll stay there because it will become the next media due to how the array works.
state.mediaNumber -= 1; // go to previous media (it could be next but not if we're at the last media.)
}
} else {
dialog.showMessageBox(app.getCurrentWindow(), {
title: 'No remaining media',
message: "You've deleted the only media in this TagSpace. However, the TagSpace still exists, and you're still able to add more media to it.",
buttons: 'Okay',
cancelId: 0,
defaultId: 0,
type: 'info'
});
}
}
trash(path.join(state.openDirectory, state.tagviewerMeta.files[index]._path)).then(() => { // delete image non-permanently
state.tagviewerMeta.files.splice(index, 1); // remove from files array.
state.tagviewerMeta.files = state.tagviewerMeta.files.map((el, i) => {
el._index = i;
return el;
});
state.tagviewerMeta.currentIndex -= 1;
debouncedSync();
});
},
changeMediaNumber: function (state, { newVal, abs, numOfFiles }) { // if commit-ing directly, pass the number of files in the payload
if (abs) {
state.mediaNumber = clamp(1, newVal, numOfFiles);
} else {
state.mediaNumber += newVal;
state.mediaNumber = clamp(1, state.mediaNumber, numOfFiles);
}
currentIndex = state.mediaNumber;
mediaNumberCopy = state.mediaNumber;
store.dispatch('updatePropMenu');
},
changeMediaNumberNoDeps: function (state, { newVal, abs, currentFileJSON, numOfFiles }) {
state.mediaNumber = clamp(1, abs ? newVal : (state.mediaNumber + newVal), numOfFiles);
mediaNumberCopy = state.mediaNumber;
if (currentFileJSON !== null) {
state.itemProperties = [ // a no-dependencies version of updatePropMenu
['Title', currentFileJSON.title, 'String'],
['Size', humanFileSize(currentFileJSON.size, true, 1), false],
['Resolution', (['.flac', '.mp4', '.webm', '.wav'].includes(path.extname(currentFileJSON._path))) ? 'Resolution is currently not supported for videos.' : currentFileJSON.resolution.join('x'), false],
...(state.tagviewerMeta.propList.map(n => {
const ret = [];
ret[0] = n[0];
ret[1] = (currentFileJSON.props[n[0]] ?? (null)); // it becomes [...[name, value, type]]
ret[2] = n[1];
return ret;
}))
];
} else {
state.itemProperties = [];
}
},
updatePropMenu: function (state, { mediaIsOpen, currentFileJSON, mediaPath }) {
if (mediaIsOpen && currentFileJSON !== null) {
state.itemProperties = [
['Title', currentFileJSON.title, 'String'],
['Size', humanFileSize(currentFileJSON.size, true, 1), false],
['Resolution', (['.flac', '.mp4', '.webm', '.wav'].includes(path.extname(mediaPath))) ? 'Resolution is currently not supported for videos.' : currentFileJSON.resolution.join('x'), false],
...(state.tagviewerMeta.propList.map(n => {
const ret = [];
ret[0] = n[0];
ret[1] = (currentFileJSON.props[n[0]] ?? (null)); // it becomes [...[name, value, type]]
ret[2] = n[1];
return ret;
}))
];
} else {
state.itemProperties = [];
}
},
changeProperty: function (state, { propName, newValue, currentRealIndex }) {
if (propName === 'Title') {
state.tagviewerMeta.files[currentRealIndex].title = newValue;
} else {
if (newValue === null) {
delete state.tagviewerMeta.files[currentRealIndex].props[propName];
} else {
state.tagviewerMeta.files[currentRealIndex].props[propName] = newValue;
}
}
app.app.showExitPrompt = true;
vm.showExitPrompt = true;
debouncedSync(); // not really used for debouncing, but more for a responsive delay before writing to metadata.
store.dispatch('updatePropMenu');
},
changeWorkingDirectory: function (state, { newDir }) {
// eslint-disable-next-line brace-style
if (state.openDirectory !== '') { store.dispatch('syncMetadata').then(() => { // to make sure data isn't lost from previous sessions.
state.openDirectory = newDir; // store a copy in OS-specific format
store.commit('loadMetadata');
if (cache.openHistory.includes(newDir)) { // remove it if it exists, then add it. (we don't want duplicates)
cache.openHistory.splice(cache.openHistory.indexOf(newDir), 1);
}
cache.openHistory.unshift(newDir);
cache.openHistory = cache.openHistory.slice(0, 10);
cache.openDirectory = newDir;
debouncedCacheSync();
document.title = `TagViewer ${_version}\u2002\u2013\u2002${state.tagviewerMeta.title}`;
store.dispatch('changeMediaNumber', { newVal: 1, abs: true }); // always
}); } else { // eslint-disable-line brace-style
state.openDirectory = newDir; // store a copy in OS-specific format
store.commit('loadMetadata');
if (cache.openHistory.includes(newDir)) { // remove it if it exists, then add it. (we don't want duplicates)
cache.openHistory.splice(cache.openHistory.indexOf(newDir), 1);
}
cache.openHistory.unshift(newDir);
cache.openHistory = cache.openHistory.slice(0, 10);
cache.openDirectory = newDir;
debouncedCacheSync();
document.title = `TagViewer ${_version}\u2002\u2013\u2002${state.tagviewerMeta.title}`;
store.dispatch('changeMediaNumber', { newVal: 1, abs: true }); // always
}
mediaNumberActuallyChanged = true;
vm.mediaNumber = 1;
},
addMedia: function (state, [object, index]) {
console.assert(state.tagviewerMeta.currentIndex === index);
Vue.set(state.tagviewerMeta.files, state.tagviewerMeta.currentIndex, object);
Vue.set(state.tagviewerMeta, 'currentIndex', state.tagviewerMeta.currentIndex + 1);
},
addFilter: function (state, filter) {
state.currentFilters.push(filter);
store.dispatch('clampMediaNumber');
},
removeFilter: function (state, index) {
state.currentFilters.splice(index, 1);
store.dispatch('updatePropMenu');
},
removeAllFilters: function (state) {
state.currentFilters.splice(0); // empty
store.dispatch('updatePropMenu');
},
removeTag: function (state, { index, currentRealIndex }) {
state.tagviewerMeta.files[currentRealIndex].tags.splice(index, 1);
store.dispatch('updatePropMenu');
app.app.showExitPrompt = true;
vm.showExitPrompt = true;
debouncedSync();
},
addTag: function (state, { tag, currentRealIndex }) {
state.tagviewerMeta.files[currentRealIndex].tags.push(state.tagviewerMeta.tagList.indexOf(tag));
store.dispatch('updatePropMenu');
app.app.showExitPrompt = true;
vm.showExitPrompt = true;
debouncedSync();
},
replaceFilter: function (state, newFilter) {
state.currentFilters = newFilter;
}
}
});
const vm = new Vue({
store: store,
el: '#vue-container',
data: {
offeringPreviousLocation: (config.offerPrevLocation ?? (true)) && Object.prototype.hasOwnProperty.call(cache, 'openDirectory') && fs.existsSync(path.join(cache.openDirectory, 'tagviewer.json')),
asideTab: 1,
tentativeFilterText: '',
autocompleteFilterText: '',
errorText: '',
filterQuake: false,
showExitPrompt: app.app.showExitPrompt,
sortBy: 'Intrinsic',
sortMethod: '',
sortBy2: '',
sortMethod2: '',
slideshowInterval: null,
isFullscreen: false,
tagSearchString: null,
colorSearchString: null,
propSearchString: null,
filterListCollapsed: [false, false, false]
},
watch: {
filterQuake: function (active) {
const filterQuakeEl = document.getElementById('filter-quake');
if (active) {
filterQuakeEl.children[1].select();
document.body.children[0].addEventListener('click', filterQuakeContainerClickHandler());
filterQuakeEl.children[1].addEventListener('input', filterQuakeAutocompleter());
filterQuakeEl.children[1].addEventListener('keydown', filterQuakeKeydownHandler());
} else {
setTimeout(() => (vm.errorText = ''), 300);
document.body.children[1].removeEventListener('click', filterQuakeContainerClickHandler());
filterQuakeEl.children[1].removeEventListener('input', filterQuakeAutocompleter());
filterQuakeEl.children[1].removeEventListener('keydown', filterQuakeKeydownHandler());
}
},
isFullscreen: function (isFS) {
if (isFS) document.addEventListener('keydown', function handler (e) { if (e.key === 'Escape') { vm.isFullscreen = false; document.removeEventListener('keypress', handler); } });
if (!isFS && (config.endSlideshowOnFSExit ?? (true))) vm.endSlideshow();