Skip to content

feat: Tree multiple level loading support #8299

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1844,7 +1844,7 @@ describe('SearchAutocomplete', function () {
expect(() => within(tray).getByText('No results')).toThrow();
});

it.skip('user can select options by pressing them', async function () {
it('user can select options by pressing them', async function () {
let {getByRole, getByText, getByTestId} = renderSearchAutocomplete();
let button = getByRole('button');

Expand Down Expand Up @@ -1892,7 +1892,7 @@ describe('SearchAutocomplete', function () {
expect(items[1]).toHaveAttribute('aria-selected', 'true');
});

it.skip('user can select options by focusing them and hitting enter', async function () {
it('user can select options by focusing them and hitting enter', async function () {
let {getByRole, getByText, getByTestId} = renderSearchAutocomplete();
let button = getByRole('button');

Expand Down
39 changes: 23 additions & 16 deletions packages/@react-stately/layout/src/ListLayout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,41 +253,48 @@ export class ListLayout<T, O extends ListLayoutOptions = ListLayoutOptions> exte

protected buildCollection(y = this.padding): LayoutNode[] {
let collection = this.virtualizer!.collection;
let skipped = 0;
let collectionNodes = [...collection];
let loaderNodes = collectionNodes.filter(node => node.type === 'loader');
let nodes: LayoutNode[] = [];
let isEmptyOrLoading = collection?.size === 0 || (collection.size === 1 && collection.getItem(collection.getFirstKey()!)!.type === 'loader');

let isEmptyOrLoading = collection?.size === 0 || !collectionNodes.some(item => item.type !== 'loader');
if (isEmptyOrLoading) {
y = 0;
}

for (let node of collection) {
for (let node of collectionNodes) {
let rowHeight = (this.rowHeight ?? this.estimatedRowHeight ?? DEFAULT_HEIGHT) + this.gap;
// Skip rows before the valid rectangle unless they are already cached.
if (node.type === 'item' && y + rowHeight < this.requestedRect.y && !this.isValid(node, y)) {
y += rowHeight;
skipped++;
continue;
}

let layoutNode = this.buildChild(node, this.padding, y, null);
y = layoutNode.layoutInfo.rect.maxY + this.gap;
nodes.push(layoutNode);
if (node.type === 'item' && y > this.requestedRect.maxY) {
let itemsAfterRect = collection.size - (nodes.length + skipped);
let lastNode = collection.getItem(collection.getLastKey()!);
if (lastNode?.type === 'loader') {
itemsAfterRect--;
}

y += itemsAfterRect * rowHeight;
if (node.type === 'loader') {
let index = loaderNodes.indexOf(node);
loaderNodes.splice(index, 1);
}

// Always add the loader sentinel if present. This assumes the loader is the last option/row
// will need to refactor when handling multi section loading
if (lastNode?.type === 'loader' && nodes.at(-1)?.layoutInfo.type !== 'loader') {
let loader = this.buildChild(lastNode, this.padding, y, null);
// Build each loader that exists in the collection that is outside the visible rect so that they are persisted
// at the proper estimated location. If the node.type is "section" then we don't do this shortcut since we have to
// build the sections to see how tall they are.
if ((node.type === 'item' || node.type === 'loader') && y > this.requestedRect.maxY) {
let lastProcessedIndex = collectionNodes.indexOf(node);
for (let loaderNode of loaderNodes) {
let loaderNodeIndex = collectionNodes.indexOf(loaderNode);
// Subtract by an additional 1 since we've already added the current item's height to y
y += (loaderNodeIndex - lastProcessedIndex - 1) * rowHeight;
let loader = this.buildChild(loaderNode, this.padding, y, null);
nodes.push(loader);
y = loader.layoutInfo.rect.maxY;
lastProcessedIndex = loaderNodeIndex;
}

// Account for the rest of the items after the last loader spinner, subtract by 1 since we've processed the current node's height already
y += (collectionNodes.length - lastProcessedIndex - 1) * rowHeight;
break;
}
}
Expand Down
9 changes: 7 additions & 2 deletions packages/@react-stately/tree/src/useTreeState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,13 @@ export function useTreeState<T extends object>(props: TreeProps<T>): TreeState<T

// Reset focused key if that item is deleted from the collection.
useEffect(() => {
if (selectionState.focusedKey != null && !tree.getItem(selectionState.focusedKey)) {
selectionState.setFocusedKey(null);
if (selectionState.focusedKey != null) {
let focusedItem = tree.getItem(selectionState.focusedKey);
// TODO: do we want to have the same logic as useListState/useGridState where it tries to find the nearest row?
// We could possibly special case this loader case and have it try to find the item just before it/the parent
if (!focusedItem || focusedItem.type === 'loader' && !focusedItem.props.isLoading) {
selectionState.setFocusedKey(null);
}
Comment on lines +69 to +74
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For now I've preserved the previous behavior of just focusing the tree if the loader disappears, but ideally we'd do something like useListState and useGridState where it looks for the closest focusable row as a substitute. Will handle that update upon refactoring some of that logic as noted in https://github.com/adobe/react-spectrum/pull/8326/files#r2116825740

}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tree, selectionState.focusedKey]);
Expand Down
71 changes: 50 additions & 21 deletions packages/react-aria-components/src/Tree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {DisabledBehavior, DragPreviewRenderer, Expandable, forwardRefType, Hover
import {DragAndDropContext, DropIndicatorContext, useDndPersistedKeys, useRenderDropIndicator} from './DragAndDrop';
import {DragAndDropHooks} from './useDragAndDrop';
import {DraggableCollectionState, DroppableCollectionState, Collection as ICollection, Node, SelectionBehavior, TreeState, useTreeState} from 'react-stately';
import {filterDOMProps, useObjectRef} from '@react-aria/utils';
import {filterDOMProps, inertValue, LoadMoreSentinelProps, UNSTABLE_useLoadMoreSentinel, useObjectRef} from '@react-aria/utils';
import React, {createContext, ForwardedRef, forwardRef, JSX, ReactNode, useContext, useEffect, useMemo, useRef} from 'react';
import {useControlledState} from '@react-stately/utils';

Expand Down Expand Up @@ -699,18 +699,39 @@ export const TreeItem = /*#__PURE__*/ createBranchComponent('item', <T extends o
);
});

export interface UNSTABLE_TreeLoadingIndicatorRenderProps extends Pick<TreeItemRenderProps, 'isFocused' | 'isFocusVisible'> {
export interface UNSTABLE_TreeLoadingSentinelRenderProps extends Pick<TreeItemRenderProps, 'isFocused' | 'isFocusVisible'> {
/**
* What level the tree item has within the tree.
* @selector [data-level]
*/
level: number
}

export interface TreeLoaderProps extends RenderProps<UNSTABLE_TreeLoadingIndicatorRenderProps>, StyleRenderProps<UNSTABLE_TreeLoadingIndicatorRenderProps> {}
export interface TreeLoadingSentinelProps extends Omit<LoadMoreSentinelProps, 'collection'>, RenderProps<UNSTABLE_TreeLoadingSentinelRenderProps> {
/**
* The load more spinner to render when loading additional items.
*/
children?: ReactNode | ((values: UNSTABLE_TreeLoadingSentinelRenderProps & {defaultChildren: ReactNode | undefined}) => ReactNode),
/**
* Whether or not the loading spinner should be rendered or not.
*/
isLoading?: boolean
}

export const UNSTABLE_TreeLoadingIndicator = createLeafComponent('loader', function TreeLoader<T extends object>(props: TreeLoaderProps, ref: ForwardedRef<HTMLDivElement>, item: Node<T>) {
export const UNSTABLE_TreeLoadingSentinel = createLeafComponent('loader', function TreeLoadingSentinel<T extends object>(props: TreeLoadingSentinelProps, ref: ForwardedRef<HTMLDivElement>, item: Node<T>) {
let state = useContext(TreeStateContext)!;
let {isLoading, onLoadMore, scrollOffset, ...otherProps} = props;
let sentinelRef = useRef(null);
let memoedLoadMoreProps = useMemo(() => ({
onLoadMore,
// TODO: this collection will update anytime a row is expanded/collapsed becaused the flattenedRows will change.
// This means onLoadMore will trigger but that might be ok cause the user should have logic to handle multiple loadMore calls
collection: state?.collection,
Comment on lines +725 to +729
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

think this should be ok, but open to discuss

sentinelRef,
scrollOffset
}), [onLoadMore, scrollOffset, state?.collection]);
UNSTABLE_useLoadMoreSentinel(memoedLoadMoreProps, sentinelRef);

ref = useObjectRef<HTMLDivElement>(ref);
let {rowProps, gridCellProps, ...states} = useTreeItem({node: item}, state, ref);
let level = rowProps['aria-level'] || 1;
Expand All @@ -726,7 +747,7 @@ export const UNSTABLE_TreeLoadingIndicator = createLeafComponent('loader', funct
let {isFocusVisible, focusProps} = useFocusRing();

let renderProps = useRenderProps({
...props,
...otherProps,
id: undefined,
children: item.rendered,
defaultClassName: 'react-aria-TreeLoader',
Expand All @@ -739,19 +760,26 @@ export const UNSTABLE_TreeLoadingIndicator = createLeafComponent('loader', funct

return (
<>
<div
ref={ref}
{...mergeProps(filterDOMProps(props as any), ariaProps, focusProps)}
{...renderProps}
data-key={rowProps['data-key']}
data-collection={rowProps['data-collection']}
data-focused={states.isFocused || undefined}
data-focus-visible={isFocusVisible || undefined}
data-level={level}>
<div {...gridCellProps}>
{renderProps.children}
</div>
{/* Alway render the sentinel. For now onus is on the user for styling when using flex + gap (this would introduce a gap even though it doesn't take room) */}
{/* @ts-ignore - compatibility with React < 19 */}
<div style={{position: 'relative', width: 0, height: 0}} inert={inertValue(true)} >
<div data-testid="loadMoreSentinel" ref={sentinelRef} style={{position: 'absolute', height: 1, width: 1}} />
</div>
{isLoading && renderProps.children && (
<div
ref={ref}
{...mergeProps(filterDOMProps(props as any), ariaProps, focusProps)}
{...renderProps}
data-key={rowProps['data-key']}
data-collection={rowProps['data-collection']}
data-focused={states.isFocused || undefined}
data-focus-visible={isFocusVisible || undefined}
data-level={level}>
<div {...gridCellProps}>
{renderProps.children}
</div>
</div>
)}
</>
);
});
Expand Down Expand Up @@ -804,9 +832,10 @@ function flattenTree<T>(collection: TreeCollection<T>, opts: TreeGridCollectionO
keyMap.set(node.key, node as CollectionNode<T>);
}

if (node.level === 0 || (parentKey != null && expandedKeys.has(parentKey) && flattenedRows.find(row => row.key === parentKey))) {
// Grab the modified node from the key map so our flattened list and modified key map point to the same nodes
flattenedRows.push(keyMap.get(node.key) || node);
// Grab the modified node from the key map so our flattened list and modified key map point to the same nodes
let modifiedNode = keyMap.get(node.key) || node;
if (modifiedNode.level === 0 || (modifiedNode.parentKey != null && expandedKeys.has(modifiedNode.parentKey) && flattenedRows.find(row => row.key === modifiedNode.parentKey))) {
flattenedRows.push(modifiedNode);
}
} else if (node.type !== null) {
keyMap.set(node.key, node as CollectionNode<T>);
Expand Down Expand Up @@ -844,7 +873,7 @@ function TreeDropIndicatorWrapper(props: DropIndicatorProps, ref: ForwardedRef<H
let level = dropState && props.target.type === 'item' ? (dropState.collection.getItem(props.target.key)?.level || 0) + 1 : 1;

return (
<TreeDropIndicatorForwardRef
<TreeDropIndicatorForwardRef
{...props}
dropIndicatorProps={dropIndicatorProps}
isDropTarget={isDropTarget}
Expand Down
2 changes: 1 addition & 1 deletion packages/react-aria-components/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export {ToggleButton, ToggleButtonContext} from './ToggleButton';
export {ToggleButtonGroup, ToggleButtonGroupContext, ToggleGroupStateContext} from './ToggleButtonGroup';
export {Toolbar, ToolbarContext} from './Toolbar';
export {TooltipTrigger, Tooltip, TooltipTriggerStateContext, TooltipContext} from './Tooltip';
export {UNSTABLE_TreeLoadingIndicator, Tree, TreeItem, TreeContext, TreeItemContent, TreeStateContext} from './Tree';
export {UNSTABLE_TreeLoadingSentinel, Tree, TreeItem, TreeContext, TreeItemContent, TreeStateContext} from './Tree';
export {useDragAndDrop} from './useDragAndDrop';
export {DropIndicator, DropIndicatorContext, DragAndDropContext} from './DragAndDrop';
export {Virtualizer} from './Virtualizer';
Expand Down
Loading