258 lines
13 KiB
Plaintext
258 lines
13 KiB
Plaintext
{% comment %}
|
|
Custom Calendar Input Component
|
|
Usage:
|
|
{% include calendar_input.liquid
|
|
id="unique_calendar_id" (required for multiple instances)
|
|
label="Select Date" (optional, defaults to "Select Date")
|
|
placeholder="YYYY-MM-DD" (optional, defaults to "YYYY-MM-DD")
|
|
value="2025-12-31" (optional, initial date in YYYY-MM-DD format)
|
|
%}
|
|
{% endcomment %}
|
|
<div class="relative" x-data="calendarInput_{{ include.id | default: 'default' }}()">
|
|
<label for="calendar-input-{{ include.id | default: 'default' }}" class="block text-xs font-medium text-gray-700 mb-1">{{ include.label | default: "Select Date" }}</label>
|
|
<div class="relative">
|
|
<input
|
|
type="text"
|
|
id="calendar-input-{{ include.id | default: 'default' }}"
|
|
name="{{ include.id | default: 'default' }}_date" {% comment %} Add a name attribute for form submission {% endcomment %}
|
|
x-ref="dateInput"
|
|
x-model="selectedDateFormatted"
|
|
@click="toggleCalendar()"
|
|
@keydown.escape="closeCalendar()"
|
|
readonly
|
|
placeholder="{{ include.placeholder | default: 'YYYY-MM-DD' }}"
|
|
class="w-full px-3 py-2 pr-10 border border-gray-300 rounded-sm focus:outline-none focus:border-indigo-700 focus:ring-1 focus:ring-indigo-700 text-sm cursor-pointer bg-white"
|
|
aria-haspopup="true"
|
|
:aria-expanded="isOpen.toString()"
|
|
aria-label="{{ include.label | default: 'Select Date' }}"
|
|
>
|
|
<div class="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
|
|
<svg class="h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
|
|
<path fill-rule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clip-rule="evenodd" />
|
|
</svg>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Calendar Dropdown -->
|
|
<div
|
|
x-show="isOpen"
|
|
@click.away="closeCalendar()"
|
|
x-transition:enter="transition ease-out duration-100"
|
|
x-transition:enter-start="opacity-0 transform scale-95"
|
|
x-transition:enter-end="opacity-100 transform scale-100"
|
|
x-transition:leave="transition ease-in duration-75"
|
|
x-transition:leave-start="opacity-100 transform scale-100"
|
|
x-transition:leave-end="opacity-0 transform scale-95"
|
|
class="absolute z-20 mt-1 w-full sm:w-72 bg-white shadow-lg rounded-base border border-gray-300 p-3"
|
|
style="display: none;" {% comment %} Prevents flash of unstyled content if JS is slow, Alpine handles visibility {% endcomment %}
|
|
>
|
|
<!-- Calendar Header: Month/Year Navigation -->
|
|
<div class="flex justify-between items-center mb-2.5">
|
|
<button @click="prevMonth()" type="button" class="p-1.5 rounded-full hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-indigo-500" aria-label="Previous month">
|
|
<svg class="w-5 h-5 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
|
|
</button>
|
|
<div class="text-sm font-semibold text-gray-800" x-text="`${monthNames[currentMonth]} ${currentYear}`"></div>
|
|
<button @click="nextMonth()" type="button" class="p-1.5 rounded-full hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-indigo-500" aria-label="Next month">
|
|
<svg class="w-5 h-5 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg>
|
|
</button>
|
|
</div>
|
|
|
|
<!-- Days of the Week -->
|
|
<div class="grid grid-cols-7 gap-1 text-center text-xs text-gray-500 mb-1.5">
|
|
<template x-for="dayName in dayShortNames" :key="dayName">
|
|
<div x-text="dayName" class="w-8 h-8 flex items-center justify-center"></div>
|
|
</template>
|
|
</div>
|
|
|
|
<!-- Dates Grid -->
|
|
<div class="grid grid-cols-7 gap-0.5">
|
|
<template x-for="blankday in blankDays" :key="`blank-${blankday}`">
|
|
<div class="w-8 h-8 border border-transparent"></div>
|
|
</template>
|
|
<template x-for="dayNumber in daysInMonth" :key="dayNumber">
|
|
<button
|
|
type="button"
|
|
@click="selectDate(dayNumber)"
|
|
x-text="dayNumber"
|
|
class="w-8 h-8 flex items-center justify-center text-center text-sm rounded-full focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-indigo-500"
|
|
:class="{
|
|
'bg-indigo-700 text-white hover:bg-indigo-800': isSelectedDate(dayNumber),
|
|
'text-gray-700 hover:bg-gray-100': !isSelectedDate(dayNumber) && !isToday(dayNumber) && !isPastDate(dayNumber),
|
|
'text-indigo-700 font-semibold border border-indigo-600 hover:bg-indigo-50': isToday(dayNumber) && !isSelectedDate(dayNumber),
|
|
'text-gray-400 cursor-not-allowed hover:bg-transparent': isPastDate(dayNumber)
|
|
}"
|
|
:disabled="isPastDate(dayNumber)"
|
|
:aria-label="`Select date ${dayNumber} ${monthNames[currentMonth]} ${currentYear}`"
|
|
:aria-pressed="isSelectedDate(dayNumber).toString()"
|
|
></button>
|
|
</template>
|
|
</div>
|
|
|
|
<!-- Calendar Footer -->
|
|
<div class="mt-3 pt-2.5 border-t border-gray-200 flex justify-between items-center">
|
|
<button @click="goToToday()" type="button" class="text-xs text-indigo-700 hover:text-indigo-900 font-medium focus:outline-none focus:underline">Today</button>
|
|
<button @click="clearDate(); closeCalendar();" type="button" class="text-xs text-gray-600 hover:text-gray-800 font-medium focus:outline-none focus:underline">Clear</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
function calendarInput_{{ include.id | default: 'default' }}() {
|
|
return {
|
|
isOpen: false,
|
|
selectedDate: null,
|
|
selectedDateFormatted: '',
|
|
currentMonth: new Date().getMonth(),
|
|
currentYear: new Date().getFullYear(),
|
|
today: new Date(new Date().setHours(0, 0, 0, 0)),
|
|
|
|
monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
|
|
dayShortNames: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
|
|
|
|
init() {
|
|
let initialDateStr = "{{ include.value }}";
|
|
if (initialDateStr) {
|
|
const parts = initialDateStr.split('-');
|
|
if (parts.length === 3) {
|
|
const initialY = parseInt(parts[0], 10);
|
|
const initialM = parseInt(parts[1], 10) - 1; // Month is 0-indexed
|
|
const initialD = parseInt(parts[2], 10);
|
|
const date = new Date(initialY, initialM, initialD);
|
|
// Check if date is valid and not a past date
|
|
if (!isNaN(date.getTime()) && date.getTime() >= this.today.getTime()) {
|
|
this.selectedDate = date;
|
|
this.currentMonth = date.getMonth();
|
|
this.currentYear = date.getFullYear();
|
|
} else if (!isNaN(date.getTime()) && this.isSameDay(date, this.today)) { // Allow today even if initial value was set to today
|
|
this.selectedDate = date;
|
|
this.currentMonth = date.getMonth();
|
|
this.currentYear = date.getFullYear();
|
|
}
|
|
}
|
|
}
|
|
|
|
this.selectedDateFormatted = this.selectedDate ? this.formatDateForInput(this.selectedDate) : '';
|
|
|
|
this.$watch('selectedDate', (value) => {
|
|
this.selectedDateFormatted = value ? this.formatDateForInput(value) : '';
|
|
if (value) {
|
|
// Dispatch event for external listeners, e.g., other Alpine components or JS
|
|
this.$refs.dateInput.dispatchEvent(new CustomEvent('date-selected', {
|
|
detail: {
|
|
date: value,
|
|
formattedDate: this.selectedDateFormatted
|
|
},
|
|
bubbles: true
|
|
}));
|
|
}
|
|
});
|
|
},
|
|
|
|
toggleCalendar() { this.isOpen = !this.isOpen; if(this.isOpen) { this.$nextTick(() => { this.focusCalendar(); }); } },
|
|
openCalendar() { if (!this.isOpen) { this.isOpen = true; this.$nextTick(() => { this.focusCalendar(); }); } },
|
|
closeCalendar() { this.isOpen = false; },
|
|
|
|
focusCalendar() {
|
|
// Focus the first focusable element in the calendar, e.g., the "previous month" button
|
|
// This helps with keyboard navigation accessibility.
|
|
// Or, find the selected/today button and focus it.
|
|
const calendarElement = this.$el.querySelector('[x-show="isOpen"]');
|
|
if (calendarElement) {
|
|
const focusableElement = calendarElement.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
|
|
if(focusableElement) focusableElement.focus();
|
|
}
|
|
},
|
|
|
|
formatDateForInput(date) {
|
|
if (!date) return '';
|
|
const year = date.getFullYear();
|
|
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
|
const day = date.getDate().toString().padStart(2, '0');
|
|
return `${year}-${month}-${day}`;
|
|
},
|
|
|
|
isSameDay(date1, date2) {
|
|
if (!date1 || !date2) return false;
|
|
return date1.getFullYear() === date2.getFullYear() &&
|
|
date1.getMonth() === date2.getMonth() &&
|
|
date1.getDate() === date2.getDate();
|
|
},
|
|
|
|
get blankDays() {
|
|
const firstDayOfMonth = new Date(this.currentYear, this.currentMonth, 1).getDay();
|
|
return Array.from({ length: firstDayOfMonth }, (_, i) => i + 1);
|
|
},
|
|
|
|
get daysInMonth() {
|
|
const numDays = new Date(this.currentYear, this.currentMonth + 1, 0).getDate();
|
|
return Array.from({ length: numDays }, (_, i) => i + 1);
|
|
},
|
|
|
|
isSelectedDate(dayNumber) {
|
|
if (!this.selectedDate) return false;
|
|
return this.selectedDate.getDate() === dayNumber &&
|
|
this.selectedDate.getMonth() === this.currentMonth &&
|
|
this.selectedDate.getFullYear() === this.currentYear;
|
|
},
|
|
|
|
isToday(dayNumber) {
|
|
const dateToCheck = new Date(this.currentYear, this.currentMonth, dayNumber);
|
|
return this.isSameDay(dateToCheck, this.today);
|
|
},
|
|
|
|
isPastDate(dayNumber) {
|
|
const dateToCheck = new Date(this.currentYear, this.currentMonth, dayNumber);
|
|
return dateToCheck.getTime() < this.today.getTime();
|
|
},
|
|
|
|
selectDate(dayNumber) {
|
|
const dateToSelect = new Date(this.currentYear, this.currentMonth, dayNumber);
|
|
if (this.isPastDate(dayNumber)) {
|
|
return; // Do not select past dates
|
|
}
|
|
this.selectedDate = dateToSelect;
|
|
// Do not automatically jump month/year on selection, user might want to see the selected date in context.
|
|
// this.currentMonth = dateToSelect.getMonth();
|
|
// this.currentYear = dateToSelect.getFullYear();
|
|
this.closeCalendar();
|
|
},
|
|
|
|
prevMonth() {
|
|
if (this.currentMonth === 0) {
|
|
this.currentMonth = 11;
|
|
this.currentYear--;
|
|
} else {
|
|
this.currentMonth--;
|
|
}
|
|
},
|
|
|
|
nextMonth() {
|
|
if (this.currentMonth === 11) {
|
|
this.currentMonth = 0;
|
|
this.currentYear++;
|
|
} else {
|
|
this.currentMonth++;
|
|
}
|
|
},
|
|
|
|
goToToday() {
|
|
this.currentMonth = this.today.getMonth();
|
|
this.currentYear = this.today.getFullYear();
|
|
// Select today only if it's not already selected, to avoid unnecessary event dispatches
|
|
if (!this.isSameDay(this.selectedDate, this.today)) {
|
|
this.selectedDate = new Date(this.today.getTime()); // Create a new Date object for today
|
|
}
|
|
// If calendar is open, and user clicks "Today", it implies selection.
|
|
// If they want to just navigate, they can use prev/next month.
|
|
// If calendar is closed, and they open it and click "Today", it should select.
|
|
this.closeCalendar(); // Close after selecting today
|
|
},
|
|
|
|
clearDate() {
|
|
this.selectedDate = null;
|
|
// this.closeCalendar(); // Already handled by button @click
|
|
}
|
|
};
|
|
}
|
|
</script>
|