Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(form): invalid fields mark their control, not just the message
Raul0aa645525c20
diff --git a/packages/react/src/Command.tsx b/packages/react/src/Command.tsxindex 8c5a179d75..c291a4c9bc 100644--- a/packages/react/src/Command.tsx+++ b/packages/react/src/Command.tsx@@ -16,7 +16,10 @@ import type {import { forwardRef } from "react";import { LuChevronDown } from "react-icons/lu";import { RxMagnifyingGlass } from "react-icons/rx";-import { useFormControlLabelledBy } from "./Form/useFormControl";+import {+ useFormControl,+ useFormControlLabelledBy+} from "./Form/useFormControl";import { Modal, ModalContent, ModalTitle } from "./Modal";import { cn } from "./utils/cn";import { HitArea, useViewport } from "./Viewport";@@ -290,7 +293,7 @@ const commandTriggerVariants = cva(},asButton: {false:- "text-foreground flex w-full whitespace-nowrap rounded-md border border-input shadow-xs data-[placeholder]:text-muted-foreground outline-none focus:border-ring focus:ring-[3px] focus:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 overflow-hidden",+ "text-foreground flex w-full whitespace-nowrap rounded-md border border-input shadow-xs data-[placeholder]:text-muted-foreground outline-none focus:border-ring focus:ring-[3px] focus:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>span]:line-clamp-1 overflow-hidden",true: "text-foreground relative font-medium shrink-0 group inline-flex select-none transform-gpu initial:border-none disabled:opacity-50 focus:!outline-none focus:!ring-0 active:!outline-none active:!ring-0 after:pointer-events-none after:absolute after:-inset-[3px] after:rounded-lg after:border after:border-blue-500 after:opacity-0 after:ring-2 after:ring-blue-500/20 after:transition-opacity focus-visible:after:opacity-100 active:after:opacity-0 before:pointer-events-none before:bg-gradient-to-b before:transition-opacity before:from-white/[0.12] before:absolute before:inset-0 before:z-[1] before:rounded before:opacity-0 bg-background hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 shadow-button-base hover:scale-100 focus-visible:scale-100 transition-[background-color,color,transform,box-shadow] duration-150 ease-in-out max-md:rounded-full max-md:overflow-visible"}},@@ -372,6 +375,7 @@ const CommandTrigger = forwardRef<ElementRef<"button">, CommandTriggerProps>(// otherwise un-hide the hit-area span on desktop.const { isPhone } = useViewport();const labelledBy = useFormControlLabelledBy(props);+ const { ariaProps } = useFormControl(props);return (<buttonref={ref}@@ -384,6 +388,7 @@ const CommandTrigger = forwardRef<ElementRef<"button">, CommandTriggerProps>(className)}{...props}+ {...ariaProps}aria-labelledby={labelledBy}>{asButton && isPhone && <HitArea />}diff --git a/packages/react/src/Form/useFormControl.tsx b/packages/react/src/Form/useFormControl.tsxindex 67d64732e6..a02e030a92 100644--- a/packages/react/src/Form/useFormControl.tsx+++ b/packages/react/src/Form/useFormControl.tsx@@ -2,97 +2,53 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type { AriaAttributes } from "react";import { ariaAttr } from "../utils/dom";-import { callAllHandlers } from "../utils/function";-import type { FormControlOptions } from "./FormControl";-import {- useFormControlContext,- useOptionalFormControlContext-} from "./FormControl";+import { useOptionalFormControlContext } from "./FormControl";-export interface UseFormControlProps<T extends HTMLElement>- extends FormControlOptions {- id?: string;- onFocus?: React.FocusEventHandler<T>;- onBlur?: React.FocusEventHandler<T>;- disabled?: boolean;- readOnly?: boolean;- required?: boolean;+export interface UseFormControlProps {+ isInvalid?: boolean;+ "aria-invalid"?: AriaAttributes["aria-invalid"];+ "aria-required"?: AriaAttributes["aria-required"];"aria-describedby"?: string;}/**- * React hook that provides the props that should be spread on to- * input fields (`input`, `select`, `textarea`, etc.).+ * What a control inside a FormControl shows and announces: whether it is+ * invalid or required, and the error message and helper text that describe+ * it. The caller's own values win; outside a FormControl only they apply.*- * It provides a convenient way to control a form fields, validation- * and helper text.- *- * @internal- */-export function useFormControl<T extends HTMLElement>(- props: UseFormControlProps<T>-) {- const { isDisabled, isInvalid, isReadOnly, isRequired, ...rest } =- useFormControlProps(props);-- return {- ...rest,- disabled: isDisabled,- readOnly: isReadOnly,- required: isRequired,- "aria-invalid": ariaAttr(isInvalid),- "aria-required": ariaAttr(isRequired),- "aria-readonly": ariaAttr(isReadOnly)- };-}--/**- * @internal+ * It sets `aria-required`, never the native `required` attribute, so the+ * browser's own validation never runs ahead of the form's.*/-export function useFormControlProps<T extends HTMLElement>(- props: UseFormControlProps<T>-) {- const field = useFormControlContext();-- const {- id,- disabled,- readOnly,- required,- isRequired,- isInvalid,- isReadOnly,- isDisabled,- onFocus,- onBlur,- ...rest- } = props;+export function useFormControl(props: UseFormControlProps) {+ const field = useOptionalFormControlContext();+ const isInvalid = props.isInvalid ?? field?.isInvalid ?? false;- const labelIds: string[] = props["aria-describedby"]+ const describedBy = props["aria-describedby"]? [props["aria-describedby"]]: [];-- // Error message must be described first in all scenarios.- if (field?.hasFeedbackText && field?.isInvalid) {- labelIds.push(field.feedbackId);+ // The error message is described first.+ if (field?.isInvalid && field.hasFeedbackText) {+ describedBy.push(field.feedbackId);}-if (field?.hasHelpText) {- labelIds.push(field.helpTextId);+ describedBy.push(field.helpTextId);}- return {- ...rest,- "aria-describedby": labelIds.join(" ") || undefined,- id: id ?? field?.id,- isDisabled: disabled ?? isDisabled ?? field?.isDisabled,- isReadOnly: readOnly ?? isReadOnly ?? field?.isReadOnly,- isRequired: required ?? isRequired ?? field?.isRequired,- isInvalid: isInvalid ?? field?.isInvalid,- onFocus: callAllHandlers(field?.onFocus, onFocus),- onBlur: callAllHandlers(field?.onBlur, onBlur)- };+ // Only the attributes that are set: an explicit `undefined` would replace a+ // value the control sets itself (Radix Select sets `aria-required`).+ const ariaProps: Pick<+ AriaAttributes,+ "aria-invalid" | "aria-required" | "aria-describedby"+ > = {};+ const invalid = props["aria-invalid"] ?? ariaAttr(isInvalid);+ if (invalid !== undefined) ariaProps["aria-invalid"] = invalid;+ const required = props["aria-required"] ?? ariaAttr(field?.isRequired);+ if (required !== undefined) ariaProps["aria-required"] = required;+ if (describedBy.length) ariaProps["aria-describedby"] = describedBy.join(" ");++ return { isInvalid, ariaProps };}/**diff --git a/packages/react/src/Input.tsx b/packages/react/src/Input.tsxindex a6418ae624..42cf28039b 100644--- a/packages/react/src/Input.tsx+++ b/packages/react/src/Input.tsx@@ -8,6 +8,7 @@ import type { HTMLAttributes, InputHTMLAttributes } from "react";import { cloneElement, createContext, forwardRef, useContext } from "react";import * as ReactAria from "react-aria-components";+import { useFormControl } from "./Form/useFormControl";import { cn } from "./utils/cn";import { getValidChildren } from "./utils/react";import { usePhoneAutoFocus } from "./Viewport";@@ -58,7 +59,7 @@ const InputGroup = forwardRef<HTMLDivElement, InputGroupProps>(({className,- isInvalid = false,+ isInvalid: isInvalidProp,isDisabled = false,insetRing,size,@@ -67,6 +68,7 @@ const InputGroup = forwardRef<HTMLDivElement, InputGroupProps>(},ref) => {+ const { isInvalid } = useFormControl({ isInvalid: isInvalidProp });const validChildren = getValidChildren(children);const _children = validChildren.map((child, index) => {@@ -196,7 +198,7 @@ const Input = forwardRef<HTMLInputElement, InputProps>(size,isFirstChild = true,isLastChild = true,- isInvalid = false,+ isInvalid: isInvalidProp,isDisabled,isReadOnly = false,borderless = false,@@ -206,6 +208,10 @@ const Input = forwardRef<HTMLInputElement, InputProps>(ref) => {const isInputGroup = useContext(InputGroupContext) ?? false;+ const { isInvalid, ariaProps } = useFormControl({+ ...props,+ isInvalid: isInvalidProp+ });const disabled = isDisabled ?? props.disabled ?? false;const autoFocus = usePhoneAutoFocus(props.autoFocus);@@ -225,6 +231,7 @@ const Input = forwardRef<HTMLInputElement, InputProps>(className)}{...props}+ {...ariaProps}autoFocus={autoFocus}// Explicit disabled must survive the spread; it was being overwritten.disabled={disabled}diff --git a/packages/react/src/Select.tsx b/packages/react/src/Select.tsxindex 1560b29f68..a02186738f 100644--- a/packages/react/src/Select.tsx+++ b/packages/react/src/Select.tsx@@ -15,7 +15,10 @@ import {LuChevronsUpDown,LuChevronUp} from "react-icons/lu";-import { useFormControlLabelledBy } from "./Form/useFormControl";+import {+ useFormControl,+ useFormControlLabelledBy+} from "./Form/useFormControl";import { compactPart } from "./MenuSheet";import {SelectSheetContent,@@ -84,6 +87,7 @@ const SelectTrigger = forwardRef<>(({ size, className, children, hideIcon, inline, ...props }, ref) => {const { isPhone } = useViewport();const labelledBy = useFormControlLabelledBy(props);+ const { ariaProps } = useFormControl(props);const Trigger = isPhone ? SelectSheetTrigger : SelectPrimitive.Trigger;const icon = (<LuChevronsUpDown className="h-4 w-4 flex-shrink-0 opacity-50" />@@ -93,6 +97,7 @@ const SelectTrigger = forwardRef<ref={ref}className={cn(!inline && selectTriggerVariants({ size }), className)}{...props}+ {...ariaProps}aria-labelledby={labelledBy}>{children}diff --git a/packages/react/src/Textarea.tsx b/packages/react/src/Textarea.tsxindex 61482d772a..5a96054fe1 100644--- a/packages/react/src/Textarea.tsx+++ b/packages/react/src/Textarea.tsx@@ -6,6 +6,7 @@ import type { VariantProps } from "class-variance-authority";import { cva } from "class-variance-authority";import type { TextareaHTMLAttributes } from "react";import { forwardRef } from "react";+import { useFormControl } from "./Form/useFormControl";import { cn } from "./utils/cn";import { usePhoneAutoFocus } from "./Viewport";@@ -32,11 +33,13 @@ export interface TextareaPropsconst Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(({ className, size, ...props }, ref) => {const autoFocus = usePhoneAutoFocus(props.autoFocus);+ const { ariaProps } = useFormControl(props);return (<textareaclassName={cn(textareaVariants({ size }), className)}ref={ref}{...props}+ {...ariaProps}autoFocus={autoFocus}/>);diff --git a/packages/react/src/__tests__/FormControl.test.tsx b/packages/react/src/__tests__/FormControl.test.tsxindex 656a39a166..73e328e4fb 100644--- a/packages/react/src/__tests__/FormControl.test.tsx+++ b/packages/react/src/__tests__/FormControl.test.tsx@@ -11,9 +11,11 @@ import { createRoot } from "react-dom/client";import { afterEach, beforeAll, describe, expect, it } from "vitest";import { CommandTrigger } from "../Command";import { FormControl } from "../Form/FormControl";+import { FormErrorMessage } from "../Form/FormError";import { FormLabel } from "../Form/FormLabel";-import { Input } from "../Input";+import { Input, InputGroup } from "../Input";import { Select, SelectTrigger, SelectValue } from "../Select";+import { Textarea } from "../Textarea";let root: Root | undefined;let container: HTMLDivElement | undefined;@@ -124,3 +126,107 @@ describe("select and combobox triggers", () => {).toBe(false);});});++describe("controls take the FormControl's state", () => {+ it("an invalid field marks its input and links the error to it", () => {+ const view = render(+ <FormControl isInvalid>+ <FormLabel htmlFor="paymentTermId">Payment term</FormLabel>+ <Input id="paymentTermId" />+ <FormErrorMessage>Payment term is required</FormErrorMessage>+ </FormControl>+ );+ const input = view.querySelector("input")!;+ const error = view.querySelector('[aria-live="polite"]')!;+ expect(input.getAttribute("aria-invalid")).toBe("true");+ expect(input.getAttribute("aria-describedby")).toBe(error.id);+ expect(input.className).toContain("border-destructive");+ });++ it("a valid field leaves its input alone", () => {+ const view = render(+ <FormControl>+ <FormLabel htmlFor="paymentTermId">Payment term</FormLabel>+ <Input id="paymentTermId" />+ </FormControl>+ );+ const input = view.querySelector("input")!;+ expect(input.hasAttribute("aria-invalid")).toBe(false);+ expect(input.hasAttribute("aria-describedby")).toBe(false);+ expect(input.className).not.toContain("border-destructive");+ });++ it("a required field is announced as required without the browser's own validation", () => {+ const view = render(+ <FormControl isRequired>+ <Input id="name" />+ </FormControl>+ );+ const input = view.querySelector("input")!;+ expect(input.getAttribute("aria-required")).toBe("true");+ expect(input.hasAttribute("required")).toBe(false);+ });++ it("text areas, select triggers and combobox triggers are marked invalid", () => {+ const view = render(+ <>+ <FormControl isInvalid>+ <Textarea />+ </FormControl>+ <FormControl isInvalid>+ <Select>+ <SelectTrigger>+ <SelectValue placeholder="Select" />+ </SelectTrigger>+ </Select>+ </FormControl>+ <FormControl isInvalid>+ <CommandTrigger role="combobox">Select</CommandTrigger>+ </FormControl>+ </>+ );+ const textarea = view.querySelector("textarea")!;+ const [select, combobox] = view.querySelectorAll('[role="combobox"]');+ expect(textarea.getAttribute("aria-invalid")).toBe("true");+ expect(select!.getAttribute("aria-invalid")).toBe("true");+ expect(combobox!.getAttribute("aria-invalid")).toBe("true");+ expect(combobox!.className).toContain("aria-invalid:border-destructive");+ });++ it("an input group draws the error border around its input", () => {+ const view = render(+ <FormControl isInvalid>+ <InputGroup>+ <Input id="price" />+ </InputGroup>+ </FormControl>+ );+ const group = view.querySelector("input")!.parentElement!;+ expect(group.className).toContain("border-destructive");+ expect(view.querySelector("input")!.getAttribute("aria-invalid")).toBe(+ "true"+ );+ });++ it("an input outside a FormControl follows its own isInvalid", () => {+ const view = render(<Input isInvalid />);+ expect(view.querySelector("input")!.getAttribute("aria-invalid")).toBe(+ "true"+ );+ });++ it("a select keeps the aria-required its own required prop sets", () => {+ const view = render(+ <FormControl>+ <Select required>+ <SelectTrigger>+ <SelectValue placeholder="Select" />+ </SelectTrigger>+ </Select>+ </FormControl>+ );+ expect(+ view.querySelector('[role="combobox"]')!.getAttribute("aria-required")+ ).toBe("true");+ });+});