@react-spectrum/tree 3.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,361 @@
1
+ /*
2
+ * Copyright 2024 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import {AriaTreeGridListProps} from '@react-aria/tree';
14
+ import {ButtonContext, Collection, TreeItemContentRenderProps, TreeItemProps, TreeItemRenderProps, TreeRenderProps, UNSTABLE_Tree, UNSTABLE_TreeItem, UNSTABLE_TreeItemContent, useContextProps} from 'react-aria-components';
15
+ import {Checkbox} from '@react-spectrum/checkbox';
16
+ import ChevronLeftMedium from '@spectrum-icons/ui/ChevronLeftMedium';
17
+ import ChevronRightMedium from '@spectrum-icons/ui/ChevronRightMedium';
18
+ import {DOMRef, Expandable, Key, SelectionBehavior, SpectrumSelectionProps, StyleProps} from '@react-types/shared';
19
+ import {isAndroid} from '@react-aria/utils';
20
+ import React, {createContext, isValidElement, ReactElement, ReactNode, useContext, useRef} from 'react';
21
+ import {SlotProvider, useDOMRef, useStyleProps} from '@react-spectrum/utils';
22
+ import {style} from '@react-spectrum/style-macro-s1' with {type: 'macro'};
23
+ import {Text} from '@react-spectrum/text';
24
+ import {useButton} from '@react-aria/button';
25
+ import {useLocale} from '@react-aria/i18n';
26
+
27
+ export interface SpectrumTreeViewProps<T> extends Omit<AriaTreeGridListProps<T>, 'children'>, StyleProps, SpectrumSelectionProps, Expandable {
28
+ /** Provides content to display when there are no items in the tree. */
29
+ renderEmptyState?: () => JSX.Element,
30
+ /**
31
+ * Handler that is called when a user performs an action on an item. The exact user event depends on
32
+ * the collection's `selectionStyle` prop and the interaction modality.
33
+ */
34
+ onAction?: (key: Key) => void,
35
+ /**
36
+ * The contents of the tree.
37
+ */
38
+ children?: ReactNode | ((item: T) => ReactNode)
39
+ }
40
+
41
+ export interface SpectrumTreeViewItemProps extends Omit<TreeItemProps, 'className' | 'style' | 'value'> {
42
+ /** Rendered contents of the tree item or child items. */
43
+ children: ReactNode,
44
+ /** Whether this item has children, even if not loaded yet. */
45
+ hasChildItems?: boolean
46
+ }
47
+
48
+ interface TreeRendererContextValue {
49
+ renderer?: (item) => React.ReactElement<any, string | React.JSXElementConstructor<any>>
50
+ }
51
+ const TreeRendererContext = createContext<TreeRendererContextValue>({});
52
+
53
+ function useTreeRendererContext(): TreeRendererContextValue {
54
+ return useContext(TreeRendererContext)!;
55
+ }
56
+
57
+ // TODO: add animations for rows appearing and disappearing
58
+
59
+ // TODO: the below is needed so the borders of the top and bottom row isn't cut off if the TreeView is wrapped within a container by always reserving the 2px needed for the
60
+ // keyboard focus ring. Perhaps find a different way of rendering the outlines since the top of the item doesn't
61
+ // scroll into view due to how the ring is offset. Alternatively, have the tree render the top/bottom outline like it does in Listview
62
+ const tree = style<Pick<TreeRenderProps, 'isEmpty'>>({
63
+ borderWidth: 2,
64
+ boxSizing: 'border-box',
65
+ borderXWidth: 0,
66
+ borderStyle: 'solid',
67
+ borderColor: {
68
+ default: 'transparent',
69
+ forcedColors: 'Background'
70
+ },
71
+ justifyContent: {
72
+ isEmpty: 'center'
73
+ },
74
+ alignItems: {
75
+ isEmpty: 'center'
76
+ },
77
+ width: {
78
+ isEmpty: 'full'
79
+ },
80
+ height: {
81
+ isEmpty: 'full'
82
+ },
83
+ display: {
84
+ isEmpty: 'flex'
85
+ }
86
+ });
87
+
88
+ function TreeView<T extends object>(props: SpectrumTreeViewProps<T>, ref: DOMRef<HTMLDivElement>) {
89
+ let {children, selectionStyle} = props;
90
+
91
+ let renderer;
92
+ if (typeof children === 'function') {
93
+ renderer = children;
94
+ }
95
+
96
+ let {styleProps} = useStyleProps(props);
97
+ let domRef = useDOMRef(ref);
98
+ let selectionBehavior = selectionStyle === 'highlight' ? 'replace' : 'toggle';
99
+
100
+ return (
101
+ <TreeRendererContext.Provider value={{renderer}}>
102
+ <UNSTABLE_Tree {...props} {...styleProps} className={({isEmpty}) => tree({isEmpty})} selectionBehavior={selectionBehavior as SelectionBehavior} ref={domRef}>
103
+ {props.children}
104
+ </UNSTABLE_Tree>
105
+ </TreeRendererContext.Provider>
106
+ );
107
+ }
108
+
109
+ interface TreeRowRenderProps extends TreeItemRenderProps {
110
+ isLink?: boolean
111
+ }
112
+
113
+ const treeRow = style<TreeRowRenderProps>({
114
+ position: 'relative',
115
+ display: 'flex',
116
+ height: 10,
117
+ width: 'full',
118
+ boxSizing: 'border-box',
119
+ fontSize: 'base',
120
+ fontWeight: 'normal',
121
+ lineHeight: 200,
122
+ color: 'body',
123
+ outlineStyle: 'none',
124
+ cursor: {
125
+ default: 'default',
126
+ isLink: 'pointer'
127
+ },
128
+ // TODO: not sure where to get the equivalent colors here, for instance isHovered is spectrum 600 with 10% opacity but I don't think that exists in the theme
129
+ backgroundColor: {
130
+ isHovered: '[var(--spectrum-table-row-background-color-hover)]',
131
+ isFocusVisibleWithin: '[var(--spectrum-table-row-background-color-hover)]',
132
+ isPressed: '[var(--spectrum-table-row-background-color-down)]',
133
+ isSelected: '[var(--spectrum-table-row-background-color-selected)]'
134
+ }
135
+ });
136
+
137
+ const treeCellGrid = style({
138
+ display: 'grid',
139
+ width: 'full',
140
+ alignItems: 'center',
141
+ // TODO: needed to use spectrum var since gridTemplateColumns uses baseSizing and not scaled sizing
142
+ gridTemplateColumns: ['minmax(0, auto)', 'minmax(0, auto)', 'minmax(0, auto)', 'var(--spectrum-global-dimension-size-500)', 'minmax(0, auto)', '1fr', 'minmax(0, auto)', 'auto'],
143
+ gridTemplateRows: '1fr',
144
+ gridTemplateAreas: [
145
+ 'drag-handle checkbox level-padding expand-button icon content actions actionmenu'
146
+ ],
147
+ color: {
148
+ isDisabled: {
149
+ default: 'gray-400',
150
+ forcedColors: 'GrayText'
151
+ }
152
+ }
153
+ });
154
+
155
+ // TODO: These styles lose against the spectrum class names, so I've did unsafe for the ones that get overridden
156
+ const treeCheckbox = style({
157
+ gridArea: 'checkbox',
158
+ transitionDuration: '160ms',
159
+ marginStart: 3,
160
+ marginEnd: 0
161
+ });
162
+
163
+ const treeIcon = style({
164
+ gridArea: 'icon',
165
+ marginEnd: 2
166
+ });
167
+
168
+ const treeContent = style<Pick<TreeItemContentRenderProps, 'isDisabled'>>({
169
+ gridArea: 'content',
170
+ textOverflow: 'ellipsis',
171
+ whiteSpace: 'nowrap',
172
+ overflow: 'hidden'
173
+ });
174
+
175
+ const treeActions = style({
176
+ gridArea: 'actions',
177
+ flexGrow: 0,
178
+ flexShrink: 0,
179
+ /* TODO: I made this one up, confirm desired behavior. These paddings are to make sure the action group has enough padding for the focus ring */
180
+ marginStart: .5,
181
+ marginEnd: 1
182
+ });
183
+
184
+ const treeActionMenu = style({
185
+ gridArea: 'actionmenu',
186
+ width: 8
187
+ });
188
+
189
+ const treeRowOutline = style({
190
+ content: '',
191
+ display: 'block',
192
+ position: 'absolute',
193
+ insetStart: 0,
194
+ insetEnd: 0,
195
+ top: {
196
+ default: 0,
197
+ isFocusVisible: '[-2px]',
198
+ isSelected: {
199
+ default: '[-1px]',
200
+ isFocusVisible: '[-2px]'
201
+ }
202
+ },
203
+ bottom: 0,
204
+ pointerEvents: 'none',
205
+ forcedColorAdjust: 'none',
206
+
207
+ boxShadow: {
208
+ isFocusVisible: '[inset 2px 0 0 0 var(--spectrum-alias-focus-color), inset -2px 0 0 0 var(--spectrum-alias-focus-color), inset 0 -2px 0 0 var(--spectrum-alias-focus-color), inset 0 2px 0 0 var(--spectrum-alias-focus-color)]',
209
+ isSelected: {
210
+ default: '[inset 1px 0 0 0 var(--spectrum-alias-focus-color), inset -1px 0 0 0 var(--spectrum-alias-focus-color), inset 0 -1px 0 0 var(--spectrum-alias-focus-color), inset 0 1px 0 0 var(--spectrum-alias-focus-color)]',
211
+ isFocusVisible: '[inset 2px 0 0 0 var(--spectrum-alias-focus-color), inset -2px 0 0 0 var(--spectrum-alias-focus-color), inset 0 -2px 0 0 var(--spectrum-alias-focus-color), inset 0 2px 0 0 var(--spectrum-alias-focus-color)]'
212
+ },
213
+ forcedColors: {
214
+ isFocusVisible: '[inset 2px 0 0 0 Highlight, inset -2px 0 0 0 Highlight, inset 0 -2px 0 0 Highlight, inset 0 2px 0 0 Highlight]',
215
+ isSelected: {
216
+ default: '[inset 1px 0 0 0 Highlight, inset -1px 0 0 0 Highlight, inset 0 -1px 0 0 Highlight, inset 0 1px 0 0 Highlight]',
217
+ isFocusVisible: '[inset 2px 0 0 0 Highlight, inset -2px 0 0 0 Highlight, inset 0 -2px 0 0 Highlight, inset 0 2px 0 0 Highlight]'
218
+ }
219
+ }
220
+ }
221
+ });
222
+
223
+ export const TreeViewItem = (props: SpectrumTreeViewItemProps) => {
224
+ let {
225
+ children,
226
+ childItems,
227
+ hasChildItems,
228
+ href
229
+ } = props;
230
+
231
+ let content;
232
+ let nestedRows;
233
+ let {renderer} = useTreeRendererContext();
234
+ // TODO alternative api is that we have a separate prop for the TreeItems contents and expect the child to then be
235
+ // a nested tree item
236
+
237
+ if (typeof children === 'string') {
238
+ content = <Text>{children}</Text>;
239
+ } else {
240
+ content = [];
241
+ nestedRows = [];
242
+ React.Children.forEach(children, node => {
243
+ if (isValidElement(node) && node.type === TreeViewItem) {
244
+ nestedRows.push(node);
245
+ } else {
246
+ content.push(node);
247
+ }
248
+ });
249
+ }
250
+
251
+ if (childItems != null && renderer) {
252
+ nestedRows = (
253
+ <Collection items={childItems}>
254
+ {renderer}
255
+ </Collection>
256
+ );
257
+ }
258
+
259
+ return (
260
+ // TODO right now all the tree rows have the various data attributes applied on their dom nodes, should they? Doesn't feel very useful
261
+ <UNSTABLE_TreeItem
262
+ {...props}
263
+ className={renderProps => treeRow({
264
+ ...renderProps,
265
+ isLink: !!href
266
+ })}>
267
+ <UNSTABLE_TreeItemContent>
268
+ {({isExpanded, hasChildRows, level, selectionMode, selectionBehavior, isDisabled, isSelected, isFocusVisible}) => (
269
+ <div className={treeCellGrid({isDisabled})}>
270
+ {selectionMode !== 'none' && selectionBehavior === 'toggle' && (
271
+ // TODO: add transition?
272
+ <Checkbox
273
+ isEmphasized
274
+ UNSAFE_className={treeCheckbox()}
275
+ UNSAFE_style={{paddingInlineEnd: '0px'}}
276
+ slot="selection" />
277
+ )}
278
+ <div style={{gridArea: 'level-padding', marginInlineEnd: `calc(${level - 1} * var(--spectrum-global-dimension-size-200))`}} />
279
+ {/* TODO: revisit when we do async loading, at the moment hasChildItems will only cause the chevron to be rendered, no aria/data attributes indicating the row's expandability are added */}
280
+ {(hasChildRows || hasChildItems) && <ExpandableRowChevron isDisabled={isDisabled} isExpanded={isExpanded} />}
281
+ <SlotProvider
282
+ slots={{
283
+ text: {UNSAFE_className: treeContent({isDisabled})},
284
+ // Note there is also an issue here where these icon props are making into the action menu's icon. Resolved by 8ab0ffb276ff437a65b365c9a3be0323a1b24656
285
+ // but could crop up later for other components
286
+ icon: {UNSAFE_className: treeIcon(), size: 'S'},
287
+ actionButton: {UNSAFE_className: treeActions(), isQuiet: true},
288
+ actionGroup: {
289
+ UNSAFE_className: treeActions(),
290
+ isQuiet: true,
291
+ density: 'compact',
292
+ buttonLabelBehavior: 'hide',
293
+ isDisabled,
294
+ overflowMode: 'collapse'
295
+ },
296
+ actionMenu: {UNSAFE_className: treeActionMenu(), UNSAFE_style: {marginInlineEnd: '.5rem'}, isQuiet: true}
297
+ }}>
298
+ {content}
299
+ </SlotProvider>
300
+ <div className={treeRowOutline({isFocusVisible, isSelected})} />
301
+ </div>
302
+ )}
303
+ </UNSTABLE_TreeItemContent>
304
+ {nestedRows}
305
+ </UNSTABLE_TreeItem>
306
+ );
307
+ };
308
+
309
+ interface ExpandableRowChevronProps {
310
+ isExpanded?: boolean,
311
+ isDisabled?: boolean,
312
+ isRTL?: boolean
313
+ }
314
+
315
+ const expandButton = style<ExpandableRowChevronProps>({
316
+ gridArea: 'expand-button',
317
+ height: 'full',
318
+ aspectRatio: 'square',
319
+ display: 'flex',
320
+ flexWrap: 'wrap',
321
+ alignContent: 'center',
322
+ justifyContent: 'center',
323
+ outlineStyle: 'none',
324
+ transform: {
325
+ isExpanded: {
326
+ default: 'rotate(90deg)',
327
+ isRTL: 'rotate(-90deg)'
328
+ }
329
+ },
330
+ transition: '[transform ease var(--spectrum-global-animation-duration-100)]'
331
+ });
332
+
333
+ function ExpandableRowChevron(props: ExpandableRowChevronProps) {
334
+ let expandButtonRef = useRef();
335
+ let [fullProps, ref] = useContextProps({...props, slot: 'chevron'}, expandButtonRef, ButtonContext);
336
+ let {isExpanded, isDisabled} = fullProps;
337
+ let {direction} = useLocale();
338
+
339
+ // Will need to keep the chevron as a button for iOS VO at all times since VO doesn't focus the cell. Also keep as button if cellAction is defined by the user in the future
340
+ let {buttonProps} = useButton({
341
+ ...fullProps,
342
+ elementType: 'span'
343
+ }, ref);
344
+
345
+ return (
346
+ <span
347
+ {...buttonProps}
348
+ ref={ref}
349
+ // Override tabindex so that grid keyboard nav skips over it. Needs -1 so android talkback can actually "focus" it
350
+ tabIndex={isAndroid() && !isDisabled ? -1 : undefined}
351
+ className={expandButton({isExpanded, isDisabled, isRTL: direction === 'rtl'})}>
352
+ {direction === 'ltr' ? <ChevronRightMedium /> : <ChevronLeftMedium />}
353
+ </span>
354
+ );
355
+ }
356
+
357
+ /**
358
+ * A tree view provides users with a way to navigate nested hierarchical information.
359
+ */
360
+ const _TreeView = React.forwardRef(TreeView) as <T>(props: SpectrumTreeViewProps<T> & {ref?: DOMRef<HTMLDivElement>}) => ReactElement;
361
+ export {_TreeView as TreeView};
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ /*
2
+ * Copyright 2020 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ /// <reference types="css-module-types" />
14
+
15
+ export {TreeViewItem, TreeView} from './TreeView';
16
+ export type {SpectrumTreeViewProps, SpectrumTreeViewItemProps} from './TreeView';