-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSVGFM.js
2766 lines (2417 loc) · 101 KB
/
SVGFM.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 svgNS = 'http://www.w3.org/2000/svg'; // I'm lazy
const fePrimRef = '<filter-primitive-reference>';
/**
* @typedef {Object} Coordinates X and Y coordinates object.
* @param {Number} x Horizontal coordinate.
* @param {Number} y Vertical coordinate.
*/
/**
* Dirty little helper to create a new element with attributes in a single call.
* @param {string} tag Element node name to create.
* @param {object} attrs Attributes to assign to the created element.
* @param {'svg'|'html'} [ns] Optional. The namespace for the element, such as SVG. Uses HTML by default.
* @returns {HTMLElement} New element.
*/
function el(tag, attrs, ns = 'html') {
if (tag === 'a' && !attrs.hasOwnProperty('href')) {
throw 'Anchor element require a `href` attribute!';
}
if (tag === 'img' && !attrs.hasOwnProperty('alt')) {
throw 'Image element require an `alt` attribute!';
}
if (ns === 'svg') {
const newEl = document.createElementNS(svgNS, tag);
for (let attr in attrs) {
newEl.setAttribute(attr, attrs[attr]);
}
return newEl;
}
return Object.assign(document.createElement(tag), attrs);
}
/**
* Removes all children inside an element.
* @param {HTMLElement} el Element to empty.
*/
function emptyEl(el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
}
/**
* Trigger a change on the target element.
* @param {HTMLElement} el Element from which to trigger the event.
*/
function triggerChange(el) {
const changeEvent = new Event('change', { bubbles: true });
el.dispatchEvent(changeEvent);
}
/**
* Injects indentation according to an element's nested level (mutates the DOM element, does not return a value).
* @param {HTMLElement} dom HTML Element with nested children to adjust.
* @param {Number} [level] Optional. The tabulation offset to use. Defaults to `0`.
*/
function autoTab(dom, level = 0) {
Array.from(dom.children).forEach((c) => {
dom.insertBefore(document.createTextNode(`\n${'\t'.repeat(level)}`), c);
// Adds correct spacing before multi-line attribute
const cAttrs = Array.from(c.attributes);
if (cAttrs.some((attr) => attr.nodeValue.includes('\n'))) {
const lineBreakAttr = cAttrs.find((attr) => attr.nodeValue.includes('\n'));
const lineBreakAttrName = lineBreakAttr.nodeName;
const lineBreakAttrString = ` ${lineBreakAttrName}="`;
const lineBreakMatch = c.outerHTML.split('\n').find((line) => line.includes(lineBreakAttrString));
const lineBreakIndex = lineBreakMatch.indexOf(lineBreakAttrString);
const lineBreakOffset = lineBreakAttrString.length + lineBreakIndex;
const offsetAttrValue = lineBreakAttr.nodeValue.split('\n').join(`\n${'\t'.repeat(level)}${' '.repeat(lineBreakOffset)}`);
lineBreakAttr.nodeValue = offsetAttrValue;
}
// If it's the last element
if (!c.nextSibling) {
dom.insertBefore(document.createTextNode(`\n${'\t'.repeat(Math.max(0, level - 1))}`), c.nextSibling);
}
autoTab(c, level + 1);
});
}
/**
* Generates a unique ID with options to prefix a namespace to it and/or make it a short UUID.
* @param {string} [prefix] Optional. Namespace for the ID.
* @param {boolean} [short] Optional. Whether the UUID returned should be short (might cause collisions in rare cases). Defaults to `false`.
* @returns {string} Generated unique ID.
*/
function generateId(prefix = '', short = false) {
const parts = [];
prefix = prefix.trim();
if (prefix) {
parts.push(prefix);
}
let uuid = crypto.randomUUID();
if (short) {
uuid = uuid.split('-')[0]; // Grab only the first set of characters
}
parts.push(uuid);
return parts.join('-');
}
/**
* Clamps a number, with a CSS function signature. If `min > max`, their values are swapped.
* @param {Number} min Lowest accepted number.
* @param {Number} num Number to clamp.
* @param {Number} max Greatest accepted number.
* @returns {Number} Clamped number.
*/
function MathClamp(min, num, max) {
if (min > max) {
[max, min] = [min, max]; // Swap the numbers if the min is greater than the max
}
return Math.min(Math.max(num, min), max);
}
/**
* Rounds a number to a provided step value
* @param {Number} num Number to "stepify".
* @param {Number} [step] Optional. The step size to use, converted into its absolute value. Defaults to `10`.
* @returns {Number} Stepped number.
*/
function MathStep(num, step = 10) {
step = Math.abs(step);
return Math.round(num / step) * step;
}
/**
* Deduplicates array items.
* @param {array} array The array to deduplicate.
* @returns {array} Deduplicated array.
*/
function ArrayUnique(array) {
return Array.from(new Set(array));
}
/**
* Finds the position of an element, optionally in relation to a reference element.
* @param {HTMLElement} element Element for which to get the position coordinates.
* @param {HTMLElement} [reference] Optional. Which element to consider the outer boundary. Default to the document body element.
* @returns {Coordinates} How far the element's top-left edge is from the reference's top-left.
*/
function getElementPosition(element, reference = document.body) {
let x = 0;
let y = 0;
if (element.offsetParent && reference.contains(element)) {
while (element) {
x += element.offsetLeft;
y += element.offsetTop;
element = element.offsetParent;
if (element === reference) {
break;
}
}
}
return { x, y };
}
/**
* Retrieve the offset between a clicked element's click-point and top-left corner.
* @param {Event} e Event instance.
* @param {HTMLElement} target Target element to compare.
* @returns {Coordinates} How far the click was from the target element's top-left edge.
*/
function getClickOffset(e, target) {
const eventX = e.clientX;
const eventY = e.clientY;
// If this is from an element that scrolls, compensate for its scroll position
const scrollX = target.closest('.app-sidebar-inner')?.scrollLeft || 0;
const scrollY = target.closest('.app-sidebar-inner')?.scrollTop || 0;
const targetX = target.offsetLeft - scrollX;
const targetY = target.offsetTop - scrollY;
const returnedOffsets = {
x: eventX - targetX,
y: eventY - targetY,
};
return returnedOffsets;
}
/**
* Retrieves the data from all the named fields of a form.
* @param {HTMLFormElement} form The form from which to retrieve the data.
* @returns {object} The collected form data.
*/
function getFormData(form) {
if (!form || !(form instanceof HTMLFormElement)) {
throw 'The provided form is not a form element.';
}
return Object.fromEntries(new FormData(form).entries());
}
/**
* Converts a string to title case.
* @param {string} str String to convert.
* @returns {string} Titlecased string.
*/
function toTitleCase(str) {
return str
.split(' ')
.map((part) => ''.concat(part.substr(0, 1).toUpperCase(), part.slice(1)))
.join(' ');
}
/**
* Converts a named color to its hexadecimal value, or returns the map for named and hex values.
* @param {string} [name] Optional. The color name to convert. If omitted, the full list of colors is returned.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/named-color MDN's Named colors list}
* @returns {string|false|object} The color if there was a match, `false` if not, or the color list if `name` was omitted.
*/
function namedColorToHex(name = null) {
const list = {
black: '#000000',
silver: '#c0c0c0',
gray: '#808080',
white: '#ffffff',
maroon: '#800000',
red: '#ff0000',
purple: '#800080',
fuchsia: '#ff00ff',
green: '#008000',
lime: '#00ff00',
olive: '#808000',
yellow: '#ffff00',
navy: '#000080',
blue: '#0000ff',
teal: '#008080',
aqua: '#00ffff',
aliceblue: '#f0f8ff',
antiquewhite: '#faebd7',
aquamarine: '#7fffd4',
azure: '#f0ffff',
beige: '#f5f5dc',
bisque: '#ffe4c4',
blanchedalmond: '#ffebcd',
blueviolet: '#8a2be2',
brown: '#a52a2a',
burlywood: '#deb887',
cadetblue: '#5f9ea0',
chartreuse: '#7fff00',
chocolate: '#d2691e',
coral: '#ff7f50',
cornflowerblue: '#6495ed',
cornsilk: '#fff8dc',
crimson: '#dc143c',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgoldenrod: '#b8860b',
darkgray: '#a9a9a9',
darkgreen: '#006400',
darkgrey: '#a9a9a9',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkseagreen: '#8fbc8f',
darkslateblue: '#483d8b',
darkslategray: '#2f4f4f',
darkslategrey: '#2f4f4f',
darkturquoise: '#00ced1',
darkviolet: '#9400d3',
deeppink: '#ff1493',
deepskyblue: '#00bfff',
dimgray: '#696969',
dimgrey: '#696969',
dodgerblue: '#1e90ff',
firebrick: '#b22222',
floralwhite: '#fffaf0',
forestgreen: '#228b22',
gainsboro: '#dcdcdc',
ghostwhite: '#f8f8ff',
gold: '#ffd700',
goldenrod: '#daa520',
greenyellow: '#adff2f',
grey: '#808080',
honeydew: '#f0fff0',
hotpink: '#ff69b4',
indianred: '#cd5c5c',
indigo: '#4b0082',
ivory: '#fffff0',
khaki: '#f0e68c',
lavender: '#e6e6fa',
lavenderblush: '#fff0f5',
lawngreen: '#7cfc00',
lemonchiffon: '#fffacd',
lightblue: '#add8e6',
lightcoral: '#f08080',
lightcyan: '#e0ffff',
lightgoldenrodyellow: '#fafad2',
lightgray: '#d3d3d3',
lightgreen: '#90ee90',
lightgrey: '#d3d3d3',
lightpink: '#ffb6c1',
lightsalmon: '#ffa07a',
lightseagreen: '#20b2aa',
lightskyblue: '#87cefa',
lightslategray: '#778899',
lightslategrey: '#778899',
lightsteelblue: '#b0c4de',
lightyellow: '#ffffe0',
limegreen: '#32cd32',
linen: '#faf0e6',
magenta: '#ff00ff',
mediumaquamarine: '#66cdaa',
mediumblue: '#0000cd',
mediumorchid: '#ba55d3',
mediumpurple: '#9370db',
mediumseagreen: '#3cb371',
mediumslateblue: '#7b68ee',
mediumspringgreen: '#00fa9a',
mediumturquoise: '#48d1cc',
mediumvioletred: '#c71585',
midnightblue: '#191970',
mintcream: '#f5fffa',
mistyrose: '#ffe4e1',
moccasin: '#ffe4b5',
navajowhite: '#ffdead',
oldlace: '#fdf5e6',
olivedrab: '#6b8e23',
orange: '#ffa500',
orangered: '#ff4500',
orchid: '#da70d6',
palegoldenrod: '#eee8aa',
palegreen: '#98fb98',
paleturquoise: '#afeeee',
palevioletred: '#db7093',
papayawhip: '#ffefd5',
peachpuff: '#ffdab9',
peru: '#cd853f',
pink: '#ffc0cb',
plum: '#dda0dd',
powderblue: '#b0e0e6',
rebeccapurple: '#663399',
rosybrown: '#bc8f8f',
royalblue: '#4169e1',
saddlebrown: '#8b4513',
salmon: '#fa8072',
sandybrown: '#f4a460',
seagreen: '#2e8b57',
seashell: '#fff5ee',
sienna: '#a0522d',
skyblue: '#87ceeb',
slateblue: '#6a5acd',
slategray: '#708090',
slategrey: '#708090',
snow: '#fffafa',
springgreen: '#00ff7f',
steelblue: '#4682b4',
tan: '#d2b48c',
thistle: '#d8bfd8',
tomato: '#ff6347',
turquoise: '#40e0d0',
violet: '#ee82ee',
wheat: '#f5deb3',
whitesmoke: '#f5f5f5',
yellowgreen: '#9acd32',
transparent: 'transparent',
inherit: 'inherit',
none: 'none',
currentcolor: 'currentColor',
};
if (!name) {
return list;
}
return list[name.toLowerCase()] || false; // Lowercase ensures cases like `currentColor` can still be mapped correctly
}
/**
* Get the actual type of a value.
* @param {*} val The value to check.
* @returns {string} Lowecase name of the value's true type.
*/
function trueType(val) {
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}
class SVGFM {
/** Scaffhold the app
* @param {HTMLElement|string} container The app container, passed as a CSS selector, or a HTML element reference.
* @param {object} config External configuration data used to set up the app.
*/
constructor(container, config) {
this.app = typeof container === 'string' ? document.querySelector(container) : container; // Store a reference to the app container
this.dropTarget = false; // This will be used in drag-and-drop operations to keep track of where the dragged element was dropped
this.inputSelectorList = `input:where([type="text"], [type="url"], [type="number"], [type="color"], [type="radio"]), textarea, select, output`;
this.localStorageKeys = {
graph: 'SVGFM_Graph',
dragAndDrop: 'SVGFM_DragAndDropData',
};
this.arrowKeyDelta = 10; // Arrow keys move nodes by this many pixels
// Set up the markup
this.app.innerHTML = ''; // Let's empty the app "canvas" first to remove the loading message
this.sidebar = el('div', { className: 'app-sidebar' });
this.sidebarInner = el('div', { className: 'app-sidebar-inner', id: 'app-sidebar-inner' });
this.graph = el('div', { className: 'app-graph' });
this.graphLines = el('svg', { class: 'app-graph-lines', xmlns: svgNS, 'aria-hidden': 'true' }, 'svg');
this.graph.append(this.graphLines);
this.preview = el('div', { className: 'app-preview' });
this.previewCode = el('textarea', { readOnly: true, className: 'app-preview-code', id: 'app-preview-code' });
this.previewCodeLabel = el('label', { innerText: 'Code Output', className: 'visually-hidden', htmlFor: 'app-preview-code' });
this.previewConfig = el('div', { className: 'app-preview-config' });
this.app.append(this.sidebar, this.graph, this.preview);
this.sidebar.append(this.sidebarInner);
this.preview.append(this.previewCodeLabel, this.previewCode, this.previewConfig);
// Set up a active node store (accessed by key as the node reference)
this.activeNodes = {};
// Collect all nodes
const attrs = config.attrMap.primitives.map((p) => Object.assign({ category: 'primitives' }, p));
const maths = config.mathsMap.map((p) => Object.assign({ category: 'maths' }, p));
const inputs = config.inputsMap.map((p) => Object.assign({ category: 'inputs' }, p));
this.nodes = [].concat(attrs, maths, inputs);
// List categories
this.categories = ArrayUnique(this.nodes.map((node) => node.category)).map((cat) => {
const catLabel = (config.categoryLabels ? config.categoryLabels[cat] : null) || toTitleCase(cat);
return { ref: cat, label: catLabel };
});
// Register unit control options
this.unitOptions = config.attrMap.unitOptions; // TODO Move this into each primitive object instead, akin to how `conditions` exists within each attribute directly (repetitive, but cleaner)
// Register all event listeners
this.app.addEventListener('dragstart', this);
this.app.addEventListener('dragend', this);
this.app.addEventListener('dragenter', this);
this.app.addEventListener('dragover', this);
this.app.addEventListener('dragleave', this);
this.app.addEventListener('drag', this);
this.app.addEventListener('drop', this);
this.app.addEventListener('focusin', this); // Bubbles! `focus` does not
this.app.addEventListener('submit', this);
this.app.addEventListener('change', this);
this.app.addEventListener('click', this);
this.app.addEventListener('dblclick', this);
this.app.addEventListener('keydown', this);
this.app.addEventListener('keyup', this);
document.addEventListener('keydown', this);
document.addEventListener('keyup', this);
document.addEventListener('visibilitychange', this);
window.addEventListener('focusout', this);
// Initialize the app
this.init();
return this; // Not good practice buuuut super useful for testing so *shrug emoji*
}
/** Sets up the app's initial state */
init() {
this.app.classList.add('defined');
// Add a datalist for named colors to be referenced for color inputs
this.colorList = el('datalist', { id: 'named-color-list' });
for (let color in namedColorToHex()) {
this.colorList.append(el('option', { value: color }));
}
this.app.append(this.colorList);
const uiSvgIcons = `<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" aria-hidden="true">
<defs>
<symbol id="icon-question" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="arcs"><circle cx="12" cy="12" r="10"></circle><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path><line x1="12" y1="17" x2="12.01" y2="17"></line></g></symbol>
<symbol id="icon-eye" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="arcs"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></g></symbol>
<symbol id="icon-close" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="arcs"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></g></symbol></symbol>
</defs>
</svg>`;
let temp = el('div', { innerHTML: uiSvgIcons });
this.app.append(temp.firstChild);
temp.remove();
temp = undefined;
// Populate the sidebar
const sideBarToolbar = el('div', { className: 'app-sidebar-toolbar' });
const sideBarTitle = el('h2', { innerText: 'Nodes' });
const sideBarToggle = el('button', { className: 'button-reset button-toggle app-sidebar-toggle', ariaControls: this.sidebarInner.id, ariaExpanded: true });
sideBarToggle.innerHTML = `
<span class="visually-hidden">Toggle Sidebar</span>
<svg aria-hidden="true" data-toolbar-toggle="open" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="arcs"><path d="M13 17l5-5-5-5M6 17l5-5-5-5"/></svg>
<svg aria-hidden="true" data-toolbar-toggle="close" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="arcs"><path d="M11 17l-5-5 5-5M18 17l-5-5 5-5"/></svg>
`;
sideBarToolbar.append(sideBarTitle, sideBarToggle);
this.sidebarInner.append(sideBarToolbar);
this.sidebarDetails = [];
this.categories.forEach((cat) => {
const detailsEl = el('details', { id: cat.ref, open: true });
const summaryEl = el('summary', { className: 'h3', innerText: cat.label });
const listEl = el('ul', { className: 'app-nodes-list' });
this.sidebarInner.append(detailsEl);
this.sidebarDetails.push(detailsEl);
detailsEl.append(summaryEl, listEl);
const availableNodes = this.nodes.filter((node) => node.category === cat.ref);
availableNodes.forEach((node) => {
const nodeNested = !!node.nested;
const listItem = el('li', { className: 'app-nodes-item' });
const nodeTile = this.addTemplateTile();
listItem.hidden = nodeNested; // Hide the item if it's only used as a nested item
nodeTile.setAttribute('data-node-ref', node.ref);
nodeTile.setAttribute('aria-roledescription', `Draggable template node for ${node.ref}`);
Object.assign(this.elData(nodeTile), { nodeRef: node.ref, nodeCategory: cat.ref, nested: node.nested });
// Append the node template to the list
nodeTile.append(el('span', { className: 'app-tile__label', innerText: node.label }));
listItem.append(nodeTile);
listEl.append(listItem);
});
});
// Add the preview resizer
this.preview.append(el('div', { className: 'app-preview-resizer', draggable: true }));
// Populate the preview form
this.previewForm = el('form', { ariaLabel: 'Preview', className: 'app-preview-form' });
const previewFormLegend = el('legend', { innerText: 'Source Graphic:', className: 'font-bold' });
const previewFormLabelImage = el('label', { htmlFor: 'filter-preview-image', className: 'app-preview-form-option' });
const previewFormLabelText = el('label', { htmlFor: 'filter-preview-text', className: 'app-preview-form-option' });
const previewFormLabelCustom = el('label', { htmlFor: 'filter-preview-custom', className: 'app-preview-form-option' });
const previewFormOptionImage = el('input', { type: 'radio', name: 'filter-preview-type', value: 'image', id: 'filter-preview-image', checked: true });
const previewFormOptionText = el('input', { type: 'radio', name: 'filter-preview-type', value: 'text', id: 'filter-preview-text' });
const previewFormOptionCustom = el('input', { type: 'radio', name: 'filter-preview-type', value: 'custom', id: 'filter-preview-custom' });
const previewFormSpanImage = el('span', { innerText: 'Image' });
const previewFormSpanText = el('span', { innerText: 'Text' });
const previewFormInputCustom = el('input', { type: 'text', placeholder: 'e.g. <svg ...', name: 'filter-preview-custom-value', ariaLabel: 'Custom SVG Code' });
previewFormLabelImage.append(previewFormOptionImage, previewFormSpanImage);
previewFormLabelText.append(previewFormOptionText, previewFormSpanText);
previewFormLabelCustom.append(previewFormOptionCustom, document.createTextNode('Code'), previewFormInputCustom);
this.previewForm.append(previewFormLegend, previewFormLabelImage, previewFormLabelText, previewFormLabelCustom);
this.previewWindow = el('div', { className: 'app-preview-window preview-box' });
this.previewConfig.append(this.previewForm, this.previewWindow);
this.sidebarInner.setAttribute('data-dropzone', 'delete'); // Dropping into sidebar will delete a node
this.graph.setAttribute('data-dropzone', 'nodes'); // Dropping into the graph will add a new node or move an existing one
// If there is a stored config, restore it
if (this.storedGraph) {
this.populateGraph(this.storedGraph); // TODO
}
// Render the UI in the initial state
this.render();
}
/**
* Interface to attach and retrieve data on elements.
* @param {HTMLElement} element Element from which to retrieve data.
* @returns {object} The element's data object. */
elData(element) {
// If the element does not have its initial data store, create it
if (!element.hasOwnProperty('_svgfm')) {
element._svgfm = {};
}
return element._svgfm;
}
/**
* Retrieves the current value of the localStorage item with the provided key.
* @returns {*}
*/
getFromLocalStorage(key) {
const value = window.localStorage.getItem(this.localStorageKeys[key]);
return value ? JSON.parse(value) : null;
}
/**
* Assigns the value of the localStorage item with the provided key. Clears the item if the value is undefined.
* @param {*} value The value of the localStorage item.
*/
updateLocalStorage(key, value) {
if (value === undefined) {
window.localStorage.removeItem(this.localStorageKeys[key]);
} else {
window.localStorage.setItem(this.localStorageKeys[key], JSON.stringify(value));
}
}
// We only need this because some browsers misbehave, yeah baby yeah!
get dataTransfer() {
return this.getFromLocalStorage('dragAndDrop');
}
set dataTransfer(value) {
this.updateLocalStorage('dragAndDrop', value);
}
get storedGraph() {
return this.getFromLocalStorage('graph');
}
set storedGraph(value) {
this.updateLocalStorage('graph', value);
}
/** Create a standard Template Tile which can be dragged from the Sidebar into the Graph */
addTemplateTile() {
const templateTile = el('div', { className: 'app-tile app-template-tile', draggable: true, tabIndex: '0', role: 'button' });
templateTile.setAttribute('data-element', 'template');
this.elData(templateTile).tileType = 'template';
return templateTile;
}
/** Creates a new instance of a Node Tile */
addNodeTile(config) {
const nodeConfig = this.nodes.find((n) => n.ref === config.ref);
const nodeData = Object.assign({ uniqueRef: generateId('node') }, nodeConfig);
// Create the node and store its instance
const node = el('div', { className: 'app-tile app-node-tile', id: nodeData.uniqueRef, tabIndex: '0', draggable: true });
nodeData.element = node;
// Store the node config and instance
Object.assign(this.elData(node), {
node: node, // Self-reference so we can do this.elData(x).node on any element
tileType: 'node',
nodeRef: config.ref,
uniqueRef: nodeData.uniqueRef,
config: nodeConfig,
});
// Create a form to control the attributes in the tile
const nodeForm = this.buildTileForm(nodeData);
// Store the form instance
this.elData(node).form = nodeForm;
node.setAttribute('data-element', 'node');
nodeForm.setAttribute('data-element', 'form');
// Position the node
this.repositionNodeTile(node, config.x, config.y);
return node;
}
/** Create a form for each type of input */
buildTileForm(nodeData) {
const nodeType = nodeData.ref;
const form = el('form', { className: 'app-node-tile__form' });
const title = el('p', { className: 'app-node-tile__title app-tile__label', id: `formtitle-${nodeData.uniqueRef}` });
title.append(el('span', { innerText: nodeData.label }));
form.setAttribute('aria-labelledby', title.id);
nodeData.element.append(form);
// Initialize controls and conditions
Object.assign(this.elData(form), {
node: nodeData.element,
controls: {},
conditions: {},
});
// For SVG primitives, add a help link to the MDN docs
if (nodeData.category === 'primitives') {
title.append(
el('a', {
href: `https://developer.mozilla.org/en-US/docs/Web/SVG/Element/${nodeData.ref}`,
ariaLabel: `${nodeData.ref} element on MDN`,
title: `${nodeData.ref} element on MDN`,
innerHTML: '<svg width="12" height="12" aria-hidden="true"><use href="#icon-question" /></svg>',
target: '_blank',
className: 'help-link',
})
);
}
const hiddenType = el('input', { type: 'hidden', name: '_node-type', value: nodeType });
const hiddenRef = el('input', { type: 'hidden', name: '_node-ref', value: nodeData.uniqueRef });
form.append(title, hiddenType, hiddenRef);
// Keep track of the controls present in the form
let controls = {};
let attrsFlat = [];
let conditionalControls = {};
// Loop over every attribute in the node
for (let attr in nodeData.attrs) {
const controlWrap = el('div', { className: 'app-node-tile__control-wrap' });
const controlField = el('div', { className: 'app-node-tile__control' });
const attrConfig = nodeData.attrs[attr];
const attrData = attrConfig.attrType;
const generatedControl = this.buildAttrControl({ attrs: nodeData.attrs, nodeType, attr, attrConfig, form, controlWrap, controlField, isSubControl: false });
const conditions = attrConfig.conditions || null;
const controlGuid = generatedControl.controlGuid;
const appendableElement = generatedControl.appendableElement;
const controlInput = generatedControl.controlInput;
const globalType = generatedControl.globalType;
const valueType = generatedControl.valueType;
const subControls = generatedControl.subControls;
const subControlsLocation = generatedControl.subControlsLocation;
Object.assign(this.elData(controlWrap), { controlWrap, controlField, controlInput, subControls, conditions });
Object.assign(this.elData(controlField), { controlWrap, controlField, controlInput, subControls, conditions });
let labelText = attrConfig.label || attrData.label || attr;
const labelWrap = el('div', { className: 'app-node-tile__control-label-wrap' });
const label = el('label', {
innerHTML: `<span class="app-node-tile__control-label-error">Invalid ${globalType}:</span> <span>${labelText}</span>`,
className: 'app-node-tile__control-label',
htmlFor: controlGuid,
title: attr, // Not very useful so I'm okay with using the title attribute here
});
labelWrap.append(label);
controlWrap.append(labelWrap);
controlWrap.setAttribute('data-element', 'control-wrap');
controlField.setAttribute('data-element', 'control');
labelWrap.setAttribute('data-element', 'label-wrap');
label.setAttribute('data-element', 'label');
if (globalType === 'color' && !attrConfig.computed) {
const customControl = el('div', { className: 'custom-input' });
const colorInputWrap = el('div', { className: 'custom-input-colorwrap' });
const colorInput = el('input', { type: 'color', value: controlInput.value, id: generateId() });
this.elData(controlInput).bindingOutput = true;
this.elData(controlInput).binding = colorInput;
this.elData(colorInput).binding = controlInput;
this.elData(colorInput).bindingOutput = false;
this.elData(customControl).customControl = {
inputType: 'color',
customWrap: colorInputWrap,
textInput: controlInput,
colorInput: colorInput,
};
customControl.style.setProperty('--c', controlInput.value);
colorInput.setAttribute('data-input-binding', controlInput.id);
colorInput.setAttribute('data-color-input-pair-item', 'picker');
controlInput.setAttribute('data-input-binding', colorInput.id);
controlInput.setAttribute('data-color-input-pair-item', 'text');
customControl.setAttribute('data-custom-input-type', 'color');
controlField.append(customControl);
colorInputWrap.append(colorInput);
customControl.append(colorInputWrap, controlInput);
} else if (appendableElement) {
controlField.append(appendableElement);
} else {
controlField.append(controlInput);
}
this.elData(controlField).input = controlInput;
// Attach the conditions attribute
if (conditions) {
controlWrap.setAttribute('data-control-conditions', JSON.stringify(conditions));
conditionalControls[attr] = conditions;
}
controlInput.setAttribute('data-control-type', valueType);
controlInput.setAttribute('data-port-type', globalType);
controlInput.classList.add('app-node-tile__controlinput');
// If data can flow from port to port
if (attrConfig.flow || attrData.flow) {
this.addFlowPorts(controlField, controlInput.id, attrConfig.flow || attrData.flow, {
valueType: valueType,
type: globalType,
relation: attrConfig.attrType.flowRelation,
});
}
// If there is unit options for the provided node type
if (this.unitOptions.hasOwnProperty(attr)) {
const attrUnitOptions = this.unitOptions[attr];
if (attrUnitOptions.primitives.includes(nodeType)) {
this.createUnitController({ controlField: controlField, label: labelWrap, input: controlInput, form: form }, attrUnitOptions);
}
}
// Add a preview button if there is a Result attribute
if (attr === 'result') {
const nodePreviewTrigger = el('button', {
type: 'button',
className: 'app-node-tile__preview-button',
draggable: true,
innerHTML: `<svg width="12" height="12" aria-hidden="true">
<use href="#icon-eye" class="app-node-tile__preview-icon app-node-tile__preview-icon--when-hidden" />
<use href="#icon-close" class="app-node-tile__preview-icon app-node-tile__preview-icon--when-shown" />
</svg>
<span class="visually-hidden">Preview filter at this step</span>`,
});
labelWrap.append(nodePreviewTrigger);
}
controlWrap.setAttribute('data-control-attr', attr);
controlWrap.append(controlField);
// Add a link to the attribute reference
if (!attrConfig.isCustomAttribute && nodeData.category === 'primitives') {
labelWrap.append(
el('a', {
href: `https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/${attr}`,
ariaLabel: `${attr} attribute on MDN`,
title: `${attr} attribute on MDN`,
innerHTML: '<svg width="12" height="12" aria-hidden="true"><use href="#icon-question" /></svg>',
target: '_blank',
className: 'help-link',
})
);
}
// Inject sub-controls
if (subControls) {
if (subControlsLocation[0] === 'outer') {
if (subControlsLocation[1] === 'before') {
controlWrap.insertBefore(subControls, controlWrap.firstChild);
} else {
controlWrap.append(subControls);
}
} else {
if (subControlsLocation[1] === 'before') {
controlField.insertBefore(subControls, controlField.firstChild);
} else {
controlField.append(subControls);
}
}
}
form.append(controlWrap);
controls[attr] = controlField;
attrsFlat.push(attr);
}
this.activeNodes[nodeData.uniqueRef] = {
nodeElement: nodeData.element,
nodeData,
controls,
conditions: conditionalControls,
};
// Adjust dynamic matrix fields
const dynamicMatrixControls = form.querySelectorAll('[data-matrix-size-from]');
for (let matrixControl of dynamicMatrixControls) {
const matrixSizeFromAttr = matrixControl.getAttribute('data-matrix-size-from');
const matrixSizeFrom = controls[matrixSizeFromAttr].querySelector(`[name="${matrixSizeFromAttr}"]`);
const matrixSize = this.getCompoundValue(matrixSizeFrom.id, form);
const linkedGridId = matrixControl.getAttribute('data-matrix-from');
const linkedGrid = form.querySelector(`#${linkedGridId}`);
const defaultMatrix = this.getMatrixValue(linkedGrid);
// In case one control affects more than one field, ensure the IDs are listed instead of replaced
if (matrixSizeFrom.hasAttribute('data-matrix-size-control')) {
const currGridList = matrixSizeFrom.getAttribute('data-matrix-size-control').split(',');
matrixSizeFrom.setAttribute('data-matrix-size-control', ArrayUnique([linkedGridId].concat(currGridList)).join(','));
} else {
matrixSizeFrom.setAttribute('data-matrix-size-control', linkedGridId);
}
const updatedMatrix = this.buildMatrix(matrixSize, defaultMatrix, linkedGrid);
triggerChange(updatedMatrix.querySelector('[data-matrix-input-cell]'));
}
// Adjust conditional fields
const formConditionalControls = Array.from(form.querySelectorAll('[data-control-conditions]'));
for (let conditionalControl of formConditionalControls) {
const conditionParsed = JSON.parse(conditionalControl.getAttribute('data-control-conditions'));
const nodeControlState = this.getControlConditionalState(conditionalControl, conditionParsed);
this.toggleConditionalControl(conditionalControl, nodeControlState);
}
return form;
}
buildAttrControl({ attrs, nodeType, attr, attrConfig, form, controlWrap, controlField, isSubControl }) {
const node = this.elData(form).node;
const attrData = attrConfig.attrType;
const attrDefault = attrConfig.default;
const attrComputed = attrConfig.computed || false;
const attrConditions = attrConfig.conditions || null;
const controlGuid = generateId('control');
const valueType = Array.isArray(attrData.value) ? '<custom:select>' : attrData.value;
let controlInput;
let globalType;
let subControls;
let subControlsLocation;
let defaultValue;
let autoWrap = false;
switch (valueType) {
case '<string>':
case '<iri>':
case fePrimRef: {
globalType = 'string';
if (attrComputed) {
controlInput = el('output', { innerText: '' });
} else {
controlInput = el('input', { type: 'text', name: attr, draggable: true });
if (valueType === fePrimRef) {
const uniqueRefName = generateId(nodeType, true);
controlInput.setAttribute('data-primitive-ref', uniqueRefName);
controlInput.value = uniqueRefName;
this.elData(controlInput).primitiveRef = true; // Boolean because the value will be pulled from the input, no need to make it more complicated
// controlInput.pattern = `[A-Za-z0-9]+`;
controlInput.required = true;
} else if (valueType === '<iri>') {
// TODO Make that dang URL pattern work on a type=text field
// ! type=url works only for absolute URLs, not ./relative or #anchor links
// controlInput.pattern = `^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?`;
controlInput.required = true;
}
}
break;
}
case '<primitive-reference-list>': {
globalType = 'string';
controlInput = el('input', { type: 'text', name: attr, draggable: true, readOnly: true });
subControls = el('div', { className: 'control-options' });
subControlsLocation = ['outer', 'after'];
const allowedSubNodes = this.nodes.filter((node) => node.nested && node.nested.includes(nodeType));
allowedSubNodes.forEach((subNode) => {
const subNodeEl = el('button', { type: 'button', innerText: `+${subNode.label}` });
subNodeEl.setAttribute('data-create-from-template', subNode.ref);
subControls.append(subNodeEl);
});
break;
}
case '<number>':
case '<number-positive>':
case '<integer>':
case '<alpha-value>': {
globalType = 'number';
if (attrComputed) {
controlInput = el('output', { innerText: '0' });
} else {
controlInput = el('input', { type: 'number', name: attr, draggable: true, autocomplete: 'off' });
// Adjust number input attributes
if (valueType === '<integer>') {
controlInput.setAttribute('step', '1');
} else if (valueType === '<number-positive>') {
controlInput.setAttribute('min', '0');
} else if (valueType === '<alpha-value>') {
controlInput.setAttribute('min', '0');
controlInput.setAttribute('max', '1');
controlInput.setAttribute('step', '0.1');
}
// Assign hardcoded attributes
if (attrConfig.min || attrConfig.min === 0) {
controlInput.setAttribute('min', attrConfig.min);
}
if (attrConfig.max || attrConfig.max === 0) {
controlInput.setAttribute('max', attrConfig.max);
}
}
break;
}
case '<color>': {
globalType = 'color';
if (attrComputed) {
controlInput = el('output', { innerText: '#ff0000' });
} else {
controlInput = el('input', { type: 'text', name: attr, draggable: true });
controlInput.setAttribute('list', this.colorList.id);
if (!attrData.placeholder) {
attrData.placeholder = '#d00dad'; // :)
}
}
break;
}
case '<identity-matrix>': {
globalType = 'string';
controlInput = el('textarea', { name: attr, draggable: true, hidden: true });
subControls = this.buildMatrix(attrConfig.size || 0, attrConfig.default || null); // Create an empty matrix by default, it'll be generated after all fields have been added, or use the provided value
subControlsLocation = ['inner', 'after'];
controlInput.setAttribute('data-matrix-from', subControls.id);
subControls.setAttribute('data-matrix-to', controlGuid);
if (attrConfig.size) {
subControls.setAttribute('data-matrix-fixed-size', attrConfig.size);
}
if (attrConfig.sizeFrom) {
controlInput.setAttribute('data-matrix-size-from', attrConfig.sizeFrom);
}
break;
}
case '<number-list>': {
globalType = 'string';