Skip to content
Closed
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
66 changes: 64 additions & 2 deletions packages/@react-spectrum/actionbar/src/ActionBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import {announce} from '@react-aria/live-announcer';
import {classNames, useDOMRef, useStyleProps} from '@react-spectrum/utils';
import CrossLarge from '@spectrum-icons/ui/CrossLarge';
import {DOMRef} from '@react-types/shared';
import {filterDOMProps} from '@react-aria/utils';
import {FocusScope} from '@react-aria/focus';
import {filterDOMProps, useLayoutEffect} from '@react-aria/utils';
import {focusSafely, FocusScope, getFocusableTreeWalker} from '@react-aria/focus';
// @ts-ignore
import intlMessages from '../intl/*.json';
import {OpenTransition} from '@react-spectrum/overlays';
Expand Down Expand Up @@ -82,6 +82,68 @@ const ActionBarInner = React.forwardRef((props: ActionBarInnerProps, ref: DOMRef
announce(stringFormatter.format('actionsAvailable'));
}, [stringFormatter]);

let restoreFocusRef = useRef<HTMLElement>(null);
let containerRef = useRef<HTMLElement>(null);

useLayoutEffect(() => {
// Event handler to keep track of focus changes within ActionBarContainer when ActionBar is open.
let timeoutId = null;
let onFocusContainer = (e:FocusEvent) => {
let activeElement = e.target as HTMLElement;
if (timeoutId) {
cancelAnimationFrame(timeoutId);
timeoutId = null;
}
timeoutId = requestAnimationFrame(() => {
if (domRef.current && !domRef.current.contains(activeElement)) {
restoreFocusRef.current = activeElement;
}
});
};

// When the ActionBar opens,
if (domRef.current) {
// store the last element to have focus,
if (!restoreFocusRef.current) {
restoreFocusRef.current = document.activeElement as HTMLElement;
}

// and store a reference to the parent ActionBarContainer element.
containerRef.current = domRef.current.parentElement;

// Listen for focus events within the ActionBarContainer,
// and if necessary update the element to which focus
// should be restored when the ActionBar closes.
containerRef.current.addEventListener('focus', onFocusContainer, true);
}

// When the ActionBar closes.
return () => {
// Wait a frame.
requestAnimationFrame(() => {
if (restoreFocusRef.current && document.body.contains(restoreFocusRef.current)) {
// If the restoreFocusRef.current is in the DOM, we can simply focus it.
focusSafely(restoreFocusRef.current);
restoreFocusRef.current = null;
} else if (containerRef.current) {
// Otherwise, we assume that the element using a SelectableCollection
// is the first child if the ActionBarContainer.
// We use a TreeWalker to find the first tabbable element to focus,
// where, on receiving focus, the SelectableCollection should set focus to the focusedKey.
let walker = getFocusableTreeWalker(containerRef.current, {tabbable: true});
let node = walker.nextNode() as HTMLElement;
node && focusSafely(node);
}

// Clean up focus event listener on ActionBarContainer.
if (containerRef.current) {
containerRef.current.removeEventListener('focus', onFocusContainer, true);
containerRef.current = null;
}
});
};
}, [domRef]);

return (
<FocusScope restoreFocus>
<div
Expand Down
10 changes: 5 additions & 5 deletions packages/@react-spectrum/actionbar/stories/Example.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,23 +74,23 @@ export function Example(props: any = {}) {
setSelectedKeys(new Set());
}}
{...props}>
<Item key="edit">
<Item key="edit" textValue="Edit">
<Edit />
<Text>Edit</Text>
</Item>
<Item key="copy">
<Item key="copy" textValue="Copy">
<Copy />
<Text>Copy</Text>
</Item>
<Item key="delete">
<Item key="delete" textValue="Delete">
<Delete />
<Text>Delete</Text>
</Item>
<Item key="move">
<Item key="move" textValue="Move">
<Move />
<Text>Move</Text>
</Item>
<Item key="duplicate">
<Item key="duplicate" textValue="Duplicate">
<Duplicate />
<Text>Duplicate</Text>
</Item>
Expand Down
105 changes: 103 additions & 2 deletions packages/@react-spectrum/actionbar/test/ActionBar.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ import React from 'react';
import {theme} from '@react-spectrum/theme-default';

describe('ActionBar', () => {
function pressKey(element, options) {
fireEvent.keyDown(element, options);
fireEvent.keyUp(element, options);
}

beforeAll(() => {
jest.spyOn(window.HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(() => 1000);
jest.spyOn(window.HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(() => 500);
Expand Down Expand Up @@ -116,8 +121,7 @@ describe('ActionBar', () => {
let toolbar = tree.getByRole('toolbar');
act(() => within(toolbar).getAllByRole('button')[0].focus());

fireEvent.keyDown(document.activeElement, {key: 'Escape'});
fireEvent.keyUp(document.activeElement, {key: 'Escape'});
pressKey(document.activeElement, {key: 'Escape'});
act(() => jest.runAllTimers());
act(() => jest.runAllTimers());

Expand All @@ -140,4 +144,101 @@ describe('ActionBar', () => {

expect(onAction).toHaveBeenCalledWith('edit');
});

it('should restore focus back to the table', () => {
jest.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(() => {
if (this instanceof HTMLButtonElement) {
return 100;
}

return 250;
});


let onAction = jest.fn();
let tree = render(<Provider theme={theme}><Example onAction={onAction} /></Provider>);
act(() => jest.runAllTimers());

let table = tree.getByRole('grid');
let rows = within(table).getAllByRole('row');

triggerPress(rows[1]);

let moreButton = tree.getByLabelText('Actions');
triggerPress(moreButton);

act(() => jest.runAllTimers());

let menu = tree.getByRole('menu');

expect(document.activeElement).toBe(menu);

pressKey(document.activeElement, {key: 'Escape'});

act(() => jest.runAllTimers());
act(() => jest.runAllTimers());

expect(document.activeElement).toBe(moreButton);

pressKey(document.activeElement, {key: 'Escape'});

act(() => jest.runAllTimers());
act(() => jest.runAllTimers());

expect(document.activeElement).toBe(rows[1]);
});

it('should restore focus back to the table when focused element index is scrolled out of view', () => {
jest.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(() => {
if (this instanceof HTMLButtonElement) {
return 100;
}

return 250;
});

let onAction = jest.fn();
let tree = render(<Provider theme={theme}><Example onAction={onAction} /></Provider>);
act(() => jest.runAllTimers());

let table = tree.getByRole('grid');
let body = table.childNodes[1];
let rows = within(table).getAllByRole('row');

triggerPress(rows[1]);

act(() => rows[2].focus());

expect(body.scrollTop).toBe(0);

body.scrollTop = 392;
fireEvent.scroll(body);
act(() => jest.runAllTimers());

expect(body.scrollTop).toBe(392);
expect(document.activeElement).toBe(table);

let moreButton = tree.getByLabelText('Actions');
triggerPress(moreButton);

act(() => jest.runAllTimers());

let menu = tree.getByRole('menu');

expect(document.activeElement).toBe(menu);

pressKey(document.activeElement, {key: 'Escape'});

act(() => jest.runAllTimers());
act(() => jest.runAllTimers());

expect(document.activeElement).toBe(moreButton);

pressKey(document.activeElement, {key: 'Escape'});

act(() => jest.runAllTimers());
act(() => jest.runAllTimers());

expect(document.activeElement === within(table).getAllByRole('row')[2] || document.activeElement === table).toBe(true);
});
});
90 changes: 43 additions & 47 deletions packages/@react-spectrum/actiongroup/src/ActionGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -290,58 +290,54 @@ function ActionGroupItem<T>({item, state, isDisabled, isEmphasized, staticColor,
}, [hideButtonText, item.rendered, textId]);

let button = (
// Use a PressResponder to send DOM props through.
// ActionButton doesn't allow overriding the role by default.
<PressResponder {...mergeProps(buttonProps, hoverProps, domProps)}>
<ClearSlots>
<SlotProvider
slots={{
text: {
id: hideButtonText ? textId : null,
isHidden: hideButtonText
}
}}>
<ActionButton
ref={ref}
UNSAFE_className={
classNames(
styles,
'spectrum-ActionGroup-item',
{
'is-selected': isSelected,
'is-hovered': isHovered,
'spectrum-ActionGroup-item--iconOnly': hideButtonText,
'spectrum-ActionGroup-item--isDisabled': isDisabled
},
<TooltipTrigger placement={orientation === 'vertical' ? 'end' : 'top'}>
{
// Use a PressResponder to send DOM props through.
// ActionButton doesn't allow overriding the role by default.
}
<PressResponder {...mergeProps(buttonProps, hoverProps, domProps)}>
<ClearSlots>
<SlotProvider
slots={{
text: {
id: hideButtonText ? textId : null,
isHidden: hideButtonText
}
}}>
<ActionButton
ref={ref}
UNSAFE_className={
classNames(
buttonStyles,
styles,
'spectrum-ActionGroup-item',
{
'spectrum-ActionButton--emphasized': isEmphasized,
'is-selected': isSelected
}
'is-selected': isSelected,
'is-hovered': isHovered,
'spectrum-ActionGroup-item--iconOnly': hideButtonText,
'spectrum-ActionGroup-item--isDisabled': isDisabled
},
classNames(
buttonStyles,
{
'spectrum-ActionButton--emphasized': isEmphasized,
'is-selected': isSelected
}
)
)
)
}
isDisabled={isDisabled}
staticColor={staticColor}
aria-label={item['aria-label']}
aria-labelledby={item['aria-label'] == null && hideButtonText ? textId : undefined}>
{item.rendered}
</ActionButton>
</SlotProvider>
</ClearSlots>
</PressResponder>
}
isDisabled={isDisabled}
staticColor={staticColor}
aria-label={item['aria-label']}
aria-labelledby={item['aria-label'] == null && hideButtonText ? textId : undefined}>
{item.rendered}
</ActionButton>
</SlotProvider>
</ClearSlots>
</PressResponder>
{hideButtonText && textContent ? <Tooltip>{textContent}</Tooltip> : null}
</TooltipTrigger>
);

if (hideButtonText && textContent) {
button = (
<TooltipTrigger placement={orientation === 'vertical' ? 'end' : 'top'}>
{button}
<Tooltip>{textContent}</Tooltip>
</TooltipTrigger>
);
}

if (item.wrapper) {
button = item.wrapper(button);
}
Expand Down
29 changes: 16 additions & 13 deletions packages/@react-spectrum/tooltip/src/TooltipTrigger.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,19 +57,22 @@ function TooltipTrigger(props: SpectrumTooltipTriggerProps) {
{...triggerProps}
ref={tooltipTriggerRef}>
{trigger}
<TooltipContext.Provider
value={{
state,
placement,
ref: overlayRef,
UNSAFE_style: overlayProps.style,
arrowProps,
...tooltipProps
}}>
<Overlay isOpen={state.isOpen}>
{tooltip}
</Overlay>
</TooltipContext.Provider>
{
tooltip &&
<TooltipContext.Provider
value={{
state,
placement,
ref: overlayRef,
UNSAFE_style: overlayProps.style,
arrowProps,
...tooltipProps
}}>
<Overlay isOpen={state.isOpen}>
{tooltip}
</Overlay>
</TooltipContext.Provider>
}
</FocusableProvider>
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@react-types/tooltip/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export interface TooltipTriggerProps extends OverlayTriggerProps {
}

export interface SpectrumTooltipTriggerProps extends TooltipTriggerProps, PositionProps {
children: [ReactElement, ReactElement],
children: [ReactElement, ReactElement] | ReactNode,

/**
* The additional offset applied along the main axis between the element and its
Expand Down