Skip to content

(WIP) Tree multiple loader 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

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 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
36 changes: 21 additions & 15 deletions packages/@react-stately/layout/src/ListLayout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,11 @@ 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;
}
Expand All @@ -265,29 +267,33 @@ export class ListLayout<T, O extends ListLayoutOptions = ListLayoutOptions> exte
// 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 (y > this.requestedRect.maxY) {
let lastProcessedIndex = collectionNodes.indexOf(node);
for (let loaderNode of loaderNodes) {
let loaderNodeIndex = collectionNodes.indexOf(loaderNode);
// Subtract by an addition 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
63 changes: 46 additions & 17 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 @@ -678,18 +678,39 @@ export const TreeItem = /*#__PURE__*/ createBranchComponent('item', <T extends o
);
});

export interface UNSTABLE_TreeLoadingIndicatorRenderProps {
export interface UNSTABLE_TreeLoadingSentinelRenderProps {
/**
* 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,
sentinelRef,
scrollOffset
}), [onLoadMore, scrollOffset, state?.collection]);
UNSTABLE_useLoadMoreSentinel(memoedLoadMoreProps, sentinelRef);

// This loader row is is non-interactable, but we want the same aria props calculated as a typical row
// @ts-ignore
let {rowProps} = useTreeItem({node: item}, state, ref);
Expand All @@ -702,7 +723,7 @@ export const UNSTABLE_TreeLoadingIndicator = createLeafComponent('loader', funct
};

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

return (
<>
<div
role="row"
ref={ref}
{...mergeProps(filterDOMProps(props as any), ariaProps)}
{...renderProps}
data-level={level}>
<div role="gridcell" aria-colindex={1}>
{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
{...mergeProps(filterDOMProps(props as any), ariaProps)}
{...renderProps}
role="row"
ref={ref}
data-level={level}>
<div role="gridcell" aria-colindex={1}>
{renderProps.children}
</div>
</div>
)}
</>
);
});
Expand Down Expand Up @@ -775,9 +803,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
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