Skip to content

fix(menu): correctly identify menu item link with same URL as web page #693

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 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
18 changes: 17 additions & 1 deletion packages/menu/demo/stories/MenuStory.tsx
Copy link
Member

Choose a reason for hiding this comment

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

Is there an item treatment that can be done for anchor items if selected is true? It would be nice to see a visual change here in the containers storybook (as opposed to react-components where we don't want any visual artifact).

Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ type MenuItemProps = {
isSelected?: boolean;
};

/**
* [1] For a disabled link to be valid, it must have:
* - `aria-disabled="true"`
* - `role="link"`, or `role="menuitem"` if within a menu
* - an `undefined` `href`
*
* @example <a role="link" aria-disabled="true">Learn something!</a>
* @see https://www.scottohara.me/blog/2021/05/28/disabled-links.html
*/
const Item = ({ item, getItemProps, focusedValue, isSelected }: MenuItemProps) => {
const itemProps = getItemProps({ item });

Expand Down Expand Up @@ -60,7 +69,14 @@ const Item = ({ item, getItemProps, focusedValue, isSelected }: MenuItemProps) =
{itemProps.href ? (
<a
{...(itemProps as AnchorHTMLAttributes<HTMLAnchorElement>)}
className="w-full rounded-sm outline-offset-0 transition-none border-width-none"
href={item.disabled ? undefined : itemProps.href}
Copy link
Member

Choose a reason for hiding this comment

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

This href prop manipulation should be happening within the hook so that spreading ...itemProps Just Works ™️

className={classNames(
' w-full rounded-sm outline-offset-0 transition-none border-width-none',
{
'text-grey-400': item.disabled,
'cursor-default': item.disabled
}
)}
>
{itemChildren}
{!!item.isExternal && (
Expand Down
93 changes: 85 additions & 8 deletions packages/menu/src/MenuContainer.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import React, { useCallback, useRef, useState } from 'react';
import { RenderResult, render, act, waitFor } from '@testing-library/react';
import { act, createEvent, fireEvent, render, RenderResult, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MenuItem, IMenuItemBase, IUseMenuProps, IUseMenuReturnValue } from './types';
import { MenuContainer } from './';
Expand Down Expand Up @@ -283,14 +283,44 @@ describe('MenuContainer', () => {
expect(menu).not.toBeVisible();
});

it('applies external anchor attributes', () => {
const { getByTestId } = render(
<TestMenu items={[{ value: 'item', href: '#0', isExternal: true }]} />
);
const menu = getByTestId('menu');
describe('navigational menu items (links)', () => {
it('applies external anchor attributes, only if not disabled', () => {
const { getByTestId } = render(
<TestMenu
items={[
{ value: 'link-1', href: '#1', isExternal: true },
{ value: 'link-2', href: '#2', isExternal: true, disabled: true }
]}
/>
);
const menu = getByTestId('menu');

expect(menu.firstChild).toHaveAttribute('target', '_blank');
expect(menu.firstChild).toHaveAttribute('rel', 'noopener noreferrer');

expect(menu.firstChild).toHaveAttribute('target', '_blank');
expect(menu.firstChild).toHaveAttribute('rel', 'noopener noreferrer');
expect(menu.childNodes[1]).not.toHaveAttribute('target', '_blank');
expect(menu.childNodes[1]).not.toHaveAttribute('rel', 'noopener noreferrer');
});

it('applies the correct aria-current attribute to active link', async () => {
const { getByTestId, getByText } = render(
<TestMenu
items={[
{ value: 'link-1', href: '#1' },
{ value: 'link-2', href: '#2' }
]}
/>
);
const trigger = getByTestId('trigger');
const link = getByText('link-2');

await waitFor(async () => {
await user.click(trigger);
await user.click(link);
});

expect(link).toHaveAttribute('aria-current', 'page');
});
});

describe('focus', () => {
Expand Down Expand Up @@ -1265,6 +1295,53 @@ describe('MenuContainer', () => {
expect(changeTypes).toContain(StateChangeTypes.MenuItemKeyDownPrevious);
});
});

describe('navigational menu items (links)', () => {
it('applies the correct aria-current attribute to selected link', async () => {
const { getByTestId, getByText } = render(
<TestMenu
items={[
{ value: 'link-1', href: '#1' },
{ value: 'link-2', href: '#2' }
]}
selectedItems={[{ value: 'link-2' }]}
/>
);
const trigger = getByTestId('trigger');
const link = getByText('link-2');

await waitFor(async () => {
await user.click(trigger);
});

expect(link).toHaveAttribute('aria-current', 'page');
});

it('prevents default when clicking a selected link', async () => {
const { getByTestId, getByText } = render(
<TestMenu
items={[
{ value: 'link-1', href: '#1' },
{ value: 'link-2', href: '#2' }
]}
selectedItems={[{ value: 'link-2' }]}
/>
);
const trigger = getByTestId('trigger');
const link = getByText('link-2');

await waitFor(async () => {
await user.click(trigger);
});

const event = createEvent.click(link);
event.preventDefault = jest.fn();
fireEvent(link, event);

expect(event.preventDefault).toHaveBeenCalledTimes(1);
expect(link).toHaveAttribute('aria-current', 'page');
});
});
});

describe('error handling', () => {
Expand Down
55 changes: 35 additions & 20 deletions packages/menu/src/useMenu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
);

const isItemSelected = useCallback(
(value: string, type?: string, name?: string): boolean | undefined => {
(value: string, type?: string, name?: string, href?: string): boolean | undefined => {
let isSelected;

if (type === 'checkbox') {
Expand All @@ -164,6 +164,10 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
const match = controlledSelectedItems.filter(item => item.name === name)[0];

isSelected = match?.value === value;
} else if (href) {
const current = controlledSelectedItems[0];

isSelected = current?.value === value;
}

return isSelected;
Expand Down Expand Up @@ -218,10 +222,10 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
);

const getSelectedItems = useCallback(
({ value, type, name, label, selected }: IMenuItemBase) => {
({ value, type, name, label, selected, href }: IMenuItemBase) => {
let changes: ISelectedItem[] | null = [...controlledSelectedItems];

if (!type) return null;
if (!(type || href)) return null;

const selectedItem = {
value,
Expand All @@ -236,7 +240,7 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
} else {
changes.push(selectedItem);
}
} else if (type === 'radio') {
} else if (type === 'radio' || href) {
const index = changes.findIndex(item => item.name === name);

if (index > -1) {
Expand Down Expand Up @@ -428,15 +432,17 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
}, [onChange]);

const handleItemClick = useCallback(
(item: IMenuItemBase) => {
(event: React.MouseEvent, item: IMenuItemBase) => {
let changeType = StateChangeTypes.MenuItemClick;
const { isNext, isPrevious } = item;
const { isNext, isPrevious, href, selected } = item;
const isTransitionItem = isNext || isPrevious;

if (isNext) {
changeType = StateChangeTypes.MenuItemClickNext;
} else if (isPrevious) {
changeType = StateChangeTypes.MenuItemClickPrevious;
} else if (href && selected) {
event.preventDefault();
}

const nextSelection = getSelectedItems(item);
Expand Down Expand Up @@ -815,7 +821,7 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
itemRole = 'menuitemcheckbox';
}

const selected = isItemSelected(value, type, name);
const selected = isItemSelected(value, type, name, href);

/**
* The "select" of useSelection isn't
Expand All @@ -829,27 +835,36 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
'data-garden-container-id': 'containers.menu.item',
'data-garden-container-version': PACKAGE_VERSION,
'aria-selected': undefined,
'aria-checked': selected,
'aria-disabled': itemDisabled,
role: itemRole === null ? undefined : itemRole,
href,
onClick,
onKeyDown,
onMouseEnter,
...other
};

if (href && isExternal) {
elementProps.target = '_blank';
elementProps.rel = 'noopener noreferrer';
}
if (href) {
/**
* Validation
*/
if (isNext || isPrevious || type) {
anchorItemError(item);
}

/**
* Validation
*/
elementProps.href = href;

if (!itemDisabled) {
if (isExternal) {
Copy link
Member

Choose a reason for hiding this comment

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

Should probably be named external to keep parity with the other aspects of the container API (selected, disabled). Compare with other container APIs – we don't enforce the isXxx naming like we do in react-components. Also, the documentation for item.href and item.external is missing from the types interface.

elementProps.target = '_blank';
elementProps.rel = 'noopener noreferrer';
}

if (href && (isNext || isPrevious || type)) {
anchorItemError(item);
if (selected) {
elementProps['aria-current'] = 'page';
}
}
} else {
elementProps['aria-checked'] = selected;
}

if (itemDisabled) {
Expand All @@ -859,8 +874,8 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
const itemProps = getElementProps({
value: value as any,
...elementProps,
onClick: composeEventHandlers(onClick, () =>
handleItemClick({ ...item, label, selected, isNext, isPrevious })
onClick: composeEventHandlers(onClick, (e: React.MouseEvent) =>
handleItemClick(e, { ...item, label, selected, isNext, isPrevious })
),
onKeyDown: composeEventHandlers(onKeyDown, (e: React.KeyboardEvent) =>
handleItemKeyDown(e, { ...item, label, selected, isNext, isPrevious })
Expand Down