GhostDatePicker specification
Status: Approved by zprue743 on 2026-11-17 (GHO-207). Field and form error flow amendment approved by zprue743 on 2026-12-02. Parent issue: GHO-103. Design plan: GHO-103 — DatePicker design plan. Dependencies: GhostCalendar, GhostDialog, and GhostPopover positioning/overlay infrastructure (already Done); no new runtime dependency.
Amendment (approved 2026-12-02, implemented): picker errors flow into the surrounding
GhostFieldandGhostFormautomatically, and the themed root's default slot is typed. The detailed contract is in the field and form error flow amendment, which takes precedence over the other sections where they differ.
Anchored-modal interpretation: GHO-103's "built on Popover" requirement is satisfied by reusing
GhostPopover's floating positioning and overlay infrastructure (useFloating, portal, dismissable layer) onGhostDialog/GhostDialogContent, while preservingGhostPopover's existing non-modal public contract.
Purpose and user problems
GhostDatePicker provides a headless date-entry and selection family in @ghostvue/vue (with optional themed wrappers and token-based CSS in @ghostvue/themes) combining ordinary text entry with an anchored modal calendar for single-date or inclusive-range selection.
- Users can type or paste dates directly in native text inputs without opening or navigating the calendar, or open the modal calendar via the trigger button.
- Applications get deterministic
CalendarDatevalues (@internationalized/date), strict ISO form serialization, native constraint-validation alignment, and WAI-ARIA APG Date Picker Dialog accessibility. - One interaction policy applies across desktop and mobile: a single-date calendar activation commits immediately and requests close; a range commits atomically only after two explicit date activations.
- Invalid or incomplete draft text never replaces the committed model or form value.
Non-goals
- Time-of-day selection, JavaScript
Dateobjects, timestamps, time zones, or date-time values. - Segmented / locale-driven date-field editors or spinbutton segments.
- Natural-language date parsing (for example,
"next Friday"). - Multi-month calendar displays, date presets, async parsing, or alternate calendar systems.
- Device-dependent commit rules or automatic mobile bottom sheets in v1.
- Adding a new package or a new runtime dependency.
- Altering
GhostPopover's non-modal public contract or nesting Popover and Dialog content. - Intercepting the entire form's submit lifecycle or inventing a form framework.
Public API
Parts and exports
Headless exports from @ghostvue/vue:
GhostDatePicker— renderless state/context root and form-value owner.GhostDatePickerInput— native text input;part="single"by default, or"start"/"end"in range mode.GhostDatePickerTrigger— nativetype="button"control with dialog relationships and an overridable accessible name.GhostDatePickerContent— positioned modal content (role="dialog",aria-modal="true"), including an accessible Close control by default; default slot holds the calendar and optional help/error content.GhostDatePickerCalendar— binds existingGhostCalendarstate and supplies a default header/navigation/grid; optional default slot allows composition with existing Calendar parts.useGhostDatePicker— composable for picker state, draft lifecycle, validation, and form integration.- Documented value, callback, error, slot, and exposed-ref types (including
GhostDatePickerRange,GhostDatePickerValue,GhostDatePickerPart,GhostDatePickerTextContext,GhostDatePickerParse,GhostDatePickerFormat,GhostDatePickerValidateRange,GhostDatePickerErrorCode,GhostDatePickerError).
Themed exports from @ghostvue/themes:
- Optional
GhostDatePicker*wrappers (packages/themes/src/ghost-date-picker*.ts) and scoped token-based CSS using--ghost-*tokens. Consumerclassandstylebindings are preserved.
Value and callback types
All public date values are Gregorian date-only CalendarDate instances (@internationalized/date) in years 0001–9999:
type GhostDatePickerRange = { start: CalendarDate; end: CalendarDate }
type GhostDatePickerValue = CalendarDate | GhostDatePickerRange | null
type GhostDatePickerPart = 'single' | 'start' | 'end'
interface GhostDatePickerTextContext {
locale: string
part: GhostDatePickerPart
}
type GhostDatePickerParse = (
text: string,
context: GhostDatePickerTextContext,
) => CalendarDate | null
type GhostDatePickerFormat = (
date: CalendarDate,
context: GhostDatePickerTextContext,
) => string
type GhostDatePickerValidateRange = (
range: GhostDatePickerRange,
) => string | null
type GhostDatePickerErrorCode =
| 'parse'
| 'incomplete'
| 'min'
| 'max'
| 'unavailable'
| 'range-order'
| 'range-validation'
| 'required'
| 'external-invalid'
| 'configuration'
| 'uncommitted'
interface GhostDatePickerError {
code: GhostDatePickerErrorCode
part: GhostDatePickerPart | 'range'
message: string
}parsereturningnullindicates invalid nonempty input; empty input is handled before invokingparse.- Callbacks (
parse,format,validateRange,validationMessage,isDateDisabled) must be synchronous and pure; promises are not supported. validateRangereturns a consumer-facing error string ornull.
Props and configuration
GhostDatePicker (root)
| Prop | Type | Default | Contract |
|---|---|---|---|
selectionMode | 'single' | 'range' | 'single' | Single date vs two-input inclusive range. Fixed for an instance; remount with a new key to change modes. |
modelValue | GhostDatePickerValue | undefined | undefined | Controlled mode-appropriate value. undefined = uncontrolled; null = controlled empty. |
defaultValue | GhostDatePickerValue | null | Initial uncontrolled value. |
open | boolean | undefined | undefined | Independently controlled open state. |
defaultOpen | boolean | false | Initial uncontrolled open state. |
minValue | CalendarDate | undefined | undefined | Inclusive lower bound, matching GhostCalendar. |
maxValue | CalendarDate | undefined | undefined | Inclusive upper bound, matching GhostCalendar. |
isDateDisabled | (date: CalendarDate) => boolean | undefined | Unavailable endpoint dates, matching GhostCalendar. |
validateRange | GhostDatePickerValidateRange | undefined | undefined | Optional whole-range business validation. |
locale | string | 'en-US' | Calendar and formatting locale. |
weekStartsOn | 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined | undefined | Week start override (Sunday = 0); defaults to locale preference. |
today | CalendarDate | undefined | undefined | Explicit current date for deterministic SSR, initial visible month fallback, and focus fallback. |
defaultVisibleMonth | CalendarDate | undefined | undefined | Initial empty-picker month; subsequent month navigation remains internal in v1. |
parse | GhostDatePickerParse | undefined | strict ISO | Synchronous parser; consumer callbacks must round-trip valid displayed dates. |
format | GhostDatePickerFormat | undefined | strict ISO | Synchronous formatter; display formatting never changes ISO form serialization. |
disabled | boolean | false | Blocks all interaction and overrides open visibility. |
readonly | boolean | false | Leaves text focusable/selectable, prevents editing/clearing, and overrides open visibility. |
required | boolean | false | Native required constraint on empty committed value. |
invalid | boolean | false | Consumer-supplied validity (external-invalid); combines with internal errors. |
name | string | undefined | undefined | Native form submission name (name in single mode; name[start] / name[end] in range mode). |
startName | string | undefined | undefined | Independent override for range start submission name. |
endName | string | undefined | undefined | Independent override for range end submission name. |
form | string | undefined | undefined | External <form> association for hidden submission inputs and reset integration. |
formatHint | string | 'YYYY-MM-DD' | Linked format description text; consumers using custom callbacks should supply matching instructions. |
validationMessage | (error: GhostDatePickerError) => string | undefined | Optional callback to localize built-in error messages (including uncommitted pending-draft validation message). |
GhostDatePickerInput
part:'single' | 'start' | 'end'(default'single').- Renders a native
<input type="text">(nonameattribute on the visible input; hidden inputs own submission). - Input-local native
nameandformattributes cannot override the root's serialization/association contract. - Input
invalid,disabled, andrequiredbindings fromGhostFieldControlcombine with root state. Local disabling does not bypass range validation. - Range inputs each receive a distinct ID and accessible label; never apply one
GhostFieldControlID to both range inputs (compose ranges with a named group and separateGhostFieldinstances/IDs for the two endpoints). - Preserves consumer
class,style, ARIA descriptions, and native input/focus event handlers when merging bindings.
GhostDatePickerTrigger
- Native
<button type="button">witharia-haspopup="dialog",aria-expanded, andaria-controls. - Accessible name includes the selected date or range; consumer localization is supported through native ARIA attributes (
aria-label/aria-labelledby).
GhostDatePickerContent
- Exposes the existing supported floating placement/collision options and portal target (
placementdefault'bottom-start',flipandshiftenabled by default). - Modal semantics (
role="dialog",aria-modal="true") are fixed in v1 rather than exposing two interaction models. - Accepts native ARIA labeling (
aria-label/aria-labelledby) andcloseLabel(default'Close date picker'). - Includes an accessible Close control by default; default slot holds
GhostDatePickerCalendarand optional help/error content.
GhostDatePickerCalendar
- Binds existing
GhostCalendarstate and supplies a default header, month navigation, and grid. - Optional default slot allows composition with existing
GhostCalendar*parts without forking calendar arithmetic or keyboard navigation.
v-model contracts
- Selection (
modelValue/update:modelValue):undefinedmeans uncontrolled (initial defaultnull);nullis a controlled empty value.- Emits proposals on valid commits and reconciles to actual props on the next Vue tick.
- Equal date/range values do not emit duplicate
update:modelValueevents. - An ignored valid proposal restores the parent's value in the display and hidden inputs; an invalid draft remains visible.
- A materially changed external
modelValuereplaces input drafts and cancels pending calendar range progress without echoingupdate:modelValue. - Never mutate consumer-owned
CalendarDateor range objects. - Reject a value of the wrong shape for
selectionModeas aconfigurationerror; never inferselectionModefrom the value.
- Open state (
open/update:open):- Independently controllable; defaults to closed (
false). - Effective visibility is
requestedOpen && !disabled && !readonly. - An ignored close proposal leaves the modal active unless
disabledorreadonlytakes precedence; do not restore focus while the modal remains open.
- Independently controllable; defaults to closed (
- Native form serialization and reset:
- Single mode with
name="date"submitsdate=2026-11-17. - Range mode with
name="stay"submitsstay[start]andstay[end];startNameandendNameoverride each endpoint independently. Omitting a name omits that corresponding successful control. - Valid empty values serialize as empty strings
"". Disabled controls are omitted from submission; readonly controls submit normally. - Hidden inputs serialize only the current committed value in ISO (
YYYY-MM-DD), never draft text or a proposed controlled value. - Uses
useNativeFormReset: uncontrolled reset restores the captured initialdefaultValue; controlled reset restores current props without emitting. Reset clears drafts, draft errors, and pending range progress, and requests close. Respects canceled resets (event.preventDefault()) and externalformassociation.
- Single mode with
Events, callbacks, slots, and exposed methods
GhostDatePickeremitsupdate:modelValueandupdate:open.GhostDatePickerdefault slot exposes{ value, open, pending, errors, clear, openCalendar, close }, wherevalueis the committed value,openis effective open state,pendingreflects uncommitted/range-in-progress state,errorsisGhostDatePickerError[],clear()commitsnull(when editable), andopenCalendar()/close()support custom controls.GhostDatePickerInputtemplate refs expose{ element, focus(), blur() }. Native input/focus events remain native fallthrough listeners.
Additive dependency contracts (Calendar and Dialog)
These shared changes are required parts of the DatePicker design and must ship with regression tests and updated docs/types/manifests:
Calendar (
ghost-calendar.ts,use-ghost-calendar.ts,GhostCalendar.vue):- Add an additive
select(date: CalendarDate)event, backed byonSelect?: (date: CalendarDate) => voidinUseGhostCalendarOptions. - Fires exactly once for each accepted activation (including repeat activation of the same date) after existing selection processing. Disabled activations emit nothing.
- Keep
GhostCalendar's existingupdate:modelValuecontract unchanged.GhostDatePickerowns an explicit range anchor, consumesselect, controls the Calendar display value, and ignores Calendar's model proposals as a source of committed picker values (ensuring a new range starts cleanly even when the prior range is one day long). - Widen only
GhostCalendarProps.modelValueandUseGhostCalendarOptions.modelValueto acceptnullwhile retainingundefinedas uncontrolled. Internally preservenullthrough the control-ownership check, then normalize it toundefinedin existing selection readers, slots, and composable return values. KeepGhostCalendarValue, existing emitted payloads, and the existing default-value contract unchanged.GhostDatePickerbindsnullwhen empty.
- Add an additive
Dialog and focus scope (
ghost-dialog.ts,GhostDialogContent.vue,use-focus-scope.ts):- Add narrowly scoped
GhostDialogContentprops:focusReady?: boolean(defaulttrue)initialFocus?: () => HTMLElement | nullreturnFocus?: () => HTMLElement | null
focusReadygates the first focus-scope activation of each opening after portal placement; once activated, keep the focus trap active until close even iffocusReadychanges.- An omitted or invalid
initialFocusretains the existing autofocus fallback; an omitted or invalidreturnFocusretains the existing saved-opener behavior. - Extend
useFocusScope(UseFocusScopeOptions) with optional reactive initial/return target resolvers; invoke them only in mounted focus lifecycles. Preserve all existing defaults. GhostDatePickersuppliesfocusReadyafter floating positioning and calendar cell rendering, an initial Calendar target (via a narrowly named internal grid/context focus-target accessor on Calendar rather than timers or undocumented DOM nesting), and a return target preferring its enabled trigger then its input.
- Add narrowly scoped
State model
Maintain three separate concepts:
- Committed model: current
CalendarDate | GhostDatePickerRange | null. - Raw input drafts: exact string(s) currently in
GhostDatePickerInput(singleorstart/end). - Pending calendar range anchor:
CalendarDate | nullheld locally while choosing a range in the modal calendar.
| Action | Result |
|---|---|
| Type or paste in input | Preserve exact text; no model update and no caret-moving reformatting. IME composition never commits. |
Enter in an edited input | Attempt a commit; call preventDefault() to prevent implicit form submission for that keystroke. |
| Blur a single input | Attempt a commit. |
| Move focus between range inputs | Retain both drafts; defer pair-level errors and commit until Enter or focus leaves the input pair. |
| Valid text commit | Publish complete value and format display text. Equal date values do not emit duplicate update:modelValue. |
| Invalid or incomplete commit | Keep draft text and prior committed value; show and associate an error. Never silently clamp, normalize an impossible date, or swap typed endpoints. |
| Clear single input, or both range inputs | Commit null; required validity then applies. Clearing only one range endpoint is incomplete and preserves the committed pair. |
| Activate calendar date in single mode | Commit and request close. |
| First calendar activation in range mode | Start a new local range anchor; keep popup open and committed value unchanged. |
| Second calendar activation in range mode | Sort the two clicked dates, validate, then atomically commit and request close. Clicking the same day twice commits a one-day range. |
| Invalid second calendar activation | Keep the anchor and popup open; announce the error so another endpoint can be chosen. |
Escape, Close button, or outside dismissal in modal | Discard calendar-only progress; do not commit. Preserve any typed drafts captured when opening. |
Escape in a closed, edited text field | Restore text from the committed value and clear draft errors; do not change the model. |
| Activate Trigger | Attempt normal text commit first, then open even if that fails so the calendar can correct invalid input. Cancellation preserves invalid drafts; successful calendar selection replaces them. |
Loading, empty, disabled, read-only, and error states
- Disabled and readonly precedence:
- Effective visibility is
requestedOpen && !disabled && !readonly. - Entering
disabledorreadonlycancels calendar progress, requestsopen = false, and immediately removes the interactive modal surface even if the parent ignoresupdate:open. - Re-enabling follows the current controlled
openprop (a retainedtruereopens). readonlyleaves text focusable and selectable but prevents editing and clearing.disabledblocks all interaction.
- Effective visibility is
- Configuration and external invalidity:
minValue > maxValueis aconfigurationerror and disables date selection.- Invalid external values or changed constraints do not rewrite the model: display the supplied value where representable, expose an error, and block validation for editable controls.
invalidprop addsexternal-invalidand combines with internal errors.- Changes to
parse,format, orlocalepreserve dirty text and revalidate it on the next commit; pristine text reformats immediately.
- Range validation policy:
- Ranges are inclusive (
start <= end); equal endpoints are valid. - Built-in bounds (
minValue/maxValue) andisDateDisabledcheck both endpoints. - Unavailable dates inside a range are permitted by default, matching
GhostCalendar. Consumers needing contiguous availability, maximum stay, or booking rules usevalidateRange. Never scan arbitrarily long ranges on every render or keystroke.
- Ranges are inclusive (
- Native constraint validation and open-modal
invalidevents:- Keep native validity synchronized on the visible input(s) while typing so invalid/incomplete drafts cannot silently submit the previous hidden value (including via
form.requestSubmit()). - An uncommitted dirty draft uses the
uncommittederror code (default message"Confirm this date") for native constraint validity untilEnter/blur; visual error announcements wait for a commit attempt. - As with native controls,
novalidate,form.submit(), and directFormDataextraction bypass validation; directFormDatareturns the committed hidden value. - Readonly controls follow HTML's native constraint-validation exemption (externally invalid readonly values expose errors but do not block submission). Disabled controls likewise do not validate.
- While the modal is open, editable inputs are outside its inert boundary: intercept their native
invalidevents withpreventDefault(), announce the error inside the dialog, and focus an internal error-summary target (tabindex="-1", named, omitted when not needed). The form remains invalid and submission remains blocked without forcing focus into an inert input or requiring the parent to accept a close request. Applies to bothrequestSubmit()andreportValidity().
- Keep native validity synchronized on the visible input(s) while typing so invalid/incomplete drafts cannot silently submit the previous hidden value (including via
Async behavior
Parsing and validation are synchronous. Consumers own remote availability loading and pass updated constraints (minValue, maxValue, isDateDisabled, disabled, invalid); GhostDatePicker revalidates any pending range when constraints change and checks again before committing.
Consumer data
- All public values are Gregorian date-only
CalendarDatevalues in years0001–9999. JavaScriptDate, timestamps, time zones, and date-time values are rejected. - Default strict ISO parsing rejects whitespace, missing zero-padding, impossible dates (e.g. Feb 30, non-leap Feb 29), overflow, and ambiguous localized strings.
- Display formatting never alters ISO form serialization.
- A thrown
parsecallback is treated as an invalid draft (parseerror); a thrownformatcallback falls back to ISO with a development diagnostic. - Custom callbacks do not bypass bounds or availability validation and must round-trip valid displayed dates.
- Consumer-owned
CalendarDateand range objects are never mutated.
Accessibility contract
Semantics and relationships
- Inputs: Native
<input type="text">with visible labels and linked format/error descriptions (aria-describedby), notrole="combobox"orrole="spinbutton". Range mode uses a named group (role="group") plus distinct Start date and End date labels. - Trigger: Native
<button type="button">witharia-haspopup="dialog",aria-expanded, andaria-controls; accessible name includes the selected date or range and is overridable via native ARIA attributes. - Content: Named
role="dialog",aria-modal="true", background inert, trapped focus, and a visible Close button (closeLabel, default'Close date picker'), following the WAI-ARIA APG Modal Dialog and Date Picker Dialog patterns. - Error summary: Inside the dialog when validation fails while open (
tabindex="-1", accessible name, omitted when not needed).
Keyboard interaction
- Trigger:
Enter/Spaceopens the modal (attempting text commit first). - Closed input:
Enterattempts commit and prevents implicit form submission;Escapein an edited field restores committed text and clears draft errors; native text editing keys are preserved. - Modal dialog:
Tab/Shift+Tabcycle through the dialog with a single gridTabstop;Escapecloses the top layer and restores focus. - Calendar grid:
ArrowLeft/ArrowRightmove days (reversed in RTL);ArrowUp/ArrowDownmove weeks;Home/Endmove to week boundaries;PageUp/PageDownmove months;Shift+PageUp/Shift+PageDownmove years;Enter/Spaceactivate a selectable date. Outside the grid, preserve native text editing keys.
Focus behavior
- Initial focus on open: Focus the selected date (or range start), else explicit
today, else the first date of the initial visible month, clamped tominValue/maxValue. Unavailable dates (isDateDisabled) remain focusable and unselectable. If no date can receive focus (for example, all dates out of bounds or disabled), focus the Close button. - Initial visible month: Committed date / range start ->
defaultVisibleMonth-> explicittoday->GhostCalendar's deterministic January 2024 fallback. Never read the client clock during SSR. - Return focus on close: Escape, single/range completion, and Close restore focus to the opener (preferring enabled trigger, then input). If the opener has disappeared or is disabled, focus the input if available; otherwise let the ancestor focus scope restore focus. Do not restore focus if a controlled parent ignores close and keeps the dialog open.
- Outside dismissal: Pointer activation outside dismisses the modal without activating underlying form controls.
Assistive technology expectations
- Preserve
GhostCalendar's localized month/day labels and month-change live announcements. - Add a polite range instruction (e.g.,
"Choose an end date") after the first range activation and polite validation feedback without duplicate month announcements. - UI instructions and error strings are consumer-localizable (
validationMessage,closeLabel, ARIA attributes);localealone does not promise built-in translations of every English string.
Rendering and customization
- Headless parts merge consumer
class,style, ARIA attributes, and event handlers without overwriting them. GhostDatePickerCalendarrenders a defaultGhostCalendarheader/navigation/grid and accepts an optional default slot for customGhostCalendar*part composition.GhostDatePickerContentrendersGhostDatePickerCalendarand an optional error summary; its default slot supports custom help/error content alongsideopenCalendar()andclose()from the root slot.@ghostvue/themesprovides optional styled wrappers using--ghost-*tokens. Sizes follow the shared control scale (control.size.mdfor the inputs and trigger,control.size.smfor the close button and calendar parts), which floors to >= 44px touch targets on coarse pointers.
Environment behavior
SSR and hydration
- Deterministic SSR-safe IDs (
useGhostId), no setup-time DOM work, and no client clock reads during SSR (document supplyingtodayfor ordinary current-month UX). - Deterministic closed and initially open (
defaultOpen/open: true) SSR and hydration. - Clean listener and portal/focus-scope cleanup on unmount; supports nested dialogs and portaled content.
Mobile and touch
- Same commit and modal interaction policy on touch (no automatic mobile sheet in v1).
- Constrain content to the viewport, allow named scroll regions when needed, avoid forcing the software keyboard open on calendar entry, and provide >= 44px themed touch targets on coarse pointers (fine pointers keep the mapped control height, at least 28px).
- Verify zoom, forced colors, and reduced motion.
Performance
- Synchronous parsing and validation only; no range-scanning loops over arbitrarily long ranges on every render or keystroke.
- Reuses
GhostCalendar's single-month (~42 cells) grid without virtualization.
Composition
- Reuses
@internationalized/date(CalendarDate),GhostCalendar,GhostDialog/GhostDialogContent,useFloating,useFocusScope,useNativeFormReset,useGhostId,useControllableState, andGhostFieldControl. - Composes
GhostDialogContentwithuseFloatingrather than modifyingGhostPopoversoGhostPopoverremains non-modal andGhostDialogremains the single owner of modal focus trapping, inerting, scroll lock, and dismissable-layer stacking.
Test plan
- Unit & state tests (
use-ghost-date-picker.test.ts,use-ghost-calendar.test.ts,use-focus-scope.test.ts):- Strict ISO parsing (including leap days), thrown/invalid callbacks, empty/partial/reversed ranges, two clicks on one day, restarting an existing one-day range, selecting an earlier second endpoint, invalid drafts preserving committed model,
validateRangerejection, changed constraints, controlled parents accepting/ignoring proposals, external updates during editing, IME composition, canceled resets, anddisabled/readonlytransitions. - Calendar
selectevent ordering, repeated-date activation, disabled suppression, controlled-emptymodelValue=nullnormalization, and unchanged existing Calendar output behavior. useFocusScopereadiness/target resolver defaults and regressions.
- Strict ISO parsing (including leap days), thrown/invalid callbacks, empty/partial/reversed ranges, two clicks on one day, restarting an existing one-day range, selecting an earlier second endpoint, invalid drafts preserving committed model,
- Vue component & SSR tests (
GhostDatePicker.test.ts,GhostCalendar.test.ts,GhostDialog.test.ts):- Headless and themed ref/slot/binding preservation,
GhostFieldintegration (single and named-group range), SSR/hydration for closed and open states, no leaked document listeners, andGhostDialogContentunchanged-default regressions.
- Headless and themed ref/slot/binding preservation,
- Browser, accessibility, and keyboard tests (
tests/e2e/ghost-date-picker.spec.ts,ghost-calendar.spec.ts,form-reset.spec.ts, dialog browser spec):- Press every documented key and assert real focus (
toBeFocused()) and ARIA state; cover Tab wrap, RTL arrow reversal, nested overlays, outside dismissal without click-through, unavailable/all-disabled grids, trigger removal, range cancellation, and open/closed axe scans. - Real
FormData, invalid submission,requestSubmit()andreportValidity()with dirty text and while modal is open, ignored controlled close, focusable in-dialog error summary, readonly validation exemption,disabled/readonlyoverridingopen=true, required fields, reset, and customname/startName/endName/formownership. - Zoom, forced colors, reduced motion, and touch target sizing.
- Press every documented key and assert real focus (
- Type tests:
- Reject plain strings,
Date, date-times, malformed ranges, and asynchronous callbacks; verify Calendar preserves existing output signatures while acceptingmodelValue=null.
- Reject plain strings,
Documentation plan
docs/components/date-picker.md: API reference, accessibility guidance,todaySSR guidance,GhostFieldrange group pattern, and a prominentvalidateRangeexample rejecting interior unavailable dates.- Typed runnable examples under
examples/date-picker/:basic,range,controlled,validation/form-reset,custom-format/locale,rtl,nested-dialog, andthemed, registered via the repository's example and manifest conventions. - Update
GhostCalendarandGhostDialogdocs, types, and manifests for their additive contracts; update only the DatePicker row indocs/roadmap.mdduring implementation.
Compatibility and release impact
- Adds
GhostDatePicker*anduseGhostDatePickerto@ghostvue/vueand@ghostvue/themes(minor Changesets for both packages at implementation time). - Additive, backwards-compatible extensions to
GhostCalendar(select/onSelect,modelValue: ... | nullinput) andGhostDialogContent/useFocusScope(focusReady,initialFocus,returnFocus). - No new runtime dependency.
Open architectural questions
None. All architectural and behavioral decisions in GHO-103 — DatePicker design plan were approved by zprue743 on 2026-11-17 (GHO-207). Manual assistive-technology review is required before stable release. The field and form error flow amendment, including FE1–FE4, was approved by zprue743 on 2026-12-02.
Field and form error flow amendment
Important
Approved on 2026-12-02 by zprue743. The maintainer chose automatic flow over a documented bridging pattern on 2026-12-01: picker errors flow into the surrounding GhostField and GhostForm without consumer wiring. The rules below specify that decision, and the choices marked FE1–FE4 were confirmed on 2026-12-02. The implementation shipped with its tests, the date-picker/form example, and Changesets.
Problem
- Two sources, wrong message. With
validateRangeorisDateDisabled, a rejected commit keeps the typed text and the previous committed value. AGhostFormschema sees only the committed value, so a field that visibly holds dates announces the form's empty-value message (for example "Choose a check-in date"). The picker's reason (for example "Stays are limited to 14 nights") reaches only the root sloterrors, so consumers render it beside the field by hand. - Stale submission.
GhostFormsetsnovalidateby default, so the picker's native custom validity does not block its submit. A rejected draft typed over a valid committed value submits the stale value. - Untyped themed slot. The themed root is a render-function component without slot types, so its default slot props resolve to
anyanderrors.map((e) => …)fails undernoImplicitAny.
Terms
- Bridged input: a
GhostDatePickerInputrendered inside aGhostField. Its host field is the nearest ancestorGhostFieldof that input. The renderless root's position does not matter, so the existing pattern of fields insideGhostDatePickerworks. - Flowing errors: entries of the root slot
errorsrouted to a host field under Routing. Messages are the final strings, already passed throughvalidationMessage. - Form messages: a named field's messages from schema issues and
setFieldErrors, asGhostFormreports them today.
Routing (FE1)
- An error with
part: 'single','start', or'end'flows into the host field of the input rendering that part. - An error with
part: 'range'(range-order,range-validation, and rangerequiredandexternal-invalid) flows into exactly one field: the host field of thestartinput, or of theendinput whenstartis not bridged. The start input comes first in DOM order, so focus after a failed submit lands on the field that holds the reason, and only one field announces it. - When both inputs share one host field, that field receives every flowing error once.
- Errors keep the order of the slot
errorslist. An error with the samecodeandpartappears once. - Not flowing:
- Calendar-only errors, such as a rejected second range activation while the dialog is open. They describe calendar progress, not the form value, and stay announced inside the dialog.
- Every error of a
disabledorreadonlypicker, matching the native constraint-validation exemption. They stay in the slot and the picker's own descriptions.
- Timing: flowing errors appear and clear in the same tick as the slot
errors: on a commit attempt (Enter, blur, focus leaving the range pair), on a validation attempt, and on changed values or constraints. A valid commit,Escaperestoring committed text, a reset, or a changed external value removes them.GhostForm'svalidateOnandrevalidateOnneither delay nor hide them, because they describe text the schema cannot see.
One message per field (FE2)
Picker codes fall into two classes:
| Class | Codes | Describes |
|---|---|---|
| Draft-describing | parse, incomplete, min, max, unavailable, range-order, range-validation, uncommitted, configuration | The text or value on screen |
| Value-state | required, external-invalid | The value the form also checks |
A host field's message list (GhostField slot error and errors, GhostFieldError message and errors, and for a named field in a form, getFieldError(P) and getFieldErrors(P)) is chosen by the first rule that applies:
- Draft-describing picker errors flow into the field: list those picker messages only. Form messages for the field are withheld, not deleted, and return once the picker errors clear if they are still current.
- The field has form messages: list the form messages only. Value-state picker errors are withheld, because the form owns the copy for an empty or invalid value.
- Otherwise: list the value-state picker messages.
Situation (max-stay example, required field) | Field message |
|---|---|
| Empty, form submitted | Schema's "Choose a check-in date" |
20-night range typed and blurred, rejected by validateRange | "Stays are limited to 14 nights" |
| Same text, form submitted | "Stays are limited to 14 nights" |
| Text corrected to a valid range and committed | None, or the schema's message |
Escape restores committed empty text | Schema's message, if current |
Announcement:
- The host field's
GhostFieldErrorstays the only live region (role="alert") for that field. Its default content is the first message, so a change is announced once. - When a host field has a registered
GhostFieldError, the bridged input does not link the picker's ownerror-descriptionfor errors routed to that field. It relies on the field's error id thatGhostFieldControlalready supplies inaria-describedby. Without a registeredGhostFieldError, or when the field is explicitly:invalid="false", the input keeps the picker's own description as today. - For a range error routed to the
startfield, theendinput keeps linking the picker's own description. That text is not a live region, so focusing the end input still explains the problem without a second announcement. - While the dialog is open the host field sits in the inert background. The in-dialog error summary remains the announced message (existing contract).
Field state:
- A non-empty message list makes the host field invalid:
data-state="invalid"on the root, andinvalid: truewitharia-invalid="true"fromGhostFieldControl. The field'sinvalidbinding returned to the input only combines intoaria-invalid; it never creates a picker error, so there is no feedback loop. - An explicit boolean
invalidonGhostFieldstill overrides the display:falsehides every message, including picker messages, andtrueforces the invalid state.
Without a form (FE3)
- Inside a
GhostFieldwith no ancestor form, or withoutname: errors flow into the field only. The field becomes invalid andGhostFieldErrorshows the picker message. Rules 1 and 3 apply; there are no form messages. - Outside any
GhostField: unchanged. The picker keeps its visually hidden error descriptions,aria-invalid, sloterrors, native custom validity, and in-dialog summary.
Form integration (FE4)
For a host field <GhostField name="P"> under GhostForm or a useGhostForm context, picker errors are a layer separate from schema and imperative errors:
- Reads:
getFieldError(P),getFieldErrors(P), and thefieldErrorsrecord follow FE2.isFieldInvalid(P),isInvalid,isValid, and rootdata-state="invalid"count flowing picker errors.getFieldIssues(P)andissuesappend each flowing picker message as{ message, path }, withpathequal toP.split('.'), the shapesetFieldErrorsalready uses. Schema and imperative issues are not removed fromissues. - Submit: a submit attempt (a native submit event or
submit()) first marks validation as attempted on every enabled, editable picker bridged into that form, as the nativeinvalidevent does today. That revealsuncommittedandrequiredwithout committing drafts. Schema validation then runs as today. If any bridged picker still has flowing errors when validation settles, the result is{ status: 'invalid', issues }with picker issues after schema issues.invalid/onInvalidfires withfieldErrorsper FE2,submit/onSubmitdoes not fire, andfocusInvalidOnSubmitfocuses the firstaria-invalid="true"control in DOM order, which is the picker input. This closes the stale-submission gap. Picker state is read when validation settles, so an error that appears or clears during an async schema check is reflected. - Explicit validation:
validate()does the same as submit without submitting.validateField(P)marks only pickers bridged toPas attempted and includes their issues. - Ownership:
clearErrors(),clearErrors(P),setFieldErrors(P, []), andsetFormErrors()do not remove picker errors; the picker owns them. An explicit:invalid="false"on the field hides them but does not unblock submit, matching how that override treats schema errors today. - Reset: imperative
reset()and a native reset clear form state as today and clear the validation-attempted state of bridged pickers. A native reset also clears drafts (existing contract). Imperativereset()does not change drafts, so an error that still describes visible text stays shown. - Lifecycle: picker errors follow the field's form registration. Renaming the field moves them to the new path; unmounting the input, the field, or the picker removes them in the same tick.
- Internal hook: the bridge uses non-exported additions to the internal field and form contexts.
GhostField,GhostForm, anduseGhostFormgain no public props, events, slots, or exports. Other controls do not adopt the hook in this amendment.
Themed slot typing
- The themed
GhostDatePickerdeclaresslots: Object as SlotsType<{ default: GhostDatePickerSlotProps }>, followingpackages/themes/src/ghost-tags-input.ts. Its default slot props then match the headless root, anderrorsisGhostDatePickerError[]. There is no runtime change. - A type test under
packages/themes/type-tests/, compiled withnoImplicitAny, proves thaterrors.map((e) => e.message)compiles, thate.codeisGhostDatePickerErrorCode, and that a wrong slot prop fails with@ts-expect-error. - The implementation change lists any other themed wrapper whose slot props resolve to
any. Fixing those is out of scope.
Contract decisions for review
- FE1: a range-scoped error goes to the
starthost field only, not to both endpoint fields. - FE2: draft-describing picker errors take precedence over form messages, and form messages take precedence over value-state picker errors.
- FE3: errors flow into a
GhostFieldeven without a form. - FE4: picker errors block
GhostFormsubmit, are revealed by a submit attempt, and cannot be cleared by the form's error APIs. Disabled and readonly pickers report nothing.
Test plan additions
- Vue component tests: routing for single mode, range with two fields, range with one shared field, and an unbridged start input. Cover each FE2 rule with the max-stay example, and assert the form's empty-value message is absent while rejected text is visible. Assert
aria-describedbyhas the field error id and not the picker error id, and that exactly one non-emptyrole="alert"exists per field. Cover clearing on valid commit,Escape, and reset; no flow from disabled, readonly, or calendar-only errors; explicitinvalidoverrides; field rename and unmount; and fields without a form or name. - Form tests: submit with a rejected draft over a valid committed value returns
invalid, emits nosubmit, and focuses the input;submit()andrequestSubmit()with an uncommitted draft revealuncommitted;clearErrorskeeps picker errors; issue shape and order; an async schema with the picker error changing before validation settles. - Browser tests: a range inside
GhostFormwith a maximum stay. Type a rejected range and blur, then assert the field error text andaria-invalid. Submit and asserttoBeFocused()on the start input. Run axe with the dialog open and closed. - Type tests: the themed slot test above.
Documentation and release plan
docs/components/date-picker.md: a "Use with GhostForm" section, error routing for the rangeGhostFieldpattern, and a registered example of a date range insideGhostFormwith a maximum stay. Note the flow in the field and form pages.- Changesets for
@ghostvue/vue(field, form, and picker behavior) and@ghostvue/themes(slot typing). - Compatibility: standalone pickers are unchanged. A picker inside a
GhostFieldnow marks the field invalid, shows its message inGhostFieldError, and movesaria-describedbyfrom the picker's description to the field error. Consumers who render sloterrorsbeside the field should remove that copy to avoid a duplicate. InsideGhostForm, rejected or uncommitted drafts now block submit. No public API is added or removed.