-
-
Notifications
You must be signed in to change notification settings - Fork 454
Expand file tree
/
Copy pathUncontrolledTabs.jsx
More file actions
433 lines (372 loc) · 11.6 KB
/
UncontrolledTabs.jsx
File metadata and controls
433 lines (372 loc) · 11.6 KB
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
import { checkPropTypes } from 'prop-types';
import React, { cloneElement, useRef, useId } from 'react';
import cx from 'clsx';
import { childrenPropType } from '../helpers/propTypes';
import { getTabsCount as getTabsCountHelper } from '../helpers/count';
import { deepMap } from '../helpers/childrenDeepMap';
import { isTabList, isTabPanel, isTab } from '../helpers/elementTypes';
function isNode(node) {
return node && 'getAttribute' in node;
}
// Determine if a node from event.target is a Tab element
function isTabNode(node) {
return isNode(node) && node.getAttribute('data-rttab');
}
// Determine if a tab node is disabled
function isTabDisabled(node) {
return isNode(node) && node.getAttribute('aria-disabled') === 'true';
}
let canUseActiveElement;
function determineCanUseActiveElement(environment) {
const env =
environment || (typeof window !== 'undefined' ? window : undefined);
try {
canUseActiveElement = !!(
typeof env !== 'undefined' &&
env.document &&
env.document.activeElement
);
// eslint-disable-next-line no-unused-vars
} catch (e) {
// Work around for IE bug when accessing document.activeElement in an iframe
// Refer to the following resources:
// http://stackoverflow.com/a/10982960/369687
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12733599
// istanbul ignore next
canUseActiveElement = false;
}
}
const defaultProps = {
className: 'react-tabs',
focus: false,
};
const propTypes = {
children: childrenPropType,
/*
Left for TS migration
direction: PropTypes.oneOf(['rtl', 'ltr']),
className: PropTypes.oneOfType([
PropTypes.string,
PropTypes.array,
PropTypes.object,
]),
disabledTabClassName: PropTypes.string,
disableUpDownKeys: PropTypes.bool,
disableLeftRightKeys: PropTypes.bool,
domRef: PropTypes.func,
focus: PropTypes.bool,
forceRenderTabPanel: PropTypes.bool,
onSelect: PropTypes.func.isRequired,
selectedIndex: PropTypes.number.isRequired,
selectedTabClassName: PropTypes.string,
selectedTabPanelClassName: PropTypes.string,
environment: PropTypes.object,*/
};
const UncontrolledTabs = (props) => {
checkPropTypes(propTypes, props, 'prop', 'UncontrolledTabs');
let tabNodes = useRef([]);
let tabIds = useRef([]);
const ref = useRef();
function setSelected(index, event) {
// Check index boundary
if (index < 0 || index >= getTabsCount()) return;
const { onSelect, selectedIndex } = props;
// Call change event handler
onSelect(index, selectedIndex, event);
}
function getNextTab(index) {
const count = getTabsCount();
// Look for non-disabled tab from index to the last tab on the right
for (let i = index + 1; i < count; i++) {
if (!isTabDisabled(getTab(i))) {
return i;
}
}
// If no tab found, continue searching from first on left to index
for (let i = 0; i < index; i++) {
if (!isTabDisabled(getTab(i))) {
return i;
}
}
// All tabs are disabled, return index
/* istanbul ignore next */
return index;
}
function getPrevTab(index) {
let i = index;
// Look for non-disabled tab from index to first tab on the left
while (i--) {
if (!isTabDisabled(getTab(i))) {
return i;
}
}
// If no tab found, continue searching from last tab on right to index
i = getTabsCount();
while (i-- > index) {
if (!isTabDisabled(getTab(i))) {
return i;
}
}
// All tabs are disabled, return index
/* istanbul ignore next */
return index;
}
function getFirstTab() {
const count = getTabsCount();
// Look for non disabled tab from the first tab
for (let i = 0; i < count; i++) {
if (!isTabDisabled(getTab(i))) {
return i;
}
}
/* istanbul ignore next */
return null;
}
function getLastTab() {
let i = getTabsCount();
// Look for non disabled tab from the last tab
while (i--) {
if (!isTabDisabled(getTab(i))) {
return i;
}
}
/* istanbul ignore next */
return null;
}
function getTabsCount() {
const { children } = props;
return getTabsCountHelper(children);
}
function getTab(index) {
return tabNodes.current[`tabs-${index}`];
}
function getChildren() {
let index = 0;
const {
children,
disabledTabClassName,
focus,
forceRenderTabPanel,
selectedIndex,
selectedTabClassName,
selectedTabPanelClassName,
environment,
} = props;
tabIds.current = tabIds.current || [];
let diff = tabIds.current.length - getTabsCount();
// Add ids if new tabs have been added
// Don't bother removing ids, just keep them in case they are added again
// This is more efficient, and keeps the uuid counter under control
const id = useId();
while (diff++ < 0) {
tabIds.current.push(`${id}${tabIds.current.length}`);
}
// Map children to dynamically setup refs
return deepMap(children, (child) => {
let result = child;
// Clone TabList and Tab components to have refs
if (isTabList(child)) {
let listIndex = 0;
// Figure out if the current focus in the DOM is set on a Tab
// If it is we should keep the focus on the next selected tab
let wasTabFocused = false;
if (canUseActiveElement == null) {
determineCanUseActiveElement(environment);
}
const env =
environment || (typeof window !== 'undefined' ? window : undefined);
if (canUseActiveElement && env) {
wasTabFocused = React.Children.toArray(child.props.children)
.filter(isTab)
.some((tab, i) => env.document.activeElement === getTab(i));
}
result = cloneElement(child, {
children: deepMap(child.props.children, (tab) => {
const key = `tabs-${listIndex}`;
const selected = selectedIndex === listIndex;
const props = {
tabRef: (node) => {
tabNodes.current[key] = node;
},
id: tabIds.current[listIndex],
selected,
focus: selected && (focus || wasTabFocused),
};
if (selectedTabClassName)
props.selectedClassName = selectedTabClassName;
if (disabledTabClassName)
props.disabledClassName = disabledTabClassName;
listIndex++;
return cloneElement(tab, props);
}),
});
} else if (isTabPanel(child)) {
const props = {
id: tabIds.current[index],
selected: selectedIndex === index,
};
if (forceRenderTabPanel) props.forceRender = forceRenderTabPanel;
if (selectedTabPanelClassName)
props.selectedClassName = selectedTabPanelClassName;
index++;
result = cloneElement(child, props);
}
return result;
});
}
function handleKeyDown(e) {
const { direction, disableUpDownKeys, disableLeftRightKeys } = props;
if (isTabFromContainer(e.target)) {
let { selectedIndex: index } = props;
let preventDefault = false;
let useSelectedIndex = false;
if (
e.code === 'Space' ||
e.keyCode === 32 /* space */ ||
e.code === 'Enter' ||
e.keyCode === 13 /* enter */
) {
preventDefault = true;
useSelectedIndex = false;
handleClick(e);
}
// keyCode is deprecated and only used here for IE
if (
(!disableLeftRightKeys &&
(e.keyCode === 37 || e.code === 'ArrowLeft')) /* arrow left */ ||
(!disableUpDownKeys &&
(e.keyCode === 38 || e.code === 'ArrowUp')) /* arrow up */
) {
// Select next tab to the left, validate if up arrow is not disabled
if (direction === 'rtl') {
index = getNextTab(index);
} else {
index = getPrevTab(index);
}
preventDefault = true;
useSelectedIndex = true;
} else if (
(!disableLeftRightKeys &&
(e.keyCode === 39 || e.code === 'ArrowRight')) /* arrow right */ ||
(!disableUpDownKeys &&
(e.keyCode === 40 || e.code === 'ArrowDown')) /* arrow down */
) {
// Select next tab to the right, validate if down arrow is not disabled
if (direction === 'rtl') {
index = getPrevTab(index);
} else {
index = getNextTab(index);
}
preventDefault = true;
useSelectedIndex = true;
} else if (e.keyCode === 35 || e.code === 'End') {
// Select last tab (End key)
index = getLastTab();
preventDefault = true;
useSelectedIndex = true;
} else if (e.keyCode === 36 || e.code === 'Home') {
// Select first tab (Home key)
index = getFirstTab();
preventDefault = true;
useSelectedIndex = true;
}
// This prevents scrollbars from moving around
if (preventDefault) {
e.preventDefault();
}
// Only use the selected index in the state if we're not using the tabbed index
if (useSelectedIndex) {
setSelected(index, e);
}
}
}
function handleClick(e) {
let node = e.target;
do {
if (isTabFromContainer(node)) {
if (isTabDisabled(node)) {
return;
}
const index = [].slice
.call(node.parentNode.children)
.filter(isTabNode)
.indexOf(node);
setSelected(index, e);
return;
}
} while ((node = node.parentNode) != null);
}
/**
* Determine if a node from event.target is a Tab element for the current Tabs container.
* If the clicked element is not a Tab, it returns false.
* If it finds another Tabs container between the Tab and `this`, it returns false.
*/
function isTabFromContainer(node) {
// return immediately if the clicked element is not a Tab.
if (!isTabNode(node)) {
return false;
}
// Check if the first occurrence of a Tabs container is `this` one.
let nodeAncestor = node.parentElement;
do {
if (nodeAncestor === ref.current) return true;
if (nodeAncestor.getAttribute('data-rttabs')) break;
nodeAncestor = nodeAncestor.parentElement;
} while (nodeAncestor);
return false;
}
const {
className: propClassName,
domRef,
children, // unused here
disabledTabClassName, // unused here
focus, // unused here
forceRenderTabPanel, // unused here
onSelect, // unused here
selectedIndex, // unused here
selectedTabClassName, // unused here
selectedTabPanelClassName, // unused here
environment, // unused here
disableUpDownKeys, // unused here
disableLeftRightKeys, // unused here
...restProps
} = props;
// Only pass valid DOM attributes and data- attributes
const domAttributes = {};
Object.keys(restProps).forEach((key) => {
if (
key.startsWith('data-') ||
key === 'id' ||
key === 'style' ||
key === 'title' ||
key === 'role' ||
key === 'tabIndex' ||
key === 'aria-label' ||
key === 'aria-labelledby' ||
key === 'aria-describedby' ||
key === 'aria-controls' ||
key === 'aria-selected' ||
key === 'aria-disabled'
) {
domAttributes[key] = restProps[key];
}
});
const className =
propClassName == null ? defaultProps.className : propClassName;
return (
<div
{...domAttributes}
className={cx(className)}
onClick={handleClick}
onKeyDown={handleKeyDown}
ref={(node) => {
ref.current = node;
if (domRef) domRef(node);
}}
data-rttabs
>
{getChildren()}
</div>
);
};
export default UncontrolledTabs;