<x-widget.datepicker>
Date picker
Single date field with a calendar popover. Submits Y-m-d; validate with NotAfterToday, or MinimumAge for birthday. Works with Livewire wire:model, name optional.
php artisan larawell:add datepicker
- Also adds
- Icon
- Used by
- Date range picker
- Needs PHP extension
intl
Usage
In other languages
Dates, month and weekday names, the week's first day and digits follow the app locale (app()->getLocale()). For Arabic, Hebrew, Persian or Urdu, set dir="rtl" and the calendar mirrors, keyboard included. The picker's own labels are plain English in the component file; edit them there.
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" dir="{{ in_array(app()->getLocale(), ['ar', 'he', 'fa', 'ur']) ? 'rtl' : 'ltr' }}">
{{-- Or set them per picker: --}}
<x-widget.datepicker name="start_date" label="Datum" locale="de" :week-start="0" />
Livewire
In a Livewire component, bind with wire:model (deferred) or wire:model.live to a string property holding YYYY-MM-DD, or null: public ?string $due = null. No name is needed. The field shows the property after every render, and a date set or cleared in PHP shows too; the calendar opens on it. Validate it like any date: 'due' => ['required', 'date'].
<div>
<x-widget.datepicker label="Due date" wire:model.live="due" :max="false" />
<x-widget.datepicker label="Date of birth" wire:model="birthday" birthday />
</div>
Examples
Basic
Submits Y-m-d. Validate it with new NotAfterToday, not before_or_equal:today, which uses the server's UTC date.
Show code Hide code
<x-widget.datepicker name="start_date" label="Start date" class="max-w-xs" />
Birthday
Only allows dates at least 18 years back. Pair it with new MinimumAge(18) on the server.
You must be 18 or older.
Show code Hide code
<x-widget.datepicker name="date_of_birth" label="Date of birth" birthday class="max-w-xs" />
States
Please choose a valid date.
Show code Hide code
<div class="grid gap-6 sm:grid-cols-2">
<x-widget.datepicker name="due_date" label="With error" value="2026-09-01" error="Please choose a valid date." />
<x-widget.datepicker name="locked_date" label="Disabled" disabled />
</div>
Props
Other attributes, such as autocomplete or data-*, are passed through to the element. class styles the component's outer wrapper.
<x-widget.datepicker>
| Prop | Default | Description |
|---|---|---|
| name |
null
|
What the date submits as (YYYY-MM-DD). Optional with wire:model, which then names it. |
| id |
null
|
Defaults to one made from the name (or the wire:model property). |
| label |
null
|
Shown above the field, and its name for screen readers. |
| value |
null
|
The date: YYYY-MM-DD or a date object. Old input wins after a failed submit; with wire:model and no value, the bound property. |
| placeholder |
null
|
Shown while no date is picked; "Choose a date" by default. |
| error |
null
|
An error message of your own; otherwise the validation error for the name, from the session or Livewire. |
| info |
null
|
A hint under the field. |
| bag |
'default'
|
Which error bag to read the error from. |
| disabled |
false
|
Greyed out: it can't be opened. |
| min |
null
|
The earliest date that can be picked: YYYY-MM-DD, a date object, or "today" (the visitor's today). |
| max |
'today'
|
The latest date: YYYY-MM-DD, a date object, "today" (the default), or false for no limit. |
| birthday |
false
|
A date-of-birth picker: true for 18 or older, or a number for another minimum age. Sets max and the hint to match. |
| week-start |
null
|
The first day of the week, 0 (Sunday) to 6 (Saturday); defaults to the locale's. |
| locale |
null
|
The language for month and day names and the date shown (en, fr, ar…); defaults to the app's. |
| required-message |
'Choose a date.'
|
With required: the message when nothing is picked. |
Source
What larawell:add datepicker writes to your app with the default namespaces. Prefer to copy by hand? Take these files, plus the ones from
the components it also adds and Field, and the theme and base CSS.
resources/views/components/widget/datepicker/index.blade.php Show
@props([
// What the date submits as (YYYY-MM-DD). Optional with wire:model, which then names it.
'name' => null,
// Defaults to one made from the name (or the wire:model property).
'id' => null,
// Shown above the field, and its name for screen readers.
'label' => null,
// The date: YYYY-MM-DD or a date object. Old input wins after a failed submit; with wire:model and no value, the
// bound property.
'value' => null,
// Shown while no date is picked; "Choose a date" by default.
'placeholder' => null,
// An error message of your own; otherwise the validation error for the name, from the session or Livewire.
'error' => null,
// A hint under the field.
'info' => null,
// Which error bag to read the error from.
'bag' => 'default',
// Greyed out: it can't be opened.
'disabled' => false,
// The earliest date that can be picked: YYYY-MM-DD, a date object, or "today" (the visitor's today).
'min' => null,
// The latest date: YYYY-MM-DD, a date object, "today" (the default), or false for no limit.
'max' => 'today',
// A date-of-birth picker: true for 18 or older, or a number for another minimum age. Sets max and the hint to
// match.
'birthday' => false,
// The first day of the week, 0 (Sunday) to 6 (Saturday); defaults to the locale's.
'weekStart' => null,
// The language for month and day names and the date shown (en, fr, ar…); defaults to the app's.
'locale' => null,
// With required: the message when nothing is picked.
'requiredMessage' => 'Choose a date.',
])
@php
$toIso = static function (mixed $date): ?string {
if ($date instanceof \DateTimeInterface) {
return $date->format('Y-m-d');
}
if (is_string($date) && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date, $parts) === 1
&& checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1])) {
return $date;
}
return null;
};
// birthday means 18 or older; birthday="21" sets another age. Pair it with new MinimumAge($age).
$minAge = match (true) {
$birthday === true => 18,
is_numeric($birthday) && (int) $birthday > 0 => (int) $birthday,
default => null,
};
$birthday = $minAge !== null;
$maxYearsBack = $minAge;
// "today" is resolved by the browser, on the user's own clock: the server's date can be a day
// behind or ahead of the user (e.g. UTC server, user in IST), which would block or allow the wrong day.
// Browser-side limit only; the Form Request must enforce the same rule with
// App\Rules\NotAfterToday (default) or MinimumAge (birthday), not 'before_or_equal:today'.
// :max="false" removes the limit (Blade turns a passed null back into the 'today' default).
$max = match (true) {
$birthday, $max === 'today' => 'today',
$max === false => null,
default => $toIso($max),
};
$min = $min === 'today' ? 'today' : $toIso($min);
$field = \App\View\Widget\FormField::make($name, $id, $errors ?? null, $error, $bag, 'datepicker', attributes: $attributes);
$id = $field->id;
$value = $toIso($field->old($value));
// Dates read the way the locale writes them; the browser keeps the same format (see the JS).
$locale = \App\View\Widget\LocalDate::locale($locale);
$weekStart ??= \App\View\Widget\LocalDate::firstDayOfWeek($locale);
$display = $value ? \App\View\Widget\LocalDate::format($value, $locale) : null;
$placeholder ??= 'Choose a date';
// Explains the greyed-out recent dates; pass info="" to hide it, or your own text to replace it.
$info ??= $birthday ? "You must be {$minAge} or older." : null;
@endphp
{{--
Built on the shared input frame (widget/field): same label, box, error and hint as every
other input, all messages, clear-on-edit. The caller's attributes go on the submitted hidden input;
`class` goes on the wrapper.
--}}
{{-- The button can't be required or aria-required, so the label says it for screen readers, and resources/js/widget/field
stops an empty submit (the value is in hidden inputs, which the browser never validates). --}}
<x-widget.field
:required="$attributes->has('required')"
:announce-required="true"
:data-required-message="$attributes->has('required') && ! $disabled ? $requiredMessage : false"
data-datepicker
data-min="{{ $min }}"
data-max="{{ $max }}"
:data-max-years-back="$maxYearsBack"
data-week-start="{{ $weekStart }}"
data-locale="{{ $locale }}"
:id="$id"
:label="$label"
:error="$field->errors"
:info="$info"
:disabled="$disabled"
box="h-12 items-center"
:class="$attributes->get('class')"
>
<button
type="button"
id="{{ $id }}"
popovertarget="{{ $id }}-calendar"
aria-haspopup="dialog"
aria-expanded="false"
{{-- A <label> would otherwise be the button's whole name, and the chosen date inside it would never be read. --}}
@if ($label) aria-labelledby="{{ $id }}-label {{ $id }}-display" @endif
{{ $field->aria($attributes, (bool) $info) }}
@disabled($disabled)
data-datepicker-trigger
class="flex h-full w-full min-w-0 items-center justify-between gap-2.5 px-5 text-start whitespace-nowrap outline-none select-none enabled:cursor-pointer disabled:cursor-not-allowed disabled:opacity-50"
>
<span
id="{{ $id }}-display"
data-datepicker-display
@if (! $display) data-empty @endif
class="text-style-2 data-empty:text-muted group-data-invalid/field:data-empty:text-error truncate"
>{{ $display ?? $placeholder }}</span>
<x-widget.icon name="calendar-days" @class(['size-5', 'opacity-40' => $disabled]) />
</button>
<input type="hidden" @if ($name) name="{{ $name }}" @endif value="{{ $value }}" data-datepicker-input {{ $field->forwarded($attributes)->except(['required']) }}>
{{-- wire:ignore: the script builds everything in here (the month and year lists, the days), and a Livewire render
would empty it again, since the server sends it empty. The value lives outside, on the hidden input(s). --}}
<div
wire:ignore
id="{{ $id }}-calendar"
popover
role="dialog"
aria-label="{{ $label ?? 'Choose a date' }}"
data-datepicker-popover
class="border-line text-foreground fixed inset-auto m-0 overflow-y-auto overscroll-contain rounded-md border bg-surface p-3 shadow-lg"
>
{{-- Selects never shrink, so the full month name always shows; a <select> is as wide as its
longest option, so if "September" fits at the 252px minimum, every month does. --}}
<div class="mb-2 flex items-center justify-between">
<button type="button" data-datepicker-prev aria-label="Previous month" class="enabled:hover:bg-field grid size-7 shrink-0 place-items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-30">
<x-widget.icon name="chevron-left" class="size-4 rtl:rotate-180" />
</button>
{{-- Each select draws its own arrow (appearance-none hides the browser's, which sits against the focus ring). --}}
<div class="flex shrink-0 gap-1">
<span class="relative inline-flex shrink-0">
<select id="{{ $id }}-month" data-datepicker-month aria-label="Month" class="hover:bg-field shrink-0 cursor-pointer appearance-none rounded-md bg-transparent py-1 ps-1 pe-5 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-primary"></select>
<x-widget.icon name="chevron-down" class="text-foreground/60 pointer-events-none absolute end-1.5 top-1/2 size-3 -translate-y-1/2" />
</span>
<span class="relative inline-flex shrink-0">
<select id="{{ $id }}-year" data-datepicker-year aria-label="Year" class="hover:bg-field shrink-0 cursor-pointer appearance-none rounded-md bg-transparent py-1 ps-1 pe-5 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-primary"></select>
<x-widget.icon name="chevron-down" class="text-foreground/60 pointer-events-none absolute end-1.5 top-1/2 size-3 -translate-y-1/2" />
</span>
</div>
<button type="button" data-datepicker-next aria-label="Next month" class="enabled:hover:bg-field grid size-7 shrink-0 place-items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-30">
<x-widget.icon name="chevron-right" class="size-4 rtl:rotate-180" />
</button>
</div>
<table data-datepicker-grid class="w-full table-fixed border-collapse text-center"></table>
</div>
</x-widget.field>
resources/js/widget/datepicker/index.js Show
// Drives <x-widget.datepicker>. Dates are plain local calendar days (no time
// part) so a timezone offset can never shift the selected day. The date helpers are
// exported for <x-widget.date-range-picker>, which works on the same calendar days.
import { closeIfOutOfView } from '../field';
export const pad = (n) => String(n).padStart(2, '0');
export const toIso = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
export const addDays = (d, n) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
export const daysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
// Keeps the day where possible but never overflows: 31 Jan + 1 month is 28/29 Feb, not 3 Mar.
export const addMonths = (d, n) => {
const target = new Date(d.getFullYear(), d.getMonth() + n, 1);
const day = Math.min(d.getDate(), daysInMonth(target.getFullYear(), target.getMonth()));
return new Date(target.getFullYear(), target.getMonth(), day);
};
export const parseIso = (value) => {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value ?? '');
return match ? new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])) : null;
};
// How the picker's locale writes dates, shared with <x-widget.date-range-picker>. The locale comes from the
// server (data-locale), which rendered the first paint in the same format. Always the Gregorian calendar,
// because the grid is: some locales (ar-SA, th) would otherwise show Hijri or Buddhist dates above it.
// Names, word order and digits stay the locale's own.
export function localeTools(root) {
const locale = root.dataset.locale || document.documentElement.lang || undefined;
const gregory = { calendar: 'gregory' };
const date = new Intl.DateTimeFormat(locale, { ...gregory, year: 'numeric', month: 'short', day: 'numeric' });
const number = new Intl.NumberFormat(locale, { useGrouping: false });
return {
locale,
rtl: getComputedStyle(root).direction === 'rtl',
format: (d) => date.format(d),
formatRange: (from, to) => date.formatRange(from, to),
number: (n) => number.format(n),
monthName: new Intl.DateTimeFormat(locale, { ...gregory, month: 'long' }),
monthCaption: new Intl.DateTimeFormat(locale, { ...gregory, month: 'long', year: 'numeric' }),
shortWeekday: new Intl.DateTimeFormat(locale, { ...gregory, weekday: 'short' }),
longWeekday: new Intl.DateTimeFormat(locale, { ...gregory, weekday: 'long' }),
dayLabel: new Intl.DateTimeFormat(locale, { ...gregory, dateStyle: 'full' }),
};
}
// Where a popover sits: under the field, lined up with its start edge (the right one in RTL), never off-screen.
export function alignedLeft(box, width, rtl) {
const edge = rtl ? box.right - width : box.left;
return Math.max(VIEWPORT_EDGE, Math.min(edge, window.innerWidth - width - VIEWPORT_EDGE));
}
// Arrow keys follow the reading direction: in RTL, left is forward in time.
export const horizontalStep = (key, rtl) => (key === 'ArrowRight' ? 1 : -1) * (rtl ? -1 : 1);
// One tone per state so no two classes fight over the same property.
// Fluid days: each fills its (equal, table-fixed) column up to 44px and stays round,
// so the grid scales with the dropdown instead of forcing a fixed width.
const DAY_BASE = 'mx-auto grid aspect-square w-full max-w-11 place-items-center rounded-full text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-primary';
const DAY_TONE = {
selected: 'bg-primary font-semibold text-on-primary',
disabled: 'cursor-not-allowed text-muted/50',
outside: 'text-muted hover:bg-field',
today: 'font-semibold text-primary hover:bg-field',
default: 'text-foreground hover:bg-field',
};
// Added on top of whichever tone applies, so today stays marked even when disabled or outside the month.
const TODAY_MARK = 'ring-1 ring-inset ring-primary';
export const VIEWPORT_EDGE = 16;
export const POPOVER_GAP = 4;
// Narrowest the calendar gets (32px days); a narrower field lets it overhang instead.
export const MIN_WIDTH = 252;
// Set up once per element. Not a data attribute: Livewire's morph removes attributes the server didn't render.
const ready = new WeakSet();
function initDatepicker(root) {
if (ready.has(root)) {
return;
}
ready.add(root);
const trigger = root.querySelector('[data-datepicker-trigger]');
const display = root.querySelector('[data-datepicker-display]');
const input = root.querySelector('[data-datepicker-input]');
const popover = root.querySelector('[data-datepicker-popover]');
const monthSelect = popover.querySelector('[data-datepicker-month]');
const yearSelect = popover.querySelector('[data-datepicker-year]');
const prevButton = popover.querySelector('[data-datepicker-prev]');
const nextButton = popover.querySelector('[data-datepicker-next]');
const grid = popover.querySelector('[data-datepicker-grid]');
const tools = localeTools(root);
const weekStart = Number(root.dataset.weekStart || 0);
// "today" means the user's local date, not the server's (see the Blade component). It and the limits built
// from it are worked out again each time the calendar opens (refreshLimits), so a page left open past
// midnight doesn't keep yesterday as today.
let today;
let min;
let max;
const parseLimit = (value) => (value === 'today' ? today : parseIso(value));
const yearsBack = (date, years) => (date && years ? new Date(date.getFullYear() - years, date.getMonth(), date.getDate()) : date);
// A birthday picker (max-years-back) has to reach the oldest people using the form, not stop at 100.
const defaultSpan = root.dataset.maxYearsBack ? 120 : 100;
function refreshLimits() {
const now = new Date();
const day = new Date(now.getFullYear(), now.getMonth(), now.getDate());
if (today && day.getTime() === today.getTime()) {
return;
}
today = day;
// Without explicit limits the year dropdown still needs a finite range.
min = parseLimit(root.dataset.min) ?? new Date(today.getFullYear() - defaultSpan, 0, 1);
max = yearsBack(parseLimit(root.dataset.max), Number(root.dataset.maxYearsBack || 0))
?? new Date(today.getFullYear() + 10, 11, 31);
yearSelect.replaceChildren();
for (let year = max.getFullYear(); year >= min.getFullYear(); year--) {
yearSelect.add(new Option(tools.number(year), String(year)));
}
}
refreshLimits();
let selected = parseIso(input.value);
let focused = today;
const isOutOfRange = (d) => d < min || d > max;
const clamp = (d) => (d > max ? max : d < min ? min : d);
const weekdayOffset = (d) => (d.getDay() - weekStart + 7) % 7;
for (let month = 0; month < 12; month++) {
monthSelect.add(new Option(tools.monthName.format(new Date(2000, month, 1)), String(month)));
}
const headRow = grid.createTHead().insertRow();
for (let i = 0; i < 7; i++) {
// 1 Jan 2023 was a Sunday, so offsetting from it lists weekdays in order.
const day = new Date(2023, 0, 1 + ((weekStart + i) % 7));
const cell = document.createElement('th');
cell.scope = 'col';
cell.abbr = tools.longWeekday.format(day);
cell.textContent = tools.shortWeekday.format(day);
cell.className = 'pb-1 text-xs font-medium text-muted';
headRow.append(cell);
}
const body = grid.createTBody();
function render() {
const year = focused.getFullYear();
const month = focused.getMonth();
yearSelect.value = String(year);
monthSelect.value = String(month);
for (const option of monthSelect.options) {
const m = Number(option.value);
option.disabled = new Date(year, m + 1, 0) < min || new Date(year, m, 1) > max;
}
prevButton.disabled = new Date(year, month, 0) < min;
nextButton.disabled = new Date(year, month + 1, 1) > max;
const focusedIso = toIso(focused);
const selectedIso = selected ? toIso(selected) : null;
const todayIso = toIso(today);
let day = addDays(new Date(year, month, 1), -weekdayOffset(new Date(year, month, 1)));
body.replaceChildren();
// Always six weeks so the popover height doesn't jump between months.
for (let week = 0; week < 6; week++) {
const row = body.insertRow();
for (let i = 0; i < 7; i++, day = addDays(day, 1)) {
const iso = toIso(day);
const disabled = isOutOfRange(day);
const tone = iso === selectedIso ? 'selected'
: disabled ? 'disabled'
: day.getMonth() !== month ? 'outside'
: iso === todayIso ? 'today'
: 'default';
const button = document.createElement('button');
button.type = 'button';
button.textContent = tools.number(day.getDate());
button.dataset.date = iso;
button.disabled = disabled;
button.tabIndex = iso === focusedIso ? 0 : -1;
button.className = `${DAY_BASE} ${DAY_TONE[tone]}${iso === todayIso ? ` ${TODAY_MARK}` : ''}`;
button.setAttribute('aria-label', tools.dayLabel.format(day));
button.setAttribute('aria-pressed', String(iso === selectedIso));
if (iso === todayIso) {
button.setAttribute('aria-current', 'date');
}
row.insertCell().append(button);
}
}
}
const focusDay = () => grid.querySelector('button[tabindex="0"]')?.focus();
function moveFocus(date) {
focused = clamp(date);
render();
focusDay();
}
function changeMonth(date, sourceButton) {
focused = clamp(date);
render();
// A nav button that just became disabled drops focus to <body>; keep keyboard users in the grid.
if (sourceButton?.disabled) {
focusDay();
}
}
function select(date) {
selected = date;
input.value = toIso(date);
display.textContent = tools.format(date);
display.removeAttribute('data-empty');
// Both events: tools like Alpine x-model and Livewire wire:model listen for `input`, plain forms for `change`.
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
popover.hidePopover();
trigger.focus();
}
function position() {
if (closeIfOutOfView(trigger, popover)) {
return;
}
const box = trigger.getBoundingClientRect();
// Same width as the field (edges line up), but at least MIN_WIDTH and never wider than the screen.
const fit = Math.min(Math.max(box.width, MIN_WIDTH), window.innerWidth - VIEWPORT_EDGE * 2);
popover.style.width = `${fit}px`;
// On very short screens the calendar scrolls inside itself rather than running off-screen.
popover.style.maxHeight = `${window.innerHeight - VIEWPORT_EDGE * 2}px`;
const { offsetWidth: width, offsetHeight: height } = popover;
const below = box.bottom + POPOVER_GAP;
const above = box.top - POPOVER_GAP - height;
let top;
if (below + height <= window.innerHeight - VIEWPORT_EDGE) {
top = below;
} else if (above >= VIEWPORT_EDGE) {
top = above;
} else {
// No room either side (e.g. a phone in landscape): stay fully visible, even if that covers the field.
top = Math.max(VIEWPORT_EDGE, window.innerHeight - VIEWPORT_EDGE - height);
}
popover.style.top = `${top}px`;
popover.style.left = `${alignedLeft(box, width, tools.rtl)}px`;
}
const KEY_MOVES = {
ArrowLeft: (d) => addDays(d, horizontalStep('ArrowLeft', tools.rtl)),
ArrowRight: (d) => addDays(d, horizontalStep('ArrowRight', tools.rtl)),
ArrowUp: (d) => addDays(d, -7),
ArrowDown: (d) => addDays(d, 7),
Home: (d) => addDays(d, -weekdayOffset(d)),
End: (d) => addDays(d, 6 - weekdayOffset(d)),
PageUp: (d, event) => addMonths(d, event.shiftKey ? -12 : -1),
PageDown: (d, event) => addMonths(d, event.shiftKey ? 12 : 1),
};
grid.addEventListener('keydown', (event) => {
const move = KEY_MOVES[event.key];
if (!move) {
return;
}
event.preventDefault();
moveFocus(move(focused, event));
});
grid.addEventListener('click', (event) => {
const button = event.target.closest('button[data-date]');
if (button && !button.disabled) {
select(parseIso(button.dataset.date));
}
});
prevButton.addEventListener('click', () => changeMonth(addMonths(focused, -1), prevButton));
nextButton.addEventListener('click', () => changeMonth(addMonths(focused, 1), nextButton));
const onViewSelect = () => {
const year = Number(yearSelect.value);
const month = Number(monthSelect.value);
changeMonth(new Date(year, month, Math.min(focused.getDate(), daysInMonth(year, month))));
};
monthSelect.addEventListener('change', onViewSelect);
yearSelect.addEventListener('change', onViewSelect);
popover.addEventListener('beforetoggle', (event) => {
if (event.newState !== 'open') {
return;
}
refreshLimits();
// The value as it is now: a Livewire render or another script may have changed it since.
selected = parseIso(input.value);
// Open on the selected day, or today clamped into range, so a birthday
// picker doesn't open on a month where every day is disabled.
focused = clamp(selected ?? today);
render();
// Hidden until positioned, otherwise it flashes at the popover default (screen centre).
popover.style.visibility = 'hidden';
});
popover.addEventListener('toggle', (event) => {
const open = event.newState === 'open';
trigger.setAttribute('aria-expanded', String(open));
if (!open) {
window.removeEventListener('scroll', position, true);
window.removeEventListener('resize', position);
return;
}
position();
popover.style.visibility = '';
focusDay();
// Capture phase so scrolling any ancestor container also repositions it.
window.addEventListener('scroll', position, true);
window.addEventListener('resize', position);
});
}
export function initDatepickers(scope = document) {
scope.querySelectorAll('[data-datepicker]').forEach(initDatepicker);
}
initDatepickers();
// Date pickers added to the page later (a Livewire render or wire:navigate, fetched HTML) set themselves up.
new MutationObserver((records) => {
for (const node of records.flatMap((record) => [...record.addedNodes])) {
if (node instanceof Element) {
(node.matches('[data-datepicker]') ? [node] : node.querySelectorAll('[data-datepicker]')).forEach(initDatepicker);
}
}
}).observe(document.documentElement, { childList: true, subtree: true });
app/View/Widget/ElementIds.php Show
<?php
declare(strict_types=1);
namespace App\View\Widget;
use Illuminate\Container\Attributes\Scoped;
use LogicException;
/**
* Keeps element ids unique within one response, so labels, aria-describedby and #fragments
* always point at the right element. Scoped: a fresh set per request (and per Octane/queue cycle).
*/
#[Scoped]
final class ElementIds
{
/** @var array<string, true> */
private array $used = [];
/**
* Reserves an id for this response.
*
* A derived id (built from a field name) gets a -2, -3 … suffix when already taken. An explicit
* id is one the caller chose and may reference from JS or CSS, so silently renaming it would
* break that reference; a duplicate throws instead, which surfaces in development and tests.
*/
public function claim(string $id, bool $explicit = false): string
{
if (!isset($this->used[$id])) {
return $this->reserve($id);
}
if ($explicit) {
throw new LogicException("Duplicate element id [{$id}] on this page. Give one of the widgets a different id or name.");
}
$suffix = 2;
while (isset($this->used["{$id}-{$suffix}"])) {
$suffix++;
}
return $this->reserve("{$id}-{$suffix}");
}
private function reserve(string $id): string
{
$this->used[$id] = true;
return $id;
}
}
app/View/Widget/FormField.php Show
<?php
declare(strict_types=1);
namespace App\View\Widget;
use Illuminate\Contracts\Support\MessageBag;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\ViewErrorBag;
use Illuminate\View\ComponentAttributeBag;
/**
* Server-side state of one form widget: its dot-notation key, a valid id, its validation
* messages and its old input. Every <x-widget.input.*> and the date picker resolve through
* here, so array names (items[0][date]) and named error bags behave the same everywhere.
*/
final class FormField
{
/**
* @param list<string> $errors
*/
private function __construct(
public readonly ?string $name,
public readonly string $id,
public readonly ?string $key,
public readonly array $errors,
// The property a wire:model or x-model attribute binds it to, if any.
public readonly ?string $bound = null,
) {}
/**
* @param mixed $errorBag the view's shared $errors (absent outside a web request)
* @param string|array<int, string>|null $error an explicit message from the caller; overrides the bag
*/
public static function make(
?string $name,
?string $id,
mixed $errorBag,
string|array|null $error = null,
string $bag = 'default',
string $idPrefix = 'field',
?ComponentAttributeBag $attributes = null,
): self {
// With no name, a Livewire or Alpine binding (wire:model="email") names the field. Its errors are filed under
// that property, and its id stays the same on every render, which Livewire's morph needs to keep the element
// (it matches elements by id: a random one makes it swap in a new field, dropping focus mid-typing).
$bound = $attributes === null ? null : self::boundTo($attributes);
$key = match (true) {
$name !== null && $name !== '' => self::key($name),
$bound !== null => self::key($bound),
default => null,
};
$messages = match (true) {
$error !== null => Arr::wrap($error),
$key !== null && $errorBag instanceof ViewErrorBag => self::messagesFor($errorBag->getBag($bag), $key),
default => [],
};
return new self(
$name,
app(ElementIds::class)->claim(
$id ?? ($key !== null ? self::idFrom($key) : $idPrefix.'-'.Str::random(6)),
explicit: $id !== null,
),
$key,
array_values(array_filter($messages, static fn (mixed $message): bool => is_string($message) && $message !== '')),
$bound,
);
}
/**
* The field's own messages, plus those Laravel files per item for a list of values: a 'tags.*' rule
* reports a bad second choice under tags.1, which a multiple select named tags must still show. Only
* numbered children count, so a field named address doesn't take errors meant for address[city].
*
* @return list<string>
*/
private static function messagesFor(MessageBag $bag, string $key): array
{
$items = array_filter(
$bag->getMessages(),
static fn (string $name): bool => preg_match('/^'.preg_quote($key, '/').'\.\d+$/', $name) === 1,
ARRAY_FILTER_USE_KEY,
);
return array_values(array_unique([...$bag->get($key), ...array_merge(...array_values($items))]));
}
/**
* items[0][date] → items.0.date and tags[] → tags: the key Laravel files errors and old input under.
*/
public static function key(string $name): string
{
return trim((string) preg_replace('/\[([^\]]*)\]/', '.$1', $name), '.');
}
/**
* The id a field named $name gets when it's the first of that name on the page, for links to it
* (the error summary). A later duplicate gets a -2 suffix, which links can't know about.
*/
public static function idFor(string $name): string
{
return self::idFrom(self::key($name));
}
/**
* The property a wire:model or x-model attribute (any modifiers) binds the field to; null without one.
*/
public static function boundTo(ComponentAttributeBag $attributes): ?string
{
return array_values(self::binding($attributes))[0] ?? null;
}
private static function idFrom(string $key): string
{
return trim((string) preg_replace('/[^A-Za-z0-9_-]+/', '-', $key), '-');
}
public function hasError(): bool
{
return $this->errors !== [];
}
public function errorId(): string
{
return $this->id.'-error';
}
public function infoId(): string
{
return $this->id.'-info';
}
/**
* Old input after a failed validation, falling back to the widget's value prop, or with none, to the bound Livewire
* property: a re-render then draws the field as it is, which Livewire morphs onto the page.
*/
public function old(mixed $default = null): mixed
{
if ($default === null) {
[$found, $live] = $this->fromLivewire();
$default = $found ? $live : null;
}
return $this->key === null ? $default : old($this->key, $default);
}
/**
* The bound property's value while Livewire renders the component that holds it: Livewire shares that component
* with every view as $__livewire. Livewire isn't a dependency; it's only looked for. [false, null] otherwise.
* $key reads inside it: a range bound to period reads period.start.
*
* @return array{0: bool, 1: mixed}
*/
public function fromLivewire(?string $key = null): array
{
$component = $this->bound === null ? null : view()->shared('__livewire');
return is_object($component) ? [true, data_get($component, $key === null ? $this->bound : "{$this->bound}.{$key}")] : [false, null];
}
/**
* The binding attribute as written (wire:model.live => period), to put on the inputs that carry the value: a range
* picker binds period.start and period.end with the same modifiers. Empty without one.
*
* @return array<string, string>
*/
public static function binding(ComponentAttributeBag $attributes): array
{
foreach ($attributes->getAttributes() as $attribute => $value) {
if (is_string($value) && $value !== '' && (str_starts_with($attribute, 'wire:model') || str_starts_with($attribute, 'x-model'))) {
return [$attribute => $value];
}
}
return [];
}
/**
* Whether a checkbox or switch renders ticked. An unticked box isn't in the request at all, so after a
* failed submit "no old value" means unticked, but only when that submit was this box's own form. A page
* with a second form (or a disabled box, which is never sent) would otherwise lose every `checked`.
*
* @param bool $alwaysSent it has an unchecked-value, so its form always sends something under its name
* @param mixed $errorBag the view's shared $errors
*/
public function checked(mixed $value, bool $default, bool $disabled, bool $alwaysSent, mixed $errorBag, string $bag = 'default'): bool
{
// Bound to a Livewire property: that says, true/false, or for a list of boxes, whether it holds this value.
[$found, $live] = $this->fromLivewire();
if ($found) {
return is_array($live) ? in_array(self::text($value), array_map(self::text(...), $live), true) : (bool) $live;
}
if ($this->key === null || $disabled || !session()->hasOldInput()) {
return $default;
}
$old = old($this->key);
if ($old !== null) {
return in_array(self::text($value), array_map(self::text(...), Arr::wrap($old)), true);
}
// Nothing under this name, though this box always sends something: its form wasn't the one submitted.
if ($alwaysSent) {
return $default;
}
// A form with its own error bag: no errors in that bag means the failed submit was a different form.
if ($bag !== 'default') {
return $errorBag instanceof ViewErrorBag && $errorBag->getBag($bag)->isNotEmpty() ? false : $default;
}
// One form, or forms sharing the default bag: there's no telling them apart, so trust the old input.
return false;
}
/** Values cast to backed enums (Plan::Pro) compare as their backing value. */
private static function text(mixed $value): string
{
return (string) ($value instanceof \BackedEnum ? $value->value : $value);
}
/**
* What the caller passed, minus `class` (that styles the wrapper) and the aria attributes
* this widget manages itself. Goes on the element that is actually submitted.
*/
public function forwarded(ComponentAttributeBag $attributes): ComponentAttributeBag
{
return $attributes->except(['class', 'aria-invalid', 'aria-describedby']);
}
/**
* aria-invalid plus one aria-describedby that joins the error, the hint and the caller's own
* ids. Two separate aria-describedby attributes would make the browser silently drop one.
*/
public function aria(ComponentAttributeBag $attributes, bool $hasInfo = false): ComponentAttributeBag
{
$describedBy = array_filter([
$this->hasError() ? $this->errorId() : null,
$hasInfo ? $this->infoId() : null,
$attributes->get('aria-describedby'),
]);
return new ComponentAttributeBag([
'aria-invalid' => $this->hasError() ? 'true' : null,
'aria-describedby' => $describedBy === [] ? null : implode(' ', $describedBy),
]);
}
/**
* For a widget whose visible control isn't the submitted input (grouped number, phone): what belongs on the
* hidden input that carries the value. Which form it's in, and Livewire and Alpine bindings, go with the value.
*/
public function bindings(ComponentAttributeBag $attributes): ComponentAttributeBag
{
return $attributes->filter(static fn (mixed $value, string $key): bool => self::isBinding($key));
}
/**
* The other side of bindings(): everything else the caller passed (required, autofocus, aria-label,
* placeholder…) goes on the visible control, where the browser validates it and screen readers hear it.
*/
public function visibleAttributes(ComponentAttributeBag $attributes, bool $hasInfo = false): ComponentAttributeBag
{
return $this->controlAttributes($attributes->filter(static fn (mixed $value, string $key): bool => !self::isBinding($key)), $hasInfo);
}
private static function isBinding(string $key): bool
{
return $key === 'form' || str_starts_with($key, 'wire:model') || str_starts_with($key, 'x-model');
}
/**
* forwarded() and aria() together, for widgets whose visible control is also the submitted one.
*/
public function controlAttributes(ComponentAttributeBag $attributes, bool $hasInfo = false): ComponentAttributeBag
{
return $this->forwarded($attributes)->merge($this->aria($attributes, $hasInfo)->getAttributes());
}
}
app/View/Widget/LocalDate.php Show
<?php
declare(strict_types=1);
namespace App\View\Widget;
use IntlCalendar;
use IntlDateFormatter;
use IntlDatePatternGenerator;
/**
* How a locale writes and lays out dates, for the date pickers. The server renders the first paint with
* this and the browser (Intl.DateTimeFormat) takes over, both asking ICU for the same "year, short month,
* day" pattern, so a date reads "Sep 26, 2026" in en-US and "26 Sept 2026" in en-GB either way.
* Falls back to plain ISO dates when PHP's intl extension is missing.
*/
final class LocalDate
{
/** "en_GB" or "en-GB" → "en-GB", the form Intl in the browser expects. */
public static function locale(?string $locale = null): string
{
return str_replace('_', '-', $locale ?? app()->getLocale());
}
/**
* A Y-m-d date the way the locale writes it: "Sep 26, 2026", "26 Sept 2026", "2026年9月26日".
*/
public static function format(string $iso, ?string $locale = null): string
{
$locale = self::locale($locale);
if (!class_exists(IntlDatePatternGenerator::class)) {
return $iso;
}
$pattern = (new IntlDatePatternGenerator($locale))->getBestPattern('yMMMd');
$formatter = new IntlDateFormatter($locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, 'UTC', IntlDateFormatter::GREGORIAN, $pattern ?: 'y-MM-dd');
$formatted = $formatter->format(new \DateTimeImmutable($iso, new \DateTimeZone('UTC')));
return is_string($formatted) ? $formatted : $iso;
}
/**
* First day of the week, as JavaScript counts days (0 = Sunday … 6 = Saturday): Monday in most of
* the world, Sunday in the US, Saturday in parts of the Middle East.
*/
public static function firstDayOfWeek(?string $locale = null): int
{
if (!class_exists(IntlCalendar::class)) {
return 1; // ISO 8601
}
$calendar = IntlCalendar::createInstance(null, str_replace('-', '_', self::locale($locale)));
$first = $calendar instanceof IntlCalendar ? $calendar->getFirstDayOfWeek() : false;
// ICU counts 1 = Sunday … 7 = Saturday.
return is_int($first) ? ($first - 1) % 7 : 1;
}
}
app/Rules/LocalToday.php Show
<?php
declare(strict_types=1);
namespace App\Rules;
use Carbon\CarbonImmutable;
/**
* "Today" for date rules when users sit in many timezones and the app runs on UTC.
*
* The server's today can be a day behind a user's local today. Comparing against the
* first timezone on Earth to reach a new day never rejects a genuine local today, and
* still rejects anything that is in the future for everyone.
*/
final class LocalToday
{
// UTC+14: the earliest timezone, so its date is the latest "today" anywhere.
private const string EARLIEST_TIMEZONE = 'Pacific/Kiritimati';
public static function latest(): CarbonImmutable
{
return CarbonImmutable::now(self::EARLIEST_TIMEZONE)->startOfDay();
}
/** Parses a strict Y-m-d date, as submitted by the date picker; anything else is null. */
public static function parse(mixed $value): ?CarbonImmutable
{
if (!is_string($value) || preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value, $parts) !== 1) {
return null;
}
if (!checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1])) {
return null;
}
return CarbonImmutable::createFromFormat('!Y-m-d', $value, self::EARLIEST_TIMEZONE);
}
}
app/Rules/MinimumAge.php Show
<?php
declare(strict_types=1);
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
/**
* Server-side twin of the date picker's `birthday` limit: the person must have reached
* `$years` on their own local today.
*/
final class MinimumAge implements ValidationRule
{
public function __construct(private readonly int $years = 18) {}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$birthDate = LocalToday::parse($value);
if ($birthDate === null) {
$fail('The :attribute must be a valid date.');
return;
}
// Overflow matches the browser: someone born on 29 Feb comes of age on 1 Mar in non-leap years.
$latestAllowed = LocalToday::latest()->subYearsWithOverflow($this->years);
if ($birthDate->greaterThan($latestAllowed)) {
$fail("You must be at least {$this->years} years old.");
}
}
}
app/Rules/NotAfterToday.php Show
<?php
declare(strict_types=1);
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
/**
* Server-side twin of the date picker's default "no future dates" limit.
* Use instead of 'before_or_equal:today', which uses the server's UTC date and can
* reject a user's genuine local today.
*/
final class NotAfterToday implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$date = LocalToday::parse($value);
if ($date === null) {
$fail('The :attribute must be a valid date.');
return;
}
if ($date->greaterThan(LocalToday::latest())) {
$fail('The :attribute may not be in the future.');
}
}
}