diff --git a/CHANGELOG.md b/CHANGELOG.md
index be85ba82..fe232e53 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,18 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p
- Added `cutOff` property to set maximum number of raw Markdown characters to render
- ``
- `hidden` property: label is not displayed but stays accessible for screen readers and keyboard navigation
+- ``
+ - label, input element, helper text and message are connected to each other automatically now
+ - each part without an own `id` gets one based on a unique ID of the field item
+ - the label refers to the input element via `for`, or via `aria-labelledby` on the input element if the label is not displayed as `label` element
+ - an already set `for` is only kept if it refers to the ID of the input element of the field item
+ - helper text and message are referred by the input element via `aria-describedby`
+ - `input`, `textarea`, `select`, the toggle button of `` and the editable area of `` are supported as input element
+ - input elements that cannot be referenced by `for`, e.g. the editable area of the code editor, are connected via `aria-labelledby`
+ - parts that are created after the field item was mounted, e.g. by the code editor, are connected as soon as they exist
+ - already set `id` values and connections are never overwritten
+ - ID references created by the field item are removed again if their part is removed from the field item
+ - `preventAriaAttribution` property: prevents this automatic connection of the field item parts
- new `utils` methods:
- `truncateMarkdownDisplay`: helper function to iterate over `Markdown` renderings to improve the experienced `cutOff` value
- new icons:
@@ -26,6 +38,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p
- Carbon, Codemirror, React-Flow
- minimum node version (`engines.node`) is `18.19.0` now
- the build of the ESM distribution needs a synchronous `import.meta.resolve`, which is only available since this version
+- ``
+ - the used `Label` element gets the `eccgui-fielditem__label` class now
- ``
- `allowedHtmlElementsInPreview` option is set to inline elements on default
- uses now the `Markdown.cutOff` property
diff --git a/src/components/Form/FieldItem.tsx b/src/components/Form/FieldItem.tsx
index 28009a57..338b3615 100644
--- a/src/components/Form/FieldItem.tsx
+++ b/src/components/Form/FieldItem.tsx
@@ -30,8 +30,32 @@ export interface FieldItemProps extends React.HTMLAttributes, Te
* Is displayed below the included input element.
*/
messageText?: string;
+ /**
+ * 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`.
+ * Set it to `true` if the using application manages the accessibility attributes itself.
+ */
+ preventAriaAttribution?: boolean;
}
+/**
+ * Input elements that could be connected to the label and the help texts of the field item.
+ */
+const connectableInputSelectors = [
+ "input",
+ "textarea",
+ "select",
+ `.${eccgui}-select button`,
+ `.${eccgui}-codeeditor .cm-content`,
+];
+
+/**
+ * Elements that can be referenced by the `for` attribute of a `label` element.
+ * Other input elements, e.g. the editable area of the code editor, need to use `aria-labelledby`.
+ */
+const labelableElements = ["BUTTON", "INPUT", "METER", "OUTPUT", "PROGRESS", "SELECT", "TEXTAREA"];
+
/**
* Form element that manages the combination of label, helper texts, input element and feedback messages.
*/
@@ -43,11 +67,123 @@ export const FieldItem = ({
helperText,
messageText,
intent,
+ preventAriaAttribution = false,
...otherProps
}: FieldItemProps) => {
+ const fieldItemRef = React.useRef(null);
+ /** 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, "");
+
const intentClass = intent ? " " + IntentClassNames[intent.toUpperCase()] : "";
- const label = ;
+ /**
+ * Connect the parts of the field item to each other for accessibility reasons.
+ * It is done on every update and DOM change because the parts may be replaced, added or removed later on.
+ * Already existing IDs and connections are never overwritten, they are managed by the using application then.
+ * Only the ID references created by the field item itself are removed again if their part does not exist anymore.
+ * It is not done at all if `preventAriaAttribution` is set.
+ */
+ const connectParts = React.useCallback(() => {
+ const fieldItem = fieldItemRef.current;
+ if (!fieldItem || preventAriaAttribution) {
+ return;
+ }
+
+ /** nested field items manage the connections of their own parts */
+ const ownPart = (candidates: NodeListOf): T | undefined =>
+ Array.from(candidates).find((candidate) => candidate.closest(`.${eccgui}-fielditem`) === fieldItem);
+
+ const labelElement = ownPart(fieldItem.querySelectorAll(`.${eccgui}-fielditem__label`));
+ const inputElement = ownPart(
+ fieldItem.querySelectorAll(
+ connectableInputSelectors.map((selector) => `.${eccgui}-fielditem__inputfields ${selector}`).join(", "),
+ ),
+ );
+ const helpElement = ownPart(fieldItem.querySelectorAll(`.${eccgui}-fielditem__helpertext`));
+ const messageElement = ownPart(fieldItem.querySelectorAll(`.${eccgui}-fielditem__message`));
+
+ const setMissingId = (element: HTMLElement | undefined, id: string) => {
+ if (element && !element.id) {
+ element.id = id;
+ }
+ };
+ setMissingId(labelElement, `label_${fieldItemId}`);
+ setMissingId(inputElement, `input_${fieldItemId}`);
+ 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);
+ parts.forEach(([element, ownId]) => {
+ if (element) {
+ if (!references.includes(element.id)) {
+ references.push(element.id);
+ }
+ } else if (references.includes(ownId)) {
+ references.splice(references.indexOf(ownId), 1);
+ }
+ });
+ if (references.length > 0) {
+ inputElement.setAttribute(attribute, references.join(" "));
+ } else {
+ inputElement.removeAttribute(attribute);
+ }
+ };
+
+ if (labelElement instanceof HTMLLabelElement && labelableElements.includes(inputElement.tagName)) {
+ // an already set `for` is only kept if it refers to the ID of the input element of this field item
+ if (labelElement.getAttribute("for") !== inputElement.id) {
+ labelElement.setAttribute("for", inputElement.id);
+ }
+ } else if (labelElement) {
+ // 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);
+ }
+ } else {
+ updateReferences("aria-labelledby", [[undefined, `label_${fieldItemId}`]]);
+ }
+
+ updateReferences("aria-describedby", [
+ [messageElement, `message_${fieldItemId}`],
+ [helpElement, `help_${fieldItemId}`],
+ ]);
+ }, [fieldItemId, preventAriaAttribution]);
+
+ React.useEffect(() => {
+ connectParts();
+ });
+
+ /**
+ * Some parts are created after the field item was mounted, e.g. the editable area of the code editor,
+ * and such changes do not trigger an update of the field item itself.
+ */
+ React.useEffect(() => {
+ const fieldItem = fieldItemRef.current;
+ if (!fieldItem || preventAriaAttribution) {
+ return;
+ }
+ const partsObserver = new MutationObserver(connectParts);
+ partsObserver.observe(fieldItem, { childList: true, subtree: true });
+ return () => partsObserver.disconnect();
+ }, [connectParts, preventAriaAttribution]);
+
+ const label = (
+
+ );
const userhelp =
helperText &&
@@ -69,6 +205,7 @@ export const FieldItem = ({
return (
) => {
+ const { container } = render();
+ const fieldItem = container.firstElementChild as HTMLElement;
+ return {
+ fieldItem,
+ label: fieldItem.getElementsByClassName(`${eccgui}-fielditem__label`)[0] as HTMLElement,
+ input: fieldItem.querySelector(`.${eccgui}-fielditem__inputfields input`) as HTMLElement,
+ help: fieldItem.getElementsByClassName(`${eccgui}-fielditem__helpertext`)[0] as HTMLElement,
+ message: fieldItem.getElementsByClassName(`${eccgui}-fielditem__message`)[0] as HTMLElement,
+ };
+};
+
+describe("FieldItem", () => {
+ describe("connection of its parts", () => {
+ it("should set IDs for all parts that do not have one already", () => {
+ const { label, input, help, message } = renderFieldItem({
+ labelProps: { text: "Label text" },
+ children: ,
+ helperText: "Helper text",
+ messageText: "Message text",
+ });
+ expect(label.id).toMatch(/^label_/);
+ expect(input.id).toMatch(/^input_/);
+ expect(help.id).toMatch(/^help_/);
+ expect(message.id).toMatch(/^message_/);
+ expect([label.id, input.id, help.id, message.id].map((id) => id.split("_")[1])).toEqual(
+ new Array(4).fill(label.id.split("_")[1]),
+ );
+ });
+ it("should create unique IDs for each field item", () => {
+ const { container } = render(
+ <>
+ } />
+ } />
+ >,
+ );
+ const inputs = container.querySelectorAll("input");
+ expect(inputs[0].id).not.toBe(inputs[1].id);
+ });
+ it("should connect label and input element via `for`", () => {
+ const { label, input } = renderFieldItem({
+ labelProps: { text: "Label text" },
+ children: ,
+ });
+ expect(label.tagName).toBe("LABEL");
+ expect(label).toHaveAttribute("for", input.id);
+ expect(input).not.toHaveAttribute("aria-labelledby");
+ });
+ it("should keep a `for` that refers to the ID of the input element", () => {
+ const { label } = renderFieldItem({
+ labelProps: { text: "Label text", htmlFor: "custominput" },
+ children: ,
+ });
+ expect(label).toHaveAttribute("for", "custominput");
+ });
+ it("should replace a `for` that does not refer to the ID of the input element", () => {
+ const { label, input } = renderFieldItem({
+ labelProps: { text: "Label text", htmlFor: "otherelement" },
+ children: ,
+ });
+ expect(input.id).toMatch(/^input_/);
+ expect(label).toHaveAttribute("for", input.id);
+ });
+ it("should replace a `for` that refers to another element than the input element", () => {
+ const { label, input } = renderFieldItem({
+ labelProps: { text: "Label text", htmlFor: "otherinput" },
+ children: (
+ <>
+
+
+ >
+ ),
+ });
+ expect(input).toHaveAttribute("id", "custominput");
+ expect(label).toHaveAttribute("for", "custominput");
+ });
+ it("should connect label and input element via `aria-labelledby` if the label is no `label` element", () => {
+ const { label, input } = renderFieldItem({
+ disabled: true,
+ labelProps: { text: "Label text" },
+ children: ,
+ });
+ expect(label.tagName).not.toBe("LABEL");
+ expect(input).toHaveAttribute("aria-labelledby", label.id);
+ });
+ it("should connect helper text and message to the input element via `aria-describedby`", () => {
+ const { input, help, message } = renderFieldItem({
+ children: ,
+ helperText: "Helper text",
+ messageText: "Message text",
+ });
+ expect(input).toHaveAttribute("aria-describedby", `${message.id} ${help.id}`);
+ });
+ it("should only refer to existing parts via `aria-describedby`", () => {
+ const { input, help } = renderFieldItem({
+ children: ,
+ helperText: "Helper text",
+ });
+ expect(input).toHaveAttribute("aria-describedby", help.id);
+ });
+ it("should not set `aria-describedby` if there is neither helper text nor message", () => {
+ const { input } = renderFieldItem({ children: });
+ expect(input).not.toHaveAttribute("aria-describedby");
+ });
+ it("should keep IDs and connections that are set already", () => {
+ const { label, help, message } = renderFieldItem({
+ labelProps: { text: "Label text", id: "customlabel", htmlFor: "custominput" },
+ children: ,
+ helperText: "Helper text",
+ messageText: "Message text",
+ });
+ const input = document.getElementById("custominput") as HTMLElement;
+ expect(label).toHaveAttribute("id", "customlabel");
+ expect(label).toHaveAttribute("for", "custominput");
+ expect(input).toHaveAttribute("aria-describedby", `customhelp ${message.id} ${help.id}`);
+ });
+ it("should not set IDs and connections if `preventAriaAttribution` is set", () => {
+ const { label, input, help, message } = renderFieldItem({
+ preventAriaAttribution: true,
+ labelProps: { text: "Label text" },
+ children: ,
+ helperText: "Helper text",
+ messageText: "Message text",
+ });
+ [label, input, help, message].forEach((element) => {
+ expect(element.id).toBe("");
+ });
+ expect(label).not.toHaveAttribute("for");
+ expect(input).not.toHaveAttribute("aria-labelledby");
+ expect(input).not.toHaveAttribute("aria-describedby");
+ });
+ it("should also connect `textarea`, `select` and select target elements", () => {
+ const inputElements = {
+ textarea: ,
+ select: (
+
+ ),
+ selecttarget: (
+
+
+
+ ),
+ };
+ Object.entries(inputElements).forEach(([elementName, inputElement]) => {
+ const { container } = render();
+ const label = container.getElementsByClassName(`${eccgui}-fielditem__label`)[0] as HTMLElement;
+ const input = container.querySelector(
+ elementName === "selecttarget" ? "button" : elementName,
+ ) as HTMLElement;
+ expect(input.id).toMatch(/^input_/);
+ expect(label).toHaveAttribute("for", input.id);
+ });
+ });
+ it("should remove the reference to a removed label from `aria-labelledby`", () => {
+ const { container, rerender } = render(
+ } />,
+ );
+ const label = container.getElementsByClassName(`${eccgui}-fielditem__label`)[0] as HTMLElement;
+ const input = container.querySelector("input") as HTMLElement;
+ expect(input).toHaveAttribute("aria-labelledby", label.id);
+
+ rerender(} />);
+ expect(container.getElementsByClassName(`${eccgui}-fielditem__label`).length).toBe(0);
+ expect(input).not.toHaveAttribute("aria-labelledby");
+ });
+ it("should remove the reference to a removed helper text from `aria-describedby`", () => {
+ const { container, rerender } = render(
+ } />,
+ );
+ const message = container.getElementsByClassName(`${eccgui}-fielditem__message`)[0] as HTMLElement;
+ const help = container.getElementsByClassName(`${eccgui}-fielditem__helpertext`)[0] as HTMLElement;
+ const input = container.querySelector("input") as HTMLElement;
+ expect(input).toHaveAttribute("aria-describedby", `${message.id} ${help.id}`);
+
+ rerender(} />);
+ expect(container.getElementsByClassName(`${eccgui}-fielditem__helpertext`).length).toBe(0);
+ expect(input).toHaveAttribute("aria-describedby", message.id);
+ });
+ it("should remove the reference to a removed message from `aria-describedby`", () => {
+ const { container, rerender } = render(
+ } />,
+ );
+ const help = container.getElementsByClassName(`${eccgui}-fielditem__helpertext`)[0] as HTMLElement;
+ const input = container.querySelector("input") as HTMLElement;
+
+ rerender(} />);
+ expect(container.getElementsByClassName(`${eccgui}-fielditem__message`).length).toBe(0);
+ expect(input).toHaveAttribute("aria-describedby", help.id);
+ });
+ it("should remove `aria-describedby` if helper text and message are removed", () => {
+ const { container, rerender } = render(
+ } />,
+ );
+ const input = container.querySelector("input") as HTMLElement;
+ expect(input).toHaveAttribute("aria-describedby");
+
+ rerender(} />);
+ expect(input).not.toHaveAttribute("aria-describedby");
+ });
+ it("should keep references of the using application if parts are removed", () => {
+ const customInput = (
+
+ );
+ const { container, rerender } = render(
+
+ {customInput}
+ ,
+ );
+ const input = container.querySelector("input") as HTMLElement;
+ const help = container.getElementsByClassName(`${eccgui}-fielditem__helpertext`)[0] as HTMLElement;
+ expect(input).toHaveAttribute("aria-labelledby", "customlabel");
+ expect(input).toHaveAttribute("aria-describedby", `customhelp ${help.id}`);
+
+ rerender({customInput});
+ expect(input).toHaveAttribute("aria-labelledby", "customlabel");
+ expect(input).toHaveAttribute("aria-describedby", "customhelp");
+ });
+ it("should connect a code editor input element via `aria-labelledby`", () => {
+ const { container } = render(
+
+
+
+
+
+
+ ,
+ );
+ const label = container.getElementsByClassName(`${eccgui}-fielditem__label`)[0] as HTMLElement;
+ const help = container.getElementsByClassName(`${eccgui}-fielditem__helpertext`)[0] as HTMLElement;
+ const input = container.querySelector(".cm-content") as HTMLElement;
+
+ expect(input.id).toMatch(/^input_/);
+ // the editable area of the code editor is no labelable element, so `for` cannot be used
+ expect(label).not.toHaveAttribute("for");
+ expect(input).toHaveAttribute("aria-labelledby", label.id);
+ expect(input).toHaveAttribute("aria-describedby", help.id);
+ });
+ it("should connect the parts of nested field items separately", () => {
+ const { container } = render(
+ }
+ />
+ }
+ />,
+ );
+ const [outerFieldItem, innerFieldItem] = Array.from(
+ container.getElementsByClassName(`${eccgui}-fielditem`),
+ ) as HTMLElement[];
+ const [outerLabel, innerLabel] = Array.from(
+ container.getElementsByClassName(`${eccgui}-fielditem__label`),
+ ) as HTMLElement[];
+ const [outerHelp, innerHelp] = Array.from(
+ container.getElementsByClassName(`${eccgui}-fielditem__helpertext`),
+ ) as HTMLElement[];
+ const input = container.querySelector("input") as HTMLElement;
+
+ expect(innerFieldItem.contains(input)).toBe(true);
+ expect(outerLabel).not.toHaveAttribute("for");
+ expect(innerLabel).toHaveAttribute("for", input.id);
+ expect(input).toHaveAttribute("aria-describedby", innerHelp.id);
+ expect(outerHelp.id).not.toBe(innerHelp.id);
+ expect(outerFieldItem.id).toBe("");
+ });
+ });
+});
+
+describe("FieldItem with CodeEditor", () => {
+ beforeAll(() => {
+ // the code editor needs range support that is not provided by jsdom
+ document.createRange = () => {
+ const range = new Range();
+ range.getBoundingClientRect = jest.fn();
+ range.getClientRects = () => ({
+ item: () => null,
+ length: 0,
+ [Symbol.iterator]: jest.fn(),
+ });
+ return range;
+ };
+ });
+
+ it("should connect the editable area of the code editor", async () => {
+ const { container } = render(
+
+
+ ,
+ );
+ const label = container.getElementsByClassName(`${eccgui}-fielditem__label`)[0] as HTMLElement;
+ const message = container.getElementsByClassName(`${eccgui}-fielditem__message`)[0] as HTMLElement;
+ const input = container.querySelector(`.${eccgui}-codeeditor .cm-content`) as HTMLElement;
+ expect(input).not.toBeNull();
+
+ // the editable area is created by the code editor itself, so it is connected asynchronously
+ await waitFor(() => {
+ expect(input.id).toMatch(/^input_/);
+ });
+ expect(label).not.toHaveAttribute("for");
+ expect(input).toHaveAttribute("aria-labelledby", label.id);
+ expect(input).toHaveAttribute("aria-describedby", message.id);
+ });
+});
diff --git a/src/extensions/codemirror/CodeMirror.stories.tsx b/src/extensions/codemirror/CodeMirror.stories.tsx
index e0c2d72c..b5e6e039 100644
--- a/src/extensions/codemirror/CodeMirror.stories.tsx
+++ b/src/extensions/codemirror/CodeMirror.stories.tsx
@@ -4,6 +4,7 @@ import { Meta, StoryFn } from "@storybook/react";
import { helpersArgTypes } from "../../../.storybook/helpers";
import { CodeEditor } from "./CodeMirror";
+import { FieldItem } from "../../components/Form/FieldItem";
export default {
title: "Extensions/CodeEditor",
@@ -20,7 +21,11 @@ export default {
} as Meta;
let forcedUpdateKey = 0; // @see https://github.com/storybookjs/storybook/issues/13375#issuecomment-1291011856
-const TemplateFull: StoryFn = (args) => ;
+const TemplateFull: StoryFn = (args) => (
+
+
+
+);
export const BasicExample = TemplateFull.bind({});
BasicExample.args = {