{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "date-picker",
  "type": "registry:ui",
  "title": "<ui-date-picker>",
  "description": "Carbon-style date picker following the WAI-ARIA APG \"Date Picker Dialog\" pattern. Each text box is a `<ui-date-field>` (date-field.ts) and the month grid a `<ui-calendar>` (calendar.ts); this element owns the state, the popover, typed-input rules, range rules and validation. Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [
    "lit@^3.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/calendar",
    "@kanok-ui/core-date",
    "@kanok-ui/core-overlay",
    "@kanok-ui/core-popup",
    "@kanok-ui/core-sheet",
    "@kanok-ui/shared-element",
    "@kanok-ui/shared-field",
    "@kanok-ui/shared-form-control",
    "@kanok-ui/shared-localize",
    "@kanok-ui/shared-position",
    "@kanok-ui/shared-quiet-focus",
    "@kanok-ui/shared-skeleton",
    "@kanok-ui/shared-slots",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/date-picker/calendar.styles.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/date-picker/calendar.styles.ts",
      "content": "export * from '../calendar/calendar.styles.ts';\n"
    },
    {
      "path": "src/primitives/date-picker/calendar.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/date-picker/calendar.ts",
      "content": "export * from '../calendar/calendar.ts';\n"
    },
    {
      "path": "src/primitives/date-picker/date-field.styles.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/date-picker/date-field.styles.ts",
      "content": "import { css } from 'lit';\n\n/** One date text box with its status icon, clear button and calendar button (ui-date-field). `--_toggle` comes from the host. */\nexport const dateFieldStyles = css`\n    :host {\n        display: block;\n    }\n\n    .field {\n        position: relative;\n    }\n\n    /* Carbon: a disabled date picker greys its label and helper (fieldTextStyles' :host(:disabled) needs a form-associated host) */\n    :host([disabled]) .label,\n    :host([disabled]) .helper {\n        color: var(--ui-ink-disabled);\n    }\n\n    input {\n        box-sizing: border-box;\n        width: 100%;\n        min-height: var(--_toggle);\n        margin: 0;\n        padding: 0 48px 0 var(--ui-space-md); /* Carbon: icon at 1rem from the end + spacing-09 inset, same on every size */\n        /* Carbon: an underline only; --ui-field-border (all sides), --ui-field-radius and --ui-field-background let a design outline the box */\n        border: var(--ui-field-border, none);\n        border-bottom: 1px solid var(--ui-field-underline-color, var(--ui-ink-subtle));\n        border-radius: var(--ui-field-radius, var(--ui-radius-none));\n        background-color: var(--ui-field-background, var(--ui-surface-1));\n        color: var(--ui-ink);\n        font: var(--ui-font-body-sm);\n        font-size: var(--ui-field-font-size, 14px);\n        letter-spacing: var(--ui-tracking-body);\n        outline: var(--ui-field-focus-width, 2px) solid transparent; /* the ring's width (Kanok: 1.5px, on the field's own border) */\n        outline-offset: calc(-1 * var(--ui-field-focus-width, 2px));\n        /* Carbon date-picker__input: all at fast-01 — its colours and outline (not the padding the × adds; Carbon has no ×) */\n        transition:\n            background-color var(--ui-duration-fast) var(--ui-easing),\n            border-color var(--ui-duration-fast) var(--ui-easing),\n            border-bottom-color var(--ui-duration-fast) var(--ui-easing),\n            color var(--ui-duration-fast) var(--ui-easing),\n            outline-color var(--ui-duration-fast) var(--ui-easing),\n            box-shadow var(--ui-duration-fast) var(--ui-easing);\n    }\n\n    input:hover:not(:disabled):not(:focus) {\n        border-color: var(--ui-field-hover-border-color, var(--ui-border-strong-1));\n        border-bottom-color: var(--ui-field-hover-border-color, var(--ui-border-strong-1));\n    }\n\n    input::placeholder {\n        color: var(--ui-ink-placeholder);\n        opacity: 1;\n    }\n\n    input:focus {\n        border-color: var(--ui-field-focus-border-color, inherit);\n        border-bottom-color: var(--ui-field-focus-border-color, var(--ui-ink-subtle));\n        outline-color: var(--ui-focus);\n        box-shadow: var(--ui-field-focus-halo, none); /* a design's halo outside the ring (Kanok: none) */\n    }\n\n    .invalid input {\n        outline-color: var(--ui-error);\n        box-shadow: var(--ui-field-invalid-halo, none); /* a design's error halo (Kanok: Pixiv's red ring) */\n    }\n\n    .invalid input:focus {\n        border-color: var(--ui-field-focus-border-color, inherit);\n        border-bottom-color: var(--ui-field-focus-border-color, var(--ui-ink-subtle));\n        outline-color: var(--ui-focus);\n        box-shadow: var(--ui-field-invalid-halo, var(--ui-field-focus-halo, none)); /* an error keeps its halo while focused (Kanok: Pixiv's red) */\n    }\n\n    input:disabled {\n        border-color: var(--ui-field-disabled-border-color, currentColor currentColor transparent);\n        color: var(--ui-ink-disabled);\n        cursor: not-allowed;\n    }\n\n    input:read-only:not(:disabled) {\n        background-color: var(--ui-field-readonly-background, transparent);\n        border-color: var(--ui-field-readonly-border-color, currentColor currentColor var(--ui-hairline));\n    }\n\n    .has-status input {\n        padding-inline-end: 72px;\n    }\n\n    /* × as in Carbon ComboBox (Carbon's DatePicker has none): end padding 70, 105 with a status icon */\n    .has-clear input {\n        padding-inline-end: 70px;\n    }\n\n    .has-status.has-clear input {\n        padding-inline-end: 105px;\n    }\n\n    .status {\n        position: absolute;\n        inset-block: 0;\n        inset-inline-end: 48px;\n        display: flex;\n        align-items: center;\n        pointer-events: none;\n    }\n\n    .has-clear .status {\n        inset-inline-end: 82px;\n    }\n\n    /* Carbon ComboBox geometry: a 24px × 45–69px from the end, a 1px border-subtle divider 41px from the end before the\n       calendar icon (16–32px), and one 74px from the end after a status icon */\n    .clear {\n        position: absolute;\n        inset-block: 0;\n        inset-inline-end: 45px;\n        display: flex;\n        align-items: center;\n        justify-content: center;\n        width: 24px;\n        height: 24px;\n        margin-block: auto;\n        padding: 0;\n        border: none;\n        background: transparent;\n        color: var(--ui-ink);\n        cursor: pointer;\n        border-radius: var(--ui-icon-control-radius, 0); /* round in a design that rounds icon controls (Kanok) */\n    }\n\n\n    .clear::after,\n    .has-status .clear::before {\n        position: absolute;\n        inset-block-start: 4px;\n        inline-size: 1px;\n        block-size: 16px;\n        background-color: var(--ui-border-subtle-2); /* border-subtle-01 */\n        content: '';\n    }\n\n    .clear::after {\n        inset-inline-start: 28px;\n    }\n\n    .has-status .clear::before {\n        inset-inline-start: -5px;\n    }\n\n    .clear:focus-visible {\n        outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n        outline-offset: -2px;\n    }\n\n    .clear svg {\n        display: block;\n        width: 16px;\n        height: 16px;\n        fill: currentColor;\n    }\n\n    /* Anchor for the OS picker: covers the field, invisible and inert */\n    .native {\n        position: absolute;\n        inset: 0;\n        width: 100%;\n        height: 100%;\n        margin: 0;\n        padding: 0;\n        border: 0;\n        opacity: 0;\n        pointer-events: none;\n    }\n\n    /*\n     * Carbon cds--date-picker__icon: a decorative 16px icon 16px from the end (48px box on every size), not a\n     * button — pointer-events none, so a click on it lands on the text box and opens the calendar.\n     */\n    .toggle {\n        position: absolute;\n        top: 0;\n        bottom: 0;\n        inset-inline-end: 0;\n        display: flex;\n        align-items: center;\n        justify-content: center;\n        width: 48px;\n        color: var(--ui-icon-primary, var(--ui-ink));\n        pointer-events: none;\n    }\n\n    input:disabled ~ .toggle {\n        color: var(--ui-icon-disabled, var(--ui-ink-disabled));\n    }\n\n    .toggle svg {\n        display: block;\n        width: 16px;\n        height: 16px;\n        fill: currentColor;\n    }\n\n    @media (forced-colors: active) {\n        input {\n            border: 1px solid FieldText;\n        }\n    }\n`;\n\n/** Carbon fluid date picker (measured on react.carbondesignsystem.com): text 32px down, calendar icon 35px down and 16px from the end. */\nexport const dateFieldFluidStyles = css`\n    :host([data-fluid]) input {\n        block-size: 64px;\n        min-height: 64px;\n        padding-block: 32px 13px;\n    }\n\n    :host([data-fluid]) .toggle {\n        inset-block: 23px auto;\n        block-size: 40px;\n    }\n\n    :host([data-fluid]) .clear {\n        inset-block: 31px auto;\n    }\n\n    :host([data-fluid]) .status {\n        --ui-fluid-icon-end: var(--ui-space-md);\n        inset-inline-end: 0;\n    }\n`;\n"
    },
    {
      "path": "src/primitives/date-picker/date-field.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/date-picker/date-field.ts",
      "content": "import { LitElement, html, nothing } from 'lit';\nimport { customElement, property, query } from 'lit/decorators.js';\nimport { fieldTextStyles, messageId, renderMessage, renderLabelText, renderStatusIcon, srOnlyStyles, fluidFieldStyles, markStatus, type FieldMessage } from '../shared/field.ts';\nimport { dateFieldStyles, dateFieldFluidStyles } from './date-field.styles.ts';\nimport { UiElement } from '../shared/element.ts';\n\n/**\n * One text box of ui-date-picker: label, text input, hidden OS date input, status icon, optional\n * clear button, calendar icon and message. The icon is decorative as in Carbon (`cds--date-picker__icon`,\n * pointer-events none): a click on it is a click on the text box, and it is not a Tab stop. Purely presentational — the picker owns the text,\n * the value and every rule; this element just renders what it is given and reports clicks.\n *\n * Native `input`, `keydown` and `pointerdown` events bubble out composed; the picker checks\n * `event.composedPath()[0] === field.input` to tell the text box from the × button. Focus moves\n * *inside* this shadow root (text box → ×) are invisible to the picker — the DOM\n * drops a focus event whose target and relatedTarget retarget to the same host — so the text box's\n * focus changes are re-dispatched as `ui-focus` / `ui-blur` with the real relatedTarget in `detail`.\n *\n * @fires ui-focus - detail `{ from }`: the text box gained focus from `from` (may be null)\n * @fires ui-blur - detail `{ next }`: the text box lost focus to `next` (may be null)\n * @fires ui-clear - The clear (×) button was pressed\n * @fires ui-native-change - detail `{ iso }`, the OS date picker chose a day\n * @csspart base - The field box\n * @csspart label - The label\n * @csspart input - The text box\n * @csspart clear-button - The × button\n * @csspart toggle - The calendar icon (decorative)\n */\n@customElement('ui-date-field')\nexport class UiDateField extends UiElement {\n    static override readonly shadowRootOptions: ShadowRootInit = {\n        ...LitElement.shadowRootOptions,\n        delegatesFocus: true,\n    };\n\n    /** `data-fluid` (set by the picker): Carbon `FluidDatePicker` box. */\n    static override readonly styles = [fieldTextStyles, srOnlyStyles, dateFieldStyles, fluidFieldStyles, dateFieldFluidStyles];\n\n    /** Id of the text input (the picker keeps ids unique across its fields). */\n    @property({ attribute: 'input-id' }) inputId = '';\n\n    /** Visible label text; the `label` slot replaces it when markup is needed. */\n    @property() label = '';\n\n    /** The date picker's name from outside (`aria-label`, a `<label for>`) while it has no `label`: an unseen label. */\n    @property({ attribute: false }) outsideName = '';\n\n    @property({ type: Boolean, attribute: 'hide-label' }) hideLabel = false;\n\n    /** The owner forwards a `label` slot with content, so the label row renders even when `label` is empty. */\n    @property({ type: Boolean, attribute: 'label-slotted' }) labelSlotted = false;\n\n    /** What the text box shows. */\n    @property() text = '';\n\n    /** Committed ISO value, for the hidden OS date input. */\n    @property() value = '';\n\n    /** Placeholder, e.g. วว/ดด/ปปปป. */\n    @property() pattern = '';\n\n    /** Format hint for screen readers when the helper line shows the author's text instead. */\n    @property() hint = '';\n\n    @property({ attribute: false }) message: FieldMessage | null = null;\n\n    @property({ type: Boolean, attribute: 'show-error' }) showError = false;\n\n    @property({ type: Boolean, attribute: 'show-clear' }) showClear = false;\n\n    /** The calendar is open for this field. */\n    @property({ type: Boolean }) expanded = false;\n\n    /** The calendar dialog the box opens (`aria-controls`; an element, since it lives in the picker's shadow root). */\n    @property({ attribute: false }) controls: Element | null = null;\n\n    /** Disables the control; a disabled `<fieldset>` ancestor does the same. Reflected: the label and helper grey out (see date-field.styles.ts). */\n    @property({ type: Boolean, reflect: true }) disabled = false;\n\n    /** Shows and submits the value but blocks changes. */\n    @property({ type: Boolean, reflect: true }) readonly = false;\n\n    /** Blocks form submission while the field is empty. */\n    @property({ type: Boolean }) required = false;\n\n    @property() min = '';\n\n    @property() max = '';\n\n    @property({ attribute: 'clear-label' }) clearLabel = '';\n\n    @query('input[type=\"text\"]') readonly input!: HTMLInputElement;\n\n    @query('.native') private readonly native!: HTMLInputElement;\n\n    /** Opens the OS date picker; false when the browser refuses (the caller then shows its own calendar). */\n    showNativePicker() {\n        try {\n            this.native.showPicker();\n            return true;\n        } catch {\n            return false;\n        }\n    }\n\n    /** Signals for the date picker that renders this field; not composed, so they stay inside its shadow root. */\n    private emit(name: string, detail?: unknown) {\n        this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true }));\n    }\n\n    private onNativeChange() {\n        if (this.native.value) this.emit('ui-native-change', { iso: this.native.value });\n    }\n\n    private onTextFocusOut(event: FocusEvent) {\n        this.emit('ui-blur', { next: event.relatedTarget as Node | null });\n    }\n\n    private renderClear() {\n        if (!this.showClear) return nothing;\n        return html`<button class=\"clear\" part=\"clear-button\" type=\"button\" tabindex=\"-1\" aria-label=${this.clearLabel} @click=${() => this.emit('ui-clear')}>\n            <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n                <path d=\"m12 4.7-.7-.7L8 7.3 4.7 4l-.7.7L7.3 8 4 11.3l.7.7L8 8.7l3.3 3.3.7-.7L8.7 8z\" />\n            </svg>\n        </button>`;\n    }\n\n    private renderLabel() {\n        // no label of its own: an unseen one with the picker's name from outside, if any\n        const unlabelled = !this.label && !this.labelSlotted;\n        if (unlabelled && !this.outsideName) return nothing;\n        return html`<label class=${this.hideLabel || unlabelled ? 'sr-only' : 'label'} part=\"label\" for=${this.inputId}>${renderLabelText(this.label, this.outsideName)}</label>`;\n    }\n\n    override updated() {\n        // element reflection reaches the picker's shadow root, which an id reference can't (browsers without it skip aria-controls)\n        if (this.input && 'ariaControlsElements' in this.input) this.input.ariaControlsElements = this.controls ? [this.controls] : null;\n    }\n\n    override render() {\n        const message = this.message;\n        markStatus(this, message);\n        const classes = [\n            this.showError ? 'invalid' : '',\n            message && message.kind !== 'helper' ? 'has-status' : '',\n            this.showClear ? 'has-clear' : '',\n        ]\n            .filter(Boolean)\n            .join(' ');\n        return html`\n            ${this.renderLabel()}\n            <div class=\"field ${classes}\" part=\"base\">\n                <input\n                    part=\"input\"\n                    id=${this.inputId}\n                    type=\"text\"\n                    inputmode=\"numeric\"\n                    autocomplete=\"off\"\n                    placeholder=${this.pattern}\n                    .value=${this.text}\n                    ?disabled=${this.disabled}\n                    ?readonly=${this.readonly}\n                    ?required=${this.required}\n                    role=\"combobox\"\n                    aria-haspopup=\"dialog\"\n                    aria-expanded=${this.expanded ? 'true' : 'false'}\n                    aria-invalid=${this.showError ? 'true' : 'false'}\n                    aria-describedby=${[messageId(this.inputId, message), this.hint ? `${this.inputId}-hint` : undefined].filter(Boolean).join(' ') || nothing}\n                    @focusin=${(e: FocusEvent) => this.emit('ui-focus', { from: e.relatedTarget as Node | null })}\n                    @focusout=${this.onTextFocusOut}\n                />\n                <input\n                    class=\"native\"\n                    type=\"date\"\n                    tabindex=\"-1\"\n                    aria-hidden=\"true\"\n                    .value=${this.value}\n                    min=${this.min || nothing}\n                    max=${this.max || nothing}\n                    @change=${this.onNativeChange}\n                />\n                ${this.hint ? html`<span class=\"sr-only\" id=\"${this.inputId}-hint\">${this.hint}</span>` : nothing}\n                <span class=\"status\">${renderStatusIcon(message)}</span>\n                ${this.renderClear()}\n                <span class=\"toggle\" part=\"toggle\" aria-hidden=\"true\">\n                    <svg viewBox=\"0 0 16 16\">\n                        <path\n                            d=\"M13 2h-2V1h-1v1H6V1H5v1H3a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1Zm0 11H3V6h10v7Zm0-8H3V3h2v1h1V3h4v1h1V3h2v2Z\"\n                        />\n                    </svg>\n                </span>\n            </div>\n            ${renderMessage(this.inputId, message)}\n        `;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-date-field': UiDateField;\n    }\n}\n"
    },
    {
      "path": "src/primitives/date-picker/date-picker-fields.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/date-picker/date-picker-fields.ts",
      "content": "import { property, query, state } from 'lit/decorators.js';\nimport { uid, barWhenDisabled, submitOnEnter, customErrorMessage, syncFluid } from '../shared/field.ts';\nimport { FormControlController } from '../shared/form-control.ts';\nimport {\n    checkDateField,\n    clampDate,\n    formatDate,\n    fromIso,\n    isThai,\n    isUnavailable,\n    parseDate,\n    toDisplayYear,\n    toIso,\n    type DateFormat,\n    type DateLimits,\n    type DateProblem,\n    type Era,\n} from '../../core/date.ts';\nimport { LocalizeController, getTranslation } from '../shared/localize.ts';\nimport type { UiDateField } from './date-field.ts';\nimport { UiElement } from '../shared/element.ts';\n\nexport type Field = 'start' | 'end';\n\n/** `container.contains(node)` across shadow boundaries (focus relatedTargets come un-retargeted in event detail). */\nexport function isWithin(node: Node | null, container: Node | null | undefined) {\n    if (!container) return false;\n    for (let n: Node | null = node; n; n = n.parentNode ?? (n as ShadowRoot).host ?? null) {\n        if (n === container) return true;\n    }\n    return false;\n}\n\ninterface FieldError {\n    flags: ValidityStateFlags;\n    message: string;\n}\n\n/** A restored FormData entry as text; files are not dates. */\nconst entryText = (entry: FormDataEntryValue | null) => (typeof entry === 'string' ? entry : '');\n\n/**\n * `<ui-date-picker>`'s fields and validation: its properties and state, the form API, each box's text and value, and\n * what makes a box invalid. `DatePickerPopup` adds the calendar's popover and sheet, `UiDatePicker` typing, picking and render.\n */\nexport class DatePickerFields extends UiElement {\n    /** Visible label text; the `label` slot replaces it when markup is needed. */\n    @property() label = '';\n\n    /** Keep the label for screen readers but don't show it. */\n    @property({ type: Boolean, attribute: 'hide-label' }) hideLabel = false;\n\n    /** Helper text under the field, shown while there is no error or warning. */\n    @property({ attribute: 'helper-text' }) helperText = '';\n\n    /** Error text shown while `invalid` or while the field fails validation. */\n    @property({ attribute: 'invalid-text' }) invalidText = '';\n\n    /** Forces the error state, e.g. after server-side validation. */\n    @property({ type: Boolean, reflect: true }) invalid = false;\n\n    /** Non-blocking warning; shown when there is no error. */\n    @property({ type: Boolean, reflect: true }) warn = false;\n\n    /** Text of the warning shown while `warn`. */\n    @property({ attribute: 'warn-text' }) warnText = '';\n\n    /** ISO yyyy-mm-dd (the start date in `range` mode). */\n    @property() value = '';\n\n    /** Reflected: form-associated elements submit under the `name` attribute. */\n    @property({ reflect: true }) name = '';\n\n    /** Two fields sharing one calendar (Carbon `datePickerType=\"range\"`). */\n    @property({ type: Boolean, reflect: true }) range = false;\n\n    /** Range mode: the end date, ISO yyyy-mm-dd. */\n    @property({ attribute: 'end-value' }) endValue = '';\n\n    /** Range mode: form entry name of the end date. Without it the range submits as one `name` entry `start/end`. */\n    @property({ attribute: 'end-name' }) endName = '';\n\n    /** Range mode: label of the end field. */\n    @property({ attribute: 'end-label' }) endLabel = '';\n\n    /** Earliest selectable date, ISO yyyy-mm-dd. */\n    @property() min = '';\n\n    /** Latest selectable date, ISO yyyy-mm-dd. */\n    @property() max = '';\n\n    @property() format: DateFormat = 'dd/mm/yyyy';\n\n    /**\n     * Locale for names, labels and messages. Defaults to the nearest `lang`: the element's own, an\n     * ancestor's, then `<html>`'s, else the browser language.\n     */\n    @property() locale = '';\n\n    /** Year era shown and typed: `be` (พ.ศ.) or `ce` (ค.ศ.). Defaults to `be` for Thai locales. */\n    @property() era: Era | '' = '';\n\n    /** 0 = Sunday … 6 = Saturday. */\n    @property({ type: Number, attribute: 'first-day' }) firstDay = 0;\n\n    /** Disables the control; a disabled `<fieldset>` ancestor does the same. */\n    @property({ type: Boolean, reflect: true }) disabled = false;\n\n    /** Blocks form submission while the field is empty. */\n    @property({ type: Boolean, reflect: true }) required = false;\n\n    /** Shows and submits the value but blocks changes. */\n    @property({ type: Boolean, reflect: true }) readonly = false;\n\n    /** Carbon `FluidDatePicker`: each date box is a 64px box with its label inside. `<ui-fluid-form>` sets it for every field inside. */\n    @property({ type: Boolean, reflect: true }) fluid = false;\n\n    /**\n     * Which picker opens: `auto` (default) = our calendar, in a bottom sheet on a phone; `custom` = our calendar as a\n     * popover on every device; `sheet` = in a bottom sheet on every device; `native` = the OS date picker.\n     */\n    @property() picker: 'auto' | 'custom' | 'sheet' | 'native' = 'auto';\n\n    /** Shows a clear button inside the field while it has text. */\n    @property({ type: Boolean, reflect: true }) clearable = false;\n\n    /** Adds a \"Today\" button under the calendar. */\n    @property({ type: Boolean, attribute: 'show-today' }) showToday = false;\n\n    /** Months to show side by side in the calendar, 1 to 12 (default 1, e.g. 2 for range picking). */\n    @property({ type: Number }) months = 1;\n\n    /** With more than one month, ‹ › turn a whole page (`months`) or one month (`single`): the calendar's `page-by`. */\n    @property({ attribute: 'page-by' }) pageBy: 'months' | 'single' = 'months';\n\n    /** Show the days of the months before and after (by default they are blank): the calendar's `show-outside-days`. */\n    @property({ type: Boolean, attribute: 'show-outside-days' }) showOutsideDays = false;\n\n    /** Extra `part` names for a calendar day, e.g. `holiday`: the calendar's `getDayParts`; the picker exports each name it returns, so `ui-date-picker::part(holiday)` styles those days. */\n    @property({ attribute: false }) getDayParts?: (date: Date) => string;\n\n    /** A column of ISO week numbers in the calendar: its `show-week-numbers`. */\n    @property({ type: Boolean, attribute: 'show-week-numbers' }) showWeekNumbers = false;\n\n    /** Weekday headings `narrow` or `short`: the calendar's `weekday-format`. */\n    @property({ attribute: 'weekday-format' }) weekdayFormat: 'narrow' | 'short' | '' = '';\n\n    /** The day the calendar marks as today, ISO (default the real today). */\n    @property() today = '';\n\n    /** Field height, same scale as ui-text-input. */\n    @property({ reflect: true }) size: 'sm' | 'md' | 'lg' = 'md'; // Carbon default (40px)\n\n    /**\n     * Property only. Return `true` for days that can't be chosen (weekends, holidays…), or a string\n     * to show that reason instead of the generic message.\n     */\n    @property({ attribute: false }) isDateDisabled?: (date: Date) => boolean | string;\n\n    @state() protected text = '';\n\n    @state() private endText = '';\n\n    /** Disabled, reset defaults, validation on submit and the name given from outside (shared by the form fields). */\n    protected readonly formControl = new FormControlController(this, { reveal: () => (this.touched = true), focus: () => this.focusInput(this.lastField), implicitSubmission: true });\n\n    @state() protected open = false;\n\n    /** Day that holds the calendar's roving focus. */\n    @state() protected focusDate = new Date();\n\n    @state() protected touched = false;\n\n    /** Range mode: the field the calendar is currently picking for. */\n    @state() protected activeField: Field = 'start';\n\n    /** The text box that last had focus: Tab / Shift+Tab / Esc in the calendar act relative to it (Carbon `_lastFocusInput`). */\n    protected lastField: Field = 'start';\n\n    /** Set while the picker itself moves focus back to a text box, so that focus doesn't re-open the calendar. */\n    protected returningFocus = false;\n\n    @query('ui-date-field[data-field=\"start\"]') protected readonly startField!: UiDateField;\n\n    @query('ui-date-field[data-field=\"end\"]') private readonly endField!: UiDateField | null;\n\n    @query('.fields') protected readonly fieldsEl!: HTMLElement;\n\n    /** Message from `setCustomValidity()`; '' = none. */\n    protected customValidityMessage = '';\n\n    /** Like `<input>.setCustomValidity()`: a non-empty message makes the field invalid (and is shown as its error once touched) until cleared with ''. */\n    setCustomValidity(message: string) {\n        this.customValidityMessage = message;\n        if (!this.hasUpdated) return;\n        this.syncValidity();\n        this.requestUpdate();\n    }\n    private readonly localize = new LocalizeController(this);\n    private readonly fieldId = uid('ui-date-picker');\n    protected defaultValue = '';\n    protected defaultEnd = '';\n    private lastSyncedValue: string | null = null;\n    private lastSyncedEnd: string | null = null;\n    /** A field whose typed date is already its value, not yet committed: the value `change` is judged against on commit. */\n    protected uncommitted: Partial<Record<Field, string>> = {};\n    /** Move DOM focus with focusDate only when the user is navigating the grid itself. */\n    protected focusInGrid = false;\n\n    /** Enter in the text box submits the form, like a native input. */\n    protected readonly onEnterKey = (event: KeyboardEvent) => submitOnEnter(this, event);\n\n    get form() {\n        return this.internals.form;\n    }\n\n    get validationMessage() {\n        return this.internals.validationMessage;\n    }\n\n    /** Whether the field takes part in constraint validation (not while disabled), as natively. */\n    get willValidate() {\n        return this.internals.willValidate;\n    }\n\n    /** The `<label>`s that point at this field. */\n    get labels() {\n        return this.internals.labels;\n    }\n\n    reportValidity() {\n        return this.formControl.reportValidity(this.internals);\n    }\n\n    get validity() {\n        return this.internals.validity;\n    }\n\n    checkValidity() {\n        return this.internals.checkValidity();\n    }\n\n    formResetCallback() {\n        this.value = this.defaultValue;\n        this.endValue = this.defaultEnd;\n        // Re-format the text boxes even when the values themselves are unchanged.\n        this.lastSyncedValue = null;\n        this.lastSyncedEnd = null;\n        this.uncommitted = {};\n        this.requestUpdate('value');\n        this.touched = false;\n    }\n\n    /** Back/forward cache and autofill hand the saved value(s) back here. */\n    formStateRestoreCallback(state: string | File | FormData | null) {\n        if (typeof state === 'string') this.value = state;\n        if (state instanceof FormData && this.endName) {\n            this.value = entryText(state.get(this.name));\n            this.endValue = entryText(state.get(this.endName));\n        } else if (state instanceof FormData) {\n            const [start = '', end = ''] = entryText(state.get(this.name)).split('/');\n            this.value = start;\n            this.endValue = end;\n        }\n    }\n    /** From an ancestor `<fieldset>`; kept apart so it never overwrites the author's `disabled`. */\n    formDisabledCallback(disabled: boolean) {\n        this.formControl.setFieldsetDisabled(disabled);\n    }\n\n    protected get isDisabled() {\n        return this.formControl.disabled;\n    }\n\n    protected get interactive() {\n        return !this.isDisabled && !this.readonly;\n    }\n\n    protected get resolvedLocale() {\n        return this.locale || this.localize.lang();\n    }\n\n    protected get resolvedEra(): Era {\n        if (this.era) return this.era;\n        return isThai(this.resolvedLocale) ? 'be' : 'ce';\n    }\n\n    protected get messages() {\n        return getTranslation(this.resolvedLocale).datePicker;\n    }\n\n    protected get pattern() {\n        return this.messages.pattern(this.format);\n    }\n\n    protected fmt(d: Date) {\n        return formatDate(d, this.format, this.resolvedEra);\n    }\n\n    private parse(text: string) {\n        return parseDate(text, this.format, this.resolvedEra);\n    }\n\n    private get minDate() {\n        return fromIso(this.min);\n    }\n\n    private get maxDate() {\n        return fromIso(this.max);\n    }\n\n    private get limits(): DateLimits {\n        return { min: this.min, max: this.max, isDateDisabled: this.isDateDisabled };\n    }\n\n    /** Outside min/max or refused by `isDateDisabled`. */\n    protected unavailable(d: Date) {\n        return isUnavailable(d, this.limits);\n    }\n\n    // ---- fields (start, and end in range mode) ----\n\n    protected get fields(): Field[] {\n        return this.range ? ['start', 'end'] : ['start'];\n    }\n\n    protected fieldText(f: Field) {\n        return f === 'start' ? this.text : this.endText;\n    }\n\n    protected setFieldText(f: Field, text: string) {\n        if (f === 'start') this.text = text;\n        else this.endText = text;\n    }\n\n    protected fieldValue(f: Field) {\n        return f === 'start' ? this.value : this.endValue;\n    }\n\n    protected fieldEl(f: Field): UiDateField | null {\n        return f === 'end' ? this.endField : this.startField;\n    }\n\n    /** The start text box; undefined before the first render. */\n    private get input(): HTMLInputElement | undefined {\n        return this.startField?.input;\n    }\n\n    /** Undefined before the first render (syncValidity runs in the first willUpdate). */\n    protected inputFor(f: Field): HTMLInputElement | undefined {\n        return (this.fieldEl(f) ?? this.startField)?.input;\n    }\n\n    protected fieldOf(event: Event): Field {\n        return (event.currentTarget as HTMLElement).dataset.field === 'end' ? 'end' : 'start';\n    }\n\n    /** Native events bubble out of the field's shadow root: only the text box itself is of interest. */\n    protected fromTextBox(event: Event, f: Field) {\n        return event.composedPath()[0] === this.inputFor(f);\n    }\n\n    protected fieldIdFor(f: Field) {\n        return f === 'start' ? this.fieldId : `${this.fieldId}-end`;\n    }\n\n    protected override willUpdate(changed: Map<string, unknown>) {\n        syncFluid(this, this.fluid);\n        // Like `<input type=date>`: a value that isn't a real yyyy-mm-dd date is sanitized to '' (never submitted as valid).\n        if (changed.has('value') && this.value && !fromIso(this.value)) this.value = '';\n        if (changed.has('endValue') && this.endValue && !fromIso(this.endValue)) this.endValue = '';\n        // External value changes (and reset) re-format the text boxes.\n        if (changed.has('value') && this.value !== this.lastSyncedValue) {\n            this.lastSyncedValue = this.value;\n            delete this.uncommitted.start;\n            this.syncText('start');\n        }\n        if (changed.has('endValue') && this.endValue !== this.lastSyncedEnd) {\n            this.lastSyncedEnd = this.endValue;\n            delete this.uncommitted.end;\n            this.syncText('end');\n        }\n        // Before render, so the error state below reflects this update.\n        this.syncValidity();\n    }\n\n    private syncText(f: Field) {\n        const d = fromIso(this.fieldValue(f));\n        this.setFieldText(f, d ? this.fmt(d) : '');\n        // Calendar already open: show the new date's month instead of the stale one.\n        if (d && this.open && this.activeField === f) {\n            this.focusInGrid = false; // an external change must not steal focus\n            this.focusDate = this.clampToRange(d);\n        }\n    }\n\n    // ---- validation ----\n\n    /** core/date's problem in this picker's words and validity flags (checked in the order a user would fix them). */\n    private describe(problem: DateProblem): FieldError {\n        const m = this.messages;\n        switch (problem.kind) {\n            case 'parse': {\n                const parseMessages = {\n                    era: () => m.badEra(String(toDisplayYear(new Date().getFullYear(), this.resolvedEra))),\n                    incomplete: () => m.incomplete,\n                    impossible: () => m.impossible,\n                    unparseable: () => m.badFormat(this.pattern),\n                };\n                return { flags: { badInput: true }, message: parseMessages[problem.error]() };\n            }\n            case 'required':\n                return { flags: { valueMissing: true }, message: m.required };\n            case 'min':\n                return { flags: { rangeUnderflow: true }, message: m.beforeMin(this.fmt(this.minDate as Date)) };\n            case 'max':\n                return { flags: { rangeOverflow: true }, message: m.afterMax(this.fmt(this.maxDate as Date)) };\n            case 'disabled':\n                return { flags: { customError: true }, message: problem.reason ?? m.dateDisabled };\n            default:\n                return { flags: { customError: true }, message: m.endBeforeStart };\n        }\n    }\n\n    /** The first thing wrong with one field, or null. */\n    protected fieldError(f: Field): FieldError | null {\n        const field = { text: this.fieldText(f), value: this.fieldValue(f), required: this.required, start: f === 'end' ? this.value : '', format: this.format, era: this.resolvedEra };\n        const problem = checkDateField(field, this.limits);\n        return problem ? this.describe(problem) : null;\n    }\n\n    private formValue(): string | FormData | null {\n        if (this.isDisabled) return null;\n        if (!this.range) return this.value; // an empty date still submits `name=`, like <input type=date>\n        const data = new FormData();\n        if (!this.endName) {\n            // Carbon cds-date-picker: one entry, the dates joined with '/' (ISO 8601 interval)\n            if (this.name) data.append(this.name, this.endValue ? `${this.value}/${this.endValue}` : this.value);\n            return data;\n        }\n        if (this.name) data.append(this.name, this.value);\n        data.append(this.endName, this.endValue);\n        return data;\n    }\n\n    private syncValidity() {\n        if (barWhenDisabled(this.internals, this.isDisabled)) return;\n        this.internals.setFormValue(this.formValue());\n        const customError = customErrorMessage(this.invalid, this.invalidText, this.customValidityMessage);\n        if (customError) {\n            this.internals.setValidity({ customError: true }, customError, this.input ?? undefined);\n            return;\n        }\n        for (const f of this.fields) {\n            const error = this.fieldError(f);\n            if (error) {\n                this.internals.setValidity(error.flags, error.message, this.inputFor(f) ?? undefined);\n                return;\n            }\n        }\n        this.internals.setValidity({});\n    }\n\n    /** Focus a text box without the focus opening the calendar. */\n    protected focusInput(f: Field) {\n        this.returningFocus = true;\n        try {\n            this.inputFor(f)?.focus();\n        } finally {\n            this.returningFocus = false;\n        }\n    }\n\n    /** The typed text, when it already reads as a complete date in the field's own format. */\n    protected typedFullDate(f: Field): Date | null {\n        const text = this.fieldText(f);\n        const result = this.parse(text);\n        return 'date' in result && this.fmt(result.date) === text ? result.date : null;\n    }\n\n    /** Commits typed text unless it already spells the committed value (so touching nothing isn't a \"touch\"). */\n    protected commitIfEdited(f: Field) {\n        const committed = fromIso(this.fieldValue(f));\n        const current = committed ? this.fmt(committed) : '';\n        if (this.fieldText(f) !== current || f in this.uncommitted) this.commitText(f);\n    }\n\n    /**\n     * Commit typed text (blur / Enter / calendar closing). A recovered date is re-formatted and committed even\n     * when it is out of range or disabled, so the field can say exactly why it is invalid; text that\n     * holds no date keeps its text with a format message. Nothing the user typed is discarded.\n     */\n    protected commitText(f: Field) {\n        this.touched = true;\n        const result = this.parse(this.fieldText(f));\n        if ('date' in result) {\n            this.setFieldText(f, this.fmt(result.date));\n            this.setValue(f, toIso(result.date));\n        } else {\n            this.setValue(f, '');\n        }\n        // Enter may submit the form before Lit's next update; make the form value current now.\n        this.syncValidity();\n    }\n\n    /** Sets a field's value; `change` fires when the committed value changes (`typing`: the value follows the text, the commit fires it). */\n    protected setValue(f: Field, next: string, typing = false) {\n        const committed = this.uncommitted[f] ?? this.fieldValue(f);\n        if (next !== this.fieldValue(f)) {\n            if (f === 'start') {\n                this.value = next;\n                this.lastSyncedValue = next;\n            } else {\n                this.endValue = next;\n                this.lastSyncedEnd = next;\n            }\n        }\n        if (typing) {\n            this.uncommitted[f] = committed;\n            return;\n        }\n        delete this.uncommitted[f];\n        if (next !== committed) this.dispatchEvent(new Event('change', { bubbles: true }));\n    }\n\n    protected clampToRange(d: Date) {\n        return clampDate(d, this.limits);\n    }\n}\n"
    },
    {
      "path": "src/primitives/date-picker/date-picker-popup.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/date-picker/date-picker-popup.ts",
      "content": "import { query, state } from 'lit/decorators.js';\nimport { syncFluid } from '../shared/field.ts';\nimport { markQuiet } from '../shared/quiet-focus.ts';\nimport { placeFloating } from '../shared/position.ts';\nimport {\n    fromIso,\n} from '../../core/date.ts';\nimport type { UiCalendar } from './calendar.ts';\nimport { outsidePress, trackAnchor } from '../../core/popup.ts';\nimport { closeOverlay, lockScroll, openOverlay, unlockScroll, type OverlayLayer } from '../../core/overlay.ts';\nimport { opensAsSheet, swipeToClose } from '../../core/sheet.ts';\nimport { DatePickerFields, isWithin, type Field } from './date-picker-fields.ts';\n\n\n/** `<ui-date-picker>`'s calendar popover and bottom sheet: opening, closing, placing, and focus inside it (on `DatePickerFields`). */\nexport class DatePickerPopup extends DatePickerFields {\n    @query('.calendar') protected readonly calendar!: HTMLElement;\n\n    @query('.sheet') private readonly sheetDialog!: HTMLDialogElement | null;\n\n    @query('.sheet-grip') private readonly sheetGrip!: HTMLElement | null;\n\n    /** The calendar opened (or last opened) in the bottom sheet rather than the popover (core/sheet opensAsSheet). */\n    @state() protected sheet = false;\n\n    @query('ui-calendar') protected readonly grid!: UiCalendar | null;\n\n\n\n    override connectedCallback() {\n        super.connectedCallback();\n        syncFluid(this, this.fluid);\n        this.requestUpdate(); // the date boxes take fluid from this render (moved into or out of a fluid form)\n        this.addEventListener('keydown', this.onEnterKey);\n        // first connection only: moving the element must not change what reset goes back to\n        this.formControl.captureDefaults(() => {\n            this.defaultValue = this.value;\n            this.defaultEnd = this.endValue;\n        });\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.removeEventListener('keydown', this.onEnterKey);\n        this.stopTracking();\n        this.stopSheet();\n    }\n\n    /**\n     * Only `picker=\"native\"`. `auto` used to mean the OS picker on touch screens, through showPicker() on a hidden date\n     * input; when a browser accepts that call and shows nothing (iOS can), nothing opened at all.\n     */\n    protected get useNativePicker() {\n        return this.picker === 'native' && 'showPicker' in HTMLInputElement.prototype;\n    }\n\n    /** That tap opened the calendar: the box must not take focus when the finger lifts (onInputTouchEnd). */\n    protected tapOpened = false;\n\n    // ---- calendar open / close ----\n\n    /** Opens on a fully typed date, else the field's value, else the start date, else today. */\n    protected openCalendar(focusGrid: boolean, f: Field = 'start') {\n        this.activeField = f;\n        this.sheet = opensAsSheet(this.picker);\n        this.focusInGrid = focusGrid || this.sheet; // a modal sheet holds focus: in its grid\n        const start = this.typedFullDate(f) ?? fromIso(this.fieldValue(f)) ?? fromIso(this.value) ?? new Date();\n        this.focusDate = this.clampToRange(start);\n        this.open = true;\n    }\n\n    private readonly reposition = () => this.position();\n\n    protected onOpenChanged() {\n        if (this.open && this.sheet) {\n            this.openSheet();\n            if (this.focusInGrid) void this.grid?.updateComplete.then(() => this.open && this.focusGridDay());\n            this.stopTracking();\n            this.stopOutside = outsidePress(document, this.onDocumentPointerDown); // a tap on the scrim closes\n        } else if (this.open) {\n            this.calendar.showPopover();\n            this.position();\n            // The grid renders in its own update; move focus once it has its day buttons.\n            if (this.focusInGrid) void this.grid?.updateComplete.then(() => this.open && this.focusGridDay());\n            // on its box while open (scrolling ancestors in any shadow root, layout shifts); a finger scroll neither\n            // closes it nor commits what was typed\n            this.stopTracking();\n            this.untrack = trackAnchor(this.startField.input, this.calendar, this.reposition);\n            this.stopOutside = outsidePress(document, this.onDocumentPointerDown);\n        } else {\n            if (this.calendar.matches(':popover-open')) this.calendar.hidePopover();\n            this.stopTracking();\n            this.stopSheet();\n            this.tapOpened = false;\n        }\n    }\n\n    /** The sheet in the overlay stack (Esc reaches the topmost layer; what opens over it knows a modal is open). */\n    private readonly sheetLayer: OverlayLayer = { escape: () => this.close(), modal: true };\n    private stopSwipe?: () => void;\n\n    private openSheet() {\n        const dialog = this.sheetDialog;\n        if (!dialog) return;\n        if (!dialog.open) dialog.showModal();\n        openOverlay(this.sheetLayer, globalThis);\n        lockScroll(this, document.documentElement);\n        this.stopSwipe?.();\n        this.stopSwipe = this.sheetGrip ? swipeToClose(this.sheetGrip, dialog, () => this.close()) : undefined;\n    }\n\n    /** Closes the sheet's dialog (the page behind is usable again) and lets go of the stack and the page. */\n    private stopSheet() {\n        if (this.sheetDialog?.open) this.sheetDialog.close();\n        this.stopSwipe?.();\n        this.stopSwipe = undefined;\n        closeOverlay(this.sheetLayer);\n        unlockScroll(this, document.documentElement);\n    }\n\n    /** The dialog's own close request (Esc, a close watcher): closed the picker's way, so typed text is committed. */\n    protected onSheetCancel(event: Event) {\n        event.preventDefault();\n        this.close();\n    }\n\n    private untrack?: () => void;\n    private stopOutside?: () => void;\n\n    private stopTracking() {\n        this.untrack?.();\n        this.stopOutside?.();\n        this.untrack = this.stopOutside = undefined;\n    }\n\n    /** Outside click closes (manual popover, so the toggle button can't re-open it on the same click). */\n    private readonly onDocumentPointerDown = (event: PointerEvent) => {\n        const path = event.composedPath();\n        if (!path.includes(this.calendar) && !path.includes(this.fieldsEl)) this.close();\n    };\n\n    /**\n     * Closes and commits any typed text that wasn't committed yet (flatpickr does the same from\n     * documentClick). Focus inside the calendar goes back to the text box that last had it (Carbon).\n     */\n    protected close() {\n        const active = this.shadowRoot?.activeElement;\n        const inCalendar = !!active && isWithin(active, this.calendar);\n        if (this.sheet) this.stopSheet(); // the page behind a modal sheet is inert: it goes first, then focus can return\n        if (inCalendar) this.focusInput(this.lastField); // before hiding, so focus never falls to the page\n        this.open = false;\n        for (const f of this.fields) this.commitIfEdited(f);\n    }\n\n    /** Set while a press inside the calendar is under way (a tap's mouse events and click come well after its touch). */\n    private pressInCalendar = false;\n    private pressTimer?: ReturnType<typeof setTimeout>;\n\n    protected readonly onCalendarPress = () => {\n        this.pressInCalendar = true;\n        clearTimeout(this.pressTimer);\n        this.pressTimer = setTimeout(() => (this.pressInCalendar = false), 700);\n    };\n\n    /** Focus on the grid's day; after a click or tap, without a keyboard ring in Kanok (shared/quiet-focus). */\n    protected focusGridDay() {\n        markQuiet(this.grid);\n        this.grid?.focusDay();\n    }\n\n    protected onCalendarFocusOut(event: FocusEvent) {\n        if (!this.open || (this.sheet && !this.sheetDialog?.open)) return; // closing: the sheet's dialog let focus go\n        const next = event.relatedTarget as Node | null;\n        if (!next) {\n            // Focus went nowhere: Safari gives a pressed button no focus (‹ › and the year steps, on an iPhone too), or it\n            // left the page (Tab on to the browser, another window). Neither is leaving the picker: a press or tap outside\n            // closes it (outsidePress), as Esc and a pick do. After a press inside, focus goes back to the grid's day.\n            if (this.pressInCalendar)\n                requestAnimationFrame(() => {\n                    const active = this.shadowRoot?.activeElement;\n                    if (this.open && !(active && isWithin(active, this.calendar))) this.focusGridDay();\n                });\n            return;\n        }\n        if (isWithin(next, this.calendar) || isWithin(next, this.fieldsEl)) return;\n        this.close();\n    }\n\n    private position() {\n        // Anchored on the text box itself (flatpickr does the same), so the calendar sits right under the input, over any helper text\n        placeFloating(this.startField.input, this.calendar, 'bottom-start', 0);\n    }\n\n    /** In the calendar Tab / Shift+Tab go round its controls (Cally, the APG dialog); Esc closes. */\n    protected onCalendarKeydown(event: KeyboardEvent) {\n        if (!this.open) return;\n        if (event.key === 'Escape') {\n            event.preventDefault();\n            event.stopPropagation();\n            this.close();\n            return;\n        }\n        if (event.key !== 'Tab' || this.sheet) return; // in the modal sheet, Tab goes round its own buttons\n        event.preventDefault();\n        this.cycleCalendarFocus(event.shiftKey);\n    }\n\n    /** Focus on the calendar's next Tab stop (‹, the year, ›, the day, Today), round from the last to the first. */\n    private cycleCalendarFocus(back: boolean) {\n        const stops = this.grid?.tabStops() ?? [];\n        if (!stops.length) return;\n        let at = stops.indexOf(this.grid?.shadowRoot?.activeElement as HTMLElement);\n        if (at < 0) at = back ? 0 : -1;\n        stops[(at + (back ? -1 : 1) + stops.length) % stops.length].focus();\n    }\n}\n"
    },
    {
      "path": "src/primitives/date-picker/date-picker-skeleton.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/date-picker/date-picker-skeleton.ts",
      "content": "import { html, css, nothing, svg } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { UiFieldSkeleton } from '../shared/skeleton.ts';\n\nconst calendar = svg`<path d=\"M13 2h-2V1h-1v1H6V1H5v1H3a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1Zm0 11H3V6h10v7Zm0-8H3V3h2v1h1V3h4v1h1V3h2v2Z\" />`;\n\n/**\n * Carbon `DatePickerSkeleton` (`cds-date-picker-input-skeleton`): the shape of a `<ui-date-picker>` while its data\n * loads — a 75×14 label bar, 8px, a 143.5px field bar; `range` draws two, 1px apart (Carbon React). Hidden from\n * assistive tech. `fluid` (Carbon `FluidDatePickerSkeleton`): a 64px box with the two bars and the calendar icon 16px\n * from the end and bottom; `range` splits it in halves with a 1px line between.\n *\n * @csspart label - Each label bar\n * @csspart field - Each field bar (fluid: the box)\n */\n@customElement('ui-date-picker-skeleton')\nexport class UiDatePickerSkeleton extends UiFieldSkeleton {\n    static override readonly styles = [\n        ...UiFieldSkeleton.styles,\n        css`\n            .inputs {\n                display: flex;\n                gap: 1px;\n            }\n\n            .input {\n                inline-size: 143.5px;\n            }\n\n            .fluid-half {\n                position: relative;\n                box-sizing: border-box;\n                block-size: 100%;\n            }\n\n            /* Carbon: each half 50% with the line inside the first */\n            .fluid-box.range .fluid-half {\n                flex: none;\n                inline-size: 50%;\n            }\n\n            .fluid-box.range {\n                display: flex;\n            }\n\n            .fluid-box.range .fluid-half:first-child {\n                border-inline-end: 1px solid var(--ui-skeleton-element);\n            }\n\n            .calendar {\n                position: absolute;\n                inset-block-end: var(--ui-space-md);\n                inset-inline-end: var(--ui-space-md);\n                inline-size: 16px;\n                block-size: 16px;\n                fill: var(--ui-icon-primary);\n            }\n        `,\n    ];\n\n    /** Start and end inputs. */\n    @property({ type: Boolean, reflect: true }) range = false;\n\n    private renderFluid() {\n        const half = html`<div class=\"fluid-half\"><span class=\"bone top\" part=\"label\"></span><span class=\"bone bottom\" part=\"value\"></span><svg class=\"calendar\" viewBox=\"0 0 16 16\">${calendar}</svg></div>`;\n        return html`<div class=\"fluid-box ${this.range ? 'range' : ''}\" part=\"field\">${half}${this.range ? half : nothing}</div>`;\n    }\n\n    override render() {\n        if (this.isFluid) return this.renderFluid();\n        const input = html`<div class=\"input\"><span class=\"bone label\" part=\"label\"></span><div class=\"bone field\" part=\"field\"></div></div>`;\n        return html`<div class=\"inputs\">${input}${this.range ? input : nothing}</div>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-date-picker-skeleton': UiDatePickerSkeleton;\n    }\n}\n"
    },
    {
      "path": "src/primitives/date-picker/date-picker.styles.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/date-picker/date-picker.styles.ts",
      "content": "import { css } from 'lit';\n\n/** Layout of ui-date-picker: field columns and the calendar popover shell. Field internals: date-field.styles.ts; grid: calendar.styles.ts. */\nexport const datePickerStyles = css`\n    :host {\n        --_toggle: var(--ui-field-height-lg, 48px);\n\n        display: block;\n        font-family: var(--ui-font-family);\n    }\n\n    :host([size='sm']) {\n        --_toggle: var(--ui-field-height-sm, 32px);\n    }\n\n    :host([size='md']) {\n        --_toggle: var(--ui-field-height-md, 40px);\n    }\n\n    .range-fields {\n        display: grid;\n        grid-template-columns: 1fr 1fr;\n        column-gap: 1px; /* Carbon: the two range inputs sit 1px apart */\n        align-items: start;\n    }\n\n    /* Carbon fluid range: the two boxes touch */\n    :host([data-fluid]) .range-fields {\n        column-gap: 0;\n    }\n\n    /* ---- calendar popover (the grid itself is <ui-calendar>) ---- */\n\n    .calendar {\n        position: absolute; /* document coordinates in the top layer: scrolls with the page, see position.ts */\n        inset: auto;\n        margin: 0;\n        box-sizing: border-box;\n        width: var(--ui-calendar-width, auto);\n        max-width: calc(100vw - 32px);\n        padding: var(--ui-calendar-padding, var(--ui-space-sm, 12px));\n        /* modern rounded card (Cally style) */\n        border: var(--ui-calendar-border, var(--ui-menu-border, 1px solid var(--ui-hairline)));\n        border-radius: var(--ui-calendar-radius, var(--ui-menu-radius, 16px));\n        background-color: var(--ui-overlay-background, var(--ui-surface-1)); /* a design can raise floating surfaces (--ui-overlay-background) */\n        --_ui-calendar-surface: var(--ui-overlay-background, var(--ui-surface-1)); /* the end-of-range day covers the range tint */\n        color: var(--ui-ink);\n        box-shadow: var(--ui-calendar-shadow, var(--ui-menu-shadow, 0 10px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.08)));\n    }\n\n    /* two months: as wide as both grids side by side; a viewport narrower than that wraps them, one under the other */\n    .calendar.multi-month {\n        width: max-content;\n    }\n\n    /* Carbon flatpickr-calendar.animate.open (fp-fade-in-down): fades in from 20px above, fast-02 with the entrance easing; it closes at once */\n    .calendar:popover-open {\n        animation: calendar-open var(--ui-duration-moderate) var(--ui-easing-entrance);\n    }\n\n    @keyframes calendar-open {\n        from {\n            opacity: 0;\n            transform: translateY(-20px);\n        }\n\n        to {\n            opacity: 1;\n            transform: none;\n        }\n    }\n\n    /*\n     * ---- the bottom sheet on a phone (picker=\"auto\" / \"sheet\"): a modal <dialog> holding the calendar ----\n     * Pinned to the bottom edge over a scrim, the calendar centred in a full-width panel with rounded top corners, its\n     * padding clear of the safe-area insets (a home indicator, a notch in landscape). A swipe on the grip moves it\n     * (core/sheet swipeToClose writes translate); let go short of closing, it springs back.\n     */\n    .sheet {\n        position: fixed;\n        inset: auto 0 0;\n        box-sizing: border-box;\n        width: 100%;\n        max-width: none;\n        max-height: 100%;\n        margin: 0;\n        padding: 0;\n        border: none;\n        background: transparent;\n        color: var(--ui-ink);\n        overflow: visible;\n        transition: translate var(--ui-duration-moderate) var(--ui-easing);\n    }\n\n    .sheet[data-dragging] {\n        transition: none;\n    }\n\n    .sheet::backdrop {\n        background-color: var(--ui-modal-scrim, rgb(22 22 22 / 0.5)); /* the modal's scrim */\n    }\n\n    /* Carbon's entrance: it rises from the bottom edge (moderate-02, entrance easing); it closes at once */\n    .sheet[open] {\n        animation: sheet-open var(--ui-duration-moderate-02) var(--ui-easing-entrance);\n    }\n\n    @keyframes sheet-open {\n        from {\n            transform: translateY(100%);\n        }\n    }\n\n    .sheet .calendar {\n        position: static;\n        display: flex;\n        flex-direction: column;\n        align-items: center;\n        width: 100%;\n        max-width: none; /* the popover's viewport margin would leave the sheet short of the right edge */\n        max-height: calc(100dvh - var(--ui-space-xl));\n        overflow-y: auto;\n        overscroll-behavior: contain;\n        padding: 0 max(var(--ui-space-xs), env(safe-area-inset-right)) calc(var(--ui-space-md) + env(safe-area-inset-bottom)) max(var(--ui-space-xs), env(safe-area-inset-left));\n        border-radius: var(--ui-sheet-radius, var(--ui-menu-radius, var(--ui-radius-none))) var(--ui-sheet-radius, var(--ui-menu-radius, var(--ui-radius-none))) 0 0;\n    }\n\n    /* the top bar: a grip (swiped down, the sheet follows the finger) and the × button, as the modal's */\n    .sheet-grip {\n        position: relative;\n        align-self: stretch;\n        display: flex;\n        justify-content: center;\n        flex: none;\n        height: 48px;\n        touch-action: none;\n        cursor: grab;\n    }\n\n    .sheet-handle {\n        width: 32px;\n        height: 4px;\n        margin-top: var(--ui-space-xs);\n        border-radius: 2px;\n        background-color: var(--ui-icon-secondary);\n    }\n\n    .sheet-close {\n        position: absolute;\n        top: 0;\n        inset-inline-end: 0;\n        display: grid;\n        place-items: center;\n        width: 48px;\n        height: 48px;\n        padding: 0;\n        border: none;\n        background: transparent;\n        color: var(--ui-ink);\n        cursor: pointer;\n        transition: background-color var(--ui-duration-moderate) var(--ui-easing);\n    }\n\n    .sheet-close:hover {\n        background-color: var(--ui-ghost-hover);\n    }\n\n    .sheet-close:focus-visible {\n        outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n        outline-offset: -2px;\n    }\n\n    .sheet-close svg {\n        width: 20px;\n        height: 20px;\n        fill: currentColor;\n    }\n\n    @media (forced-colors: active) {\n        input {\n            border: 1px solid FieldText;\n        }\n        .calendar {\n            border: 1px solid CanvasText;\n        }\n        .sheet-handle {\n            background-color: CanvasText;\n        }\n    }\n`;\n"
    },
    {
      "path": "src/primitives/date-picker/date-picker.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/date-picker/date-picker.ts",
      "content": "import { LitElement, html, nothing } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport { pickMessage, pickErrorText, hasData } from '../shared/field.ts';\nimport { SlotController } from '../shared/slots.ts';\nimport {\n    fromIso,\n    normalizeDigits,\n    pickInRange,\n    toIso,\n} from '../../core/date.ts';\nimport { getTranslation } from '../shared/localize.ts';\nimport { datePickerStyles } from './date-picker.styles.ts';\nimport './calendar.ts';\nimport './date-field.ts';\nimport { opensAsSheet } from '../../core/sheet.ts';\nimport { isWithin, type Field } from './date-picker-fields.ts';\nimport { DatePickerPopup } from './date-picker-popup.ts';\n\n\nexport type { DateFormat, Era } from '../../core/date.ts';\n\n/** Parts of each `<ui-date-field>`, re-exported plainly and as `start-*` / `end-*` in range mode. */\nconst FIELD_PARTS = ['base', 'label', 'input', 'clear-button', 'toggle', 'status-icon', 'helper-text', 'warning-text', 'warn-text', 'error-text', 'invalid-text'];\n\n/** The calendar's parts the picker exports (with the names `getDayParts` returns). */\nconst CALENDAR_PARTS = 'header, nav, heading, month-select, year-select, month-title, grid, day, selected, today, outside, disabled, disallowed, range-start, range-end, in-range, weeknumber, today-button';\n\n/**\n * Carbon-style date picker following the WAI-ARIA APG \"Date Picker Dialog\" pattern. Each text box is\n * a `<ui-date-field>` (date-field.ts) and the month grid a `<ui-calendar>` (calendar.ts); this element\n * owns the state, the popover, typed-input rules, range rules and validation.\n *\n * - Users can type the date or pick it from the calendar. Typed text is parsed the way Carbon /\n *   flatpickr do it: on blur or Enter the numbers are pulled out of whatever was typed\n *   (`s10/12/2026sdsd` → 10/12/2026). Unlike flatpickr, nothing is guessed or discarded silently:\n *   an incomplete date (`10/12`), an impossible one (`31/04`) or text with no date in it stays in\n *   the field with a message, and a date outside min/max or refused by `isDateDisabled` is kept with its own message\n *   (as Angular Material / MUI do). Text that already reads as a fully formatted, selectable date is\n *   committed at once while typing. Thai digits ๐–๙ become 0–9.\n * - `isDateDisabled` (property) greys out and refuses individual days, e.g. weekends or holidays;\n *   return a string instead of `true` to use it as the message.\n * - `clearable` adds a clear button inside the field. `size` sm / md / lg matches ui-text-input.\n * - `show-today` adds a \"Today\" button under the calendar (Carbon has none; opt-in, Ant / MUI style).\n * - `range` (Carbon `datePickerType=\"range\"`): two fields, start (`value` / `name` / `label`) and\n *   end (`end-value` / `end-name` / `end-label`), sharing one calendar. Without `end-name` the form gets one\n *   `name` entry `start/end` (Carbon cds-date-picker's range value); with it, two entries. As Cally's range: a pick\n *   keeps the calendar open for the end, with a preview on either side of the start (the pointer's day or the keyboard's;\n *   a refused day doesn't move it); picking an end before the start swaps the two; with a whole range chosen, a pick\n *   starts a new one; `change` fires once both ends are picked (or the calendar closes). A typed end before the start is\n *   kept and reported instead of swapped. Days between are highlighted.\n * - Keyboard and focus as Carbon (cds-date-picker / React DatePicker, tested key by key): the calendar\n *   opens when the text box gets focus (a click or Tab) and focus stays there, so typing continues and\n *   the calendar follows the typed date. ↓ from the text box moves into the calendar (the field's date, else\n *   today); Tab moves on to the next field, committing what was typed (Carbon: Tab goes into the calendar). In\n *   the calendar Tab and Shift+Tab go round its own controls, ‹, the month, the year, › and the day (Cally, the APG date\n *   picker dialog). The calendar icon is decorative (Carbon), not a button. Picking (the end, in a range) or Esc closes and returns\n *   focus to the text box.\n * - Calendar keys: ←/→ day, ↑/↓ week, Home/End week start/end, PageUp/PageDown month,\n *   Shift+PageUp/PageDown year, Enter/Space select, Esc close. While the end is picked the range\n *   preview follows the keyboard focus or the pointer, whichever moved last.\n * - The calendar header has Cally's month and year selects; the month shows its own days, in the weeks it needs\n *   (`show-outside-days`: six weeks with the days of the months before and after).\n * - Month changes are announced via a live region.\n * - Thai: `locale=\"th\"`, a `lang=\"th\"` attribute on the element or an ancestor, or `<html lang=\"th\">`\n *   gives Thai labels and messages (see shared/localize.ts; register other languages) and shows\n *   years in พ.ศ.; override with `era=\"ce\"`. Typed years follow the same era.\n * - Form-associated: submits `value` as ISO yyyy-mm-dd (always ค.ศ.); honours required / min / max.\n * - `picker=\"auto\"` (default) and `custom` open our calendar on every device (a tap on a touch screen opens it with a\n *   day focused, so no on-screen keyboard covers it; a second tap on the box types); `native` opens the OS date picker\n *   via showPicker(). On a phone (a touch screen under 42rem, core/sheet SHEET_MEDIA) `auto` opens the calendar in a\n *   bottom sheet: a modal `<dialog>` over a scrim (the page behind inert, focus kept inside, the page held still) that\n *   Esc, the × button, a swipe down on its grip or a tap on the scrim closes, padded clear of the safe-area insets.\n *   Focusing the box there doesn't open it (the box keeps focus, so you can type); a tap, ↓ or the toggle does.\n *   `custom` keeps the popover on phones too; `sheet` uses the sheet on every device.\n * - `readonly` keeps and submits the value but blocks typing and the calendar; `warn` shows a\n *   non-blocking warning.\n * - State on the host for app styles: `data-open` while the calendar is open, `data-show-error` /\n *   `data-show-warn` while an error / warning line shows (range: under either field)\n *   (e.g. `ui-date-picker[data-open]::part(base)`).\n *\n * @cssstate open - While its list or calendar is open (also `[data-open]`)\n * @cssstate show-error - While its error message shows (also `[data-show-error]`)\n * @cssstate show-warn - While its warning message shows (also `[data-show-warn]`)\n * @fires change - When a committed value (start or end) changes: blur, Enter, a calendar pick or clear.\n * @fires ui-range-start - Detail `{ date }`, `range`: a calendar pick began a range (its start), as Cally's `rangestart`; `change` waits for the end\n * @fires ui-range-end - Detail `{ date }`, `range`: a calendar pick finished a range (its end), as Cally's `rangeend`\n *   A typed date outside min/max is still committed, with the field reporting the range error.\n * @slot label - Label content with markup; the `label` attribute is the plain-text fallback\n * @slot helper-text - Helper text with markup (links, bold); overrides `helper-text`\n * @slot warn-text - Warning text shown while `warn`; overrides `warn-text`\n * @slot invalid-text - Error text shown while invalid; overrides `invalid-text`\n * @slot end-label - Label of the end field in range mode; overrides `end-label`\n * @csspart base - The field box (range: also `start-base` / `end-base`; same for every field part)\n * @csspart label - The label\n * @csspart input - The text box\n * @csspart clear-button - The × button\n * @csspart toggle - The calendar icon (decorative, as Carbon)\n * @csspart status-icon - The error / warning icon\n * @csspart helper-text - The helper line\n * @csspart warning-text - The warning line\n * @csspart warn-text - Same line as `warning-text` (named after the `warn-text` attribute / slot)\n * @csspart error-text - The error line\n * @csspart invalid-text - Same line as `error-text` (named after the `invalid-text` attribute / slot)\n * @csspart calendar - The popover shell (in the bottom sheet: the sheet's panel)\n * @csspart sheet - The bottom sheet `<dialog>` on a phone (`picker=\"auto\"` / `sheet`; style its scrim with `::part(sheet)::backdrop`)\n * @csspart sheet-grip - The sheet's top bar, which a swipe down closes\n * @csspart sheet-close - The sheet's × button\n * @csspart header - Calendar month / year row\n * @csspart nav - Previous / next month buttons\n * @csspart heading - The month and year selects' row\n * @csspart month-select - The month select (`<ui-calendar-select-month>`'s select)\n * @csspart year-select - The year select (`<ui-calendar-select-year>`'s select)\n * @csspart month-title - A month's name over its grid when several show\n * @csspart grid - The table of days\n * @csspart day - Each day button (its state also: `selected`, `today`, `outside`, `disabled`, `disallowed`, `range-start`, `range-end`, `in-range`, and the names `getDayParts` returns)\n * @csspart weeknumber - A week-number cell (`show-week-numbers`)\n * @csspart today-button - The optional \"Today\" button\n * @cssprop --ui-field-border - Border on every side of the box (default none: Carbon's underline only; Kanok: a 1px outline)\n * @cssprop --ui-field-disabled-border-color - Border colour when disabled (default: the underline transparent)\n * @cssprop --ui-field-readonly-border-color - Border colour when read-only (default: a hairline underline)\n * @cssprop --ui-field-radius - Corner radius of the box (default 0; Kanok: 6px)\n * @cssprop --ui-field-background - Fill of the box (default `--ui-surface-1`; Kanok: transparent)\n * @cssprop --ui-label-font - Font of the label (default `--ui-font-caption`; Kanok: 14px semibold)\n * @cssprop --ui-label-color - Colour of the label (default `--ui-ink-muted`; Kanok: `--ui-ink`)\n * @cssprop --ui-menu-radius / --ui-menu-border / --ui-menu-shadow - Corners, border and shadow of the calendar (the menu settings)\n * @cssprop --ui-sheet-radius - The bottom sheet's top corners (default: the menu radius)\n * @cssprop --ui-modal-scrim - The bottom sheet's scrim, as the modal's (default Carbon's overlay)\n * @cssprop --ui-calendar-day-radius - Corner radius of a day (default 0; Kanok: 6px)\n * @cssprop --ui-calendar-today-dot-radius - Corner radius of today's dot (default 0, a square; Kanok: 50%, a dot)\n * @cssprop --ui-field-readonly-background - The box's fill when read-only (default transparent; Kanok: a faint ink tint, so read-only reads as set and never weaker than disabled)\n * @cssprop --ui-fluid-background / --ui-fluid-gap - A fluid box's fill and the space under it (default the layer's fill, 0: boxes that touch; Kanok: transparent, 8px)\n * @cssprop --ui-icon-control-radius - Corners of its small icon buttons, their hover fill and ring (default 0; Kanok: round)\n * @cssprop --ui-focus-offset - `outline-offset` of the month arrows' and Today's focus ring (default -2px: inside; Kanok: 2px outside)\n */\n@customElement('ui-date-picker')\nexport class UiDatePicker extends DatePickerPopup {\n    static override hostStates: readonly string[] = ['open', 'show-error', 'show-warn'];\n\n    static readonly formAssociated = true;\n\n    static override readonly shadowRootOptions: ShadowRootInit = {\n        ...LitElement.shadowRootOptions,\n        delegatesFocus: true,\n    };\n\n    static override readonly styles = [datePickerStyles];\n\n    /** The names `getDayParts` returned so far: the calendar's parts the picker exports. */\n    @state() private dayPartNames: readonly string[] = [];\n\n    protected override updated(changed: Map<string, unknown>) {\n        if (changed.has('open')) this.onOpenChanged();\n        this.syncHostState();\n    }\n\n    /** Internal states as presence attributes on the host, so app styles can select them (same conditions as render). */\n    private syncHostState() {\n        const kinds = new Set(this.fields.map((f) => this.fieldStatus(f).message?.kind));\n        this.toggleAttribute('data-open', this.open);\n        this.toggleAttribute('data-show-error', kinds.has('error'));\n        this.toggleAttribute('data-show-warn', kinds.has('warn'));\n    }\n\n    // ---- text entry ----\n\n    private onInput(event: Event) {\n        const f = this.fieldOf(event);\n        const input = this.inputFor(f);\n        if (!input || !this.fromTextBox(event, f)) return;\n        const { value, selectionStart } = input;\n        const next = normalizeDigits(value);\n        if (next !== value) {\n            input.value = next;\n            if (selectionStart !== null) input.setSelectionRange(selectionStart, selectionStart);\n        }\n        this.setFieldText(f, next);\n        // Carbon's handleInput: text that already formats back to itself is selected immediately (`change` waits for the commit).\n        const typed = this.typedFullDate(f);\n        if (typed && !this.unavailable(typed)) {\n            this.setValue(f, toIso(typed), true);\n            if (this.open) this.focusDate = this.clampToRange(typed); // the grid follows, focus stays in the box\n        }\n    }\n\n\n    private onFieldKeydown(event: KeyboardEvent) {\n        if (event.key === 'Escape' && this.open) {\n            event.preventDefault();\n            event.stopPropagation();\n            this.close();\n            return;\n        }\n        const f = this.fieldOf(event);\n        if (!this.fromTextBox(event, f)) return;\n        if (event.key === 'ArrowDown') {\n            // ↓ goes into the calendar (and opens it); Tab moves on to the next field, so typing a date and tabbing on works\n            event.preventDefault();\n            if (!this.interactive) return;\n            if (this.open) {\n                this.activeField = f;\n                this.focusGridDay();\n            } else {\n                this.openCalendar(true, f);\n            }\n        } else if (event.key === 'Tab' && !event.shiftKey && this.open && f === this.fields.at(-1) && this.calendar.matches(':popover-open')) {\n            // the calendar follows the boxes in the Tab order: hidden now, the browser's Tab goes on past the picker (its blur commits)\n            this.calendar.hidePopover();\n        } else if (event.key === 'Tab' && event.shiftKey && this.open && f === 'start') {\n            this.close(); // Carbon: Shift+Tab out of the first box closes\n        } else if (event.key === 'Enter') {\n            this.commitText(f);\n            this.close();\n        }\n    }\n\n    private onInputPointerDown(event: PointerEvent) {\n        this.tapOpened = false;\n        if (!this.interactive || this.useNativePicker) return;\n        const f = this.fieldOf(event);\n        if (!this.fromTextBox(event, f)) return;\n        if (event.pointerType === 'mouse') {\n            if (this.open) this.activeField = f;\n            else this.openCalendar(false, f);\n            // the box goes inert under the sheet: its mousedown would take focus from the grid to the page\n            if (this.open && this.sheet) event.preventDefault();\n            return;\n        }\n        // A finger or a pen: a tap (not the start of a scroll) opens the calendar with a day focused, not the box, so no\n        // on-screen keyboard comes up over it (onInputPointerUp). With the calendar open, a tap on the box types.\n        // with the sheet, a tap on the box that already has focus (the sheet just closed onto it) types instead\n        const typing = opensAsSheet(this.picker) && !!this.fieldEl(f)?.matches(':focus-within');\n        this.tap = this.open || typing ? null : { id: event.pointerId, field: f };\n    }\n\n    /** A touch or pen press on a box that may become the tap that opens the calendar. */\n    private tap: { id: number; field: Field } | null = null;\n\n    private onInputPointerUp(event: PointerEvent) {\n        const tap = this.tap;\n        this.tap = null;\n        if (!tap || tap.id !== event.pointerId || this.open || !this.interactive) return;\n        this.tapOpened = true;\n        this.openCalendar(true, tap.field);\n    }\n\n    /** The finger scrolled the page instead: no tap. */\n    private onInputPointerCancel() {\n        this.tap = null;\n    }\n\n    /** Lifting the finger would focus the box (and raise the keyboard) after the tap opened the calendar: not then. */\n    private onInputTouchEnd(event: TouchEvent) {\n        if (!this.tapOpened) return;\n        this.tapOpened = false;\n        event.preventDefault();\n    }\n\n    /** Touch (or `picker=\"native\"`): a tap on the text box opens the OS date picker; the calendar icon is no button any more. */\n    private onInputClick(event: MouseEvent) {\n        const f = this.fieldOf(event);\n        if (!this.interactive || !this.useNativePicker || !this.fromTextBox(event, f)) return;\n        if (!this.openNativePicker(f) && !this.open) this.openCalendar(false, f);\n    }\n\n    /**\n     * Carbon: focusing a text box opens the calendar (focus stays in the box). Focus the picker puts back\n     * itself (after a pick, Esc, a form's invalid event) doesn't. Range: the box with focus is the one picked for.\n     */\n    private onInputFocusIn(event: CustomEvent<{ from: Node | null } | undefined>) {\n        const f = this.fieldOf(event);\n        this.activeField = f;\n        this.lastField = f;\n        if (this.tapOpened) {\n            // the tap that opened the calendar focused the box after all (a pen sends no touchend): the calendar keeps it\n            this.tapOpened = false;\n            void this.grid?.updateComplete.then(() => this.open && this.focusGridDay());\n            return;\n        }\n        if (this.open || this.returningFocus || !this.interactive || this.useNativePicker) return;\n        if (isWithin(event.detail?.from ?? null, this.calendar)) return;\n        if (opensAsSheet(this.picker)) return; // a sheet would take focus from the box: focus alone leaves it for typing\n        this.openCalendar(false, f);\n    }\n\n    /**\n     * Like flatpickr's onBlur: focus moving into the calendar doesn't commit (the user may be about to\n     * pick a day); any other blur commits what was typed. Native `change` isn't used because it also\n     * fires on that move into the calendar.\n     */\n    private onInputFocusOut(event: CustomEvent<{ next: Node | null }>) {\n        const f = this.fieldOf(event);\n        const next = event.detail.next;\n        if (isWithin(next, this.calendar)) return;\n        this.commitIfEdited(f);\n        if (!isWithin(next, this.fieldsEl)) this.open = false;\n    }\n\n    /** Returns false if the browser refused (then we fall back to our calendar). */\n    private openNativePicker(f: Field) {\n        return this.fieldEl(f)?.showNativePicker() ?? false;\n    }\n\n    /** The OS picker can't grey out `isDateDisabled` days, so its pick is committed and validated like typed text. */\n    private onNativeChange(event: CustomEvent<{ iso: string }>) {\n        const date = fromIso(event.detail.iso);\n        if (!date) return;\n        const f = this.fieldOf(event);\n        this.touched = true;\n        this.setFieldText(f, this.fmt(date));\n        this.setValue(f, toIso(date));\n    }\n\n    // ---- calendar interaction ----\n\n    private clear(event: Event) {\n        const f = this.fieldOf(event);\n        this.setFieldText(f, '');\n        this.setValue(f, '');\n        this.focusInput(f); // back to the box without popping the calendar open\n    }\n\n    private select(d: Date) {\n        if (this.unavailable(d)) return;\n        this.touched = true;\n        if (this.range) {\n            this.selectInRange(d);\n            return;\n        }\n        this.text = this.fmt(d);\n        this.setValue('start', toIso(d));\n        this.close();\n    }\n\n    /**\n     * Range rules (core/date pickInRange); each box whose value the pick set shows it. The first pick of a range shows its\n     * start at once but its `change` waits for the end (or the calendar closing), as Cally changes once both are picked.\n     */\n    private selectInRange(d: Date) {\n        const iso = toIso(d);\n        const next = pickInRange({ start: this.value, end: this.endValue, active: this.activeField }, iso);\n        for (const f of this.fields) {\n            const value = f === 'start' ? next.start : next.end;\n            if (value === this.fieldValue(f) && value !== iso && !(f in this.uncommitted)) continue;\n            const date = fromIso(value);\n            this.setFieldText(f, date ? this.fmt(date) : '');\n            this.setValue(f, value, !next.done);\n        }\n        if (next.done) this.close();\n        else this.activeField = next.active; // keep the calendar open to pick the end\n    }\n\n    // ---- render ----\n\n    private readonly slots = new SlotController(this);\n\n    /** One field's error flag and message line (error > warning > helper; the warning only under the start field). */\n    private fieldStatus(f: Field) {\n        const error = this.fieldError(f);\n        const showError = this.interactive && (this.invalid || (this.touched && (!!this.customValidityMessage || error !== null)));\n        const message = pickMessage({\n            showError,\n            errorText: pickErrorText(this.invalid, this.customValidityMessage, this.invalidText || error?.message || ''),\n            showWarn: this.warn && this.interactive && f === 'start',\n            warnText: this.warnText,\n            helperText: (f === 'start' ? this.helperText : '') || this.messages.hint(this.pattern),\n            slots: f === 'start' ? this.slots : undefined,\n        });\n        return { showError, message };\n    }\n\n    /** One column: a `<ui-date-field>` fed with this field's text, state and message. */\n    private renderField(f: Field) {\n        const m = this.messages;\n        const id = this.fieldIdFor(f);\n        const { showError, message } = this.fieldStatus(f);\n        const text = this.fieldText(f);\n        // the format hint is the default helper line; when the author's helper text replaces it, keep it for screen readers\n        const ownHelper = f === 'start' && (this.helperText !== '' || this.slots.has('helper-text'));\n        // class: Firefox shares one style between look-alike siblings and with it the first one's exportparts, so\n        // the end field matched ::part(start-input); a different class stops the sharing\n        return html`<ui-date-field\n            class=${f}\n            data-field=${f}\n            ?data-fluid=${hasData(this, 'fluid')}\n            exportparts=${FIELD_PARTS.map((p) => `${p}, ${p}:${f}-${p}`).join(', ')}\n            input-id=${id}\n            .label=${f === 'start' ? this.label : this.endLabel}\n            .outsideName=${f === 'start' ? this.formControl.fallbackName(this.label, this.internals) : ''}\n            ?label-slotted=${this.slots.has(f === 'start' ? 'label' : 'end-label')}\n            ?hide-label=${this.hideLabel}\n            .text=${text}\n            .value=${this.fieldValue(f)}\n            .pattern=${this.pattern}\n            .hint=${ownHelper ? m.hint(this.pattern) : ''}\n            .message=${message}\n            ?show-error=${showError}\n            ?show-clear=${this.clearable && this.interactive && text !== ''}\n            ?expanded=${this.open && this.activeField === f}\n            .controls=${this.calendar ?? null}\n            ?disabled=${this.isDisabled}\n            ?readonly=${this.readonly}\n            ?required=${this.required}\n            .min=${this.min}\n            .max=${this.max}\n            clear-label=${m.clear}\n            @input=${this.onInput}\n            @keydown=${this.onFieldKeydown}\n            @pointerdown=${this.onInputPointerDown}\n            @pointerup=${this.onInputPointerUp}\n            @pointercancel=${this.onInputPointerCancel}\n            @touchend=${this.onInputTouchEnd}\n            @click=${this.onInputClick}\n            @ui-focus=${this.onInputFocusIn}\n            @ui-blur=${this.onInputFocusOut}\n            @ui-clear=${this.clear}\n            @ui-native-change=${this.onNativeChange}\n        >${this.renderForwardedSlots(f)}</ui-date-field>`;\n    }\n\n    /**\n     * The picker's slots reach the matching column: `label` / `helper-text` / `warn-text` / `invalid-text` → start,\n     * `end-label` → end. A forwarding `<slot>` is rendered only when something is slotted: an empty forwarded slot still\n     * counts as \"assigned\" inside ui-date-field and would hide its attribute-text fallback (label, helper, error).\n     */\n    private renderForwardedSlots(f: Field) {\n        const forward = (from: string, to: string) => (this.slots.has(from) ? html`<slot name=${from} slot=${to}></slot>` : nothing);\n        if (f === 'end') return forward('end-label', 'label');\n        return html`${forward('label', 'label')}${forward('helper-text', 'helper-text')}${forward('warn-text', 'warn-text')}${forward('invalid-text', 'invalid-text')}`;\n    }\n\n    /** The calendar's `ui-range-start` / `ui-range-end` stay in the picker's shadow root: the picker reports them itself. */\n    private readonly forwardRangeEvent = (event: CustomEvent<{ date: Date }>) => {\n        event.stopPropagation();\n        this.dispatchEvent(new CustomEvent(event.type, { detail: { date: event.detail.date }, bubbles: true, composed: true }));\n    };\n\n    /** `getDayParts` for the calendar, noting each new name so the picker exports it. */\n    private readonly dayParts = (date: Date) => {\n        const names = this.getDayParts?.(date) ?? '';\n        const fresh = names.split(/\\s+/).filter((name, i, all) => name && !this.dayPartNames.includes(name) && all.indexOf(name) === i);\n        if (fresh.length) this.dayPartNames = [...this.dayPartNames, ...fresh];\n        return names;\n    };\n\n    private renderGrid() {\n        // the calendar's own change is stopped: the picker reports its change, the calendar's would reach the page as a second one\n        return html`<ui-calendar\n            exportparts=${[CALENDAR_PARTS, ...this.dayPartNames].join(', ')}\n            .value=${this.value}\n            .endValue=${this.range ? this.endValue : ''}\n            ?range=${this.range}\n            .activeField=${this.activeField}\n            .focusDate=${this.focusDate}\n            .min=${this.min}\n            .max=${this.max}\n            .isDateDisabled=${this.isDateDisabled}\n            .locale=${this.resolvedLocale}\n            .era=${this.resolvedEra}\n            .firstDay=${this.firstDay}\n            .months=${this.months}\n            .pageBy=${this.pageBy}\n            ?show-outside-days=${this.showOutsideDays}\n            .getDayParts=${this.getDayParts ? this.dayParts : undefined}\n            ?show-week-numbers=${this.showWeekNumbers}\n            .weekdayFormat=${this.weekdayFormat}\n            .today=${this.today}\n            ?show-today=${this.showToday}\n            @ui-pick=${(e: CustomEvent<{ date: Date }>) => this.select(e.detail.date)}\n            @change=${(e: Event) => e.stopPropagation()}\n            @ui-range-start=${this.forwardRangeEvent}\n            @ui-range-end=${this.forwardRangeEvent}\n            @ui-focus-change=${(e: CustomEvent<{ date: Date }>) => (this.focusDate = e.detail.date)}\n        ></ui-calendar>`;\n    }\n\n    /** The sheet's top bar: a grip to swipe it down, and the × button. */\n    private renderSheetGrip() {\n        return html`<div class=\"sheet-grip\" part=\"sheet-grip\">\n            <span class=\"sheet-handle\" aria-hidden=\"true\"></span>\n            <button class=\"sheet-close\" part=\"sheet-close\" type=\"button\" aria-label=${getTranslation(this.resolvedLocale).common.close} @click=${() => this.close()}>\n                <svg viewBox=\"0 0 32 32\" aria-hidden=\"true\">\n                    <path d=\"M24 9.4 22.6 8 16 14.6 9.4 8 8 9.4l6.6 6.6L8 22.6 9.4 24l6.6-6.6 6.6 6.6 1.4-1.4-6.6-6.6z\" />\n                </svg>\n            </button>\n        </div>`;\n    }\n\n    override render() {\n        const m = this.messages;\n        // several months, or a week-number column, need more than the one-month width\n        const popoverClass = this.months > 1 || this.showWeekNumbers ? 'calendar multi-month' : 'calendar';\n        // one template either way: the boxes stay the same elements (and keep focus) whichever way the calendar opens\n        const calendar = this.sheet\n            ? html`<dialog class=\"sheet\" part=\"sheet\" aria-label=${m.chooseDate} @cancel=${this.onSheetCancel}>\n                  <div\n                      class=\"calendar\"\n                      part=\"calendar\"\n                      @keydown=${this.onCalendarKeydown}\n                      @focusout=${this.onCalendarFocusOut}\n                      @touchstart=${this.onCalendarPress}\n                      @pointerdown=${this.onCalendarPress}\n                      @mousedown=${this.onCalendarPress}\n                  >\n                      ${this.renderSheetGrip()} ${this.open ? this.renderGrid() : nothing}\n                  </div>\n              </dialog>`\n            : html`<div\n                  class=${popoverClass}\n                  part=\"calendar\"\n                  popover=\"manual\"\n                  role=\"dialog\"\n                  aria-label=${m.chooseDate}\n                  @keydown=${this.onCalendarKeydown}\n                  @focusout=${this.onCalendarFocusOut}\n                  @touchstart=${this.onCalendarPress}\n                  @pointerdown=${this.onCalendarPress}\n                  @mousedown=${this.onCalendarPress}\n              >\n                  ${this.open ? this.renderGrid() : nothing}\n              </div>`;\n        return html`\n            <div class=\"fields ${this.range ? 'range-fields' : ''}\">${this.fields.map((f) => this.renderField(f))}</div>\n            ${calendar}\n        `;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-date-picker': UiDatePicker;\n    }\n}\n"
    }
  ]
}
