Skip to content
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
41 changes: 28 additions & 13 deletions packages/@react-aria/focus/src/FocusScope.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
getActiveElement,
getEventTarget,
getOwnerDocument,
getOwnerWindow,
isAndroid,
isChrome,
isFocusable,
Expand Down Expand Up @@ -295,23 +296,37 @@ function shouldContainFocus(scopeRef: ScopeRef) {
return true;
}

function isTabbableRadio(element: HTMLInputElement) {
if (element.checked) {
return true;
}
let radios: HTMLInputElement[] = [];
function getRadiosInGroup(element: HTMLInputElement): HTMLInputElement[] {
if (!element.form) {
radios = ([...getOwnerDocument(element).querySelectorAll(`input[type="radio"][name="${CSS.escape(element.name)}"]`)] as HTMLInputElement[]).filter(radio => !radio.form);
} else {
let radioList = element.form?.elements?.namedItem(element.name) as RadioNodeList;
radios = [...(radioList ?? [])] as HTMLInputElement[];
// Radio buttons outside a form - query the document
return Array.from(
getOwnerDocument(element).querySelectorAll<HTMLInputElement>(
`input[type="radio"][name="${CSS.escape(element.name)}"]`
)
).filter(radio => !radio.form);
}
if (!radios) {
return false;

// namedItem returns RadioNodeList (iterable) for 2+ elements, but a single Element for exactly 1.
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection/namedItem
const radioList = element.form.elements.namedItem(element.name);
let ownerWindow = getOwnerWindow(element);
if (radioList instanceof ownerWindow.RadioNodeList) {
return Array.from(radioList).filter(
(el): el is HTMLInputElement => el instanceof ownerWindow.HTMLInputElement
);
}
let anyChecked = radios.some(radio => radio.checked);
if (radioList instanceof ownerWindow.HTMLInputElement) {
return [radioList];
}
return [];
}

return !anyChecked;
function isTabbableRadio(element: HTMLInputElement): boolean {
if (element.checked) {
return true;
}
const radios = getRadiosInGroup(element);
return radios.length > 0 && !radios.some(radio => radio.checked);
}

function useFocusContainment(scopeRef: RefObject<Element[] | null>, contain?: boolean) {
Expand Down
26 changes: 26 additions & 0 deletions packages/@react-aria/focus/test/FocusScope.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1538,6 +1538,32 @@ describe('FocusScope', function () {
expect(document.activeElement).toBe(getByTestId('button1'));
});

it('handles forms with a single radio button without crashing', async function () {
// Regression test for https://github.com/adobe/react-spectrum/issues/9569
// form.elements.namedItem() returns Element (not RadioNodeList) for single elements
function Test() {
return (
<FocusScope contain>
<button data-testid="button1">First button</button>
<form>
<input type="radio" id="only" name="option" value="only" />
<label htmlFor="only">Only Option</label>
</form>
<button data-testid="button2">Second button</button>
</FocusScope>
);
}

let {getByTestId, getByRole} = render(<Test />);
let radio = getByRole('radio');
await user.tab();
expect(document.activeElement).toBe(getByTestId('button1'));
await user.tab();
expect(document.activeElement).toBe(radio);
await user.tab();
expect(document.activeElement).toBe(getByTestId('button2'));
});

describe('nested focus scopes', function () {
it('should make child FocusScopes the active scope regardless of DOM structure', function () {
function ChildComponent(props) {
Expand Down
3 changes: 2 additions & 1 deletion packages/@react-aria/menu/src/useMenuItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ export function useMenuItem<T>(props: AriaMenuItemProps, state: TreeState<T>, re
}

if (isVirtualized) {
ariaProps['aria-posinset'] = item?.index;
let index = Number(item?.index);
ariaProps['aria-posinset'] = Number.isNaN(index) ? undefined : index + 1;
ariaProps['aria-setsize'] = getItemCount(state.collection);
}

Expand Down
73 changes: 72 additions & 1 deletion packages/@react-aria/menu/test/useMenu.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@
* governing permissions and limitations under the License.
*/


import {AriaMenuProps, useMenu, useMenuItem} from '../';
import {Item} from '@react-stately/collections';
import {Key} from '@react-types/shared';
import {pointerMap, render} from '@react-spectrum/test-utils-internal';
import React from 'react';
import {TreeState, useTreeState} from '@react-stately/tree';
import userEvent from '@testing-library/user-event';
import {useTreeState} from '@react-stately/tree';

function Menu<T extends object>(props: AriaMenuProps<T> & {onSelect: () => void}) {
// Create menu state based on the incoming props
Expand Down Expand Up @@ -51,6 +53,41 @@ function MenuItem({item, state, onAction}) {
);
}

interface VirtualizedMenuItemProps<T> {
item: {key: Key, rendered: React.ReactNode, index?: number},
state: TreeState<T>,
onAction?: (key: Key) => void
}

function VirtualizedMenuItem<T>({item, state, onAction}: VirtualizedMenuItemProps<T>) {
let ref = React.useRef(null);
let {menuItemProps} = useMenuItem(
{key: item.key, onAction, isVirtualized: true},
state,
ref
);

return (
<li {...menuItemProps} ref={ref}>
{item.rendered}
</li>
);
}

function VirtualizedMenu<T extends object>(props: AriaMenuProps<T>) {
let state = useTreeState(props);
let ref = React.useRef(null);
let {menuProps} = useMenu(props, state, ref);

return (
<ul {...menuProps} ref={ref}>
{[...state.collection].map((item) => (
<VirtualizedMenuItem key={item.key} item={item} state={state} />
))}
</ul>
);
}

describe('useMenuTrigger', function () {
let user;
beforeAll(() => {
Expand All @@ -75,3 +112,37 @@ describe('useMenuTrigger', function () {
expect(onSelect).toHaveBeenCalledTimes(1);
});
});

describe('useMenuItem with isVirtualized', function () {
it('sets correct aria-posinset (1-based) for virtualized menu items', () => {
let {getAllByRole} = render(
<VirtualizedMenu aria-label="test menu">
<Item key="1">One</Item>
<Item key="2">Two</Item>
<Item key="3">Three</Item>
</VirtualizedMenu>
);

let items = getAllByRole('menuitem');
// aria-posinset should be 1-based (1, 2, 3), not 0-based (0, 1, 2)
expect(items[0]).toHaveAttribute('aria-posinset', '1');
expect(items[1]).toHaveAttribute('aria-posinset', '2');
expect(items[2]).toHaveAttribute('aria-posinset', '3');
});

it('sets correct aria-setsize for virtualized menu items', () => {
let {getAllByRole} = render(
<VirtualizedMenu aria-label="test menu">
<Item key="1">One</Item>
<Item key="2">Two</Item>
<Item key="3">Three</Item>
</VirtualizedMenu>
);

let items = getAllByRole('menuitem');
// aria-setsize should match the total number of items
expect(items[0]).toHaveAttribute('aria-setsize', '3');
expect(items[1]).toHaveAttribute('aria-setsize', '3');
expect(items[2]).toHaveAttribute('aria-setsize', '3');
});
});
3 changes: 2 additions & 1 deletion packages/@react-spectrum/s2/src/TableView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -955,7 +955,8 @@ const cell = style<CellRenderProps & S2TableProps & {isDivider: boolean}>({
...commonCellStyles,
color: {
default: baseColor('neutral-subdued'),
isSelected: baseColor('neutral')
isSelected: baseColor('neutral'),
forcedColors: 'ButtonText'
},
paddingY: centerPadding(),
minHeight: {
Expand Down
6 changes: 4 additions & 2 deletions packages/react-aria-components/src/Button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,13 @@ export const Button = /*#__PURE__*/ createHideableComponent(function Button(prop
);
});

// Events to preserve when isPending is true (for tooltips and other overlays)
const PRESERVED_EVENT_PATTERN = /Focus|Blur|Hover|Pointer(Enter|Leave|Over|Out)|Mouse(Enter|Leave|Over|Out)/;

function useDisableInteractions(props, isPending) {
// Don't allow interaction while isPending is true
if (isPending) {
for (const key in props) {
if (key.startsWith('on') && !(key.includes('Focus') || key.includes('Blur'))) {
if (key.startsWith('on') && !PRESERVED_EVENT_PATTERN.test(key)) {
props[key] = undefined;
}
}
Expand Down
6 changes: 4 additions & 2 deletions packages/react-aria-components/src/ComboBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,10 @@ function ComboBoxInner<T extends object>({props, collection, comboBoxRef: ref}:
data-open={state.isOpen || undefined}
data-disabled={props.isDisabled || undefined}
data-invalid={validation.isInvalid || undefined}
data-required={props.isRequired || undefined} />
{name && formValue === 'key' && <input type="hidden" name={name} form={props.form} value={state.selectedKey ?? ''} />}
data-required={props.isRequired || undefined}>
{renderProps.children}
{name && formValue === 'key' && <input type="hidden" name={name} form={props.form} value={state.selectedKey ?? ''} />}
</dom.div>
</Provider>
);
}
5 changes: 3 additions & 2 deletions packages/react-aria-components/src/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -431,12 +431,13 @@ export const MenuItem = /*#__PURE__*/ createLeafComponent(ItemNode, function Men
let state = useContext(MenuStateContext)!;
let ref = useObjectRef<any>(forwardedRef);
let selectionManager = useContext(SelectionManagerContext)!;

let {isVirtualized} = useContext(CollectionRendererContext);
let {menuItemProps, labelProps, descriptionProps, keyboardShortcutProps, ...states} = useMenuItem({
...props,
id,
key: item.key,
selectionManager
selectionManager,
isVirtualized: isVirtualized
}, state, ref);

let {hoverProps, isHovered} = useHover({
Expand Down
28 changes: 27 additions & 1 deletion packages/react-aria-components/stories/Button.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
*/

import {action} from '@storybook/addon-actions';
import {Button, ProgressBar, Text} from 'react-aria-components';
import {Button, ProgressBar, Text, Tooltip, TooltipTrigger} from 'react-aria-components';
import {mergeProps} from '@react-aria/utils';
import {Meta, StoryObj} from '@storybook/react';
import React, {useEffect, useRef, useState} from 'react';
Expand Down Expand Up @@ -39,6 +39,13 @@ export const PendingButton: ButtonStory = {
}
};

export const PendingButtonTooltip: ButtonStory = {
render: (args) => <PendingButtonTooltipExample {...args} />,
args: {
children: 'Press me, then hover again to see tooltip'
}
};

function PendingButtonExample(props) {
let [isPending, setPending] = useState(false);

Expand Down Expand Up @@ -84,6 +91,25 @@ function PendingButtonExample(props) {
);
}

function PendingButtonTooltipExample(props) {
return (
<TooltipTrigger>
<PendingButtonExample {...props} />
<Tooltip
offset={6}
style={{
background: 'Canvas',
color: 'CanvasText',
border: '1px solid gray',
padding: 5,
borderRadius: 4
}}>
Tooltip should appear on hover
</Tooltip>
</TooltipTrigger>
);
}

export const RippleButtonExample: ButtonStory = {
render: () => (
<RippleButton data-testid="button-example">Press me</RippleButton>
Expand Down
33 changes: 31 additions & 2 deletions packages/react-aria-components/stories/Menu.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
*/

import {action} from '@storybook/addon-actions';
import {Button, Header, Heading, Input, Keyboard, Label, Menu, MenuItemProps, MenuSection, MenuTrigger, Popover, Separator, SubmenuTrigger, SubmenuTriggerProps, Text, TextField} from 'react-aria-components';
import {Button, Header, Heading, Input, Keyboard, Label, ListLayout, Menu, MenuItemProps, MenuSection, MenuTrigger, Popover, Separator, SubmenuTrigger, SubmenuTriggerProps, Text, TextField, Virtualizer} from 'react-aria-components';
import {Meta, StoryFn, StoryObj} from '@storybook/react';
import {MyMenuItem} from './utils';
import React, {JSX} from 'react';
Expand Down Expand Up @@ -444,7 +444,7 @@ function MenuItemWithCustomElement(props: MenuItemProps) {
// Otherwise we'd need another way to set the expected element type.
return (
<MyMenuItem
{...props}
{...props}
render={domProps => 'href' in domProps ? <RouterLink {...domProps} /> : <div {...domProps} />} />
);
}
Expand All @@ -453,3 +453,32 @@ function RouterLink(props: React.AnchorHTMLAttributes<HTMLAnchorElement>) {
// eslint-disable-next-line jsx-a11y/anchor-has-content
return <a {...mergeProps(props, {onClick: e => {e.preventDefault(); console.log('click');}})} />;
}

let items = Array.from({length: 600}, (_, index) => {
// Return the object structure for each element
return {
id: index + 1,
name: `Object ${index + 1}`,
value: Math.random()
};
});
export const VirtualizedExample: MenuStory = () => {
return (
<MenuTrigger>
<Button aria-label="Actions">
Menu ☰
</Button>
<Popover>
<Virtualizer
layout={ListLayout}
layoutOptions={{estimatedRowHeight: 36}}>
<Menu className={styles.menu} items={items}>
{(item) => {
return <MyMenuItem>{item.name}</MyMenuItem>;
}}
</Menu>
</Virtualizer>
</Popover>
</MenuTrigger>
);
};
19 changes: 19 additions & 0 deletions packages/react-aria-components/test/Tooltip.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,25 @@ describe('Tooltip', () => {
expect(arrow).toHaveStyle('position: absolute');
});

it('shows on hover when button has isPending', async () => {
let {getByRole} = render(
<TooltipTrigger delay={0}>
<Button isPending>Pending Button</Button>
<Tooltip>Tooltip content</Tooltip>
</TooltipTrigger>
);

let button = getByRole('button');

fireEvent.mouseMove(document.body);
await user.hover(button);
act(() => jest.runAllTimers());

let tooltip = getByRole('tooltip');
expect(tooltip).toBeInTheDocument();
expect(tooltip).toHaveTextContent('Tooltip content');
});

it('shows on focus', async () => {
let {getByRole} = renderTooltip();
let button = getByRole('button');
Expand Down
Loading
Loading