Skip to content

Refactor Virtualizer to improve performance, stability, and complexity #6451

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

Merged
merged 3 commits into from
Jun 3, 2024
Merged
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
"@babel/preset-react": "^7.24.1",
"@babel/preset-typescript": "^7.24.1",
"@babel/register": "^7.23.7",
"@faker-js/faker": "^8.4.1",
"@octokit/rest": "*",
"@parcel/bundler-library": "2.11.1-dev.3224",
"@parcel/optimizer-data-url": "2.0.0-dev.1601",
Expand Down
32 changes: 28 additions & 4 deletions packages/@react-aria/focus/src/FocusScope.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ interface IFocusContext {
}

const FocusContext = React.createContext<IFocusContext | null>(null);
const RESTORE_FOCUS_EVENT = 'react-aria-focus-scope-restore';

let activeScope: ScopeRef = null;

Expand Down Expand Up @@ -117,12 +118,21 @@ export function FocusScope(props: FocusScopeProps) {
// Find all rendered nodes between the sentinels and add them to the scope.
let node = startRef.current?.nextSibling!;
let nodes: Element[] = [];
let stopPropagation = e => e.stopPropagation();
while (node && node !== endRef.current) {
nodes.push(node as Element);
// Stop custom restore focus event from propagating to parent focus scopes.
node.addEventListener(RESTORE_FOCUS_EVENT, stopPropagation);
node = node.nextSibling as Element;
}

scopeRef.current = nodes;

return () => {
for (let node of nodes) {
node.removeEventListener(RESTORE_FOCUS_EVENT, stopPropagation);
}
};
}, [children]);

useActiveScopeTracker(scopeRef, restoreFocus, contain);
Expand Down Expand Up @@ -470,7 +480,7 @@ function focusElement(element: FocusableElement | null, scroll = false) {
}
}

function focusFirstInScope(scope: Element[], tabbable:boolean = true) {
function getFirstInScope(scope: Element[], tabbable = true) {
let sentinel = scope[0].previousElementSibling!;
let scopeRoot = getScopeRoot(scope);
let walker = getFocusableTreeWalker(scopeRoot, {tabbable}, scope);
Expand All @@ -485,7 +495,11 @@ function focusFirstInScope(scope: Element[], tabbable:boolean = true) {
nextNode = walker.nextNode();
}

focusElement(nextNode as FocusableElement);
return nextNode as FocusableElement;
}

function focusFirstInScope(scope: Element[], tabbable:boolean = true) {
focusElement(getFirstInScope(scope, tabbable));
}

function useAutoFocus(scopeRef: RefObject<Element[]>, autoFocus?: boolean) {
Expand Down Expand Up @@ -692,7 +706,7 @@ function useRestoreFocus(scopeRef: RefObject<Element[]>, restoreFocus?: boolean,
let treeNode = clonedTree.getTreeNode(scopeRef);
while (treeNode) {
if (treeNode.nodeToRestore && treeNode.nodeToRestore.isConnected) {
focusElement(treeNode.nodeToRestore);
restoreFocusToElement(treeNode.nodeToRestore);
return;
}
treeNode = treeNode.parent;
Expand All @@ -703,7 +717,8 @@ function useRestoreFocus(scopeRef: RefObject<Element[]>, restoreFocus?: boolean,
treeNode = clonedTree.getTreeNode(scopeRef);
while (treeNode) {
if (treeNode.scopeRef && treeNode.scopeRef.current && focusScopeTree.getTreeNode(treeNode.scopeRef)) {
focusFirstInScope(treeNode.scopeRef.current, true);
let node = getFirstInScope(treeNode.scopeRef.current, true);
restoreFocusToElement(node);
return;
}
treeNode = treeNode.parent;
Expand All @@ -715,6 +730,15 @@ function useRestoreFocus(scopeRef: RefObject<Element[]>, restoreFocus?: boolean,
}, [scopeRef, restoreFocus]);
}

function restoreFocusToElement(node: FocusableElement) {
// Dispatch a custom event that parent elements can intercept to customize focus restoration.
// For example, virtualized collection components reuse DOM elements, so the original element
// might still exist in the DOM but representing a different item.
if (node.dispatchEvent(new CustomEvent(RESTORE_FOCUS_EVENT, {bubbles: true, cancelable: true}))) {
Copy link
Member Author

Choose a reason for hiding this comment

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

This custom event fixes restoring focus when closing an ActionBar, which previously only worked because of the animation removing rows in TableView. Without the animation, row elements are reused to represent a different object immediately, and focus appears to be restored to the wrong item. Dispatching a custom event allows useSelectableCollection to pick this up and apply its own logic instead of the default provided by FocusScope.

focusElement(node);
}
}

/**
* Create a [TreeWalker]{@link https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker}
* that matches all focusable/tabbable elements.
Expand Down
65 changes: 65 additions & 0 deletions packages/@react-aria/focus/test/FocusScope.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {Provider} from '@react-spectrum/provider';
import React, {useEffect, useState} from 'react';
import ReactDOM from 'react-dom';
import {Example as StorybookExample} from '../stories/FocusScope.stories';
import {useEvent} from '@react-aria/utils';
import userEvent from '@testing-library/user-event';


Expand Down Expand Up @@ -764,6 +765,70 @@ describe('FocusScope', function () {
expect(document.activeElement).toBe(button2);
expect(input1).not.toBeInTheDocument();
});

it('should allow restoration to be overridden with a custom event', async function () {
function Test() {
let [show, setShow] = React.useState(false);
let ref = React.useRef(null);
useEvent(ref, 'react-aria-focus-scope-restore', e => {
e.preventDefault();
});

return (
<div ref={ref}>
<button onClick={() => setShow(true)}>Show</button>
{show && <FocusScope restoreFocus>
<input autoFocus onKeyDown={() => setShow(false)} />
</FocusScope>}
</div>
);
}

let {getByRole} = render(<Test />);
let button = getByRole('button');
await user.click(button);

let input = getByRole('textbox');
expect(document.activeElement).toBe(input);

await user.keyboard('{Escape}');
act(() => jest.runAllTimers());
expect(input).not.toBeInTheDocument();
expect(document.activeElement).toBe(document.body);
});

it('should not bubble focus scope restoration event out of nested focus scopes', async function () {
function Test() {
let [show, setShow] = React.useState(false);
let ref = React.useRef(null);
useEvent(ref, 'react-aria-focus-scope-restore', e => {
e.preventDefault();
});

return (
<div ref={ref}>
<FocusScope>
<button onClick={() => setShow(true)}>Show</button>
{show && <FocusScope restoreFocus>
<input autoFocus onKeyDown={() => setShow(false)} />
</FocusScope>}
</FocusScope>
</div>
);
}

let {getByRole} = render(<Test />);
let button = getByRole('button');
await user.click(button);

let input = getByRole('textbox');
expect(document.activeElement).toBe(input);

await user.keyboard('{Escape}');
act(() => jest.runAllTimers());
expect(input).not.toBeInTheDocument();
expect(document.activeElement).toBe(button);
});
});

describe('auto focus', function () {
Expand Down
33 changes: 22 additions & 11 deletions packages/@react-aria/selection/src/useSelectableCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ export function useSelectableCollection(options: AriaSelectableCollectionOptions
};

// Store the scroll position so we can restore it later.
/// TODO: should this happen all the time??
Copy link
Member Author

Choose a reason for hiding this comment

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

I can't remember why we did this or what it fixed. Maybe it isn't needed anymore??

Copy link
Member

Choose a reason for hiding this comment

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

Well, I thought it was for this flow:
Go to collection and focus some item
Tab out of the collection
Scroll the collection (scroll wheel or track pad, anything that doesn't put focus back into the collection)
Tab back to the collection
Focus should go to the last focused Item

It looks like it's still working if I remove it though. I thought maybe it wasn't needed anymore because persistedKeys took care of it. This code was added before persistedKeys, however, it appeared to work before as well.

Maybe @LFDanLu will remember, the only note was a comment from him referencing an issue he tried to solve previously #2233

Copy link
Member

@LFDanLu LFDanLu May 30, 2024

Choose a reason for hiding this comment

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

So you can reproduce by getting rid of the scrollPos references completely and by using the "useTable -> Scroll testing" story. Keyboard nav into the table and focus any cell that isn't in the first row, then tab out and shift tab back into the table:

Screen.Recording.2024-05-29.at.5.05.56.PM.mov

If my memory + notes on the PR serves, this is due to how focus lands on the last checkbox in the table before being marshalled to the proper tracked focused key -> causes a scroll position change in the scrollable body -> messes up scrollIntoView calculations. Think the same issue happens if shift tabbing to a previously focused table column as well

let scrollPos = useRef({top: 0, left: 0});
useEvent(scrollRef, 'scroll', isVirtualized ? null : () => {
scrollPos.current = {
Expand Down Expand Up @@ -342,7 +343,7 @@ export function useSelectableCollection(options: AriaSelectableCollectionOptions
scrollRef.current.scrollLeft = scrollPos.current.left;
}

if (!isVirtualized && manager.focusedKey != null) {
if (manager.focusedKey != null) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Was removing !isVirtualized intentional here?

Copy link
Member Author

Choose a reason for hiding this comment

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

yeah we centralized the logic between both virtualized and non-virtualized collections so now they are both handled here. was there a concern or just curious?

// Refocus and scroll the focused item into view if it exists within the scrollable region.
let element = scrollRef.current.querySelector(`[data-key="${CSS.escape(manager.focusedKey.toString())}"]`) as HTMLElement;
if (element) {
Expand Down Expand Up @@ -400,17 +401,21 @@ export function useSelectableCollection(options: AriaSelectableCollectionOptions
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

// If not virtualized, scroll the focused element into view when the focusedKey changes.
// When virtualized, Virtualizer handles this internally.
// Scroll the focused element into view when the focusedKey changes.
let lastFocusedKey = useRef(manager.focusedKey);
useEffect(() => {
let modality = getInteractionModality();
if (manager.isFocused && manager.focusedKey != null && scrollRef?.current) {
let element = scrollRef.current.querySelector(`[data-key="${CSS.escape(manager.focusedKey.toString())}"]`) as HTMLElement;
if (element && (modality === 'keyboard' || autoFocusRef.current)) {
if (!isVirtualized) {
scrollIntoView(scrollRef.current, element);
}
if (manager.isFocused && manager.focusedKey != null && manager.focusedKey !== lastFocusedKey.current && scrollRef?.current) {
let modality = getInteractionModality();
let element = ref.current.querySelector(`[data-key="${CSS.escape(manager.focusedKey.toString())}"]`) as HTMLElement;
if (!element) {
// If item element wasn't found, return early (don't update autoFocusRef and lastFocusedKey).
// The collection may initially be empty (e.g. virtualizer), so wait until the element exists.
return;
}

if (modality === 'keyboard' || autoFocusRef.current) {
scrollIntoView(scrollRef.current, element);

// Avoid scroll in iOS VO, since it may cause overlay to close (i.e. RAC submenu)
if (modality !== 'virtual') {
scrollIntoViewport(element, {containingElement: ref.current});
Expand All @@ -425,7 +430,13 @@ export function useSelectableCollection(options: AriaSelectableCollectionOptions

lastFocusedKey.current = manager.focusedKey;
autoFocusRef.current = false;
}, [isVirtualized, scrollRef, manager.focusedKey, manager.isFocused, ref]);
});

// Intercept FocusScope restoration since virtualized collections can reuse DOM nodes.
useEvent(ref, 'react-aria-focus-scope-restore', e => {
e.preventDefault();
manager.setFocused(true);
});

let handlers = {
onKeyDown,
Expand Down
50 changes: 32 additions & 18 deletions packages/@react-aria/utils/src/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,40 +26,54 @@ function testPlatform(re: RegExp) {
: false;
}

export function isMac() {
return testPlatform(/^Mac/i);
function cached(fn: () => boolean) {
if (process.env.NODE_ENV === 'test') {
return fn;
}

let res: boolean | null = null;
return () => {
if (res == null) {
res = fn();
}
return res;
};
}

export function isIPhone() {
export const isMac = cached(function () {
return testPlatform(/^Mac/i);
});

export const isIPhone = cached(function () {
return testPlatform(/^iPhone/i);
}
});

export function isIPad() {
export const isIPad = cached(function () {
return testPlatform(/^iPad/i) ||
// iPadOS 13 lies and says it's a Mac, but we can distinguish by detecting touch support.
(isMac() && navigator.maxTouchPoints > 1);
}
});

export function isIOS() {
export const isIOS = cached(function () {
return isIPhone() || isIPad();
}
});

export function isAppleDevice() {
export const isAppleDevice = cached(function () {
return isMac() || isIOS();
}
});

export function isWebKit() {
export const isWebKit = cached(function () {
return testUserAgent(/AppleWebKit/i) && !isChrome();
}
});

export function isChrome() {
export const isChrome = cached(function () {
return testUserAgent(/Chrome/i);
}
});

export function isAndroid() {
export const isAndroid = cached(function () {
return testUserAgent(/Android/i);
}
});

export function isFirefox() {
export const isFirefox = cached(function () {
return testUserAgent(/Firefox/i);
}
});
2 changes: 1 addition & 1 deletion packages/@react-aria/utils/src/useEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {useEffectEvent} from './useEffectEvent';

export function useEvent<K extends keyof GlobalEventHandlersEventMap>(
ref: RefObject<EventTarget>,
event: K,
event: K | (string & {}),
handler?: (this: Document, ev: GlobalEventHandlersEventMap[K]) => any,
options?: boolean | AddEventListenerOptions
) {
Expand Down
4 changes: 2 additions & 2 deletions packages/@react-aria/virtualizer/src/ScrollView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ function ScrollView(props: ScrollViewProps, ref: RefObject<HTMLDivElement>) {
updateSize();
}, [updateSize]);
let raf = useRef<ReturnType<typeof requestAnimationFrame> | null>();
let onResize = () => {
let onResize = useCallback(() => {
if (isOldReact) {
raf.current ??= requestAnimationFrame(() => {
updateSize();
Expand All @@ -164,7 +164,7 @@ function ScrollView(props: ScrollViewProps, ref: RefObject<HTMLDivElement>) {
} else {
updateSize();
}
};
}, [updateSize]);
useResizeObserver({ref, onResize});
useEffect(() => {
return () => {
Expand Down
Loading