1 | import KEYCODE from './keycode';
|
2 | import { each } from './object';
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | function _isVisible(node) {
|
15 | while (node) {
|
16 | var _node = node,
|
17 | nodeName = _node.nodeName;
|
18 |
|
19 | if (nodeName === 'BODY' || nodeName === 'HTML') {
|
20 | break;
|
21 | }
|
22 | if (node.style.display === 'none' || node.style.visibility === 'hidden') {
|
23 | return false;
|
24 | }
|
25 | node = node.parentNode;
|
26 | }
|
27 | return true;
|
28 | }
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 | function _isFocusable(node) {
|
37 | var nodeName = node.nodeName.toLowerCase();
|
38 | var tabIndex = parseInt(node.getAttribute('tabindex'), 10);
|
39 | var hasTabIndex = !isNaN(tabIndex) && tabIndex > -1;
|
40 |
|
41 | if (_isVisible(node)) {
|
42 | if (nodeName === 'input') {
|
43 | return !node.disabled && node.type !== 'hidden';
|
44 | } else if (['select', 'textarea', 'button'].indexOf(nodeName) > -1) {
|
45 | return !node.disabled;
|
46 | } else if (nodeName === 'a') {
|
47 | return node.getAttribute('href') || hasTabIndex;
|
48 | } else {
|
49 | return hasTabIndex;
|
50 | }
|
51 | }
|
52 | return false;
|
53 | }
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | export function getFocusNodeList(node) {
|
61 | var res = [];
|
62 | var nodeList = node.querySelectorAll('*');
|
63 |
|
64 | each(nodeList, function (item) {
|
65 | if (_isFocusable(item)) {
|
66 | var method = item.getAttribute('data-auto-focus') ? 'unshift' : 'push';
|
67 | res[method](item);
|
68 | }
|
69 | });
|
70 |
|
71 | if (_isFocusable(node)) {
|
72 | res.unshift(node);
|
73 | }
|
74 |
|
75 | return res;
|
76 | }
|
77 |
|
78 |
|
79 | var lastFocusElement = null;
|
80 |
|
81 |
|
82 |
|
83 |
|
84 | export function saveLastFocusNode() {
|
85 | lastFocusElement = document.activeElement;
|
86 | }
|
87 |
|
88 |
|
89 |
|
90 |
|
91 | export function clearLastFocusNode() {
|
92 | lastFocusElement = null;
|
93 | }
|
94 |
|
95 |
|
96 |
|
97 |
|
98 | export function backLastFocusNode() {
|
99 | if (lastFocusElement) {
|
100 | try {
|
101 |
|
102 | lastFocusElement.focus();
|
103 | } catch (e) {
|
104 |
|
105 | }
|
106 | }
|
107 | }
|
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 | export function limitTabRange(node, e) {
|
115 | if (e.keyCode === KEYCODE.TAB) {
|
116 | var tabNodeList = getFocusNodeList(node);
|
117 | var maxIndex = tabNodeList.length - 1;
|
118 | var index = tabNodeList.indexOf(document.activeElement);
|
119 |
|
120 | if (index > -1) {
|
121 | var targetIndex = index + (e.shiftKey ? -1 : 1);
|
122 | targetIndex < 0 && (targetIndex = maxIndex);
|
123 | targetIndex > maxIndex && (targetIndex = 0);
|
124 | tabNodeList[targetIndex].focus();
|
125 | e.preventDefault();
|
126 | }
|
127 | }
|
128 | } |
\ | No newline at end of file |