/
Commons.js
857 lines (736 loc) · 23.3 KB
/
Commons.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
/*
* ADOBE CONFIDENTIAL
*
* Copyright 2017 Adobe
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Adobe and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Adobe and its
* suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe.
*/
import Promise from 'promise-polyfill';
import ResizeObserver from 'resize-observer-polyfill/dist/ResizeObserver';
// Used for unique IDs
let nextID = 0;
// Remove namespace from global options
const cleanOption = (name) => {
name = name.replace('coral', '');
return name.charAt(0).toLowerCase() + name.slice(1);
};
// Threshold time in milliseconds that the setTimeout will wait for the transitionEnd event to be triggered.
const TRANSITION_DURATION_THRESHOLD = 100;
// Based on jQuery's :focusable selector
const FOCUSABLE_ELEMENTS = [
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'button:not([disabled])',
'a[href]',
'area[href]',
'summary',
'iframe',
'object',
'embed',
'audio[controls]',
'video[controls]',
'[contenteditable]'
];
// To support Coral.commons.ready and differentiate lightweight tags from defined elements
const CORAL_COMPONENTS = [
'coral-accordion',
'coral-accordion-item',
'coral-accordion-item-content',
'coral-accordion-item-label',
'coral-actionbar',
'coral-actionbar-container',
'coral-actionbar-item',
'coral-actionbar-primary',
'coral-actionbar-secondary',
'coral-alert',
'coral-alert-header',
'coral-alert-content',
'coral-alert-footer',
'a[is="coral-anchorbutton"]',
'coral-autocomplete',
'coral-autocomplete-item',
'coral-autocomplete-item',
'button[is="coral-button"]',
'coral-buttongroup',
'coral-calendar',
'coral-card',
'coral-card-banner',
'coral-card-banner-content',
'coral-card-banner-header',
'coral-card-context',
'coral-card-description',
'coral-card-property',
'coral-card-propertylist',
'coral-card-subtitle',
'coral-card-title',
'coral-charactercount',
'coral-checkbox',
'coral-clock',
'coral-colorinput',
'coral-colorinput-colorproperties',
'coral-colorinput-item',
'coral-colorinput-slider',
'coral-colorinput-swatch',
'coral-colorinput-swatches',
'coral-columnview',
'coral-columnview-column',
'coral-columnview-column-content',
'coral-columnview-item',
'coral-columnview-item-content',
'coral-columnview-item-thumbnail',
'coral-columnview-preview',
'coral-columnview-preview-content',
'coral-cyclebutton',
'coral-cyclebutton-action',
'coral-cyclebutton-item',
'coral-datepicker',
'coral-dialog',
'coral-dialog-header',
'coral-dialog-content',
'coral-dialog-footer',
'coral-drawer',
'coral-fileupload',
'coral-icon',
'coral-list',
'coral-selectlist',
'coral-buttonlist',
'coral-anchorlist',
'coral-list-item',
'coral-selectlist-item',
'coral-selectlist-group',
'a[is="coral-anchorlist-item"]',
'button[is="coral-buttonlist-item"]',
'coral-masonry',
'coral-masonry-item',
'coral-multifield',
'coral-multifield-item',
'coral-numberinput',
'coral-overlay',
'coral-panel',
'coral-panelstack',
'coral-playground',
'coral-popover',
'coral-progress',
'coral-quickactions',
'coral-radio',
'coral-search',
'coral-select',
'coral-select-item',
'coral-shell',
'coral-shell-header',
'coral-shell-help',
'a[is="coral-shell-homeanchor"]',
'a[is="coral-shell-help-item"]',
'a[is="coral-shell-workspace"]',
'a[is="coral-shell-solution"]',
'coral-shell-menu',
'coral-shell-menubar',
'coral-shell-menubar-item',
'coral-shell-organization',
'coral-shell-orgswitcher',
'coral-shell-solution',
'coral-shell-solutions',
'coral-shell-solutionswitcher',
'coral-shell-suborganization',
'coral-shell-user',
'coral-shell-workspaces',
'coral-slider',
'coral-slider-item',
'coral-rangedslider',
'coral-step',
'coral-steplist',
'coral-step-label',
'coral-switch',
'table[is="coral-table"]',
'thead[is="coral-table-head"]',
'tbody[is="coral-table-body"]',
'tfoot[is="coral-table-foot"]',
'tr[is="coral-table-row"]',
'td[is="coral-table-cell"]',
'th[is="coral-table-headercell"]',
'col[is="coral-table-column"]',
'coral-tab',
'coral-tab-label',
'coral-tablist',
'coral-tabview',
'coral-taglist',
'coral-tag',
'textarea[is="coral-textarea"]',
'input[is="coral-textfield"]',
'coral-tooltip',
'coral-tooltip-content',
'coral-tree',
'coral-tree-item',
'coral-wait',
'coral-wizardview'
];
/**
Converts CSS time to milliseconds. It supports both s and ms units. If the provided value has an unrecogenized unit,
zero will be returned.
@private
@param {String} time
The time string to convert to milliseconds.
@returns {Number} the time in milliseconds.
*/
function cssTimeToMilliseconds(time) {
const num = parseFloat(time, 10);
let unit = time.match(/m?s/);
if (unit) {
unit = unit[0];
}
if (unit === 's') {
return num * 1000;
}
else if (unit === 'ms') {
return num;
}
// unrecognized unit, so we return 0
return 0;
}
/**
@private
@param first
@param second
@return {Function}
*/
function returnFirst(first, second) {
// eslint-disable-next-line func-names
return function(...args) {
const ret = first.apply(this, args);
second.apply(this, args);
return ret;
};
}
/**
Check if the provided object is a function
@ignore
@param {*} object
The object to test
@returns {Boolean} Whether the provided object is a function.
*/
function isFunction(object) {
return typeof object === 'function';
}
/**
Utility belt.
*/
class Commons {
/** @ignore */
constructor() {
// Create a Map to link elements to observe to their resize event callbacks
this._resizeObserverMap = new Map();
this._resizeObserver = new ResizeObserver((entries) => {
for (let i = 0; i < entries.length; i++) {
const observedElement = entries[i].target;
const allCallbacks = this._resizeObserverMap.get(observedElement);
if (allCallbacks) {
for (let j = 0; j < allCallbacks.length; j++) {
allCallbacks[j].call(observedElement);
}
}
}
});
const focusableElements = FOCUSABLE_ELEMENTS.slice();
this._focusableElementsSelector = focusableElements.join(',');
focusableElements.push('[tabindex]:not([tabindex="-1"])');
this._tabbableElementsSelector = focusableElements.join(':not([tabindex="-1"]),');
this._coralSelector = CORAL_COMPONENTS.join(',');
const scripts = document.getElementsByTagName('script');
this._script = scripts[scripts.length - 1];
}
/**
Returns Coral global options retrieved on the <code><script></code> data attributes including:
- <code>[data-coral-icons]</code>: source folder of the SVG icons. If the icons are renamed, you'll have to load them
manually using {@link Icon.load}.
- <code>[data-coral-typekit]</code>: custom typekit id used to load the fonts.
@returns {Object}
The global options object.
*/
get options() {
const options = {};
const props = this._script.dataset;
for (const key in props) {
// Detect Coral namespaced options
if (key.indexOf('coral') === 0) {
options[cleanOption(key)] = props[key];
}
}
return options;
}
/**
Copy the properties from all provided objects into the first object.
@param {Object} dest
The object to copy properties to
@param {...Object} source
An object to copy properties from. Additional objects can be passed as subsequent arguments.
@returns {Object}
The destination object, <code>dest</code>
*/
extend(...args) {
const dest = args[0];
for (let i = 1, ni = args.length; i < ni; i++) {
const source = args[i];
for (const prop in source) {
dest[prop] = source[prop];
}
}
return dest;
}
/**
Copy the properties from the source object to the destination object, but calls the callback if the property is
already present on the destination object.
@param {Object} dest
The object to copy properties to
@param {...Object} source
An object to copy properties from. Additional objects can be passed as subsequent arguments.
@param {CommonsHandleCollision} [handleCollision]
Called if the property being copied is already present on the destination.
The return value will be used as the property value.
@returns {Object}
The destination object, <code>dest</code>
*/
augment(...args) {
const dest = args[0];
let handleCollision;
let argCount = args.length;
const lastArg = args[argCount - 1];
if (typeof lastArg === 'function') {
handleCollision = lastArg;
// Don't attempt to augment using the last argument
argCount--;
}
for (let i = 1; i < argCount; i++) {
const source = args[i];
for (const prop in source) {
if (typeof dest[prop] !== 'undefined') {
if (typeof handleCollision === 'function') {
// Call the handleCollision callback if the property is already present
const ret = handleCollision(dest[prop], source[prop], prop, dest, source);
if (typeof ret !== 'undefined') {
dest[prop] = ret;
}
}
// Otherwise, do nothing
}
else {
dest[prop] = source[prop];
}
}
}
return dest;
}
/**
Return a new object with the swapped keys and values of the provided object.
@param {Object} obj
The object to copy.
@returns {Object}
An object with its keys as the values and values as the keys of the source object.
*/
swapKeysAndValues(obj) {
const map = {};
for (const key in obj) {
map[obj[key]] = key;
}
return map;
}
/**
Execute the provided callback on the next animation frame.
@param {Function} onNextFrame
The callback to execute.
*/
nextFrame(onNextFrame) {
return window.requestAnimationFrame(() => {
if (typeof onNextFrame === 'function') {
onNextFrame();
}
});
}
/**
Execute the provided callback once a CSS transition has ended. This method listens for the next transitionEnd event
on the given DOM element. In case the provided element does not have a transition defined, the callback will be
called in the next macrotask to allow a normal application execution flow. It cannot be used to listen continuously
on transitionEnd events.
@param {HTMLElement} element
The DOM element that is affected by the CSS transition.
@param {CommonsTransitionEndCallback} onTransitionEndCallback
The callback to execute.
*/
transitionEnd(element, onTransitionEndCallback) {
let propertyName;
let hasTransitionEnded = false;
let transitionEndEventName = null;
const transitions = {
transition: 'transitionend',
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
MSTransition: 'msTransitionEnd'
};
let transitionEndTimeout = null;
const onTransitionEnd = (event) => {
const transitionStoppedByTimeout = typeof event === 'undefined';
if (!hasTransitionEnded) {
hasTransitionEnded = true;
clearTimeout(transitionEndTimeout);
// Remove event listener (if any was used by the current browser)
element.removeEventListener(transitionEndEventName, onTransitionEnd);
// Call callback with specified element
onTransitionEndCallback({
target: element,
cssTransitionSupported: true,
transitionStoppedByTimeout: transitionStoppedByTimeout
});
}
};
// Find transitionEnd event name used by browser
for (propertyName in transitions) {
if (element.style[propertyName] !== undefined) {
transitionEndEventName = transitions[propertyName];
break;
}
}
if (transitionEndEventName !== null) {
let timeoutDelay = 0;
// Gets the animation time (in milliseconds) using the computed style
const transitionDuration = cssTimeToMilliseconds(window.getComputedStyle(element).transitionDuration);
// We only setup the event listener if there is a valid transition
if (transitionDuration !== 0) {
// Register on transitionEnd event
element.addEventListener(transitionEndEventName, onTransitionEnd);
// As a fallback we use the transitionDuration plus a threshold. This can happen in IE10/11 where
// transitionEnd events are sometimes skipped
timeoutDelay = transitionDuration + TRANSITION_DURATION_THRESHOLD;
}
// Fallback in case the event does not trigger (IE10/11) or if the element does not have a valid transition
transitionEndTimeout = window.setTimeout(onTransitionEnd, timeoutDelay);
}
}
/**
Checks if Coral components and all nested Coral components are defined as Custom Elements.
@param {HTMLElement} element
The element that should be watched.
@param {CommonsReadyCallback} onDefined
The callback to call when all components are ready.
@see https://developer.mozilla.org/en-US/docs/Web/Web_Components/Custom_Elements
*/
ready(element, onDefined) {
let root = element;
if (typeof element === 'function') {
onDefined = element;
root = document.body;
}
if (!root) {
root = document.body;
}
if (!(root instanceof HTMLElement)) {
// commons.ready should not be blocking by default
onDefined(root);
return;
}
// @todo use ':not(:defined)' once supported ?
const elements = root.querySelectorAll(this._coralSelector);
// Holds promises that resolve when the elements is defined
const promises = [];
// Don't forget to check root
if (root !== document.body && !root._componentReady && root.matches(this._coralSelector)) {
const name = (root.getAttribute('is') || root.tagName).toLowerCase();
promises.push(window.customElements.whenDefined(name));
}
// Check all descending elements
for (let i = 0; i < elements.length; i++) {
const el = elements[i];
if (!el._componentReady) {
const name = (el.getAttribute('is') || el.tagName).toLowerCase();
promises.push(window.customElements.whenDefined(name));
}
}
// Call callback once all defined
if (promises.length) {
Promise.all(promises)
.then(() => {
onDefined(element instanceof HTMLElement && element || window);
})
.catch((err) => {
console.error(err);
});
}
else {
// Call callback by default if all defined already
onDefined(element instanceof HTMLElement && element || window);
}
}
/**
Assign an object given a nested path
@param {Object} root
The root object on which the path should be traversed.
@param {String} path
The path at which the object should be assignment.
@param {String} obj
The object to assign at path.
@throws Will throw an error if the path is not present on the object.
*/
setSubProperty(root, path, obj) {
const nsParts = path.split('.');
let curObj = root;
if (nsParts.length === 1) {
// Assign immediately
curObj[path] = obj;
return;
}
// Make sure we can assign at the requested location
while (nsParts.length > 1) {
const part = nsParts.shift();
if (curObj[part]) {
curObj = curObj[part];
}
else {
throw new Error(`Coral.commons.setSubProperty: could not set ${path}, part ${part} not found`);
}
}
// Do the actual assignment
curObj[nsParts.shift()] = obj;
}
/**
Get the value of the property at the given nested path.
@param {Object} root
The root object on which the path should be traversed.
@param {String} path
The path of the sub-property to return.
@returns {*}
The value of the provided property.
@throws Will throw an error if the path is not present on the object.
*/
getSubProperty(root, path) {
const nsParts = path.split('.');
let curObj = root;
if (nsParts.length === 1) {
// Return property immediately
return curObj[path];
}
// Make sure we can assign at the requested location
while (nsParts.length) {
const part = nsParts.shift();
// The property might be undefined, and that's OK if it's the last part
if (nsParts.length === 0 || typeof curObj[part] !== 'undefined') {
curObj = curObj[part];
}
else {
throw new Error(`Coral.commons.getSubProperty: could not get ${path}, part ${part} not found`);
}
}
return curObj;
}
/**
Apply a mixin to the given object.
@param {Object} target
The object to apply the mixin to.
@param {Object|Function} mixin
The mixin to apply.
@param {Object} options
An object to pass to functional mixins.
*/
_applyMixin(target, mixin, options) {
const mixinType = typeof mixin;
if (mixinType === 'function') {
mixin(target, options);
}
else if (mixinType === 'object' && mixin !== null) {
this.extend(target, mixin);
}
else {
throw new Error(`Coral.commons.mixin: Cannot mix in ${mixinType} to ${target.toString()}`);
}
}
/**
Mix a set of mixins to a target object.
@private
@param {Object} target
The target prototype or instance on which to apply mixins.
@param {Object|CoralMixin|Array<Object|CoralMixin>} mixins
A mixin or set of mixins to apply.
@param {Object} options
An object that will be passed to functional mixins as the second argument (options).
*/
mixin(target, mixins, options) {
if (Array.isArray(mixins)) {
for (let i = 0; i < mixins.length; i++) {
this._applyMixin(target, mixins[i], options);
}
}
else {
this._applyMixin(target, mixins, options);
}
}
/**
Get a unique ID.
@returns {String} unique identifier.
*/
getUID() {
return `coral-id-${nextID++}`;
}
/**
Call all of the provided functions, in order, returning the return value of the specified function.
@param {...Function} func
A function to call
@param {Number} [nth=0]
A zero-based index indicating the noth argument to return the value of.
If the nth argument is not a function, <code>null</code> will be returned.
@returns {Function} The aggregate function.
*/
callAll(...args) {
let nth = args[args.length - 1];
if (typeof nth !== 'number') {
nth = 0;
}
// Get the function whose value we should return
let funcToReturn = args[nth];
// Only use arguments that are functions
const functions = Array.prototype.filter.call(args, isFunction);
if (functions.length === 2 && nth === 0) {
// Most common usecase: two valid functions passed
return returnFirst(functions[0], functions[1]);
}
else if (functions.length === 1) {
// Common usecase: one valid function passed
return functions[0];
}
else if (functions.length === 0) {
return () => {
// Fail case: no valid functions passed
};
}
if (typeof funcToReturn !== 'function') {
// If the argument at the provided index wasn't a function, just return the value of the first valid function
funcToReturn = functions[0];
}
// eslint-disable-next-line func-names
return function() {
let finalRet;
let ret;
let func;
// Skip first arg
for (let i = 0; i < functions.length; i++) {
func = functions[i];
ret = func.apply(this, args);
// Store return value of desired function
if (func === funcToReturn) {
finalRet = ret;
}
}
return finalRet;
};
}
/**
Adds a resize listener to the given element.
@param {HTMLElement} element
The element to add the resize event to.
@param {Function} onResize
The resize callback.
*/
// eslint-disable-next-line func-names
addResizeListener(element, onResize) {
// Map callback to element
if (!this._resizeObserverMap.has(element)) {
this._resizeObserverMap.set(element, []);
}
this._resizeObserverMap.get(element).push(onResize);
// Observe element resize events
this._resizeObserver.observe(element);
}
/**
Removes a resize listener from the given element.
@param {HTMLElement} element
The element to remove the resize event from.
@param {Function} onResize
The resize callback.
*/
// eslint-disable-next-line func-names
removeResizeListener(element, onResize) {
// Stop observing element resize events
this._resizeObserver.unobserve(element);
this._resizeObserver.disconnect(element);
// Remove event from map
const onResizeEvents = this._resizeObserverMap.get(element);
const index = onResizeEvents.indexOf(onResize);
if (index !== -1) {
onResizeEvents.splice(index, 1);
}
}
/**
Caution: the selector doesn't verify if elements are visible.
@type {String}
@readonly
@see https://www.w3.org/TR/html5/editing.html#focus-management
*/
get FOCUSABLE_ELEMENT_SELECTOR() {
return this._focusableElementsSelector;
}
/**
Caution: the selector doesn't verify if elements are visible.
@type {String}
@readonly
@see https://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute
*/
get TABBABLE_ELEMENT_SELECTOR() {
return this._tabbableElementsSelector;
}
}
/**
Called when a property already exists on the destination object.
@typedef {function} CommonsHandleCollision
@param {*} oldValue
The value currently present on the destination object.
@param {*} newValue
The value on the destination object.
@param {*} prop
The property that collided.
@param {*} dest
The destination object.
@param {*} source
The source object.
@returns {*} The value to use. If <code>undefined</code>, the old value will be used.
*/
/**
Execute the callback once a CSS transition has ended.
@typedef {function} CommonsTransitionEndCallback
@param event
The event passed to the callback.
@param {HTMLElement} event.target
The DOM element that was affected by the CSS transition.
@param {Boolean} event.cssTransitionSupported
Whether CSS transitions are supported by the browser.
@param {Boolean} event.transitionStoppedByTimeout
Whether the CSS transition has been ended by a timeout (should only happen as a fallback).
*/
/**
Execute the callback once a component and sub-components are ready. See {@link Commons.ready}.
@typedef {function} CommonsReadyCallback
@param {HTMLElement} element
The element that is ready.
*/
/**
A functional mixin.
@typedef {Object} CoralMixin
@private
@param {Object} target
The target prototype or instance to apply the mixin to.
@param {Object} options
Options for this mixin.
@param {Coral~PropertyDescriptor.properties} options.properties
The properties object as passed to <code>Coral.register</code>. This can be modified in place.
*/
/**
A utility belt.
@type {Commons}
*/
const commons = new Commons();
export default commons;