forked from minj/foxtrick
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdom.js
1471 lines (1292 loc) · 37.4 KB
/
dom.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
/**
* dom.js
* Utilities for HTML and DOM
*/
'use strict';
/* eslint-disable */
if (!this.Foxtrick)
// @ts-ignore
var Foxtrick = {};
/* eslint-enable */
/**
* Node type map.
*
* Allegedly not available in some browsers
* @type {Object}
*/
Foxtrick.NodeTypes = {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12,
};
// eslint-disable-next-line valid-jsdoc
/**
* Create an element in SVG namespace. Root element is typically 'svg'.
* @template {keyof SVGElementTagNameMap} K
* @param {document} doc
* @param {K} type
* @return {SVGElementTagNameMap[K]}
*/
Foxtrick.createSVG = function(doc, type) {
return doc.createElementNS('http://www.w3.org/2000/svg', type);
};
/**
* Create an element with Foxtrick feature highlight enabled.
* This and other similar functions must be used on the outer container
* of DOM created and/or modified by Foxtrick.
* Returns the element.
* @template {keyof HTMLElementTagNameMap} K
* @param {document} doc
* @param {any} module // TODO module type
* @param {K} type
* @return {HTMLElementTagNameMap[K]}
*/
// eslint-disable-next-line consistent-this
Foxtrick.createFeaturedElement = function(doc, module, type) {
if (module && module.MODULE_NAME && module.MODULE_CATEGORY) {
let node = doc.createElement(type);
node.className = 'ft-dummy';
if (Foxtrick.Prefs.getBool('featureHighlight')) {
let cat = Foxtrick.L10n.getString('tab.' + module.MODULE_CATEGORY);
node.title = module.MODULE_NAME + ' (' + cat + '): ' +
Foxtrick.Prefs.getModuleDescription(module.MODULE_NAME);
}
return node;
}
let msg = `Incorrect usage of createFeaturedElement. typeof module = '${typeof module}'`;
Foxtrick.log(new Error(msg));
return null;
};
/**
* Insert a new row in a table with Foxtrick feature highlight.
* Returns the row.
* @param {HTMLTableElement} table
* @param {any} module // TODO module type
* @param {number} index
* @return {HTMLTableRowElement}
*/
// eslint-disable-next-line consistent-this
Foxtrick.insertFeaturedRow = function(table, module, index) {
var row = table.insertRow(index);
row.className = 'ft-dummy';
if (Foxtrick.Prefs.getBool('featureHighlight')) {
var cat = Foxtrick.L10n.getString('tab.' + module.MODULE_CATEGORY);
row.title = module.MODULE_NAME + ' (' + cat + '): ' +
Foxtrick.Prefs.getModuleDescription(module.MODULE_NAME);
}
return row;
};
/**
* Insert a new cell in a row with Foxtrick feature highlight.
* Returns the cell.
* @param {HTMLTableRowElement} row
* @param {any} module // TODO module type
* @param {number} index
* @return {HTMLTableCellElement}
*/
// eslint-disable-next-line consistent-this
Foxtrick.insertFeaturedCell = function(row, module, index) {
let cell = row.insertCell(index);
cell.className = 'ft-dummy';
if (Foxtrick.Prefs.getBool('featureHighlight')) {
let cat = Foxtrick.L10n.getString('tab.' + module.MODULE_CATEGORY);
cell.title = module.MODULE_NAME + ' (' + cat + '): ' +
Foxtrick.Prefs.getModuleDescription(module.MODULE_NAME);
}
return cell;
};
/**
* Enable Foxtrick feature highlight on an existing element
* @template {HTMLElement} E
* @param {E} node
* @param {any} module // TODO module type
* @return {E}
*/
// eslint-disable-next-line consistent-this
Foxtrick.makeFeaturedElement = function(node, module) {
Foxtrick.addClass(node, 'ft-dummy');
if (Foxtrick.Prefs.getBool('featureHighlight')) {
let cat = Foxtrick.L10n.getString('tab.' + module.MODULE_CATEGORY);
node.title = module.MODULE_NAME + ' (' + cat + '): ' +
Foxtrick.Prefs.getModuleDescription(module.MODULE_NAME) +
(node.title ? ' / ' + node.title : '');
}
return node;
};
/**
* Test whether an attribute of an element has the given value
* or contains it in a space-delimited list
* @param {Element} el
* @param {string} attribute
* @param {string} value
* @return {boolean}
*/
Foxtrick.hasAttributeValue = function(el, attribute, value) {
let val = String(value).trim();
let reg = new RegExp(`(\\s|^)${Foxtrick.strToRe(val)}(\\s|$)`);
return el && typeof el.getAttribute === 'function' && el.getAttribute(attribute) &&
reg.test(el.getAttribute(attribute));
};
/**
* Add a value to the space-delimited list of element's attribute
* @param {Element} el
* @param {string} attribute
* @param {string} value
*/
Foxtrick.addAttributeValue = function(el, attribute, value) {
let val = String(value).trim();
if (Foxtrick.hasAttributeValue(el, attribute, val))
return;
let curr = el.getAttribute(attribute);
if (curr === null || curr === '')
el.setAttribute(attribute, val);
else
el.setAttribute(attribute, `${curr} ${val}`.trim());
};
/**
* Remove a value from the space-delimited list of element's attribute
* @param {Element} el
* @param {string} attribute
* @param {string} value
*/
Foxtrick.removeAttributeValue = function(el, attribute, value) {
let val = String(value).trim();
let curr = el.getAttribute(attribute);
if (curr === null || curr === '')
return;
let reg = new RegExp(`(\\s|^)${Foxtrick.strToRe(val)}(\\s|$)`, 'g');
el.setAttribute(attribute, curr.replace(reg, ' ').trim());
};
/**
* Set element attributes/properties based on attribute map.
*
* Also supports style/dataset and on* listeners.
*
* @param {HTMLElement} el
* @param {any} attributes // TODO constrain
*/
Foxtrick.setAttributes = function(el, attributes) {
const ELEMENT_PROPERTIES = [
'textContent',
'className',
];
const ATTRIBUTE_MAP = Object.assign(Object.create(null), {
ariaLabel: 'aria-label',
});
for (let [attr, val] of Object.entries(attributes)) {
if ((attr == 'dataset' || attr == 'style') && typeof val == 'object') {
for (let [item, subVal] of Object.entries(val)) {
// @ts-ignore
el[attr][item] = subVal;
}
}
else if (attr.startsWith('on') && typeof val == 'function') {
let type = /** @type {keyof HTMLElementEventMap} */ (attr.slice(2).toLowerCase());
if (type == 'click') {
Foxtrick.onClick(el, val);
}
// @ts-ignore
else if (type == 'mutate') {
Foxtrick.onChange(el, val);
}
else {
let eventType = /** @type {keyof HTMLElementEventMap} */ (type);
Foxtrick.listen(el, eventType, val);
}
}
else if (Foxtrick.has(ELEMENT_PROPERTIES, attr)) {
// @ts-ignore
el[attr] = val;
}
else if (attr in ATTRIBUTE_MAP) {
el.setAttribute(ATTRIBUTE_MAP[attr], val);
}
else {
el.setAttribute(attr, val);
}
}
};
/**
* Test whether an element has a class
* @param {Element} el
* @param {string} cls
* @return {boolean}
*/
Foxtrick.hasClass = function(el, cls) {
if (!el || !el.classList)
return false;
return el.classList.contains(cls);
};
/**
* Add a class or a space-delimited list of classes to an alement
* @param {Element} el
* @param {string} cls
*/
Foxtrick.addClass = function(el, cls) {
if (!el || !el.classList)
return;
let classes = cls.trim().split(' ');
for (let c in classes)
el.classList.add(classes[c]);
};
/**
* Remove a class from an element
* @param {Element} el
* @param {string} cls
*/
Foxtrick.removeClass = function(el, cls) {
if (el && el.classList)
el.classList.remove(cls);
};
/**
* Toggle a class of an element
* @param {Element} el
* @param {string} cls
*/
Foxtrick.toggleClass = function(el, cls) {
if (el && el.classList)
el.classList.toggle(cls);
};
/**
* Test whether document contains an element with a given ID
* @param {document} doc
* @param {string} id
* @return {boolean}
*/
Foxtrick.hasElement = function(doc, id) {
return !!doc.getElementById(id);
};
/**
* Test whether an element is within another element
* @param {Node} descendant
* @param {Node} ancestor
* @return {boolean}
*/
Foxtrick.isDescendantOf = function(descendant, ancestor) {
return ancestor.contains(descendant);
};
/**
* Get the given element's index among its siblings
* @param {Node} element
* @return {number}
*/
Foxtrick.getChildIndex = function(element) {
let count = 0;
let el = element;
while (el.previousSibling) {
++count;
el = el.previousSibling;
}
return count;
};
/**
* Because types /sigh
* @template {Element|DocumentFragment} E
* @param {E} el
* @param {boolean} [deep]
* @return {E}
*/
Foxtrick.cloneElement = function(el, deep) {
return /** @type {E} */ (el.cloneNode(deep));
};
/**
* Insert adjacent content.
* ! Target must be Element !
*
* @param {InsertPosition} where
* @param {Node|string} newNode
* @param {Element} target
*/
Foxtrick.insertAdjacent = function(where, newNode, target) {
let doc = target.ownerDocument;
let win = doc.defaultView;
// @ts-ignore
let isElement = newNode instanceof win.Element;
// @ts-ignore
let isNode = newNode instanceof win.Node;
if (isElement) {
let element = /** @type {Element} */ (newNode);
target.insertAdjacentElement(where, element);
}
else {
let text = isNode ? /** @type {Node} */ (newNode).textContent : String(newNode);
target.insertAdjacentText(where, text);
}
};
/**
* Insert newNode before sibling
* @param {Node|string} newNode
* @param {Node} sibling
*/
Foxtrick.insertBefore = function(newNode, sibling) {
let doc = sibling.ownerDocument;
let win = doc.defaultView;
let parent = sibling.parentNode;
// @ts-ignore
if (sibling instanceof win.Element) {
let el = /** @type {Element} */ (sibling);
Foxtrick.insertAdjacent('beforebegin', newNode, el);
}
// @ts-ignore
else if (newNode instanceof win.Node) {
let node = /** @type {Node} */ (newNode);
parent.insertBefore(node, sibling);
}
else {
let text = doc.createTextNode(String(newNode));
parent.insertBefore(text, sibling);
}
};
/**
* Insert newNode after sibling
* @param {Node|string} newNode
* @param {Node} sibling
*/
Foxtrick.insertAfter = function(newNode, sibling) {
let doc = sibling.ownerDocument;
let win = doc.defaultView;
let parent = sibling.parentNode;
// @ts-ignore
if (sibling instanceof win.Element) {
let el = /** @type {Element} */ (sibling);
Foxtrick.insertAdjacent('afterend', newNode, el);
}
// @ts-ignore
else if (newNode instanceof win.Node) {
let node = /** @type {Node} */ (newNode);
parent.insertBefore(node, sibling.nextSibling);
}
else {
let text = doc.createTextNode(String(newNode));
parent.insertBefore(text, sibling.nextSibling);
}
};
/**
* Insert newNode as first child of parent
* @param {Node|string} newNode
* @param {Node} parent
*/
Foxtrick.prependChild = function(newNode, parent) {
let doc = parent.ownerDocument;
let win = doc.defaultView;
// @ts-ignore
if (parent instanceof win.Element) {
let el = /** @type {Element} */ (parent);
Foxtrick.insertAdjacent('afterbegin', newNode, el);
}
// @ts-ignore
else if (newNode instanceof win.Node) {
let node = /** @type {Node} */ (newNode);
parent.insertBefore(node, parent.firstChild);
}
else {
let text = doc.createTextNode(String(newNode));
parent.insertBefore(text, parent.firstChild);
}
};
/**
* Insert newNode as last child of parent
* @param {Node|string} newNode
* @param {Node} parent
*/
Foxtrick.appendChild = function(newNode, parent) {
let doc = parent.ownerDocument;
let win = doc.defaultView;
// @ts-ignore
if (parent instanceof win.Element) {
let el = /** @type {Element} */ (parent);
Foxtrick.insertAdjacent('beforeend', newNode, el);
}
// @ts-ignore
else if (newNode instanceof win.Node) {
let node = /** @type {Node} */ (newNode);
parent.appendChild(node);
}
else {
let text = doc.createTextNode(String(newNode));
parent.appendChild(text);
}
};
/**
* Append an array of elements to a container
* @param {Node} parent
* @param {(Node|string)[]} children
*/
Foxtrick.appendChildren = function(parent, children) {
Foxtrick.forEach(function(child) {
Foxtrick.appendChild(child, parent);
}, children);
};
/**
* Append child(ren) to parent.
*
* child may be a Node, string or an array of such.
*
* @param {Node} parent
* @param {Node|string|(Node|string)[]} child
*/
Foxtrick.append = function(parent, child) {
let doc = parent.ownerDocument;
let win = doc.defaultView;
if (Foxtrick.isArrayLike(child)) {
let children = /** @type {(Node|string)[]} */ (child);
Foxtrick.forEach(function(c) {
Foxtrick.append(parent, c);
}, children);
}
// @ts-ignore
else if (child instanceof win.Node) {
let node = /** @type {Node} */ (child);
parent.appendChild(node);
}
else if (child != null) {
// skip null/undefined
let str = String(child);
parent.appendChild(doc.createTextNode(str));
}
};
/**
* Adds a click event listener to an element.
*
* Sets tabindex=0 and role=button if these attributes have no value.
*
* ! This does more harm than good on 'delegated' listeners, listen() should be used instead.
*
* The callback is executed with global change listeners stopped.
*
* @template {Element} T
*
* @param {T} el
* @param {Listener<T,MouseEvent>} listener
* @param {boolean} [useCapture]
* @return {function():void} remove wrapped listener
*/
Foxtrick.onClick = function(el, listener, useCapture) {
Foxtrick.clickTarget(el);
return Foxtrick.listen(el, 'click', listener, useCapture);
};
/**
* Sets tabindex=0 and role=button if these attributes have no value.
*
* Uses wrappers for elements with important accessibility semantics.
*
* ! This does more harm than good on 'delegated' listeners
*
* @param {Element} el
*/
Foxtrick.clickTarget = function(el) {
/**
* @param {Element} e
* @return {Element}
*/
const wrapContents = (e) => {
let span = e.ownerDocument.createElement('span');
Foxtrick.append(span, [...e.childNodes]);
return e.appendChild(span);
};
/**
* @param {Element} e
* @return {Element}
*/
const wrapElement = (e) => {
let span = e.ownerDocument.createElement('span');
e.parentElement.replaceChild(span, e);
span.appendChild(e);
return span;
};
/** @type {Partial<Record<keyof HTMLElementTagNameMap, function(Element):Element>>} */
const ROLES_CBS = {
h1: wrapContents,
h2: wrapContents,
h3: wrapContents,
h4: wrapContents,
h5: wrapContents,
h6: wrapContents,
td: wrapContents,
th: wrapContents,
img: wrapElement,
input: null,
};
/** @type {Element} */
let target = null;
let name = el.nodeName.toLowerCase();
if (name in ROLES_CBS) {
let tag = /** @type {keyof HTMLElementTagNameMap} */ (name);
let role = ROLES_CBS[tag];
if (typeof role == 'function')
target = role(el);
}
else {
target = el;
}
if (!target)
return;
if (!target.hasAttribute('tabindex'))
target.setAttribute('tabindex', '0');
if (!target.hasAttribute('role'))
target.setAttribute('role', 'button');
};
/**
* Add an event listener to an element.
*
* The callback is executed with global change listeners stopped.
*
* @template {EventTarget} T
* @template {keyof HTMLElementEventMap} E
*
* @param {T} el
* @param {E} evType event type
* @param {Listener<T,HTMLEvent<E>>} listener
* @param {boolean} [useCapture]
* @return {function():void} remove wrapped listener
*/
Foxtrick.listen = function(el, evType, listener, useCapture) {
/**
* @this {T}
* @param {HTMLEvent<E>} ev
*/
let listen = function listen(ev) {
let target = /** @type {Element|Document} */ (ev.target);
let doc = target instanceof Document ? target : target.ownerDocument;
Foxtrick.stopObserver(doc);
/** @type {boolean|Promise<any>|void} */
let ret;
try {
ret = listener.call(this, ev);
}
catch (e) {
Foxtrick.log(e);
}
if (ret === false) {
ev.stopPropagation();
ev.preventDefault();
}
else if (ret instanceof Promise) {
Foxtrick.finally(ret, () => {
Foxtrick.log.flush(doc);
Foxtrick.startObserver(doc);
}).catch(Foxtrick.catch('async listen'));
}
else {
Foxtrick.log.flush(doc);
Foxtrick.startObserver(doc);
}
};
/*
README: since TS 3.5 union type checking became 'smarter' and errors here
since addEventListener API is contravariant (dumb) here,
it will not accept a callback requiring a more specific Event
we know better however, since we actually type-check the evType argument
*/
let cb = /** @type {EventListener} */ (listen);
el.addEventListener(evType, cb, useCapture);
return () => el.removeEventListener(evType, cb, useCapture);
};
/**
* Activate an element by adding a copy listener.
*
* copy maybe a string or a function that returns {mime, content}
* mime may specify additional mime type
* 'text/plain' is always used
*
* @param {Element} el
* @param {string|function():string} copy {string|function}
* @param {?string} [mime]
*/
Foxtrick.addCopying = function(el, copy, mime) {
Foxtrick.onClick(el, function() {
// eslint-disable-next-line no-invalid-this
let doc = this.ownerDocument;
Foxtrick.copy(doc, copy, mime);
});
};
/**
* Add a mutation observer to a node.
* Should not be used directly.
* Calls callback(mutations) on childList changes in the whole tree.
* Default behavior can be overridden by specifying observer options.
* Stops observing in case callback returns true.
* Returns the observer.
* @param {Node} node observer target
* @param {function(MutationRecord[]): boolean|void} shouldStop
* @param {MutationObserverInit} [options] observer options
* @return {MutationObserver}
*/
Foxtrick.observe = function(node, shouldStop, options) {
/** @type {MutationObserverInit} */
let opts = { childList: true, subtree: true };
Object.assign(opts, options);
/**
* @this {MutationObserver}
*/
let observe = function() {
this.takeRecords();
this.observe(node, opts);
};
let observer = new MutationObserver((mutations, observer) => {
observer.disconnect();
if (!shouldStop(mutations))
observe.call(observer);
});
// @ts-ignore
observer.reconnect = observe;
observe.call(observer);
return observer;
};
/**
* Execute callback(doc, node, observer) when node changes.
* Stops observing if callback returns true.
* Returns the observer.
* @template {Node} T
* @param {T} node
* @param {function(document, T): boolean|void} callback
* @param {MutationObserverInit} [obsOpts] observer options
* @return {MutationObserver}
*/
Foxtrick.onChange = function(node, callback, obsOpts) {
return Foxtrick.observe(node, function() {
let doc = node.ownerDocument;
try {
return callback(doc, node);
}
catch (e) {
Foxtrick.log('Error in callback for onChange', e);
return true;
}
}, obsOpts);
};
/**
* Get nodes whose children change.
* Stops observing if callback returns true.
* Returns the observer.
* @param {Node} node container
* @param {function(Node[]):boolean|void} callback
* @param {MutationObserverInit} [obsOpts] observer options
* @return {MutationObserver}
*/
Foxtrick.getChanges = function(node, callback, obsOpts) {
return Foxtrick.observe(node, function(records) {
let affectedNodes = records.map(r => r.target);
let uniques = Foxtrick.unique(affectedNodes);
try {
return callback(uniques);
}
catch (e) {
Foxtrick.log('Error in callback for getChanges', e);
return true;
}
}, obsOpts);
};
/**
* Add a box to the sidebar, either on the right or on the left.
* Returns the added box.
* @author Ryan Li, LA-MJ
* @param {document} doc
* @param {string} title the title of the box, will create one if inexists
* @param {Element} content HTML node of the content
* @param {number} prec precedence of the box, the smaller, the higher
* @param {boolean} [forceLeft] force the box to be displayed on the left
* @return {Element} box to be added to
*/
// eslint-disable-next-line complexity
Foxtrick.addBoxToSidebar = function(doc, title, content, prec, forceLeft) { // FIXME support angular
// class of the box to add
var boxClass = 'sidebarBox';
var sidebar = doc.getElementById('sidebar');
if (!sidebar || forceLeft) {
if ((sidebar = doc.querySelector('.subMenu')))
boxClass = 'subMenuBox';
else if ((sidebar = doc.querySelector('.subMenuConf')))
boxClass = 'subMenuBox';
}
if (!sidebar)
return null;
// destination box
var dest;
// existing sidebar boxes
var existings = sidebar.getElementsByClassName(boxClass);
for (let box of existings) {
let hdr = box.querySelector('h2').textContent;
if (hdr == title) {
// found destination box
dest = box;
break;
}
}
// create new box if old one doesn't exist
if (!dest) {
dest = doc.createElement('div');
dest.className = boxClass;
dest.setAttribute('x-precedence', String(prec));
// boxHead
let boxHead = doc.createElement('div');
boxHead.className = 'boxHead';
dest.appendChild(boxHead);
// boxHead - boxLeft
let headBoxLeft = doc.createElement('div');
headBoxLeft.className = 'boxLeft';
boxHead.appendChild(headBoxLeft);
// boxHead - boxLeft - h2
let h2 = doc.createElement('h2');
h2.textContent = title;
headBoxLeft.appendChild(h2);
// boxBody
let boxBody = doc.createElement('div');
boxBody.className = 'boxBody';
dest.appendChild(boxBody);
// append content to boxBody
boxBody.appendChild(content);
// boxFooter
let boxFooter = doc.createElement('div');
boxFooter.className = 'boxFooter';
dest.appendChild(boxFooter);
// boxFooter - boxLeft
let footBoxLeft = doc.createElement('div');
footBoxLeft.className = 'boxLeft';
boxFooter.appendChild(footBoxLeft);
// now we insert the newly created box
var inserted = false;
for (let [i, box] of [...existings].entries()) {
// precedence of current box, hattrick boxes are set to 0
let curPrec = parseInt(box.getAttribute('x-precedence'), 10) || 0;
if (curPrec <= prec)
continue;
if (i === 0 && curPrec === 0) {
// first to be added and placed before HT boxes. add it on top
// before possible updatepanel div (eg teampage challenge and mailto)
sidebar.insertBefore(dest, sidebar.firstChild);
}
else {
box.parentNode.insertBefore(dest, box);
}
inserted = true;
break;
}
if (!inserted)
sidebar.appendChild(dest);
}
// finally we add the content
dest.querySelector('.boxBody').appendChild(content);
return dest;
};
/**
* Get element position relative to reference.
* Returns the position as an object {top, left}.
* @param {HTMLElement} el
* @param {HTMLElement} ref
* @return {{top: number, left: number}} position
*/
Foxtrick.getElementPosition = function(el, ref) {
let top = 0, left = 0;
let e = el;
while (e && e !== ref) {
top += e.offsetTop;
left += e.offsetLeft;
e = /** @type {HTMLElement} */ (e.offsetParent);
}
return { top, left };
};
/**
* Convert a string into data URI text file
* @param {string} str
* @return {string}
*/
Foxtrick.getDataURIText = function(str) {
return 'data:text/plain;charset=utf-8,' + encodeURIComponent(str);
};
/**
* Add an image in an asynchronous way.
* TODO: promisify
* Used to be the only way to add images from FT package
* in some extension architectures.
* Continued to be used with forward compatibility in mind.
* Callback receives the created image.
* @param {document} doc
* @param {Node} parent
* @param {any} features a map of image attributes // TODO constrain
* @param {Node} [insertBefore] next sibling
* @param {function(HTMLImageElement):void} [callback]
*/
Foxtrick.addImage = function(doc, parent, features, insertBefore, callback) {
let img = doc.createElement('img');
Foxtrick.setAttributes(img, features);
if (insertBefore)
parent.insertBefore(img, insertBefore);
else
parent.appendChild(img);
callback && callback(img);
};
/**
* Add a specialty icon from a specialty number.
*
* options is a map of DOM attributes: {string: string}.
* NOTE: insertBefore and onError has special meaning.
*
* Returns Promise.<HTMLImageElement>
*
* @param {Node} parent
* @param {number} specNum {Integer}
* @param {any} [features] image attributes // TODO constrain
* @return {Promise<HTMLImageElement>}
*/
Foxtrick.addSpecialty = function(parent, specNum, features = {}) {
let doc = parent.ownerDocument;
let specialtyName = Foxtrick.L10n.getSpecialtyFromNumber(specNum);
let specialtyUrl = Foxtrick.getSpecialtyImagePathFromNumber(specNum);
/** @type {Node} */
let insertBefore = null;
if (Foxtrick.hasProp(features, 'insertBefore')) {
// @ts-ignore
insertBefore = features.insertBefore;
delete features.insertBefore;
}
let imgContainer = doc.createElement('span');
if (insertBefore)
parent.insertBefore(imgContainer, insertBefore);
else
parent.appendChild(imgContainer);
if (Foxtrick.Prefs.isModuleEnabled('SpecialtyInfo')) {
Foxtrick.addClass(imgContainer, 'ft-specInfo-parent');
imgContainer.dataset.specialty = specNum.toString();
specialtyName += '\n' + Foxtrick.L10n.getString('SpecialtyInfo.open');
features.tabindex = '0';
features.role = 'button';
}
let opts = Object.assign({
alt: specialtyName,
title: specialtyName,
src: specialtyUrl,
}, features);
return new Promise(function(resolve) {
Foxtrick.addImage(doc, imgContainer, opts, null, resolve);
});
};
/**
* Make table rows from a row definition array.
*
* Row definitions may be <TR>s or arrays of cell definitions.
* Cell definitions may be either cell attribute maps,
* or Nodes, Strings and arrays of such.
*
* An optional section param is a <TABLE>, <THEAD>, <TBODY> or <TFOOT>
* to add rows to. A new table is created by default.
*
* Returns the created table or section.
*
* @template {HTMLTableSectionElement} T
* @param {document} doc
* @param {(HTMLTableRowElement|(*|Node|string|(Node|string)[])[])[]} rows
* @param {?T} section
* @return {T|HTMLTableElement}
*/
Foxtrick.makeRows = function(doc, rows, section) {
let t = section || doc.createElement('table');