Add more airlines and fix edit bugs

This commit is contained in:
2026-04-20 16:42:11 +10:00
parent 061ee9dd07
commit e007824fa9
15 changed files with 458 additions and 276 deletions
@@ -18,7 +18,7 @@ const chartOptions = computed(() => ({
type: 'donut',
background: 'transparent',
fontFamily: 'inherit',
lazy: true,
animations: { enabled: false },
},
theme: { mode: 'dark' },
labels: props.labels,
@@ -64,20 +64,16 @@ const chartOptions = computed(() => ({
},
}))
const ready = ref(false)
</script>
<template>
<div class="chart-wrap">
<div class="chart-title">{{ title }}</div>
<PlaneLoader v-if="!ready" />
<VueApexCharts
type="donut"
:height="height"
:options="options ?? chartOptions"
:series="series"
:class="{ 'chart-hidden': !ready }"
@mounted="ready = true"
/>
</div>
</template>
@@ -100,4 +96,8 @@ const ready = ref(false)
.chart-hidden {
visibility: hidden;
}
:deep(svg) {
outline: none;
}
</style>
@@ -37,7 +37,7 @@ const chartOptions = computed(() => ({
toolbar: { show: false },
animations: { enabled: false },
stacked: true,
lazy: true,
animation: { enabled: false },
},
theme: { mode: 'dark' },
plotOptions: {
@@ -74,7 +74,6 @@ const chartOptions = computed(() => ({
},
}))
const ready = ref(false)
</script>
<template>
@@ -83,14 +82,11 @@ const ready = ref(false)
<div v-if="categories.length" class="chart-outer">
<div class="chart-scroll" :style="{ height: scrollHeight }">
<PlaneLoader v-if="!ready" />
<VueApexCharts
type="bar"
:height="chartHeight"
:options="options ?? chartOptions"
:series="series"
:class="{ 'chart-hidden': !ready }"
@mounted="ready = true"
/>
</div>
@@ -167,6 +163,10 @@ const ready = ref(false)
color: #445566;
}
:deep(svg) {
outline: none;
}
.chart-hidden {
visibility: hidden;
}
@@ -1,6 +1,5 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import PlaneLoader from "@/Components/FlightsGoneBy/PlaneLoader.vue"
import { ref, watch, onMounted } from 'vue'
import VueApexCharts from 'vue3-apexcharts'
import { ChartType } from "@/Types/types"
@@ -8,19 +7,24 @@ const props = defineProps<{
type: ChartType
title: string
height: number | string
series: unknown[]
series: { name: string; data: number[] }[]
categories: unknown[]
options?: object
}>()
const chartOptions = computed(() => ({
const chartRef = ref()
const isUpdating = ref(false)
const ready = ref(false)
let rafId: number | null = null
const staticOptions = {
chart: {
type: 'bar',
stacked: true,
toolbar: { show: false },
background: 'transparent',
fontFamily: 'inherit',
lazy: true,
animations: { enabled: false },
},
theme: { mode: 'dark' },
plotOptions: {
@@ -37,12 +41,6 @@ const chartOptions = computed(() => ({
yaxis: { lines: { show: true } },
xaxis: { lines: { show: false } },
},
xaxis: {
categories: props.categories,
axisBorder: { show: false },
axisTicks: { show: false },
labels: { style: { colors: '#445566', fontSize: '12px' } },
},
yaxis: {
labels: { style: { colors: '#445566', fontSize: '12px' } },
},
@@ -58,23 +56,59 @@ const chartOptions = computed(() => ({
hover: { filter: { type: 'lighten', value: 0.1 } },
active: { filter: { type: 'none' } },
},
}))
}
const ready = ref(false)
const initialOptions = {
...staticOptions,
xaxis: {
categories: props.categories,
axisBorder: { show: false },
axisTicks: { show: false },
labels: { style: { colors: '#445566', fontSize: '12px' } },
},
}
onMounted(() => { ready.value = true })
watch(
[() => props.categories, () => props.series],
([cats, series]) => {
if (!ready.value) return
// Show skeleton immediately, defer the ApexCharts work
isUpdating.value = true
if (rafId !== null) cancelAnimationFrame(rafId)
rafId = requestAnimationFrame(() => {
chartRef.value?.updateOptions(
{ xaxis: { categories: cats } },
false,
false,
)
chartRef.value?.updateSeries(series, false)
isUpdating.value = false
rafId = null
})
},
{ deep: false }
)
</script>
<template>
<div class="chart-wrap">
<div class="chart-title">{{title}}</div>
<PlaneLoader v-if="!ready" />
<VueApexCharts
:type="type"
:height="height"
:options="options ?? chartOptions"
:series="series"
:class="{ 'chart-hidden': !ready }"
@mounted="ready = true"
/>
<div class="chart-title">{{ title }}</div>
<div class="chart-area" :style="{ height: typeof height === 'number' ? height + 'px' : height }">
<VueApexCharts
ref="chartRef"
:type="type"
:height="height"
:options="options ?? initialOptions"
:series="series"
:style="{ opacity: isUpdating ? 0 : 1 }"
class="apex-chart"
/>
<div v-if="isUpdating" class="chart-skeleton" />
</div>
</div>
</template>
@@ -93,12 +127,34 @@ const ready = ref(false)
letter-spacing: 0.08em;
}
.chart-empty {
height: 280px;
display: flex;
align-items: center;
justify-content: center;
font-size: 13px;
color: #445566;
.chart-area {
position: relative;
}
.apex-chart {
transition: opacity 0.15s ease;
}
.chart-skeleton {
position: absolute;
inset: 0;
border-radius: 6px;
background: linear-gradient(
90deg,
rgba(255, 255, 255, 0.03) 25%,
rgba(255, 255, 255, 0.07) 50%,
rgba(255, 255, 255, 0.03) 75%
);
background-size: 200% 100%;
animation: shimmer 1.2s ease-in-out infinite;
}
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
:deep(svg) {
outline: none;
}
</style>
@@ -3,7 +3,7 @@
import FlightClassBadge from "@/Components/FlightsGoneBy/FlightClassBadge.vue";
import AirlineLogo from "@/Components/FlightsGoneBy/AirlineLogo.vue";
import {Flight} from "@/Types/types";
import { computed, ref } from "vue";
import { computed, ref, watch, nextTick } from "vue";
import type { DataTableSortItem } from 'vuetify';
import InlineBadge from "@/Components/FlightsGoneBy/InlineBadge.vue";
import AirportToolTip from "@/Components/FlightsGoneBy/AirportToolTip.vue";
@@ -13,8 +13,10 @@ import {FlightStats} from "@/Composables/useFlightStats";
const props = defineProps<{
flightStats: FlightStats
canEdit: boolean
flightId?: number | null
}>()
const ITEMS_PER_PAGE = 25
const headers = [
{ title: '', key: 'airline', sortable: true },
@@ -50,15 +52,14 @@ const customKeySort = {
duration: (a: any, b: any) => (a ?? 0) - (b ?? 0),
}
// Track active sort state
const sortBy = ref<DataTableSortItem[]>([])
const currentPage = ref(1)
const today = new Date()
today.setHours(0, 0, 0, 0)
const isSorting = computed(() => sortBy.value.length > 0)
// Split flights into upcoming vs departed, sorted by date within each group
const upcomingFlights = computed(() =>
props.flightStats.upcomingFlights.value
)
@@ -69,7 +70,6 @@ const departedFlights = computed(() =>
.sort((a, b) => new Date(b.departure_date).getTime() - new Date(a.departure_date).getTime())
)
// Flat ordered list with group markers injected — used only when not sorting
type GroupedFlight = Flight & { _group?: 'upcoming' | 'departed'; _groupHeader?: boolean; _groupLabel?: string }
const groupedItems = computed<GroupedFlight[]>(() => {
@@ -88,7 +88,6 @@ const groupedItems = computed<GroupedFlight[]>(() => {
return result
})
// When sorting, pass all flights flat; when not sorting, pass grouped (headers will be rendered via #item slot trick)
const allFlights = computed(() => [
...props.flightStats.upcomingFlights.value,
...props.flightStats.pastFlights.value,
@@ -97,6 +96,34 @@ const allFlights = computed(() => [
const tableItems = computed(() =>
isSorting.value ? allFlights.value : groupedItems.value
)
watch(
[() => props.flightId, tableItems],
async ([id]) => {
if (!id) return
// Count the flight's position among data rows (skipping group headers)
const items = tableItems.value
let dataIndex = 0
let found = false
for (const item of items) {
if ((item as any)._groupHeader) continue
if ((item as any).id === id) { found = true; break }
dataIndex++
}
if (!found) return
currentPage.value = Math.floor(dataIndex / ITEMS_PER_PAGE) + 1
await nextTick()
const row = document.querySelector<HTMLElement>(`tr[data-flight-id="${id}"]`)
row?.scrollIntoView({ behavior: 'smooth', block: 'center' })
},
{ immediate: true }
)
</script>
<template>
@@ -104,14 +131,13 @@ const tableItems = computed(() =>
:headers="headers"
:custom-key-sort="customKeySort"
:items="tableItems"
:items-per-page="25"
:items-per-page="ITEMS_PER_PAGE"
v-model:sort-by="sortBy"
v-model:page="currentPage"
class="departures-table"
hover
>
<!-- GROUP HEADER ROW (injected as a fake item) -->
<template #item="{ item, columns }">
<!-- Section divider row -->
<template v-if="(item as any)._groupHeader && !isSorting">
<tr class="section-header-row">
<td :colspan="columns.length" class="section-header-cell">
@@ -133,34 +159,32 @@ const tableItems = computed(() =>
</tr>
</template>
<!-- Normal data row -->
<template v-else-if="!(item as any)._groupHeader">
<tr
class="v-data-table__tr"
:class="(item as any)._group && !isSorting ? `group-row--${(item as any)._group}` : ''"
:class="[
(item as any)._group && !isSorting ? `group-row--${(item as any)._group}` : '',
(item as any).id === flightId ? 'flight-row--highlighted' : '',
]"
:data-flight-id="(item as any).id"
>
<!-- Airline logo -->
<td class="v-data-table__td airline-logo-cell">
<AirlineLogo size="32" :airline="(item as any).airline" class="airline-logo-img" />
</td>
<!-- Flight number -->
<td class="v-data-table__td flight-number-cell">
<div class="flight-cell">
<span class="flight-number">{{ (item as any).flight_number }}</span>
</div>
</td>
<!-- Departure airport -->
<td class="v-data-table__td">
<AirportToolTip :airport="(item as Flight).departure_airport">
<span class="iata">{{ (item as Flight).departure_airport.display_code }}</span><br/>
<span class="iata">{{ (item as Flight).departure_airport.display_code }}</span><br/>
</AirportToolTip>
<span class="city-name">{{ (item as Flight).departure_airport.municipality }}</span>
<span class="city-name">{{ (item as Flight).departure_airport.municipality }}</span>
</td>
<!-- Arrival airport -->
<td class="v-data-table__td">
<AirportToolTip :airport="(item as Flight).arrival_airport">
<span class="iata">{{ (item as Flight).arrival_airport.display_code }}</span><br/>
@@ -168,17 +192,14 @@ const tableItems = computed(() =>
<span class="city-name">{{ (item as Flight).arrival_airport.municipality }}</span>
</td>
<!-- Departure date -->
<td class="v-data-table__td">
<span class="date-cell">{{ (item as Flight).departure_date_display }}</span>
</td>
<!-- Departure time -->
<td class="v-data-table__td">
<span class="time-cell">{{ (item as Flight).departure_time_display }}</span>
</td>
<!-- Arrival time -->
<td class="v-data-table__td">
<span class="time-cell">{{ (item as Flight).arrival_time_display }}</span>
<sup v-if="(item as Flight).arrival_day_difference" class="day-diff">
@@ -190,21 +211,18 @@ const tableItems = computed(() =>
<span class="mono-tag">{{ (item as Flight).duration_display ?? '—' }}</span>
</td>
<!-- Distance -->
<td class="v-data-table__td">
<span class="mono-tag distance-cell">
{{ (item as Flight).distance ? Math.round((item as Flight).distance).toLocaleString() + ' km' : '' }}
</span>
</td>
<!-- Aircraft -->
<td class="v-data-table__td">
<AircraftToolTip v-if="(item as any).aircraft" :aircraft="(item as any).aircraft">
<span class="mono-tag">{{ (item as any).aircraft?.designator }}</span>
</AircraftToolTip>
</td>
<!-- Class -->
<td class="v-data-table__td ">
<span class="class-cell">
<FlightClassBadge :flight="(item as Flight)" />
@@ -213,7 +231,6 @@ const tableItems = computed(() =>
</span>
</td>
<!-- Actions -->
<td class="v-data-table__td actions-cell">
<template v-if="canEdit">
<v-menu>
@@ -241,7 +258,6 @@ const tableItems = computed(() =>
</template>
</template>
<!-- Empty state -->
<template #no-data>
<div class="no-data">
<span>NO FLIGHTS ON RECORD</span>
@@ -251,14 +267,12 @@ const tableItems = computed(() =>
</template>
<style scoped>
/* ── Vuetify table overrides ── */
.departures-table {
background: transparent !important;
color: #c8cdd8 !important;
font-family: 'Barlow', sans-serif !important;
}
/* Header row */
:deep(.v-data-table-header__content) {
font-family: 'Share Tech Mono', monospace !important;
font-size: 0.68rem !important;
@@ -273,7 +287,6 @@ const tableItems = computed(() =>
padding: 0.75rem 1rem !important;
}
/* Body rows — alternating, no borders */
:deep(.v-data-table__tr:nth-child(odd)) {
background: rgba(255,255,255,0.025) !important;
}
@@ -293,7 +306,6 @@ const tableItems = computed(() =>
color: #c8cdd8 !important;
}
/* Footer / pagination */
:deep(.v-data-table-footer) {
background: transparent !important;
border-top: 1px solid rgba(255,255,255,0.06) !important;
@@ -310,13 +322,11 @@ const tableItems = computed(() =>
color: #ffc107 !important;
}
/* Sort icon colour */
:deep(.v-data-table-header__sort-icon) {
color: #ffc107 !important;
opacity: 0.5;
}
/* ── Section header rows ── */
.section-header-row {
background: transparent !important;
}
@@ -334,7 +344,6 @@ const tableItems = computed(() =>
position: relative;
}
/* Upcoming = amber accent */
.section-header-inner.upcoming .section-header-icon,
.section-header-inner.upcoming .section-header-label {
color: #ffc107;
@@ -344,7 +353,6 @@ const tableItems = computed(() =>
background: linear-gradient(to right, rgba(255,193,7,0.4), transparent);
}
/* Departed = muted slate */
.section-header-inner.departed .section-header-icon,
.section-header-inner.departed .section-header-label {
color: #778899;
@@ -383,7 +391,6 @@ const tableItems = computed(() =>
min-width: 2rem;
}
/* ── Airline + flight number fused cells ── */
:deep(.v-data-table__th:nth-child(1)) {
width: 50px !important;
min-width: 50px !important;
@@ -406,7 +413,6 @@ const tableItems = computed(() =>
padding-left: 0.5rem !important;
}
/* ── Cell styles ── */
.flight-cell {
display: flex;
align-items: center;
@@ -484,7 +490,6 @@ const tableItems = computed(() =>
gap: 0.5rem;
}
/* ── Empty state ── */
.no-data {
padding: 3rem;
text-align: center;
@@ -506,4 +511,14 @@ const tableItems = computed(() =>
letter-spacing: 0.08em !important;
color: #c8cdd8 !important;
}
/* ── Highlighted flight row ── */
.flight-row--highlighted {
box-shadow: inset 3px 0 0 #ffc107;
}
.flight-row--highlighted td {
background: rgba(255, 193, 7, 0.08) !important;
transition: background 0.3s ease;
}
</style>
@@ -24,44 +24,46 @@ defineProps<{
</script>
<template>
<!-- Year full width -->
<div class="flight-charts glass">
<FlightsPerYearChart :flight-stats="flightStats" />
</div>
<!-- Month + Day of week -->
<div class="flight-charts glass charts-row">
<FlightsPerMonthChart :flight-stats="flightStats" />
<FlightsPerDayChart :flight-stats="flightStats" />
</div>
<!-- Reasons + Class + Seat type -->
<div class="flight-charts glass charts-row">
<FlightClassChart :flight-stats="flightStats" />
<FlightReasonsChart :flight-stats="flightStats" />
<SeatTypeChart :flight-stats="flightStats" />
</div>
<!-- Countries (tall) + Continents & Flight Type stacked -->
<div class="flight-charts glass charts-row">
<CountriesChart :max-visible="18" :flight-stats="flightStats" class="chart-tall" />
<div class="charts-stack">
<ContinentsChart :flight-stats="flightStats" />
<FlightTypeChart :flight-stats="flightStats" />
<div>
<!-- Year full width -->
<div class="flight-charts glass">
<FlightsPerYearChart :flight-stats="flightStats" />
</div>
</div>
<!-- Airlines + Airports -->
<div class="flight-charts glass charts-row">
<TopAirlinesChart :flight-stats="flightStats" />
<TopAirportsChart :flight-stats="flightStats" />
</div>
<!-- Month + Day of week -->
<div class="flight-charts glass charts-row">
<FlightsPerMonthChart :flight-stats="flightStats" />
<FlightsPerDayChart :flight-stats="flightStats" />
</div>
<!-- Routes + International vs Domestic -->
<div class="flight-charts glass charts-row">
<!--
<TopRoutesChart :flights="[...flights, ...upcomingFlights]" :upcoming-flights="upcomingFlights" />
-->
<!-- Reasons + Class + Seat type -->
<div class="flight-charts glass charts-row">
<FlightClassChart :flight-stats="flightStats" />
<FlightReasonsChart :flight-stats="flightStats" />
<SeatTypeChart :flight-stats="flightStats" />
</div>
<!-- Countries (tall) + Continents & Flight Type stacked -->
<div class="flight-charts glass charts-row">
<CountriesChart :max-visible="18" :flight-stats="flightStats" class="chart-tall" />
<div class="charts-stack">
<ContinentsChart :flight-stats="flightStats" />
<FlightTypeChart :flight-stats="flightStats" />
</div>
</div>
<!-- Airlines + Airports -->
<div class="flight-charts glass charts-row">
<TopAirlinesChart :flight-stats="flightStats" />
<TopAirportsChart :flight-stats="flightStats" />
</div>
<!-- Routes + International vs Domestic -->
<div class="flight-charts glass charts-row">
<!--
<TopRoutesChart :flights="[...flights, ...upcomingFlights]" :upcoming-flights="upcomingFlights" />
-->
</div>
</div>
</template>
@@ -1,18 +1,12 @@
<script setup lang="ts">
import type { Flight } from '@/Types/types'
import { computed, ref } from 'vue'
import { ref } from 'vue'
import { usePage } from '@inertiajs/vue3'
const props = defineProps<{
flights: Flight[]
}>()
const selectedYears = ref<number[]>([])
const selectedAirlines = ref<number[]>([])
const selectedCountries = ref<string[]>([])
const selectedContinents = ref<string[]>([])
const selectedFlightClasses = ref<number[]>([])
const emit = defineEmits<{
change: [filters: {
years: number[]
@@ -23,6 +17,53 @@ const emit = defineEmits<{
}]
}>()
// ── Available options ─────────────────────────────────────────────────────────
// flights is server-rendered and never mutated client-side, so we build options
// once as a plain value rather than a reactive computed.
function buildOptions(flights: Flight[]) {
const years = new Set<number>()
const airlines = new Map<number, { id: number; name: string }>()
const countries = new Map<string, { code: string; name: string }>()
const continents = new Map<string, { code: string; name: string }>()
const classes = new Map<number, { id: number; name: string }>()
flights.forEach(f => {
years.add(new Date(f.departure_date).getFullYear())
if (f.airline?.id && f.airline?.name)
airlines.set(f.airline.id, { id: f.airline.id, name: f.airline.name })
const dep = f.departure_airport.region
const arr = f.arrival_airport.region
if (dep?.country) countries.set(dep.country.code, { code: dep.country.code, name: dep.country.name })
if (arr?.country) countries.set(arr.country.code, { code: arr.country.code, name: arr.country.name })
if (dep?.continent) continents.set(dep.continent.code, { code: dep.continent.code, name: dep.continent.name })
if (arr?.continent) continents.set(arr.continent.code, { code: arr.continent.code, name: arr.continent.name })
if (f.flight_class?.id && f.flight_class?.name)
classes.set(f.flight_class.id, { id: f.flight_class.id, name: f.flight_class.name })
})
return {
years: [...years].sort((a, b) => b - a),
airlines: [...airlines.values()].sort((a, b) => a.name.localeCompare(b.name)),
countries: [...countries.values()].sort((a, b) => a.name.localeCompare(b.name)),
continents: [...continents.values()].sort((a, b) => a.name.localeCompare(b.name)),
classes: [...classes.values()].sort((a, b) => a.name.localeCompare(b.name)),
}
}
const availableOptions = buildOptions(props.flights)
// ── Filter state ──────────────────────────────────────────────────────────────
const selectedYears = ref<number[]>([])
const selectedAirlines = ref<number[]>([])
const selectedCountries = ref<string[]>([])
const selectedContinents = ref<string[]>([])
const selectedFlightClasses = ref<number[]>([])
function emitFilters() {
emit('change', {
years: selectedYears.value,
@@ -33,65 +74,20 @@ function emitFilters() {
})
}
// ── Helpers ───────────────────────────────────────────────────────────────────
const page = usePage()
const airlineLogoUrl = (id: number) =>
`${page.props.logo_api_url}/airlines/logos/tail/id/${id}`
const countryFlagClass = (code: string) =>
`fi fi-${code.toLowerCase()}`
const availableYears = computed(() => {
const years = new Set<number>()
props.flights.forEach(f => years.add(new Date(f.departure_date).getFullYear()))
return [...years].sort((a, b) => b - a)
})
const availableAirlines = computed((): { id: number; name: string }[] => {
const map = new Map<number, { id: number; name: string }>()
props.flights.forEach(f => {
if (f.airline?.id && f.airline?.name)
map.set(f.airline.id, { id: f.airline.id, name: f.airline.name })
})
return [...map.values()].sort((a, b) => a.name.localeCompare(b.name))
})
const availableCountries = computed((): { code: string; name: string }[] => {
const map = new Map<string, { code: string; name: string }>()
props.flights.forEach(f => {
const dep = f.departure_airport.region?.country
const arr = f.arrival_airport.region?.country
if (dep) map.set(dep.code, { code: dep.code, name: dep.name })
if (arr) map.set(arr.code, { code: arr.code, name: arr.name })
})
return [...map.values()].sort((a, b) => a.name.localeCompare(b.name))
})
const availableContinents = computed((): { code: string; name: string }[] => {
const map = new Map<string, { code: string; name: string }>()
props.flights.forEach(f => {
const dep = f.departure_airport.region?.continent
const arr = f.arrival_airport.region?.continent
if (dep) map.set(dep.code, { code: dep.code, name: dep.name })
if (arr) map.set(arr.code, { code: arr.code, name: arr.name })
})
return [...map.values()].sort((a, b) => a.name.localeCompare(b.name))
})
const availableFlightClasses = computed((): { id: number; name: string }[] => {
const map = new Map<number, { id: number; name: string }>()
props.flights.forEach(f => {
if (f.flight_class?.id && f.flight_class?.name)
map.set(f.flight_class.id, { id: f.flight_class.id, name: f.flight_class.name })
})
return [...map.values()].sort((a, b) => a.name.localeCompare(b.name))
})
</script>
<template>
<div class="flight-filters">
<v-select
v-model="selectedYears"
:items="availableYears"
:items="availableOptions.years"
label="Year"
multiple clearable hide-details
density="compact" variant="outlined"
@@ -107,7 +103,7 @@ const availableFlightClasses = computed((): { id: number; name: string }[] => {
<v-select
v-model="selectedAirlines"
:items="availableAirlines"
:items="availableOptions.airlines"
item-title="name" item-value="id"
label="Airline"
multiple clearable hide-details
@@ -140,7 +136,7 @@ const availableFlightClasses = computed((): { id: number; name: string }[] => {
<v-select
v-model="selectedCountries"
:items="availableCountries"
:items="availableOptions.countries"
item-title="name" item-value="code"
label="Country"
multiple clearable hide-details
@@ -169,7 +165,7 @@ const availableFlightClasses = computed((): { id: number; name: string }[] => {
<v-select
v-model="selectedContinents"
:items="availableContinents"
:items="availableOptions.continents"
item-title="name" item-value="code"
label="Continent"
multiple clearable hide-details
@@ -186,7 +182,7 @@ const availableFlightClasses = computed((): { id: number; name: string }[] => {
<v-select
v-model="selectedFlightClasses"
:items="availableFlightClasses"
:items="availableOptions.classes"
item-title="name" item-value="id"
label="Flight class"
multiple clearable hide-details
@@ -25,10 +25,6 @@ const emit = defineEmits<{
}]
}>()
const chartsVisible = ref(false)
onMounted(async () => {
setTimeout(() => { chartsVisible.value = true }, 1)
})
const mappedFlights = computed(() => [
...props.stats.pastFlights.value,
@@ -41,9 +37,9 @@ const mappedFlights = computed(() => [
<FlightMap :flights="mappedFlights" />
<FlightFilter :flights="mappedFlights" @change="$emit('filtersChange', $event)" />
<FlightStatsBar :flights="stats.pastFlights.value" :upcoming-flights="stats.upcomingFlights.value" />
<FlightCharts v-if="chartsVisible" :stats="stats" :flight-stats="stats"/>
<div v-else style="width:100%; display:flex; align-items: center;justify-content: center">
<FlightCharts :stats="stats" :flight-stats="stats"/>
<!-- <div v-else style="width:100%; display:flex; align-items: center;justify-content: center">
<PlaneLoader />
</div>
</div>-->
</div>
</template>
+147 -79
View File
@@ -1,64 +1,45 @@
// composables/useFlightStats.ts
import {computed, ComputedRef, Ref} from 'vue'
import type {Airport, Flight} from '@/Types/types'
import { computed, Ref, watch } from 'vue'
import type { Airport, Flight } from '@/Types/types'
const flightYear = (f: Flight): number =>
Number(new Intl.DateTimeFormat('en', {
timeZone: f.departure_airport.timezone,
year: 'numeric',
}).format(new Date(f.departure_date)))
const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
// ── Date part cache ───────────────────────────────────────────────────────────
// Intl.DateTimeFormat is expensive. We compute each flight's date parts once
// and cache them for the lifetime of the page.
const dayIndex = (f: Flight): number => {
const localDay = new Intl.DateTimeFormat('en', {
timeZone: f.departure_airport.timezone,
weekday: 'long',
}).format(new Date(f.departure_date))
const idx = DAYS.indexOf(localDay)
return idx === -1 ? 0 : idx
}
const dateCache = new Map<number, { year: number; month: number; day: number }>()
export function getFlightsPerDay(flights: Flight[], upcomingFlights: Flight[]) {
const countByDay = (list: Flight[]) =>
DAYS.map((_, i) => list.filter(f => dayIndex(f) === i).length)
function getDateParts(f: Flight): { year: number; month: number; day: number } {
if (dateCache.has(f.id)) return dateCache.get(f.id)!
return {
days: DAYS,
series: [
{ name: 'Flown', data: countByDay(flights) },
{ name: 'Upcoming', data: countByDay(upcomingFlights) },
],
const tz = f.departure_airport.timezone
const date = new Date(f.departure_date)
const fmt = (opts: Intl.DateTimeFormatOptions) =>
new Intl.DateTimeFormat('en', { timeZone: tz, ...opts }).format(date)
const localDay = fmt({ weekday: 'long' })
const dayIdx = DAYS.indexOf(localDay)
const parts = {
year: Number(fmt({ year: 'numeric' })),
month: Number(fmt({ month: 'numeric' })) - 1,
day: dayIdx === -1 ? 0 : dayIdx,
}
dateCache.set(f.id, parts)
return parts
}
const monthIndex = (f: Flight): number =>
Number(new Intl.DateTimeFormat('en', {
timeZone: f.departure_airport.timezone,
month: 'numeric',
}).format(new Date(f.departure_date))) - 1
export function getFlightsPerMonth(flights: Flight[], upcomingFlights: Flight[]) {
const countByMonth = (list: Flight[]) =>
MONTHS.map((_, i) => list.filter(f => monthIndex(f) === i).length)
return {
months: MONTHS,
series: [
{ name: 'Flown', data: countByMonth(flights) },
{ name: 'Upcoming', data: countByMonth(upcomingFlights) },
],
}
}
// ── Per year / month / day ────────────────────────────────────────────────────
export function getFlightsPerYear(flights: Flight[], upcomingFlights: Flight[]) {
console.time('getFlightsPerYear')
const allFlights = [...flights, ...upcomingFlights]
const allYears = new Set<number>()
allFlights.forEach(f => allYears.add(flightYear(f)))
const sorted = [...allYears].sort((a, b) => a - b)
const allYears = new Set(allFlights.map(f => getDateParts(f).year))
const sorted = [...allYears].sort((a, b) => a - b)
let min = sorted[0]
let max = sorted[sorted.length - 1]
@@ -69,17 +50,53 @@ export function getFlightsPerYear(flights: Flight[], upcomingFlights: Flight[])
const years = Array.from({ length: max - min + 1 }, (_, i) => min + i)
const countByYear = (list: Flight[]) =>
years.map(year => list.filter(f => flightYear(f) === year).length)
years.map(year => list.filter(f => getDateParts(f).year === year).length)
return {
const result = {
years,
series: [
{ name: 'Flown', data: countByYear(flights) },
{ name: 'Upcoming', data: countByYear(upcomingFlights) },
],
}
console.timeEnd('getFlightsPerYear')
return result
}
export function getFlightsPerMonth(flights: Flight[], upcomingFlights: Flight[]) {
console.time('getFlightsPerMonth')
const countByMonth = (list: Flight[]) =>
MONTHS.map((_, i) => list.filter(f => getDateParts(f).month === i).length)
const result = {
months: MONTHS,
series: [
{ name: 'Flown', data: countByMonth(flights) },
{ name: 'Upcoming', data: countByMonth(upcomingFlights) },
],
}
console.timeEnd('getFlightsPerMonth')
return result
}
export function getFlightsPerDay(flights: Flight[], upcomingFlights: Flight[]) {
console.time('getFlightsPerDay')
const countByDay = (list: Flight[]) =>
DAYS.map((_, i) => list.filter(f => getDateParts(f).day === i).length)
const result = {
days: DAYS,
series: [
{ name: 'Flown', data: countByDay(flights) },
{ name: 'Upcoming', data: countByDay(upcomingFlights) },
],
}
console.timeEnd('getFlightsPerDay')
return result
}
// ── Grouping helpers ──────────────────────────────────────────────────────────
function groupByName(flights: Flight[], accessor: (f: Flight) => string) {
const counts = new Map<string, number>()
flights.forEach(f => {
@@ -94,17 +111,28 @@ function groupByName(flights: Flight[], accessor: (f: Flight) => string) {
}
export function getFlightReasons(flights: Flight[]) {
return groupByName(flights, f => f.flight_reason?.name ?? 'Unknown')
console.time('getFlightReasons')
const result = groupByName(flights, f => f.flight_reason?.name ?? 'Unknown')
console.timeEnd('getFlightReasons')
return result
}
export function getFlightClasses(flights: Flight[]) {
return groupByName(flights, f => f.flight_class?.name ?? 'Unknown')
console.time('getFlightClasses')
const result = groupByName(flights, f => f.flight_class?.name ?? 'Unknown')
console.timeEnd('getFlightClasses')
return result
}
export function getSeatTypes(flights: Flight[]) {
return groupByName(flights, f => f.seat_type?.name ?? 'Unknown')
console.time('getSeatTypes')
const result = groupByName(flights, f => f.seat_type?.name ?? 'Unknown')
console.timeEnd('getSeatTypes')
return result
}
// ── Countries ─────────────────────────────────────────────────────────────────
function countCountries(flights: Flight[]) {
const counts = new Map<string, { count: number; code: string }>()
flights.forEach(f => {
@@ -126,11 +154,12 @@ function countCountries(flights: Flight[]) {
}
export function getCountries(flights: Flight[], upcomingFlights: Flight[]) {
console.time('getCountries')
const past = countCountries(flights)
const upcoming = countCountries(upcomingFlights)
const allCountries = new Set([...past.keys(), ...upcoming.keys()])
const allNames = new Set([...past.keys(), ...upcoming.keys()])
const sorted = [...allCountries]
const sorted = [...allNames]
.map(name => ({
name,
code: (past.get(name) ?? upcoming.get(name))!.code,
@@ -139,16 +168,21 @@ export function getCountries(flights: Flight[], upcomingFlights: Flight[]) {
}))
.sort((a, b) => (b.past + b.upcoming) - (a.past + a.upcoming))
return {
const result = {
countries: sorted,
series: [
{ name: 'Flights', data: sorted.map(s => s.past) },
{ name: 'Upcoming', data: sorted.map(s => s.upcoming) },
],
}
console.timeEnd('getCountries')
return result
}
// ── Continents ────────────────────────────────────────────────────────────────
export function getContinents(flights: Flight[]) {
console.time('getContinents')
const counts = new Map<string, number>()
flights.forEach(f => {
const continents = new Set<string>()
@@ -159,12 +193,16 @@ export function getContinents(flights: Flight[]) {
continents.forEach(c => counts.set(c, (counts.get(c) ?? 0) + 1))
})
const sorted = [...counts.entries()].sort((a, b) => b[1] - a[1])
return {
const result = {
labels: sorted.map(([name]) => name),
series: sorted.map(([, count]) => count),
}
console.timeEnd('getContinents')
return result
}
// ── Airlines ──────────────────────────────────────────────────────────────────
function countAirlines(flights: Flight[]) {
const counts = new Map<string, { count: number; id: number }>()
flights.forEach(f => {
@@ -178,11 +216,12 @@ function countAirlines(flights: Flight[]) {
}
export function getTopAirlines(flights: Flight[], upcomingFlights: Flight[]) {
console.time('getTopAirlines')
const past = countAirlines(flights)
const upcoming = countAirlines(upcomingFlights)
const allAirlines = new Set([...past.keys(), ...upcoming.keys()])
const allNames = new Set([...past.keys(), ...upcoming.keys()])
const sorted = [...allAirlines]
const sorted = [...allNames]
.map(name => ({
name,
id: (past.get(name) ?? upcoming.get(name))!.id,
@@ -191,15 +230,19 @@ export function getTopAirlines(flights: Flight[], upcomingFlights: Flight[]) {
}))
.sort((a, b) => (b.past + b.upcoming) - (a.past + a.upcoming))
return {
const result = {
airlines: sorted,
series: [
{ name: 'Flights', data: sorted.map(s => s.past) },
{ name: 'Upcoming', data: sorted.map(s => s.upcoming) },
],
}
console.timeEnd('getTopAirlines')
return result
}
// ── Airports ──────────────────────────────────────────────────────────────────
interface AirportItem {
label: string
fullName: string
@@ -214,7 +257,8 @@ function airportLabel(airport: Airport | null | undefined): string | null {
}
export function getTopAirports(flights: Flight[], upcomingFlights: Flight[]) {
const map = new Map<string, AirportItem>()
console.time('getTopAirports')
const map = new Map<string, AirportItem>()
const empty = (): AirportItem => ({ departures: 0, arrivals: 0, upcoming: 0, label: '', fullName: '' })
flights.forEach(f => {
@@ -262,7 +306,7 @@ export function getTopAirports(flights: Flight[], upcomingFlights: Flight[]) {
(b.departures + b.arrivals + b.upcoming) - (a.departures + a.arrivals + a.upcoming)
)
return {
const result = {
airports: sorted,
series: [
{ name: 'Departures', data: sorted.map(s => s.departures) },
@@ -270,9 +314,14 @@ export function getTopAirports(flights: Flight[], upcomingFlights: Flight[]) {
{ name: 'Upcoming', data: sorted.map(s => s.upcoming) },
],
}
console.timeEnd('getTopAirports')
return result
}
// ── Flight types ──────────────────────────────────────────────────────────────
export function getFlightTypes(flights: Flight[]) {
console.time('getFlightTypes')
const counts = { International: 0, Domestic: 0 }
flights.forEach(f => {
const dep = f.departure_airport.region?.country?.id
@@ -282,37 +331,56 @@ export function getFlightTypes(flights: Flight[]) {
}
})
const sorted = Object.entries(counts).filter(([, count]) => count > 0)
return {
const result = {
labels: sorted.map(([name]) => name),
series: sorted.map(([, count]) => count),
}
console.timeEnd('getFlightTypes')
return result
}
// ── Composable ────────────────────────────────────────────────────────────────
export type FlightStats = ReturnType<typeof useFlightStats>
export function useFlightStats(flights: Ref<Flight[]>) {
const now = new Date()
const pastFlights = computed(() =>
flights.value.filter(f => new Date(f.departure_date) <= now)
)
const upcomingFlights = computed(() =>
flights.value.filter(f => new Date(f.departure_date) > now)
)
// Pre-warm the date cache as soon as flights are available so the first
// filter interaction doesn't pay the Intl.DateTimeFormat cost.
watch(flights, (list) => {
console.time('dateCache warm')
list.forEach(f => getDateParts(f))
console.timeEnd('dateCache warm')
}, { immediate: true })
const pastFlights = computed(() => {
console.time('pastFlights')
const result = flights.value.filter(f => new Date(f.departure_date) <= now)
console.timeEnd('pastFlights')
return result
})
const upcomingFlights = computed(() => {
console.time('upcomingFlights')
const result = flights.value.filter(f => new Date(f.departure_date) > now)
console.timeEnd('upcomingFlights')
return result
})
const allFlights = computed(() => flights.value)
const perYear = computed(() => getFlightsPerYear(pastFlights.value, upcomingFlights.value))
const perMonth = computed(() => getFlightsPerMonth(pastFlights.value, upcomingFlights.value))
const perDay = computed(() => getFlightsPerDay(pastFlights.value, upcomingFlights.value))
const reasons = computed(() => getFlightReasons(allFlights.value))
const classes = computed(() => getFlightClasses(allFlights.value))
const seatTypes = computed(() => getSeatTypes(allFlights.value))
const countries = computed(() => getCountries(pastFlights.value, upcomingFlights.value))
const continents = computed(() => getContinents(allFlights.value))
const topAirlines = computed(() => getTopAirlines(pastFlights.value, upcomingFlights.value))
const topAirports = computed(() => getTopAirports(pastFlights.value, upcomingFlights.value))
const flightTypes = computed(() => getFlightTypes(allFlights.value))
const perYear = computed(() => getFlightsPerYear(pastFlights.value, upcomingFlights.value))
const perMonth = computed(() => getFlightsPerMonth(pastFlights.value, upcomingFlights.value))
const perDay = computed(() => getFlightsPerDay(pastFlights.value, upcomingFlights.value))
const reasons = computed(() => getFlightReasons(allFlights.value))
const classes = computed(() => getFlightClasses(allFlights.value))
const seatTypes = computed(() => getSeatTypes(allFlights.value))
const countries = computed(() => getCountries(pastFlights.value, upcomingFlights.value))
const continents = computed(() => getContinents(allFlights.value))
const topAirlines = computed(() => getTopAirlines(pastFlights.value, upcomingFlights.value))
const topAirports = computed(() => getTopAirports(pastFlights.value, upcomingFlights.value))
const flightTypes = computed(() => getFlightTypes(allFlights.value))
return {
pastFlights,
+1 -1
View File
@@ -135,7 +135,7 @@ const submitForm = useForm({
})
function submit() {
submitForm.flight_number = form.flight_number
submitForm.flight_number = flightNumber.value
submitForm.departure_date = form.departure_date
submitForm.arrival_date = form.arrival_date
submitForm.from_id = form.from?.value ?? null
+34 -7
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import MainLayout from "@/Layouts/MainLayout.vue";
import { Head } from '@inertiajs/vue3'
import { ref, computed, defineAsyncComponent } from 'vue'
import {ref, computed, defineAsyncComponent, watchEffect, onMounted} from 'vue'
import { Flight, ProfileView, User } from "@/Types/types"
import { router } from '@inertiajs/vue3'
import { useFlightStats, FlightStats } from "@/Composables/useFlightStats"
@@ -17,9 +17,12 @@ const props = defineProps<{
user: User
flights: Flight[]
canEdit: boolean
selectedFlightId: number | null
initialView?: ProfileView
}>()
const localSelectedFlightId = ref(props.selectedFlightId)
// ── Filter state ──────────────────────────────────────────────────────────────
const selectedYears = ref<number[]>([])
const selectedAirlines = ref<number[]>([])
@@ -34,13 +37,17 @@ function onFiltersChange(filters: {
continents: string[]
flightClasses: number[]
}) {
localSelectedFlightId.value = null
console.time('filter+stats')
selectedYears.value = filters.years
selectedAirlines.value = filters.airlines
selectedCountries.value = filters.countries
selectedContinents.value = filters.continents
selectedFlightClasses.value = filters.flightClasses
console.timeEnd('filter+stats')
}
function matchesFilters(f: Flight): boolean {
const date = new Date(f.departure_date)
if (selectedYears.value.length && !selectedYears.value.includes(date.getFullYear())) return false
@@ -55,14 +62,33 @@ function matchesFilters(f: Flight): boolean {
const arrCode = f.arrival_airport.region?.continent?.code
if (!selectedContinents.value.includes(depCode ?? '') && !selectedContinents.value.includes(arrCode ?? '')) return false
}
if (selectedFlightClasses.value.length && !selectedFlightClasses.value.includes(f.flight_class?.id ?? -1)) return false
return true
return !(selectedFlightClasses.value.length && !selectedFlightClasses.value.includes(f.flight_class?.id ?? -1));
}
const filteredFlights = computed(() => props.flights.filter(matchesFilters))
const filteredFlights = computed(() => {
console.time('filteredFlights')
const result = props.flights.filter(matchesFilters)
console.timeEnd('filteredFlights')
return result
})
const stats = useFlightStats(filteredFlights)
watchEffect(() => {
console.time('all.charts.input')
// just access each stat to trigger the log
const _ = [
stats.perYear.value,
stats.perMonth.value,
stats.perDay.value,
stats.topAirlines.value,
stats.topAirports.value,
stats.countries.value,
]
console.timeEnd('all.charts.input')
})
// ── View switching ────────────────────────────────────────────────────────────
const activeView = ref<ProfileView>(props.initialView ?? 'board')
@@ -73,6 +99,7 @@ const routeNames = {
} as const
function switchView(view: ProfileView) {
localSelectedFlightId.value = null
activeView.value = view
window.history.replaceState(
window.history.state,
@@ -86,10 +113,10 @@ function switchView(view: ProfileView) {
<Head :title="`${user.name}'s Flights`" />
<ProfileLayout :flights="flights" :user="user">
<ProfileViewSwitcher :active-view="activeView" @update:active-view="switchView" />
<DepartureBoard v-show="activeView === 'board'" :flight-stats="stats" :canEdit="canEdit" />
<BoardingPasses v-show="activeView === 'passes'" :flight-stats="stats" :canEdit="canEdit" />
<DepartureBoard v-if="activeView === 'board'" :flight-id="localSelectedFlightId" :flight-stats="stats" :canEdit="canEdit" />
<BoardingPasses v-if="activeView === 'passes'" :flight-stats="stats" :canEdit="canEdit" />
<FlightMapAndCharts
v-show="activeView === 'map'"
v-if="activeView === 'map'"
:stats="stats"
:canEdit="canEdit"
@filters-change="onFiltersChange"