diff --git a/jest.config.ts b/jest.config.ts index d0dbd1b889..6b3f2d6e24 100644 --- a/jest.config.ts +++ b/jest.config.ts @@ -1,5 +1,5 @@ -import { getJestProjects } from '@nx/jest'; +import { getJestProjectsAsync } from '@nx/jest'; -export default { - projects: getJestProjects(), -}; +export default async () => ({ + projects: await getJestProjectsAsync(), +}); diff --git a/packages/gamut/src/ConnectedForm/ConnectedFormGroup.tsx b/packages/gamut/src/ConnectedForm/ConnectedFormGroup.tsx index 90944d44ae..8344b977cb 100644 --- a/packages/gamut/src/ConnectedForm/ConnectedFormGroup.tsx +++ b/packages/gamut/src/ConnectedForm/ConnectedFormGroup.tsx @@ -33,6 +33,11 @@ export interface ConnectedFormGroupBaseProps name: string; label: React.ReactNode; required?: boolean; + /** + * InfoTip to display next to the field label. String labels automatically + * label the InfoTip button. For ReactNode labels, provide `ariaLabel` or + * set `labelledByFieldLabel: true` to ensure the InfoTip is accessible. + */ infotip?: InfoTipProps; } diff --git a/packages/gamut/src/ConnectedForm/__tests__/ConnectedForm.test.tsx b/packages/gamut/src/ConnectedForm/__tests__/ConnectedForm.test.tsx index b5f5918126..e96a3b7348 100644 --- a/packages/gamut/src/ConnectedForm/__tests__/ConnectedForm.test.tsx +++ b/packages/gamut/src/ConnectedForm/__tests__/ConnectedForm.test.tsx @@ -2,8 +2,9 @@ import { setupRtl } from '@codecademy/gamut-tests'; import { fireEvent, queries } from '@testing-library/dom'; import { act, RenderResult, waitFor } from '@testing-library/react'; +import { InfoTipProps } from '../../Tip/InfoTip'; import { createPromise } from '../../utils'; -import { ConnectedForm } from '..'; +import { ConnectedForm, ConnectedFormGroup, ConnectedInput } from '..'; import { PlainConnectedFields } from '../__fixtures__/helpers'; const renderView = setupRtl(ConnectedForm, { @@ -359,3 +360,87 @@ describe('ConnectedForm', () => { }); }); }); + +describe('ConnectedFormGroup infotip accessibility', () => { + const label = 'Infotip Label'; + const info = 'helpful information'; + const ariaLabel = 'Custom label'; + + const renderConnectedFormGroupView = setupRtl(ConnectedForm, { + defaultValues: { input: '' }, + onSubmit: jest.fn(), + children: null, + }); + + const renderWithInfotip = ({ + infotip, + fieldLabel = label, + }: { + infotip: InfoTipProps; + fieldLabel?: React.ReactNode; + }) => + renderConnectedFormGroupView({ + children: ( + + ), + }); + + it('automatically labels InfoTip button by the field label when label is a string', () => { + const { view } = renderWithInfotip({ infotip: { info } }); + + view.getByRole('button', { name: `${label}\u00A0(optional)` }); + }); + + it('uses explicit ariaLabel when provided', () => { + const { view } = renderWithInfotip({ + infotip: { info, ariaLabel }, + }); + + view.getByRole('button', { name: ariaLabel }); + }); + + it('uses explicit ariaLabelledby when provided', () => { + const externalLabelId = 'external-label-id'; + const externalLabelText = 'External Label'; + + const { view } = renderConnectedFormGroupView({ + children: ( + <> + {externalLabelText} + + + ), + }); + + view.getByRole('button', { name: externalLabelText }); + }); + + it('does not automatically label InfoTip when label is a ReactNode', () => { + const { view } = renderWithInfotip({ + infotip: { info, ariaLabel }, + fieldLabel: {label}, + }); + + view.getByRole('button', { name: ariaLabel }); + expect(view.queryByRole('button', { name: new RegExp(label) })).toBeNull(); + }); + + it('labels InfoTip by field label when labelledByFieldLabel is true with ReactNode label', () => { + const { view } = renderWithInfotip({ + infotip: { info, labelledByFieldLabel: true }, + fieldLabel: {label}, + }); + + view.getByRole('button', { name: new RegExp(label) }); + }); +}); diff --git a/packages/gamut/src/Form/__tests__/FormGroup.test.tsx b/packages/gamut/src/Form/__tests__/FormGroup.test.tsx index 0fc10265cc..d774b702ed 100644 --- a/packages/gamut/src/Form/__tests__/FormGroup.test.tsx +++ b/packages/gamut/src/Form/__tests__/FormGroup.test.tsx @@ -70,4 +70,44 @@ describe('FormGroup', () => { 'there is no up dog here...' ); }); + + describe('infotip accessibility', () => { + const info = 'helpful information'; + const ariaLabel = 'Custom label'; + + it('automatically labels InfoTip button by the field label when label is a string', () => { + const { view } = renderView({ label, htmlFor, infotip: { info } }); + + view.getByRole('button', { name: new RegExp(label) }); + }); + + it('uses explicit ariaLabel when provided', () => { + const { view } = renderView({ + label, + htmlFor, + infotip: { info, ariaLabel }, + }); + + view.getByRole('button', { name: ariaLabel }); + }); + + it('uses explicit ariaLabelledby when provided', () => { + const externalLabelId = 'external-label-id'; + const externalLabelText = 'External Label'; + + const { view } = renderView({ + label, + htmlFor, + infotip: { info, ariaLabelledby: externalLabelId }, + children: ( + <> + {externalLabelText} + + + ), + }); + + view.getByRole('button', { name: externalLabelText }); + }); + }); }); diff --git a/packages/gamut/src/Form/elements/FormGroupLabel.tsx b/packages/gamut/src/Form/elements/FormGroupLabel.tsx index 5ab9d96caa..f0e39fb2b0 100644 --- a/packages/gamut/src/Form/elements/FormGroupLabel.tsx +++ b/packages/gamut/src/Form/elements/FormGroupLabel.tsx @@ -1,7 +1,7 @@ import { states, variant } from '@codecademy/gamut-styles'; import { StyleProps } from '@codecademy/variance'; import styled from '@emotion/styled'; -import { HTMLAttributes } from 'react'; +import { HTMLAttributes, useId } from 'react'; import * as React from 'react'; import { FlexBox } from '../..'; @@ -62,6 +62,13 @@ export const FormGroupLabel: React.FC = ({ size, ...rest }) => { + const labelId = useId(); + const isStringLabel = typeof children === 'string'; + const shouldLabelInfoTip = + (isStringLabel || infotip?.labelledByFieldLabel) && + !infotip?.ariaLabel && + !infotip?.ariaLabelledby; + return ( - {infotip && } + {infotip && ( + + )} ); }; diff --git a/packages/gamut/src/GridForm/GridFormInputGroup/__fixtures__/renderers.tsx b/packages/gamut/src/GridForm/GridFormInputGroup/__fixtures__/renderers.tsx index ef1740d298..937208ad7c 100644 --- a/packages/gamut/src/GridForm/GridFormInputGroup/__fixtures__/renderers.tsx +++ b/packages/gamut/src/GridForm/GridFormInputGroup/__fixtures__/renderers.tsx @@ -83,13 +83,15 @@ export const getComponent = (componentName: string) => { type GridFormInputGroupTestComponentProps = GridFormInputGroupProps & { mode?: 'onSubmit' | 'onChange'; + externalLabel?: { id: string; text: string }; }; export const GridFormInputGroupTestComponent: React.FC< GridFormInputGroupTestComponentProps -> = ({ field, mode = 'onSubmit', ...rest }) => { +> = ({ field, mode = 'onSubmit', externalLabel, ...rest }) => { return ( + {externalLabel && {externalLabel.text}} ); diff --git a/packages/gamut/src/GridForm/GridFormInputGroup/__tests__/GridFormInputGroup.test.tsx b/packages/gamut/src/GridForm/GridFormInputGroup/__tests__/GridFormInputGroup.test.tsx index 7c2a3e578a..f6d44c7ecc 100644 --- a/packages/gamut/src/GridForm/GridFormInputGroup/__tests__/GridFormInputGroup.test.tsx +++ b/packages/gamut/src/GridForm/GridFormInputGroup/__tests__/GridFormInputGroup.test.tsx @@ -238,4 +238,69 @@ describe('GridFormInputGroup', () => { }); expect(view.container).not.toContainHTML('Column'); }); + + describe('infotip accessibility', () => { + const info = 'helpful information'; + const ariaLabel = 'Custom label'; + const textLabel = 'Stub Text'; + const checkboxLabel = 'Check me!'; + + it('automatically labels InfoTip button by the field label when label is a string', () => { + const { view } = renderView({ + field: { ...stubTextField, infotip: { info } }, + }); + + view.getByRole('button', { name: new RegExp(textLabel) }); + }); + + it('uses explicit ariaLabel when provided', () => { + const { view } = renderView({ + field: { ...stubTextField, infotip: { info, ariaLabel } }, + }); + + view.getByRole('button', { name: ariaLabel }); + }); + + it('uses explicit ariaLabelledby when provided', () => { + const externalLabelId = 'external-label-id'; + const externalLabelText = 'External Label'; + + const { view } = renderView({ + field: { + ...stubTextField, + infotip: { info, ariaLabelledby: externalLabelId }, + }, + externalLabel: { id: externalLabelId, text: externalLabelText }, + }); + + view.getByRole('button', { name: externalLabelText }); + }); + + it('does not automatically label InfoTip when label is a ReactNode', () => { + const { view } = renderView({ + field: { + ...stubCheckboxField, + label: {checkboxLabel}, + infotip: { info, ariaLabel }, + }, + }); + + view.getByRole('button', { name: ariaLabel }); + expect( + view.queryByRole('button', { name: new RegExp(checkboxLabel) }) + ).toBeNull(); + }); + + it('labels InfoTip by field label when labelledByFieldLabel is true with ReactNode label', () => { + const { view } = renderView({ + field: { + ...stubCheckboxField, + label: {checkboxLabel}, + infotip: { info, labelledByFieldLabel: true }, + }, + }); + + view.getByRole('button', { name: new RegExp(checkboxLabel) }); + }); + }); }); diff --git a/packages/gamut/src/GridForm/types.ts b/packages/gamut/src/GridForm/types.ts index 4ac4a39b49..1852e0d5c5 100644 --- a/packages/gamut/src/GridForm/types.ts +++ b/packages/gamut/src/GridForm/types.ts @@ -31,6 +31,11 @@ export type BaseFormField = { */ id?: string; + /** + * InfoTip to display next to the field label. String labels automatically + * label the InfoTip button. For ReactNode labels, provide `ariaLabel` or + * set `labelledByFieldLabel: true` to ensure the InfoTip is accessible. + */ infotip?: InfoTipProps; isSoloField?: boolean; diff --git a/packages/gamut/src/Tip/InfoTip/InfoTipButton.tsx b/packages/gamut/src/Tip/InfoTip/InfoTipButton.tsx index e9137d78c0..f402542a69 100644 --- a/packages/gamut/src/Tip/InfoTip/InfoTipButton.tsx +++ b/packages/gamut/src/Tip/InfoTip/InfoTipButton.tsx @@ -22,15 +22,26 @@ export type InfoTipButtonProps = ComponentProps & Pick; export const InfoTipButton = forwardRef( - ({ active, children, emphasis, ...props }, ref) => { + ( + { + active, + children, + emphasis, + 'aria-label': ariaLabel, + 'aria-labelledby': ariaLabelledby, + ...props + }, + ref + ) => { const Icon = emphasis === 'high' ? MiniInfoCircleIcon : MiniInfoOutlineIcon; return ( {Icon && ( diff --git a/packages/gamut/src/Tip/InfoTip/elements.tsx b/packages/gamut/src/Tip/InfoTip/elements.tsx deleted file mode 100644 index f1e21a5350..0000000000 --- a/packages/gamut/src/Tip/InfoTip/elements.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { css } from '@codecademy/gamut-styles'; -import styled from '@emotion/styled'; - -import { Text } from '../../Typography'; - -export const ScreenreaderNavigableText = styled(Text)( - css({ position: 'absolute' }) -); diff --git a/packages/gamut/src/Tip/InfoTip/index.tsx b/packages/gamut/src/Tip/InfoTip/index.tsx index 3c6c4736b1..da2ea43f0b 100644 --- a/packages/gamut/src/Tip/InfoTip/index.tsx +++ b/packages/gamut/src/Tip/InfoTip/index.tsx @@ -8,7 +8,6 @@ import { } from 'react'; import { getFocusableElements as getFocusableElementsUtil } from '../../utils/focus'; -import { extractTextContent } from '../../utils/react'; import { FloatingTip } from '../shared/FloatingTip'; import { InlineTip } from '../shared/InlineTip'; import { @@ -17,26 +16,43 @@ import { tipDefaultProps, } from '../shared/types'; import { isElementVisible } from '../shared/utils'; -import { ScreenreaderNavigableText } from './elements'; import { InfoTipButton } from './InfoTipButton'; export type InfoTipProps = TipBaseProps & { alignment?: TipBaseAlignment; + /** + * Accessible label for the InfoTip button. Its recommended to provide either `ariaLabel` or `ariaLabelledby`. + */ + ariaLabel?: string; + /** + * ID of an element that labels the InfoTip button. Its recommended to provide either `ariaLabel` or `ariaLabelledby`. + */ + ariaLabelledby?: string; + /** + * Accessible role description for the InfoTip button. Useful for translation. + * @default "More information button" + */ + ariaRoleDescription?: string; emphasis?: 'low' | 'high'; + /** + * When true, the InfoTip button will be labelled by the form field's label element. + * This is automatic for string labels, but can be opted into for ReactNode labels. + */ + labelledByFieldLabel?: boolean; /** * Called when the info tip is clicked - the onClick function is called after the DOM updates and the tip is mounted. */ onClick?: (arg0: { isTipHidden: boolean }) => void; }; -const ARIA_HIDDEN_DELAY_MS = 1000; - -// Match native dialogs with open attribute, and role-based dialogs that aren't aria-hidden const MODAL_SELECTOR = 'dialog[open],[role="dialog"]:not([aria-hidden="true"]),[role="alertdialog"]:not([aria-hidden="true"])'; export const InfoTip: React.FC = ({ alignment = 'top-right', + ariaLabel, + ariaLabelledby, + ariaRoleDescription = 'More information button', emphasis = 'low', info, onClick, @@ -46,8 +62,6 @@ export const InfoTip: React.FC = ({ const isFloating = placement === 'floating'; const [isTipHidden, setHideTip] = useState(true); - const [isAriaHidden, setIsAriaHidden] = useState(false); - const [shouldAnnounce, setShouldAnnounce] = useState(false); const [loaded, setLoaded] = useState(false); const wrapperRef = useRef(null); @@ -55,28 +69,10 @@ export const InfoTip: React.FC = ({ const popoverContentNodeRef = useRef(null); const isInitialMount = useRef(true); - const ariaHiddenTimeoutRef = useRef(null); - const announceTimeoutRef = useRef(null); - const getFocusableElements = useCallback(() => { return getFocusableElementsUtil(popoverContentNodeRef.current); }, []); - const clearAndSetTimeout = useCallback( - ( - timeoutRef: React.MutableRefObject, - callback: () => void, - delay: number - ) => { - clearTimeout(timeoutRef.current ?? undefined); - timeoutRef.current = setTimeout(() => { - callback(); - timeoutRef.current = null; - }, delay); - }, - [] - ); - const popoverContentRef = useCallback( (node: HTMLDivElement | null) => { popoverContentNodeRef.current = node; @@ -90,35 +86,11 @@ export const InfoTip: React.FC = ({ useEffect(() => { setLoaded(true); - - const ariaHiddenTimeout = ariaHiddenTimeoutRef.current; - const announceTimeout = announceTimeoutRef.current; - - return () => { - clearTimeout(ariaHiddenTimeout ?? undefined); - clearTimeout(announceTimeout ?? undefined); - }; }, []); - const setTipIsHidden = useCallback( - (nextTipState: boolean) => { - setHideTip(nextTipState); - - if (!nextTipState && !isFloating) { - clearAndSetTimeout( - ariaHiddenTimeoutRef, - () => setIsAriaHidden(true), - ARIA_HIDDEN_DELAY_MS - ); - } else if (nextTipState) { - if (isAriaHidden) setIsAriaHidden(false); - setShouldAnnounce(false); - clearTimeout(ariaHiddenTimeoutRef.current ?? undefined); - ariaHiddenTimeoutRef.current = null; - } - }, - [isAriaHidden, isFloating, clearAndSetTimeout] - ); + const setTipIsHidden = useCallback((nextTipState: boolean) => { + setHideTip(nextTipState); + }, []); const handleOutsideClick = useCallback( (e: MouseEvent) => { @@ -137,11 +109,7 @@ export const InfoTip: React.FC = ({ const clickHandler = useCallback(() => { const currentTipState = !isTipHidden; setTipIsHidden(currentTipState); - - if (!currentTipState) { - clearAndSetTimeout(announceTimeoutRef, () => setShouldAnnounce(true), 0); - } - }, [isTipHidden, setTipIsHidden, clearAndSetTimeout]); + }, [isTipHidden, setTipIsHidden]); useLayoutEffect(() => { if (isInitialMount.current) { @@ -192,7 +160,16 @@ export const InfoTip: React.FC = ({ if (event.key !== 'Tab' || event.shiftKey) return; const focusableElements = getFocusableElements(); - if (focusableElements.length === 0) return; + const { activeElement } = document; + + // If no focusable elements and popover itself has focus, wrap to button + if (focusableElements.length === 0) { + if (activeElement === popoverContentNodeRef.current) { + event.preventDefault(); + buttonRef.current?.focus(); + } + return; + } const lastElement = focusableElements[focusableElements.length - 1]; @@ -218,7 +195,17 @@ export const InfoTip: React.FC = ({ return () => document.removeEventListener('keydown', handleGlobalEscapeKey, true); - }, [isTipHidden, isFloating, setTipIsHidden, getFocusableElements]); + }, [isTipHidden, isFloating, getFocusableElements, setTipIsHidden]); + + useEffect(() => { + if (isTipHidden) return; + + const timeoutId = setTimeout(() => { + popoverContentNodeRef.current?.focus(); + }, 0); + + return () => clearTimeout(timeoutId); + }, [isTipHidden]); const Tip = loaded && isFloating ? FloatingTip : InlineTip; @@ -227,69 +214,25 @@ export const InfoTip: React.FC = ({ alignment, info, isTipHidden, + contentRef: popoverContentRef, wrapperRef, - ...(isFloating && { popoverContentRef }), ...rest, }), - [ - alignment, - info, - isTipHidden, - wrapperRef, - isFloating, - popoverContentRef, - rest, - ] - ); - - const extractedTextContent = useMemo(() => extractTextContent(info), [info]); - - const screenreaderInfo = - shouldAnnounce && !isTipHidden ? extractedTextContent : '\xa0'; - - const screenreaderText = useMemo( - () => ( - - {screenreaderInfo} - - ), - [isAriaHidden, screenreaderInfo] + [alignment, info, isTipHidden, popoverContentRef, wrapperRef, rest] ); - const button = useMemo( - () => ( + return ( + - ), - [isTipHidden, emphasis, clickHandler] - ); - - /* - * For floating placement, screenreader text comes before button to maintain - * correct DOM order despite Portal rendering. See GMT-64 for planned fix. - */ - return ( - - {isFloating && alignment.includes('top') ? ( - <> - {screenreaderText} - {button} - - ) : ( - <> - {button} - {screenreaderText} - - )} ); }; diff --git a/packages/gamut/src/Tip/__tests__/InfoTip.test.tsx b/packages/gamut/src/Tip/__tests__/InfoTip.test.tsx index 0a9ba89bfc..1115e0cac6 100644 --- a/packages/gamut/src/Tip/__tests__/InfoTip.test.tsx +++ b/packages/gamut/src/Tip/__tests__/InfoTip.test.tsx @@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event'; import { InfoTip } from '../InfoTip'; import { + clickButton, createLinkSetup, expectTipsClosed, expectTipsVisible, @@ -12,22 +13,22 @@ import { pressKey, setupLinkTestWithPlacement, setupMultiLinkTestWithPlacement, - testEscapeKeyReturnsFocus, testEscapeKeyWithOutsideFocus, testFocusWrap, testInfoTipInsideModalClosesOnEscape, testModalDoesNotCloseInfoTip, testOutsideClick, testRapidToggle, - testShowTipOnClick, testTabbingBetweenLinks, + testTabFromPopoverWithNoInteractiveElements, } from './helpers'; import { MultipleInfoTipsMock } from './mocks'; -const infoText = 'I am information'; +const info = 'I am information'; const linkText = 'cool link'; const renderView = setupRtl(InfoTip, { - info: infoText, + ariaLabel: 'Show information', + info, }); describe('InfoTip', () => { @@ -37,39 +38,79 @@ describe('InfoTip', () => { ])('$placement placement', ({ placement }) => { it('shows the tip when it is clicked on', async () => { const { view } = renderView({ placement }); - await testShowTipOnClick({ view, info: infoText, placement }); + + const isInline = placement === 'inline'; + + if (isInline) { + const tip = view.getByText(info); + expect(tip).not.toBeVisible(); + } else { + expect(view.queryByText(info)).toBeNull(); + } + + await userEvent.click(view.getByRole('button')); + + if (isInline) { + const tip = view.getByText(info); + expect(tip).toBeVisible(); + } else { + await waitFor(() => { + expect(view.getByText(info)).toBeVisible(); + }); + } }); it('closes the tip when Escape key is pressed and returns focus to button', async () => { const { view } = renderView({ placement }); - await testEscapeKeyReturnsFocus({ view, info: infoText, placement }); + const button = await clickButton(view); + + await waitFor(() => { + expect(view.getByText(info)).toBeVisible(); + }); + + await pressKey('{Escape}'); + + await waitFor(() => { + const tip = view.queryByText(info); + if (placement === 'inline') { + expect(tip).not.toBeVisible(); + } else { + expect(tip).toBeNull(); + } + expect(button).toHaveFocus(); + }); }); it('closes the tip when Escape is pressed even when focus is on an outside element', async () => { const { view } = renderView({ placement }); - await testEscapeKeyWithOutsideFocus({ view, info: infoText }); + await testEscapeKeyWithOutsideFocus({ view, info }); }); it('does not close the tip when Escape is pressed if a modal is open', async () => { const { view } = renderView({ placement }); - await testModalDoesNotCloseInfoTip({ view, info: infoText, placement }); + await testModalDoesNotCloseInfoTip({ view, info, placement }); }); it('closes the tip when Escape is pressed if the InfoTip is inside a modal', async () => { - await testInfoTipInsideModalClosesOnEscape({ - info: infoText, - placement, - }); + await testInfoTipInsideModalClosesOnEscape({ info, placement }); + }); + + it('closes the tip when clicking outside the wrapper', async () => { + const { view } = renderView({ placement }); + await testOutsideClick({ view, info, placement }); + }); + + it('handles rapid open/close cycles correctly', async () => { + const onClick = jest.fn(); + const { view } = renderView({ placement, onClick }); + await testRapidToggle({ view, onClick }); }); it('calls onClick with isTipHidden: false when tip opens', async () => { const onClick = jest.fn(); const { view } = renderView({ placement, onClick }); - const button = view.getByLabelText('Show information'); - await act(async () => { - await userEvent.click(button); - }); + await clickButton(view); await waitFor(() => { expect(onClick).toHaveBeenCalledWith({ isTipHidden: false }); @@ -79,11 +120,8 @@ describe('InfoTip', () => { it('calls onClick with isTipHidden: true when tip closes', async () => { const onClick = jest.fn(); const { view } = renderView({ placement, onClick }); - const button = view.getByLabelText('Show information'); - await act(async () => { - await userEvent.click(button); - }); + await clickButton(view); await waitFor(() => { expect(onClick).toHaveBeenCalledWith({ isTipHidden: false }); @@ -91,9 +129,7 @@ describe('InfoTip', () => { onClick.mockClear(); - await act(async () => { - await userEvent.click(button); - }); + await clickButton(view); await waitFor(() => { expect(onClick).toHaveBeenCalledWith({ isTipHidden: true }); @@ -111,17 +147,6 @@ describe('InfoTip', () => { expect(onClick).not.toHaveBeenCalled(); }); - it('closes the tip when clicking outside the wrapper', async () => { - const { view } = renderView({ placement }); - await testOutsideClick({ view, info: infoText, placement }); - }); - - it('handles rapid open/close cycles correctly', async () => { - const onClick = jest.fn(); - const { view } = renderView({ placement, onClick }); - await testRapidToggle({ view, onClick }); - }); - it('allows normal tabbing through focusable elements within tip', async () => { const firstLinkText = 'first link'; const secondLinkText = 'second link'; @@ -162,6 +187,8 @@ describe('InfoTip', () => { }); describe('floating placement focus management', () => { + const linkText = 'cool link'; + describe.each<{ direction: 'forward' | 'backward' }>([ { direction: 'forward' }, { direction: 'backward' }, @@ -171,55 +198,63 @@ describe('InfoTip', () => { ? 'tabbing forward from last' : 'shift+tabbing backward from first' } focusable element`, async () => { - const { view, containerRef } = setupLinkTestWithPlacement( + const { view } = setupLinkTestWithPlacement( linkText, 'floating', renderView ); - await testFocusWrap({ view, containerRef, direction }); + await testFocusWrap({ view, direction }); }); }); - it('does not wrap focus when tabbing from non-last focusable element', async () => { - const firstLinkText = 'first link'; - const secondLinkText = 'second link'; - const { view } = setupMultiLinkTestWithPlacement( - firstLinkText, - secondLinkText, - 'floating', - renderView - ); - - const button = view.getByLabelText('Show information'); - await act(async () => { - await userEvent.click(button); - }); + it('wraps focus to button when tabbing from popover with no interactive elements', async () => { + const { view } = renderView({ placement: 'floating' }); + await testTabFromPopoverWithNoInteractiveElements(view); + }); + }); - await waitFor(() => { - expect(view.getByText(firstLinkText)).toBeVisible(); - }); + describe('ariaLabel', () => { + it('applies aria-label when provided', () => { + const { view } = renderView({}); + view.getByLabelText('Show information'); + }); - await act(async () => { - await userEvent.tab(); + it('applies custom aria-label when provided', () => { + const { view } = renderView({ + ariaLabel: 'Additional details', }); + view.getByLabelText('Additional details'); + }); - const firstLink = await waitFor(() => { - const link = view.getByRole('link', { name: firstLinkText }); - expect(link).toHaveFocus(); - return link; + it('works with floating placement', () => { + const { view } = renderView({ + placement: 'floating', + ariaLabel: 'Help text', }); + view.getByLabelText('Help text'); + }); + }); - await act(async () => { - await userEvent.tab(); - }); + describe('ariaRoleDescription', () => { + it('applies default aria-roledescription', () => { + const { view } = renderView({}); + const button = view.getByRole('button'); + expect(button).toHaveAttribute( + 'aria-roledescription', + 'More information button' + ); + }); - await waitFor(() => { - const secondLink = view.getByRole('link', { name: secondLinkText }); - expect(secondLink).toHaveFocus(); - expect(button).not.toHaveFocus(); - expect(firstLink).not.toHaveFocus(); + it('applies custom aria-roledescription when provided', () => { + const { view } = renderView({ + ariaRoleDescription: 'Botón de más información', }); + const button = view.getByRole('button'); + expect(button).toHaveAttribute( + 'aria-roledescription', + 'Botón de más información' + ); }); }); @@ -241,7 +276,7 @@ describe('InfoTip', () => { await pressKey('{Escape}'); await waitFor(() => { - expectTipsClosed(tips.map(({ info }) => ({ text: info }))); + expectTipsClosed(); }); }); @@ -264,7 +299,7 @@ describe('InfoTip', () => { await userEvent.click(view.getByTestId('outside')); await waitFor(() => { - expectTipsClosed(tips.map(({ info }) => ({ text: info }))); + expectTipsClosed(); }); }); @@ -279,17 +314,13 @@ describe('InfoTip', () => { await openInfoTipsWithKeyboard({ view, count: tips.length }); await waitFor(() => { - expectTipsVisible( - tips.map(({ info, placement }) => ({ text: info, placement })) - ); + expectTipsVisible(tips.map(({ info }) => ({ text: info }))); }); await pressKey('{Escape}'); await waitFor(() => { - expectTipsClosed( - tips.map(({ info, placement }) => ({ text: info, placement })) - ); + expectTipsClosed(); }); }); }); diff --git a/packages/gamut/src/Tip/__tests__/helpers.tsx b/packages/gamut/src/Tip/__tests__/helpers.tsx index 4eaa8ef41a..9807f6b590 100644 --- a/packages/gamut/src/Tip/__tests__/helpers.tsx +++ b/packages/gamut/src/Tip/__tests__/helpers.tsx @@ -5,19 +5,17 @@ import { createRef, RefObject } from 'react'; import { Anchor } from '../../Anchor'; import { Text } from '../../Typography'; -import { InfoTip, InfoTipProps } from '../InfoTip'; +import { InfoTip } from '../InfoTip'; import { TipPlacements } from '../shared/types'; type InfoTipView = ReturnType< ReturnType> >['view']; -type Placement = NonNullable; - type ViewParam = { view: InfoTipView }; type LinkTextParam = { linkText: string }; type InfoParam = { info: string }; -type PlacementParam = { placement: Placement }; +type PlacementParam = { placement: TipPlacements }; export const createFocusOnClick = (ref: RefObject) => { return ({ isTipHidden }: { isTipHidden: boolean }) => { @@ -33,13 +31,14 @@ export const createLinkSetup = ({ href?: string; }) => { const containerRef = createRef(); + const onClick = createFocusOnClick(containerRef); const info = ( Hey! Here is a {linkText} that is super important. ); - return { containerRef, info, onClick: createFocusOnClick(containerRef) }; + return { containerRef, info, onClick }; }; export const createMultiLinkSetup = ({ @@ -54,27 +53,24 @@ export const createMultiLinkSetup = ({ secondHref?: string; }) => { const containerRef = createRef(); + const onClick = createFocusOnClick(containerRef); const info = ( {firstLinkText} and{' '} {secondLinkText} ); - return { containerRef, info, onClick: createFocusOnClick(containerRef) }; + return { containerRef, info, onClick }; }; export const clickButton = async (view: InfoTipView) => { - const button = view.getByLabelText('Show information'); - await act(async () => { - await userEvent.click(button); - }); + const button = view.getByRole('button'); + await userEvent.click(button); return button; }; export const pressKey = async (key: string) => { - await act(async () => { - await userEvent.keyboard(key); - }); + await userEvent.keyboard(key); }; export const waitForLinkToHaveFocus = async ({ @@ -104,95 +100,32 @@ export const openTipTabToLinkAndWaitForFocus = async ( linkText: string ) => { const link = await openTipAndWaitForLink({ view, linkText }); - await act(async () => { - await userEvent.tab(); - }); + await userEvent.tab(); await waitFor(() => { expect(link).toHaveFocus(); }); return link; }; -export const testShowTipOnClick = async ({ - view, - info, - placement, -}: ViewParam & InfoParam & PlacementParam) => { - const isInline = placement === 'inline'; - const tip = isInline ? view.getByText(info) : null; - - if (isInline) { - expect(tip).not.toBeVisible(); - } else { - expect(view.queryByText(info)).toBeNull(); - } - - await act(async () => { - await userEvent.click(view.getByRole('button')); - }); - - if (isInline) { - expect(tip?.parentElement).not.toHaveStyle({ - visibility: 'hidden', - opacity: 0, - }); - expect(tip).toBeVisible(); - } else { - // The first get by text result is the a11y text, the second is the actual tip text - expect(view.queryAllByText(info).length).toBe(2); - } -}; - -export const testEscapeKeyReturnsFocus = async ({ - view, - info, - placement, -}: ViewParam & InfoParam & PlacementParam) => { - const button = view.getByLabelText('Show information'); - await act(async () => { - await userEvent.click(button); - }); - - const isInline = placement === 'inline'; - - if (isInline) { - const tip = getTipContent(view, info); - expect(tip).toBeVisible(); - } else { - await waitFor(() => { - expect(view.getAllByText(info).length).toBeGreaterThan(0); - }); - } - - await pressKey('{Escape}'); - - await waitFor(() => { - if (isInline) { - expect(getTipContent(view, info)).not.toBeVisible(); - } else { - expect(view.queryByText(info)).toBeNull(); - } - expect(button).toHaveFocus(); - }); +const waitForPopoverFocus = async (view: InfoTipView) => { + await waitFor( + () => { + const popover = view.getByTestId('popover-content-container'); + expect(popover).toHaveFocus(); + }, + { timeout: 2000 } + ); }; export const testFocusWrap = async ({ view, - containerRef, direction, }: ViewParam & { - containerRef: RefObject; direction: 'forward' | 'backward'; }) => { const button = await clickButton(view); - await waitFor( - () => { - expect(containerRef.current).toBeTruthy(); - expect(containerRef.current).toHaveFocus(); - }, - { timeout: 2000 } - ); + await waitForPopoverFocus(view); if (direction === 'forward') { await pressKey('{Tab}'); @@ -206,17 +139,18 @@ export const testFocusWrap = async ({ }); }; -export const getTipContent = ( - view: InfoTipView, - text: string, - useQuery = false +export const testTabFromPopoverWithNoInteractiveElements = async ( + view: InfoTipView ) => { - const elements = view[useQuery ? 'queryAllByText' : 'getAllByText'](text); - // Find the tip body (not the screenreader text with aria-live="assertive") - return ( - elements.find((el) => el.getAttribute('aria-live') !== 'assertive') ?? - elements[0] - ); + const button = await clickButton(view); + + await waitForPopoverFocus(view); + + await pressKey('{Tab}'); + + await waitFor(() => { + expect(button).toHaveFocus(); + }); }; export const testTabbingBetweenLinks = async ({ @@ -229,10 +163,10 @@ export const testTabbingBetweenLinks = async ({ secondLinkText: string; placement: TipPlacements; }) => { - await clickButton(view); + const button = await clickButton(view); await waitFor(() => { - expect(view.getByText(firstLinkText)).toBeVisible(); + expect(button).toHaveAttribute('aria-expanded', 'true'); }); await pressKey('{Tab}'); @@ -247,7 +181,7 @@ export const testTabbingBetweenLinks = async ({ expect(firstLink).not.toHaveFocus(); if (placement === 'floating') { - expect(view.getByLabelText('Show information')).not.toHaveFocus(); + expect(button).not.toHaveFocus(); } }; @@ -256,9 +190,9 @@ export const setupLinkTestWithPlacement = ( placement: TipPlacements, renderView: ReturnType> ) => { - const { containerRef, info, onClick } = createLinkSetup({ linkText }); + const { info, onClick } = createLinkSetup({ linkText }); const { view } = renderView({ placement, info, onClick }); - return { view, containerRef, info, onClick }; + return { view, info, onClick }; }; export const setupMultiLinkTestWithPlacement = ( @@ -283,12 +217,12 @@ export const testEscapeKeyWithOutsideFocus = async ({ outsideButton.textContent = 'Outside Button'; await withTemporaryElement(outsideButton, document.body, async () => { - const button = await clickButton(view); + const button = view.getByLabelText('Show information'); + await userEvent.click(button); await waitFor(() => { expect(button).toHaveAttribute('aria-expanded', 'true'); - const tip = getTipContent(view, info); - expect(tip).toBeVisible(); + expect(view.getByText(info)).toBeVisible(); }); outsideButton.focus(); @@ -298,7 +232,7 @@ export const testEscapeKeyWithOutsideFocus = async ({ await waitFor(() => { expect(button).toHaveAttribute('aria-expanded', 'false'); - const tip = getTipContent(view, info, true); + const tip = view.queryByText(info); expect(tip).not.toBeVisible(); }); }); @@ -308,19 +242,11 @@ const assertTipOpen = async ({ view, button, info, - placement, -}: ViewParam & InfoParam & PlacementParam & { button: HTMLElement }) => { - const isFloating = placement === 'floating'; - - if (isFloating) { - await waitFor(() => { - expect(view.queryAllByText(info).length).toBe(2); - expect(button).toHaveAttribute('aria-expanded', 'true'); - }); - } else { - expect(getTipContent(view, info)).toBeVisible(); +}: ViewParam & InfoParam & { button: HTMLElement }) => { + await waitFor(() => { + expect(view.getByText(info)).toBeVisible(); expect(button).toHaveAttribute('aria-expanded', 'true'); - } + }); }; const assertTipClosed = async ({ @@ -332,10 +258,11 @@ const assertTipClosed = async ({ const isFloating = placement === 'floating'; await waitFor(() => { + const tip = view.queryByText(info); if (isFloating) { - expect(view.queryByText(info)).toBeNull(); + expect(tip).toBeNull(); } else { - expect(getTipContent(view, info)).not.toBeVisible(); + expect(tip).not.toBeVisible(); } expect(button).toHaveAttribute('aria-expanded', 'false'); }); @@ -361,7 +288,7 @@ export const testOutsideClick = async ({ }: ViewParam & InfoParam & PlacementParam) => { const button = await clickButton(view); - await assertTipOpen({ view, button, info, placement }); + await assertTipOpen({ view, button, info }); const outsideElement = document.createElement('div'); @@ -378,7 +305,7 @@ export const testModalDoesNotCloseInfoTip = async ({ }: ViewParam & InfoParam & PlacementParam) => { const button = await clickButton(view); - await assertTipOpen({ view, button, info, placement }); + await assertTipOpen({ view, button, info }); const mockModal = document.createElement('div'); mockModal.setAttribute('role', 'dialog'); @@ -393,12 +320,12 @@ export const testModalDoesNotCloseInfoTip = async ({ await withTemporaryElement(mockModal, parent, async () => { modalButton.focus(); await pressKey('{Escape}'); - await assertTipOpen({ view, button, info, placement }); + await assertTipOpen({ view, button, info }); }); } else { await withTemporaryElement(mockModal, parent, async () => { await pressKey('{Escape}'); - await assertTipOpen({ view, button, info, placement }); + await assertTipOpen({ view, button, info }); }); } }; @@ -409,19 +336,13 @@ export const testRapidToggle = async ({ }: ViewParam & { onClick: jest.Mock }) => { const button = view.getByLabelText('Show information'); - await act(async () => { - await userEvent.click(button); - }); + await userEvent.click(button); await waitFor(() => expect(onClick).toHaveBeenCalledTimes(1)); - await act(async () => { - await userEvent.click(button); - }); + await userEvent.click(button); await waitFor(() => expect(onClick).toHaveBeenCalledTimes(2)); - await act(async () => { - await userEvent.click(button); - }); + await userEvent.click(button); await waitFor(() => expect(onClick).toHaveBeenCalledTimes(3)); expect(onClick).toHaveBeenCalledTimes(3); @@ -439,37 +360,23 @@ export const testInfoTipInsideModalClosesOnEscape = async ({ const { view } = renderView(); const openModalButton = view.getByRole('button', { name: 'Open Modal' }); - await act(async () => { - await userEvent.click(openModalButton); - }); + await userEvent.click(openModalButton); await waitFor(() => { expect(view.getByRole('dialog')).toBeInTheDocument(); }); const infoTipButton = view.getByLabelText('Show information'); + await userEvent.click(infoTipButton); - await act(async () => { - await userEvent.click(infoTipButton); - }); - - // Wait for InfoTip to be visible await waitFor(() => { - const infoTexts = view.getAllByText(info); - const visibleInfo = infoTexts.find( - (el) => el.getAttribute('aria-hidden') !== 'true' - ); - expect(visibleInfo).toBeVisible(); + expect(view.getByText(info)).toBeVisible(); }); await pressKey('{Escape}'); - // InfoTip should be closed - both the tip body and screenreader text should not be visible await waitFor(() => { - const infoTexts = view.queryAllByText(info); - infoTexts.forEach((el) => { - expect(el).not.toBeVisible(); - }); + expect(view.queryByText(info)).not.toBeVisible(); }); expect(view.getByRole('dialog')).toBeInTheDocument(); @@ -480,60 +387,6 @@ type ViewWithQueries = { getAllByLabelText: (text: string) => HTMLElement[]; }; -export const getVisibleTip = ({ - text, - placement, -}: { - text: string; - placement?: 'inline' | 'floating'; -}) => { - const elements = screen.queryAllByText(text); - - for (const el of elements) { - if (el.closest('[class*="ScreenreaderNavigableText"]')) { - continue; - } - - if (!placement || placement === 'inline') { - const tipBody = el.closest('[class*="TipBody"]'); - if (tipBody && tipBody.getAttribute('aria-hidden') === 'false') { - return el; - } - } - - if (placement === 'floating') { - const popover = el.closest('[data-testid="popover-content-container"]'); - if (popover) { - return el; - } - } - } - - return undefined; -}; - -export const expectTipToBeVisible = ({ - text, - placement, -}: { - text: string; - placement?: 'inline' | 'floating'; -}) => { - const tip = getVisibleTip({ text, placement }); - expect(tip).toBeVisible(); -}; - -export const expectTipToBeClosed = ({ - text, - placement, -}: { - text: string; - placement?: 'inline' | 'floating'; -}) => { - const tip = getVisibleTip({ text, placement }); - expect(tip).not.toBeVisible(); -}; - export const openInfoTipsWithKeyboard = async ({ view, count, @@ -542,29 +395,37 @@ export const openInfoTipsWithKeyboard = async ({ count: number; }) => { const buttons = view.getAllByLabelText('Show information'); - buttons[0].focus(); - await userEvent.keyboard('{Enter}'); - for (let i = 1; i < count; i += 1) { - // eslint-disable-next-line no-await-in-loop - await userEvent.tab(); - // eslint-disable-next-line no-await-in-loop + await act(async () => { + buttons[0].focus(); await userEvent.keyboard('{Enter}'); - } + + for (let i = 1; i < count; i += 1) { + // eslint-disable-next-line no-await-in-loop + await userEvent.tab(); + // eslint-disable-next-line no-await-in-loop + await userEvent.keyboard('{Enter}'); + } + }); + + // Wait for all tips to finish opening + await waitFor(() => { + buttons.forEach((button) => { + expect(button).toHaveAttribute('aria-expanded', 'true'); + }); + }); }; -export const expectTipsVisible = ( - tips: { text: string; placement?: 'inline' | 'floating' }[] -) => { - tips.forEach(({ text, placement }) => { - expectTipToBeVisible({ text, placement }); +export const expectTipsVisible = (tips: { text: string }[]) => { + tips.forEach(({ text }) => { + const element = screen.queryByText(text); + expect(element).toBeInTheDocument(); }); }; -export const expectTipsClosed = ( - tips: { text: string; placement?: 'inline' | 'floating' }[] -) => { - tips.forEach(({ text, placement }) => { - expectTipToBeClosed({ text, placement }); +export const expectTipsClosed = () => { + const buttons = screen.getAllByLabelText('Show information'); + buttons.forEach((button) => { + expect(button).toHaveAttribute('aria-expanded', 'false'); }); }; diff --git a/packages/gamut/src/Tip/__tests__/mocks.tsx b/packages/gamut/src/Tip/__tests__/mocks.tsx index af62b1ced5..9ccc2b2811 100644 --- a/packages/gamut/src/Tip/__tests__/mocks.tsx +++ b/packages/gamut/src/Tip/__tests__/mocks.tsx @@ -30,7 +30,11 @@ export const InfoTipInsideModalMock: React.FC< title="Test Modal" onRequestClose={() => setIsOpen(false)} > - + ); @@ -43,7 +47,12 @@ export const MultipleInfoTipsMock: React.FC<{ return ( <> {tips.map(({ id, info, placement }) => ( - + ))} {includeOutsideElement &&
Outside
} diff --git a/packages/gamut/src/Tip/shared/FloatingTip.tsx b/packages/gamut/src/Tip/shared/FloatingTip.tsx index c251d1570c..c301366154 100644 --- a/packages/gamut/src/Tip/shared/FloatingTip.tsx +++ b/packages/gamut/src/Tip/shared/FloatingTip.tsx @@ -31,7 +31,7 @@ export const FloatingTip: React.FC = ({ loading, narrow, overline, - popoverContentRef, + contentRef, truncateLines, type, username, @@ -152,9 +152,7 @@ export const FloatingTip: React.FC = ({ width={inheritDims ? 'inherit' : undefined} onBlur={toolOnlyEventFunc} onFocus={toolOnlyEventFunc} - onKeyDown={ - escapeKeyPressHandler ? (e) => escapeKeyPressHandler(e) : undefined - } + onKeyDown={escapeKeyPressHandler} onMouseDown={(e) => e.preventDefault()} onMouseEnter={toolOnlyEventFunc} > @@ -167,7 +165,7 @@ export const FloatingTip: React.FC = ({ horizontalOffset={offset} isOpen={isPopoverOpen} outline - popoverContainerRef={popoverContentRef} + popoverContainerRef={contentRef} skipFocusTrap targetRef={ref} variant="secondary" diff --git a/packages/gamut/src/Tip/shared/InlineTip.tsx b/packages/gamut/src/Tip/shared/InlineTip.tsx index dec57516fa..871cfaac1a 100644 --- a/packages/gamut/src/Tip/shared/InlineTip.tsx +++ b/packages/gamut/src/Tip/shared/InlineTip.tsx @@ -23,6 +23,7 @@ export const InlineTip: React.FC = ({ loading, narrow, overline, + contentRef, truncateLines, type, username, @@ -45,9 +46,7 @@ export const InlineTip: React.FC = ({ height={inheritDims ? 'inherit' : undefined} ref={wrapperRef} width={inheritDims ? 'inherit' : undefined} - onKeyDown={ - escapeKeyPressHandler ? (e) => escapeKeyPressHandler(e) : undefined - } + onKeyDown={escapeKeyPressHandler} > {children} @@ -65,7 +64,9 @@ export const InlineTip: React.FC = ({ color="currentColor" horizNarrow={narrow && isHorizontalCenter} id={id} + ref={contentRef} role={type === 'tool' ? 'tooltip' : undefined} + tabIndex={type === 'info' ? -1 : undefined} width={narrow && !isHorizontalCenter ? narrowWidth : 'max-content'} zIndex="auto" > diff --git a/packages/gamut/src/Tip/shared/types.tsx b/packages/gamut/src/Tip/shared/types.tsx index a91c5e6a6f..164ed1aaf3 100644 --- a/packages/gamut/src/Tip/shared/types.tsx +++ b/packages/gamut/src/Tip/shared/types.tsx @@ -78,7 +78,7 @@ export type TipPlacementComponentProps = Omit< escapeKeyPressHandler?: (event: React.KeyboardEvent) => void; id?: string; isTipHidden?: boolean; - popoverContentRef?: + contentRef?: | React.RefObject | ((node: HTMLDivElement | null) => void); type: 'info' | 'tool' | 'preview'; diff --git a/packages/styleguide/src/lib/Atoms/FormElements/FormGroup/FormGroup.mdx b/packages/styleguide/src/lib/Atoms/FormElements/FormGroup/FormGroup.mdx index bafb0f40f6..6690273240 100644 --- a/packages/styleguide/src/lib/Atoms/FormElements/FormGroup/FormGroup.mdx +++ b/packages/styleguide/src/lib/Atoms/FormElements/FormGroup/FormGroup.mdx @@ -69,6 +69,12 @@ A field can include our existing `InfoTip`< +#### Accessibility + +InfoTip buttons are automatically labelled by string field labels for accessibility. + + + ## Playground diff --git a/packages/styleguide/src/lib/Atoms/FormElements/FormGroup/FormGroup.stories.tsx b/packages/styleguide/src/lib/Atoms/FormElements/FormGroup/FormGroup.stories.tsx index 09faa218a1..c8ce0e0781 100644 --- a/packages/styleguide/src/lib/Atoms/FormElements/FormGroup/FormGroup.stories.tsx +++ b/packages/styleguide/src/lib/Atoms/FormElements/FormGroup/FormGroup.stories.tsx @@ -97,3 +97,14 @@ export const HighEmphasisInfoTip: Story = { children: , }, }; + +export const InfoTipAutoLabelling: Story = { + args: { + label: 'Email address', + htmlFor: 'auto-label-input', + infotip: { + info: 'We will never share your email with third parties.', + }, + children: , + }, +}; diff --git a/packages/styleguide/src/lib/Molecules/Tips/InfoTip/InfoTip.mdx b/packages/styleguide/src/lib/Molecules/Tips/InfoTip/InfoTip.mdx index 15b440bf55..d8123beb1f 100644 --- a/packages/styleguide/src/lib/Molecules/Tips/InfoTip/InfoTip.mdx +++ b/packages/styleguide/src/lib/Molecules/Tips/InfoTip/InfoTip.mdx @@ -28,8 +28,7 @@ export const parameters = { A tip is triggered by clicking on an information icon button and can be closed by clicking outside, pressing Esc, or clicking the info button again. Use an infotip to provide additional info about a nearby element or content. - -Infotip consists of an icon button and the .tip-bg subcomponent. The info button has low and high emphasis variants and the `.tip` has 4 alignment variants. +The info button has low and high emphasis variants and the `Tip` has 4 alignment variants. ## Variants @@ -57,16 +56,18 @@ This `floating` variant should only be used as needed. ### InfoTips with links or buttons -Links or buttons within InfoTips should be used sparingly and only when the information is critical to the user's understanding of the content. If an infotip _absolutely requires_ a link or button, it needs to provide a programmatic focus by way of the `onClick` prop. The `onClick` prop accepts a function that can accept an `{isTipHidden}` argument and using that you can set programmatic focus as needed. +Links or buttons within InfoTips should be used sparingly and only when the information is critical to the user's understanding of the content. When an InfoTip opens, focus automatically moves to the tip content, allowing keyboard users to immediately interact with any links or buttons inside. -### Floating placement +### Automatic Focus Management -When using `placement="floating"`, InfoTips implements focus management for easier navigation: +InfoTips automatically manage focus for optimal keyboard accessibility: -- **Tab**: Navigate forward through focusable elements (links, buttons) inside the tip. When reaching the last element, wraps back to the InfoTip button for convenience -- **Shift+Tab**: Navigate backward naturally through the page +- **Opening**: Focus automatically moves to the tip content when opened +- **Tab (Floating)**: Navigate forward through focusable elements (links, buttons) inside the tip. When reaching the last element, wraps back to the InfoTip button +- **Shift+Tab (Floating)**: Navigate backward naturally - from the button, exits to the previous page element +- **Tab/Shift+Tab (Inline)**: Follows normal document flow - **Escape**: Closes the tip and returns focus to the InfoTip button @@ -82,6 +83,21 @@ InfoTips have intelligent Escape key handling that works correctly both inside a +## Custom Accessible Labeling + +Provide either `ariaLabel` or `ariaLabelledby` to ensure screen reader users understand the purpose of the InfoTip button. + +The InfoTip button's accessible label can be customized using either prop: + +- **`ariaLabel`**: Directly sets the accessible label text. Useful when you want to provide a custom label without referencing another element. +- **`ariaLabelledby`**: References the ID of another element to use as the label. Useful when you want the InfoTip button to be labeled by visible text elsewhere on the page. This is useful for when the `InfoTip` is beside text that contextualizes it. + +### Custom Role Description + +The `InfoTipButton` uses [`aria-roledescription`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-roledescription) to provide additional context to screen reader users about the button's specific purpose. This defaults to `"More information button"` but can be customized via the `ariaRoleDescription` prop for translation or other accessibility needs. + + + ## InfoTips and zIndex You can change the zIndex of your `InfoTip` with the zIndex property. diff --git a/packages/styleguide/src/lib/Molecules/Tips/InfoTip/InfoTip.stories.tsx b/packages/styleguide/src/lib/Molecules/Tips/InfoTip/InfoTip.stories.tsx index 66807b72d2..5fa267cfd9 100644 --- a/packages/styleguide/src/lib/Molecules/Tips/InfoTip/InfoTip.stories.tsx +++ b/packages/styleguide/src/lib/Molecules/Tips/InfoTip/InfoTip.stories.tsx @@ -4,17 +4,20 @@ import { FillButton, FlexBox, GridBox, + IconButton, InfoTip, Modal, Text, } from '@codecademy/gamut'; +import { SparkleIcon } from '@codecademy/gamut-icons'; import type { Meta, StoryObj } from '@storybook/react'; -import { useRef, useState } from 'react'; +import { useState } from 'react'; const meta: Meta = { component: InfoTip, args: { alignment: 'top-left', + ariaLabel: 'More information', info: `I am additional information about a nearby element or content.`, }, }; @@ -28,7 +31,10 @@ export const Emphasis: Story = { }, render: (args) => ( - Some text that needs info + + Some text that needs info + + ), }; @@ -38,10 +44,15 @@ export const Alignments: Story = { {(['top-right', 'top-left', 'bottom-right', 'bottom-left'] as const).map( (alignment) => { + const labelId = `alignment-${alignment}`; return ( - {alignment} - + {alignment} + ); } @@ -56,10 +67,51 @@ export const Placement: Story = { }, render: (args) => ( - + This text is in a small space and needs floating placement {' '} - + + + ), +}; + +export const AriaLabel: Story = { + render: (args) => ( + + + + Using ariaLabel (no visible label text): + + + + null} + /> + + + + + + Using ariaLabelledby (references visible text): + + + + + I am some helpful yet concise text that needs more explanation + + + ), }; @@ -69,19 +121,16 @@ export const WithLinksOrButtons: Story = { placement: 'floating', }, render: function WithLinksOrButtons(args) { - const ref = useRef(null); - - const onClick = ({ isTipHidden }: { isTipHidden: boolean }) => { - if (!isTipHidden) ref.current?.focus(); - }; - return ( - This text is in a small space and needs info {' '} + + This text is in a small space and needs info + {' '} + Hey! Here is a{' '} cool link @@ -93,7 +142,6 @@ export const WithLinksOrButtons: Story = { that is also super important. } - onClick={onClick} /> ); @@ -102,42 +150,35 @@ export const WithLinksOrButtons: Story = { export const KeyboardNavigation: Story = { render: function KeyboardNavigation() { - const floatingRef = useRef(null); - const inlineRef = useRef(null); - const examples = [ { title: 'Floating Placement', placement: 'floating' as const, - ref: floatingRef, links: ['Link 1', 'Link 2', 'Link 3'], }, { title: 'Inline Placement', placement: 'inline' as const, alignment: 'bottom-right' as const, - ref: inlineRef, links: ['Link A', 'Link B'], }, ]; return ( - + - {examples.map(({ title, placement, alignment, ref, links }) => { - const onClick = ({ isTipHidden }: { isTipHidden: boolean }) => { - if (!isTipHidden) ref.current?.focus(); - }; - + {examples.map(({ title, placement, alignment, links }) => { + const labelId = `keyboard-nav-${placement}`; return ( - + {title} + {links.map((label, idx) => ( <> {idx > 0 && ', '} @@ -150,7 +191,6 @@ export const KeyboardNavigation: Story = { } placement={placement} - onClick={onClick} /> ); @@ -162,6 +202,10 @@ export const KeyboardNavigation: Story = { Keyboard Navigation: +
  • + Opening: Focus automatically moves to the tip + content when opened +
  • Floating - Tab: Navigates forward through links, then wraps to button (contained) @@ -224,8 +268,10 @@ export const InfoTipInsideModal: Story = { This modal contains an InfoTip below: - Some text that needs explanation - + + Some text that needs explanation + + @@ -253,11 +299,14 @@ export const ZIndex: Story = { I will not be behind the infotip, sad + unreadable - + I will be behind the infotip, nice + great - + ), }; @@ -265,7 +314,10 @@ export const ZIndex: Story = { export const Default: Story = { render: (args) => ( - Some text that needs info + + Some text that needs info + + ), }; diff --git a/packages/styleguide/src/lib/Organisms/ConnectedForm/ConnectedFormGroup/ConnectedFormGroup.mdx b/packages/styleguide/src/lib/Organisms/ConnectedForm/ConnectedFormGroup/ConnectedFormGroup.mdx index f150a0955e..5214d35cbf 100644 --- a/packages/styleguide/src/lib/Organisms/ConnectedForm/ConnectedFormGroup/ConnectedFormGroup.mdx +++ b/packages/styleguide/src/lib/Organisms/ConnectedForm/ConnectedFormGroup/ConnectedFormGroup.mdx @@ -61,6 +61,26 @@ A `ConnectedFormGroup` can be in one of three states: `default`, `error`, or `di +## InfoTip + +A `ConnectedFormGroup` can include an `infotip` prop to provide additional context. + +### Automatic labelling + +InfoTip buttons are automatically labelled by string field labels for accessibility. + + + +### ReactNode labels + +For ReactNode labels (e.g., styled text or icons), you have three options: + +- `labelledByFieldLabel: true` - opt into automatic labelling by the field label +- `ariaLabel` - provide a custom accessible name +- `ariaLabelledby` - reference another element on the page, such as a section heading + + + ## Playground To see how a `ConnectedFormGroup` can be used in a `ConnectedForm`, check out the ConnectedForm page. diff --git a/packages/styleguide/src/lib/Organisms/ConnectedForm/ConnectedFormGroup/ConnectedFormGroup.stories.tsx b/packages/styleguide/src/lib/Organisms/ConnectedForm/ConnectedFormGroup/ConnectedFormGroup.stories.tsx index 716e2ecf22..375c91e32d 100644 --- a/packages/styleguide/src/lib/Organisms/ConnectedForm/ConnectedFormGroup/ConnectedFormGroup.stories.tsx +++ b/packages/styleguide/src/lib/Organisms/ConnectedForm/ConnectedFormGroup/ConnectedFormGroup.stories.tsx @@ -2,7 +2,9 @@ import { ConnectedForm, ConnectedFormGroup, ConnectedFormGroupProps, + ConnectedInput, ConnectedRadioGroupInput, + Text, useConnectedForm, } from '@codecademy/gamut'; import { action } from '@storybook/addon-actions'; @@ -119,3 +121,85 @@ export const States = () => { ); }; + +/** + * InfoTip buttons are automatically labelled by string field labels for accessibility. + * Screen readers will announce "Field Label, button" when focusing the InfoTip. + */ +export const InfoTipAutoLabelling: Story = { + render: () => ( + action('Form Submitted')(values)} + > + + + ), +}; + +/** + * For ReactNode labels, you have three options for accessible InfoTip labelling: + * - `labelledByFieldLabel: true` - uses the field label + * - `ariaLabel` - provides a custom accessible name + * - `ariaLabelledby` - references another element on the page + */ +export const InfoTipWithReactNodeLabel: Story = { + render: () => ( + action('Form Submitted')(values)} + > + + API Configuration + + + Username (labelledByFieldLabel) + + } + name="username" + /> + + Password (ariaLabel) + + } + name="password" + /> + + API Key (ariaLabelledby) + + } + name="apiKey" + /> + + ), +}; diff --git a/packages/styleguide/src/lib/Organisms/GridForm/Fields.mdx b/packages/styleguide/src/lib/Organisms/GridForm/Fields.mdx index 84f408b073..7385423a85 100644 --- a/packages/styleguide/src/lib/Organisms/GridForm/Fields.mdx +++ b/packages/styleguide/src/lib/Organisms/GridForm/Fields.mdx @@ -95,3 +95,23 @@ Hidden inputs can be used to include data that users can't see or modify with th We call it a "sweet container" so that bots do not immediately detect it as a honeypot input. + +## InfoTip + +Any field can include an `infotip` prop to provide additional context to users. + +### Automatic labelling + +InfoTip buttons are automatically labelled by string field labels for accessibility. + + + +### ReactNode labels + +For ReactNode labels, you have three options: + +- `labelledByFieldLabel: true` - opt into automatic labelling by the field label +- `ariaLabel` - provide a custom accessible name +- `ariaLabelledby` - reference another element on the page, such as a section heading + + diff --git a/packages/styleguide/src/lib/Organisms/GridForm/Fields.stories.tsx b/packages/styleguide/src/lib/Organisms/GridForm/Fields.stories.tsx index 40ecc134b0..03c2a4e73f 100644 --- a/packages/styleguide/src/lib/Organisms/GridForm/Fields.stories.tsx +++ b/packages/styleguide/src/lib/Organisms/GridForm/Fields.stories.tsx @@ -1,4 +1,4 @@ -import { FormGroup, GridForm, Input } from '@codecademy/gamut'; +import { FormGroup, GridForm, Input, Text } from '@codecademy/gamut'; import { action } from '@storybook/addon-actions'; import type { Meta, StoryObj } from '@storybook/react'; @@ -328,3 +328,75 @@ export const SweetContainer: Story = { ], }, }; + +/** + * InfoTip buttons are automatically labelled by string field labels for accessibility. + * Screen readers will announce "Field Label, button" when focusing the InfoTip. + */ +export const InfoTipAutoLabelling: Story = { + args: { + fields: [ + { + label: 'Email address', + name: 'email', + size: 9, + type: 'email', + infotip: { + info: 'We will never share your email with third parties.', + placement: 'floating', + }, + }, + ], + }, +}; + +/** + * For ReactNode labels, you have three options for accessible InfoTip labelling: + * - `labelledByFieldLabel: true` - uses the field label + * - `ariaLabel` - provides a custom accessible name + * - `ariaLabelledby` - references another element on the page + */ +export const InfoTipWithReactNodeLabel: Story = { + render: (args) => ( + <> + + API Configuration + + + + ), + args: { + fields: [ + { + label: Username (labelledByFieldLabel), + name: 'username', + size: 9, + type: 'text', + infotip: { + info: 'Choose a unique username between 3-20 characters.', + labelledByFieldLabel: true, + }, + }, + { + label: Password (ariaLabel), + name: 'password', + size: 9, + type: 'password', + infotip: { + info: 'Password must be at least 8 characters with one uppercase letter and one number.', + ariaLabel: 'Password requirements', + }, + }, + { + label: API Key (ariaLabelledby), + name: 'apiKey', + size: 9, + type: 'text', + infotip: { + info: 'You can find your API key in the developer settings dashboard.', + ariaLabelledby: 'api-section-heading', + }, + }, + ], + }, +}; diff --git a/packages/styleguide/src/lib/Organisms/GridForm/Layout.mdx b/packages/styleguide/src/lib/Organisms/GridForm/Layout.mdx index 0c1ac337c0..44f9aba287 100644 --- a/packages/styleguide/src/lib/Organisms/GridForm/Layout.mdx +++ b/packages/styleguide/src/lib/Organisms/GridForm/Layout.mdx @@ -34,7 +34,7 @@ Solo field form should always have their solo input be required. They should aut ## InfoTips -A field can include our existing `InfoTip`. See the InfoTip story for more information on what props are available. +A field can include our existing `InfoTip`. See the Fields story for specific accessibility tooling and InfoTip story for more information on what props are available. See the Radio story for an example of how to add a infotip to a radio option.