feat: Create CSS-only scrolling date picker visual mock-up

This commit is contained in:
Kerby Martino (aider) committed 2025-05-11 05:28:01 +08:00
1 parent 13583e8ef7
commit 9175335d05
1 file changed
+93 -217
+93 -217
View File
@@ -1,29 +1,40 @@
{% comment %} {% comment %}
Custom Calendar Input Component Pure CSS Scrolling Date Picker Visual Mock-up
Usage: Usage:
{% include calendar_input.liquid {% include calendar_input.liquid
id="unique_calendar_id" (required for multiple instances) id="unique_calendar_id" (required for multiple instances)
label="Select Date" (optional, defaults to "Select Date") label="Select Date" (optional, defaults to "Select Date")
placeholder="YYYY-MM-DD" (optional, defaults to "YYYY-MM-DD") placeholder="YYYY-MM-DD" (optional, defaults to "YYYY-MM-DD")
value="2025-12-31" (optional, initial date in YYYY-MM-DD format)
%} %}
This component is a visual mock-up and does not provide actual date selection functionality.
The input field will not be updated by this picker.
{% endcomment %} {% endcomment %}
<div class="relative" x-data="calendarInput_{{ include.id | default: 'default' }}()">
{% assign current_year = "now" | date: "%Y" | plus: 0 %}
{% assign future_year_limit = current_year | plus: 10 %}
{% assign years = "" %}
{% for i in (current_year..future_year_limit) %}
{% assign years = years | append: i | append: "," %}
{% endfor %}
{% assign years_array = years | split: "," %}
{% assign months_array = "January,February,March,April,May,June,July,August,September,October,November,December" | split: "," %}
{% assign days_array = "" %}
{% for i in (1..31) %}
{% assign days_array = days_array | append: i | append: "," %}
{% endfor %}
{% assign days_array = days_array | split: "," %}
<div class="relative group">
<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> <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"> <div class="relative">
<input <input
type="text" type="text"
id="calendar-input-{{ include.id | default: 'default' }}" id="calendar-input-{{ include.id | default: 'default' }}"
name="{{ include.id | default: 'default' }}_date" {% comment %} Add a name attribute for form submission {% endcomment %} name="{{ include.id | default: 'default' }}_date_display"
x-ref="dateInput"
x-model="selectedDateFormatted"
@click="toggleCalendar()"
@keydown.escape="closeCalendar()"
readonly readonly
placeholder="{{ include.placeholder | default: 'YYYY-MM-DD' }}" 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" 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 peer"
aria-haspopup="true"
:aria-expanded="isOpen.toString()"
aria-label="{{ include.label | default: 'Select Date' }}" aria-label="{{ include.label | default: 'Select Date' }}"
> >
<div class="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none"> <div class="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
@@ -33,225 +44,90 @@ Usage:
</div> </div>
</div> </div>
<!-- Calendar Dropdown --> <!-- CSS-only "Dropdown" - Appears on input focus or hover of the parent div -->
<div <!-- For a pure CSS dropdown, we often rely on :focus-within or :hover on a parent.
x-show="isOpen" Here, using :focus on the input (peer) to show the picker.
@click.away="closeCalendar()" Alternatively, wrap input and picker in a div and use group-hover.
x-transition:enter="transition ease-out duration-100" For simplicity, this example shows it on input focus.
x-transition:enter-start="opacity-0 transform scale-95" -->
x-transition:enter-end="opacity-100 transform scale-100" <div class="absolute z-20 mt-1 w-full sm:w-80 bg-white shadow-lg rounded-base border border-gray-300 p-3
x-transition:leave="transition ease-in duration-75" opacity-0 pointer-events-none peer-focus:opacity-100 peer-focus:pointer-events-auto
x-transition:leave-start="opacity-100 transform scale-100" group-hover:opacity-100 group-hover:pointer-events-auto
x-transition:leave-end="opacity-0 transform scale-95" transition-opacity duration-150 ease-in-out">
class="absolute z-20 mt-1 w-full sm:w-72 bg-white shadow-lg rounded-base border border-gray-300 p-3" <div class="flex justify-between items-stretch h-48 relative">
style="display: none;" {% comment %} Prevents flash of unstyled content if JS is slow, Alpine handles visibility {% endcomment %} <!-- Selection Indicator Line -->
> <div class="absolute top-1/2 left-0 right-0 h-px bg-indigo-300 -translate-y-1/2 z-0"></div>
<!-- Calendar Header: Month/Year Navigation --> <div class="absolute top-1/2 left-0 right-0 h-8 bg-indigo-50 -translate-y-1/2 z-0 rounded-sm"></div>
<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> <!-- Year Column -->
</button> <div class="flex-1 overflow-y-scroll scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100 relative z-10">
<div class="text-sm font-semibold text-gray-800" x-text="`${monthNames[currentMonth]} ${currentYear}`"></div> <div class="flex flex-col items-center justify-start pt-16 pb-16"> <!-- Padding top/bottom to center items -->
<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"> {% for year_val in years_array %}
<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> {% if year_val != "" %}
</button> <div class="h-8 flex items-center justify-center text-sm text-gray-700 hover:text-indigo-700 w-full cursor-default">{{ year_val }}</div>
{% endif %}
{% endfor %}
</div>
</div> </div>
<!-- Days of the Week --> <!-- Month Column -->
<div class="grid grid-cols-7 gap-1 text-center text-xs text-gray-500 mb-1.5"> <div class="flex-1 overflow-y-scroll scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100 relative z-10">
<template x-for="dayName in dayShortNames" :key="dayName"> <div class="flex flex-col items-center justify-start pt-16 pb-16">
<div x-text="dayName" class="w-8 h-8 flex items-center justify-center"></div> {% for month_val in months_array %}
</template> {% if month_val != "" %}
<div class="h-8 flex items-center justify-center text-sm text-gray-700 hover:text-indigo-700 w-full cursor-default">{{ month_val }}</div>
{% endif %}
{% endfor %}
</div>
</div> </div>
<!-- Dates Grid --> <!-- Day Column -->
<div class="grid grid-cols-7 gap-0.5"> <div class="flex-1 overflow-y-scroll scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100 relative z-10">
<template x-for="blankday in blankDays" :key="`blank-${blankday}`"> <div class="flex flex-col items-center justify-start pt-16 pb-16">
<div class="w-8 h-8 border border-transparent"></div> {% for day_val in days_array %}
</template> {% if day_val != "" %}
<template x-for="dayNumber in daysInMonth" :key="dayNumber"> <div class="h-8 flex items-center justify-center text-sm text-gray-700 hover:text-indigo-700 w-full cursor-default">{{ day_val }}</div>
<button {% endif %}
type="button" {% endfor %}
@click="selectDate(dayNumber)" </div>
x-text="dayNumber" </div>
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> </div>
<!-- Calendar Footer --> <!-- Buttons Below -->
<div class="mt-3 pt-2.5 border-t border-gray-200 flex justify-between items-center"> <div class="mt-3 pt-2.5 border-t border-gray-200 flex justify-end items-center space-x-2">
<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 type="button" class="text-xs text-gray-600 hover:text-gray-800 font-medium px-3 py-1.5 rounded-sm hover:bg-gray-100 focus:outline-none focus:ring-1 focus:ring-indigo-500">Cancel</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> <button type="button" class="text-xs text-white bg-indigo-700 hover:bg-indigo-800 font-medium px-3 py-1.5 rounded-sm focus:outline-none focus:ring-1 focus:ring-offset-1 focus:ring-indigo-500">Set Date</button>
</div> </div>
<p class="text-xs text-gray-500 mt-2 text-center">This is a visual mock-up. Date selection is not functional.</p>
</div> </div>
</div> </div>
<script> <style>
function calendarInput_{{ include.id | default: 'default' }}() { /* Minimal scrollbar styling for webkit browsers */
return { .scrollbar-thin::-webkit-scrollbar {
isOpen: false, width: 6px;
selectedDate: null, height: 6px;
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();
} }
.scrollbar-thin::-webkit-scrollbar-track {
background: #f1f1f1; /* gray-100 approx */
border-radius: 10px;
} }
.scrollbar-thin::-webkit-scrollbar-thumb {
background: #d1d5db; /* gray-300 approx */
border-radius: 10px;
}
.scrollbar-thin::-webkit-scrollbar-thumb:hover {
background: #9ca3af; /* gray-400 approx */
} }
this.selectedDateFormatted = this.selectedDate ? this.formatDateForInput(this.selectedDate) : ''; /* For Firefox */
.scrollbar-thin {
this.$watch('selectedDate', (value) => { scrollbar-width: thin;
this.selectedDateFormatted = value ? this.formatDateForInput(value) : ''; scrollbar-color: #d1d5db #f1f1f1;
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(); }); } }, /* Ensure scrolling snaps to items if desired (more complex, browser support varies) */
openCalendar() { if (!this.isOpen) { this.isOpen = true; this.$nextTick(() => { this.focusCalendar(); }); } }, /* Basic approach: each item has a fixed height, scroll container has a height multiple of item height */
closeCalendar() { this.isOpen = false; }, /* The pt-16/pb-16 on the inner divs of scroll columns is a hack to "center" the first/last few items against the selection line */
</style>
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>