diff --git a/CHANGELOG.md b/CHANGELOG.md index 93be23c7..4427357b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p - `role` property: `menu` (default) or `listbox`, forwarded to the included `` and used for `aria-haspopup` of the toggler - `` - keyboard interaction follows the [WAI-ARIA combobox pattern](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/#keyboardinteraction): `Tab` and `Shift+Tab` only move the focus, they do not select the active option or create a new item from the query anymore, use `Enter` for it +- `` + - Restore keyboard navigation for non-filterable Select. + - Restore predictable Enter, arrow key, Escape, and Tab behavior, with a visible focus indicator. + - Keep focus on the combobox and expose the active option to screen readers. + - Keep the clear action reachable with Tab and Shift+Tab and support clearing with Enter or Space without opening the options. + - Expose the clear action as a button named by `onClearanceText`, and as disabled if the Select is disabled. + - Prevent any interaction with the clear action of a disabled Select. + - Without `fill`, the wrapper element used for `wrapperProps` and test IDs is displayed inline, like the Select itself. ## [26.2.1] - 2026-11-02 diff --git a/src/components/Form/FieldItem.tsx b/src/components/Form/FieldItem.tsx index 410d5275..87a900c8 100644 --- a/src/components/Form/FieldItem.tsx +++ b/src/components/Form/FieldItem.tsx @@ -33,7 +33,8 @@ export interface FieldItemProps extends React.HTMLAttributes, Te /** * Prevent the automatic connection of the field item parts. * By default, label, input element, helper text and message are connected to each - * other via `for`, `aria-labelledby` and `aria-describedby`. + * other via `for`, `aria-labelledby` and `aria-describedby`, and a click on the label focuses + * input elements that cannot be connected natively via `for`. * Set it to `true` if the using application manages the accessibility attributes itself. */ preventAriaAttribution?: boolean; @@ -41,12 +42,19 @@ export interface FieldItemProps extends React.HTMLAttributes, Te /** * Input elements that could be connected to the label and the help texts of the field item. + * + * Input elements that get their accessible name from their content, e.g. `button` or `output`, + * should refer to themselves via `aria-labelledby`, otherwise the connected label replaces their content as name. + * The field item puts its label ID in front of this self-reference, so label and content are both announced. + * This only works if `preventAriaAttribution` is not `true`. Otherwise, the connection between label + * and input element needs to be managed manually according to the WAI-ARIA specifications anyway. */ const connectableInputSelectors = [ - "input", + 'input:not([type="hidden"])', "textarea", "select", - `.${eccgui}-select button`, + `.${eccgui}-select[role="combobox"]`, + `.${eccgui}-select:not([role="combobox"]) button`, `.${eccgui}-codeeditor .cm-content`, ]; @@ -71,6 +79,9 @@ export const FieldItem = ({ ...otherProps }: FieldItemProps) => { const fieldItemRef = React.useRef(null); + const connectedInputRef = React.useRef(undefined); + /** label ID that was added to `aria-labelledby` by the field item itself, it may be set by the application */ + const labelledByRef = React.useRef<{ element: HTMLElement; id: string } | undefined>(undefined); /** unique ID of this field item, used as suffix for the IDs of its parts */ const fieldItemId = React.useId().replace(/[^a-zA-Z0-9_-]/g, ""); @@ -100,7 +111,10 @@ export const FieldItem = ({ connectableInputSelectors.map((selector) => `.${eccgui}-fielditem__inputfields ${selector}`).join(", "), ), ); - const inputElement = inputElements[0]; + // an explicit `for` of the label selects the connected input element, otherwise the first one is used + const labelTarget = labelElement instanceof HTMLLabelElement ? labelElement.getAttribute("for") : null; + const inputElement = + inputElements.find((element) => labelTarget && element.id === labelTarget) ?? inputElements[0]; const helpElement = ownPart(fieldItem.querySelectorAll(`.${eccgui}-fielditem__helpertext`)); const messageElement = ownPart(fieldItem.querySelectorAll(`.${eccgui}-fielditem__message`)); @@ -114,16 +128,16 @@ export const FieldItem = ({ setMissingId(helpElement, `help_${fieldItemId}`); setMissingId(messageElement, `message_${fieldItemId}`); - if (!inputElement) { - return; - } - /** * Update a list of ID references, only the IDs created by this field item are removed if their part is gone. * References set by the using application always stay untouched. */ - const updateReferences = (attribute: string, parts: [HTMLElement | undefined, string][]) => { - const references = (inputElement.getAttribute(attribute) ?? "").split(" ").filter(Boolean); + const updateReferences = ( + element: HTMLElement, + attribute: string, + parts: [HTMLElement | undefined, string][], + ) => { + const references = (element.getAttribute(attribute) ?? "").split(" ").filter(Boolean); parts.forEach(([element, ownId]) => { if (element) { if (!references.includes(element.id)) { @@ -134,35 +148,83 @@ export const FieldItem = ({ } }); if (references.length > 0) { - inputElement.setAttribute(attribute, references.join(" ")); + element.setAttribute(attribute, references.join(" ")); } else { - inputElement.removeAttribute(attribute); + element.removeAttribute(attribute); } }; - if (labelElement instanceof HTMLLabelElement && labelableElements.includes(inputElement.tagName)) { - // an already set `for` is only kept if it refers to a labelable input element of this field item - const labelTarget = labelElement.getAttribute("for"); - const refersToOwnInput = inputElements.some( - (element) => element.id === labelTarget && labelableElements.includes(element.tagName), - ); - if (!refersToOwnInput) { + const previousInput = connectedInputRef.current; + if (previousInput && previousInput !== inputElement) { + if (previousInput.id === `input_${fieldItemId}`) { + previousInput.removeAttribute("id"); + } + updateReferences(previousInput, "aria-labelledby", [[undefined, `label_${fieldItemId}`]]); + updateReferences(previousInput, "aria-describedby", [ + [undefined, `message_${fieldItemId}`], + [undefined, `help_${fieldItemId}`], + ]); + } + connectedInputRef.current = inputElement; + + // remove the label ID added before if that label is not connected to that input element anymore + const labelledBy = labelledByRef.current; + if (labelledBy && (labelledBy.element !== inputElement || labelledBy.id !== labelElement?.id)) { + updateReferences(labelledBy.element, "aria-labelledby", [[undefined, labelledBy.id]]); + labelledByRef.current = undefined; + } + + if (!inputElement) { + return; + } + + const connectsNatively = + labelElement instanceof HTMLLabelElement && labelableElements.includes(inputElement.tagName); + + if (connectsNatively) { + // a `for` that does not refer to an input element of this field item is replaced + if (labelTarget !== inputElement.id) { labelElement.setAttribute("for", inputElement.id); } - } else if (labelElement) { + } else if (labelElement instanceof HTMLLabelElement) { // labels that are not `label` elements, e.g. of disabled field items, cannot use `for` // the same is true for input elements that cannot be referenced by `for` - if (!inputElement.getAttribute("aria-labelledby")) { - inputElement.setAttribute("aria-labelledby", labelElement.id); + labelElement.removeAttribute("for"); + } + + if (labelElement) { + /** references of the using application, without the label ID added by the field item itself */ + const ownLabelId = labelledByRef.current?.id; + const applicationReferences = (inputElement.getAttribute("aria-labelledby") ?? "") + .split(" ") + .filter((id) => id && id !== ownLabelId); + /** + * A native connection via `for` is overruled by an `aria-labelledby` of the application, + * so the label ID is put in front of those references then. + * This is also necessary for input elements that have an own content as name, e.g. `button` or `output`: + * a native label would replace that name, so they need to refer to themselves via `aria-labelledby`, + * e.g. the toggle button of ` @@ -81,6 +84,45 @@ describe("FieldItem", () => { ), }); expect(label).toHaveAttribute("for", "otherinput"); + // the explicitly labelled input element is the connected one, also for the descriptions + expect(fieldItem.querySelector("#otherinput")).toHaveAccessibleDescription("Help text"); + expect(fieldItem.querySelector("#custominput")).not.toHaveAttribute("aria-describedby"); + }); + it.each([ + [ + "a non-filterable Select", +
+ Value +
, + ], + [ + "a code editor", +
+
+
, + ], + ])("should keep a `for` that refers to an input element after %s", async (_, firstElement) => { + const user = userEvent.setup(); + const { label, fieldItem } = renderFieldItem({ + labelProps: { text: "Label text", htmlFor: "otherinput" }, + helperText: "Help text", + children: ( + <> + {firstElement} + + + ), + }); + const otherInput = fieldItem.querySelector("#otherinput"); + + expect(label).toHaveAttribute("for", "otherinput"); + expect(otherInput).toHaveAccessibleName("Label text"); + expect(otherInput).toHaveAccessibleDescription("Help text"); + expect(fieldItem.querySelector("[aria-labelledby]")).not.toBeInTheDocument(); + expect(fieldItem.querySelector("[aria-describedby]")).toBe(otherInput); + + await user.click(screen.getByText("Label text")); + expect(otherInput).toHaveFocus(); }); it("should replace a `for` that refers to an input element outside of the field item", () => { const { container } = render( @@ -146,6 +188,47 @@ describe("FieldItem", () => { expect(label).toHaveAttribute("for", "custominput"); expect(input).toHaveAttribute("aria-describedby", `customhelp ${message.id} ${help.id}`); }); + it("should put the label ID in front of an `aria-labelledby` of the application", () => { + const { container } = render( + <> + Custom label + + + + , + ); + const label = container.getElementsByClassName(`${eccgui}-fielditem__label`)[0] as HTMLElement; + const input = container.querySelector("input") as HTMLElement; + expect(label).toHaveAttribute("for", input.id); + expect(input).toHaveAttribute("aria-labelledby", `${label.id} customlabel`); + expect(input).toHaveAccessibleName("Label text Custom label"); + }); + it("should not add the label ID to an `aria-labelledby` of the application that contains it already", () => { + const { label, input } = renderFieldItem({ + labelProps: { text: "Label text", id: "customlabel" }, + children: , + }); + expect(label).toHaveAttribute("for", input.id); + expect(input).toHaveAttribute("aria-labelledby", "otherlabel customlabel"); + }); + it("should remove the added label ID if the application removes its `aria-labelledby`", () => { + const fieldItem = (labelledBy?: string) => ( + + + + ); + const { container, rerender } = render(fieldItem("customlabel")); + const label = container.getElementsByClassName(`${eccgui}-fielditem__label`)[0] as HTMLElement; + const input = container.querySelector("input") as HTMLElement; + expect(input).toHaveAttribute("aria-labelledby", `${label.id} customlabel`); + + rerender(fieldItem("otherlabel")); + expect(input).toHaveAttribute("aria-labelledby", `${label.id} otherlabel`); + + rerender(fieldItem()); + expect(input).not.toHaveAttribute("aria-labelledby"); + expect(label).toHaveAttribute("for", input.id); + }); it("should not set IDs and connections if `preventAriaAttribution` is set", () => { const { label, input, help, message } = renderFieldItem({ preventAriaAttribution: true, @@ -185,6 +268,99 @@ describe("FieldItem", () => { expect(label).toHaveAttribute("for", input.id); }); }); + it("connects the Select combobox instead of its inner button", () => { + const { fieldItem, label } = renderFieldItem({ + labelProps: { text: "Filter by language" }, + helperText: "Only matching values are shown.", + messageText: "Choose a language.", + children: ( + + ), + }); + const combobox = fieldItem.querySelector('[role="combobox"]'); + const button = fieldItem.querySelector("button"); + + expect(combobox).toHaveAccessibleName("Filter by language"); + expect(combobox).toHaveAccessibleDescription("Choose a language. Only matching values are shown."); + expect(combobox).toHaveAttribute("id", expect.stringMatching(/^input_/)); + expect(label).not.toHaveAttribute("for"); + expect(button).not.toHaveAttribute("id"); + expect(button).not.toHaveAttribute("aria-describedby"); + }); + it("ignores hidden inputs before a Select", () => { + const { fieldItem, label } = renderFieldItem({ + labelProps: { text: "Type" }, + helperText: "Choose a type.", + children: ( + <> + +
+ +
+ + ), + }); + const hiddenInput = fieldItem.querySelector("input"); + const combobox = fieldItem.querySelector('[role="combobox"]'); + + expect(combobox).toHaveAccessibleName("Type"); + expect(combobox).toHaveAccessibleDescription("Choose a type."); + expect(label).not.toHaveAttribute("for"); + expect(hiddenInput).not.toHaveAttribute("id"); + expect(hiddenInput).not.toHaveAttribute("aria-describedby"); + }); + it("keeps a custom accessible name on the Select combobox", () => { + const { fieldItem } = renderFieldItem({ + labelProps: { text: "Type" }, + children: ( + <> + Custom type +
+ +
+ + ), + }); + + expect(fieldItem.querySelector('[role="combobox"]')).toHaveAccessibleName("Custom type"); + }); + it("reconnects the label when a Select becomes filterable", () => { + const { container, rerender } = render( + +
+ +
+
, + ); + const button = container.querySelector("button"); + const label = container.querySelector("label"); + const selectTarget = container.querySelector('[role="combobox"]'); + expect(selectTarget).toHaveAccessibleName("Type"); + + rerender( + +
+ +
+
, + ); + expect(label).toHaveAttribute("for", button?.id); + expect(selectTarget).not.toHaveAttribute("id"); + expect(selectTarget).not.toHaveAttribute("aria-labelledby"); + + rerender( + +
+ +
+
, + ); + expect(label).not.toHaveAttribute("for"); + expect(container.querySelector('[role="combobox"]')).toHaveAccessibleName("Type"); + expect(button).not.toHaveAttribute("id"); + }); it("should remove the reference to a removed label from `aria-labelledby`", () => { const { container, rerender } = render( } />, @@ -249,6 +425,59 @@ describe("FieldItem", () => { expect(input).toHaveAttribute("aria-labelledby", "customlabel"); expect(input).toHaveAttribute("aria-describedby", "customhelp"); }); + it("should remove a label ID of the application from `aria-labelledby` if another input element is connected", () => { + const fieldItem = (htmlFor?: string) => ( + +
+
+
+ + + ); + const { container, rerender } = render(fieldItem()); + const editor = container.querySelector("#editor"); + const otherInput = container.querySelector("#otherinput"); + expect(editor).toHaveAttribute("aria-labelledby", "customlabel"); + + rerender(fieldItem("otherinput")); + expect(editor).not.toHaveAttribute("aria-labelledby"); + expect(container.querySelector("label")).toHaveAttribute("for", "otherinput"); + expect(otherInput).toHaveAccessibleName("Label text"); + + rerender(fieldItem()); + expect(editor).toHaveAttribute("aria-labelledby", "customlabel"); + expect(container.querySelector("label")).not.toHaveAttribute("for"); + }); + it("should remove a label ID of the application from `aria-labelledby` if the label is removed", () => { + const editor = ( +
+
+
+ ); + const { container, rerender } = render( + {editor}, + ); + expect(container.querySelector("#editor")).toHaveAttribute("aria-labelledby", "customlabel"); + + rerender({editor}); + expect(container.querySelector("#editor")).not.toHaveAttribute("aria-labelledby"); + }); + it("should keep an `aria-labelledby` of the application if another input element is connected", () => { + const fieldItem = (htmlFor?: string) => ( + +
+
+
+ + + ); + const { container, rerender } = render(fieldItem()); + const editor = container.querySelector("#editor"); + expect(editor).toHaveAttribute("aria-labelledby", "otherlabel"); + + rerender(fieldItem("otherinput")); + expect(editor).toHaveAttribute("aria-labelledby", "otherlabel"); + }); it("should connect a code editor input element via `aria-labelledby`", () => { const { container } = render( @@ -304,6 +533,152 @@ describe("FieldItem", () => { }); }); +describe("FieldItem label activation", () => { + const renderCombobox = (props: React.ComponentProps = {}) => + renderFieldItem({ + labelProps: { text: "Type" }, + children: ( +
+ +
+ ), + ...props, + }); + + it("focuses the combobox when clicking its label", async () => { + const user = userEvent.setup(); + renderCombobox(); + + await user.click(screen.getByText("Type")); + + expect(screen.getByRole("combobox", { name: "Type" })).toHaveFocus(); + }); + + it("focuses an input when its label is rendered as a span", async () => { + const user = userEvent.setup(); + renderFieldItem({ + labelProps: { text: "Name", isLayoutForElement: "span" }, + children: , + }); + + await user.click(screen.getByText("Name")); + + expect(screen.getByRole("textbox", { name: "Name" })).toHaveFocus(); + }); + + it("focuses the control inside a focusable ancestor", async () => { + const user = userEvent.setup(); + render( +
+ +
+ Value +
+
+
, + ); + + await user.click(screen.getByText("Type")); + + expect(screen.getByRole("combobox")).toHaveFocus(); + }); + + it("preserves native activation of an explicitly labelled second input", async () => { + const user = userEvent.setup(); + const { input } = renderFieldItem({ + labelProps: { text: "Second", htmlFor: "second" }, + children: ( + <> + + + + ), + }); + const focusFirst = jest.spyOn(input, "focus"); + + await user.click(screen.getByText("Second")); + + expect(screen.getByRole("textbox", { name: "Second" })).toHaveFocus(); + expect(focusFirst).not.toHaveBeenCalled(); + }); + + it.each([false, true])("respects a label click handler with preventDefault=%s", async (cancel) => { + const user = userEvent.setup(); + const onClick = jest.fn((event: React.MouseEvent) => { + if (cancel) event.preventDefault(); + }); + renderCombobox({ labelProps: { text: "Type", onClick } }); + + await user.click(screen.getByText("Type")); + + expect(onClick).toHaveBeenCalledTimes(1); + if (cancel) { + expect(screen.getByRole("combobox")).not.toHaveFocus(); + } else { + expect(screen.getByRole("combobox")).toHaveFocus(); + } + }); + + it.each(["link", "button", "focusable text"])("preserves clicks on a %s inside the label", async (kind) => { + const user = userEvent.setup(); + const help = + kind === "link" ? ( + Help + ) : kind === "button" ? ( + + ) : ( + Help + ); + renderCombobox({ labelProps: { text: "Type", additionalElements: help } }); + const focusControl = jest.spyOn(screen.getByRole("combobox"), "focus"); + + await user.click(screen.getByText("Help")); + + expect(focusControl).not.toHaveBeenCalled(); + expect(screen.getByText("Help")).toHaveFocus(); + }); + + it("preserves clicks on portaled label content", async () => { + const user = userEvent.setup(); + renderCombobox({ + labelProps: { + text: "Type", + additionalElements: createPortal(, document.body), + }, + }); + const focusControl = jest.spyOn(screen.getByRole("combobox"), "focus"); + + await user.click(screen.getByText("Help")); + + expect(focusControl).not.toHaveBeenCalled(); + expect(screen.getByText("Help")).toHaveFocus(); + }); + + it("does not focus the control of a disabled field", async () => { + const user = userEvent.setup(); + renderCombobox({ disabled: true }); + const focusControl = jest.spyOn(screen.getByRole("combobox"), "focus"); + + await user.click(screen.getByText("Type")); + + expect(focusControl).not.toHaveBeenCalled(); + }); + + it("does not add focus behavior when automatic connections are disabled", async () => { + const user = userEvent.setup(); + const onClick = jest.fn(); + renderCombobox({ preventAriaAttribution: true, labelProps: { text: "Type", onClick } }); + const focusControl = jest.spyOn(screen.getByRole("combobox"), "focus"); + + await user.click(screen.getByText("Type")); + + expect(onClick).toHaveBeenCalledTimes(1); + expect(focusControl).not.toHaveBeenCalled(); + }); +}); + describe("FieldItem with CodeEditor", () => { beforeAll(() => { // the code editor needs range support that is not provided by jsdom @@ -338,4 +713,28 @@ describe("FieldItem with CodeEditor", () => { expect(input).toHaveAttribute("aria-labelledby", label.id); expect(input).toHaveAttribute("aria-describedby", message.id); }); + + it.each([ + [false, false], + [false, true], + [true, false], + [true, true], + ])("handles label clicks with disabled=%s and readOnly=%s", async (disabled, readOnly) => { + const user = userEvent.setup(); + const { container } = render( + + + , + ); + const input = container.querySelector(".cm-content"); + await waitFor(() => expect(input).toHaveAccessibleName("Expression")); + + await user.click(screen.getByText("Expression")); + + if (disabled) { + expect(input).not.toHaveFocus(); + } else { + expect(input).toHaveFocus(); + } + }); }); diff --git a/src/components/Select/Select.stories.tsx b/src/components/Select/Select.stories.tsx index e8ca072e..81e2cbab 100644 --- a/src/components/Select/Select.stories.tsx +++ b/src/components/Select/Select.stories.tsx @@ -4,7 +4,7 @@ import { Meta, StoryFn } from "@storybook/react"; import { fn } from "storybook/test"; import { helpersArgTypes } from "../../../.storybook/helpers"; -import { Button, Depiction, MenuItem, Select } from "../../index"; +import { Button, Depiction, FieldItem, MenuItem, Select, Tag } from "../../index"; import { FullExample as DepictionExample } from "../Depiction/stories/Depiction.stories"; export default { @@ -20,19 +20,36 @@ export default { }, } as Meta; -const Template: StoryFn = (args) => +
+); export const Default = Template.bind({}); Default.args = { items: loremIpsum({ p: 1, avgSentencesPerParagraph: 5, random: false }) .toString() .split(".") + .filter((item) => item.trim().length > 0) .map((item) => { return { label: item }; }), - itemRenderer: (item, props) => { - return ; - }, + itemRenderer: (item, { handleClick, handleFocus, id, modifiers }) => ( + + ), fill: true, }; @@ -48,12 +65,66 @@ UsingDepictionAsIcon.args = { /** * A controlled select target is used by adding `children` elements to ` + * + , + ); + + await user.click(screen.getByRole("button", { name: "Choose language" })); + expect(screen.getByRole("combobox")).toHaveAttribute("aria-controls", screen.getByRole("listbox").id); +}); + +describe("Select clear action accessible name", () => { + it.each([ + [false, undefined, "Reset selection", "Reset selection"], + [false, "", "Reset selection", null], + [false, " ", "Reset selection", null], + [false, "Clear type", "Clear type", "Clear type"], + [true, undefined, "Reset selection", "Reset selection"], + [true, "", "Reset selection", null], + [true, " ", "Reset selection", null], + [true, "Clear type", "Clear type", "Clear type"], + ])( + "filterable %s with onClearanceText %j is named %j", + (filterable, clearanceText, expectedName, expectedTitle) => { + render( + ( + + )} + onItemSelect={onItemSelect} + onClearanceText={onClearanceText} + onClearanceHandler={() => { + onClear(); + setText(undefined); + }} + text={text} + placeholder="Choose a type" + contextOverlayProps={{ transitionDuration: 0 }} + /> + + + + ); + }; + render(); + const control = screen.getByRole(filterable ? "button" : "combobox", { name: "Type" }); + const getClearAction = () => control.querySelector('[tabindex="0"]'); + return { control, getClearAction, onClear, onItemSelect }; + }; + + it.each(["Reset selection", ""])("tabs through the clear action with onClearanceText %j", async (clearanceText) => { + const user = userEvent.setup(); + const { control: combobox, getClearAction, onClear } = renderClearableSelect(clearanceText); + + await user.tab(); + expect(screen.getByRole("button", { name: "Before" })).toHaveFocus(); + await user.tab(); + expect(combobox).toHaveFocus(); + await user.tab(); + expect(getClearAction()).toHaveFocus(); + await user.tab(); + expect(screen.getByRole("button", { name: "After" })).toHaveFocus(); + await user.tab({ shift: true }); + expect(getClearAction()).toHaveFocus(); + await user.tab({ shift: true }); + expect(combobox).toHaveFocus(); + await user.tab({ shift: true }); + expect(screen.getByRole("button", { name: "Before" })).toHaveFocus(); + expect(combobox).toHaveAttribute("aria-expanded", "false"); + expect(onClear).not.toHaveBeenCalled(); + }); + + it.each(["{Enter}", " "])("clears with %s without opening the list", async (key) => { + const user = userEvent.setup(); + const { control: combobox, getClearAction, onClear, onItemSelect } = renderClearableSelect(); + await user.tab(); + await user.tab(); + await user.tab(); + expect(getClearAction()).toHaveFocus(); + await user.keyboard("{ArrowDown}"); + expect(combobox).toHaveAttribute("aria-expanded", "false"); + expect(getClearAction()).toHaveFocus(); + + await user.keyboard(key); + + expect(onClear).toHaveBeenCalledTimes(1); + expect(onItemSelect).not.toHaveBeenCalled(); + expect(combobox).toHaveTextContent("Choose a type"); + expect(combobox).toHaveAttribute("aria-expanded", "false"); + expect(combobox).toHaveFocus(); + await user.tab(); + expect(screen.getByRole("button", { name: "After" })).toHaveFocus(); + }); + + it.each(["Reset selection", ""])( + "closes the open list when tabbing to clear with onClearanceText %j", + async (clearanceText) => { + const user = userEvent.setup(); + const { control: combobox, getClearAction } = renderClearableSelect(clearanceText); + await user.tab(); + await user.tab(); + await user.keyboard("{Enter}"); + expect(combobox).toHaveAttribute("aria-expanded", "true"); + + await user.tab(); + + await waitFor(() => expect(combobox).toHaveAttribute("aria-expanded", "false")); + await waitFor(() => expect(getClearAction()).toHaveFocus()); + await user.tab(); + await waitFor(() => expect(screen.getByRole("button", { name: "After" })).toHaveFocus()); + }, + ); + + it("keeps focus on the next control after tabbing past the clear action", async () => { + const user = userEvent.setup(); + renderClearableSelect(); + await user.tab(); + await user.tab(); + await user.tab(); + await user.tab(); + + await act(async () => new Promise((resolve) => setTimeout(resolve, 200))); + + expect(screen.getByRole("button", { name: "After" })).toHaveFocus(); + }); + + it("skips both the combobox and clear action when disabled", async () => { + const user = userEvent.setup(); + const { onClear } = renderClearableSelect("Reset selection", true); + await user.tab(); + await user.tab(); + + expect(screen.getByRole("button", { name: "After" })).toHaveFocus(); + expect(onClear).not.toHaveBeenCalled(); + }); + + it.each(["{Enter}", " "])("clears a filterable Select with %s without opening the list", async (key) => { + const user = userEvent.setup(); + const { control, getClearAction, onClear, onItemSelect } = renderClearableSelect( + "Reset selection", + false, + true, + ); + await user.tab(); + await user.tab(); + expect(control).toHaveFocus(); + await user.tab(); + expect(getClearAction()).toHaveFocus(); + + await user.keyboard(key); + + expect(onClear).toHaveBeenCalledTimes(1); + expect(onItemSelect).not.toHaveBeenCalled(); + expect(control).toHaveFocus(); + expect(control).toHaveTextContent("Choose a type"); + expect(screen.queryByRole("listbox")).not.toBeInTheDocument(); + }); + + it("preserves pointer clearing without opening the list", async () => { + const user = userEvent.setup(); + const { control, getClearAction, onClear } = renderClearableSelect(); + + await user.click(getClearAction()!); + + expect(onClear).toHaveBeenCalledTimes(1); + expect(control).toHaveFocus(); + expect(control).toHaveAttribute("aria-expanded", "false"); + expect(control).toHaveTextContent("Choose a type"); + }); + + it.each([false, true])("handles label clicks with disabled=%s", async (disabled) => { + const user = userEvent.setup(); + render( + + ( + + )} + onItemSelect={onItemSelect} + text="Value" + contextOverlayProps={{ transitionDuration: 0 }} + /> + + + , + ); + + await user.tab(); + await user.tab(); + const combobox = screen.getByRole("combobox"); + expect(combobox).toHaveFocus(); + expect(combobox).toHaveAccessibleName("Type"); + expect(screen.queryByRole("button", { name: "Type" })).not.toBeInTheDocument(); + + await user.keyboard("{Enter}"); + expect(combobox).toHaveAttribute("aria-expanded", "true"); + expect(combobox).toHaveFocus(); + expect(document.getElementById(combobox.getAttribute("aria-activedescendant")!)).toEqual( + screen.getByRole("option", { name: "Value" }), + ); + + await user.keyboard("{ArrowDown}"); + expect(combobox).toHaveFocus(); + expect(combobox).toHaveAttribute("aria-activedescendant", expect.any(String)); + expect(document.getElementById(combobox.getAttribute("aria-activedescendant")!)).toEqual( + screen.getByRole("option", { name: "Object" }), + ); + + await user.keyboard("{Escape}"); + expect(combobox).toHaveFocus(); + expect(onItemSelect).not.toHaveBeenCalled(); + await user.tab(); + await waitFor(() => expect(screen.getByRole("button", { name: "After" })).toHaveFocus()); + await waitFor(() => expect(combobox).toHaveAttribute("aria-expanded", "false")); + await waitFor(() => expect(screen.queryByRole("listbox")).not.toBeInTheDocument()); + expect(combobox).not.toHaveAttribute("aria-activedescendant"); + }); + + it("selects the active option with Enter and keeps a custom button out of the Tab order", async () => { + const user = userEvent.setup(); + const onItemSelect = jest.fn(); + render( + <> + + + , + ); + + const combobox = screen.getByRole("combobox"); + await user.tab(); + expect(combobox).toHaveFocus(); + await user.keyboard("{Enter}{ArrowDown}{Enter}"); + expect(onItemSelect).toHaveBeenCalledWith("Object", expect.anything()); + await waitFor(() => expect(combobox).toHaveAttribute("aria-expanded", "false")); + await waitFor(() => expect(screen.queryByRole("listbox")).not.toBeInTheDocument()); + expect(combobox).toHaveFocus(); + await user.tab(); + expect(screen.getByRole("button", { name: "After" })).toHaveFocus(); + }); + + it("prevents scrolling the page when Space opens or is pressed in the list", async () => { + render( + ( + + )} + onItemSelect={jest.fn()} + text="Value" + contextOverlayProps={{ transitionDuration: 0 }} + /> + + , + ); + + const combobox = screen.getByRole("combobox"); + await user.tab(); + await user.keyboard("{Enter}"); + expect(combobox).toHaveAttribute("aria-expanded", "true"); + await user.tab(); + expect(screen.getByRole("button", { name: "After" })).toHaveFocus(); + await waitFor(() => expect(combobox).toHaveAttribute("aria-expanded", "false")); + }); +}); + +describe("non-filterable Select target", () => { + const CustomTarget = ({ label }: { label: string }) => ; + + const renderSelect = (filterable: boolean, children?: React.ReactNode, text: string | undefined = "Value") => ( + + ); + + it.each([false, true])( + "renders the default target without a select button (inside FieldItem: %s)", + (inFieldItem) => { + const select = renderSelect(false); + render(inFieldItem ? {select} : select); + + const combobox = screen.getByRole("combobox"); + // the clear action is the only button inside the combobox + expect(screen.getByRole("button")).toHaveAccessibleName("Reset selection"); + expect(combobox).toContainElement(screen.getByRole("button")); + expect(combobox).toHaveTextContent("Value"); + // only decorative icons are hidden, the selected value and the clear action stay exposed + expect(combobox.querySelector('[aria-hidden="true"]:not(svg)')).not.toBeInTheDocument(); + if (inFieldItem) { + expect(combobox).toHaveAccessibleName("Type"); + } + }, + ); + + it("exposes the placeholder of the default target", () => { + render(renderSelect(false, undefined, "")); + expect(screen.getByRole("combobox")).toHaveTextContent("Choose a type"); + }); + + it.each([ + ["button", ], + [ + "fragment", + <> + + , + ], + [ + "array", + [ + , + Text, + ], + ], + [ + "div containing a button", +
+ +
, + ], + ["component without prop forwarding", ], + ])("keeps a custom %s target out of the Tab order", async (_, children) => { + const user = userEvent.setup(); + const { container } = render( + <> + {renderSelect(false, children)} + + , + ); + const targetButton = container.querySelector(".eccgui-select button"); + + expect(targetButton).toHaveAttribute("tabindex", "-1"); + expect(targetButton).toHaveAttribute("aria-hidden", "true"); + await user.tab(); + expect(screen.getByRole("combobox")).toHaveFocus(); + await user.tab(); + expect(screen.getByRole("button", { name: "After" })).toHaveFocus(); + }); + + it("keeps focusable elements out of the Tab order that a custom target renders later", async () => { + const user = userEvent.setup(); + let showButton: (show: boolean) => void = () => undefined; + const LateTarget = () => { + const [show, setShow] = React.useState(false); + showButton = setShow; + return Value{show && }; + }; + render( + <> + {renderSelect(false, )} + + , + ); + + act(() => showButton(true)); + const lateButton = screen.getByText("Late"); + await waitFor(() => expect(lateButton).toHaveAttribute("tabindex", "-1")); + expect(lateButton).toHaveAttribute("aria-hidden", "true"); + await user.tab(); + expect(screen.getByRole("combobox")).toHaveFocus(); + await user.tab(); + expect(screen.getByRole("button", { name: "After" })).toHaveFocus(); + }); + + it("keeps an element of a custom target out of the Tab order if it changes its tabindex later", async () => { + let setTabIndex: (tabIndex: number) => void = () => undefined; + const ChangingTarget = () => { + const [tabIndex, setIndex] = React.useState(-1); + setTabIndex = setIndex; + return Value; + }; + render(renderSelect(false, )); + const target = screen.getByText("Value"); + expect(target).toHaveAttribute("tabindex", "-1"); + + act(() => setTabIndex(0)); + await waitFor(() => expect(target).toHaveAttribute("tabindex", "-1")); + expect(target).toHaveAttribute("aria-hidden", "true"); + }); + + it("restores a custom target when the Select becomes filterable", () => { + const children = ( + + ); + const { container, rerender } = render( + {renderSelect(false, children)}, + ); + const getTargetButton = () => container.querySelector(".eccgui-select button"); + expect(getTargetButton()).toHaveAttribute("tabindex", "-1"); + expect(getTargetButton()).toHaveAttribute("aria-hidden", "true"); + + rerender({renderSelect(true, children)}); + expect(getTargetButton()).toHaveAttribute("tabindex", "0"); + expect(getTargetButton()).toHaveAttribute("aria-hidden", "false"); + expect(screen.getByRole("button", { name: "Type" })).toBe(getTargetButton()); + + rerender({renderSelect(false, children)}); + expect(getTargetButton()).toHaveAttribute("tabindex", "-1"); + expect(getTargetButton()).toHaveAttribute("aria-hidden", "true"); + expect(screen.getByRole("combobox", { name: "Type" })).toBeInTheDocument(); + }); + + it("switches the default target between button and combobox content", () => { + const { rerender } = render({renderSelect(false)}); + // the clear action is the only button + expect(screen.getByRole("button")).toHaveAccessibleName("Reset selection"); + + rerender({renderSelect(true)}); + expect(screen.queryByRole("combobox")).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Type" })).toHaveTextContent("Value"); + + rerender({renderSelect(false)}); + expect(screen.getByRole("button")).toHaveAccessibleName("Reset selection"); + expect(screen.getByRole("combobox", { name: "Type" })).toHaveTextContent("Value"); + }); +}); diff --git a/src/components/Select/Select.tsx b/src/components/Select/Select.tsx index 23a7a39a..8142cc09 100644 --- a/src/components/Select/Select.tsx +++ b/src/components/Select/Select.tsx @@ -1,6 +1,7 @@ import React from "react"; import { Classes as BlueprintClasses, InputGroupProps } from "@blueprintjs/core"; -import { Select as BlueprintSelect, SelectProps as BlueprintSelectProps } from "@blueprintjs/select"; +import { executeItemsEqual, Select as BlueprintSelect, SelectProps as BlueprintSelectProps } from "@blueprintjs/select"; +import classNames from "classnames"; import { CLASSPREFIX as eccgui } from "../../configuration/constants"; import { Button, ButtonProps } from "../Button/Button"; @@ -14,6 +15,19 @@ export interface SelectProps TestableComponent, Omit, "popoverTargetProps" | "popoverContentProps" | "popoverProps" | "popoverRef">, Pick { + /** + * Converts a custom query into items passed to `onItemSelect`. Use with `createNewItemRenderer`. + * For restricted input, return an empty array to reject a query and set this prop to `undefined` + * while creation is unavailable. Hiding the create option alone does not disable keyboard creation. + * See the CreatingItems story. + */ + createNewItemFromQuery?: BlueprintSelectProps["createNewItemFromQuery"]; + /** + * Renders the option for adding a custom value alongside the existing items. + * Give it a stable ID and connect `inputProps["aria-activedescendant"]` while it is active; + * clear the reference when the active create option is unavailable. See the CreatingItems story. + */ + createNewItemRenderer?: BlueprintSelectProps["createNewItemRenderer"]; /** * Textual representation of the the selected value. * This is displayed if the select target is not controlled directly via `children` elements. @@ -39,6 +53,8 @@ export interface SelectProps /** * Tooltip to show for the clear button. * Only works with the uncontrolled default select target. + * Set your i18n label, otherwise it falls back to "Reset selection". + * An empty text only removes the tooltip, the clear button keeps "Reset selection" as accessible name. */ onClearanceText?: string; /** @@ -48,6 +64,21 @@ export interface SelectProps wrapperProps?: React.HTMLAttributes; } +const onClearanceTextDefault = "Reset selection"; + +/** + * Elements inside custom `children` of a non-filterable Select that need to be removed from the Tab order. + */ +const focusableSelectors = "a[href], button, input, select, textarea, summary, [tabindex], [contenteditable=true]"; + +const restoreAttribute = (element: HTMLElement, attribute: string, value: string | null) => { + if (value === null) { + element.removeAttribute(attribute); + } else { + element.setAttribute(attribute, value); + } +}; + /** * Create a Select box without the HTML select element. * It is possible to filter options, as well as to add new options if necessary. @@ -64,19 +95,329 @@ export function Select({ rightIcon, onClearanceHandler, inputProps, - onClearanceText = "Reset selection", + filterable = true, + itemRenderer, + onActiveItemChange, + onClearanceText = onClearanceTextDefault, "data-test-id": dataTestId, "data-testid": dataTestid, wrapperProps, ...otherSelectProps }: SelectProps) { + const comboboxRef = React.useRef(null); + const blueprintSelectRef = React.useRef | null>(null); + const tabDestinationRef = React.useRef(null); + const tabPressedRef = React.useRef(false); + const wrapperRef = React.useRef(null); + const itemIds = React.useRef>([]); + /** focusable elements of custom `children` that were hidden inside the combobox, with their original attributes */ + const hiddenTargetElements = React.useRef( + new Map(), + ); + + /** + * The combobox of a non-filterable Select is the only interactive element, so a custom target can only be presentational. + * Focusable elements of custom `children` are removed from the Tab order and hidden from screen readers, + * their original attributes are restored if they are not inside the combobox anymore. + */ + const secureCustomTarget = () => { + const combobox = !filterable && children ? comboboxRef.current : null; + const focusableChildren = combobox + ? Array.from(combobox.querySelectorAll(focusableSelectors)) + : []; + const hiddenElements = hiddenTargetElements.current; + hiddenElements.forEach((original, element) => { + if (!focusableChildren.includes(element)) { + restoreAttribute(element, "tabindex", original.tabIndex); + restoreAttribute(element, "aria-hidden", original.ariaHidden); + hiddenElements.delete(element); + } + }); + focusableChildren.forEach((element) => { + if (!hiddenElements.has(element)) { + hiddenElements.set(element, { + tabIndex: element.getAttribute("tabindex"), + ariaHidden: element.getAttribute("aria-hidden"), + }); + } + // only set changed attributes, otherwise the mutation observer below would be triggered endlessly + if (element.getAttribute("tabindex") !== "-1") { + element.setAttribute("tabindex", "-1"); + } + if (element.getAttribute("aria-hidden") !== "true") { + element.setAttribute("aria-hidden", "true"); + } + }); + }; + const secureCustomTargetRef = React.useRef(secureCustomTarget); + secureCustomTargetRef.current = secureCustomTarget; + + React.useLayoutEffect(() => { + if (!filterable) { + // Blueprint overwrites popoverTargetProps.tabIndex, so set it on the rendered combobox. + const combobox = wrapperRef.current?.querySelector(`.${eccgui}-select[role="combobox"]`); + if (combobox) { + combobox.tabIndex = otherSelectProps.disabled ? -1 : 0; + comboboxRef.current = combobox; + } + } + secureCustomTarget(); + }); + + /** + * Custom `children` may render focusable elements later on, e.g. after loading data, + * without an update of the Select itself. + */ + const hasCustomTarget = !!children; + React.useEffect(() => { + const wrapper = wrapperRef.current; + if (filterable || !hasCustomTarget || !wrapper) { + return; + } + const targetObserver = new MutationObserver(() => secureCustomTargetRef.current()); + targetObserver.observe(wrapper, { + childList: true, + subtree: true, + attributes: true, + attributeFilter: ["tabindex", "aria-hidden", "href", "contenteditable"], + }); + return () => targetObserver.disconnect(); + }, [filterable, hasCustomTarget]); + + /** + * Move focus to the Tab destination after Blueprint restored it to the combobox in the next animation frame. + * If focus was moved again in the meantime, e.g. by a further Tab, that newer destination is used instead. + */ + const keepTabDestination = (tabDestination: HTMLElement) => { + let destination = tabDestination; + const trackFocus = (event: FocusEvent) => { + if (event.target instanceof HTMLElement && event.target !== comboboxRef.current) { + destination = event.target; + } + }; + document.addEventListener("focusin", trackFocus); + // Registered after Blueprint's focus restoration, so it runs after it within the same frame. + requestAnimationFrame(() => { + document.removeEventListener("focusin", trackFocus); + const active = document.activeElement; + if ( + destination.isConnected && + destination !== active && + (active === comboboxRef.current || active === document.body || active === null) + ) { + destination.focus(); + } + }); + }; + + const handleActiveItemChange: BlueprintSelectProps["onActiveItemChange"] = (activeItem, isCreateNewItem) => { + if (!filterable && comboboxRef.current) { + const matchingItem = itemIds.current.find(({ item }) => + executeItemsEqual(otherSelectProps.itemsEqual, item, activeItem), + ); + if (matchingItem && !isCreateNewItem) { + comboboxRef.current.setAttribute("aria-activedescendant", matchingItem.id); + } else { + comboboxRef.current.removeAttribute("aria-activedescendant"); + } + } + onActiveItemChange?.(activeItem, isCreateNewItem); + }; + + const renderItem: BlueprintSelectProps["itemRenderer"] = (item, props) => { + if (props.id) { + itemIds.current[props.index] = { item, id: props.id }; + } + return itemRenderer(item, props); + }; + + const handleClear = (event: React.SyntheticEvent) => { + event.stopPropagation(); + if (otherSelectProps.disabled) { + return; + } + const trigger = event.currentTarget.closest("button"); + onClearanceHandler?.(); + if (filterable) { + trigger?.focus(); + } else { + comboboxRef.current?.focus(); + } + }; + + const handleEnterSpaceUsage = (event: React.KeyboardEvent, triggerClearance: boolean) => { + event.stopPropagation(); + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + + if (triggerClearance) { + handleClear(event); + } + } + }; + + const clearanceText = onClearanceText.trim(); + const clearAction = onClearanceHandler && text && ( + handleEnterSpaceUsage(e, false)} + onKeyUp={(e) => handleEnterSpaceUsage(e, true)} + > + + + ); + const defaultRightIcon = ( + <> + {clearAction} + {typeof rightIcon === "string" ? ( + + ) : ( + (rightIcon ?? ) + )} + + ); + const defaultText = {text || placeholder}; + const textClassName = text ? "" : BlueprintClasses.TEXT_MUTED; + const togglerTestIds = { + "data-test-id": dataTestId ? dataTestId + "_toggler" : undefined, + "data-testid": dataTestid ? dataTestid + "_toggler" : undefined, + }; + + /** + * The default target button of a filterable select refers to itself via `aria-labelledby`. + * Otherwise a connected label, e.g. by `` via `for`, would replace the button text + * as accessible name, and screen readers would not announce the selected value anymore. + * A `` puts its label ID in front of this self-reference, so both are announced. + */ + const defaultTargetId = `defaulttarget_${React.useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; + + const defaultTarget = filterable ? ( +