-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
TreeNode.js
358 lines (329 loc) · 10.3 KB
/
TreeNode.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
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { CaretDown } from '@carbon/icons-react';
import classNames from 'classnames';
import { keys, match, matches } from '../../internal/keyboard';
import uniqueId from '../../tools/uniqueId';
import { usePrefix } from '../../internal/usePrefix';
import { useControllableState } from '../../internal/useControllableState';
import { useFeatureFlag } from '../FeatureFlags';
const TreeNode = React.forwardRef(
(
{
active,
children,
className,
depth,
disabled,
id: nodeId,
isExpanded,
defaultIsExpanded,
label,
onNodeFocusEvent,
onSelect: onNodeSelect,
onToggle,
onTreeSelect,
renderIcon: Icon,
selected,
value,
...rest
},
ref
) => {
const enableTreeviewControllable = useFeatureFlag(
'enable-treeview-controllable'
);
const { current: id } = useRef(nodeId || uniqueId());
const controllableExpandedState = useControllableState({
value: isExpanded,
onChange: onToggle,
defaultValue: defaultIsExpanded,
});
const uncontrollableExpandedState = useState(isExpanded);
const [expanded, setExpanded] = enableTreeviewControllable
? controllableExpandedState
: uncontrollableExpandedState;
const currentNode = useRef(null);
const currentNodeLabel = useRef(null);
const prefix = usePrefix();
const nodesWithProps = React.Children.map(children, (node) => {
if (React.isValidElement(node)) {
return React.cloneElement(node, {
active,
depth: depth + 1,
disabled,
onTreeSelect,
selected,
tabIndex: (!node.props.disabled && -1) || null,
});
}
});
const isActive = active === id;
const isSelected = selected.includes(id);
const treeNodeClasses = classNames(className, `${prefix}--tree-node`, {
[`${prefix}--tree-node--active`]: isActive,
[`${prefix}--tree-node--disabled`]: disabled,
[`${prefix}--tree-node--selected`]: isSelected,
[`${prefix}--tree-node--with-icon`]: Icon,
[`${prefix}--tree-leaf-node`]: !children,
[`${prefix}--tree-parent-node`]: children,
});
const toggleClasses = classNames(
`${prefix}--tree-parent-node__toggle-icon`,
{
[`${prefix}--tree-parent-node__toggle-icon--expanded`]: expanded,
}
);
function handleToggleClick(event) {
if (disabled) {
return;
}
// Prevent the node from being selected
event.stopPropagation();
if (!enableTreeviewControllable) {
onToggle?.(event, { id, isExpanded: !expanded, label, value });
}
setExpanded(!expanded);
}
function handleClick(event) {
event.stopPropagation();
if (!disabled) {
onTreeSelect?.(event, { id, label, value });
onNodeSelect?.(event, { id, label, value });
rest?.onClick?.(event);
}
}
function handleKeyDown(event) {
if (disabled) {
return;
}
if (matches(event, [keys.ArrowLeft, keys.ArrowRight, keys.Enter])) {
event.stopPropagation();
}
if (match(event, keys.ArrowLeft)) {
const findParentTreeNode = (node) => {
if (node.classList.contains(`${prefix}--tree-parent-node`)) {
return node;
}
if (node.classList.contains(`${prefix}--tree`)) {
return null;
}
return findParentTreeNode(node.parentNode);
};
if (children && expanded) {
if (!enableTreeviewControllable) {
onToggle?.(event, { id, isExpanded: false, label, value });
}
setExpanded(false);
} else {
/**
* When focus is on a leaf node or a closed parent node, move focus to
* its parent node (unless its depth is level 1)
*/
findParentTreeNode(currentNode.current.parentNode)?.focus();
}
}
if (children && match(event, keys.ArrowRight)) {
if (expanded) {
/**
* When focus is on an expanded parent node, move focus to the first
* child node
*/
currentNode.current.lastChild.firstChild.focus();
} else {
if (!enableTreeviewControllable) {
onToggle?.(event, { id, isExpanded: true, label, value });
}
setExpanded(true);
}
}
if (matches(event, [keys.Enter, keys.Space])) {
event.preventDefault();
handleClick(event);
}
rest?.onKeyDown?.(event);
}
function handleFocusEvent(event) {
if (event.type === 'blur') {
rest?.onBlur?.(event);
}
if (event.type === 'focus') {
rest?.onFocus?.(event);
}
onNodeFocusEvent?.(event);
}
useEffect(() => {
/**
* Negative margin shifts node to align with the left side boundary of the
* tree
* Dynamically calculate padding to recreate tree node indentation
* - parent nodes with icon have (depth + 1rem + depth * 0.5) left padding
* - parent nodes have (depth + 1rem) left padding
* - leaf nodes have (depth + 2.5rem) left padding without icons (because
* of expand icon + spacing)
* - leaf nodes have (depth + 2rem + depth * 0.5) left padding with icons (because of
* reduced spacing between the expand icon and the node icon + label)
*/
const calcOffset = () => {
// parent node with icon
if (children && Icon) {
return depth + 1 + depth * 0.5;
}
// parent node without icon
if (children) {
return depth + 1;
}
// leaf node with icon
if (Icon) {
return depth + 2 + depth * 0.5;
}
// leaf node without icon
return depth + 2.5;
};
if (currentNodeLabel.current) {
currentNodeLabel.current.style.marginInlineStart = `-${calcOffset()}rem`;
currentNodeLabel.current.style.paddingInlineStart = `${calcOffset()}rem`;
}
if (!enableTreeviewControllable) {
// sync props and state
setExpanded(isExpanded);
}
}, [
children,
depth,
Icon,
isExpanded,
enableTreeviewControllable,
setExpanded,
]);
const treeNodeProps = {
...rest,
['aria-current']: isActive || null,
['aria-selected']: disabled ? null : isSelected,
['aria-disabled']: disabled,
className: treeNodeClasses,
id,
onBlur: handleFocusEvent,
onClick: handleClick,
onFocus: handleFocusEvent,
onKeyDown: handleKeyDown,
ref: currentNode,
role: 'treeitem',
};
if (!children) {
return (
<li {...treeNodeProps}>
<div className={`${prefix}--tree-node__label`} ref={currentNodeLabel}>
{Icon && <Icon className={`${prefix}--tree-node__icon`} />}
{label}
</div>
</li>
);
}
return (
// eslint-disable-next-line jsx-a11y/role-supports-aria-props
<li {...treeNodeProps} aria-expanded={!!expanded} ref={ref}>
<div className={`${prefix}--tree-node__label`} ref={currentNodeLabel}>
{/* https://github.com/carbon-design-system/carbon/pull/6008#issuecomment-675738670 */}
{/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
<span
className={`${prefix}--tree-parent-node__toggle`}
disabled={disabled}
onClick={handleToggleClick}>
<CaretDown className={toggleClasses} />
</span>
<span className={`${prefix}--tree-node__label__details`}>
{Icon && <Icon className={`${prefix}--tree-node__icon`} />}
{label}
</span>
</div>
{expanded && (
<ul role="group" className={`${prefix}--tree-node__children`}>
{nodesWithProps}
</ul>
)}
</li>
);
}
);
TreeNode.propTypes = {
/**
* **Note:** this is controlled by the parent TreeView component, do not set manually.
* The ID of the active node in the tree
*/
active: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Specify the children of the TreeNode
*/
children: PropTypes.node,
/**
* Specify an optional className to be applied to the TreeNode
*/
className: PropTypes.string,
/**
* **[Experimental]** The default expansion state of the node.
* *This is only supported with the `enable-treeview-controllable` feature flag!*
*/
defaultIsExpanded: PropTypes.bool,
/**
* **Note:** this is controlled by the parent TreeView component, do not set manually.
* TreeNode depth to determine spacing
*/
depth: PropTypes.number,
/**
* Specify if the TreeNode is disabled
*/
disabled: PropTypes.bool,
/**
* Specify the TreeNode's ID. Must be unique in the DOM and is used for props.active and props.selected
*/
id: PropTypes.string,
/**
* Specify if the TreeNode is expanded (only applicable to parent nodes)
*/
isExpanded: PropTypes.bool,
/**
* Rendered label for the TreeNode
*/
label: PropTypes.node,
/**
* Callback function for when the node receives or loses focus
*/
onNodeFocusEvent: PropTypes.func,
/**
* Callback function for when the node is selected
*/
onSelect: PropTypes.func,
/**
* Callback function for when a parent node is expanded or collapsed
*/
onToggle: PropTypes.func,
/**
* Callback function for when any node in the tree is selected
*/
onTreeSelect: PropTypes.func,
/**
* Optional prop to allow each node to have an associated icon.
* Can be a React component class
*/
renderIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
/**
* **Note:** this is controlled by the parent TreeView component, do not set manually.
* Array containing all selected node IDs in the tree
*/
selected: PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.string, PropTypes.number])
),
/**
* Specify the value of the TreeNode
*/
value: PropTypes.string,
};
TreeNode.displayName = 'TreeNode';
export default TreeNode;