Skip to content
Brok UI

Loading…

No results

Date Range Picker

Open source

One field that opens a two-month range calendar with presets and a hovered span preview; start and end post as {name}_start / {name}_end, the field shows the range in the chosen display format, and min/max/disabled days pass to the calendar.

Version
v1.3.3
Stability
stable
License
MIT
Related
Date Picker
Calendar
Time Picker

Preview

Posts stay_start and stay_end as ISO dates.

previews.components.date-range-picker.default.blade.php Blade
<div class="mx-auto w-full max-w-sm">
    <x-ui.field name="stay" label="Stay" hint="Posts stay_start and stay_end as ISO dates.">
        <x-ui.date-range-picker name="stay" start-value="2026-09-22" end-value="2026-09-27" />
    </x-ui.field>
</div>

Installation

terminal
php artisan ui:add date-range-picker

Note

This component ships an Alpine behavior module at resources/js/ui/date-range-picker.js. Import it once from your bundle so it registers on alpine:init:

resources/js/ui/index.js JS
import './date-range-picker.js';

Registry contract

php artisan ui:add date-range-picker writes only the files below. The CLI validates each file hash before writing and asks before it replaces a local change, unless you pass --force.

  • blade resources/views/components/ui/date-range-picker/date-range-picker.blade.php
  • js resources/js/ui/date-range-picker.js
Registry dependencies
button calendar
Packages
composer: jml/brok:^0.2
npm: alpinejs

Use with AI

A brief for your coding agent: install command, usage, props, guidance and the rules. Copy it, or open a prompt about this component in an assistant.

date-range-picker.md
# Brok UI: Date Range Picker (`date-range-picker`)

One field that opens a two-month range calendar with presets and a hovered span preview; start and end post as {name}_start / {name}_end, the field shows the range in the chosen display format, and min/max/disabled days pass to the calendar.

Brok UI is a Laravel Blade component registry. Installed components are plain Blade files the app owns.

## Install

```bash
php artisan ui:add date-range-picker
```

## Usage

```blade
<div class="mx-auto w-full max-w-sm">
    <x-ui.field name="stay" label="Stay" hint="Posts stay_start and stay_end as ISO dates.">
        <x-ui.date-range-picker name="stay" start-value="2026-09-22" end-value="2026-09-27" />
    </x-ui.field>
</div>
```

## Props

- `name` (string, default `range`) — Base name for the hidden start/end inputs (defaults to {name}_start/{name}_end).
- `startName` (mixed|null, default `null`) — Overrides the hidden start-input name.
- `endName` (mixed|null, default `null`) — Overrides the hidden end-input name.
- `startValue` (string, default ``) — Initial selected ISO start date.
- `endValue` (string, default ``) — Initial selected ISO end date.
- `locale` (mixed|null, default `null`) — Intl locale override.
- `firstDay` (int, default `1`) — First weekday shown in the calendar (0 = Sunday).
- `placeholder` (string, default `Pick a date range`) — Field text shown with no range selected.
- `display` (string, default `medium`) — How the range reads in the field: an Intl style or a token pattern, as in date-picker.
- `presets` (mixed|null, default `null`) — Custom preset list ([['label' => ..., 'start' => iso, 'end' => iso]]) that replaces the built-in set; pass [] for none.
- `min` (mixed|null, default `null`) — ISO date lower bound, passed to the calendar.
- `max` (mixed|null, default `null`) — ISO date upper bound, passed to the calendar.
- `disabled` (array, default `[]`) — ISO dates and/or weekday numbers to disable, passed to the calendar.
- `months` (int, default `2`) — Consecutive months shown in the calendar (1-3).
- `weekNumbers` (bool, default `false`) — Shows the ISO week-number column.
- `startPlaceholder` (mixed|null, default `null`) — Declared for a future split start/end field label; not read by the current single combined-field markup.
- `endPlaceholder` (mixed|null, default `null`) — Declared for a future split start/end field label; not read by the current single combined-field markup.
- `invalid` (bool, default `false`) — Forces the invalid state (aria-invalid and the invalid border); the shared error bag also sets it for a message on the name or on either posted start/end key.

## Use when

- Use when date, time, or bounded-value context helps users enter valid values faster and with fewer errors.
- Collecting a start and end date in one field, such as a report or booking date range.
- Wanting built-in quick presets (Today, Last 7 days, This month, …) alongside the calendar.

## Avoid when

- Do not force a picker when expert users can type the value faster and validation is straightforward.
- Collecting a single date; use date-picker instead.

## Anti-patterns

- Forcing a picker when typing is faster

## Rules

- Use the `<brok:date-range-picker>` tag (or `<x-ui.date-range-picker>`) in Blade; do not rewrite the component.
- Prefer the documented props and variants over utility-class overrides; when a utility must win, use the `!` important modifier.
- Use semantic design tokens (`bg-primary`, `text-muted-foreground`), never raw colour utilities.
- Keep the `data-slot` attributes; they are the styling and test hooks.

## Links

- Docs: https://brokui.dev/docs/components/date-range-picker
- Registry JSON (files, props, contract): https://brokui.dev/r/open/date-range-picker.json

Working in Claude Code, Cursor or Codex? Give the agent the whole registry through the MCP server or the Brok UI skill.

Examples

invalid.blade.php Blade
@php
    // Simulate a failed $request->validate() round-trip: seed the shared $errors
    // bag the way a redirect-back (or Livewire) does, then restore the previous
    // bag after this preview so later renders on the page stay clean.
    $previousErrors = view()->shared('errors');
    $previewErrors = new \Illuminate\Support\ViewErrorBag;
    $previewErrors->put('default', new \Illuminate\Support\MessageBag([
        'period' => [__('Choose a reporting period.')],
        'stay_end' => [__('A stay can be at most 14 nights.')],
    ]));
    view()->share('errors', $previewErrors);
@endphp

<div class="mx-auto flex w-full max-w-sm flex-col gap-6">
    {{-- An error on the field name: the field prints it, the trigger points at it. --}}
    <x-ui.field name="period" label="{{ __('Reporting period') }}" hint="{{ __('Posts period_start and period_end.') }}">
        <x-ui.date-range-picker />
    </x-ui.field>

    {{-- An error on the posted end key: the picker prints it under the trigger. --}}
    <x-ui.field name="stay" label="{{ __('Stay') }}">
        <x-ui.date-range-picker start-value="2026-09-01" end-value="2026-09-30" />
    </x-ui.field>
</div>

@php
    view()->share('errors', $previousErrors);
@endphp

API

manifest knowledge + registry-derived coverage

Props

Props accepted by this component: name, type, default value and description.
Prop Type Default Description
name string range Base name for the hidden start/end inputs (defaults to {name}_start/{name}_end).
startName mixed | null null Overrides the hidden start-input name.
endName mixed | null null Overrides the hidden end-input name.
startValue string Initial selected ISO start date.
endValue string Initial selected ISO end date.
locale mixed | null null Intl locale override.
firstDay int 1 First weekday shown in the calendar (0 = Sunday).
placeholder string Pick a date range Field text shown with no range selected.
display string medium How the range reads in the field: an Intl style or a token pattern, as in date-picker.
presets mixed | null null Custom preset list ([['label' => ..., 'start' => iso, 'end' => iso]]) that replaces the built-in set; pass [] for none.
min mixed | null null ISO date lower bound, passed to the calendar.
max mixed | null null ISO date upper bound, passed to the calendar.
disabled array [] ISO dates and/or weekday numbers to disable, passed to the calendar.
months int 2 Consecutive months shown in the calendar (1-3).
weekNumbers bool false Shows the ISO week-number column.
startPlaceholder mixed | null null Declared for a future split start/end field label; not read by the current single combined-field markup.
endPlaceholder mixed | null null Declared for a future split start/end field label; not read by the current single combined-field markup.
invalid bool false Forces the invalid state (aria-invalid and the invalid border); the shared error bag also sets it for a message on the name or on either posted start/end key.

Slots

  • default — Not used by this component; present for attribute-bag compatibility.
  • x-ui.date-range-picker.date-range-picker — Installed subcomponent from the registry item.

Data slots

Stable hooks for CSS overrides and browser tests.

date-range-picker date-range-picker-content date-range-picker-error date-range-picker-presets date-range-picker-trigger

Behavior

  • A button-styled field opens a two-month range calendar (chrome=false) with a preset list; picking a start then an end previews the hovered span, fills {name}_start/{name}_end hidden inputs, and Apply closes the popover.
  • Presets can be replaced via the presets prop or disabled entirely by passing an empty array.
  • Validation: a message in the shared error bag for the name, or for the posted start/end keys ({name}_start/{name}_end, or the dotted form of bracketed start-name/end-name such as period.start), sets aria-invalid on the trigger and swaps its border to the invalid state; old() refills the range after a redirect-back. Inside a named field the trigger takes the field name as its id, and a start/end message the field cannot see prints under the trigger.
  • Installs a JavaScript behavior module when the registry item includes resources/js/ui files.
  • Declares registry capability flags: a11y, responsive, rtl, darkMode, localized, interactive, behaviorTest.

Guidance

Date and time picker

Choose a date, time, or bounded contextual value.

Use when

  • Use when date, time, or bounded-value context helps users enter valid values faster and with fewer errors.
  • Collecting a start and end date in one field, such as a report or booking date range.
  • Wanting built-in quick presets (Today, Last 7 days, This month, …) alongside the calendar.

Avoid when

  • Do not force a picker when expert users can type the value faster and validation is straightforward.
  • Collecting a single date; use date-picker instead.

Use instead

  • Direct typed entry with validation

Anti-patterns

  • Forcing a picker when typing is faster
Anatomy
root date-range-picker-trigger date-range-picker-content date-range-picker-presets date-range-picker-error
Theming hooks
field-trigger

Accessibility

WCAG 2.2 AA Keyboard focus-visible RTL-ready Localized labels Dark mode
Keyboard
Escape
Focus
managed
  • The trigger exposes aria-haspopup="dialog" and aria-expanded; presets are grouped under role="group" and the popover closes on Escape or click-outside, returning focus to the trigger.
  • Inside a named field the trigger is labelled by the field label and aria-describedby lists the field hint ({name}-description), the field error ({name}-error) and any start/end error ({name}-range-error); a consumer aria-describedby moves to the trigger. A standalone picker sets aria-invalid only and never references missing nodes.
  • Semantic HTML and a stable data-slot attribute for styling and scripting hooks.
  • Focus-visible rings use the ring token, so keyboard focus is always visible.
  • Disabled and invalid states are conveyed to assistive tech, not by color alone.
  • Targets WCAG 2.2 AA; verify contrast in light, dark, admin and customer surfaces in the preview.
  • Labels go through __() and layout uses logical properties (ms-*, text-start), so it mirrors under dir="rtl" — flip the preview to RTL to confirm.
  • Dark mode uses the same semantic tokens under the dark class; high contrast follows forced-color system tokens.

Livewire

Needs wire:key

Add a stable wire:key when Livewire can reorder this interactive component.

livewire-component.blade.php Blade
<div wire:key="date-range-picker-{{ $record->id }}">
    <div class="mx-auto w-full max-w-sm">
        <x-ui.field name="stay" label="Stay" hint="Posts stay_start and stay_end as ISO dates.">
            <x-ui.date-range-picker name="stay" start-value="2026-09-22" end-value="2026-09-27" />
        </x-ui.field>
    </div>
</div>

Validation

Validation support: laravel-error-bag. Keep the error message connected with aria-describedby.

livewire-form.blade.php Blade
<form wire:submit="save" class="space-y-2">
    <brok:date-range-picker
        wire:model="value"
        :aria-invalid="$errors->has('value') ? 'true' : 'false'"
        aria-describedby="value-error"
    />

    @error('value')
        <p id="value-error" role="alert">{{ $message }}</p>
    @enderror

    <brok:button type="submit" wire:loading.attr="disabled">
        <span wire:loading.remove>Save</span>
        <span wire:loading>Saving…</span>
    </brok:button>
</form>

Source

The exact, editable files ui:add writes into your app. Previews render this same code; there are no preview-only components.

resources/views/components/ui/date-range-picker/date-range-picker.blade.php Blade
{{-- A wrapping <x-ui.field name="…"> shares its name, label and hint down via
     @aware, so this composite self-wires old()/aria-invalid/aria-describedby off
     the shared $errors bag. The field context is read before @props takes the
     picker's own `name`: without an own name an aware name comes from a field;
     with one, the field's label or hint (props the picker lacks) reveals it. A
     standalone picker never points aria-describedby at nodes that do not exist. --}}
@aware([
    'name' => null,
    'label' => null,
    'hint' => null,
])

@php
    $fieldLabel = $attributes->has('label') ? null : ($label ?? null);
    $fieldHint = $attributes->has('hint') ? null : ($hint ?? null);
    $insideField = $attributes->has('name') ? filled($fieldLabel) || filled($fieldHint) : filled($name ?? null);
@endphp

{{--
    Date Range Picker — one field that opens a two-month calendar in range mode
    with presets. Picking a start then an end (the pointer previews the span)
    fills two hidden inputs (`{name}_start` / `{name}_end` by default), so a
    range posts in an ordinary form. Localized, RTL-safe via logical properties.

    Props:
    - display: how the range reads in the field (Intl style or a pattern, as in
      date-picker); the hidden values stay ISO.
    - presets: [['label' => 'Last 7 days', 'start' => iso, 'end' => iso]] to
      replace the built-in set (today, yesterday, last 7 / 30 days, this and
      last month); pass [] for none.
    - min / max / disabled / months / week-numbers: passed to the calendar.
    - invalid: forces the invalid state; the shared error bag also sets it when
      it has a message for the name or for either posted start/end key.
--}}
@props([
    'name' => 'range',
    'startName' => null,
    'endName' => null,
    'startValue' => '',
    'endValue' => '',
    'locale' => null,
    'firstDay' => 1,
    'placeholder' => 'Pick a date range',
    'display' => 'medium',
    'presets' => null,
    'min' => null,
    'max' => null,
    'disabled' => [],
    'months' => 2,
    'weekNumbers' => false,
    'startPlaceholder' => null,
    'endPlaceholder' => null,
    'invalid' => false,
])

@php
    $styles = require base_path(config('ui.component_path', 'resources/views/components/ui').'/_styles.php');
    $trigger = $styles['field-trigger'];
    $fieldName = $insideField ? $name : null;
    $startName = $startName ?? (filled($name) ? $name.'_start' : null);
    $endName = $endName ?? (filled($name) ? $name.'_end' : null);

    // Validation keys use dots where the posted names use brackets
    // (`period[start]` validates as `period.start`).
    $errorKey = fn ($posted) => filled($posted) ? rtrim(str_replace(['[', ']'], ['.', ''], (string) $posted), '.') : null;
    $startKey = $errorKey($startName);
    $endKey = $errorKey($endName);

    // old() repopulates the range after a failed redirect-back.
    $resolvedStart = filled($startKey) ? old($startKey, $startValue) : $startValue;
    $resolvedEnd = filled($endKey) ? old($endKey, $endValue) : $endValue;

    // The shared error bag marks the field invalid for a message on the name
    // itself or on either posted key; the wrapping field prints the name's
    // message, this component prints the start/end ones it cannot see.
    $bag = ($errors ?? null) instanceof \Illuminate\Support\ViewErrorBag ? $errors : null;
    $hasNameError = $bag && filled($name) && $bag->has($name);
    $partMessages = $bag
        ? collect([$startKey, $endKey])->filter()->unique()->reject(fn ($key) => $key === $name)
            ->map(fn ($key) => $bag->first($key))->filter()->unique()->values()
        : collect();
    $isInvalid = (bool) $invalid || $hasNameError || $partMessages->isNotEmpty();
    $partErrorId = filled($fieldName) && $partMessages->isNotEmpty() ? $fieldName.'-range-error' : null;

    $describedBy = collect(preg_split('/\s+/', trim((string) $attributes->get('aria-describedby', ''))) ?: [])
        ->when(filled($fieldName) && filled($fieldHint), fn ($ids) => $ids->push($fieldName.'-description'))
        ->when(filled($fieldName) && $hasNameError, fn ($ids) => $ids->push($fieldName.'-error'))
        ->push($partErrorId)
        ->filter()
        ->unique()
        ->implode(' ');
    $months = max(1, min(3, (int) $months));
    $listId = 'date-range-presets-'.\Illuminate\Support\Str::random(6);

    // Built-in presets are computed client-side (today is the browser's day).
    $presetList = $presets === null
        ? [
            ['label' => __('Today'), 'key' => 'today'],
            ['label' => __('Yesterday'), 'key' => 'yesterday'],
            ['label' => __('Last 7 days'), 'key' => 'last-7'],
            ['label' => __('Last 30 days'), 'key' => 'last-30'],
            ['label' => __('This month'), 'key' => 'this-month'],
            ['label' => __('Last month'), 'key' => 'last-month'],
        ]
        : array_values(array_filter((array) $presets, fn ($p) => is_array($p) && filled($p['label'] ?? null)));
@endphp

<div
    x-data="uiDateRangePicker({ start: @js($resolvedStart), end: @js($resolvedEnd), locale: @js($locale), display: @js((string) $display) })"
    {{-- Modelable: `x-model` (Alpine) and `wire:model` (Livewire binds through
         the same x-model contract) attach to the root. Inert without either. --}}
    x-modelable="model"
    data-slot="date-range-picker"
    @if ($isInvalid) data-invalid="true" @endif
    @keydown.escape="if (open) { $event.stopPropagation(); closeAndFocus() }"
    @click.outside="close()"
    @change="onChange($event.detail)"
    {{ $attributes->except(['aria-describedby'])->merge(['class' => 'relative w-full']) }}
>
    @if (filled($startName)) <input type="hidden" name="{{ $startName }}" :value="start" /> @endif
    @if (filled($endName)) <input type="hidden" name="{{ $endName }}" :value="end" /> @endif

    <button
        type="button"
        data-slot="date-range-picker-trigger"
        x-ref="trigger"
        aria-haspopup="dialog"
        :aria-expanded="open"
        @if (filled($fieldName)) id="{{ $fieldName }}" @endif
        {{-- A labelled field names the trigger through its <label for>. --}}
        @if (blank($fieldName) || blank($fieldLabel)) aria-label="{{ __('Date range') }}" @endif
        @if ($isInvalid) aria-invalid="true" @endif
        @if (filled($describedBy)) aria-describedby="{{ $describedBy }}" @endif
        @click="toggle()"
        class="{{ $trigger['base'] }} {{ $trigger['sizes']['md'] }} {{ $trigger['states'][$isInvalid ? 'invalid' : 'default'] }}"
    >
        <span class="truncate" :class="label ? 'text-foreground' : 'text-muted-foreground'" x-text="label || @js($placeholder)"></span>
        <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="size-4 shrink-0 text-muted-foreground">
            <rect width="18" height="18" x="3" y="4" rx="2" />
            <path d="M3 10h18M8 2v4M16 2v4" />
        </svg>
    </button>

    <div
        data-slot="date-range-picker-content"
        role="dialog"
        aria-modal="false"
        aria-label="{{ __('Choose a date range') }}"
        x-show="open"
        x-cloak
        x-transition:enter="motion-safe:transition motion-safe:duration-100"
        x-transition:enter-start="opacity-0 scale-95"
        x-transition:enter-end="opacity-100 scale-100"
        class="absolute start-0 z-dropdown mt-1 flex w-max max-w-none flex-col rounded-md border border-border bg-popover text-popover-foreground shadow-md motion-reduce:transition-none sm:flex-row"
    >
        @if ($presetList !== [])
            <div data-slot="date-range-picker-presets" class="flex shrink-0 flex-row flex-wrap gap-1 border-b border-border p-2 sm:w-40 sm:flex-col sm:border-b-0 sm:border-e" role="group" aria-label="{{ __('Presets') }}">
                @foreach ($presetList as $preset)
                    <button
                        type="button"
                        @click="applyPreset(@js($preset))"
                        class="rounded-sm px-2 py-1 text-start text-sm text-foreground transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-[length:var(--ring-width)] focus-visible:ring-ring motion-reduce:transition-none"
                    >{{ $preset['label'] }}</button>
                @endforeach
            </div>
        @endif
        <div class="p-3">
            <x-ui.calendar
                mode="range"
                :start="$resolvedStart"
                :end="$resolvedEnd"
                :locale="$locale"
                :first-day="$firstDay"
                :min="$min"
                :max="$max"
                :disabled="$disabled"
                :months="$months"
                :week-numbers="$weekNumbers"
                :chrome="false"
            />
            <div class="mt-3 flex items-center justify-between gap-3 border-t border-border pt-3">
                <span class="min-w-0 truncate text-xs text-muted-foreground" x-text="label || @js(__('Pick a start, then an end'))"></span>
                <div class="flex shrink-0 gap-2">
                    <x-ui.button variant="ghost" size="sm" x-on:click="clear()" x-show="start" x-cloak>{{ __('Clear') }}</x-ui.button>
                    <x-ui.button size="sm" x-on:click="closeAndFocus()" ::disabled="!end">{{ __('Apply') }}</x-ui.button>
                </div>
            </div>
        </div>
    </div>

    @if (filled($partErrorId))
        <p data-slot="date-range-picker-error" id="{{ $partErrorId }}" role="alert" class="mt-field min-w-0 break-words text-sm font-medium text-destructive">
            {{ $partMessages->implode(' ') }}
        </p>
    @endif
</div>
resources/js/ui/date-range-picker.js JS
/**
 * Date Range Picker behavior.
 *
 * Owns the popover (open/close, Escape, click-outside, focus return), the field
 * label and the two hidden values; the composed calendar (mode: 'range') owns
 * the picking and reports through its `change` event ({ start, end, complete }).
 * Presets set the calendar's range directly (`setRange`) so the grid and the
 * field agree. Self-registers on `alpine:init` so import order does not matter.
 */

/**
 * Format an ISO date for display. `display` is an Intl style (`short`, `medium`,
 * `long`, `full`) or a pattern of tokens: d, dd, M, MM, MMM, MMMM, yy, yyyy,
 * EEE, EEEE (any other character is printed as is, e.g. "dd/MM/yyyy").
 */
function formatIsoDate(iso, display, locale) {
    if (!iso) return '';
    const [y, m, d] = iso.split('-').map(Number);
    const date = new Date(y, m - 1, d);
    if (['short', 'medium', 'long', 'full'].includes(display)) {
        return new Intl.DateTimeFormat(locale, { dateStyle: display }).format(date);
    }
    const part = (options) => new Intl.DateTimeFormat(locale, options).format(date);
    const tokens = {
        yyyy: () => String(y),
        yy: () => String(y).slice(-2),
        MMMM: () => part({ month: 'long' }),
        MMM: () => part({ month: 'short' }),
        MM: () => String(m).padStart(2, '0'),
        M: () => String(m),
        dd: () => String(d).padStart(2, '0'),
        d: () => String(d),
        EEEE: () => part({ weekday: 'long' }),
        EEE: () => part({ weekday: 'short' }),
    };
    return display.replace(/yyyy|yy|MMMM|MMM|MM|M|dd|d|EEEE|EEE/g, (token) => tokens[token]());
}

document.addEventListener('alpine:init', () => {
    window.Alpine.data('uiDateRangePicker', (config = {}) => ({
        open: false,
        start: config.start || '',
        end: config.end || '',
        locale: config.locale || document.documentElement.lang || 'en',
        display: config.display || 'medium',
        label: '',

        init() {
            this.updateLabel();
        },

        /**
         * Modelable value (`x-modelable="model"` on the root): `{ start, end }`
         * as ISO dates. An inbound value (Livewire, `x-model`) accepts that
         * object or a `[start, end]` pair and refreshes the label.
         */
        get model() {
            return { start: this.start, end: this.end };
        },
        set model(v) {
            const pair = Array.isArray(v) ? { start: v[0], end: v[1] } : (v && typeof v === 'object' ? v : {});
            const start = pair.start == null ? '' : String(pair.start);
            const end = pair.end == null ? '' : String(pair.end);
            if (start === this.start && end === this.end) return;
            this.start = start;
            this.end = end;
            this.updateLabel();
            this.calendar()?.setRange(start, end);
        },

        toIso(date) {
            const y = date.getFullYear();
            const m = String(date.getMonth() + 1).padStart(2, '0');
            const d = String(date.getDate()).padStart(2, '0');
            return `${y}-${m}-${d}`;
        },

        updateLabel() {
            if (!this.start) {
                this.label = '';
                return;
            }
            const from = formatIsoDate(this.start, this.display, this.locale);
            const to = this.end ? formatIsoDate(this.end, this.display, this.locale) : '…';
            this.label = `${from} – ${to}`;
        },

        toggle() {
            this.open ? this.close() : this.show();
        },

        show() {
            this.open = true;
            this.$nextTick(() => {
                this.$root.querySelector('[data-slot="calendar"] [data-date][tabindex="0"]')?.focus();
            });
        },

        close() {
            this.open = false;
        },

        closeAndFocus() {
            if (!this.open) return;
            this.open = false;
            this.$nextTick(() => this.$refs.trigger?.focus());
        },

        /** The composed calendar's Alpine data (its root owns its own scope, so no $refs). */
        calendar() {
            const el = this.$root.querySelector('[data-slot="calendar"]');
            return el ? window.Alpine.$data(el) : null;
        },

        /** Driven by the calendar's `change` event. */
        onChange(detail) {
            if (!detail || !('start' in detail)) return;
            this.start = detail.start || '';
            this.end = detail.end || '';
            this.updateLabel();
        },

        clear() {
            this.start = '';
            this.end = '';
            this.updateLabel();
            this.calendar()?.setRange('', '');
        },

        /** Built-in presets resolve against the browser's today; custom ones carry ISO dates. */
        applyPreset(preset) {
            let start = preset.start || '';
            let end = preset.end || '';
            if (preset.key) {
                const today = new Date();
                const at = (days) => this.toIso(new Date(today.getFullYear(), today.getMonth(), today.getDate() + days));
                switch (preset.key) {
                    case 'today': start = end = at(0); break;
                    case 'yesterday': start = end = at(-1); break;
                    case 'last-7': start = at(-6); end = at(0); break;
                    case 'last-30': start = at(-29); end = at(0); break;
                    case 'this-month':
                        start = this.toIso(new Date(today.getFullYear(), today.getMonth(), 1));
                        end = this.toIso(new Date(today.getFullYear(), today.getMonth() + 1, 0));
                        break;
                    case 'last-month':
                        start = this.toIso(new Date(today.getFullYear(), today.getMonth() - 1, 1));
                        end = this.toIso(new Date(today.getFullYear(), today.getMonth(), 0));
                        break;
                    default: return;
                }
            }
            this.start = start;
            this.end = end;
            this.updateLabel();
            this.calendar()?.setRange(start, end);
        },
    }));
});

Ownership & lifecycle

Owner, release state, review evidence and adoption for this item.
Owner
Platform UI (@JoshJML)
Current version
1.3.3
Status
Stable
License
open
Accessibility reviewed
No review date recorded
Last breaking change
No date recorded
Deprecation
Not deprecated
Contract
v6
Foundation
≥ 1.0.0