import * as React from "react"; import { Label, type LabelProps } from "./label.js"; import { cn } from "../../utils.js"; import "./field.css"; export interface FieldContextValue { id: string; name?: string; required?: boolean; disabled?: boolean; error?: string | boolean; descriptionId: string; errorId: string; } const FieldContext = React.createContext(undefined); export function useFieldContext(): FieldContextValue { const context = React.useContext(FieldContext); if (!context) { throw new Error("useFieldContext must be used within a "); } return context; } export type FieldOrientation = "vertical" | "horizontal" | "responsive"; export interface FieldProps extends React.HTMLAttributes { id?: string; name?: string; required?: boolean; disabled?: boolean; error?: string | boolean; orientation?: FieldOrientation; } const Field = React.forwardRef( ( { id: explicitId, name, required, disabled, error, orientation = "vertical", className, children, ...props }, ref ) => { const generatedId = React.useId(); const id = explicitId || generatedId; const descriptionId = `${id}-description`; const errorId = `${id}-error`; const contextValue = React.useMemo( () => ({ id, name, required, disabled, error, descriptionId, errorId, }), [id, name, required, disabled, error, descriptionId, errorId] ); return (
{children}
); } ); Field.displayName = "Field"; export interface FieldLabelProps extends Omit { htmlFor?: string; } const FieldLabel = React.forwardRef< React.ElementRef, FieldLabelProps >( ( { className, htmlFor, required: explicitRequired, disabled: explicitDisabled, ...props }, ref ) => { const context = React.useContext(FieldContext); const targetId = htmlFor ?? context?.id; const isRequired = explicitRequired ?? context?.required; const isDisabled = explicitDisabled ?? context?.disabled; return (