Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

fix(components/form): resolve FormControl label target regressions (#3369) (#3387)

Santhi Prakashea3980cba05f
diff --git a/apps/web/src/components/input/chip-input.test.tsx b/apps/web/src/components/input/chip-input.test.tsx
index 32afe7637..ebc6cfaf5 100644
--- a/apps/web/src/components/input/chip-input.test.tsx
+++ b/apps/web/src/components/input/chip-input.test.tsx
@@ -4,6 +4,7 @@ import { fireEvent, render, screen } from "@testing-library/react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { i18n } from "@lingui/core";
import { I18nProvider } from "@lingui/react";
+import { FormControl, FormItem, FormLabel } from "@reactive-resume/ui/components/form";
import { ChipInput } from "./chip-input";
beforeAll(() => {
@@ -81,4 +82,39 @@ describe("ChipInput", () => {
const { container } = renderInput({ defaultValue: ["a"] });
expect(container.querySelector("kbd")).not.toBeNull();
});
+
+ it("wires the inner input to a FormLabel and lets it outrank the generic aria-label", () => {
+ render(
+ <I18nProvider i18n={i18n}>
+ <FormItem>
+ <FormLabel>Tags</FormLabel>
+ <FormControl render={<ChipInput defaultValue={[]} onChange={vi.fn()} />} />
+ </FormItem>
+ </I18nProvider>,
+ );
+
+ const label = screen.getByText("Tags");
+ const input = document.querySelector("input") as HTMLInputElement;
+
+ expect(input).toHaveAttribute("id");
+ expect(input.id).toMatch(/-form-item$/);
+ expect(label).toHaveAttribute("for", input.id);
+ expect(input).toHaveAttribute("aria-labelledby", label.id);
+ expect(input).toHaveAccessibleName("Tags");
+ });
+
+ it("keeps a generic accessible name when the FormControl has no FormLabel", () => {
+ render(
+ <I18nProvider i18n={i18n}>
+ <FormItem>
+ <FormControl render={<ChipInput defaultValue={[]} onChange={vi.fn()} />} />
+ </FormItem>
+ </I18nProvider>,
+ );
+
+ const input = document.querySelector("input") as HTMLInputElement;
+
+ expect(document.getElementById(input.getAttribute("aria-labelledby") ?? "")).toBeNull();
+ expect(input).toHaveAccessibleName("Add keyword");
+ });
});
diff --git a/apps/web/src/components/input/chip-input.tsx b/apps/web/src/components/input/chip-input.tsx
index b0218a8fc..87fe962e1 100644
--- a/apps/web/src/components/input/chip-input.tsx
+++ b/apps/web/src/components/input/chip-input.tsx
@@ -17,6 +17,7 @@ import { AnimatePresence, m } from "motion/react";
import * as React from "react";
import { createPortal } from "react-dom";
import { Badge } from "@reactive-resume/ui/components/badge";
+import { useFormControl } from "@reactive-resume/ui/components/form";
import { Input } from "@reactive-resume/ui/components/input";
import { Kbd } from "@reactive-resume/ui/components/kbd";
import { cn } from "@reactive-resume/utils/style";
@@ -152,8 +153,17 @@ export function ChipInput({
onChange,
className,
hideDescription = false,
+ id: idProp,
+ "aria-describedby": ariaDescribedByProp,
+ "aria-invalid": ariaInvalidProp,
...props
}: Props) {
+ const formControl = useFormControl();
+ const controlId = idProp ?? formControl.id;
+ const describedBy = ariaDescribedByProp ?? formControl["aria-describedby"];
+ const invalid = ariaInvalidProp ?? formControl["aria-invalid"];
+ const labelId = formControl.labelId;
+
const [chips, setChips] = useControlledState<string[]>({
value,
defaultValue,
@@ -368,9 +378,16 @@ export function ChipInput({
<Input
ref={inputRef}
type="text"
+ id={controlId}
value={input}
autoComplete="off"
+ // A resolvable aria-labelledby outranks aria-label, so a rendered FormLabel still wins;
+ // when the FormControl has no FormLabel the reference dangles and the accessible name
+ // falls back to aria-label instead of going empty.
aria-label={isEditingKeyword ? t`Edit keyword` : t`Add keyword`}
+ aria-labelledby={labelId}
+ aria-describedby={describedBy}
+ aria-invalid={invalid}
placeholder={isEditingKeyword ? t`Editing keyword...` : t`Add a keyword...`}
onKeyDown={handleKeyDown}
onChange={handleInputChange}
diff --git a/apps/web/src/routes/builder/$resumeId/-sidebar/right/sections/layout/index.tsx b/apps/web/src/routes/builder/$resumeId/-sidebar/right/sections/layout/index.tsx
index cf0b9aa97..c1d13748b 100644
--- a/apps/web/src/routes/builder/$resumeId/-sidebar/right/sections/layout/index.tsx
+++ b/apps/web/src/routes/builder/$resumeId/-sidebar/right/sections/layout/index.tsx
@@ -1,5 +1,6 @@
import type z from "zod";
import { Trans } from "@lingui/react/macro";
+import * as React from "react";
import { metadataSchema } from "@reactive-resume/schema/resume/data";
import { FormControl, FormItem, FormLabel, FormMessage } from "@reactive-resume/ui/components/form";
import {
@@ -52,6 +53,8 @@ function LayoutSectionForm() {
persist(form.state.values);
};
+ const labelId = React.useId();
+
return (
<form
className="space-y-4"
@@ -64,23 +67,20 @@ function LayoutSectionForm() {
<form.Field name="sidebarWidth">
{(field) => (
<FormItem hasError={field.state.meta.isTouched && field.state.meta.errors.length > 0}>
- <FormLabel>
+ <FormLabel id={labelId}>
<Trans>Sidebar Width</Trans>
</FormLabel>
<div className="flex items-center gap-4">
- <FormControl
- render={
- <Slider
- min={10}
- max={50}
- step={0.01}
- value={[field.state.value]}
- onValueChange={(value) => {
- field.handleChange(Array.isArray(value) ? value[0] : value);
- handleAutoSave();
- }}
- />
- }
+ <Slider
+ aria-labelledby={labelId}
+ min={10}
+ max={50}
+ step={0.01}
+ value={[field.state.value]}
+ onValueChange={(value) => {
+ field.handleChange(Array.isArray(value) ? value[0] : value);
+ handleAutoSave();
+ }}
/>
<FormControl
diff --git a/packages/ui/src/components/form.test.tsx b/packages/ui/src/components/form.test.tsx
index a6c2e960b..130473496 100644
--- a/packages/ui/src/components/form.test.tsx
+++ b/packages/ui/src/components/form.test.tsx
@@ -1,6 +1,9 @@
import { render, screen } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
+import { useId } from "react";
import { FormControl, FormDescription, FormItem, FormLabel, FormMessage } from "./form";
+import { InputGroup, InputGroupInput } from "./input-group";
+import { Slider } from "./slider";
describe("FormItem", () => {
it("renders with data-slot='form-item'", () => {
@@ -62,6 +65,135 @@ describe("FormLabel", () => {
});
describe("FormControl", () => {
+ it("forwards the generated id to the real control inside an InputGroup wrapper", () => {
+ render(
+ <FormItem>
+ <FormLabel>Slug</FormLabel>
+ <FormControl
+ render={
+ <InputGroup data-testid="group">
+ <InputGroupInput data-testid="input" />
+ </InputGroup>
+ }
+ />
+ </FormItem>,
+ );
+
+ const label = screen.getByText("Slug");
+ const group = screen.getByTestId("group");
+ const input = screen.getByTestId("input") as HTMLInputElement;
+
+ expect(input).toHaveAttribute("id");
+ expect(input.getAttribute("id")).toMatch(/-form-item$/);
+ expect(label).toHaveAttribute("for", input.id);
+ expect(group).not.toHaveAttribute("id", input.id);
+ });
+
+ it("forwards the generated id to the Base UI Slider control", () => {
+ render(
+ <FormItem>
+ <FormLabel>Sidebar Width</FormLabel>
+ <FormControl render={<Slider defaultValue={[30]} />} />
+ </FormItem>,
+ );
+
+ const label = screen.getByText("Sidebar Width");
+ const labelId = label.id;
+ const htmlFor = label.getAttribute("for");
+ const sliderInput = document.querySelector('input[type="range"]') as HTMLInputElement;
+
+ expect(sliderInput).toBeInTheDocument();
+ expect(sliderInput.id).toBe(htmlFor);
+ expect(sliderInput.getAttribute("aria-labelledby")).toBe(labelId);
+ });
+
+ it("leaves the Slider control ids unique when the FormControl wraps a range slider", () => {
+ render(
+ <FormItem>
+ <FormLabel>Range</FormLabel>
+ <FormControl render={<Slider defaultValue={[20, 40]} />} />
+ </FormItem>,
+ );
+
+ const label = screen.getByText("Range");
+ const rangeInputs = Array.from(document.querySelectorAll('input[type="range"]'));
+
+ expect(rangeInputs).toHaveLength(2);
+ expect(new Set(rangeInputs.map((input) => input.id)).size).toBe(2);
+ for (const input of rangeInputs) {
+ expect(input).toHaveAttribute("aria-labelledby", label.id);
+ }
+ });
+
+ it("reflects the FormControl error state as aria-invalid on the Slider control", () => {
+ render(
+ <FormItem hasError>
+ <FormLabel>Sidebar Width</FormLabel>
+ <FormControl render={<Slider defaultValue={[30]} />} />
+ </FormItem>,
+ );
+
+ const sliderInput = document.querySelector('input[type="range"]') as HTMLInputElement;
+
+ expect(sliderInput).toBeInTheDocument();
+ expect(sliderInput.getAttribute("aria-invalid")).toBe("true");
+ });
+
+ it("keeps ids distinct when a FormItem contains a Slider and an InputGroup control", () => {
+ function TestField() {
+ const labelId = useId();
+
+ return (
+ <FormItem>
+ <FormLabel id={labelId}>Sidebar Width</FormLabel>
+ <div className="flex items-center gap-4">
+ <Slider defaultValue={[30]} aria-labelledby={labelId} />
+ <FormControl
+ render={
+ <InputGroup data-testid="group">
+ <InputGroupInput data-testid="input" />
+ </InputGroup>
+ }
+ />
+ </div>
+ </FormItem>
+ );
+ }
+
+ render(<TestField />);
+
+ const label = screen.getByText("Sidebar Width");
+ const numericInput = screen.getByTestId("input") as HTMLInputElement;
+ const sliderInput = document.querySelector('input[type="range"]') as HTMLInputElement;
+
+ expect(label).toHaveAttribute("for", numericInput.id);
+ expect(sliderInput).toHaveAttribute("aria-labelledby", label.id);
+ expect(sliderInput.id).not.toBe(numericInput.id);
+
+ const allInputs = document.querySelectorAll("input");
+ const uniqueIds = new Set(Array.from(allInputs).map((input) => input.id));
+ expect(uniqueIds.size).toBe(allInputs.length);
+ });
+
+ it("warns when the generated id lands on a non-labelable wrapper", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ render(
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormControl render={<div data-testid="wrapper" />} />
+ </FormItem>,
+ );
+
+ expect(warn).toHaveBeenCalled();
+ const call = warn.mock.calls.find(
+ ([message]) => typeof message === "string" && message.includes("not a labelable element"),
+ );
+ expect(call).toBeTruthy();
+
+ warn.mockRestore();
+ });
+
it("sets aria-describedby pointing only to description when no error", () => {
render(
<FormItem>
diff --git a/packages/ui/src/components/form.tsx b/packages/ui/src/components/form.tsx
index 9df892fd6..592f295a5 100644
--- a/packages/ui/src/components/form.tsx
+++ b/packages/ui/src/components/form.tsx
@@ -14,6 +14,20 @@ function useFormItem() {
return React.use(FormItemContext);
}
+type FormControlContextValue = {
+ id?: string;
+ labelId?: string;
+ hasError?: boolean;
+ "aria-describedby"?: string;
+ "aria-invalid"?: boolean | "true" | "false";
+};
+
+const FormControlContext = React.createContext<FormControlContextValue | null>(null);
+
+function useFormControl(): FormControlContextValue {
+ return React.use(FormControlContext) ?? {};
+}
+
type FormItemProps = React.ComponentProps<"div"> & { hasError?: boolean };
function FormItem({ className, hasError = false, ...props }: FormItemProps) {
@@ -32,6 +46,7 @@ function FormLabel({ className, ...props }: React.ComponentProps<typeof Label>)
return (
<Label
+ id={`${id}-form-item-label`}
data-slot="form-label"
data-error={hasError}
className={cn("mb-0.5 data-[error=true]:text-destructive", className)}
@@ -41,23 +56,86 @@ function FormLabel({ className, ...props }: React.ComponentProps<typeof Label>)
);
}
+const LABELABLE_TAGS = new Set(["button", "input", "meter", "output", "progress", "select", "textarea"]);
+const LABELABLE_ROLES = new Set([
+ "button",
+ "combobox",
+ "gridcell",
+ "listbox",
+ "option",
+ "progressbar",
+ "radio",
+ "searchbox",
+ "slider",
+ "spinbutton",
+ "switch",
+ "tab",
+ "textbox",
+ "treeitem",
+]);
+
+function isLabelableElement(element: Element) {
+ if (LABELABLE_TAGS.has(element.tagName.toLowerCase())) return true;
+ if (element.getAttribute("contenteditable") === "true") return true;
+ const role = element.getAttribute("role");
+ if (role && LABELABLE_ROLES.has(role)) return true;
+ return false;
+}
+
+function useFormControlWarning(controlId: string) {
+ React.useEffect(() => {
+ if (process.env.NODE_ENV === "production") return;
+ if (typeof document === "undefined") return;
+
+ const element = document.getElementById(controlId);
+ if (!element) {
+ console.warn(
+ `FormControl: no element in the document has the generated id "${controlId}". The <FormLabel for="${controlId}"> target is dangling.`,
+ );
+ return;
+ }
+
+ if (!isLabelableElement(element)) {
+ console.warn(
+ `FormControl: the element that carries the generated id "${controlId}" is not a labelable element. A <label for="${controlId}"> will not name the control.`,
+ );
+ }
+ }, [controlId]);
+}
+
function FormControl({ render, ...props }: useRender.ComponentProps<"div">) {
const { id, hasError } = useFormItem();
+ const controlId = `${id}-form-item`;
+ const labelId = `${id}-form-item-label`;
+ const describedBy = hasError ? `${id}-form-item-description ${id}-form-item-message` : `${id}-form-item-description`;
+
+ const contextValue = React.useMemo<FormControlContextValue>(
+ () => ({
+ id: controlId,
+ labelId,
+ hasError,
+ "aria-describedby": describedBy,
+ "aria-invalid": hasError,
+ }),
+ [controlId, describedBy, hasError, labelId],
+ );
- return useRender({
+ useFormControlWarning(controlId);
+
+ const element = useRender({
defaultTagName: "div",
render,
state: { slot: "form-control" },
props: {
- id: `${id}-form-item`,
+ id: controlId,
"data-slot": "form-control",
- "aria-describedby": hasError
- ? `${id}-form-item-description ${id}-form-item-message`
- : `${id}-form-item-description`,
+ "aria-describedby": describedBy,
"aria-invalid": hasError,
...props,
},
});
+
+ return <FormControlContext.Provider value={contextValue}>{element}</FormControlContext.Provider>;
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
@@ -114,4 +192,4 @@ function FormMessage({ className, errors, ...props }: FormMessageProps) {
);
}
-export { FormControl, FormDescription, FormItem, FormLabel, FormMessage };
+export { FormControl, FormControlContext, FormDescription, FormItem, FormLabel, FormMessage, useFormControl };
diff --git a/packages/ui/src/components/input-group.test.tsx b/packages/ui/src/components/input-group.test.tsx
index 97965d90e..58cddce1b 100644
--- a/packages/ui/src/components/input-group.test.tsx
+++ b/packages/ui/src/components/input-group.test.tsx
@@ -2,6 +2,7 @@ import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, test } from "vitest";
import { createPortal } from "react-dom";
+import { FormControl, FormItem, FormLabel } from "./form";
import {
InputGroup,
InputGroupAddon,
@@ -27,6 +28,43 @@ describe("InputGroup", () => {
render(<InputGroup data-testid="g" className="my-class" />);
expect(screen.getByTestId("g")).toHaveClass("my-class");
});
+
+ it("preserves explicit fieldset identity and description in standalone usage", () => {
+ // Standalone (no FormControl ancestor) the native fieldset props must
+ // survive: the generated-prop strip only applies to FormControl
+ // compositions, where the inner control carries them via context.
+ render(
+ <InputGroup id="caller-group" aria-describedby="hint" data-testid="g">
+ <InputGroupInput data-testid="i" />
+ </InputGroup>,
+ );
+
+ const g = screen.getByTestId("g");
+ expect(g).toHaveAttribute("id", "caller-group");
+ expect(g).toHaveAttribute("aria-describedby", "hint");
+ });
+
+ it("keeps the generated control id off the fieldset inside a FormControl", () => {
+ render(
+ <FormItem>
+ <FormLabel>Slug</FormLabel>
+ <FormControl
+ render={
+ <InputGroup data-testid="g">
+ <InputGroupInput data-testid="i" />
+ </InputGroup>
+ }
+ />
+ </FormItem>,
+ );
+
+ const g = screen.getByTestId("g");
+ const input = screen.getByTestId("i");
+
+ expect(input).toHaveAttribute("id");
+ expect(input.getAttribute("id")).toMatch(/-form-item$/);
+ expect(g).not.toHaveAttribute("id");
+ });
});
describe("InputGroupAddon", () => {
diff --git a/packages/ui/src/components/input-group.tsx b/packages/ui/src/components/input-group.tsx
index 46e391307..02739706e 100644
--- a/packages/ui/src/components/input-group.tsx
+++ b/packages/ui/src/components/input-group.tsx
@@ -2,14 +2,34 @@ import type { VariantProps } from "class-variance-authority";
import type * as React from "react";
import { cva } from "class-variance-authority";
import { Button } from "@reactive-resume/ui/components/button";
+import { useFormControl } from "@reactive-resume/ui/components/form";
import { Input } from "@reactive-resume/ui/components/input";
import { Textarea } from "@reactive-resume/ui/components/textarea";
import { cn } from "@reactive-resume/utils/style";
-function InputGroup({ className, ...props }: React.ComponentProps<"fieldset">) {
+function InputGroup({
+ className,
+ id: idProp,
+ "aria-describedby": ariaDescribedByProp,
+ "aria-invalid": ariaInvalidProp,
+ ...props
+}: React.ComponentProps<"fieldset">) {
+ const formControl = useFormControl();
+ // Inside a FormControl composition the generated control props belong to
+ // the inner input (delivered via context), not the fieldset wrapper.
+ // Standalone usage has no FormControl, so explicit native fieldset props
+ // must survive untouched.
+ const insideFormControl = formControl.id !== undefined;
+ const fieldsetId = insideFormControl ? undefined : idProp;
+ const fieldsetDescribedBy = insideFormControl ? undefined : ariaDescribedByProp;
+ const fieldsetInvalid = insideFormControl ? undefined : ariaInvalidProp;
+
return (
<fieldset
data-slot="input-group"
+ id={fieldsetId}
+ aria-describedby={fieldsetDescribedBy}
+ aria-invalid={fieldsetInvalid}
className={cn(
"group/input-group relative flex h-9 w-full min-w-0 items-center rounded-lg border border-input outline-none transition-colors in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-start]]:h-auto has-[>textarea]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:flex-col has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot][aria-invalid=true]]:border-destructive has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=inline-start]]:[&>input]:ps-1.5 has-[>[data-align=inline-end]]:[&>input]:pe-1.5 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3",
className,
@@ -114,10 +134,24 @@ function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
);
}
-function InputGroupInput({ className, ...props }: React.ComponentProps<"input">) {
+function InputGroupInput({
+ className,
+ id: idProp,
+ "aria-describedby": ariaDescribedByProp,
+ "aria-invalid": ariaInvalidProp,
+ ...props
+}: React.ComponentProps<"input">) {
+ const formControl = useFormControl();
+ const controlId = idProp ?? formControl.id;
+ const describedBy = ariaDescribedByProp ?? formControl["aria-describedby"];
+ const invalid = ariaInvalidProp ?? formControl["aria-invalid"];
+
return (
<Input
data-slot="input-group-control"
+ id={controlId}
+ aria-describedby={describedBy}
+ aria-invalid={invalid}
className={cn(
"flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0",
className,
@@ -127,10 +161,24 @@ function InputGroupInput({ className, ...props }: React.ComponentProps<"input">)
);
}
-function InputGroupTextarea({ className, ...props }: React.ComponentProps<"textarea">) {
+function InputGroupTextarea({
+ className,
+ id: idProp,
+ "aria-describedby": ariaDescribedByProp,
+ "aria-invalid": ariaInvalidProp,
+ ...props
+}: React.ComponentProps<"textarea">) {
+ const formControl = useFormControl();
+ const controlId = idProp ?? formControl.id;
+ const describedBy = ariaDescribedByProp ?? formControl["aria-describedby"];
+ const invalid = ariaInvalidProp ?? formControl["aria-invalid"];
+
return (
<Textarea
data-slot="input-group-control"
+ id={controlId}
+ aria-describedby={describedBy}
+ aria-invalid={invalid}
className={cn(
"flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0",
className,
diff --git a/packages/ui/src/components/slider.test.tsx b/packages/ui/src/components/slider.test.tsx
index 08bd34cfe..f07845456 100644
--- a/packages/ui/src/components/slider.test.tsx
+++ b/packages/ui/src/components/slider.test.tsx
@@ -35,6 +35,18 @@ describe("Slider", () => {
expect(screen.getByTestId("s")).toHaveClass("custom-slider");
});
+ it("lets a caller-supplied data-slot override the default", () => {
+ render(<Slider data-testid="s" defaultValue={[50]} data-slot="custom-slider" />);
+ expect(screen.getByTestId("s")).toHaveAttribute("data-slot", "custom-slider");
+ });
+
+ it("preserves a caller-supplied id in standalone usage", () => {
+ // Standalone (no FormControl ancestor) an explicit id must survive:
+ // LabelableProvider only applies an id when a FormControl supplies one.
+ const { container } = render(<Slider id="caller-slider" defaultValue={[30]} />);
+ expect(container.querySelector("#caller-slider")).toBeInTheDocument();
+ });
+
it("renders 2 thumbs with default min/max if no defaultValue or value passed", () => {
const { container } = render(<Slider />);
// Source code: defaults to [min, max] when neither value nor defaultValue is array
diff --git a/packages/ui/src/components/slider.tsx b/packages/ui/src/components/slider.tsx
index 6114cc3a5..ff4fb4535 100644
--- a/packages/ui/src/components/slider.tsx
+++ b/packages/ui/src/components/slider.tsx
@@ -1,9 +1,28 @@
import { Slider as SliderPrimitive } from "@base-ui/react/slider";
+import { useFormControl } from "@reactive-resume/ui/components/form";
import { cn } from "@reactive-resume/utils/style";
const THUMB_POSITION_KEYS = ["single", "start", "end"] as const;
-function Slider({ className, defaultValue, value, min = 0, max = 100, ...props }: SliderPrimitive.Root.Props) {
+function Slider({
+ className,
+ defaultValue,
+ value,
+ min = 0,
+ max = 100,
+ // Inside FormControl the generated id belongs to the real control
+ // (input[type=range]) that syncThumbInput applies it to — repeating it here
+ // would duplicate the id on the wrapper div. Standalone usage has no
+ // FormControl context, so an explicit caller id must survive there.
+ id: idProp,
+ "aria-labelledby": ariaLabelledBy,
+ "aria-describedby": ariaDescribedBy,
+ "aria-invalid": ariaInvalid,
+ ...props
+}: SliderPrimitive.Root.Props) {
+ const { id: controlId, labelId } = useFormControl();
+ const id = controlId == null ? idProp : undefined;
+
const _values = Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min, max];
const thumbDescriptors = _values.map((thumbValue, position) => ({
key:
@@ -12,15 +31,33 @@ function Slider({ className, defaultValue, value, min = 0, max = 100, ...props }
: (THUMB_POSITION_KEYS[position + 1] ?? `thumb-${position}-${thumbValue}`),
}));
+ // Base UI owns the accessible control (input[type=range]): it renders the input from a
+ // fixed prop list, generates the input's id internally, and only applies aria-invalid
+ // through its own Field validation context. Bridge FormControl's generated id and error
+ // state onto the input via inputRef. A range slider renders one input per thumb, so only
+ // a single-thumb slider may claim the id — the rule Base UI applies to its own ids too.
+ const ownsControlId = controlId != null && _values.length === 1;
+ const syncThumbInput = (input: HTMLInputElement | null) => {
+ if (!input) return;
+ if (ariaInvalid == null) {
+ input.removeAttribute("aria-invalid");
+ } else {
+ input.setAttribute("aria-invalid", String(ariaInvalid));
+ }
+ if (ownsControlId) input.id = controlId;
+ };
+
return (
<SliderPrimitive.Root
className={cn("data-vertical:h-full data-horizontal:w-full", className)}
- data-slot="slider"
+ id={id}
defaultValue={defaultValue}
value={value}
min={min}
max={max}
thumbAlignment="edge"
+ data-slot="slider"
+ aria-labelledby={ariaLabelledBy ?? labelId}
{...props}
>
<SliderPrimitive.Control className="relative flex w-full touch-none select-none items-center data-vertical:h-full data-vertical:min-h-40 data-vertical:w-auto data-vertical:flex-col data-disabled:opacity-50">
@@ -37,6 +74,8 @@ function Slider({ className, defaultValue, value, min = 0, max = 100, ...props }
<SliderPrimitive.Thumb
data-slot="slider-thumb"
key={thumb.key}
+ aria-describedby={ariaDescribedBy}
+ inputRef={syncThumbInput}
className="relative block size-3 shrink-0 select-none rounded-full border border-ring bg-white ring-ring/50 transition-[color,box-shadow] after:absolute after:-inset-2 hover:ring-3 focus-visible:outline-hidden focus-visible:ring-3 active:ring-3 disabled:pointer-events-none disabled:opacity-50"
/>
))}