Components
Form
Fields stacked 24px apart, a failure from the server in a dark red box, and the actions at the end, the main one last. Errors wait until a field is left or the form is sent.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add form<script type="module" src="/spyglass-ds/elements/form.js"></script>Usage
Any form with more than one field: tracking a brand, inviting a teammate, account settings. useForm holds the values, the rules and the send.
Never
- Errors while the first value is still being typed
- The browser's own error bubbles
- A red hairline at rest
- Two primary buttons: one White action, the rest secondary or ghost
Props
The web component takes the same as attributes or properties (<spyglass-form>); title is heading there.
<Form>
| Prop | Type | Default |
|---|---|---|
failure | string A failure from the server, shown above the actions. | |
label | string The form's name for assistive tech. | |
onSubmit | () => void It was sent (a submit button or Enter in a field). | |
actions | ReactNode The buttons at the end, the main one last. | |
children | ReactNode | |
className | string |
Examples
The same example in React and as web components; both render identically.
'use client'
import { useState } from 'react'
import { Button } from '@/react/components/ui/Button'
import { Field } from '@/react/components/ui/Field'
import { Form } from '@/react/components/ui/Form'
import { Input } from '@/react/components/ui/Input'
import { NativeSelect } from '@/react/components/ui/NativeSelect'
import { useForm } from '@/react/hooks/useForm'
// Tracking a new brand: a name, its site and where it advertises. Send it empty to see the errors; a name of "Acme"
// shows the server's answer.
export default function Track() {
const [added, setAdded] = useState('')
const { values, set, errors, sending, failure, touch, submit, reset } = useForm(
{ brand: '', site: '', platform: 'meta' },
{
brand: v => (!String(v).trim() ? 'Name the brand to track.' : undefined),
site: v => (!String(v).trim() ? 'Add the brand\'s site.' : !/^[\w-]+(\.[\w-]+)+$/.test(String(v).trim()) ? 'Use a domain, such as acme.com.' : undefined),
},
)
function send() {
void submit(async (v) => {
await new Promise(resolve => setTimeout(resolve, 600))
if (v.brand.trim().toLowerCase() === 'acme') throw new Error('Acme is already on your list.')
setAdded(v.brand.trim())
})
}
return (
<div className="w-100 max-w-full">
{!added
? (
<Form
label="Track a brand"
failure={failure}
onSubmit={send}
actions={(
<>
<Button variant="ghost" onClick={reset}>Clear</Button>
<Button type="submit" disabled={sending}>{sending ? 'Adding' : 'Start tracking'}</Button>
</>
)}
>
<Field label="Brand" description="The name as it shows on its ads." error={errors.brand}>
{({ id, describedBy, invalid }) => <Input id={id} value={values.brand} onChange={e => set('brand', e.target.value)} invalid={invalid} aria-describedby={describedBy} autoComplete="off" placeholder="Acme Studio" onBlur={() => touch('brand')} />}
</Field>
<Field label="Site" error={errors.site}>
{({ id, describedBy, invalid }) => <Input id={id} value={values.site} onChange={e => set('site', e.target.value)} invalid={invalid} aria-describedby={describedBy} autoComplete="off" placeholder="acme.com" onBlur={() => touch('site')} />}
</Field>
<Field label="Platform">
{({ id }) => (
<NativeSelect id={id} value={values.platform} onChange={e => set('platform', e.target.value)}>
<option value="meta">Meta</option><option value="tiktok">TikTok</option><option value="all">Every platform</option>
</NativeSelect>
)}
</Field>
</Form>
)
: (
<div className="flex flex-col items-start gap-4 rounded-container bg-surface-raised p-6" role="status">
<p className="type-ui text-fg">Tracking {added}. New ads show up within a day.</p>
<Button variant="secondary" onClick={() => { setAdded(''); reset() }}>Track another</Button>
</div>
)}
</div>
)
}<!-- Tracking a new brand: a name, its site and where it advertises. Send it empty to see the errors; a name of "Acme"
shows the server's answer. -->
<div id="track-brand-form" class="w-100 max-w-full">
<spyglass-form label="Track a brand">
<spyglass-field label="Brand" description="The name as it shows on its ads.">
<spyglass-input data-key="brand" autocomplete="off" placeholder="Acme Studio"></spyglass-input>
</spyglass-field>
<spyglass-field label="Site">
<spyglass-input data-key="site" autocomplete="off" placeholder="acme.com"></spyglass-input>
</spyglass-field>
<spyglass-field label="Platform">
<spyglass-native-select data-key="platform" value="meta"><option value="meta">Meta</option><option value="tiktok">TikTok</option><option value="all">Every platform</option></spyglass-native-select>
</spyglass-field>
<spyglass-button slot="actions" variant="ghost" data-clear>Clear</spyglass-button>
<spyglass-button slot="actions" type="submit">Start tracking</spyglass-button>
</spyglass-form>
<template>
<div class="flex flex-col items-start gap-4 rounded-container bg-surface-raised p-6" role="status">
<p class="type-ui text-fg"></p>
<spyglass-button variant="secondary">Track another</spyglass-button>
</div>
</template>
</div>
<script type="module">
// useForm: an error shows once its field is left or the form sent, then follows the value.
await customElements.whenDefined('spyglass-form')
const root = document.getElementById('track-brand-form')
const form = root.querySelector('spyglass-form')
const template = root.querySelector('template')
const submitButton = form.querySelector('[type="submit"]')
const fields = Object.fromEntries([...form.querySelectorAll('[data-key]')].map((el) => [el.dataset.key, el]))
const initial = { brand: '', site: '', platform: 'meta' }
const rules = {
brand: (v) => (!String(v).trim() ? 'Name the brand to track.' : undefined),
site: (v) => (!String(v).trim() ? "Add the brand's site." : !/^[\w-]+(\.[\w-]+)+$/.test(String(v).trim()) ? 'Use a domain, such as acme.com.' : undefined),
}
let values = { ...initial }
let touched = {}
let tried = false
let sending = false
const all = () => Object.fromEntries(Object.entries(rules).map(([k, rule]) => [k, rule(values[k], values)]).filter(([, m]) => m))
const paint = () => {
const errors = all()
for (const key of Object.keys(rules)) {
const message = tried || touched[key] ? errors[key] : undefined
fields[key].closest('spyglass-field').error = message
fields[key].invalid = !!message
}
submitButton.disabled = sending
// Only a changed label is written: replacing the text under a press would swallow its click.
const label = sending ? 'Adding' : 'Start tracking'
if (submitButton.textContent !== label) submitButton.textContent = label
}
for (const [key, el] of Object.entries(fields)) {
el.addEventListener('input', () => { values = { ...values, [key]: el.value }; paint() })
el.addEventListener('change', () => { values = { ...values, [key]: el.value }; paint() })
el.addEventListener('focusout', () => { touched[key] = true; paint() })
}
const reset = () => {
values = { ...initial }
touched = {}
tried = false
form.failure = undefined
fields.brand.value = ''
fields.site.value = ''
fields.platform.value = 'meta'
paint()
}
form.querySelector('[data-clear]').addEventListener('click', reset)
form.addEventListener('submit', async () => {
tried = true
form.failure = undefined
paint()
if (Object.keys(all()).length || sending) return
sending = true
paint()
try {
await new Promise((resolve) => setTimeout(resolve, 600))
if (values.brand.trim().toLowerCase() === 'acme') throw new Error('Acme is already on your list.')
const done = template.content.firstElementChild.cloneNode(true)
done.querySelector('p').textContent = `Tracking ${values.brand.trim()}. New ads show up within a day.`
done.querySelector('spyglass-button').addEventListener('click', () => {
done.replaceWith(form)
reset()
})
form.replaceWith(done)
} catch (error) {
form.failure = error.message
} finally {
sending = false
paint()
}
})
paint()
</script>Source
'use client'
import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'
// A form composed from Field, Input and Button: fields stacked 24px apart, each a Field with its label over it and its
// description or error under it; a failure from the server in a dark red box with the brand corner above the actions;
// the actions at the end, the main one last. It never validates as the first value is typed: useForm shows an error
// once its field is left or the form is sent, then follows the value; on a send with errors focus moves to the first
// field that is wrong. The browser's own bubbles are off (noValidate); Enter in a field sends it.
export interface FormProps {
/** A failure from the server, shown above the actions. */
failure?: string
/** The form's name for assistive tech. */
label?: string
/** It was sent (a submit button or Enter in a field). */
onSubmit?: () => void
/** The buttons at the end, the main one last. */
actions?: ReactNode
children?: ReactNode
className?: string
}
export function Form({ failure, label, onSubmit, actions, children, className }: FormProps) {
const form = useRef<HTMLFormElement | null>(null)
// Focus moves after the next render, once the errors the submit raised are drawn.
const [sent, setSent] = useState(0)
useEffect(() => {
if (sent) form.current?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus()
}, [sent])
function send(event: FormEvent) {
event.preventDefault()
onSubmit?.()
setSent(n => n + 1)
}
return (
<form data-ds="form" ref={form} className={className ? `flex flex-col gap-6 ${className}` : 'flex flex-col gap-6'} noValidate aria-label={label} onSubmit={send}>
{children}
{failure && <p className="rounded-control bg-surface-danger px-4 py-3 type-ui text-fg-danger" role="alert">{failure}</p>}
{actions && <div className="flex flex-wrap items-center justify-end gap-2">{actions}</div>}
</form>
)
}
export default Form'use client'
import { useCallback, useRef, useState } from 'react'
/** A rule for one field: the message to show when the value is wrong, or nothing when it is right. */
export type Rule<V extends Record<string, unknown>> = (value: V[keyof V], values: V) => string | undefined
/**
* A form's values, its errors and its submit (the Form item). An error shows once its field has been left or the form
* submitted, never while the first value is still being typed; after that it updates as the value changes. `submit`
* checks every rule and runs `send` only when all pass, holding `sending` while it runs; a thrown Error's message
* becomes the form's `failure`. `values` is read with `set(key, value)` to write one.
*/
export function useForm<V extends Record<string, unknown>>(initial: V, rules: Partial<Record<keyof V, Rule<V>>>) {
const [values, setValues] = useState<V>({ ...initial })
const [touched, setTouched] = useState<Record<string, boolean>>({})
const [tried, setTried] = useState(false)
const [sending, setSending] = useState(false)
const [failure, setFailure] = useState('')
// The latest values and sending, for a submit called from a stale closure.
const latest = useRef(values)
latest.current = values
const busy = useRef(false)
const first = useRef(initial)
const rulesRef = useRef(rules)
rulesRef.current = rules
const check = (v: V) => {
const out: Partial<Record<keyof V, string>> = {}
for (const key of Object.keys(rulesRef.current) as Array<keyof V>) {
const message = rulesRef.current[key]?.(v[key], v)
if (message) out[key] = message
}
return out
}
const all = check(values)
/** The errors to show now. */
const errors: Partial<Record<keyof V, string>> = {}
for (const key of Object.keys(all) as Array<keyof V>) if (tried || touched[String(key)]) errors[key] = all[key]
const valid = Object.keys(all).length === 0
const set = useCallback(<K extends keyof V>(key: K, value: V[K]) => {
setValues(v => ({ ...v, [key]: value }))
}, [])
const touch = useCallback((key: keyof V) => {
setTouched(t => ({ ...t, [String(key)]: true }))
}, [])
const submit = useCallback(async (send: (values: V) => Promise<void> | void) => {
setTried(true)
setFailure('')
if (Object.keys(check(latest.current)).length || busy.current) return false
busy.current = true
setSending(true)
try {
await send(latest.current)
return true
}
catch (error) {
setFailure(error instanceof Error ? error.message : 'Something went wrong. Try again.')
return false
}
finally {
busy.current = false
setSending(false)
}
}, []) // eslint-disable-line react-hooks/exhaustive-deps
const reset = useCallback(() => {
setValues({ ...first.current })
setTouched({})
setTried(false)
setFailure('')
}, [])
return { values, set, errors, valid, sending, failure, touch, submit, reset }
}import { html, nothing, type PropertyValues } from 'lit'
import { DsElement, define } from '@/elements/lib/element'
import styles from 'virtual:tw'
// Form.tsx as <spyglass-form>: fields stacked 24px apart, each a <spyglass-field> with its label over it and its
// description or error under it; a `failure` from the server in a dark red box with the brand corner above the
// actions; the actions (slot="actions") at the end, the main one last. It never validates as the first value is typed:
// the page shows an error once its field is left or the form is sent, and on a send with errors focus moves to the
// first field that is wrong: marked `invalid` (or aria-invalid="true"), or failing its own validity. Like a novalidate
// form it never blocks a send or shows the browser's bubbles; checkValidity() and reportValidity() check its fields.
//
// A <form> in a shadow root does not own the fields the page puts in its slots, so the element is the form's behavior
// itself: a press on a submit button in it (a <button type="submit"> or an element with type="submit"), or Enter in a
// one-line field, fires `submit`; a press on a reset button fires `reset`. The host is the form's box (React's root
// <form>), so a class on the element lands on it.
type Validatable = HTMLElement & { checkValidity(): boolean, reportValidity(): boolean, validity: ValidityState, willValidate: boolean }
const TEXT_INPUT = /^(text|email|password|search|tel|url|number|date|datetime-local|month|time|week)$/
/**
* @summary A form: fields, a failure, the actions.
* @slot - The fields.
* @slot actions - The buttons at the end, the main one last.
* @fires submit - It was sent (a submit button or Enter in a field).
* @fires reset - A reset button was pressed.
*/
export class Form extends DsElement {
static styles = [DsElement.styles, styles]
static properties = { failure: {}, label: {} }
/** A failure from the server, shown above the actions. */
failure?: string
/** The form's name for assistive tech. */
label?: string
constructor() {
super()
this.addEventListener('click', this.onClick)
this.addEventListener('keydown', this.onKey)
}
protected updated(changed: PropertyValues) {
super.updated(changed)
// The host is the form, for assistive tech too.
this.setAttribute('role', 'form')
if (this.label) this.setAttribute('aria-label', this.label)
else this.removeAttribute('aria-label')
}
/**
* What a control does when pressed: submit, reset or neither. An element's `type` is its attribute or its property
* (React sets it as a property); a page's own <button> submits unless its type says otherwise, as in a native form;
* a button inside an element's shadow root counts only for the type written on it.
*/
private typeOf(n: HTMLElement): string | null {
if (n.localName.includes('-')) {
const prop = (n as HTMLElement & { type?: unknown }).type
return n.getAttribute('type') ?? (typeof prop === 'string' ? prop : null)
}
if (n.localName !== 'button') return null
return n.getAttribute('type') ?? (n.getRootNode() === this.getRootNode() ? 'submit' : null)
}
/** The control in the event's path that submits or resets, if any. */
private kind(event: Event): 'submit' | 'reset' | null {
for (const n of event.composedPath()) {
if (n === this) break
if (!(n instanceof HTMLElement)) continue
const type = this.typeOf(n)
if (type === 'submit' || type === 'reset') return n.matches(':disabled, [disabled]') ? null : type
}
return null
}
private onClick = (event: MouseEvent) => {
const kind = this.kind(event)
if (kind === 'submit') this.send()
else if (kind === 'reset') this.emit('reset')
}
// Enter in a one-line field sends it, as in a native form, unless its submit button is disabled.
private onKey = (event: KeyboardEvent) => {
if (event.key !== 'Enter' || event.isComposing || event.defaultPrevented) return
const target = event.composedPath()[0]
if (!(target instanceof HTMLInputElement) || !TEXT_INPUT.test(target.type)) return
const button = [...this.querySelectorAll<HTMLElement>('*')].find((n) => (n.localName === 'button' || n.localName.includes('-')) && this.typeOf(n) === 'submit')
if (button?.matches(':disabled, [disabled]')) return
event.preventDefault()
this.send()
}
/** Sends it, as a submit button does. */
async send() {
this.emit('submit')
// Focus moves after the next render, once the errors the submit raised are drawn.
await new Promise((resolve) => setTimeout(resolve))
this.firstWrong()?.focus()
}
/** Its fields: the controls and form-associated elements in it that take part in validation. */
get fields(): Validatable[] {
return [...this.querySelectorAll<HTMLElement>('*')].filter((el): el is Validatable => typeof (el as Partial<Validatable>).checkValidity === 'function' && (el as Validatable).willValidate === true)
}
private firstWrong() {
const fields = new Set<HTMLElement>(this.fields)
return [...this.querySelectorAll<HTMLElement>('*')].find((el) => el.matches('[invalid], [aria-invalid="true"]') || (fields.has(el) && !(el as Validatable).validity.valid)) ?? null
}
/** Whether every field is valid (no events, no messages). */
checkValidity() {
return this.fields.every((f) => f.validity.valid)
}
/** Like checkValidity, and the first invalid field shows the browser's message and takes focus. */
reportValidity() {
const bad = this.fields.find((f) => !f.validity.valid)
return bad ? bad.reportValidity() : true
}
render() {
return html`<slot></slot>
${this.failure
? html`<p class="rounded-control bg-surface-danger px-4 py-3 type-ui text-fg-danger" role="alert">${this.failure}</p>`
: nothing}
${this.hasSlot('actions') ? html`<div class="flex flex-wrap items-center justify-end gap-2"><slot name="actions"></slot></div>` : nothing}`
}
}
define('form', Form)/* The host is the form's box (Form.tsx's root <form>), so a class on <spyglass-form> lands on it as on <Form>. */
:host { @apply flex flex-col gap-6; }Reference: Derived from the brand guidelines (no form in the brand assets): Field, Input and Button, the red tints for the failure, one White primary.