-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathspatial-navigation-polyfill.js
1750 lines (1560 loc) · 70.1 KB
/
spatial-navigation-polyfill.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
/* Spatial Navigation Polyfill
*
* It follows W3C official specification
* https://drafts.csswg.org/css-nav-1/
*
* Copyright (c) 2018-2019 LG Electronics Inc.
* https://github.com/WICG/spatial-navigation/polyfill
*
* Licensed under the MIT license (MIT)
*/
(function () {
// The polyfill must not be executed, if it's already enabled via browser engine or browser extensions.
if ('navigate' in window) {
return;
}
const ARROW_KEY_CODE = {37: 'left', 38: 'up', 39: 'right', 40: 'down'};
const TAB_KEY_CODE = 9;
let mapOfBoundRect = null;
let startingPoint = null; // Saves spatial navigation starting point
let savedSearchOrigin = {element: null, rect: null}; // Saves previous search origin
let searchOriginRect = null; // Rect of current search origin
/**
* Initiate the spatial navigation features of the polyfill.
* @function initiateSpatialNavigation
*/
function initiateSpatialNavigation() {
/*
* Bind the standards APIs to be exposed to the window object for authors
*/
window.navigate = navigate;
window.Element.prototype.spatialNavigationSearch = spatialNavigationSearch;
window.Element.prototype.focusableAreas = focusableAreas;
window.Element.prototype.getSpatialNavigationContainer = getSpatialNavigationContainer;
/*
* CSS.registerProperty() from the Properties and Values API
* Reference: https://drafts.css-houdini.org/css-properties-values-api/#the-registerproperty-function
*/
if (window.CSS && CSS.registerProperty) {
if (window.getComputedStyle(document.documentElement).getPropertyValue('--spatial-navigation-contain') === '') {
CSS.registerProperty({
name: '--spatial-navigation-contain',
syntax: 'auto | contain',
inherits: false,
initialValue: 'auto'
});
}
if (window.getComputedStyle(document.documentElement).getPropertyValue('--spatial-navigation-action') === '') {
CSS.registerProperty({
name: '--spatial-navigation-action',
syntax: 'auto | focus | scroll',
inherits: false,
initialValue: 'auto'
});
}
if (window.getComputedStyle(document.documentElement).getPropertyValue('--spatial-navigation-function') === '') {
CSS.registerProperty({
name: '--spatial-navigation-function',
syntax: 'normal | grid',
inherits: false,
initialValue: 'normal'
});
}
}
}
/**
* Add event handlers for the spatial navigation behavior.
* This function defines which input methods trigger the spatial navigation behavior.
* @function spatialNavigationHandler
*/
function spatialNavigationHandler() {
/*
* keydown EventListener :
* If arrow key pressed, get the next focusing element and send it to focusing controller
*/
window.addEventListener('keydown', (e) => {
const currentKeyMode = (parent && parent.__spatialNavigation__.keyMode) || window.__spatialNavigation__.keyMode;
const eventTarget = document.activeElement;
const dir = ARROW_KEY_CODE[e.keyCode];
if (e.keyCode === TAB_KEY_CODE) {
startingPoint = null;
}
if (!currentKeyMode ||
(currentKeyMode === 'NONE') ||
((currentKeyMode === 'SHIFTARROW') && !e.shiftKey) ||
((currentKeyMode === 'ARROW') && e.shiftKey) ||
(e.ctrlKey || e.metaKey || e.altKey))
return;
if (!e.defaultPrevented) {
let focusNavigableArrowKey = {left: true, up: true, right: true, down: true};
// Edge case (text input, area) : Don't move focus, just navigate cursor in text area
if ((eventTarget.nodeName === 'INPUT') || eventTarget.nodeName === 'TEXTAREA') {
focusNavigableArrowKey = handlingEditableElement(e);
}
if (focusNavigableArrowKey[dir]) {
e.preventDefault();
mapOfBoundRect = new Map();
navigate(dir);
mapOfBoundRect = null;
startingPoint = null;
}
}
});
/*
* mouseup EventListener :
* If the mouse click a point in the page, the point will be the starting point.
* NOTE: Let UA set the spatial navigation starting point based on click
*/
document.addEventListener('mouseup', (e) => {
startingPoint = {x: e.clientX, y: e.clientY};
});
/*
* focusin EventListener :
* When the element get the focus, save it and its DOMRect for resetting the search origin
* if it disappears.
*/
window.addEventListener('focusin', (e) => {
if (e.target !== window) {
savedSearchOrigin.element = e.target;
savedSearchOrigin.rect = e.target.getBoundingClientRect();
}
});
}
/**
* Enable the author to trigger spatial navigation programmatically, as if the user had done so manually.
* @see {@link https://drafts.csswg.org/css-nav-1/#dom-window-navigate}
* @function navigate
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
*/
function navigate(dir) {
// spatial navigation steps
// 1
const searchOrigin = findSearchOrigin();
let eventTarget = searchOrigin;
let elementFromPosition = null;
// 2 Optional step, UA defined starting point
if (startingPoint) {
// if there is a starting point, set eventTarget as the element from position for getting the spatnav container
elementFromPosition = document.elementFromPoint(startingPoint.x, startingPoint.y);
// Use starting point if the starting point isn't inside the focusable element (but not container)
// * Starting point is meaningfull when:
// 1) starting point is inside the spatnav container
// 2) starting point is inside the non-focusable element
if (elementFromPosition === null) {
elementFromPosition = document.body;
}
if (isFocusable(elementFromPosition) && !isContainer(elementFromPosition)) {
startingPoint = null;
} else if (isContainer(elementFromPosition)) {
eventTarget = elementFromPosition;
} else {
eventTarget = elementFromPosition.getSpatialNavigationContainer();
}
}
// 4
if (eventTarget === document || eventTarget === document.documentElement) {
eventTarget = document.body || document.documentElement;
}
// 5
// At this point, spatialNavigationSearch can be applied.
// If startingPoint is either a scroll container or the document,
// find the best candidate within startingPoint
let container = null;
if ((isContainer(eventTarget) || eventTarget.nodeName === 'BODY') && !(eventTarget.nodeName === 'INPUT')) {
if (eventTarget.nodeName === 'IFRAME') {
eventTarget = eventTarget.contentDocument.documentElement;
}
container = eventTarget;
let bestInsideCandidate = null;
// 5-2
if ((document.activeElement === searchOrigin) ||
(document.activeElement === document.body) && (searchOrigin === document.documentElement)) {
if (getCSSSpatNavAction(eventTarget) === 'scroll') {
if (scrollingController(eventTarget, dir)) return;
} else if (getCSSSpatNavAction(eventTarget) === 'focus') {
bestInsideCandidate = eventTarget.spatialNavigationSearch(dir, {container: eventTarget, candidates: getSpatialNavigationCandidates(eventTarget, {mode: 'all'})});
if (focusingController(bestInsideCandidate, dir)) return;
} else if (getCSSSpatNavAction(eventTarget) === 'auto') {
bestInsideCandidate = eventTarget.spatialNavigationSearch(dir, {container: eventTarget});
if (focusingController(bestInsideCandidate, dir) || scrollingController(eventTarget, dir)) return;
}
} else {
// when the previous search origin became offscreen
container = container.getSpatialNavigationContainer();
}
}
// 6
// Let container be the nearest ancestor of eventTarget
container = eventTarget.getSpatialNavigationContainer();
let parentContainer = (container.parentElement) ? container.getSpatialNavigationContainer() : null;
// When the container is the viewport of a browsing context
if (!parentContainer && ( window.location !== window.parent.location)) {
parentContainer = window.parent.document.documentElement;
}
if (getCSSSpatNavAction(container) === 'scroll') {
if (scrollingController(container, dir)) return;
} else if (getCSSSpatNavAction(container) === 'focus') {
navigateChain(eventTarget, container, parentContainer, dir, 'all');
} else if (getCSSSpatNavAction(container) === 'auto') {
navigateChain(eventTarget, container, parentContainer, dir, 'visible');
}
}
/**
* Move the focus to the best candidate or do nothing.
* @function focusingController
* @param bestCandidate {Node} - The best candidate of the spatial navigation
* @param dir {SpatialNavigationDirection}- The directional information for the spatial navigation (e.g. LRUD)
* @returns {boolean}
*/
function focusingController(bestCandidate, dir) {
// 10 & 11
// When bestCandidate is found
if (bestCandidate) {
// When bestCandidate is a focusable element and not a container : move focus
/*
* [event] navbeforefocus : Fired before spatial or sequential navigation changes the focus.
*/
if (!createSpatNavEvents('beforefocus', bestCandidate, null, dir))
return true;
const container = bestCandidate.getSpatialNavigationContainer();
if ((container !== window) && (getCSSSpatNavAction(container) === 'focus')) {
bestCandidate.focus();
} else {
bestCandidate.focus({preventScroll: true});
}
startingPoint = null;
return true;
}
// When bestCandidate is not found within the scrollport of a container: Nothing
return false;
}
/**
* Directionally scroll the scrollable spatial navigation container if it can be manually scrolled more.
* @function scrollingController
* @param container {Node} - The spatial navigation container which can scroll
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @returns {boolean}
*/
function scrollingController(container, dir) {
// If there is any scrollable area among parent elements and it can be manually scrolled, scroll the document
if (isScrollable(container, dir) && !isScrollBoundary(container, dir)) {
moveScroll(container, dir);
return true;
}
// If the spatnav container is document and it can be scrolled, scroll the document
if (!container.parentElement && !isHTMLScrollBoundary(container, dir)) {
moveScroll(container.ownerDocument.documentElement, dir);
return true;
}
return false;
}
/**
* Find the candidates within a spatial navigation container include delegable container.
* This function does not search inside delegable container or focusable container.
* In other words, this return candidates set is not included focusable elements inside delegable container or focusable container.
*
* @function getSpatialNavigationCandidates
* @param container {Node} - The spatial navigation container
* @param option {FocusableAreasOptions} - 'mode' attribute takes 'visible' or 'all' for searching the boundary of focusable elements.
* Default value is 'visible'.
* @returns {sequence<Node>} candidate elements within the container
*/
function getSpatialNavigationCandidates (container, option = {mode: 'visible'}) {
let candidates = [];
if (container.childElementCount > 0) {
if (!container.parentElement) {
container = container.getElementsByTagName('body')[0] || document.body;
}
const children = container.children;
for (const elem of children) {
if (isDelegableContainer(elem)) {
candidates.push(elem);
} else if (isFocusable(elem)) {
candidates.push(elem);
if (!isContainer(elem) && elem.childElementCount) {
candidates = candidates.concat(getSpatialNavigationCandidates(elem, {mode: 'all'}));
}
} else if (elem.childElementCount) {
candidates = candidates.concat(getSpatialNavigationCandidates(elem, {mode: 'all'}));
}
}
}
return (option.mode === 'all') ? candidates : candidates.filter(isVisible);
}
/**
* Find the candidates among focusable elements within a spatial navigation container from the search origin (currently focused element)
* depending on the directional information.
* @function getFilteredSpatialNavigationCandidates
* @param element {Node} - The currently focused element which is defined as 'search origin' in the spec
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @param candidates {sequence<Node>} - The candidates for spatial navigation without the directional information
* @param container {Node} - The spatial navigation container
* @returns {Node} The candidates for spatial navigation considering the directional information
*/
function getFilteredSpatialNavigationCandidates (element, dir, candidates, container) {
const targetElement = element;
// Removed below line due to a bug. (iframe body rect is sometime weird.)
// const targetElement = (element.nodeName === 'IFRAME') ? element.contentDocument.body : element;
// If the container is unknown, get the closest container from the element
container = container || targetElement.getSpatialNavigationContainer();
// If the candidates is unknown, find candidates
// 5-1
candidates = (!candidates || candidates.length <= 0) ? getSpatialNavigationCandidates(container) : candidates;
return filteredCandidates(targetElement, candidates, dir, container);
}
/**
* Find the best candidate among the candidates within the container from the search origin (currently focused element)
* @see {@link https://drafts.csswg.org/css-nav-1/#dom-element-spatialnavigationsearch}
* @function spatialNavigationSearch
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @param candidates {sequence<Node>} - The candidates for spatial navigation
* @param container {Node} - The spatial navigation container
* @returns {Node} The best candidate which will gain the focus
*/
function spatialNavigationSearch (dir, args) {
const targetElement = this;
let internalCandidates = [];
let externalCandidates = [];
let insideOverlappedCandidates = getOverlappedCandidates(targetElement);
let bestTarget;
// Set default parameter value
if (!args)
args = {};
const defaultContainer = targetElement.getSpatialNavigationContainer();
let defaultCandidates = getSpatialNavigationCandidates(defaultContainer);
const container = args.container || defaultContainer;
if (args.container && (defaultContainer.contains(args.container))) {
defaultCandidates = defaultCandidates.concat(getSpatialNavigationCandidates(container));
}
const candidates = (args.candidates && args.candidates.length > 0) ?
args.candidates.filter((candidate) => container.contains(candidate)) :
defaultCandidates.filter((candidate) => container.contains(candidate) && (container !== candidate));
// Find the best candidate
// 5
// If startingPoint is either a scroll container or the document,
// find the best candidate within startingPoint
if (candidates && candidates.length > 0) {
// Divide internal or external candidates
candidates.forEach(candidate => {
if (candidate !== targetElement) {
(targetElement.contains(candidate) && targetElement !== candidate ? internalCandidates : externalCandidates).push(candidate);
}
});
// include overlapped element to the internalCandidates
let fullyOverlapped = insideOverlappedCandidates.filter(candidate => !internalCandidates.includes(candidate));
let overlappedContainer = candidates.filter(candidate => (isContainer(candidate) && isEntirelyVisible(targetElement, candidate)));
let overlappedByParent = overlappedContainer.map((elm) => elm.focusableAreas()).flat().filter(candidate => candidate !== targetElement);
internalCandidates = internalCandidates.concat(fullyOverlapped).filter((candidate) => container.contains(candidate));
externalCandidates = externalCandidates.concat(overlappedByParent).filter((candidate) => container.contains(candidate));
// Filter external Candidates
if (externalCandidates.length > 0) {
externalCandidates = getFilteredSpatialNavigationCandidates(targetElement, dir, externalCandidates, container);
}
// If there isn't search origin element but search orgin rect exist (search origin isn't in the layout case)
if (searchOriginRect) {
bestTarget = selectBestCandidate(targetElement, getFilteredSpatialNavigationCandidates(targetElement, dir, internalCandidates, container), dir);
}
if ((internalCandidates && internalCandidates.length > 0) && !(targetElement.nodeName === 'INPUT')) {
bestTarget = selectBestCandidateFromEdge(targetElement, internalCandidates, dir);
}
bestTarget = bestTarget || selectBestCandidate(targetElement, externalCandidates, dir);
if (bestTarget && isDelegableContainer(bestTarget)) {
// if best target is delegable container, then find descendants candidate inside delegable container.
const innerTarget = getSpatialNavigationCandidates(bestTarget, {mode: 'all'});
const descendantsBest = innerTarget.length > 0 ? targetElement.spatialNavigationSearch(dir, {candidates: innerTarget, container: bestTarget}) : null;
if (descendantsBest) {
bestTarget = descendantsBest;
} else if (!isFocusable(bestTarget)) {
// if there is no target inside bestTarget and delegable container is not focusable,
// then try to find another best target without curren best target.
candidates.splice(candidates.indexOf(bestTarget), 1);
bestTarget = candidates.length ? targetElement.spatialNavigationSearch(dir, {candidates: candidates, container: container}) : null;
}
}
return bestTarget;
}
return null;
}
/**
* Get the filtered candidate among candidates.
* @see {@link https://drafts.csswg.org/css-nav-1/#select-the-best-candidate}
* @function filteredCandidates
* @param currentElm {Node} - The currently focused element which is defined as 'search origin' in the spec
* @param candidates {sequence<Node>} - The candidates for spatial navigation
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @param container {Node} - The spatial navigation container
* @returns {sequence<Node>} The filtered candidates which are not the search origin and not in the given spatial navigation direction from the search origin
*/
// TODO: Need to fix filtering the candidates with more clean code
function filteredCandidates(currentElm, candidates, dir, container) {
const originalContainer = currentElm.getSpatialNavigationContainer();
let eventTargetRect;
// If D(dir) is null, let candidates be the same as visibles
if (dir === undefined)
return candidates;
// Offscreen handling when originalContainer is not <HTML>
if (originalContainer.parentElement && container !== originalContainer && !isVisible(currentElm)) {
eventTargetRect = getBoundingClientRect(originalContainer);
} else {
eventTargetRect = searchOriginRect || getBoundingClientRect(currentElm);
}
/*
* Else, let candidates be the subset of the elements in visibles
* whose principal box’s geometric center is within the closed half plane
* whose boundary goes through the geometric center of starting point and is perpendicular to D.
*/
if ((isContainer(currentElm) || currentElm.nodeName === 'BODY') && !(currentElm.nodeName === 'INPUT')) {
return candidates.filter(candidate => {
const candidateRect = getBoundingClientRect(candidate);
return container.contains(candidate) &&
((currentElm.contains(candidate) && isInside(eventTargetRect, candidateRect) && candidate !== currentElm) ||
isOutside(candidateRect, eventTargetRect, dir));
});
} else {
return candidates.filter(candidate => {
const candidateRect = getBoundingClientRect(candidate);
const candidateBody = (candidate.nodeName === 'IFRAME') ? candidate.contentDocument.body : null;
return container.contains(candidate) &&
candidate !== currentElm && candidateBody !== currentElm &&
isOutside(candidateRect, eventTargetRect, dir) &&
!isInside(eventTargetRect, candidateRect);
});
}
}
/**
* Select the best candidate among given candidates.
* @see {@link https://drafts.csswg.org/css-nav-1/#select-the-best-candidate}
* @function selectBestCandidate
* @param currentElm {Node} - The currently focused element which is defined as 'search origin' in the spec
* @param candidates {sequence<Node>} - The candidates for spatial navigation
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @returns {Node} The best candidate which will gain the focus
*/
function selectBestCandidate(currentElm, candidates, dir) {
const container = currentElm.getSpatialNavigationContainer();
const spatialNavigationFunction = getComputedStyle(container).getPropertyValue('--spatial-navigation-function');
const currentTargetRect = searchOriginRect || getBoundingClientRect(currentElm);
let distanceFunction;
let alignedCandidates;
switch (spatialNavigationFunction) {
case 'grid':
alignedCandidates = candidates.filter(elm => isAligned(currentTargetRect, getBoundingClientRect(elm), dir));
if (alignedCandidates.length > 0) {
candidates = alignedCandidates;
}
distanceFunction = getAbsoluteDistance;
break;
default:
distanceFunction = getDistance;
break;
}
return getClosestElement(currentElm, candidates, dir, distanceFunction);
}
/**
* Select the best candidate among candidates by finding the closet candidate from the edge of the currently focused element (search origin).
* @see {@link https://drafts.csswg.org/css-nav-1/#select-the-best-candidate (Step 5)}
* @function selectBestCandidateFromEdge
* @param currentElm {Node} - The currently focused element which is defined as 'search origin' in the spec
* @param candidates {sequence<Node>} - The candidates for spatial navigation
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @returns {Node} The best candidate which will gain the focus
*/
function selectBestCandidateFromEdge(currentElm, candidates, dir) {
if (startingPoint)
return getClosestElement(currentElm, candidates, dir, getDistanceFromPoint);
else
return getClosestElement(currentElm, candidates, dir, getInnerDistance);
}
/**
* Select the closest candidate from the currently focused element (search origin) among candidates by using the distance function.
* @function getClosestElement
* @param currentElm {Node} - The currently focused element which is defined as 'search origin' in the spec
* @param candidates {sequence<Node>} - The candidates for spatial navigation
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @param distanceFunction {function} - The distance function which measures the distance from the search origin to each candidate
* @returns {Node} The candidate which is the closest one from the search origin
*/
function getClosestElement(currentElm, candidates, dir, distanceFunction) {
let eventTargetRect = null;
if (( window.location !== window.parent.location ) && (currentElm.nodeName === 'BODY' || currentElm.nodeName === 'HTML')) {
// If the eventTarget is iframe, then get rect of it based on its containing document
// Set the iframe's position as (0,0) because the rects of elements inside the iframe don't know the real iframe's position.
eventTargetRect = window.frameElement.getBoundingClientRect();
eventTargetRect.x = 0;
eventTargetRect.y = 0;
} else {
eventTargetRect = searchOriginRect || currentElm.getBoundingClientRect();
}
let minDistance = Number.POSITIVE_INFINITY;
let minDistanceElements = [];
if (candidates) {
for (let i = 0; i < candidates.length; i++) {
const distance = distanceFunction(eventTargetRect, getBoundingClientRect(candidates[i]), dir);
// If the same distance, the candidate will be selected in the DOM order
if (distance < minDistance) {
minDistance = distance;
minDistanceElements = [candidates[i]];
} else if (distance === minDistance) {
minDistanceElements.push(candidates[i]);
}
}
}
if (minDistanceElements.length === 0)
return null;
return (minDistanceElements.length > 1 && distanceFunction === getAbsoluteDistance) ?
getClosestElement(currentElm, minDistanceElements, dir, getEuclideanDistance) : minDistanceElements[0];
}
/**
* Get container of an element.
* @see {@link https://drafts.csswg.org/css-nav-1/#dom-element-getspatialnavigationcontainer}
* @module Element
* @function getSpatialNavigationContainer
* @returns {Node} The spatial navigation container
*/
function getSpatialNavigationContainer() {
let container = this;
do {
if (!container.parentElement) {
if (window.location !== window.parent.location) {
container = window.parent.document.documentElement;
} else {
container = window.document.documentElement;
}
break;
} else {
container = container.parentElement;
}
} while (!isContainer(container));
return container;
}
/**
* Get nearest scroll container of an element.
* @function getScrollContainer
* @param Element
* @returns {Node} The spatial navigation container
*/
function getScrollContainer(element) {
let scrollContainer = element;
do {
if (!scrollContainer.parentElement) {
if (window.location !== window.parent.location) {
scrollContainer = window.parent.document.documentElement;
} else {
scrollContainer = window.document.documentElement;
}
break;
} else {
scrollContainer = scrollContainer.parentElement;
}
} while (!isScrollContainer(scrollContainer) || !isVisible(scrollContainer));
if (scrollContainer === document || scrollContainer === document.documentElement) {
scrollContainer = window;
}
return scrollContainer;
}
/**
* Find focusable elements within the spatial navigation container.
* @see {@link https://drafts.csswg.org/css-nav-1/#dom-element-focusableareas}
* @function focusableAreas
* @param option {FocusableAreasOptions} - 'mode' attribute takes 'visible' or 'all' for searching the boundary of focusable elements.
* Default value is 'visible'.
* @returns {sequence<Node>} All focusable elements or only visible focusable elements within the container
*/
function focusableAreas(option = {mode: 'visible'}) {
const container = this.parentElement ? this : document.body;
const focusables = Array.prototype.filter.call(container.getElementsByTagName('*'), isFocusable);
return (option.mode === 'all') ? focusables : focusables.filter(isVisible);
}
/**
* Create the NavigationEvent: navbeforefocus, navnotarget
* @see {@link https://drafts.csswg.org/css-nav-1/#events-navigationevent}
* @function createSpatNavEvents
* @param option {string} - Type of the navigation event (beforefocus, notarget)
* @param element {Node} - The target element of the event
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
*/
function createSpatNavEvents(eventType, containerElement, currentElement, direction) {
if (['beforefocus', 'notarget'].includes(eventType)) {
const data = {
causedTarget: currentElement,
dir: direction
};
const triggeredEvent = new CustomEvent('nav' + eventType, {bubbles: true, cancelable: true, detail: data});
return containerElement.dispatchEvent(triggeredEvent);
}
}
/**
* Get the value of the CSS custom property of the element
* @function readCssVar
* @param element {Node}
* @param varName {string} - The name of the css custom property without '--'
* @returns {string} The value of the css custom property
*/
function readCssVar(element, varName) {
return element.style.getPropertyValue(`--${varName}`).trim();
}
/**
* Decide whether or not the 'contain' value is given to 'spatial-navigation-contain' css property of an element
* @function isCSSSpatNavContain
* @param element {Node}
* @returns {boolean}
*/
function isCSSSpatNavContain(element) {
return readCssVar(element, 'spatial-navigation-contain') === 'contain';
}
/**
* Return the value of 'spatial-navigation-action' css property of an element
* @function getCSSSpatNavAction
* @param element {Node} - would be the spatial navigation container
* @returns {string} auto | focus | scroll
*/
function getCSSSpatNavAction(element) {
return readCssVar(element, 'spatial-navigation-action') || 'auto';
}
/**
* Only move the focus with spatial navigation. Manually scrolling isn't available.
* @function navigateChain
* @param eventTarget {Node} - currently focused element
* @param container {SpatialNavigationContainer} - container
* @param parentContainer {SpatialNavigationContainer} - parent container
* @param option - visible || all
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
*/
function navigateChain(eventTarget, container, parentContainer, dir, option) {
let currentOption = {candidates: getSpatialNavigationCandidates(container, {mode: option}), container};
while (parentContainer) {
if (focusingController(eventTarget.spatialNavigationSearch(dir, currentOption), dir)) {
return;
} else {
if ((option === 'visible') && scrollingController(container, dir)) return;
else {
if (!createSpatNavEvents('notarget', container, eventTarget, dir)) return;
// find the container
if (container === document || container === document.documentElement) {
if ( window.location !== window.parent.location ) {
// The page is in an iframe. eventTarget needs to be reset because the position of the element in the iframe
eventTarget = window.frameElement;
container = eventTarget.ownerDocument.documentElement;
}
} else {
container = parentContainer;
}
currentOption = {candidates: getSpatialNavigationCandidates(container, {mode: option}), container};
let nextContainer = container.getSpatialNavigationContainer();
if (nextContainer !== container) {
parentContainer = nextContainer;
} else {
parentContainer = null;
}
}
}
}
currentOption = {candidates: getSpatialNavigationCandidates(container, {mode: option}), container};
// Behavior after 'navnotarget' - Getting out from the current spatnav container
if ((!parentContainer && container) && focusingController(eventTarget.spatialNavigationSearch(dir, currentOption), dir)) return;
if (!createSpatNavEvents('notarget', currentOption.container, eventTarget, dir)) return;
if ((getCSSSpatNavAction(container) === 'auto') && (option === 'visible')) {
if (scrollingController(container, dir)) return;
}
}
/**
* Find search origin
* @see {@link https://drafts.csswg.org/css-nav-1/#nav}
* @function findSearchOrigin
* @returns {Node} The search origin for the spatial navigation
*/
function findSearchOrigin() {
let searchOrigin = document.activeElement;
if (!searchOrigin || (searchOrigin === document.body && !document.querySelector(':focus'))) {
// When the previous search origin lost its focus by blur: (1) disable attribute (2) visibility: hidden
if (savedSearchOrigin.element && (searchOrigin !== savedSearchOrigin.element)) {
const elementStyle = window.getComputedStyle(savedSearchOrigin.element, null);
const invisibleStyle = ['hidden', 'collapse'];
if (savedSearchOrigin.element.disabled || invisibleStyle.includes(elementStyle.getPropertyValue('visibility'))) {
searchOrigin = savedSearchOrigin.element;
return searchOrigin;
}
}
searchOrigin = document.documentElement;
}
// When the previous search origin lost its focus by blur: (1) display:none () element size turned into zero
if (savedSearchOrigin.element &&
((getBoundingClientRect(savedSearchOrigin.element).height === 0) || (getBoundingClientRect(savedSearchOrigin.element).width === 0))) {
searchOriginRect = savedSearchOrigin.rect;
}
if (!isVisibleInScroller(searchOrigin)) {
const scroller = getScrollContainer(searchOrigin);
if (scroller && ((scroller === window) || (getCSSSpatNavAction(scroller) === 'auto')))
return scroller;
}
return searchOrigin;
}
/**
* Move the scroll of an element depending on the given spatial navigation directrion
* (Assume that User Agent defined distance is '40px')
* @see {@link https://drafts.csswg.org/css-nav-1/#directionally-scroll-an-element}
* @function moveScroll
* @param element {Node} - The scrollable element
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @param offset {Number} - The explicit amount of offset for scrolling. Default value is 0.
*/
function moveScroll(element, dir, offset = 0) {
if (element) {
switch (dir) {
case 'left': element.scrollLeft -= (40 + offset); break;
case 'right': element.scrollLeft += (40 + offset); break;
case 'up': element.scrollTop -= (40 + offset); break;
case 'down': element.scrollTop += (40 + offset); break;
}
}
}
/**
* Decide whether an element is container or not.
* @function isContainer
* @param element {Node} element
* @returns {boolean}
*/
function isContainer(element) {
return (!element.parentElement) ||
(element.nodeName === 'IFRAME') ||
(isScrollContainer(element)) ||
(isCSSSpatNavContain(element));
}
/**
* Decide whether an element is delegable container or not.
* NOTE: THIS IS NON-NORMATIVE API.
* @function isDelegableContainer
* @param element {Node} element
* @returns {boolean}
*/
function isDelegableContainer(element) {
return readCssVar(element, 'spatial-navigation-contain') === 'delegable';
}
/**
* Decide whether an element is a scrollable container or not.
* @see {@link https://drafts.csswg.org/css-overflow-3/#scroll-container}
* @function isScrollContainer
* @param element {Node}
* @returns {boolean}
*/
function isScrollContainer(element) {
const elementStyle = window.getComputedStyle(element, null);
const overflowX = elementStyle.getPropertyValue('overflow-x');
const overflowY = elementStyle.getPropertyValue('overflow-y');
return ((overflowX !== 'visible' && overflowX !== 'clip' && isOverflow(element, 'left')) ||
(overflowY !== 'visible' && overflowY !== 'clip' && isOverflow(element, 'down'))) ?
true : false;
}
/**
* Decide whether this element is scrollable or not.
* NOTE: If the value of 'overflow' is given to either 'visible', 'clip', or 'hidden', the element isn't scrollable.
* If the value is 'hidden', the element can be only programmically scrollable. (https://drafts.csswg.org/css-overflow-3/#valdef-overflow-hidden)
* @function isScrollable
* @param element {Node}
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @returns {boolean}
*/
function isScrollable(element, dir) { // element, dir
if (element && typeof element === 'object') {
if (dir && typeof dir === 'string') { // parameter: dir, element
if (isOverflow(element, dir)) {
// style property
const elementStyle = window.getComputedStyle(element, null);
const overflowX = elementStyle.getPropertyValue('overflow-x');
const overflowY = elementStyle.getPropertyValue('overflow-y');
switch (dir) {
case 'left':
/* falls through */
case 'right':
return (overflowX !== 'visible' && overflowX !== 'clip' && overflowX !== 'hidden');
case 'up':
/* falls through */
case 'down':
return (overflowY !== 'visible' && overflowY !== 'clip' && overflowY !== 'hidden');
}
}
return false;
} else { // parameter: element
return (element.nodeName === 'HTML' || element.nodeName === 'BODY') ||
(isScrollContainer(element) && isOverflow(element));
}
}
}
/**
* Decide whether an element is overflow or not.
* @function isOverflow
* @param element {Node}
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @returns {boolean}
*/
function isOverflow(element, dir) {
if (element && typeof element === 'object') {
if (dir && typeof dir === 'string') { // parameter: element, dir
switch (dir) {
case 'left':
/* falls through */
case 'right':
return (element.scrollWidth > element.clientWidth);
case 'up':
/* falls through */
case 'down':
return (element.scrollHeight > element.clientHeight);
}
} else { // parameter: element
return (element.scrollWidth > element.clientWidth || element.scrollHeight > element.clientHeight);
}
return false;
}
}
/**
* Decide whether the scrollbar of the browsing context reaches to the end or not.
* @function isHTMLScrollBoundary
* @param element {Node} - The top browsing context
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @returns {boolean}
*/
function isHTMLScrollBoundary(element, dir) {
let result = false;
switch (dir) {
case 'left':
result = element.scrollLeft === 0;
break;
case 'right':
result = (element.scrollWidth - element.scrollLeft - element.clientWidth) === 0;
break;
case 'up':
result = element.scrollTop === 0;
break;
case 'down':
result = (element.scrollHeight - element.scrollTop - element.clientHeight) === 0;
break;
}
return result;
}
/**
* Decide whether the scrollbar of an element reaches to the end or not.
* @function isScrollBoundary
* @param element {Node}
* @param dir {SpatialNavigationDirection} - The directional information for the spatial navigation (e.g. LRUD)
* @returns {boolean}
*/
function isScrollBoundary(element, dir) {
if (isScrollable(element, dir)) {
const winScrollY = element.scrollTop;
const winScrollX = element.scrollLeft;
const height = element.scrollHeight - element.clientHeight;
const width = element.scrollWidth - element.clientWidth;
switch (dir) {
case 'left': return (winScrollX === 0);
case 'right': return (Math.abs(winScrollX - width) <= 1);
case 'up': return (winScrollY === 0);
case 'down': return (Math.abs(winScrollY - height) <= 1);
}
}
return false;
}
/**
* Decide whether an element is inside the scorller viewport or not
*
* @function isVisibleInScroller
* @param element {Node}
* @returns {boolean}
*/
function isVisibleInScroller(element) {
const elementRect = element.getBoundingClientRect();
let nearestScroller = getScrollContainer(element);
let scrollerRect = null;
if (nearestScroller !== window) {
scrollerRect = getBoundingClientRect(nearestScroller);
} else {
scrollerRect = new DOMRect(0, 0, window.innerWidth, window.innerHeight);
}
if (isInside(scrollerRect, elementRect, 'left') && isInside(scrollerRect, elementRect, 'down'))
return true;
else
return false;
}
/**
* Decide whether an element is focusable for spatial navigation.
* 1. If element is the browsing context (document, iframe), then it's focusable,
* 2. If the element is scrollable container (regardless of scrollable axis), then it's focusable,
* 3. The value of tabIndex >= 0, then it's focusable,
* 4. If the element is disabled, it isn't focusable,
* 5. If the element is expressly inert, it isn't focusable,
* 6. Whether the element is being rendered or not.
*
* @function isFocusable
* @param element {Node}
* @returns {boolean}
*
* @see {@link https://html.spec.whatwg.org/multipage/interaction.html#focusable-area}
*/
function isFocusable(element) {
if ((element.tabIndex < 0) || isAtagWithoutHref(element) || isActuallyDisabled(element) || isExpresslyInert(element) || !isBeingRendered(element))
return false;
else if ((!element.parentElement) || (isScrollable(element) && isOverflow(element)) || (element.tabIndex >= 0))