Component specification: GhostForm
Important
Status: Approved design (#414). Zac signed off on F1–F5 as proposed at eda553c2c6b6a0a098db1c5aafff8a9893848719 (recorded by zprue743 on PR #487, 2026-11-28). This is a docs-only specification PR; implementation (#420) remains blocked until this revised specification PR merges into master.
Purpose and user problems
GhostField wires accessible label, description, and error relationships (for/id, aria-describedby, aria-invalid, required) for a single control, while leaving validation scheduling, schema execution, error mapping, and focus recovery to each screen. In practice, every form screen ends up hand-rolling the same fragile plumbing seen in examples/field/profile-settings.vue:
- computing per-field validity flags and matching error copy by hand;
- intercepting native
<form novalidate>submitevents and manually querying[aria-invalid="true"]to move focus when validation fails; - parsing raw control strings into domain types (trimmed strings, coerced numbers, normalized emails, structured nested records) outside a typed submission boundary;
- guarding asynchronous schema checks and async submit mutations against duplicate clicks, out-of-order responses, and mid-flight form resets; and
- separating field-scoped errors from form-level cross-field or server failures.
GhostForm and useGhostForm provide a headless, schema-library-agnostic form contract built on the Standard Schema v1 (~standard) interface:
- Consumers keep full ownership of reactive control state (
v-modelonGhostInput,GhostTextarea,GhostSelect,GhostCheckbox,GhostRadioGroup,GhostNumberInput,GhostDatePicker, and future multi-value primitives). - Any Standard Schema v1 validator (Zod 3.24+/4, Valibot 1.0+, ArkType 2.0+, Yup 1.7+, or a plain inline
~standardobject) validates consumer input and delivers typed transformed output (StandardSchemaV1.InferOutput<TSchema>) to the submit handler only when validation succeeds. - Field-path issues automatically associate with matching
<GhostField name="…">instances soinvalid,aria-invalid="true",GhostFieldErrorvisibility, andaria-describedbystay synchronized without per-field boilerplate, while root/form-level issues surface cleanly forGhostInlineAlertor custom summaries. - Standalone
GhostFieldinstances outsideGhostForm—or insideGhostFormwithout anameprop—keep their exact0.1.0prop-driven behavior.
Non-goals
- Schema authoring or bundled validation rules. GhostVue does not ship a schema DSL, built-in regex validators, or localized error catalogs. Validation logic and issue messages come from the consumer's Standard Schema v1 object or programmatic
setFieldErrors/setFormErrorscalls. - Auto-generated form markup from a schema.
GhostFormnever inspects schema internals to synthesize inputs, labels, or layouts. Consumers compose explicitGhostFieldand control components in templates. - Form-owned value cloning or silent input coercion.
GhostFormnever clones or mutates the consumer'svaluesobject and never writes transformed schema output back intovalues. - Field-array state managers (
append,remove,move,swap). Consumers mutate their own reactive arrays directly with standard JavaScript/Vue array methods;GhostFormmaps nested array paths (webhooks.0.url) onto the current array state. - Multi-control group selection or fieldset markup. Multi-checkbox array models belong to
GhostCheckboxGroup(#463) and named<fieldset>/<legend>sections belong toGhostFieldset(#464);GhostFormcomposes with both without owning their selection or group semantics. - Persistence, autosave, multi-step wizard routing, or unsaved-navigation prompts. Those remain application-level concerns built on top of
values,isDirty, and@submit. - Visual chrome in headless
@ghostvue/vue. Spacing, card framing, and action-bar layout stay in consumer markup or@ghostvue/themesprimitives.
Public API
Package boundary and exports
All exports live in @ghostvue/vue (see F5, resolved as @ghostvue/vue-only in 0.2.0):
- Component:
GhostForm - Composable:
useGhostForm - Context key (for
GhostFieldintegration):ghostFormContextKey - Types:
StandardSchemaV1(and namespace membersProps,Result,SuccessResult,FailureResult,Issue,PathSegment,Options,Types,InferInput,InferOutput)GhostFormValidateTriggerGhostFormFieldPathGhostFormProps,GhostFormEmits,GhostFormSlotProps,GhostFormExposedGhostFormSubmitPayload,GhostFormInvalidPayload,GhostFormSubmitResultUseGhostFormOptions,UseGhostFormReturn,GhostFormFieldBindings
- Additive prop and slot extensions on existing
GhostFieldfamily:GhostFieldProps: optionalname?: string | undefinedGhostFielddefault slot: optional scoped slot propsGhostFieldSlotProps({ invalid, error, errors, touched, dirty })GhostFieldErrordefault slot: optional scoped slot propsGhostFieldErrorSlotProps({ message, errors })
No code is added to @ghostvue/core: form context handoff, reactive path tracking, afterNativeFormReset coordination, and post-flush focus management are Vue lifecycle responsibilities (architecture rules).
Standard Schema v1 contract and dependency evaluation
GhostForm consumes the upstream Standard Schema v1 structural protocol:
export interface StandardSchemaV1<Input = unknown, Output = Input> {
readonly '~standard': StandardSchemaV1.Props<Input, Output>
}
export declare namespace StandardSchemaV1 {
export interface Props<Input = unknown, Output = Input> {
readonly version: 1
readonly vendor: string
readonly validate: (
value: unknown,
options?: Options | undefined,
) => Result<Output> | Promise<Result<Output>>
readonly types?: Types<Input, Output> | undefined
}
export interface Options {
readonly libraryOptions?: Record<string, unknown> | undefined
}
export type Result<Output> = SuccessResult<Output> | FailureResult
export interface SuccessResult<Output> {
readonly value: Output
readonly issues?: undefined
}
export interface FailureResult {
readonly issues: ReadonlyArray<Issue>
}
export interface Issue {
readonly message: string
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined
}
export interface PathSegment {
readonly key: PropertyKey
}
export interface Types<Input = unknown, Output = Input> {
readonly input: Input
readonly output: Output
}
export type InferInput<Schema extends StandardSchemaV1> = NonNullable<
Schema['~standard']['types']
>['input']
export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<
Schema['~standard']['types']
>['output']
}Note on TypeScript variance: both Input and Output appear only in covariant readonly positions (types?: { readonly input: Input; readonly output: Output }), while validate accepts unknown. Every concrete StandardSchemaV1<I, O> instance is therefore assignable to StandardSchemaV1 (StandardSchemaV1<unknown, unknown>) under strict: true and exactOptionalPropertyTypes: true with zero any constraints.
Dependency policy evaluation
Evaluated against the repository dependency policy:
| Criterion | Option A (Recommended): Local StandardSchemaV1 type declaration in @ghostvue/vue + dev-only @standard-schema/spec | Option B: @standard-schema/spec (^1.1.0) in @ghostvue/vue production dependencies | Option C (Rejected): @standard-schema/spec as optional peerDependency |
|---|---|---|---|
| Runtime JS / gzip bundle impact | 0 B (pnpm size unchanged for uninvolved components) | 0 B runtime JS (types-only package), but adds a published package manifest edge | 0 B |
Consumer node_modules footprint | Zero additional production packages | Installed for every @ghostvue/vue consumer even when GhostForm is unused | None unless installed |
attw --pack / skipLibCheck: false | Self-contained in dist/index.d.ts; resolves in Node10, Node16, and Bundler modes with nothing external | Resolves because dependencies installs @standard-schema/spec | Fails when consumer omits optional peer and dist/index.d.ts re-exports it |
| Drift protection (TypeScript standard) | Exact dev pin @standard-schema/spec (1.1.0, MIT, 0 transitive deps, no install scripts) checked for bidirectional type equality in packages/vue/type-tests/ | Imported directly from @standard-schema/spec | Imported from peer |
License, audit, allowBuilds | MIT (dev only); pnpm audit --prod unchanged; allowBuilds unchanged | MIT; zero transitive dependencies; allowBuilds unchanged | N/A |
Decision (F1): Adopt Option A. Standard Schema v1 was explicitly designed around structural ~standard compatibility so UI libraries do not force an extra production dependency edge, mirroring @ghostvue/vue/resolver matching unplugin-vue-components structurally (package boundaries). Pinning @standard-schema/spec as an exact devDependency in a compile-time type test guarantees the exported StandardSchemaV1 declaration never drifts from upstream.
Typed consumer example (Standard Schema v1, transformed output, nested paths, form-level issues, and GhostField handoff)
The example below upgrades the examples/field/profile-settings.vue workflow to GhostForm. It works identically with Zod (z.object(...)), Valibot (v.object(...)), ArkType (type(...)), or an inline StandardSchemaV1 validator, and demonstrates:
- Input vs transformed output:
values.seatLimitis edited as astring('25') inGhostInput, while@submitreceivesoutput.seatLimitas anumber(25) and normalizeddisplayName/supportEmailstrings, leavingvaluesuntouched. - Nested object and array paths:
billing.postalCodeandwebhooks.0.urlmap directly to<GhostField name="billing.postalCode">and<GhostField :name="webhooks.${index}.url">. - Form-level issues: cross-field root issues (
path: undefinedor[]) surface onformErrorsand render inGhostInlineAlert. GhostFieldhandoff and standalone opt-out: namedGhostFieldinstances deriveinvalidand<GhostFieldError />copy automatically, while the disabledOrganization IDGhostFieldomitsnameand stays purely prop-driven.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
GhostForm,
type GhostFormSubmitPayload,
type StandardSchemaV1,
} from '@ghostvue/vue'
import {
GhostButton,
GhostCard,
GhostField,
GhostFieldControl,
GhostFieldDescription,
GhostFieldError,
GhostFieldLabel,
GhostInlineAlert,
GhostInput,
} from '@ghostvue/themes'
interface ProfileInput {
displayName: string
supportEmail: string
seatLimit: string
billing: {
postalCode: string
}
webhooks: { url: string }[]
}
interface ProfileOutput {
displayName: string
supportEmail: string
seatLimit: number
billing: {
postalCode: string
}
webhooks: { url: URL }[]
}
/*
* Any Standard Schema v1 validator (Zod, Valibot, ArkType) satisfies this
* interface. Shown inline to make the ~standard input -> output contract explicit.
*/
const profileSchema: StandardSchemaV1<ProfileInput, ProfileOutput> = {
'~standard': {
version: 1,
vendor: 'example',
validate(raw) {
const data = raw as ProfileInput
const issues: StandardSchemaV1.Issue[] = []
const displayName = data.displayName.trim()
if (displayName.length === 0) {
issues.push({
message: 'Enter a display name.',
path: ['displayName'],
})
}
const supportEmail = data.supportEmail.trim().toLowerCase()
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(supportEmail)) {
issues.push({
message: 'Enter an address like team@company.com.',
path: [{ key: 'supportEmail' }],
})
}
const parsedSeats = Number(data.seatLimit.trim())
if (!Number.isInteger(parsedSeats) || parsedSeats < 1) {
issues.push({
message: 'Seat limit must be a whole number of at least 1.',
path: ['seatLimit'],
})
}
const postalCode = data.billing.postalCode.trim()
if (postalCode.length < 3) {
issues.push({
message: 'Enter a valid billing postal code.',
path: ['billing', 'postalCode'],
})
}
const webhooks: { url: URL }[] = []
data.webhooks.forEach((entry, index) => {
try {
webhooks.push({ url: new URL(entry.url.trim()) })
} catch {
issues.push({
message: 'Enter a full https:// webhook URL.',
path: ['webhooks', index, 'url'],
})
}
})
if (parsedSeats > 100 && webhooks.length === 0) {
// Root issue (no path): surfaced in `formErrors`, not attached to a field.
issues.push({
message: 'Plans above 100 seats require at least one audit webhook.',
})
}
if (issues.length > 0) {
return { issues }
}
return {
value: {
displayName,
supportEmail,
seatLimit: parsedSeats,
billing: { postalCode },
webhooks,
},
}
},
},
}
const initialValues = (): ProfileInput => ({
displayName: 'Ada Lovelace',
supportEmail: 'ada@analytical-engines',
seatLimit: '25',
billing: { postalCode: 'EC1A 1BB' },
webhooks: [{ url: 'https://hooks.analytical.engine/audit' }],
})
const values = reactive<ProfileInput>(initialValues())
const billingId = 'org_01J9XK2M8P'
const lastSavedSeats = ref<number | null>(null)
function handleSave({
output,
setFieldErrors,
waitUntil,
}: GhostFormSubmitPayload<ProfileOutput, ProfileInput>): void {
// `output.seatLimit` is inferred as `number`; `output.webhooks[0]?.url` is `URL`.
waitUntil(
Promise.resolve().then(() => {
if (output.supportEmail.endsWith('@blocked.example')) {
setFieldErrors('supportEmail', [
'Use a verified workspace domain for support alerts.',
])
return
}
lastSavedSeats.value = output.seatLimit
}),
)
}
function handleReset(): void {
Object.assign(values, initialValues())
lastSavedSeats.value = null
}
</script>
<template>
<GhostForm
v-slot="{ formErrors, isSubmitting }"
:schema="profileSchema"
:values="values"
@submit="handleSave"
@reset="handleReset"
>
<GhostCard as="section" aria-labelledby="profile-title">
<template #header>
<h2 id="profile-title">Workspace profile</h2>
</template>
<GhostInlineAlert
v-if="formErrors.length > 0"
announce="alert"
tone="danger"
>
<template #title>Unable to save profile</template>
<template #message>
<ul>
<li v-for="(err, idx) in formErrors" :key="idx">{{ err }}</li>
</ul>
</template>
</GhostInlineAlert>
<GhostField name="displayName" required>
<GhostFieldLabel>Display name</GhostFieldLabel>
<GhostFieldControl v-slot="field">
<GhostInput
v-bind="field"
v-model="values.displayName"
name="displayName"
autocomplete="name"
block
/>
</GhostFieldControl>
<GhostFieldError />
</GhostField>
<GhostField name="supportEmail" required>
<GhostFieldLabel>Support email</GhostFieldLabel>
<GhostFieldDescription>
Alerts and billing receipts are sent to this address.
</GhostFieldDescription>
<GhostFieldControl v-slot="field">
<GhostInput
v-bind="field"
v-model="values.supportEmail"
type="email"
name="supportEmail"
autocomplete="email"
block
/>
</GhostFieldControl>
<GhostFieldError />
</GhostField>
<GhostField name="seatLimit" required>
<GhostFieldLabel>Seat limit</GhostFieldLabel>
<GhostFieldControl v-slot="field">
<GhostInput
v-bind="field"
v-model="values.seatLimit"
inputmode="numeric"
name="seatLimit"
block
/>
</GhostFieldControl>
<GhostFieldError />
</GhostField>
<GhostField name="billing.postalCode" required>
<GhostFieldLabel>Billing postal code</GhostFieldLabel>
<GhostFieldControl v-slot="field">
<GhostInput
v-bind="field"
v-model="values.billing.postalCode"
name="billing.postalCode"
autocomplete="postal-code"
block
/>
</GhostFieldControl>
<GhostFieldError />
</GhostField>
<GhostField
v-for="(hook, index) in values.webhooks"
:key="index"
:name="`webhooks.${index}.url`"
required
>
<GhostFieldLabel>Webhook URL {{ index + 1 }}</GhostFieldLabel>
<GhostFieldControl v-slot="field">
<GhostInput
v-bind="field"
v-model="hook.url"
type="url"
:name="`webhooks.${index}.url`"
block
/>
</GhostFieldControl>
<GhostFieldError />
</GhostField>
<!-- No `name` prop: opts out of GhostForm validation and stays prop-driven. -->
<GhostField disabled>
<GhostFieldLabel>Organization ID</GhostFieldLabel>
<GhostFieldControl v-slot="field">
<GhostInput v-bind="field" :model-value="billingId" block />
</GhostFieldControl>
</GhostField>
<template #footer>
<p role="status">
{{ lastSavedSeats !== null ? `Saved ${lastSavedSeats} seats.` : '' }}
</p>
<GhostButton type="reset" variant="ghost" tone="neutral">
Reset
</GhostButton>
<GhostButton type="submit" :loading="isSubmitting">
Save profile
</GhostButton>
</template>
</GhostCard>
</GhostForm>
</template>Props and configuration
GhostForm (<script setup lang="ts" generic="TSchema extends StandardSchemaV1 = StandardSchemaV1, TValues = StandardSchemaV1.InferInput<TSchema>">)
| Prop | Type | Default | Contract |
|---|---|---|---|
schema | TSchema | required | Standard Schema v1 validator (schema['~standard'].version === 1). |
values | TValues | required | Consumer-owned input state passed to schema['~standard'].validate(values, schemaOptions). Read without cloning or mutation. Defaults to StandardSchemaV1.InferInput<TSchema>; pass explicit TValues when draft UI values start wider than input. |
validateOn | GhostFormValidateTrigger | 'submit' | Trigger that first reveals issues on an untouched field before the form has been submitted ('submit' | 'blur' | 'change'). |
revalidateOn | GhostFormValidateTrigger | 'change' | Trigger that re-validates a field once it already has visible issues or after the first failed submit attempt ('submit' | 'blur' | 'change'). |
novalidate | boolean | true | Sets HTML novalidate on <form> so Standard Schema v1 owns submit validation while child required / type attributes keep assistive-technology and virtual-keyboard semantics. Pass :novalidate="false" to run native constraint checks first. |
focusInvalidOnSubmit | boolean | true | When a submit attempt fails validation, moves focus after DOM flush to the first focusable invalid control in rendered DOM order. |
initialIssues | readonly StandardSchemaV1.Issue[] | undefined | undefined | Optional seed issues (for example from an SSR form action) partitioned into fieldErrors and formErrors at setup without running validate(). Captured once at setup; cleared on the next validation or reset(). |
schemaOptions | StandardSchemaV1.Options | undefined | undefined | Optional vendor options forwarded verbatim as the second argument to schema['~standard'].validate(values, schemaOptions). |
Native <form> attributes (id, action, method, enctype, autocomplete, aria-*, data-*, class, style) fall through to the single <form> root element. GhostForm owns novalidate, aria-busy (set to 'true' while isSubmitting is true, unless overridden via explicit aria-busy attr), data-part="root", data-ghost-form="", and data-state.
useGhostForm(options)
type GhostFormValidateTrigger = 'submit' | 'blur' | 'change'
interface UseGhostFormOptions<
TSchema extends StandardSchemaV1 = StandardSchemaV1,
TValues = StandardSchemaV1.InferInput<TSchema>,
> {
schema: MaybeRefOrGetter<TSchema>
values: MaybeRefOrGetter<TValues>
validateOn?: MaybeRefOrGetter<GhostFormValidateTrigger | undefined>
revalidateOn?: MaybeRefOrGetter<GhostFormValidateTrigger | undefined>
novalidate?: MaybeRefOrGetter<boolean | undefined>
focusInvalidOnSubmit?: MaybeRefOrGetter<boolean | undefined>
initialIssues?: readonly StandardSchemaV1.Issue[] | undefined
schemaOptions?: MaybeRefOrGetter<StandardSchemaV1.Options | undefined>
/**
* Provides `ghostFormContextKey` to descendant `GhostField` components when
* called inside `setup()`. Disable when hosting multiple `useGhostForm`
* instances in a single component setup scope without `<GhostForm>` wrappers.
* @default true
*/
provideContext?: boolean
onSubmit?: (
payload: GhostFormSubmitPayload<
StandardSchemaV1.InferOutput<TSchema>,
TValues
>,
) => unknown | Promise<unknown>
onInvalid?: (payload: GhostFormInvalidPayload<TValues>) => void
onReset?: (event: Event | null) => void
}GhostField handoff extensions
GhostField gains one optional prop and two optional scoped-slot surfaces:
| Surface | Addition | Contract |
|---|---|---|
GhostField name prop | name?: string | undefined (default undefined) | Canonical dot-path key (for example 'supportEmail', 'billing.postalCode', 'webhooks.0.url'). Associates the field with an ancestor GhostForm / useGhostForm context when non-empty. |
GhostField invalid prop | invalid?: boolean | undefined (default undefined) | Explicit boolean (true or false) always wins over form state. When omitted (undefined) on a named field inside GhostForm, invalid resolves from form.isFieldInvalid(name); else false. |
GhostField default slot props | { invalid: boolean; error: string | undefined; errors: readonly string[]; touched: boolean; dirty: boolean } | Optional scoped bindings for custom error layouts. Outside GhostForm (or without name), error is undefined, errors is [], and touched / dirty are false. |
GhostFieldError fallback copy | Renders fieldContext.errorMessage when default slot has no renderable content | Consumer default-slot content always takes precedence over schema message text. Scoped slot receives { message: string | undefined; errors: readonly string[] }. |
GhostFieldControl slot props (id, disabled, invalid, required, aria-describedby, aria-invalid) do not inject name into the spread object, because composite triggers such as GhostSelectTrigger render <button type="button" role="combobox"> while the name prop for native FormData belongs on GhostSelect root. Controls that participate in native FormData pass their own name attribute as today.
v-model contracts
GhostForm declares no v-model. Consumers own values as a reactive object, ref, or getter (:values="values"), and individual controls keep their own v-model contracts (GhostInput, GhostCheckbox, GhostSelect, GhostRadioGroup, etc.) via useControllableState. Avoiding a second form-wide v-model:values channel eliminates double-emit loops, deep-clone overhead, and confusion between raw TValues input and transformed TOutput.
Events, callbacks, slots, and exposed methods
Payloads and return types
interface GhostFormSubmitPayload<TOutput, TValues> {
/** Validated and transformed schema output (`StandardSchemaV1.InferOutput<TSchema>`). */
readonly output: TOutput
/** Snapshot reference to the consumer `values` passed into validation. */
readonly values: TValues
/** Originating native `SubmitEvent` when triggered from `<form>`, or `null` for `submit()`. */
readonly event: SubmitEvent | null
/**
* Registers an asynchronous post-validation mutation (for example an API save)
* on `<GhostForm>` `@submit` listeners so `isSubmitting`, `isPending`,
* `aria-busy`, and duplicate-submit protection stay active until `promise`
* settles (or `reset()` cancels the submit epoch). In `useGhostForm`,
* returning a Promise from `options.onSubmit` tracks it automatically.
*/
waitUntil(promise: PromiseLike<unknown>): void
/** Imperative server-error helpers scoped to the active form. */
setFieldErrors(
path: GhostFormFieldPath<TValues> | (string & {}),
messages: readonly string[],
): void
setFormErrors(messages: readonly string[]): void
reset(): void
}
interface GhostFormInvalidPayload<TValues> {
/** All issues returned by the schema for this validation pass, in vendor order. */
readonly issues: readonly StandardSchemaV1.Issue[]
/** Visible field-scoped error messages keyed by canonical dot-path. */
readonly fieldErrors: Readonly<Record<string, readonly string[]>>
/** Visible form-level error messages (empty/missing or symbol path). */
readonly formErrors: readonly string[]
readonly values: TValues
readonly event: SubmitEvent | null
}
type GhostFormSubmitResult<TOutput> =
| { readonly status: 'submitted'; readonly output: TOutput }
| {
readonly status: 'invalid'
readonly issues: readonly StandardSchemaV1.Issue[]
}
| { readonly status: 'aborted' }
| { readonly status: 'ignored' }GhostForm events
| Event | Payload | When emitted |
|---|---|---|
submit | GhostFormSubmitPayload<StandardSchemaV1.InferOutput<TSchema>, TValues> | Schema validation for an accepted submit attempt succeeded with { value } (and was not superseded by reset() while awaiting). |
invalid | GhostFormInvalidPayload<TValues> | Submit attempt failed schema validation (issues non-empty) and was not superseded by a newer validation or reset(). |
reset | event: Event | null | Form reset completed (after afterNativeFormReset for a non-cancelled DOM reset event, or synchronously during imperative reset()). |
GhostForm default scoped slot (GhostFormSlotProps<TSchema, TValues>) and UseGhostFormReturn<TSchema, TValues>
| Member | Type | Contract |
|---|---|---|
fieldErrors | Readonly<Record<string, readonly string[]>> (ComputedRef in composable) | Currently visible error messages keyed by canonical dot-path. |
formErrors | readonly string[] (ComputedRef in composable) | Currently visible root/form-level error messages. |
issues | readonly StandardSchemaV1.Issue[] (ComputedRef in composable) | All currently visible StandardSchemaV1.Issue entries in vendor order. |
isValid | boolean (ComputedRef in composable) | true when issues.length === 0 (no visible field or form errors). |
isInvalid | boolean (ComputedRef in composable) | true when at least one visible field or form error exists. |
isValidating | boolean (ComputedRef in composable) | true while an asynchronous schema['~standard'].validate() promise for the current validation epoch is pending. |
isSubmitting | boolean (ComputedRef in composable) | true from the start of submit() through async validation and any tracked async submit handler (onSubmit return Promise or waitUntil). |
isPending | boolean (ComputedRef in composable) | isValidating || isSubmitting. |
isDirty | boolean (ComputedRef in composable) | true when at least one tracked field path has changed since setup or the last reset(). |
hasSubmitted | boolean (ComputedRef in composable) | true after at least one submit attempt since setup or the last reset(). |
submitCount | number (ComputedRef in composable) | Count of non-ignored submit attempts since setup or the last reset(). |
getFieldError(path) | (path: GhostFormFieldPath<TValues>) => string | undefined | First visible error message for path, or undefined. |
getFieldErrors(path) | (path: GhostFormFieldPath<TValues>) => readonly string[] | All visible error messages for path ([] when valid or unrevealed). |
getFieldIssues(path) | (path: GhostFormFieldPath<TValues>) => readonly StandardSchemaV1.Issue[] | Visible StandardSchemaV1.Issue objects mapped to path. |
isFieldInvalid(path) | (path: GhostFormFieldPath<TValues>) => boolean | getFieldErrors(path).length > 0. |
isFieldTouched(path) | (path: GhostFormFieldPath<TValues>) => boolean | true once path has blurred or been marked via touchField(path). |
isFieldDirty(path) | (path: GhostFormFieldPath<TValues>) => boolean | true once the value at path changed after setup or reset(). |
fieldProps(path) | (path: GhostFormFieldPath<TValues>) => GhostFormFieldBindings | Escape hatch for <GhostField v-bind="form.fieldProps('email')"> or custom wrappers without context injection ({ name, invalid }). |
validate() | () => Promise<{ valid: boolean; output?: Output; issues: readonly Issue[] }> | Runs full-form validation immediately, reveals all paths and form errors, and resolves with the outcome (without running onSubmit). |
validateField(path) | (path: GhostFormFieldPath<TValues>) => Promise<readonly StandardSchemaV1.Issue[]> | Marks path revealed, runs schema validation, updates only revealed paths, and resolves with path's resulting issues. |
submit(event?) | (event?: SubmitEvent | null) => Promise<GhostFormSubmitResult<Output>> | Runs full-form validation and, when valid, invokes onSubmit / emits submit. |
reset() | () => void | Synchronously aborts in-flight epochs, clears errors/touched/dirty/hasSubmitted/submitCount, and emits reset / invokes onReset(null). |
clearErrors(path?) | (path?: GhostFormFieldPath<TValues>) => void | Clears visible errors for path, or all field and form errors (and bumps validationEpoch when clearing all). |
setFieldErrors(path, msgs) | (path: GhostFormFieldPath<TValues> | (string & {}), messages: readonly string[]) => void | Sets explicit field error messages (for example from a 422 API response) and marks path revealed. Empty messages clears path. |
setFormErrors(messages) | (messages: readonly string[]) => void | Sets explicit form-level error messages (for example from a 409/500 API response). Empty array clears formErrors. |
touchField(path) | (path: GhostFormFieldPath<TValues>) => void | Marks path touched without running validation. |
blurField(path) | (path: GhostFormFieldPath<TValues>) => void | Marks path touched and schedules validation when validateOn === 'blur' or (revalidateOn === 'blur' and path is revealed/submitted). |
UseGhostFormReturn additionally exposes:
formRef:(el: Element | ComponentPublicInstance | null) => void(bound automatically viaformProps.refwhen spread on<form v-bind="form.formProps">)formProps:ComputedRef<GhostFormRootAttributes>containingref,novalidate,aria-busy,data-part="root",data-ghost-form="",data-state,onSubmit, andonResetfor standalone<form>elements.
GhostForm exposed template ref (GhostFormExposed<TSchema, TValues>)
element: HTMLFormElement | null(nullbefore mount and after unmount)submit,validate,validateField,reset,clearErrors,setFieldErrors,setFormErrors(same signatures as above)
State model
Validation triggers and progressive issue visibility
Standard Schema v1 exposes a single root validate(value) function rather than per-field sub-schemas, because real forms frequently enforce cross-field refinements (confirmPassword === password, endDate >= startDate). Every validation pass therefore calls schema['~standard'].validate(toValue(values), toValue(schemaOptions)) once and filters which issues become visible using two tracking sets:
hasSubmitted: boolean— startsfalse; becomestrueas soon as a non-ignoredsubmit()orvalidate()runs; resets tofalseonreset().revealedPaths: Set<string>— paths unlocked for error display before the first submit attempt (validateField(path),setFieldErrors(path, ...), or a field trigger matchingvalidateOn).
Trigger event on field P | Before first submit (hasSubmitted === false) | After first submit (hasSubmitted === true) |
|---|---|---|
Value at P changes | Marks P dirty. Runs validation if validateOn === 'change' (adds P to revealedPaths) or if P is already in revealedPaths and revalidateOn === 'change'. | Marks P dirty. Runs validation if revalidateOn === 'change', updating all field errors and formErrors together. |
Field P blurs | Marks P touched. Runs validation if validateOn === 'blur' (adds P to revealedPaths) or if P is already in revealedPaths and revalidateOn === 'blur'. | Marks P touched. Runs validation if revalidateOn === 'blur', updating all field errors and formErrors together. |
Form submit | Sets hasSubmitted = true, increments submitCount, runs validation, and reveals every field issue and every formErrors entry. | Increments submitCount, runs validation, and updates every field issue and formErrors entry. |
With the defaults (validateOn: 'submit', revalidateOn: 'change'):
- Typing or tabbing through a fresh form shows no premature errors ("punish late").
- Submitting an invalid form reveals all field and form-level issues at once and focuses the first invalid control.
- Fixing an invalid field clears its error on the very next edit ("reward early") without requiring another submit click, and cross-field refinements recompute across sibling fields simultaneously.
Blur detection across composite and portaled controls
Inside <GhostField name="P">, GhostField listens for focusout on its root div.ghost-field:
- If
event.relatedTargetis aNodestill contained insidefieldRoot(for example arrowing between radios insideGhostRadioGroupor moving between parts ofGhostDatePicker), focus has not left the field;blurField(P)does not fire. - If
event.relatedTargetis inside a portaled overlay controlled by an element insidefieldRoot—detected by matching any[aria-controls]id insidefieldRootto an ancestor ofrelatedTarget(such as openingGhostSelectContentorGhostComboboxContentteleported todocument.body)—focus has moved into the field's own popup rather than leaving the field;blurField(P)is deferred until focus leaves both the popup andfieldRootwithout returning to the trigger. - When focus genuinely leaves the field and its controlled popup,
blurField(P)runs.
Loading, empty, disabled, read-only, and error states
GhostForm sets a single data-state hook on <form class="ghost-form" data-part="root"> with deterministic precedence:
submitting—isSubmittingistruevalidating—isValidatingistrueandisSubmittingisfalseinvalid—isInvalidistrueand neither pending flag is active- omitted — idle with no visible errors
- Never auto-disable controls while pending.
GhostFormdoes not propagatedisabled="true"toGhostFieldor form controls duringisValidatingorisSubmitting. Setting nativedisabledon a focused<input>or<button>causes browsers to dropdocument.activeElementto<body>, destroying keyboard position during async blur/change checks and preventing screen readers from reading the active control. Consumers bind:loading="isSubmitting"on their submitGhostButtonor explicitly disable sections when their UX intentionally locks editing (and manage focus accordingly). - Disabled and read-only fields. Standard Schema v1 validates the
valuesobject, not DOMFormData. A disabled or read-onlyGhostFieldwithout anameprop (such asOrganization IDinprofile-settings.vue) never displays schema errors. If a namedGhostFieldhasdisabled: true, it still reflects schema state unless explicit:invalid="false"overrides it, but focus-on-invalid-submit skips disabled controls because they are not tabbable.
Async behavior
Synchronous fast-path
Standard Schema v1 allows validate() to return either Result<Output> or Promise<Result<Output>>. GhostForm inspects the return value with a thenable check (result !== null && (typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function'):
- Synchronous
Result: processed immediately in the same synchronous turn.isValidatingnever flips totrue, avoiding a one-microtask flash ofdata-state="validating"on synchronous Zod, Valibot, or ArkType schemas. - Promise / thenable
Result: setsisValidating = trueuntil that validation epoch settles, is superseded by a newer validation epoch, or is cancelled byreset()/ unmount.
Duplicate submit protection
- Native
<form>submitevents callevent.preventDefault()synchronously on every press whennovalidateis active (and wheneverGhostFormhandles the event) so a double-press ofEnteror double-click on<GhostButton type="submit">never triggers a browser page reload. - While
isSubmitting === true: any subsequentsubmit()call or nativesubmitevent is ignored (submitCountdoes not increment, neitherschema['~standard'].validate()noronSubmitruns a second time, andsubmit()resolves to{ status: 'ignored' }). - While
isValidating === trueandisSubmitting === false(a backgroundblurorchangevalidation is in flight):submit()supersedes the background validation! It advancesvalidationEpoch(invalidating the in-flight background Promise), setsisSubmitting = true, and runs a fresh authoritative full-form validation on the latestvalues. A slow backgroundblurcheck therefore never blocks or drops a real user submit.
Out-of-order asynchronous results (monotonic epochs)
useGhostForm maintains two internal monotonic integers: validationEpoch and submitEpoch.
- Starting any validation (
validate,validateField, background trigger, orsubmit) incrementsvalidationEpoch(const runId = ++validationEpoch). Onlysubmit()acquiressubmitEpoch(const currentSubmitId = ++submitEpoch) and setsisSubmitting = true; backgroundchange/blurtriggers and imperativevalidate()/validateField()calls never ownsubmitEpoch. - When an async
validate()Promise settles:- If
runId !== validationEpoch, the outcome is stale and discarded immediately: it must not writefieldErrors,formErrors, orissues, must not changeisValidating(which now belongs to the newervalidationEpoch), must not focus an element, and must not emitsubmitorinvalid. A supersededsubmit()call resolves to{ status: 'aborted' }(and clearsisSubmittingonly ifcurrentSubmitId === submitEpoch). - Only when
runId === validationEpochdoes the outcome commit errors or proceed toonSubmit, and clearisValidating = false.
- If
- Accepted
submit()calls keepcurrentSubmitId === submitEpochactive whileonSubmit/waitUntilawaits an async mutation:- Background
change/blurvalidations (orvalidate()/validateField()) may advancevalidationEpochwithout clearingisSubmitting. isSubmittingclears tofalseonly whencurrentSubmitId === submitEpochfinishes (its validation fails/aborts/throws, or itsonSubmit/waitUntilsettles—resolves or rejects) or whenreset()/ unmount advancessubmitEpoch.
- Background
- Unexpected validator exceptions: compliant Standard Schema v1 validators return
{ issues }rather than throwing.- If
validate()throws synchronously or rejects for the active validation epoch (runId === validationEpoch):isValidatingresets tofalseso validation never wedges.isSubmittingresets tofalseonly when that validation belongs to the active pending submit (currentSubmitId === submitEpoch). Failures from backgroundchange/blurvalidations (orvalidate()/validateField()) must preserveisSubmittingso an active asynconSubmit/waitUntilmutation retains itssubmitEpochduplicate-submit lock until that save settles orreset()/ unmount advancessubmitEpoch.- When a submit validation throws/rejects,
onSubmitis not called and imperativesubmit()rejects with the thrown error (for native DOM@submitdispatch, forwarded to Vue'shandleError/onErrorCapturedchain after resetting pending flags). Active background/imperative validation failures likewise rejectvalidate()/validateField()or forward DOM-triggered errors to Vue'shandleError/onErrorCapturedchain without disturbingisSubmitting.
- Stale validation epoch rejections (
runId !== validationEpoch) are swallowed silently so a cancelled check cannot surface an unhandled rejection (if a supersededsubmit()'s ownvalidate()rejects aftervalidationEpochmoved, it resolves to{ status: 'aborted' }and clearsisSubmittingonly ifcurrentSubmitId === submitEpoch).
- If
Reset during validation and native form events
GhostForm coordinates imperative resets and native <form> reset events with packages/vue/src/form-reset.ts using a shared active-hold suppression set (activeResetHolds: Set<symbol>, where isResetting is activeResetHolds.size > 0):
- Shared suppression holds (
acquireResetSuppression/releaseResetSuppression):- Each reset acquires its own unique hold token (
const hold = Symbol(), added toactiveResetHolds) and deletes only its own token when that reset's flush/settlement completes. - Because holds are tracked additively rather than by overwriting a single
resetSuppressionEpoch, an imperativeform.reset()called during or after a native reset batch never invalidates or short-circuits the native reset's hold:isResettingstaystrueuntil every active hold releases.
- Each reset acquires its own unique hold token (
- Imperative
form.reset():- Synchronously increments
validationEpochandsubmitEpoch(immediately invalidating any in-flightvalidate()oronSubmit/waitUntilPromise), setsisValidating = falseandisSubmitting = false, and clearsfieldErrors,formErrors,issues,touchedPaths,dirtyPaths,revealedPaths,hasSubmitted(false), andsubmitCount(0). - Acquires an imperative hold (
const imperativeHold = acquireResetSuppression()), invokesonReset?.(null)/ emitsreset(null), and schedulesnextTick(() => releaseResetSuppression(imperativeHold))so consumer baseline writes insideonReset/@resetdo not triggervalidateOn: 'change'or mark fields dirty—without disturbing any still-pending native-reset hold inactiveResetHolds.
- Synchronously increments
- Native
<form>resetevent (clicking<GhostButton type="reset">or callingformElement.reset()):GhostFormdoes not callevent.preventDefault(), preserving native reset delivery to uncontrolled child controls (GhostInput,GhostCheckbox,GhostSelect,GhostRadioGroup) that listen withuseNativeFormReset.- Because
GhostFormlistens directly on<form>(target phase) while child controls listen ondocument(bubble phase) viauseNativeFormReset,GhostForm'safterNativeFormResetmacrotask runs before child controls'afterNativeFormResetmacrotasks. HoldingisResettingacross a singlenextTick()insideGhostForm's macrotask would therefore expire before later child macrotasks execute and emitupdate:modelValueto restore seeds on controlled controls whose current value differs from their reset seed. - To prevent premature expiry,
packages/vue/src/form-reset.tsmaintains aWeakMap<Event, ...>batch tracker across allafterNativeFormResetcallbacks scheduled for the sameresetEvent(decrementing in afinallyblock as each macrotask callback completes—or when cancelled on unmount—and notifying settlement hooks once the pending count foreventreaches0, or immediately when none remain) viaafterNativeFormResetSettled(event, onSettled)/whenNativeFormResetSettled(event). GhostFormschedules its reset reconciliation withafterNativeFormReset(event, apply):- If any listener on the form,
document, orwindowcallsevent.preventDefault()during dispatch,afterNativeFormResetskipsapply: errors, pending state, andsubmitCountremain intact and no hold is acquired. - Otherwise,
applysynchronously acquires a native hold (const nativeHold = acquireResetSuppression()), registers settlement release viaafterNativeFormResetSettled(event, () => void nextTick(() => releaseResetSuppression(nativeHold))), bumpsvalidationEpochandsubmitEpoch, clears pending flags, errors, and tracking sets, and invokesonReset?.(event)/ emitsreset(event). - If a consumer calls imperative
form.reset()from insideonReset(event)/@reset(or beforeeventsettles),imperativeHoldreleases at the microtasknextTick()ofGhostForm's macrotask whilenativeHoldremains inactiveResetHoldsuntil both every childafterNativeFormResetmacrotask registered foreventhas finished (or been cancelled on unmount) and the subsequentnextTick()reactive flush completes. Reactive path watchers triggered by consumer@resetwrites and childupdate:modelValueseed restorations thus flush entirely whileisResettingistruewithout marking fields dirty or triggeringvalidateOn: 'change'.
- If any listener on the form,
- Pending
afterNativeFormResettimers and settlement listeners are cancelled,activeResetHolds.clear()runs soisResettingclears immediately, and anisUnmounted/unmountEpochguard prevents late callbacks from mutating state inonBeforeUnmount.
Consumer data
Ownership and immutability
valuesis consumer-owned (reactive(...),ref(...), or a getter).GhostFormpassestoValue(values)directly toschema['~standard'].validatewithout cloning, freezing, or mutating any property or nested array.- Transformed
TOutput(result.value) is forwarded exclusively tosubmit/onSubmitand the resolvedsubmit()/validate()result. Consumer-ownedvaluesretains its input representation so bound controls never lose formatting (for example trailing decimals or whitespace while editing) or receive incompatible types (numberorURLpushed into astringGhostInput). - Issue arrays from
result.issuesare copied into immutable surface records without mutating vendorIssueobjects.
Nested path normalization and issue partitioning
Each StandardSchemaV1.Issue has path?: ReadonlyArray<PropertyKey | PathSegment> | undefined, where PathSegment is { readonly key: PropertyKey }:
- Empty or missing path (
issue.path === undefined || issue.path.length === 0): classified as a form-level issue (formIssues/formErrors). Never assigned tofieldErrors['']. - Segment unwrapping: each entry
segmentinissue.pathunwraps tokey = typeof segment === 'object' && segment !== null && 'key' in segment ? segment.key : segment. - Symbol segments: if any unwrapped
keyhastypeof key === 'symbol', the path cannot match a string templatenameprop. Rather than throwingTypeErroronString(symbol)or synthesizing'Symbol(...)', the issue is classified intoformIssues/formErrorswith its originalissue.pathpreserved onissues. - Canonical dot-path string (
string | numbersegments): remaining keys convert viaString(key)and join with.:['supportEmail']or[{ key: 'supportEmail' }]→'supportEmail'['billing', 'postalCode']→'billing.postalCode'['webhooks', 0, 'url']or[{ key: 'webhooks' }, { key: 0 }, { key: 'url' }]→'webhooks.0.url'
- Multiple issues on the same path: preserved in vendor emission order in
fieldErrors[path](readonly string[]).getFieldError(path)and default<GhostFieldError />renderfieldErrors[path][0]; consumers who display every rule violation iterategetFieldErrors(path)or<GhostFieldError v-slot="{ errors }">. - Unmatched dot-paths (conditional or unmounted fields, or object-group paths): an issue with a non-empty string/number path such as
'billing'or an unmounted step field'shipping.city'stays infieldErrors['billing']/fieldErrors['shipping.city'](when revealed) so programmatic readers, error summaries iteratingissues, and futureGhostFieldseterror wiring can read it by path without pollutingformErrorswhenever a conditional field togglesv-if. - Literal dots in object keys:
0.2.0treats.as the path separator and does not define an escape syntax for property names containing literal.characters (documented limitation; see F4).
Compile-time path helper (GhostFormFieldPath<TValues>)
GhostFormFieldPath<TValues> computes valid dot-paths up to a bounded recursion depth of 4 levels so autocomplete and typo detection work on nested objects and arrays without triggering TypeScript recursion limits (TypeScript standard):
- Plain object keys
K extends string:'K'and, for nested objects/arrays,`${K}.${GhostFormFieldPath<TValues[K]>}`. - Array /
ReadonlyArray<E>properties:`${K}` | `${K}.${number}`and, whenEis an object,`${K}.${number}.${GhostFormFieldPath<E>}`. - Terminal leaf types (
Date,URL,RegExp,File,Blob, functions, primitives,Map,Set) do not recurse into prototype methods. - When
TValuesisunknownor an index-signature record (Record<string, unknown>),GhostFormFieldPath<TValues>widens tostring.
Accessibility contract
Semantics and relationships
- Root:
GhostFormrenders a native<form>element. Native<form>exposes theformlandmark role only when given an accessible name (aria-labeloraria-labelledbyfallthrough), matching HTML ARIA rules;GhostFormnever invents aroleattribute. - Field naming, descriptions, and errors: delegated to
GhostField:GhostFieldLabelnames the control viafor/id(or implicit wrapping).GhostFieldDescriptionattaches persistent hint copy viaaria-describedby.- When
GhostFormmarks<GhostField name="P">invalid,GhostFieldsetsdata-state="invalid",GhostFieldControlpassesinvalid: trueandaria-invalid="true"to the control, and<GhostFieldError />unhides withrole="alert"and registers itserrorIdintoaria-describedbyafterdescriptionId(aria-describedby="desc-id error-id") so hints are never overwritten when an error appears. - When
P's error clears,aria-invalidis omitted (neveraria-invalid="false"),<GhostFieldError />returns tohiddenwithoutrole="alert", anderrorIdis removed fromaria-describedbywhile keepingdescriptionIdintact.
- Form-level issues (
formErrors):GhostFormstays markup-less inside its default slot so consumers control placement. Consumers presentformErrorswith<GhostInlineAlert v-if="formErrors.length > 0" announce="alert" tone="danger">above the fields or near the submit bar. - Pending submission: while
isSubmittingistrue,<form>setsaria-busy="true"(omitted whenfalse). Backgroundblur/changevalidations (isValidating && !isSubmitting) do not setaria-busyon<form>so screen readers do not suppress or chatter across unrelated fields during typing.
Keyboard interaction
GhostForm intercepts no keyboard events directly; all keyboard behavior flows through native HTML form rules and child controls:
| Key / Interaction | Where | Behavior |
|---|---|---|
Tab / Shift+Tab | Form controls and actions | Native sequential focus order across enabled controls; focusout on leaving a GhostField triggers blur validation when validateOn / revalidateOn is 'blur'. |
Enter | Native text-like <input> (GhostInput, GhostNumberInput) | Triggers native form submit per HTML implicit-submission rules, intercepted by GhostForm (preventDefault()) to run Standard Schema v1 validation. |
Enter | <textarea> (GhostTextarea) | Inserts a newline; does not submit the form. |
Enter / Space | Open composite popups (GhostSelect, GhostCombobox, GhostDatePicker) | Handled by the open widget (preventDefault() selects option/date and closes popup); must not submit the ancestor GhostForm. |
Enter / Space | <GhostButton type="submit"> | Activates native submit button, firing <form> submit → GhostForm validation. |
Enter / Space | <GhostButton type="reset"> | Activates native reset button, firing <form> reset → child useNativeFormReset + GhostForm afterNativeFormReset reconciliation. |
Focus behavior
When focusInvalidOnSubmit is true (default) and a submit validation fails (issues non-empty on an active epoch):
- Wait one
nextTickso Vue flushesaria-invalid="true"and visible<GhostFieldError />nodes into the DOM before moving focus. - Bail out without moving focus if:
- the form element unmounted or is disconnected;
validationEpochorsubmitEpochadvanced in the meantime (superseded or reset); ordocument.activeElementcurrently sits inside an active modal focus trap (useFocusScopewithtrapped: true) outside the<form>element (for example a modal dialog opened while an async submit check was in flight), soGhostFormnever yanks focus against an upper modal trap.
- Resolve the first focusable invalid control in rendered DOM order inside the
<form>element (never registration order, so conditionalv-ifinsertions or responsive/keyed field reorders focus the visually first invalid control):- Walk elements matching
[aria-invalid="true"]inside<form>in document order. - If a candidate element is itself tabbable/focusable and enabled (
GhostInput,GhostTextarea,GhostCheckbox,GhostSelectTrigger,GhostComboboxInput,GhostNumberInput,GhostDatePickerInput), call.focus()on it and stop. - If the candidate is a non-focusable group host carrying
aria-invalid="true"(for exampleGhostRadioGroup's<fieldset aria-invalid="true">), querygetTabbableElements(candidate)[0](which selects the checked enabled radio if any, else the first enabled radio perfocus.md) and focus that item.
- Walk elements matching
- If validation failed solely due to
formErrors(zero invalid field controls), focus remains on the submit trigger so keyboard context is preserved while the form-levelrole="alert"region announces the error. - Background
blurandchangevalidations never move focus.
Assistive technology expectations
- On invalid submit, moving focus to the first invalid control after
nextTickcauses NVDA, JAWS, and VoiceOver to announce the control's label, role,"invalid entry"(aria-invalid="true"), description, and the newly linked error copy (aria-describedby) on the focused control instead of reading every field error simultaneously. - Remaining invalid fields expose
aria-invalid="true"and their ownaria-describedbyerror message as the user tabs forward to repair each field. - Standalone
GhostFieldoutsideGhostFormkeeps its exact existing AT announcements (GhostFieldErrorrole="alert"when consumer slot content is present, hidden when empty).
Rendering and customization
GhostForm is a single-element headless primitive (<form>). It introduces no wrapper <div>s, no internal error-summary markup, and no action-bar chrome:
- Simple configuration:
<GhostForm :schema="schema" :values="values" @submit="save">with<GhostField name="...">and<GhostFieldError />children. - Custom error copy / multiple messages per field: scoped slots on
GhostFieldError(v-slot="{ message, errors }") orGhostField(v-slot="{ invalid, errors, touched, dirty }"), or explicit:invalidonGhostFieldto override schema state. - Form-level banners and pending controls: default scoped slot on
GhostForm(v-slot="{ formErrors, isSubmitting, isValid, isDirty }"), composed withGhostInlineAlertandGhostButton. - Lower-level composable:
useGhostForm+<form v-bind="form.formProps">for custom form hosts or non-GhostFieldcontrols usingform.getFieldErrorandform.isFieldInvalid.
Stable styling hooks (ADR 0004):
- Root
<form>: classghost-form,data-part="root",data-ghost-form="",data-state="submitting" | "validating" | "invalid"(omitted when idle and valid). - Consumer
classandstylemerge onto<form>and are never overwritten.
Environment behavior
SSR and hydration
- Deterministic initial markup: neither
GhostFormnoruseGhostFormrunsschema['~standard'].validate()duringsetup()orrenderToString. Server HTML renders<form class="ghost-form" data-part="root" data-ghost-form="" novalidate>withisValidating === false,isSubmitting === false, and noaria-busyordata-stateunlessinitialIssuesis provided. - No browser globals in setup:
document,window,HTMLElement, andfocus()are never read duringsetup()or SSR render.GhostFormExposed.elementisnulluntil mount. - Hydrating server-seeded
initialIssues: wheninitialIssuesis passed (for example from a Nuxt server route or progressive-enhancement POST), setup partitions those issues synchronously and marks all seeded paths revealed plushasSubmitted = true:GhostFieldrendersdata-state="invalid"andGhostFieldControlrendersaria-invalid="true"in both SSR HTML and the initial client hydration pass.<GhostFieldError />renders the seeded error text withrole="alert"and withouthiddenin both SSR HTML and the initial client render.- Matching
GhostField's established hydration contract verified intests/integration/ghost-field-error-ssr.test.ts,aria-describedbyomitserrorIdduring SSR and the first client hydration render (regardless of whether<GhostFieldError />sits before or after<GhostFieldControl>), thenuseGhostFieldPartContentattacheserrorIdtoaria-describedbyinonMounted→nextTickwith zero hydration mismatch warnings and identicaluseGhostIdelement ids.
Mobile and touch
- Setting
novalidateon<form>suppresses inconsistent mobile browser validation bubbles while preserving nativetype="email",type="url",type="tel",inputmode, andautocompletevirtual-keyboard hints on child inputs. - Focusing the first invalid control on submit scrolls that control into the mobile viewport via native
.focus()behavior. Touch target sizing stays with the child controls (GhostInput,GhostSelect,GhostButton).
Performance
- No deep cloning or full-tree
JSON.stringify:valuesis passed by reference toschema['~standard'].validate. - Targeted path tracking: dirty/change detection evaluates one lightweight path getter (
readPathValue(toValue(values), segments)) per registered fieldname(O(registered fields × path depth)), rather than a{ deep: true }watcher over arbitrary nested objects or large arrays outside form fields. Forms withvalidateOn === 'submit'andrevalidateOn === 'submit'still track dirty state per registered path inO(registered fields)per mutated field and runvalidate()only on submit. - Zero global listeners:
GhostFormbindssubmitandresetdirectly on its own<form>element (formProps.onSubmit/formProps.onReset) rather than addingdocument-level listeners. PendingafterNativeFormResetmacrotasks and epoch state clean up deterministically inonBeforeUnmount. - Bundle tree-shaking: when Option A (F1) is used,
StandardSchemaV1compiles away completely (0 Bruntime overhead whenGhostFormis not imported, and a compact state/epoch composable when it is).
Composition
Reused @ghostvue/vue primitives and conventions:
GhostField,GhostFieldLabel,GhostFieldDescription,GhostFieldError,GhostFieldControl,ghostFieldContextKey, anduseGhostFieldPartContent— existing label, hint,role="alert", andaria-describedbymachinery, extended with optionalghostFormContextKeyinjection whennameis set.afterNativeFormResetand per-Eventbatch settlement (packages/vue/src/form-reset.ts) — macrotask reset reconciliation after fullresetevent dispatch soevent.defaultPreventedis honored identically toGhostInput,GhostCheckbox,GhostSelect, andGhostRadioGroup, andGhostForm's sharedactiveResetHoldskeepsisResettingactive across overlapping imperative/native resets until all descendantuseNativeFormResetmacrotasks for the sameEventand their reactive flushes complete.getTabbableElements(packages/vue/src/get-tabbable-elements.ts) — resolves the first enabled tabbable target inside composite/group controls such asGhostRadioGroupwhen focusing the first invalid field on submit.GhostInlineAlertandGhostButton— composed by consumers in slots for form-level alerts and:loading="isSubmitting"submit buttons without couplingGhostFormto@ghostvue/themes.
Behavior of GhostField outside GhostForm
GhostField reads inject(ghostFormContextKey, null):
- When used outside
GhostForm(for example in DataTable filter toolbars, dialogs withoutGhostForm, or standaloneexamples/field/profile-settings.vue):- No warning or error is emitted.
GhostFieldperforms no registration, attaches nofocusoutlistener, and creates no path watchers.invalid,disabled, andrequireddefault tofalseand follow the component's props exclusively.<GhostFieldError />renders only consumer-supplied slot content and stayshiddenwithoutrole="alert"when empty.
- When used inside
GhostFormwithout anameprop (or withname=""):- Identical to standalone
GhostField: opts out of schema error lookup, blur/dirty tracking, and registration.
- Identical to standalone
- When used inside
GhostFormwithname="supportEmail"and an explicit:invalid="customBoolean"prop:- Explicit
:invalid="true"or:invalid="false"overridesGhostForm's computedisFieldInvalid('supportEmail'), preserving local escape hatches.
- Explicit
Test plan
Framework-neutral / unit tests (packages/vue/src/use-ghost-form.test.ts)
- Input vs transformed output: schema trims
' Ada '→'Ada'and transformsseatLimit: '25'→25; validsubmit()resolves to{ status: 'submitted', output: { displayName: 'Ada', seatLimit: 25 } }, invokesonSubmitonce with the transformedoutput, and leavesvalues.seatLimit === '25'andvalues.displayName === ' Ada 'unmutated. - Invalid submission & issue partitioning: schema returning
{ issues: [{ message: 'Required', path: ['displayName'] }, { message: 'Bad ZIP', path: [{ key: 'billing' }, { key: 'postalCode' }] }, { message: 'Bad URL', path: ['webhooks', 0, 'url'] }, { message: 'Root conflict' }, { message: 'Empty path', path: [] }, { message: 'Symbol key', path: [Symbol('internal')] }] }maps dot-paths'displayName','billing.postalCode', and'webhooks.0.url'intofieldErrors, routes missing/[]/symbolpaths intoformErrorsin order, setsisInvalid === true, does not invokeonSubmit, and invokesonInvalidonce. - Multiple issues on one path: preserves all messages in
getFieldErrors(path)and returnsmessages[0]fromgetFieldError(path). - Validation triggers (
validateOn/revalidateOn):- Default (
submit/change): editing and blurring before submit keepfieldErrorsempty; failedsubmit()reveals all errors; editing one invalid field immediately clears its error while keeping sibling errors; editing a field involved in a cross-field refinement after submit updates both fields andformErrors. validateOn: 'blur': blurring'supportEmail'reveals only'supportEmail''s issue while untouched invalid'displayName'remains hidden until blurred or submitted.validateOn: 'change': editing'supportEmail'reveals only'supportEmail''s issue without revealing untouched fields.
- Default (
- Synchronous fast-path: synchronous
validate()never setsisValidating === trueacross microtasks. - Duplicate submit: while
isSubmittingistrue(either inside asyncvalidate()or inside asynconSubmit/waitUntil), a secondsubmit()resolves to{ status: 'ignored' }, does not incrementsubmitCount, and callsvalidate()andonSubmitonly once total. Conversely, while only a backgroundblurvalidation is pending (isValidating === true,isSubmitting === false),submit()supersedes the background run and completes submission. - Concrete async race 1 — out-of-order validations: trigger validation A (deferred Promise
d1) with invalid input, then trigger validation B (deferred Promised2) with valid input; resolved2first (assertisValidating === false,fieldErrorsempty), then resolved1with{ issues: [{ message: 'Stale error', path: ['email'] }] }; assertd1's stale result does not write'Stale error', flipisValidating, or emitinvalid. Also verify the reverse race (two overlappingsubmit()/validate()calls whered1would have succeeded with staleoutputafter a newer invalid state). - Concrete async race 2 — reset during pending validation and pending submit: start async
submit()(pendingd1), callform.reset()whileisValidatingistrue(assertisValidating === false,isSubmitting === false,hasSubmitted === false,submitCount === 0synchronously), then resolved1with{ issues }(and in a second case with{ value }); assertfieldErrorsstays{},formErrorsstays[],isValidatingstaysfalse, andonSubmitis never called. Repeat withreset()called after validation succeeded while asynconSubmit(d2) is in flight. - Validator rejection recovery & submit-lock preservation:
- When an active async
submit()validation rejects withnew Error('RPC timeout'),isValidatingandisSubmittingreturn tofalseandonSubmitdoes not run. - Regression — deferred save + rejecting background validation + second submit: start an async
submit()whose validation passes and whoseonSubmit/waitUntilawaits a deferred save PromisedSave(isSubmitting === true); whiledSaveis pending, trigger a backgroundchange(orblur) validation whosevalidate()rejects withnew Error('Background check failed'); assertisValidatingresets tofalse,isSubmittingstaystrue, a secondsubmit()attempt resolves to{ status: 'ignored' }without incrementingsubmitCountor starting a secondonSubmitcall, andisSubmittingclears tofalseonly whendSavesettles (orreset()runs).
- When an active async
Vue component and SSR tests (packages/vue/src/GhostForm.test.ts, tests/integration/ghost-form-ssr.test.ts)
GhostFieldhandoff & cleanup:<GhostField name="supportEmail">inside<GhostForm>receivesdata-state="invalid", setsaria-invalid="true"onGhostInput, unhides<GhostFieldError />with the schema message androle="alert", and linkserrorIdinaria-describedbyalongsideGhostFieldDescription'sdescriptionId; fixing the value removesaria-invalid, hides<GhostFieldError />, and keepsdescriptionIdinaria-describedby.- Standalone & opt-out
GhostField:<GhostField>rendered outside<GhostForm>,<GhostField>withoutnameinside<GhostForm>, and<GhostField name="supportEmail" :invalid="false">inside<GhostForm>preserve prop-driven validity without errors or console warnings. - Native
<form>resetcooperation (uncontrolled & controlled):- Clicking
<button type="reset">restores uncontrolledGhostInputdefaultValueand, afterawait waitForFormResetDeferral(), clearsGhostFormerrors without re-triggeringvalidateOn: 'change'; a listener callingevent.preventDefault()onresetcancels both control andGhostFormreset. - Regression — controlled
GhostInputwhose value differs from reset seed: mount<GhostForm validate-on="change">with a controlled<GhostInput v-model="values.displayName" default-value="Ada" />, changevalues.displayNameto'Bob'(differing from the'Ada'seed, marking'displayName'dirty), trigger a native<form>reset(via<button type="reset">orformElement.reset()), andawait waitForFormResetDeferral()+await nextTick(); assertvalues.displayNamerestores to'Ada',isDirty === false,isFieldDirty('displayName') === false,fieldErrorsstays empty, andvalidateOn: 'change'does not run for the child'supdate:modelValuerestoration. - Regression — native
<form>resetcallback invoking imperativeform.reset()with controlledGhostInput: mount<GhostForm validate-on="change">with a controlled<GhostInput v-model="values.displayName" default-value="Ada" />and an@reset/onResetcallback that invokes imperativeform.reset()whenevent !== null(without writingvalues.displayNameitself), changevalues.displayNameto'Bob'(marking'displayName'dirty), trigger a native<form>reset, andawait waitForFormResetDeferral()+await nextTick()so both the imperativenextTick()and the childafterNativeFormResetmacrotask + reactive flush settle; assertvalues.displayNamerestores to'Ada',isDirty === false,isFieldDirty('displayName') === false,fieldErrorsstays empty, andschema['~standard'].validatedoes not run for the controlled child'supdate:modelValuerestoration.
- Clicking
- Popup blur exclusion: moving
focusoutfromGhostSelectTriggerto the portaledGhostSelectContentreferenced byaria-controlsdoes not trigger prematurevalidateOn: 'blur'validation while selecting an option. - SSR and hydration (
expectSsrHydration):- Idle
<GhostForm>with named<GhostField>s and empty<GhostFieldError />renders matching SSR and hydrated DOM with hidden error nodes, noaria-invalid,novalidate, and zero Vue hydration warnings. <GhostForm :initial-issues="serverIssues">rendersdata-state="invalid",aria-invalid="true", and visible<GhostFieldError role="alert">copy on the server, hydrates cleanly withoutaria-describedbymismatch across both[Label, Control, Error]and[Label, Error, Control]child orders, and attachesaria-describedbyafter mount.
- Idle
Browser keyboard and accessible-error tests (tests/e2e/form.spec.ts)
- Keyboard invalid submit → focus & ARIA relationship (
@cross-browser): focus the firstGhostInput, type invalid values, pressEnterto submit via native implicit form submission; assert page does not reload, real focus (await expect(firstInvalidInput).toBeFocused()) moves to the first invalid control in DOM order (including when the first invalid field is aGhostRadioGroupwhose<fieldset>carriesaria-invalid="true"and focus lands on its first enabled<input type="radio">),aria-invalid="true"is present,aria-describedbyresolves to both the visibleGhostFieldDescriptionand visibleGhostFieldError(role="alert"), and form-level issues render inGhostInlineAlert(role="alert"). - Composite popup
Enterisolation: open aGhostSelectinsideGhostFormwith the keyboard, arrow to an option, and pressEnter; assert the option is selected and the listbox closes without submittingGhostForm. - Keyboard repair & valid submit:
Tabthrough invalid fields, correct each value (assertingaria-invalidclears on edit), pressEnteron the submitGhostButton, and assert the typed transformed payload renders in the status output andaxeScanreports zero violations in both idle and invalid states (lightanddarkmodes).
Compile-time / type inference tests (packages/vue/type-tests/GhostFormConsumer.ts, GhostFormConsumer.vue)
- Upstream Standard Schema v1 compatibility: bidirectional assignability between
@ghostvue/vue'sStandardSchemaV1and@standard-schema/spec'sStandardSchemaV1, plus a concrete transformed schema (Input = { count: string; nested: { tags: { label: string }[] } },Output = { count: number; nested: { tags: { label: string }[] } }). - Positive inference:
<GhostForm :schema="schema" :values="values" @submit="({ output }) => output.count.toFixed(0)">anduseGhostForm({ schema, values })inferoutput.countasnumber,values.countasstring, and accept valid dot-paths'count','nested.tags','nested.tags.0', and'nested.tags.0.label'ingetFieldError/validateField. - Negative assertions (
// @ts-expect-errorand<!-- @vue-expect-error -->):- Passing
{ count: 123 }asvalueswhenInferInput<typeof schema>['count']isstringfails typecheck. - Calling
output.count.trim()(treating transformednumberoutput as rawstringinput) fails typecheck. - Calling
form.getFieldError('nonExistentPath')orform.validateField('nested.wrong')fails typecheck againstGhostFormFieldPath<TValues>. - Passing an object with
'~standard': { version: 2, ... }fails theStandardSchemaV1constraint.
- Passing
Documentation plan
When #420 implements the approved contract:
- Publish
docs/components/form.mdwith generated<!-- @generated docs-api:vue/ghost-form begin -->API reference tables, Standard Schema v1 library recipes (Zod, Valibot, ArkType, and zero-dependency custom schemas), input-vs-output transformation explanation, nested object/array dot-paths, form-levelGhostInlineAlertcomposition, async race/server-error handling (setFieldErrors,waitUntil), SSRinitialIssues, and accessibility guidance. - Cross-link from
docs/components/field.mdshowing standaloneGhostFieldvs<GhostField name="...">insideGhostForm. - Add executable examples under
examples/form/(for exampleexamples/form/profile-schema.vue,examples/form/async-validation.vue, andexamples/form/nested-webhooks.vue), register them inpackages/vue/registry/form.registry.jsonandghost-form.manifest.jsonviapnpm manifests:writeandpnpm registries:write, and add playground coverage plus Linux Docker visual baselines (pnpm test:visual:docker).
Compatibility and release impact
- Additive
0.2.0surface:GhostForm,useGhostForm,StandardSchemaV1, and related types are new named exports in@ghostvue/vue. - Backwards-compatible
GhostFieldextension:name?: string | undefinedand scoped default-slot props onGhostFieldandGhostFieldErrorare purely additive. ChangingGhostField's internal prop default forinvalidfromfalsetoundefinedwhile computingBoolean(props.invalid ?? formInvalid ?? false)preserves identicalfalsedefaults for all existing callers and identicalpackages/vue/manifests/ghost-field.manifest.jsonconsumer behavior. - Changeset impact: None on this docs-only specification PR. Implementation in
#420requires aminorChangeset for@ghostvue/vue(F5 resolved against a@ghostvue/themesre-export in0.2.0).
Open architectural questions
None blocking. Zac approved F1–F5 as proposed at eda553c2c6b6a0a098db1c5aafff8a9893848719 (recorded by zprue743 on PR #487, 2026-11-28); implementation (#420) remains held until this revised specification PR merges into master. Recorded decisions for #420:
- Standard Schema v1 type source (F1, approved: Option A).
- Adopted: Export a local, spec-exact
StandardSchemaV1TypeScript interface/namespace from@ghostvue/vue(0production dependencies) and pin@standard-schema/specas adevDependencyin compile-time type tests to enforce bidirectional type equality. - Alternative (rejected): Add
@standard-schema/spec(^1.1.0, MIT, types-only) to@ghostvue/vuedependenciesand re-export itsStandardSchemaV1type directly.
- Adopted: Export a local, spec-exact
- Async submit handler tracking on
<GhostForm>(F2, approved: Option A).- Adopted: Keep
submit,invalid, andresetindefineEmitsso they appear as standard events inghost-form.manifest.jsonand generated API docs, and providepayload.waitUntil(promise)onGhostFormSubmitPayloadfor async<GhostForm @submit>handlers (whileuseGhostForm({ onSubmit })awaits a returnedPromisedirectly). - Alternative (rejected): Declare
onSubmit?: (payload: ...) => unknown | Promise<unknown>indefinePropsinstead ofdefineEmitsso<GhostForm @submit="asyncSave">returns itsPromisedirectly withoutwaitUntil(...), accepting thatvue-component-metarecordsonSubmitinpropsrather thanevents.
- Adopted: Keep
- Default trigger pair and duplicate-submit policy (F3, approved: Option A).
- Adopted: Default
validateOn: 'submit'andrevalidateOn: 'change', ignore duplicate submits whileisSubmitting === true({ status: 'ignored' }), and letsubmit()supersede backgroundblur/changevalidations whenisSubmitting === false. - Alternative (rejected): Default
validateOn: 'blur', or queue/abort-and-restart in-flight submissions on a second submit click.
- Adopted: Default
- Canonical nested path encoding and unmatched paths (F4, approved: Option A).
- Adopted: Join
string | numberpath segments with.(billing.postalCode,webhooks.0.url), keep non-empty unmatched paths infieldErrors[path]without duplicating them intoformErrors, and route only empty/missing orsymbol-containing paths intoformErrors. - Alternative (rejected): Support JSON-Pointer/bracket syntax (
webhooks[0].url) or also mirror unmatched field paths (no mounted<GhostField name="...">) intoformErrors.
- Adopted: Join
- Package surface in
@ghostvue/themes(F5, approved:@ghostvue/vue-only).- Adopted: Export
GhostFormanduseGhostFormfrom@ghostvue/vueonly in0.2.0, becauseGhostFormowns no visual tokens or layout chrome (consumers composeGhostCard,GhostField,GhostFieldset, or CSS grid). - Alternative (rejected): Re-export
GhostFormfrom@ghostvue/themes(either as a pass-through or with an optional default vertical field-stack gap) so themed consumers can importGhostFormfrom@ghostvue/themesalongsideGhostFieldandGhostInput.
- Adopted: Export