Form Fields
Inputs, textareas, selects, labels, helper text, switches and checkboxes styled for the newt/ui dark theme.
Form fields are the inputs, textareas, selects, labels, helper text, switches and checkboxes of a form, styled for the newt/ui dark theme. Compose a form from the exported parts.
A Field wires the parts inside it. The Label points at the control, and the control lists its help line in aria-describedby, and its error line while it is invalid. You write no ids.
Input and Select are 40px tall, the height of a medium button; size="sm" makes them 32px. Every text control takes a stronger edge on hover, a 2px --newt-focus-ring ring inside its edge on focus, the --newt-text-danger edge while invalid, and half opacity while disabled.
Three parts are built on Radix primitives in React and Reka UI primitives in Vue. Label is on Label (Radix, Reka UI). Switch is on Switch (Radix, Reka UI). Checkbox is on Checkbox (Radix, Reka UI). Field, Input, Textarea, Select and FieldHelp are native elements.
newt-fieldimport {
Field,
FieldHelp,
Input,
Label,
Switch,
} from "@/registry/bases/newt/ui/form-fields"
/*
* Inside a `Field`, the label, the input and the help line share ids: the
* label points at the input, and the input is described by the help line.
*/
export default function FormFieldsDemo() {
return (
<div className="flex w-full max-w-sm flex-col gap-6">
<Field>
<Label>Label</Label>
<Input placeholder="Placeholder" />
<FieldHelp>Helper text</FieldHelp>
</Field>
<div className="flex items-center justify-between text-newt-text-primary">
<span>Toggle label</span>
<Switch aria-label="Toggle label" />
</div>
</div>
)
}<script setup lang="ts">
import { ref } from "vue"
import {
Field,
FieldHelp,
Input,
Label,
Switch,
} from "~~/registry/bases/newt/ui/form-fields"
/*
* Inside a `Field`, the label, the input and the help line share ids: the
* label points at the input, and the input is described by the help line.
*/
const value = ref("")
const enabled = ref(false)
</script>
<template>
<div class="flex w-full max-w-sm flex-col gap-6">
<Field>
<Label>Label</Label>
<Input v-model="value" placeholder="Placeholder" />
<FieldHelp>Helper text</FieldHelp>
</Field>
<div class="flex items-center justify-between text-newt-text-primary">
<span>Toggle label</span>
<Switch v-model="enabled" aria-label="Toggle label" />
</div>
</div>
</template>Installation
npx newtui@latest add form-fieldsnpx shadcn@latest add @newtui/form-fieldsnpx shadcn-vue@latest add @newtui/form-fieldspnpm dlx newtui@latest add form-fieldspnpm dlx shadcn@latest add @newtui/form-fieldspnpm dlx shadcn-vue@latest add @newtui/form-fieldsyarn dlx newtui@latest add form-fieldsyarn dlx shadcn@latest add @newtui/form-fieldsyarn dlx shadcn-vue@latest add @newtui/form-fieldsbunx newtui@latest add form-fieldsbunx shadcn@latest add @newtui/form-fieldsbunx shadcn-vue@latest add @newtui/form-fieldsdeno run -A npm:newtui@latest add form-fieldsdeno run -A npm:shadcn@latest add @newtui/form-fieldsdeno run -A npm:shadcn-vue@latest add @newtui/form-fieldsvlx newtui@latest add form-fieldsvlx shadcn@latest add @newtui/form-fieldsvlx shadcn-vue@latest add @newtui/form-fieldsvp dlx newtui@latest add form-fieldsvp dlx shadcn@latest add @newtui/form-fieldsvp dlx shadcn-vue@latest add @newtui/form-fieldsnubx newtui@latest add form-fieldsnubx shadcn@latest add @newtui/form-fieldsnubx shadcn-vue@latest add @newtui/form-fieldsnlx newtui@latest add form-fieldsnlx shadcn@latest add @newtui/form-fieldsnlx shadcn-vue@latest add @newtui/form-fieldsupx newtui@latest add form-fieldsupx shadcn@latest add @newtui/form-fieldsupx shadcn-vue@latest add @newtui/form-fields- newtui
- shadcn
- npm
- pnpm
- yarn
- bun
- deno
- vlt
- vp
- nub
- ni
- upm
The shadcn CLI needs the @newtui registry in your components.json. Set it up.
Install the dependencies
npm install radix-ui class-variance-authoritypnpm add radix-ui class-variance-authorityyarn add radix-ui class-variance-authoritybun add radix-ui class-variance-authoritydeno add npm:radix-ui npm:class-variance-authorityvlt install radix-ui class-variance-authorityvp add radix-ui class-variance-authoritynub add radix-ui class-variance-authorityni radix-ui class-variance-authorityupm add radix-ui class-variance-authority- npm
- pnpm
- yarn
- bun
- deno
- vlt
- vp
- nub
- ni
- upm
npm install reka-ui class-variance-authoritypnpm add reka-ui class-variance-authorityyarn add reka-ui class-variance-authoritybun add reka-ui class-variance-authoritydeno add npm:reka-ui npm:class-variance-authorityvlt install reka-ui class-variance-authorityvp add reka-ui class-variance-authoritynub add reka-ui class-variance-authorityni reka-ui class-variance-authorityupm add reka-ui class-variance-authority- npm
- pnpm
- yarn
- bun
- deno
- vlt
- vp
- nub
- ni
- upm
Copy the source into your project
"use client"
import { cva, type VariantProps } from "class-variance-authority"
import {
Checkbox as CheckboxPrimitive,
Label as LabelPrimitive,
Switch as SwitchPrimitive,
} from "radix-ui"
import * as React from "react"
import { cn } from "@/lib/utils"
/*
* A field shares one set of ids with the parts inside it. The control takes
* `controlId`, the label points at it, and each help line registers the id
* it renders with, so the control's `aria-describedby` names only the lines
* that exist.
*/
type HelpKind = "description" | "error"
interface FieldContextValue {
controlId: string
descriptionId: string
errorId: string
invalid: boolean
registered: Readonly<Record<HelpKind, string | undefined>>
register: (kind: HelpKind, id: string) => () => void
}
const FieldContext = React.createContext<FieldContextValue | null>(null)
export interface FieldProps extends React.ComponentProps<"div"> {
/**
* Marks the whole field as failing validation. The controls inside it read
* it, set `aria-invalid` and take the danger edge, so one prop restyles the
* group rather than each control being told separately.
*/
invalid?: boolean
}
const Field = React.forwardRef<HTMLDivElement, FieldProps>(
({ className, invalid = false, ...props }, ref) => {
const baseId = React.useId()
const [registered, setRegistered] = React.useState<
Record<HelpKind, string | undefined>
>({
description: undefined,
error: undefined,
})
const register = React.useCallback((kind: HelpKind, id: string) => {
setRegistered((current) => ({ ...current, [kind]: id }))
return () =>
setRegistered((current) =>
current[kind] === id ? { ...current, [kind]: undefined } : current
)
}, [])
const value = React.useMemo<FieldContextValue>(
() => ({
controlId: `${baseId}-control`,
descriptionId: `${baseId}-description`,
errorId: `${baseId}-error`,
invalid,
registered,
register,
}),
[baseId, invalid, registered, register]
)
return (
<FieldContext.Provider value={value}>
<div
ref={ref}
data-invalid={invalid || undefined}
className={cn(
"group/field flex min-w-0 flex-col gap-[var(--newt-space-2)]",
className
)}
{...props}
/>
</FieldContext.Provider>
)
}
)
Field.displayName = "Field"
interface ControlWiringInput {
id?: string
invalid?: boolean
"aria-describedby"?: string
"aria-invalid"?: React.AriaAttributes["aria-invalid"]
}
/*
* What a control inside a field sets on its native element: the field's id
* unless the caller gave one, the description, the error while invalid, and
* `aria-invalid` when the control or its field says so. Exported for the
* registry controls that sit in a field without being one of these, such as
* `SelectMenu`.
*/
function useControlWiring({
id,
invalid,
"aria-describedby": describedBy,
"aria-invalid": ariaInvalid,
}: ControlWiringInput) {
const field = React.useContext(FieldContext)
const isInvalid =
invalid ??
(ariaInvalid === true || ariaInvalid === "true" || field?.invalid === true)
/*
* Each id once, in order: the caller's first, then the field's. A form
* library may pass the id a help line also registers.
*/
const ids = [
...new Set(
[
...(describedBy ?? "").split(/\s+/),
field?.registered.description,
isInvalid ? field?.registered.error : undefined,
].filter((value): value is string => Boolean(value))
),
]
/* `"grammar"` and `"spelling"` reach the element unchanged. */
const passThrough =
ariaInvalid === "grammar" || ariaInvalid === "spelling"
? ariaInvalid
: undefined
return {
id: id ?? field?.controlId,
/* A field's `Label` names its control, so the control needs no other name. */
inField: field !== null,
invalid: isInvalid,
ariaInvalid: isInvalid ? true : passThrough,
describedBy: ids.length > 0 ? ids.join(" ") : undefined,
}
}
/*
* Radix Label is a native `<label>` that does not select its text on a
* double press, so a quick second press on it only reaches the control.
* Inside a field it points at the field's control unless given `htmlFor`.
*/
const Label = React.forwardRef<
React.ComponentRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, htmlFor, ...props }, ref) => {
const field = React.useContext(FieldContext)
return (
<LabelPrimitive.Root
ref={ref}
htmlFor={htmlFor ?? field?.controlId}
className={cn(
"font-[family-name:var(--newt-font-sans)] text-[length:var(--newt-font-size-md)] font-[number:var(--newt-font-weight-medium)] leading-[var(--newt-line-height-tight)] text-newt-text-primary",
className
)}
{...props}
/>
)
})
Label.displayName = "Label"
/*
* The box every text control shares. Leaving a hover is quick, arriving a
* little slower. Focus draws a 2px ring inside the edge, so it never
* overlaps a neighbour; an invalid control keeps the danger colour for the
* edge, the hover and the ring alike.
*/
const controlBoxClassName =
"box-border w-full rounded-[var(--newt-radius-md)] border border-solid border-newt-border bg-newt-bg-input font-[family-name:var(--newt-font-sans)] text-[length:var(--newt-font-size-md)] font-[number:var(--newt-font-weight-normal)] text-newt-text-primary transition-[border-color,outline-color] duration-instant ease-newt-in hover:duration-base hover:ease-newt-out motion-reduce:transition-none [&:not([data-invalid]):not([data-disabled]):not(:disabled):not(:has(>input:disabled,>select:disabled)):not(:focus-within):hover]:border-newt-border-strong focus-within:border-newt-focus-ring focus-within:outline focus-within:outline-2 focus-within:outline-offset-[-2px] focus-within:outline-newt-focus-ring data-[invalid]:border-newt-text-danger data-[invalid]:focus-within:border-newt-text-danger data-[invalid]:focus-within:outline-newt-text-danger data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 disabled:cursor-not-allowed disabled:opacity-50 [&:has(>input:disabled,>select:disabled)]:cursor-not-allowed [&:has(>input:disabled,>select:disabled)]:opacity-50 leading-[var(--newt-line-height-tight)]"
const controlVariants = cva(
cn(controlBoxClassName, "relative flex items-center"),
{
variants: {
size: {
sm: "h-newt-control-sm",
md: "h-newt-control-md",
},
},
defaultVariants: { size: "md" },
}
)
/* The native element inside the box: bare, filling it, inheriting its text. */
const bareControlClassName =
"h-full min-w-0 flex-1 border-0 bg-transparent py-0 text-inherit tracking-[inherit] outline-none [font:inherit] placeholder:text-newt-text-muted disabled:cursor-not-allowed"
const accessoryClassName =
"flex aspect-square h-[calc(100%_-_2_*_var(--newt-space-1))] shrink-0 items-center justify-center rounded-[var(--newt-radius-sm)] text-newt-text-secondary"
type ControlSize = NonNullable<VariantProps<typeof controlVariants>["size"]>
export interface InputProps extends Omit<
React.ComponentProps<"input">,
"size"
> {
/** `md` is 40px tall, `sm` 32px. */
size?: ControlSize
/**
* Marks the input as failing validation: sets `aria-invalid` and the
* danger edge. Inside a `Field`, the field's `invalid` applies when this
* is left undefined.
*/
invalid?: boolean
/** Content before the text, such as an icon, in a square slot. */
leading?: React.ReactNode
/** Content after the text, such as an icon or a unit, in a square slot. */
trailing?: React.ReactNode
}
/*
* The box is a wrapper, so it can hold the accessories; `className` lands on
* it, and `ref` and every other prop on the native `<input>`.
*/
const Input = React.forwardRef<HTMLInputElement, InputProps>(
(
{
className,
type = "text",
size,
invalid,
leading,
trailing,
id,
disabled,
hidden,
"aria-describedby": ariaDescribedBy,
"aria-invalid": ariaInvalid,
...props
},
ref
) => {
const wiring = useControlWiring({
id,
invalid,
"aria-describedby": ariaDescribedBy,
"aria-invalid": ariaInvalid,
})
/* A hidden input holds a form value and draws nothing, so it has no box. */
if (type === "hidden") {
return (
<input ref={ref} type="hidden" id={id} disabled={disabled} {...props} />
)
}
const hasLeading = leading !== undefined && leading !== null
const hasTrailing = trailing !== undefined && trailing !== null
return (
<div
hidden={hidden}
data-invalid={wiring.invalid || undefined}
data-disabled={disabled || undefined}
className={cn(
controlVariants({ size }),
"cursor-text",
/*
* Tailwind v3's preflight hides `[hidden]` without `!important`,
* so the box's `flex` would win; `hidden` replaces it.
*/
hidden && "hidden",
hasLeading && "ps-[var(--newt-space-1)]",
hasTrailing && "pe-[var(--newt-space-1)]",
className
)}
>
{hasLeading ? (
<span data-slot="leading" className={accessoryClassName}>
{leading}
</span>
) : null}
<input
ref={ref}
type={type}
id={wiring.id}
disabled={disabled}
aria-invalid={wiring.ariaInvalid}
aria-describedby={wiring.describedBy}
className={cn(
bareControlClassName,
hasLeading ? "ps-0" : "ps-[var(--newt-space-3)]",
hasTrailing ? "pe-0" : "pe-[var(--newt-space-3)]"
)}
{...props}
/>
{hasTrailing ? (
<span data-slot="trailing" className={accessoryClassName}>
{trailing}
</span>
) : null}
</div>
)
}
)
Input.displayName = "Input"
export interface TextareaProps extends React.ComponentProps<"textarea"> {
/**
* Marks the textarea as failing validation. Inside a `Field`, the field's
* `invalid` applies when this is left undefined.
*/
invalid?: boolean
}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
(
{
className,
invalid,
id,
disabled,
"aria-describedby": ariaDescribedBy,
"aria-invalid": ariaInvalid,
...props
},
ref
) => {
const wiring = useControlWiring({
id,
invalid,
"aria-describedby": ariaDescribedBy,
"aria-invalid": ariaInvalid,
})
return (
<textarea
ref={ref}
id={wiring.id}
disabled={disabled}
aria-invalid={wiring.ariaInvalid}
aria-describedby={wiring.describedBy}
data-invalid={wiring.invalid || undefined}
data-disabled={disabled || undefined}
className={cn(
controlBoxClassName,
"block min-h-[80px] resize-y p-[var(--newt-space-3)] placeholder:text-newt-text-muted",
/* `block` beats Tailwind v3's preflight `[hidden]`; `hidden` replaces it. */
props.hidden && "hidden",
className
)}
{...props}
/>
)
}
)
Textarea.displayName = "Textarea"
export interface SelectProps extends Omit<
React.ComponentProps<"select">,
"size"
> {
/** `md` is 40px tall, `sm` 32px. */
size?: ControlSize
/**
* Marks the select as failing validation. Inside a `Field`, the field's
* `invalid` applies when this is left undefined.
*/
invalid?: boolean
}
/*
* The browser's own `<select>`, its arrow replaced by a 20px chevron. Like
* `Input`, the box is a wrapper: `className` lands on it, the rest on the
* native element.
*/
const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
(
{
className,
size,
invalid,
id,
disabled,
hidden,
"aria-describedby": ariaDescribedBy,
"aria-invalid": ariaInvalid,
children,
...props
},
ref
) => {
const wiring = useControlWiring({
id,
invalid,
"aria-describedby": ariaDescribedBy,
"aria-invalid": ariaInvalid,
})
return (
<div
hidden={hidden}
data-invalid={wiring.invalid || undefined}
data-disabled={disabled || undefined}
className={cn(controlVariants({ size }), hidden && "hidden", className)}
>
<select
ref={ref}
id={wiring.id}
disabled={disabled}
aria-invalid={wiring.ariaInvalid}
aria-describedby={wiring.describedBy}
className={cn(
bareControlClassName,
"w-full cursor-pointer appearance-none ps-[var(--newt-space-3)] pe-[calc(var(--newt-space-3)_+_var(--newt-space-5)_+_var(--newt-space-1))] [&>option]:bg-newt-bg-floating"
)}
{...props}
>
{children}
</select>
<svg
aria-hidden="true"
viewBox="0 0 20 20"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="pointer-events-none absolute end-[calc(var(--newt-space-3)-1px)] top-1/2 size-[var(--newt-space-5)] -translate-y-1/2 text-newt-text-primary"
>
<path d="m5 8 5 5 5-5" />
</svg>
</div>
)
}
)
Select.displayName = "Select"
export interface FieldHelpProps extends React.ComponentProps<"span"> {
/**
* `help` is the field's description; `error` colours the text and
* announces it, because a validation message that appears after a submit
* is useless to a reader who never sees it. Inside a `Field`, the control
* lists the description in its `aria-describedby`, and the error while the
* control is invalid.
*/
variant?: "help" | "error"
}
const FieldHelp = React.forwardRef<HTMLSpanElement, FieldHelpProps>(
({ className, variant = "help", id, ...props }, ref) => {
const field = React.useContext(FieldContext)
const kind: HelpKind = variant === "error" ? "error" : "description"
const ownId =
id ?? (kind === "error" ? field?.errorId : field?.descriptionId)
const register = field?.register
React.useEffect(() => {
if (!register || !ownId) return undefined
return register(kind, ownId)
}, [register, kind, ownId])
return (
<span
ref={ref}
id={ownId}
role={variant === "error" ? "alert" : undefined}
className={cn(
"text-[length:var(--newt-font-size-xs)] font-[number:var(--newt-font-weight-normal)] leading-[var(--newt-line-height-tight)]",
variant === "error"
? "text-newt-text-danger"
: "text-newt-text-secondary",
field && "-mt-[var(--newt-space-1)]",
className
)}
{...props}
/>
)
}
)
FieldHelp.displayName = "FieldHelp"
/*
* Radix owns the behaviour of the two toggles: the role, the checked state,
* the space bar and the hidden input a form reads when they carry a `name`.
*
* Switch: 48 x 24px, a 16px thumb 3px inside the border, 24px of travel
* times the writing direction.
*/
const Switch = React.forwardRef<
React.ComponentRef<typeof SwitchPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>
>(({ className, id, ...props }, ref) => {
/* Inside a `Field`, it takes the id the field's `Label` points at. */
const field = React.useContext(FieldContext)
return (
<SwitchPrimitive.Root
ref={ref}
id={id ?? field?.controlId}
className={cn(
"relative box-border inline-flex h-newt-control-xs w-[calc(2*var(--newt-control-xs))] shrink-0 cursor-pointer rounded-[var(--newt-radius-full)] border border-solid border-newt-border bg-newt-bg-input p-0 transition-[background-color,border-color] duration-base ease-newt-out focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-newt-focus-ring disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none enabled:hover:border-newt-border-strong",
"data-[state=checked]:border-newt-border-subtle data-[state=checked]:bg-newt-brand enabled:data-[state=checked]:hover:border-newt-border-subtle enabled:data-[state=checked]:hover:bg-newt-brand-hover",
className
)}
{...props}
>
<SwitchPrimitive.Thumb className="absolute start-[3px] top-[3px] size-[var(--newt-space-4)] rounded-[var(--newt-radius-full)] bg-newt-text-secondary transition-[transform,background-color] duration-base ease-newt-out motion-reduce:transition-none data-[state=checked]:translate-x-[calc(var(--newt-dir)*var(--newt-space-6))] data-[state=checked]:bg-newt-on-accent" />
</SwitchPrimitive.Root>
)
})
Switch.displayName = "Switch"
/*
* The tick and the dash are drawn along their length. Each path carries
* `pathLength="1"`: a dash of 1 covers it, and an offset of 1.25 parks it in
* the gap of 2, so a round cap leaves no dot. The mark draws in over
* `--newt-duration-fast` and leaves over `--newt-duration-instant`.
*/
const checkboxMarkClassName =
"[stroke-dasharray:1_2] [stroke-dashoffset:1.25] transition-[stroke-dashoffset] duration-instant ease-newt-in motion-reduce:transition-none"
/* Checkbox: a 20px box, a 14px tick, a dash for the mixed state. */
const Checkbox = React.forwardRef<
React.ComponentRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, id, ...props }, ref) => {
/* Inside a `Field`, it takes the id the field's `Label` points at. */
const field = React.useContext(FieldContext)
return (
<CheckboxPrimitive.Root
ref={ref}
id={id ?? field?.controlId}
className={cn(
"group box-border inline-flex size-[var(--newt-space-5)] shrink-0 cursor-pointer items-center justify-center rounded-[var(--newt-radius-sm)] border border-solid border-newt-border-strong bg-newt-bg-input p-0 text-newt-on-accent transition-[background-color,border-color] duration-instant ease-newt-in hover:duration-base hover:ease-newt-out focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-newt-focus-ring disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none enabled:hover:border-newt-text-muted",
"data-[state=checked]:border-newt-border-subtle data-[state=checked]:bg-newt-brand data-[state=indeterminate]:border-newt-border-subtle data-[state=indeterminate]:bg-newt-brand enabled:data-[state=checked]:hover:border-newt-border-subtle enabled:data-[state=checked]:hover:bg-newt-brand-hover enabled:data-[state=indeterminate]:hover:border-newt-border-subtle enabled:data-[state=indeterminate]:hover:bg-newt-brand-hover",
className
)}
{...props}
>
{/* Mounted in every state, so the mark can draw in and out. */}
<CheckboxPrimitive.Indicator forceMount className="flex">
<svg
aria-hidden="true"
viewBox="0 0 16 16"
width="14"
height="14"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
className="overflow-visible"
>
{/* A mixed state draws a dash, so a partial group does not read as full. */}
<path
className={cn(
checkboxMarkClassName,
"group-data-[state=checked]:duration-fast group-data-[state=checked]:ease-newt-out group-data-[state=checked]:[stroke-dashoffset:0]"
)}
d="M3 8.5 6.5 12 13 4.5"
pathLength={1}
/>
<path
className={cn(
checkboxMarkClassName,
"group-data-[state=indeterminate]:duration-fast group-data-[state=indeterminate]:ease-newt-out group-data-[state=indeterminate]:[stroke-dashoffset:0]"
)}
d="M4 8h8"
pathLength={1}
/>
</svg>
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
})
Checkbox.displayName = "Checkbox"
export {
Field,
Label,
Input,
Textarea,
Select,
FieldHelp,
Switch,
Checkbox,
controlVariants,
useControlWiring,
}<script setup lang="ts">
import { computed, provide, reactive, useId, type HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
import { fieldContextKey, type HelpKind } from "."
/*
* `invalid` marks the whole field. The controls inside read it, set
* `aria-invalid` and take the danger edge, so a form library that only knows
* "this field is in error" says it once rather than per control.
*/
const { class: className, invalid = false } = defineProps<{
class?: HTMLAttributes["class"]
invalid?: boolean
}>()
const baseId = useId()
const registered = reactive<Record<HelpKind, string | undefined>>({
description: undefined,
error: undefined,
})
provide(fieldContextKey, {
controlId: `${baseId}-control`,
descriptionId: `${baseId}-description`,
errorId: `${baseId}-error`,
invalid: computed(() => invalid),
registered,
register(kind, id) {
registered[kind] = id
return () => {
if (registered[kind] === id) registered[kind] = undefined
}
},
})
</script>
<template>
<div
:data-invalid="invalid || undefined"
:class="
cn(
'group/field flex min-w-0 flex-col gap-[var(--newt-space-2)]',
className
)
"
>
<slot />
</div>
</template><script setup lang="ts">
import { Label, type LabelProps } from "reka-ui"
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
import { useFieldContext } from "."
/*
* Reka Label is a native `<label>` that does not select its text on a double
* press, so a quick second press on it only reaches the control. Inside a
* field it points at the field's control unless given `for`.
*/
const {
class: className,
for: htmlFor,
...rest
} = defineProps<LabelProps & { class?: HTMLAttributes["class"] }>()
const field = useFieldContext()
</script>
<template>
<Label
v-bind="rest"
:for="htmlFor ?? field?.controlId"
:class="
cn(
'font-[family-name:var(--newt-font-sans)] text-[length:var(--newt-font-size-md)] font-[number:var(--newt-font-weight-medium)] leading-[var(--newt-line-height-tight)] text-newt-text-primary',
className
)
"
>
<slot />
</Label>
</template><script setup lang="ts">
import { computed, useAttrs, type HTMLAttributes, type VNode } from "vue"
import { cn } from "@/lib/utils"
import {
accessoryClassName,
bareControlClassName,
controlVariants,
controlWiring,
useFieldContext,
type AriaInvalid,
type ControlVariants,
} from "."
/*
* The box is a wrapper, so it can hold the `leading` and `trailing` slots;
* `class` lands on it, and every other attribute on the native `<input>`.
*/
defineOptions({ inheritAttrs: false })
const {
class: className,
size,
/*
* `undefined` means "let the field decide". Vue casts an absent `boolean`
* prop to `false` unless it has a default, so the default keeps it unset.
*/
invalid = undefined,
id,
type = "text",
disabled = false,
hidden = false,
ariaDescribedby,
ariaInvalid,
} = defineProps<{
class?: HTMLAttributes["class"]
/** `md` is 40px tall, `sm` 32px. */
size?: ControlVariants["size"]
/**
* Marks the input as failing validation: sets `aria-invalid` and the
* danger edge. Inside a `Field`, the field's `invalid` applies when this
* is left undefined.
*/
invalid?: boolean
id?: string
type?: string
disabled?: boolean
/**
* Hides the box with the input. A prop, not an attribute, because Vue's
* attributes object is not reactive and the box must follow a change.
*/
hidden?: boolean
/** Ids to describe the control with, before the field's own. */
ariaDescribedby?: string
ariaInvalid?: AriaInvalid
}>()
const slots = defineSlots<{
/** Content before the text, such as an icon, in a square slot. */
leading?: () => VNode[]
/** Content after the text, such as an icon or a unit, in a square slot. */
trailing?: () => VNode[]
}>()
const model = defineModel<string | number>()
const attrs = useAttrs()
const field = useFieldContext()
const wiring = computed(() =>
controlWiring(field, {
id,
invalid,
describedBy: ariaDescribedby,
ariaInvalid,
})
)
</script>
<template>
<!-- A hidden input holds a form value and draws nothing, so it has no box. -->
<input
v-if="type === 'hidden'"
v-bind="attrs"
v-model="model"
type="hidden"
:id="id"
:disabled="disabled"
/>
<div
v-else
:hidden="hidden"
:data-invalid="wiring.invalid || undefined"
:data-disabled="disabled || undefined"
:class="
cn(
controlVariants({ size }),
'cursor-text',
hidden && 'hidden',
slots.leading && 'ps-[var(--newt-space-1)]',
slots.trailing && 'pe-[var(--newt-space-1)]',
className
)
"
>
<span v-if="slots.leading" data-slot="leading" :class="accessoryClassName">
<slot name="leading" />
</span>
<input
v-bind="attrs"
v-model="model"
:type="type"
:id="wiring.id"
:disabled="disabled"
:aria-invalid="wiring.ariaInvalid"
:aria-describedby="wiring.describedBy"
:class="
cn(
bareControlClassName,
slots.leading ? 'ps-0' : 'ps-[var(--newt-space-3)]',
slots.trailing ? 'pe-0' : 'pe-[var(--newt-space-3)]'
)
"
/>
<span
v-if="slots.trailing"
data-slot="trailing"
:class="accessoryClassName"
>
<slot name="trailing" />
</span>
</div>
</template><script setup lang="ts">
import { computed, useAttrs, type HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
import {
controlBoxClassName,
controlWiring,
useFieldContext,
type AriaInvalid,
} from "."
defineOptions({ inheritAttrs: false })
const {
class: className,
/* `undefined` means "let the field decide"; see `Input`. */
invalid = undefined,
id,
disabled = false,
hidden = false,
ariaDescribedby,
ariaInvalid,
} = defineProps<{
class?: HTMLAttributes["class"]
/**
* Marks the textarea as failing validation. Inside a `Field`, the field's
* `invalid` applies when this is left undefined.
*/
invalid?: boolean
id?: string
disabled?: boolean
/**
* Hides the textarea. Its `block` class would beat Tailwind v3's preflight
* `[hidden]`, so the `hidden` class goes with it; see `Input`.
*/
hidden?: boolean
/** Ids to describe the control with, before the field's own. */
ariaDescribedby?: string
ariaInvalid?: AriaInvalid
}>()
const model = defineModel<string>()
const attrs = useAttrs()
const field = useFieldContext()
const wiring = computed(() =>
controlWiring(field, {
id,
invalid,
describedBy: ariaDescribedby,
ariaInvalid,
})
)
</script>
<template>
<textarea
v-bind="attrs"
v-model="model"
:id="wiring.id"
:disabled="disabled"
:hidden="hidden || undefined"
:aria-invalid="wiring.ariaInvalid"
:aria-describedby="wiring.describedBy"
:data-invalid="wiring.invalid || undefined"
:data-disabled="disabled || undefined"
:class="
cn(
controlBoxClassName,
'block min-h-[80px] resize-y p-[var(--newt-space-3)] placeholder:text-newt-text-muted',
hidden && 'hidden',
className
)
"
/>
</template><script setup lang="ts">
import { computed, useAttrs, type HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
import {
bareControlClassName,
controlVariants,
controlWiring,
useFieldContext,
type AriaInvalid,
type ControlVariants,
} from "."
/*
* The browser's own `<select>`, its arrow replaced by a 20px chevron. Like
* `Input`, the box is a wrapper: `class` lands on it, every other attribute
* on the native element.
*/
defineOptions({ inheritAttrs: false })
const {
class: className,
size,
/* `undefined` means "let the field decide"; see `Input`. */
invalid = undefined,
id,
disabled = false,
hidden = false,
ariaDescribedby,
ariaInvalid,
} = defineProps<{
class?: HTMLAttributes["class"]
/** `md` is 40px tall, `sm` 32px. */
size?: ControlVariants["size"]
/**
* Marks the select as failing validation. Inside a `Field`, the field's
* `invalid` applies when this is left undefined.
*/
invalid?: boolean
id?: string
disabled?: boolean
/** Hides the box with the select; see `Input`. */
hidden?: boolean
/** Ids to describe the control with, before the field's own. */
ariaDescribedby?: string
ariaInvalid?: AriaInvalid
}>()
const model = defineModel<string | number>()
const attrs = useAttrs()
const field = useFieldContext()
const wiring = computed(() =>
controlWiring(field, {
id,
invalid,
describedBy: ariaDescribedby,
ariaInvalid,
})
)
</script>
<template>
<div
:hidden="hidden"
:data-invalid="wiring.invalid || undefined"
:data-disabled="disabled || undefined"
:class="cn(controlVariants({ size }), hidden && 'hidden', className)"
>
<select
v-bind="attrs"
v-model="model"
:id="wiring.id"
:disabled="disabled"
:aria-invalid="wiring.ariaInvalid"
:aria-describedby="wiring.describedBy"
:class="
cn(
bareControlClassName,
'w-full cursor-pointer appearance-none ps-[var(--newt-space-3)] pe-[calc(var(--newt-space-3)_+_var(--newt-space-5)_+_var(--newt-space-1))] [&>option]:bg-newt-bg-floating'
)
"
>
<slot />
</select>
<svg
aria-hidden="true"
viewBox="0 0 20 20"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="pointer-events-none absolute end-[calc(var(--newt-space-3)-1px)] top-1/2 size-[var(--newt-space-5)] -translate-y-1/2 text-newt-text-primary"
>
<path d="m5 8 5 5 5-5" />
</svg>
</div>
</template><script setup lang="ts">
import {
computed,
onBeforeUnmount,
onMounted,
watch,
type HTMLAttributes,
} from "vue"
import { cn } from "@/lib/utils"
import { useFieldContext } from "."
/*
* `help` is the field's description; `error` colours the text and announces
* it, because a validation message that appears after a submit is useless to
* a reader who never sees it. Inside a `Field`, the control lists the
* description in its `aria-describedby`, and the error while it is invalid.
*/
const {
class: className,
variant = "help",
id,
} = defineProps<{
class?: HTMLAttributes["class"]
variant?: "help" | "error"
id?: string
}>()
const field = useFieldContext()
const kind = computed(() =>
variant === "error" ? ("error" as const) : ("description" as const)
)
const ownId = computed(
() => id ?? (kind.value === "error" ? field?.errorId : field?.descriptionId)
)
/* Registered after mount, so the server render and hydration agree. */
let unregister: (() => void) | undefined
onMounted(() => {
watch(
[kind, ownId],
([nextKind, nextId]) => {
unregister?.()
unregister =
field && nextId ? field.register(nextKind, nextId) : undefined
},
{ immediate: true }
)
})
onBeforeUnmount(() => unregister?.())
</script>
<template>
<span
:id="ownId"
:role="variant === 'error' ? 'alert' : undefined"
:class="
cn(
'text-[length:var(--newt-font-size-xs)] font-[number:var(--newt-font-weight-normal)] leading-[var(--newt-line-height-tight)]',
variant === 'error'
? 'text-newt-text-danger'
: 'text-newt-text-secondary',
field && '-mt-[var(--newt-space-1)]',
className
)
"
>
<slot />
</span>
</template><script setup lang="ts">
import {
SwitchRoot,
SwitchThumb,
useForwardPropsEmits,
type SwitchRootEmits,
type SwitchRootProps,
} from "reka-ui"
import { computed, type HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
import { useFieldContext } from "."
/*
* Reka owns the behaviour: the role, the checked state, the space bar and the
* hidden input a form reads when the switch carries a `name`.
*
* 48 x 24px, a 16px thumb 3px inside the border, 24px of travel times the
* writing direction.
*/
const props = defineProps<
SwitchRootProps & { class?: HTMLAttributes["class"] }
>()
const emits = defineEmits<SwitchRootEmits>()
const delegated = computed(() => {
const { class: _class, ...rest } = props
return rest
})
const forwarded = useForwardPropsEmits(delegated, emits)
/* Inside a `Field`, it takes the id the field's `Label` points at. */
const field = useFieldContext()
</script>
<template>
<SwitchRoot
v-bind="forwarded"
:id="props.id ?? field?.controlId"
:class="
cn(
'relative box-border inline-flex h-newt-control-xs w-[calc(2*var(--newt-control-xs))] shrink-0 cursor-pointer rounded-[var(--newt-radius-full)] border border-solid border-newt-border bg-newt-bg-input p-0 transition-[background-color,border-color] duration-base ease-newt-out focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-newt-focus-ring disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none enabled:hover:border-newt-border-strong',
'data-[state=checked]:border-newt-border-subtle data-[state=checked]:bg-newt-brand enabled:data-[state=checked]:hover:border-newt-border-subtle enabled:data-[state=checked]:hover:bg-newt-brand-hover',
props.class
)
"
>
<SwitchThumb
class="absolute start-[3px] top-[3px] size-[var(--newt-space-4)] rounded-[var(--newt-radius-full)] bg-newt-text-secondary transition-[transform,background-color] duration-base ease-newt-out motion-reduce:transition-none data-[state=checked]:translate-x-[calc(var(--newt-dir)*var(--newt-space-6))] data-[state=checked]:bg-newt-on-accent"
/>
</SwitchRoot>
</template><script setup lang="ts">
import {
CheckboxIndicator,
CheckboxRoot,
useForwardPropsEmits,
type CheckboxRootEmits,
type CheckboxRootProps,
} from "reka-ui"
import { computed, type HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
import { useFieldContext } from "."
/*
* Reka owns the behaviour: the role, the checked state, the space bar and the
* hidden input a form reads when the checkbox carries a `name`. A 20px box,
* a 14px tick, a dash for the mixed state.
*/
const props = defineProps<
CheckboxRootProps & { class?: HTMLAttributes["class"] }
>()
const emits = defineEmits<CheckboxRootEmits>()
const delegated = computed(() => {
const { class: _class, ...rest } = props
return rest
})
const forwarded = useForwardPropsEmits(delegated, emits)
/* Inside a `Field`, it takes the id the field's `Label` points at. */
const field = useFieldContext()
/*
* The tick and the dash are drawn along their length. Each path carries
* `pathLength="1"`: a dash of 1 covers it, and an offset of 1.25 parks it in
* the gap of 2, so a round cap leaves no dot. The mark draws in over
* `--newt-duration-fast` and leaves over `--newt-duration-instant`.
*/
const markClassName =
"[stroke-dasharray:1_2] [stroke-dashoffset:1.25] transition-[stroke-dashoffset] duration-instant ease-newt-in motion-reduce:transition-none"
</script>
<template>
<CheckboxRoot
v-bind="forwarded"
:id="props.id ?? field?.controlId"
:class="
cn(
'group box-border inline-flex size-[var(--newt-space-5)] shrink-0 cursor-pointer items-center justify-center rounded-[var(--newt-radius-sm)] border border-solid border-newt-border-strong bg-newt-bg-input p-0 text-newt-on-accent transition-[background-color,border-color] duration-instant ease-newt-in hover:duration-base hover:ease-newt-out focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-newt-focus-ring disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none enabled:hover:border-newt-text-muted',
'data-[state=checked]:border-newt-border-subtle data-[state=checked]:bg-newt-brand data-[state=indeterminate]:border-newt-border-subtle data-[state=indeterminate]:bg-newt-brand enabled:data-[state=checked]:hover:border-newt-border-subtle enabled:data-[state=checked]:hover:bg-newt-brand-hover enabled:data-[state=indeterminate]:hover:border-newt-border-subtle enabled:data-[state=indeterminate]:hover:bg-newt-brand-hover',
props.class
)
"
>
<!-- Mounted in every state, so the mark can draw in and out. -->
<CheckboxIndicator force-mount class="flex">
<svg
aria-hidden="true"
viewBox="0 0 16 16"
width="14"
height="14"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
class="overflow-visible"
>
<!-- A mixed state draws a dash, so a partial group does not read as full. -->
<path
:class="
cn(
markClassName,
'group-data-[state=checked]:duration-fast group-data-[state=checked]:ease-newt-out group-data-[state=checked]:[stroke-dashoffset:0]'
)
"
d="M3 8.5 6.5 12 13 4.5"
pathLength="1"
/>
<path
:class="
cn(
markClassName,
'group-data-[state=indeterminate]:duration-fast group-data-[state=indeterminate]:ease-newt-out group-data-[state=indeterminate]:[stroke-dashoffset:0]'
)
"
d="M4 8h8"
pathLength="1"
/>
</svg>
</CheckboxIndicator>
</CheckboxRoot>
</template>import { cva, type VariantProps } from "class-variance-authority"
import { inject, type InjectionKey, type Ref } from "vue"
export { default as Field } from "./Field.vue"
export { default as Label } from "./Label.vue"
export { default as Input } from "./Input.vue"
export { default as Textarea } from "./Textarea.vue"
export { default as Select } from "./Select.vue"
export { default as FieldHelp } from "./FieldHelp.vue"
export { default as Switch } from "./Switch.vue"
export { default as Checkbox } from "./Checkbox.vue"
/*
* A field shares one set of ids with the parts inside it. The control takes
* `controlId`, the label points at it, and each help line registers the id
* it renders with, so the control's `aria-describedby` names only the lines
* that exist.
*/
export type HelpKind = "description" | "error"
export interface FieldContext {
controlId: string
descriptionId: string
errorId: string
invalid: Readonly<Ref<boolean>>
registered: Readonly<Record<HelpKind, string | undefined>>
register: (kind: HelpKind, id: string) => () => void
}
export const fieldContextKey: InjectionKey<FieldContext> = Symbol("newt-field")
export function useFieldContext(): FieldContext | undefined {
return inject(fieldContextKey, undefined)
}
export type AriaInvalid = boolean | "true" | "false" | "grammar" | "spelling"
interface ControlWiringInput {
id?: string
invalid?: boolean
describedBy?: string
ariaInvalid?: AriaInvalid
}
/*
* What a control inside a field sets on its native element: the field's id
* unless the caller gave one, the description, the error while invalid, and
* `aria-invalid` when the control or its field says so. Also used by the
* registry controls that sit in a field without being one of these, such as
* `SelectMenu`.
*/
export function controlWiring(
field: FieldContext | undefined,
{ id, invalid, describedBy, ariaInvalid }: ControlWiringInput
) {
const isInvalid =
invalid ??
(ariaInvalid === true ||
ariaInvalid === "true" ||
field?.invalid.value === true)
/*
* Each id once, in order: the caller's first, then the field's. A form
* library may pass the id a help line also registers.
*/
const ids = [
...new Set(
[
...(describedBy ?? "").split(/\s+/),
field?.registered.description,
isInvalid ? field?.registered.error : undefined,
].filter((value): value is string => Boolean(value))
),
]
/* `"grammar"` and `"spelling"` reach the element unchanged. */
const passThrough =
ariaInvalid === "grammar" || ariaInvalid === "spelling"
? ariaInvalid
: undefined
return {
id: id ?? field?.controlId,
invalid: isInvalid,
ariaInvalid: isInvalid ? true : passThrough,
describedBy: ids.length > 0 ? ids.join(" ") : undefined,
}
}
/*
* The box every text control shares. Leaving a hover is quick, arriving a
* little slower. Focus draws a 2px ring inside the edge, so it never
* overlaps a neighbour; an invalid control keeps the danger colour for the
* edge, the hover and the ring alike.
*/
export const controlBoxClassName =
"box-border w-full rounded-[var(--newt-radius-md)] border border-solid border-newt-border bg-newt-bg-input font-[family-name:var(--newt-font-sans)] text-[length:var(--newt-font-size-md)] font-[number:var(--newt-font-weight-normal)] text-newt-text-primary transition-[border-color,outline-color] duration-instant ease-newt-in hover:duration-base hover:ease-newt-out motion-reduce:transition-none [&:not([data-invalid]):not([data-disabled]):not(:disabled):not(:has(>input:disabled,>select:disabled)):not(:focus-within):hover]:border-newt-border-strong focus-within:border-newt-focus-ring focus-within:outline focus-within:outline-2 focus-within:outline-offset-[-2px] focus-within:outline-newt-focus-ring data-[invalid]:border-newt-text-danger data-[invalid]:focus-within:border-newt-text-danger data-[invalid]:focus-within:outline-newt-text-danger data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 disabled:cursor-not-allowed disabled:opacity-50 [&:has(>input:disabled,>select:disabled)]:cursor-not-allowed [&:has(>input:disabled,>select:disabled)]:opacity-50 leading-[var(--newt-line-height-tight)]"
export const controlVariants = cva(
`${controlBoxClassName} relative flex items-center`,
{
variants: {
size: {
sm: "h-newt-control-sm",
md: "h-newt-control-md",
},
},
defaultVariants: { size: "md" },
}
)
export type ControlVariants = VariantProps<typeof controlVariants>
/* The native element inside the box: bare, filling it, inheriting its text. */
export const bareControlClassName =
"h-full min-w-0 flex-1 border-0 bg-transparent py-0 text-inherit tracking-[inherit] outline-none [font:inherit] placeholder:text-newt-text-muted disabled:cursor-not-allowed"
export const accessoryClassName =
"flex aspect-square h-[calc(100%_-_2_*_var(--newt-space-1))] shrink-0 items-center justify-center rounded-[var(--newt-radius-sm)] text-newt-text-secondary"Update the import paths
The files import @/lib/utils and sibling components through the aliases in your components.json. Point them at wherever those live in your project.
No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Form Fields to your React project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.
No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Form Fields to your Vue project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.
Usage
import { FormFields } from "@/components/ui/form-fields"
export function Example() {
return <FormFields />
}<script setup lang="ts">
import { Field, Label, Input, Textarea, Select, FieldHelp, Switch, Checkbox } from "@/components/ui/form-fields"
</script>
<template>
<Field />
</template>Examples
Validation error
Set invalid on the Field and every control inside it takes the danger edge and aria-invalid. Swap the help line to variant="error": the control lists it in aria-describedby, and the line is announced as well as coloured. A control also takes invalid of its own, which wins over the field. Type a valid channel name to see both clear.
newt-field"use client"
import * as React from "react"
import {
Field,
FieldHelp,
Input,
Label,
} from "@/registry/bases/newt/ui/form-fields"
/*
* `invalid` is said once, on the field: the input inside reads it for its
* edge and `aria-invalid`, and lists the error line in `aria-describedby`.
* The error line is announced when it appears.
*/
export default function FormFieldsErrorDemo() {
const [name, setName] = React.useState("Game Night!")
const invalid = !/^[a-z0-9-]+$/.test(name)
return (
<Field invalid={invalid} className="w-full max-w-sm">
<Label>Channel name</Label>
<Input value={name} onChange={(event) => setName(event.target.value)} />
{invalid ? (
<FieldHelp variant="error">
Use lowercase letters, numbers and hyphens only.
</FieldHelp>
) : (
<FieldHelp>Members will see #{name}.</FieldHelp>
)}
</Field>
)
}<script setup lang="ts">
import { computed, ref } from "vue"
import {
Field,
FieldHelp,
Input,
Label,
} from "~~/registry/bases/newt/ui/form-fields"
/*
* `invalid` is said once, on the field: the input inside reads it for its
* edge and `aria-invalid`, and lists the error line in `aria-describedby`.
* The error line is announced when it appears.
*/
const name = ref("Game Night!")
const invalid = computed(() => !/^[a-z0-9-]+$/.test(name.value))
</script>
<template>
<Field :invalid="invalid" class="w-full max-w-sm">
<Label>Channel name</Label>
<Input v-model="name" />
<FieldHelp v-if="invalid" variant="error">
Use lowercase letters, numbers and hyphens only.
</FieldHelp>
<FieldHelp v-else>Members will see #{{ name }}.</FieldHelp>
</Field>
</template>Sizes
size is md (40px) by default, or sm (32px) for a dense row. It applies to Input and Select; the native size attribute of those elements is not available.
newt-fieldimport {
Field,
Input,
Label,
Select,
} from "@/registry/bases/newt/ui/form-fields"
/* `md` is 40px tall, the height of a medium button; `sm` is 32px. */
export default function FormFieldsSizesDemo() {
return (
<div className="flex w-full max-w-sm flex-col gap-6">
<Field>
<Label>Medium</Label>
<Input placeholder="40px tall" />
</Field>
<Field>
<Label>Small</Label>
<Input size="sm" placeholder="32px tall" />
</Field>
<Field>
<Label>Small select</Label>
<Select size="sm" defaultValue="all">
<option value="all">All messages</option>
<option value="mentions">Only mentions</option>
<option value="none">Nothing</option>
</Select>
</Field>
</div>
)
}<script setup lang="ts">
import { ref } from "vue"
import {
Field,
Input,
Label,
Select,
} from "~~/registry/bases/newt/ui/form-fields"
/* `md` is 40px tall, the height of a medium button; `sm` is 32px. */
const notify = ref("all")
</script>
<template>
<div class="flex w-full max-w-sm flex-col gap-6">
<Field>
<Label>Medium</Label>
<Input placeholder="40px tall" />
</Field>
<Field>
<Label>Small</Label>
<Input size="sm" placeholder="32px tall" />
</Field>
<Field>
<Label>Small select</Label>
<Select v-model="notify" size="sm">
<option value="all">All messages</option>
<option value="mentions">Only mentions</option>
<option value="none">Nothing</option>
</Select>
</Field>
</div>
</template>Leading and trailing
leading and trailing put an icon, a unit or a short label in a square slot inside the box, before or after the text. In React they are props that take a node; in Vue they are slots with the same names. The slots are decoration: keep the name of the control on its Label, and say a unit in the help line too.
newt-fieldimport {
Field,
FieldHelp,
Input,
Label,
} from "@/registry/bases/newt/ui/form-fields"
function SearchIcon() {
return (
<svg
aria-hidden="true"
viewBox="0 0 20 20"
width="16"
height="16"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
>
<circle cx="9" cy="9" r="5.5" />
<path d="m13 13 4 4" />
</svg>
)
}
/*
* `leading` and `trailing` sit in square slots inside the box. They are
* decoration: the input keeps its own label, so the slots carry no name.
*/
export default function FormFieldsAccessoriesDemo() {
return (
<div className="flex w-full max-w-sm flex-col gap-6">
<Field>
<Label>Search members</Label>
<Input type="search" placeholder="Username" leading={<SearchIcon />} />
</Field>
<Field>
<Label>Slowmode</Label>
<Input
type="number"
defaultValue={30}
min={0}
trailing={<span aria-hidden="true">s</span>}
/>
<FieldHelp>Seconds between two messages from one member.</FieldHelp>
</Field>
</div>
)
}<script setup lang="ts">
import { ref } from "vue"
import {
Field,
FieldHelp,
Input,
Label,
} from "~~/registry/bases/newt/ui/form-fields"
/*
* The `leading` and `trailing` slots sit in square slots inside the box.
* They are decoration: the input keeps its own label, so the slots carry no
* name.
*/
const slowmode = ref(30)
</script>
<template>
<div class="flex w-full max-w-sm flex-col gap-6">
<Field>
<Label>Search members</Label>
<Input type="search" placeholder="Username">
<template #leading>
<svg
aria-hidden="true"
viewBox="0 0 20 20"
width="16"
height="16"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
>
<circle cx="9" cy="9" r="5.5" />
<path d="m13 13 4 4" />
</svg>
</template>
</Input>
</Field>
<Field>
<Label>Slowmode</Label>
<Input v-model="slowmode" type="number" min="0">
<template #trailing>
<span aria-hidden="true">s</span>
</template>
</Input>
<FieldHelp>Seconds between two messages from one member.</FieldHelp>
</Field>
</div>
</template>Disabled
disabled dims the control to half opacity and stops hover and input.
newt-fieldimport {
Field,
FieldHelp,
Input,
Label,
Select,
Textarea,
} from "@/registry/bases/newt/ui/form-fields"
/* A disabled control dims to half and takes no input or hover. */
export default function FormFieldsDisabledDemo() {
return (
<div className="flex w-full max-w-sm flex-col gap-6">
<Field>
<Label>Server ID</Label>
<Input defaultValue="1234567890" disabled />
<FieldHelp>Set when the server was created.</FieldHelp>
</Field>
<Field>
<Label>Region</Label>
<Select defaultValue="auto" disabled>
<option value="auto">Automatic</option>
</Select>
</Field>
<Field>
<Label>Rules</Label>
<Textarea
rows={2}
defaultValue="Managed by the community team."
disabled
/>
</Field>
</div>
)
}<script setup lang="ts">
import {
Field,
FieldHelp,
Input,
Label,
Select,
Textarea,
} from "~~/registry/bases/newt/ui/form-fields"
/* A disabled control dims to half and takes no input or hover. */
</script>
<template>
<div class="flex w-full max-w-sm flex-col gap-6">
<Field>
<Label>Server ID</Label>
<Input model-value="1234567890" disabled />
<FieldHelp>Set when the server was created.</FieldHelp>
</Field>
<Field>
<Label>Region</Label>
<Select model-value="auto" disabled>
<option value="auto">Automatic</option>
</Select>
</Field>
<Field>
<Label>Rules</Label>
<Textarea
rows="2"
model-value="Managed by the community team."
disabled
/>
</Field>
</div>
</template>Textarea
Textarea shares the input’s styling and resizes vertically. Pair it with a FieldHelp when the text has a limit the reader should see coming.
newt-field"use client"
import * as React from "react"
import {
Field,
FieldHelp,
Label,
Textarea,
} from "@/registry/bases/newt/ui/form-fields"
const LIMIT = 120
export default function FormFieldsTextareaDemo() {
const [topic, setTopic] = React.useState(
"Patch notes, release dates and nothing else."
)
return (
<Field className="w-full max-w-sm">
<Label>Channel topic</Label>
<Textarea
rows={3}
maxLength={LIMIT}
placeholder="Let everyone know what this channel is for"
value={topic}
onChange={(event) => setTopic(event.target.value)}
/>
<FieldHelp>
{topic.length} of {LIMIT} characters
</FieldHelp>
</Field>
)
}<script setup lang="ts">
import { ref } from "vue"
import {
Field,
FieldHelp,
Label,
Textarea,
} from "~~/registry/bases/newt/ui/form-fields"
const LIMIT = 120
const topic = ref("Patch notes, release dates and nothing else.")
</script>
<template>
<Field class="w-full max-w-sm">
<Label>Channel topic</Label>
<Textarea
v-model="topic"
rows="3"
:maxlength="LIMIT"
placeholder="Let everyone know what this channel is for"
/>
<FieldHelp>{{ topic.length }} of {{ LIMIT }} characters</FieldHelp>
</Field>
</template>Native select
Select is the browser’s own <select> in the field’s clothes, its arrow replaced by a 20px chevron: use it for a short list in a dense form, and reach for Select Menu when options need icons or descriptions.
newt-field"use client"
import * as React from "react"
import {
Field,
FieldHelp,
Label,
Select,
} from "@/registry/bases/newt/ui/form-fields"
export default function FormFieldsSelectDemo() {
const [duration, setDuration] = React.useState("1d")
return (
<Field className="w-full max-w-sm">
<Label>Hide after inactivity</Label>
<Select
value={duration}
onChange={(event) => setDuration(event.target.value)}
>
<option value="1h">1 hour</option>
<option value="1d">24 hours</option>
<option value="3d">3 days</option>
<option value="1w">1 week</option>
</Select>
<FieldHelp>
Quiet threads leave the channel list after this long.
</FieldHelp>
</Field>
)
}<script setup lang="ts">
import { ref } from "vue"
import {
Field,
FieldHelp,
Label,
Select,
} from "~~/registry/bases/newt/ui/form-fields"
const duration = ref("1d")
</script>
<template>
<Field class="w-full max-w-sm">
<Label>Hide after inactivity</Label>
<Select v-model="duration">
<option value="1h">1 hour</option>
<option value="1d">24 hours</option>
<option value="3d">3 days</option>
<option value="1w">1 week</option>
</Select>
<FieldHelp>Quiet threads leave the channel list after this long.</FieldHelp>
</Field>
</template>Switch and checkbox
A Switch is for a setting that applies the moment it is flipped, a Checkbox for an answer submitted with the rest of the form. Both take disabled, and both are buttons that need a name from aria-labelledby or aria-label.
newt-field"use client"
import * as React from "react"
import { Checkbox, Switch } from "@/registry/bases/newt/ui/form-fields"
/*
* A switch takes effect at once; a checkbox is an answer that waits for the
* form around it. Both are buttons, so each needs a name of its own.
*/
export default function FormFieldsTogglesDemo() {
const [previews, setPreviews] = React.useState(true)
const [remember, setRemember] = React.useState(true)
return (
<div className="flex w-full max-w-sm flex-col gap-4 text-sm text-newt-text-primary">
<div className="flex items-center justify-between gap-4">
<span id="newt-toggle-previews">Show link previews</span>
<Switch
aria-labelledby="newt-toggle-previews"
checked={previews}
onCheckedChange={setPreviews}
/>
</div>
<div className="flex items-center justify-between gap-4">
<span id="newt-toggle-streamer" className="text-newt-text-muted">
Streamer mode (set by your server)
</span>
<Switch aria-labelledby="newt-toggle-streamer" disabled />
</div>
<div className="flex items-center gap-3">
<Checkbox
aria-labelledby="newt-toggle-remember"
checked={remember}
// Radix also reports "indeterminate"; this box has two states.
onCheckedChange={(checked) => setRemember(checked === true)}
/>
<span id="newt-toggle-remember">Remember this device</span>
</div>
<div className="flex items-center gap-3">
<Checkbox aria-labelledby="newt-toggle-beta" disabled />
<span id="newt-toggle-beta" className="text-newt-text-muted">
Join the beta (invite only)
</span>
</div>
</div>
)
}<script setup lang="ts">
import { ref } from "vue"
import { Checkbox, Switch } from "~~/registry/bases/newt/ui/form-fields"
/*
* A switch takes effect at once; a checkbox is an answer that waits for the
* form around it. Both are buttons, so each needs a name of its own.
*/
const previews = ref(true)
const remember = ref(true)
</script>
<template>
<div
class="flex w-full max-w-sm flex-col gap-4 text-sm text-newt-text-primary"
>
<div class="flex items-center justify-between gap-4">
<span id="newt-toggle-previews">Show link previews</span>
<Switch v-model="previews" aria-labelledby="newt-toggle-previews" />
</div>
<div class="flex items-center justify-between gap-4">
<span id="newt-toggle-streamer" class="text-newt-text-muted">
Streamer mode (set by your server)
</span>
<Switch aria-labelledby="newt-toggle-streamer" disabled />
</div>
<div class="flex items-center gap-3">
<Checkbox v-model="remember" aria-labelledby="newt-toggle-remember" />
<span id="newt-toggle-remember">Remember this device</span>
</div>
<div class="flex items-center gap-3">
<Checkbox aria-labelledby="newt-toggle-beta" disabled />
<span id="newt-toggle-beta" class="text-newt-text-muted">
Join the beta (invite only)
</span>
</div>
</div>
</template>API reference
Field
invalid?boolean | undefined
Marks the whole field as failing validation. The controls inside it read it, set `aria-invalid` and take the danger edge, so one prop restyles the group rather than each control being told separately.
boolean | undefinedInput
size?"sm" | "md"
The height: `md` is 40px, `sm` is 32px.
"sm" | "md""md"invalid?boolean | undefined
Marks the input as failing validation: sets `aria-invalid` and the danger edge. Inside a `Field`, the field's `invalid` applies when this is left undefined.
boolean | undefinedleading?ReactNode / slot
Content before the text, such as an icon, in a square slot. A prop in React, a slot in Vue.
ReactNode / slottrailing?ReactNode / slot
Content after the text, such as an icon or a unit, in a square slot. A prop in React, a slot in Vue.
ReactNode / slotSelect
size?"sm" | "md"
The height: `md` is 40px, `sm` is 32px.
"sm" | "md""md"invalid?boolean | undefined
Marks the select as failing validation. Inside a `Field`, the field's `invalid` applies when this is left undefined.
boolean | undefinedTextarea
invalid?boolean | undefined
Marks the textarea as failing validation. Inside a `Field`, the field's `invalid` applies when this is left undefined.
boolean | undefinedFieldHelp
variant?"help" | "error" | undefined
`help` is the field's description. `error` colours the text and announces it: a validation message that appears after a submit is useless to a reader who never sees it. Inside a `Field`, the control lists the description in its `aria-describedby`, and the error while it is invalid.
"help" | "error" | undefinedSwitch
checked / v-model?boolean
Whether the switch is on. In React, leave it undefined and pass `defaultChecked` to let the switch own it.
booleandefaultChecked / default-value?boolean
The state on first render, for an uncontrolled switch.
booleanfalseonCheckedChange?(checked: boolean) => void
React only. Called when the switch changes; Vue emits `update:modelValue`.
(checked: boolean) => voidname?string
The field name. Inside a `<form>`, the switch submits `value` under this name while it is on.
stringvalue?string
The value a form receives while the switch is on.
string"on"required?boolean
The form does not submit until the switch is on.
booleanfalsedisabled?boolean
Dims the switch and stops it taking input.
booleanfalseCheckbox
checked / v-model?boolean | "indeterminate"
Whether the box is ticked. In React, leave it undefined and pass `defaultChecked` to let the checkbox own it.
boolean | "indeterminate"defaultChecked / default-value?boolean | "indeterminate"
The state on first render, for an uncontrolled checkbox.
boolean | "indeterminate"falseonCheckedChange?(checked: boolean | "indeterminate") => void
React only. Called when the checkbox changes; Vue emits `update:modelValue`.
(checked: boolean | "indeterminate") => voidname?string
The field name. Inside a `<form>`, the checkbox submits `value` under this name while it is ticked.
stringvalue?string
The value a form receives while the box is ticked.
string"on"required?boolean
The form does not submit until the box is ticked.
booleanfalsedisabled?boolean
Dims the checkbox and stops it taking input.
booleanfalseThe registry exports Field, Label, Input, Textarea, Select, FieldHelp, Switch, Checkbox and controlVariants. Label, Switch and Checkbox accept the other props of the primitive they wrap. The other parts accept the native attributes of the element they render. React uses className. Vue uses class and fallthrough attributes. Input and Select render a box around the native element: className (class in Vue) styles the box, and every other attribute reaches the native <input> or <select>. In React, ref reaches the native element too; in Vue, a template ref gives the component instance. An Input with type="hidden" renders the bare native input with no box, and hidden hides the box.
The HTML classes are .newt-field, .newt-label, .newt-input, .newt-input--sm, .newt-input-group with __leading and __trailing, .newt-textarea, .newt-select-group with .newt-select and __chevron, .newt-help with .newt-field__help--error, .newt-switch with __input and __thumb, and .newt-checkbox with __input and __box. The HTML switch and checkbox are native checkboxes, so they need no script.
Accessibility
Associate every control with a visible label. Label renders a native <label>. Inside a Field, it points at the field’s control by itself; outside one, or when you give the control an id, set htmlFor (for in Vue) to that id. Inside a Field, the control’s aria-describedby names the help line and, while invalid, the error line, after any id you pass yourself. invalid sets aria-invalid, so the state does not depend on colour alone.
Focus draws a 2px --newt-focus-ring ring inside the edge of a text control; an invalid control draws it in --newt-text-danger. Error text uses the same token, which keeps 4.5:1 on every surface. The leading and trailing slots are not part of the control’s name.
Switch is a button with role="switch", and Checkbox is a button with role="checkbox". Both carry aria-checked, and Space toggles them. Give each one a name with a Label, aria-labelledby or aria-label. A focused Switch or Checkbox draws a 2px --newt-focus-ring ring 2px outside its edge. The switch thumb slides with --newt-duration-base and follows the writing direction. The checkbox tick, or the dash of the mixed state, draws itself along its length with --newt-duration-fast. With reduced motion, both change at once.
Tokens
Form Fields reads its colours, radii and motion from the --newt-* tokens installed with the library. Override a token and every component that reads it follows, including this one — see the token layer. In the plain HTML and CSS distribution the same component is newt-field.
--newt-space-2--newt-font-size-md--newt-font-weight-medium--newt-line-height-tight--newt-text-primary--newt-bg-input--newt-border--newt-radius-md--newt-font-sans--newt-font-weight-normal--newt-duration-instant--newt-ease-in--newt-control-md--newt-space-3--newt-control-sm--newt-border-strong--newt-duration-base--newt-ease-out--newt-focus-ring--newt-text-link--newt-text-muted--newt-text-danger--newt-danger--newt-space-1--newt-radius-sm--newt-text-secondary--newt-space-5--newt-font-size-xs--newt-control-xs--newt-radius-full--newt-space-4--newt-brand--newt-border-subtle--newt-brand-hover--newt-dir--newt-space-6--newt-on-accent--newt-font-size-sm--newt-duration-fast