Added custom date format

This commit is contained in:
2026-07-18 00:47:14 +10:00
parent 792cb082fd
commit 39c0ce1b44
7 changed files with 112 additions and 212 deletions
+76 -164
View File
@@ -41,95 +41,9 @@ const isEdit = !!props.flight
// ── User format preferences ─────────────────────────────────────────────────
const timeFormat = computed(() => page.auth?.user?.resolved_settings?.time_format ?? 'ampm')
// day.js/date-fns-style tokens, e.g. 'D MMM YYYY' -> "7 Dec 2026". Not user-configurable yet.
const dateFormat = computed(() => 'DD-MM-YYYY')
// ── Date token formatting/parsing helpers (D, DD, M, MM, MMM, MMMM, YY, YYYY) ──
const pad = (n: number) => String(n).padStart(2, '0')
const MONTHS_SHORT = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
const MONTHS_LONG = ['January','February','March','April','May','June','July','August','September','October','November','December']
// Formats a Date according to a token format string. Tokens matched longest-first
// so e.g. "YYYY" isn't partially consumed by a lone "Y"-style rule.
function formatDateForFormat(d: Date | null, format: string): string {
if (!d) return ''
return format.replace(/YYYY|YY|MMMM|MMM|MM|M|DD|D/g, (token) => {
switch (token) {
case 'YYYY': return String(d.getFullYear())
case 'YY': return String(d.getFullYear()).slice(-2)
case 'MMMM': return MONTHS_LONG[d.getMonth()]
case 'MMM': return MONTHS_SHORT[d.getMonth()]
case 'MM': return pad(d.getMonth() + 1)
case 'M': return String(d.getMonth() + 1)
case 'DD': return pad(d.getDate())
case 'D': return String(d.getDate())
default: return token
}
})
}
// Extracts the ordered list of D/M/Y tokens from a format string, e.g.
// "D MMM YYYY" -> ['D', 'MMM', 'YYYY']
function getFormatTokens(format: string): string[] {
return format.match(/YYYY|YY|MMMM|MMM|MM|M|DD|D/g) ?? ['D', 'MMM', 'YYYY']
}
// Parses user-typed text into a Date, following the token order of `format`.
// Splits on any run of non-alphanumeric characters, so "/", "-", ".", and
// spaces are all accepted as separators regardless of what the format uses.
// Month tokens (MMM/MMMM) match against month names case-insensitively.
function parseDateInputStr(input: string, format: string): Date | null {
const trimmed = input.trim()
if (!trimmed) return null
const parts = trimmed.split(/[^a-zA-Z0-9]+/).filter(Boolean)
const tokens = getFormatTokens(format)
if (parts.length !== tokens.length) return null
let day: number | null = null
let month: number | null = null // 0-indexed
let year: number | null = null
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i]
const part = parts[i]
if (token === 'D' || token === 'DD') {
const val = parseInt(part, 10)
if (isNaN(val)) return null
day = val
} else if (token === 'M' || token === 'MM') {
const val = parseInt(part, 10)
if (isNaN(val)) return null
month = val - 1
} else if (token === 'MMM' || token === 'MMMM') {
const lower = part.toLowerCase()
const idx = MONTHS_LONG.findIndex(m => m.toLowerCase().startsWith(lower) || lower.startsWith(m.slice(0, 3).toLowerCase()))
if (idx === -1) return null
month = idx
} else if (token === 'YYYY') {
const val = parseInt(part, 10)
if (isNaN(val)) return null
year = val
} else if (token === 'YY') {
const val = parseInt(part, 10)
if (isNaN(val)) return null
year = val < 100 ? 2000 + val : val
}
}
if (day === null || month === null || year === null) return null
const date = new Date(year, month, day)
// Reject dates that overflowed (e.g. day 31 in a 30-day month)
if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
return null
}
return date
}
// ── Flight number lookup ──────────────────────────────────────────────────────
const flightNumber = ref(props.flight?.flight_number ?? '')
@@ -397,47 +311,36 @@ const arrivalMax = computed(() => getArrivalBound(form, 3))
const arrivalMinDate = computed(() => arrivalMin.value ? new Date(arrivalMin.value) : undefined)
const arrivalMaxDate = computed(() => arrivalMax.value ? new Date(arrivalMax.value) : undefined)
// ── Editable, format-aware date text inputs ─────────────────────────────────
// ── Native date inputs ───────────────────────────────────────────────────────
// departureDatePart / arrivalDatePart stay the source of truth as Date
// objects. These input refs are what the text-fields actually bind to, so
// the user can type freely; parsing only commits on blur/enter.
// objects. These computed get/set pairs are what the native <input type=date>
// elements bind to — the browser handles locale display, typing, and
// validation itself, so no custom format-aware parsing is needed here.
// The Vuetify v-date-picker is still available via a separate calendar icon
// for users who prefer to pick from a calendar rather than type.
const departureDateInput = ref(formatDateForFormat(departureDatePart.value, dateFormat.value))
const arrivalDateInput = ref(formatDateForFormat(arrivalDatePart.value, dateFormat.value))
watch([departureDatePart, dateFormat], () => {
departureDateInput.value = formatDateForFormat(departureDatePart.value, dateFormat.value)
})
watch([arrivalDatePart, dateFormat], () => {
arrivalDateInput.value = formatDateForFormat(arrivalDatePart.value, dateFormat.value)
})
function commitDepartureDateInput() {
if (!departureDateInput.value.trim()) {
departureDatePart.value = null
return
}
const parsed = parseDateInputStr(departureDateInput.value, dateFormat.value)
if (parsed) {
departureDatePart.value = parsed
} else {
departureDateInput.value = formatDateForFormat(departureDatePart.value, dateFormat.value)
}
function toIsoDateString(d: Date | null): string {
if (!d) return ''
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
}
function commitArrivalDateInput() {
if (!arrivalDateInput.value.trim()) {
arrivalDatePart.value = null
return
}
const parsed = parseDateInputStr(arrivalDateInput.value, dateFormat.value)
if (parsed) {
arrivalDatePart.value = parsed
} else {
arrivalDateInput.value = formatDateForFormat(arrivalDatePart.value, dateFormat.value)
}
function fromIsoDateString(value: string): Date | null {
if (!value) return null
const [y, m, d] = value.split('-').map(Number)
if (!y || !m || !d) return null
return new Date(y, m - 1, d)
}
const departureDateValue = computed({
get: () => toIsoDateString(departureDatePart.value),
set: (value: string) => { departureDatePart.value = fromIsoDateString(value) },
})
const arrivalDateValue = computed({
get: () => toIsoDateString(arrivalDatePart.value),
set: (value: string) => { arrivalDatePart.value = fromIsoDateString(value) },
})
// ── Editable, format-aware time text fields ────────────────────────────────
// departureTimePart / arrivalTimePart stay the source of truth as internal
// "HH:mm" (24hr) strings. These input refs are what the text-fields actually
@@ -569,28 +472,30 @@ function commitArrivalTimeInput() {
<!-- Departure date + time -->
<v-row>
<v-col cols="12" sm="6">
<v-menu v-model="depDateMenu" :close-on-content-click="false">
<template #activator="{ props: menuProps }">
<v-text-field
v-bind="menuProps"
v-model="departureDateInput"
label="Departure Date"
clearable
prepend-inner-icon="mdi-calendar"
:placeholder="dateFormat"
:disabled="!lookupComplete"
:error-messages="submitForm.errors.departure_date"
@click:clear="clearDepartureDate"
@blur="commitDepartureDateInput"
@keydown.enter="commitDepartureDateInput"
autocomplete="false"
/>
<v-text-field
v-model="departureDateValue"
type="date"
label="Departure Date"
prepend-inner-icon="mdi-calendar"
:disabled="!lookupComplete"
:error-messages="submitForm.errors.departure_date"
>
<template #append-inner>
<v-menu v-model="depDateMenu" :close-on-content-click="false">
<template #activator="{ props: menuProps }">
<v-icon
v-bind="menuProps"
icon="mdi-calendar-month"
style="cursor: pointer"
/>
</template>
<v-date-picker
v-model="departureDatePart"
@update:model-value="depDateMenu = false"
/>
</v-menu>
</template>
<v-date-picker
v-model="departureDatePart"
@update:model-value="depDateMenu = false"
/>
</v-menu>
</v-text-field>
</v-col>
<v-col cols="12" sm="6">
<v-menu v-model="depTimeMenu" :close-on-content-click="false">
@@ -626,29 +531,32 @@ function commitArrivalTimeInput() {
<!-- Arrival date + time -->
<v-row>
<v-col cols="12" sm="6">
<v-menu v-model="arrDateMenu" :close-on-content-click="false">
<template #activator="{ props: menuProps }">
<v-text-field
v-bind="menuProps"
v-model="arrivalDateInput"
label="Arrival Date"
clearable
prepend-inner-icon="mdi-calendar"
:placeholder="dateFormat"
:disabled="!lookupComplete"
:error-messages="submitForm.errors.arrival_date"
@click:clear="clearArrivalDate"
@blur="commitArrivalDateInput"
@keydown.enter="commitArrivalDateInput"
/>
<v-text-field
v-model="arrivalDateValue"
type="date"
label="Arrival Date"
prepend-inner-icon="mdi-calendar"
:disabled="!lookupComplete"
:error-messages="submitForm.errors.arrival_date"
>
<template #append-inner>
<v-menu v-model="arrDateMenu" :close-on-content-click="false">
<template #activator="{ props: menuProps }">
<v-icon
v-bind="menuProps"
icon="mdi-calendar-month"
style="cursor: pointer"
/>
</template>
<v-date-picker
v-model="arrivalDatePart"
:min="arrivalMinDate"
:max="arrivalMaxDate"
@update:model-value="arrDateMenu = false"
/>
</v-menu>
</template>
<v-date-picker
v-model="arrivalDatePart"
:min="arrivalMinDate"
:max="arrivalMaxDate"
@update:model-value="arrDateMenu = false"
/>
</v-menu>
</v-text-field>
</v-col>
<v-col cols="12" sm="6">
<v-menu v-model="arrTimeMenu" :close-on-content-click="false">
@@ -860,4 +768,8 @@ function commitArrivalTimeInput() {
</template>
<style scoped>
:deep(input[type="date"]::-webkit-calendar-picker-indicator) {
display: none;
-webkit-appearance: none;
}
</style>
-1
View File
@@ -191,7 +191,6 @@ watch(() => form.flight_reason, (val) => console.log('flight_reason changed:', v
<v-select v-model="form.seat_type" label="Seat Type" :items="flight.seat_types" :error-messages="submitForm.errors.seat_type_id" />
</v-col>
<v-col cols="12" md="6">
{{console.log(form.flight_reason)}}
<v-select v-model="form.flight_reason" label="Reason" :items="flight.flight_reasons" :error-messages="submitForm.errors.flight_reason_id" />
</v-col>
</v-row>