-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
1309 lines (1259 loc) · 35.9 KB
/
script.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
/**
* Symbiota Label Builder Functions
* Author: Laura Rocha Prado
* Version: 2020
*/
/** Creating Page Elements/Controls
******************************
*/
// Defines formattable items in label (also used to create preview elements)
const fieldProps = [
{
block: 'labelBlock',
name: 'Occurrence ID',
id: 'occid',
group: 'specimen',
},
{
block: 'labelBlock',
name: 'Catalog Number',
id: 'catalognumber',
group: 'specimen',
},
{
block: 'labelBlock',
name: 'Other Catalog Numbers',
id: 'othercatalognumbers',
group: 'specimen',
},
{ block: 'labelBlock', name: 'Family', id: 'family', group: 'taxon' },
{
block: 'labelBlock',
name: 'Scientific Name',
id: 'scientificname',
group: 'taxon',
},
{ block: 'labelBlock', name: 'Taxon Rank', id: 'taxonrank', group: 'taxon' },
{
block: 'labelBlock',
name: 'Infraspecific Epithet',
id: 'infraspecificepithet',
group: 'taxon',
},
{
block: 'labelBlock',
name: 'Scientific Name Authorship',
id: 'scientificnameauthorship',
group: 'taxon',
},
{
block: 'labelBlock',
name: 'Parent Author',
id: 'parentauthor',
group: 'taxon',
},
{
block: 'labelBlock',
name: 'Identified By',
id: 'identifiedby',
group: 'determination',
},
{
block: 'labelBlock',
name: 'Date Identified',
id: 'dateidentified',
group: 'determination',
},
{
block: 'labelBlock',
name: 'Identification References',
id: 'identificationreferences',
group: 'determination',
},
{
block: 'labelBlock',
name: 'Identification Remarks',
id: 'identificationremarks',
group: 'determination',
},
{
block: 'labelBlock',
name: 'Taxon Remarks',
id: 'taxonremarks',
group: 'determination',
},
{
block: 'labelBlock',
name: 'Identification Qualifier',
id: 'identificationqualifier',
group: 'determination',
},
{
block: 'labelBlock',
name: 'Type Status',
id: 'typestatus',
group: 'specimen',
},
{
block: 'labelBlock',
name: 'Recorded By',
id: 'recordedby',
group: 'event',
},
{
block: 'labelBlock',
name: 'Record Number',
id: 'recordnumber',
group: 'event',
},
{
block: 'labelBlock',
name: 'Associated Collectors',
id: 'associatedcollectors',
group: 'event',
},
{ block: 'labelBlock', name: 'Event Date', id: 'eventdate', group: 'event' },
{ block: 'labelBlock', name: 'Year', id: 'year', group: 'event' },
{ block: 'labelBlock', name: 'Month', id: 'month', group: 'event' },
{ block: 'labelBlock', name: 'Month Name', id: 'monthname', group: 'event' },
{ block: 'labelBlock', name: 'Day', id: 'day', group: 'event' },
{
block: 'labelBlock',
name: 'Verbatim Event Date',
id: 'verbatimeventdate',
group: 'event',
},
{ block: 'labelBlock', name: 'Habitat', id: 'habitat', group: 'event' },
{ block: 'labelBlock', name: 'Substrate', id: 'substrate', group: 'event' },
{
block: 'labelBlock',
name: 'Occurrence Remarks',
id: 'occurrenceremarks',
group: 'specimen',
},
{
block: 'labelBlock',
name: 'Associated Taxa',
id: 'associatedtaxa',
group: 'taxon',
},
// { block: 'labelBlock', name: 'Dynamic Properties', id: 'dynamicProperties' },
{
block: 'labelBlock',
name: 'Verbatim Attributes',
id: 'verbatimattributes',
group: 'event',
},
{ block: 'labelBlock', name: 'Behavior', id: 'behavior', group: 'specimen' },
{
block: 'labelBlock',
name: 'Reproductive Condition',
id: 'reproductivecondition',
group: 'specimen',
},
{
block: 'labelBlock',
name: 'Cultivation Status',
id: 'cultivationstatus',
group: 'specimen',
},
{
block: 'labelBlock',
name: 'Establishment Means',
id: 'establishmentmeans',
group: 'specimen',
},
{
block: 'labelBlock',
name: 'Life Stage',
id: 'lifeStage',
group: 'specimen',
},
{ block: 'labelBlock', name: 'Sex', id: 'sex', group: 'specimen' },
{
block: 'labelBlock',
name: 'Individual Count',
id: 'individualcount',
group: 'specimen',
},
{
block: 'labelBlock',
name: 'Sampling Protocol',
id: 'samplingprotocol',
group: 'specimen',
},
{
block: 'labelBlock',
name: 'Preparations',
id: 'preparations',
group: 'specimen',
},
{ block: 'labelBlock', name: 'Country', id: 'country', group: 'locality' },
{
block: 'labelBlock',
name: 'State/Province',
id: 'stateprovince',
group: 'locality',
},
{ block: 'labelBlock', name: 'County', id: 'county', group: 'locality' },
{
block: 'labelBlock',
name: 'Municipality',
id: 'municipality',
group: 'locality',
},
{ block: 'labelBlock', name: 'Locality', id: 'locality', group: 'locality' },
{
block: 'labelBlock',
name: 'Decimal Latitude',
id: 'decimallatitude',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Decimal Longitude',
id: 'decimallongitude',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Geodetic Datum',
id: 'geodeticdatum',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Coordinate Uncertainty In Meters',
id: 'coordinateuncertaintyinmeters',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Verbatim Coordinates',
id: 'verbatimcoordinates',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Elevation In Meters',
id: 'elevationinmeters',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Verbatim Elevation',
id: 'verbatimelevation',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Minimum Depth In Meters',
id: 'minimumdepthinmeters',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Maximum Depth In Meters',
id: 'maximumdepthinmeters',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Verbatim Depth',
id: 'verbatimdepth',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Disposition',
id: 'disposition',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Storage Location',
id: 'storagelocation',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Duplicate Quantity',
id: 'duplicatequantity',
group: 'locality',
},
{
block: 'labelBlock',
name: 'Date Last Modified',
id: 'datelastmodified',
group: 'event',
},
];
// Defines formatting buttons
const formatsArr = [
{ group: 'field', func: 'font-bold', icon: 'format_bold', title: 'Bold' },
{ group: 'field', func: 'italic', icon: 'format_italic', title: 'Italic' },
{
group: 'field',
func: 'underline',
icon: 'format_underlined',
title: 'Underline',
},
{
group: 'field',
func: 'uppercase',
icon: 'format_size',
title: 'Uppercase',
},
{
group: 'field-block',
func: 'bar',
icon: '',
name: 'Bar Below',
title: 'Add bar below line',
},
{
group: 'field-block',
func: 'bar-top',
icon: '',
name: 'Bar Above',
title: 'Add bar above line',
},
];
// Defines dropdown style groups
const dropdownsArr = [
{
id: 'text',
name: 'font-size',
group: 'field',
options: [
{ value: '', text: 'Font Size' },
{ value: 'text-xs', text: 'X-Small' },
{ value: 'text-sm', text: 'Small' },
{ value: 'text-base', text: 'Normal' },
{ value: 'text-lg', text: 'Large' },
{ value: 'text-xl', text: 'X-Large' },
{ value: 'text-2xl', text: '2X-Large' },
{ value: 'text-3xl', text: '3X-Large' },
{ value: 'text-4xl', text: '4X-Large' },
{ value: 'text-5xl', text: '5X-Large' },
{ value: 'text-6xl', text: '6X-Large' },
],
},
{
id: 'float',
name: 'float',
group: 'field',
options: [
{ value: '', text: 'Position in Line' },
// { value: 'float-none', text: 'None' },
{ value: 'float-left', text: 'Left' },
{ value: 'float-right', text: 'Right' },
],
},
{
id: 'font-family',
name: 'font-family',
group: 'field',
options: [
{ value: '', text: 'Font Family' },
{ value: 'font-family-arial', text: 'Arial (sans-serif)' },
{ value: 'font-family-verdana', text: 'Verdana (sans-serif)' },
{ value: 'font-family-helvetica', text: 'Helvetica (sans-serif)' },
{ value: 'font-family-tahoma', text: 'Tahoma (sans-serif)' },
{ value: 'font-family-trebuchet', text: 'Trebuchet (sans-serif)' },
{ value: 'font-family-times', text: 'Times New Roman (serif)' },
{ value: 'font-family-georgia', text: 'Georgia (serif)' },
{ value: 'font-family-garamond', text: 'Garamond (serif)' },
{ value: 'font-family-courier', text: 'Courier New (monospace)' },
{ value: 'font-family-brush', text: 'Brush Script MT (cursive)' },
],
},
{
id: 'text-align',
name: 'text-align',
group: 'field-block',
options: [
{ value: '', text: 'Text Align' },
{ value: 'text-align-center', text: 'Center' },
{ value: 'text-align-right', text: 'Right' },
// { value: 'text-align-justify', text: 'Justify' },
{ value: 'text-align-left', text: 'Left' },
],
},
{
id: 'mt',
name: 'spacing-top',
group: 'field-block',
options: [
{ value: '', text: 'Line Spacing Top' },
{ value: 'mt-0', text: '0' },
{ value: 'mt-1', text: '1' },
{ value: 'mt-2', text: '2' },
{ value: 'mt-3', text: '3' },
{ value: 'mt-4', text: '4' },
{ value: 'mt-5', text: '5' },
{ value: 'mt-6', text: '6' },
{ value: 'mt-8', text: '8' },
{ value: 'mt-10', text: '10' },
{ value: 'mt-12', text: '12' },
],
},
{
id: 'mb',
name: 'spacing-bottom',
group: 'field-block',
options: [
{ value: '', text: 'Line Spacing Bottom' },
{ value: 'mb-0', text: '0' },
{ value: 'mb-1', text: '1' },
{ value: 'mb-2', text: '2' },
{ value: 'mb-3', text: '3' },
{ value: 'mb-4', text: '4' },
{ value: 'mb-5', text: '5' },
{ value: 'mb-6', text: '6' },
{ value: 'mb-8', text: '8' },
{ value: 'mb-10', text: '10' },
{ value: 'mb-12', text: '12' },
],
},
];
const dummy = document.getElementById('dummy');
const fieldDiv = document.getElementById('fields');
const fieldListDiv = document.getElementById('fields-list');
const controlDiv = document.getElementById('controls');
const fieldsFilter = document.getElementById('fields-filter');
const labelMid = document.getElementById('label-middle');
// Initially creates all fields
createFields(fieldProps, fieldListDiv);
// Creates formatting (button) controls in page
formatsArr.forEach((format) => {
let targetDiv = document.getElementById(`${format.group}-options`);
let btn = document.createElement('button');
btn.classList.add('control');
btn.disabled = true;
btn.dataset.func = format.func;
btn.dataset.group = format.group;
btn.title = format.title;
if (format.icon !== '') {
let icon = document.createElement('span');
icon.classList.add('material-icons');
icon.innerText = format.icon;
btn.appendChild(icon);
} else {
btn.innerText = format.name;
}
targetDiv.appendChild(btn);
});
// Creates formatting (dropdown) controls in page
dropdownsArr.forEach((dropObj) => {
let targetDiv = document.getElementById(`${dropObj.group}-options`);
let lbl = document.createElement('label');
lbl.htmlFor = dropObj.id;
lbl.innerText = dropObj.options[0].text + ':';
lbl.style = 'display: block;';
let slct = document.createElement('select');
slct.dataset.group = dropObj.group;
slct.classList.add('control');
slct.name = dropObj.name;
slct.id = dropObj.id;
slct.disabled = true;
dropObj.options.forEach((choice) => {
let opt = document.createElement('option');
opt.value = choice.value;
opt.innerText = choice.text;
slct.appendChild(opt);
});
targetDiv.appendChild(lbl);
targetDiv.appendChild(slct);
});
// Grabs elements
const containers = document.querySelectorAll('.container');
const draggables = document.querySelectorAll('.draggable');
const build = document.getElementById('build-label');
const preview = document.getElementById('preview-label');
const controls = document.querySelectorAll('.control');
const inputs = document.querySelectorAll('input');
// JSON TRANSLATION
let jsonSource = [
{
divBlock: {
className: 'label-blocks',
style: '',
blocks: [
{
fieldBlock: [
{
field: 'family',
className: 'uppercase text-sm',
},
],
delimiter: ' ',
className: 'text-align-center mb-4',
},
{
fieldBlock: [
{
field: 'scientificname',
className: 'italic font-bold',
},
{
field: 'scientificnameauthorship',
prefix: '(',
suffix: ')',
},
],
delimiter: ' ',
},
{
fieldBlock: [
{
field: 'catalognumber',
className: 'font-bold text-xl',
},
{
field: 'othercatalognumbers',
className: 'font-bold text-xl',
},
],
delimiter: ', ',
className: 'mt-10',
},
],
},
},
];
function translateJson(source) {
// Source has to be "simple", as in: following structure output by generateJson()
// console.log(source);
let srcLines = source[0].divBlock.blocks;
srcLines ? '' : (preview.innerText = '<h1>ERROR</h1>');
let lineCount = srcLines.length;
// Create additional blocks in label builder
for (i = 0; i < lineCount - 1; i++) {
addLine();
}
let lbBlocks = labelMid.querySelectorAll('.field-block');
// Add field(s) inside line[i]
srcLines.forEach((srcLine, i) => {
// Style fieldblocks
let lbBlock = lbBlocks[i];
lbBlock.dataset.delimiter = srcLine.delimiter;
srcLine.className !== undefined
? (lbBlock.className = lbBlock.className + ' ' + srcLine.className)
: '';
// Array of fields based on fieldProps filtered by current fields in json format
let fieldsArr = srcLine.fieldBlock;
let propsArr = [];
fieldsArr.forEach(({ field, className }) => {
let props = fieldProps.find((obj) => obj.id === field);
propsArr.push(props);
});
createFields(propsArr, lbBlocks[i]);
// Select created item in label build (have to limit to one line at a time)
let createdLis = lbBlocks[i].querySelectorAll('.draggable');
// Add classes from json to item
createdLis.forEach((li, j) => {
let srcFieldsArr = srcLines[i].fieldBlock;
let srcPropsArr = srcFieldsArr[j];
let fieldId = srcPropsArr.field;
let classes = srcPropsArr.className;
let prefix = srcPropsArr.prefix;
let suffix = srcPropsArr.suffix;
if (li.id === fieldId) {
classes !== undefined ? (li.className = 'draggable ' + classes) : '';
prefix !== undefined ? (li.dataset.prefix = prefix) : '';
suffix !== undefined ? (li.dataset.suffix = suffix) : '';
}
});
});
refreshAvailFields();
refreshPreview();
}
// Initially sets state of lines
refreshLineState();
/** Methods
******************************
*/
/**
* Displays user instructions overlay
*/
const overlay = document.getElementById('instructions');
function openOverlay() {
overlay.classList.remove('hidden');
}
/**
* Hides user instructions overlay
*/
function closeOverlay() {
overlay.classList.add('hidden');
}
/**
* Filters array based on desired property
* @param {Array} arr Array to be filtered
* @param {Object} criteria Pair or pairs of property and criterion
*/
function filterObject(arr, criteria) {
return arr.filter(function (obj) {
return Object.keys(criteria).every(function (c) {
return obj[c] == criteria[c];
});
});
}
/**
* Removes object from array based on desired property
* @param {Array} arr Array to be cleaned
* @param {Object} criteria Pair or pairs of property and criterion
*/
function removeObject(arr, criteria) {
return arr.filter(function (obj) {
return Object.keys(criteria).every(function (c) {
return obj[c] !== criteria[c];
});
});
}
/**
* Gets list of fields currently available to drag to label build area
*/
function getCurrFields() {
let currFields = fieldProps;
let usedFields = document.querySelectorAll('#label-middle .draggable');
if (usedFields.length > 0) {
usedFields.forEach((usedField) => {
currFields = removeObject(currFields, { id: usedField.id });
});
}
return currFields;
}
/**
* Filters available fields on select option
*/
function filterFields(value) {
// let value = this.value;
let filteredFields = '';
value === 'all'
? (filteredFields = getCurrFields())
: (filteredFields = filterObject(getCurrFields(), { group: value }));
fieldListDiv.innerHTML = '';
createFields(filteredFields, fieldListDiv);
}
function refreshAvailFields() {
let available = getCurrFields();
fieldListDiv.innerHTML = '';
let selectedFilter = fieldsFilter.value;
selectedFilter != 'all'
? filterFields(selectedFilter)
: createFields(available, fieldListDiv);
}
/**
* Creates draggable elements
* @param {Arr} arr Array with list of currently available fields
*/
function createFields(arr, target) {
arr.forEach((field) => {
let li = document.createElement('li');
li.innerHTML = field.name;
li.id = field.id;
if (field.block === 'labelBlock') {
let closeBtn = document.createElement('span');
closeBtn.classList.add('material-icons');
closeBtn.innerText = 'cancel';
closeBtn.addEventListener('click', removeField, false);
li.appendChild(closeBtn);
li.draggable = 'true';
li.classList.add('draggable');
li.dataset.category = field.group;
li.addEventListener('dragstart', handleDragStart, false);
li.addEventListener('dragover', handleDragOver, false);
li.addEventListener('drop', handleDrop, false);
li.addEventListener('dragend', handleDragEnd, false);
target.appendChild(li);
}
});
}
/**
* Appends line (fieldBlock) to label builder
* Binded to button, adds editable div
*/
function addLine() {
let line = document.createElement('div');
line.classList.add('field-block', 'container');
line.dataset.delimiter = ' ';
let midBlocks = document.querySelectorAll('#label-middle > .field-block');
let close = document.createElement('span');
close.classList.add('material-icons');
close.innerText = 'close';
line.appendChild(close);
let up = document.createElement('span');
up.classList.add('material-icons');
up.innerText = 'keyboard_arrow_up';
line.appendChild(up);
let down = document.createElement('span');
down.classList.add('material-icons');
down.innerText = 'keyboard_arrow_down';
line.appendChild(down);
let lastBlock = midBlocks[midBlocks.length - 1];
lastBlock.parentNode.insertBefore(line, lastBlock.nextSibling);
// Allows items to be added/reordered inside fieldBlock
line.addEventListener('dragover', (e) => {
e.preventDefault();
const dragging = document.querySelector('.dragging');
dragging !== null ? line.appendChild(dragging) : '';
});
refreshLineState();
}
/**
* Refreshes line state
* If there is only one line, disables line controls
*/
function refreshLineState() {
let lines = labelMid.querySelectorAll('.field-block');
let icons = lines[0].querySelectorAll('.material-icons');
let isSingleLine = lines.length == 1;
icons.forEach((icon) => {
isSingleLine
? icon.classList.add('disabled')
: icon.classList.remove('disabled');
});
}
/**
* Removes line from label-middle
* @param {Object} line node to be removed
*/
function removeLine(line) {
let lineCount = labelMid.querySelectorAll('.field-block').length;
lineCount > 1 ? line.remove() : false;
refreshLineState();
refreshAvailFields();
}
/**
* Removes field from label-middle
* @param {Object} field node to be removed
*/
function removeField(field) {
field.target.parentNode.remove();
// Refresh available fields list
refreshAvailFields();
}
/**
* Refreshes label preview
* Triggered every time items are updated
*/
function refreshPreview() {
let labelList = [];
let fieldBlocks = document.querySelectorAll('#build-label .field-block');
// Builds array with directives (labelList)
fieldBlocks.forEach((block) => {
let itemsArr = [];
let items = block.querySelectorAll('li');
items.forEach((item) => {
let itemObj = {};
let className = Array.from(item.classList).filter(isPrintStyle);
itemObj.field = item.id;
itemObj.className = className;
itemObj.prefix = item.dataset.prefix;
itemObj.suffix = item.dataset.suffix;
itemsArr.push(itemObj);
});
labelList.push(itemsArr);
let fieldBlockStyles = Array.from(block.classList).filter(isPrintStyle);
fieldBlockStyles ? (itemsArr.className = fieldBlockStyles) : '';
let fieldBlockDelim = block.dataset.delimiter;
fieldBlockDelim == undefined
? (itemsArr.delimiter = ' ')
: (itemsArr.delimiter = fieldBlockDelim);
});
// Clears preview div before appending elements
preview.innerHTML = '';
// Creates HTML elements and appends to preview div
labelList.forEach((labelItem, blockIdx) => {
let blockLen = labelItem.length;
let fieldBlock = document.createElement('div');
fieldBlock.classList.add('field-block');
let labelItemStyles = labelItem.className;
labelItemStyles.forEach((style) => {
fieldBlock.classList.add(style);
});
preview.appendChild(fieldBlock);
labelItem.forEach((field, fieldIdx) => {
createPreviewEl(field, fieldBlock);
let isLast = fieldIdx == blockLen - 1;
// Adds delimiter if existing up to last element
if (!isLast) {
let preview = document.getElementsByClassName(field.field);
let delim = document.createElement('span');
delim.innerText = labelItem.delimiter;
preview[0].after(delim);
}
});
});
return labelList;
}
/**
* Creates elements in preview div, based on controls in build
* @param {Object} element Field, constructed in `refreshPreview()`
* @param {DOM Node} parent DOM Node where element will be inserted
*/
function createPreviewEl(element, parent) {
// Grabs information from fieldProps array to create elements matching on id
let fieldInfo =
fieldProps[fieldProps.findIndex((x) => x.id === element.field)];
let div = document.createElement('div');
div.innerHTML = fieldInfo.name.split(' ').join('');
div.classList.add(fieldInfo.id);
div.classList.add(...element.className);
parent.appendChild(div);
let hasPrefix = element.prefix != undefined;
let hasSuffix = element.suffix != undefined;
if (hasPrefix) {
let currText = div.innerText;
let prefSpan = `<span>${element.prefix}</span>`;
div.innerHTML = prefSpan + currText;
}
if (hasSuffix) {
let sufSpan = document.createElement('span');
sufSpan.innerText = element.suffix;
div.appendChild(sufSpan);
}
}
/**
* Returns true if item is formattable
* @param {Object} element
*/
function isFormattable(element) {
if (
element.classList.contains('field-block') ||
element.classList.contains('draggable')
) {
return true;
} else {
return false;
}
}
/**
* Checks if class should be output in JSON
* @param {String} className found in item
*/
function isPrintStyle(className) {
const functionalStyles = [
'draggable',
'selected',
'field-block',
'container',
];
return !functionalStyles.includes(className);
}
/**
* Generate JSON string for current configurations
* @param {Array} list Array of fields, built by `refreshPreview()`
*/
function generateJson(list) {
let wrapper = [
{
divBlock: {
className: 'label-blocks',
style: '',
blocks: [],
},
},
];
// console.log(wrapper.divBlock.blocks.length);
let labelBlocks = [];
// Parse nested array
Object.keys(list).forEach((index) => {
let fieldBlockObj = {};
// Joins array of className items for fields
let fieldItem = list[index];
fieldItem.map((prop) => {
prop.className.length > 0
? (prop.className = prop.className.join(' '))
: delete prop.className;
});
fieldBlockObj.fieldBlock = fieldItem;
let fieldBlockDelim = fieldItem.delimiter;
fieldBlockDelim !== undefined
? (fieldBlockObj.delimiter = fieldBlockDelim)
: '';
let fieldBlockStyles = fieldItem.className;
fieldBlockStyles.length > 0
? (fieldBlockObj.className = fieldItem.className.join(' '))
: delete fieldBlockObj.className;
labelBlocks.push(fieldBlockObj);
});
wrapper[0].divBlock.blocks = labelBlocks;
// console.log(wrapper);
// let json = JSON.stringify(labelBlocks, null, 2);
let json = JSON.stringify(wrapper, null, 2);
// console.log(json);
return json;
}
/**
* Prints JSON in interface
*
*/
function printJson() {
let list = refreshPreview();
let copyBtn = document.getElementById('copyBtn');
let isEmpty = list[0].length == 0;
let message = '';
if (isEmpty) {
copyBtn.style.display = 'none';
alert(
'Label format is empty! Please drag some items to the build area before trying again'
);
} else {
let json = generateJson(refreshPreview());
copyBtn.style.display = 'inline-block';
dummy.value = json;
}
}
/**
* Provides textarea where users can paste JSON format for validation
*/
function loadJson() {
let currBlocks = labelMid.querySelectorAll('.field-block');
let numBlocks = currBlocks.length;
// Clears lines & fields if already used
if (numBlocks > 1) {
for (i = 1; i < numBlocks; i++) {
removeLine(currBlocks[i]);
}
}
let firstBlock = currBlocks[0];
let currFields = firstBlock.querySelectorAll('.draggable');
currFields.forEach((currField) => {
currField.remove();
});
let sourceStr = dummy.value.replace(/'/g, '"');
sourceJson = false;
try {
sourceJson = JSON.parse(sourceStr);
} catch (error) {
console.log(error);
}
if (sourceJson) {
translateJson(sourceJson);
refreshLineState();
} else {
preview.innerText =
'Your label format is not translatable at this time. Please adjust your JSON definition and try again.';
}
}
/**
* Copies JSON output to user's clipboard
*/
function copyJson() {
dummy.select();
dummy.setSelectionRange(0, 99999); /* For mobile devices */
document.execCommand('copy');
/* Alert the copied text */
alert('Copied JSON to clipboard');
}
/**
* Toggles select/deselect clicked element
* @param {DOM Node} element
*/
function toggleSelect(element) {
element.classList.toggle('selected');
let isSelected = element.classList.contains('selected');
return isSelected;
}
/**
* Toggles formatting controls based on filter and state
* @param {String} filter Class of formatting control (field or field-block)
* @param {Boolean} bool
*/
function activateControls(filter, bool) {
let filtered = document.querySelectorAll(`[data-group=${filter}]`);
filtered.forEach((control) => {