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
+9 -9
View File
@@ -97,9 +97,9 @@ class FlightController extends Controller
{ {
$validated = $request->validate($this->rules()); $validated = $request->validate($this->rules());
auth()->user()->flights()->create($this->flightPayload($validated)); $newFlight = auth()->user()->flights()->create($this->flightPayload($validated));
return redirect()->route('dashboard', Auth::user()->name); return redirect()->route('profile.departure-board', [Auth::user()->name, $newFlight->id]);
} }
public function update(Request $request, UserFlight $flight) public function update(Request $request, UserFlight $flight)
@@ -110,14 +110,14 @@ class FlightController extends Controller
$flight->update($this->flightPayload($validated)); $flight->update($this->flightPayload($validated));
return redirect()->route('dashboard', Auth::user()->name); return redirect()->route('profile.departure-board', [Auth::user()->name, $flight->id]);
} }
public function add(){ public function add(){
return Inertia::render('AddFlight', [ return Inertia::render('AddFlight', [
'seat_types' => SeatType::all()->toArray(), 'seat_types' => SeatType::orderBy('id')->get()->toArray(),
'flight_reasons' => FlightReason::all()->toArray(), 'flight_reasons' => FlightReason::orderBy('id')->get()->toArray(),
'flight_classes' => FlightClass::all()->toArray(), 'flight_classes' => FlightClass::orderBy('id')->get()->toArray(),
]); ]);
} }
@@ -148,9 +148,9 @@ class FlightController extends Controller
]; ];
return Inertia::render('AddFlight', [ return Inertia::render('AddFlight', [
'flight' => $flightData, 'flight' => $flightData,
'seat_types' => SeatType::all()->toArray(), 'seat_types' => SeatType::orderBy('id')->get()->toArray(),
'flight_classes' => FlightClass::all()->toArray(), 'flight_reasons' => FlightReason::orderBy('id')->get()->toArray(),
'flight_reasons' => FlightReason::all()->toArray(), 'flight_classes' => FlightClass::orderBy('id')->get()->toArray(),
]); ]);
} }
} }
@@ -10,7 +10,7 @@ use Inertia\Inertia;
class FlightProfileController extends Controller class FlightProfileController extends Controller
{ {
public function profileData(string $username, string $view) : array { public function profileData(string $username, string $view, ?int $selectedFlightId = null) : array {
$user = User::whereRaw(DB::raw('LOWER(name) = ?'), [strtolower($username)])->firstOrFail(); $user = User::whereRaw(DB::raw('LOWER(name) = ?'), [strtolower($username)])->firstOrFail();
$flights = UserFlight::where('user_id', $user->id) $flights = UserFlight::where('user_id', $user->id)
@@ -33,11 +33,12 @@ class FlightProfileController extends Controller
'canEdit' => auth()->check() && auth()->id() === $user->id, 'canEdit' => auth()->check() && auth()->id() === $user->id,
'flights' => UserFlightResource::collection($flights)->resolve(), 'flights' => UserFlightResource::collection($flights)->resolve(),
'initialView' => $view, 'initialView' => $view,
'selectedFlightId' => $selectedFlightId,
]; ];
} }
public function departureBoard(string $username){ public function departureBoard(string $username, ?UserFlight $flight = null){
$profileData = $this->profileData($username, 'board'); $profileData = $this->profileData($username, 'board', $flight?->id);
return Inertia::render('UserProfile', $profileData); return Inertia::render('UserProfile', $profileData);
} }
+19
View File
@@ -7,6 +7,7 @@
"dependencies": { "dependencies": {
"@mdi/font": "^7.4.47", "@mdi/font": "^7.4.47",
"apexcharts": "^5.10.5", "apexcharts": "^5.10.5",
"chart.js": "^4.5.1",
"echarts": "^6.0.0", "echarts": "^6.0.0",
"flag-icons": "^7.5.0", "flag-icons": "^7.5.0",
"maplibre-gl": "^5.22.0", "maplibre-gl": "^5.22.0",
@@ -182,6 +183,12 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@kurkle/color": {
"version": "0.3.4",
"resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz",
"integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==",
"license": "MIT"
},
"node_modules/@mapbox/jsonlint-lines-primitives": { "node_modules/@mapbox/jsonlint-lines-primitives": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.2.tgz", "resolved": "https://registry.npmjs.org/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.2.tgz",
@@ -2378,6 +2385,18 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/chart.js": {
"version": "4.5.1",
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",
"integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",
"license": "MIT",
"dependencies": {
"@kurkle/color": "^0.3.0"
},
"engines": {
"pnpm": ">=8"
}
},
"node_modules/chokidar": { "node_modules/chokidar": {
"version": "3.6.0", "version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
+1
View File
@@ -29,6 +29,7 @@
"dependencies": { "dependencies": {
"@mdi/font": "^7.4.47", "@mdi/font": "^7.4.47",
"apexcharts": "^5.10.5", "apexcharts": "^5.10.5",
"chart.js": "^4.5.1",
"echarts": "^6.0.0", "echarts": "^6.0.0",
"flag-icons": "^7.5.0", "flag-icons": "^7.5.0",
"maplibre-gl": "^5.22.0", "maplibre-gl": "^5.22.0",
@@ -18,7 +18,7 @@ const chartOptions = computed(() => ({
type: 'donut', type: 'donut',
background: 'transparent', background: 'transparent',
fontFamily: 'inherit', fontFamily: 'inherit',
lazy: true, animations: { enabled: false },
}, },
theme: { mode: 'dark' }, theme: { mode: 'dark' },
labels: props.labels, labels: props.labels,
@@ -64,20 +64,16 @@ const chartOptions = computed(() => ({
}, },
})) }))
const ready = ref(false)
</script> </script>
<template> <template>
<div class="chart-wrap"> <div class="chart-wrap">
<div class="chart-title">{{ title }}</div> <div class="chart-title">{{ title }}</div>
<PlaneLoader v-if="!ready" />
<VueApexCharts <VueApexCharts
type="donut" type="donut"
:height="height" :height="height"
:options="options ?? chartOptions" :options="options ?? chartOptions"
:series="series" :series="series"
:class="{ 'chart-hidden': !ready }"
@mounted="ready = true"
/> />
</div> </div>
</template> </template>
@@ -100,4 +96,8 @@ const ready = ref(false)
.chart-hidden { .chart-hidden {
visibility: hidden; visibility: hidden;
} }
:deep(svg) {
outline: none;
}
</style> </style>
@@ -37,7 +37,7 @@ const chartOptions = computed(() => ({
toolbar: { show: false }, toolbar: { show: false },
animations: { enabled: false }, animations: { enabled: false },
stacked: true, stacked: true,
lazy: true, animation: { enabled: false },
}, },
theme: { mode: 'dark' }, theme: { mode: 'dark' },
plotOptions: { plotOptions: {
@@ -74,7 +74,6 @@ const chartOptions = computed(() => ({
}, },
})) }))
const ready = ref(false)
</script> </script>
<template> <template>
@@ -83,14 +82,11 @@ const ready = ref(false)
<div v-if="categories.length" class="chart-outer"> <div v-if="categories.length" class="chart-outer">
<div class="chart-scroll" :style="{ height: scrollHeight }"> <div class="chart-scroll" :style="{ height: scrollHeight }">
<PlaneLoader v-if="!ready" />
<VueApexCharts <VueApexCharts
type="bar" type="bar"
:height="chartHeight" :height="chartHeight"
:options="options ?? chartOptions" :options="options ?? chartOptions"
:series="series" :series="series"
:class="{ 'chart-hidden': !ready }"
@mounted="ready = true"
/> />
</div> </div>
@@ -167,6 +163,10 @@ const ready = ref(false)
color: #445566; color: #445566;
} }
:deep(svg) {
outline: none;
}
.chart-hidden { .chart-hidden {
visibility: hidden; visibility: hidden;
} }
@@ -1,6 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref } from 'vue' import { ref, watch, onMounted } from 'vue'
import PlaneLoader from "@/Components/FlightsGoneBy/PlaneLoader.vue"
import VueApexCharts from 'vue3-apexcharts' import VueApexCharts from 'vue3-apexcharts'
import { ChartType } from "@/Types/types" import { ChartType } from "@/Types/types"
@@ -8,19 +7,24 @@ const props = defineProps<{
type: ChartType type: ChartType
title: string title: string
height: number | string height: number | string
series: unknown[] series: { name: string; data: number[] }[]
categories: unknown[] categories: unknown[]
options?: object options?: object
}>() }>()
const chartOptions = computed(() => ({ const chartRef = ref()
const isUpdating = ref(false)
const ready = ref(false)
let rafId: number | null = null
const staticOptions = {
chart: { chart: {
type: 'bar', type: 'bar',
stacked: true, stacked: true,
toolbar: { show: false }, toolbar: { show: false },
background: 'transparent', background: 'transparent',
fontFamily: 'inherit', fontFamily: 'inherit',
lazy: true, animations: { enabled: false },
}, },
theme: { mode: 'dark' }, theme: { mode: 'dark' },
plotOptions: { plotOptions: {
@@ -37,12 +41,6 @@ const chartOptions = computed(() => ({
yaxis: { lines: { show: true } }, yaxis: { lines: { show: true } },
xaxis: { lines: { show: false } }, xaxis: { lines: { show: false } },
}, },
xaxis: {
categories: props.categories,
axisBorder: { show: false },
axisTicks: { show: false },
labels: { style: { colors: '#445566', fontSize: '12px' } },
},
yaxis: { yaxis: {
labels: { style: { colors: '#445566', fontSize: '12px' } }, labels: { style: { colors: '#445566', fontSize: '12px' } },
}, },
@@ -58,23 +56,59 @@ const chartOptions = computed(() => ({
hover: { filter: { type: 'lighten', value: 0.1 } }, hover: { filter: { type: 'lighten', value: 0.1 } },
active: { filter: { type: 'none' } }, 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> </script>
<template> <template>
<div class="chart-wrap"> <div class="chart-wrap">
<div class="chart-title">{{title}}</div> <div class="chart-title">{{ title }}</div>
<PlaneLoader v-if="!ready" /> <div class="chart-area" :style="{ height: typeof height === 'number' ? height + 'px' : height }">
<VueApexCharts <VueApexCharts
:type="type" ref="chartRef"
:height="height" :type="type"
:options="options ?? chartOptions" :height="height"
:series="series" :options="options ?? initialOptions"
:class="{ 'chart-hidden': !ready }" :series="series"
@mounted="ready = true" :style="{ opacity: isUpdating ? 0 : 1 }"
/> class="apex-chart"
/>
<div v-if="isUpdating" class="chart-skeleton" />
</div>
</div> </div>
</template> </template>
@@ -93,12 +127,34 @@ const ready = ref(false)
letter-spacing: 0.08em; letter-spacing: 0.08em;
} }
.chart-empty { .chart-area {
height: 280px; position: relative;
display: flex; }
align-items: center;
justify-content: center; .apex-chart {
font-size: 13px; transition: opacity 0.15s ease;
color: #445566; }
.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> </style>
@@ -3,7 +3,7 @@
import FlightClassBadge from "@/Components/FlightsGoneBy/FlightClassBadge.vue"; import FlightClassBadge from "@/Components/FlightsGoneBy/FlightClassBadge.vue";
import AirlineLogo from "@/Components/FlightsGoneBy/AirlineLogo.vue"; import AirlineLogo from "@/Components/FlightsGoneBy/AirlineLogo.vue";
import {Flight} from "@/Types/types"; import {Flight} from "@/Types/types";
import { computed, ref } from "vue"; import { computed, ref, watch, nextTick } from "vue";
import type { DataTableSortItem } from 'vuetify'; import type { DataTableSortItem } from 'vuetify';
import InlineBadge from "@/Components/FlightsGoneBy/InlineBadge.vue"; import InlineBadge from "@/Components/FlightsGoneBy/InlineBadge.vue";
import AirportToolTip from "@/Components/FlightsGoneBy/AirportToolTip.vue"; import AirportToolTip from "@/Components/FlightsGoneBy/AirportToolTip.vue";
@@ -13,8 +13,10 @@ import {FlightStats} from "@/Composables/useFlightStats";
const props = defineProps<{ const props = defineProps<{
flightStats: FlightStats flightStats: FlightStats
canEdit: boolean canEdit: boolean
flightId?: number | null
}>() }>()
const ITEMS_PER_PAGE = 25
const headers = [ const headers = [
{ title: '', key: 'airline', sortable: true }, { title: '', key: 'airline', sortable: true },
@@ -50,15 +52,14 @@ const customKeySort = {
duration: (a: any, b: any) => (a ?? 0) - (b ?? 0), duration: (a: any, b: any) => (a ?? 0) - (b ?? 0),
} }
// Track active sort state
const sortBy = ref<DataTableSortItem[]>([]) const sortBy = ref<DataTableSortItem[]>([])
const currentPage = ref(1)
const today = new Date() const today = new Date()
today.setHours(0, 0, 0, 0) today.setHours(0, 0, 0, 0)
const isSorting = computed(() => sortBy.value.length > 0) const isSorting = computed(() => sortBy.value.length > 0)
// Split flights into upcoming vs departed, sorted by date within each group
const upcomingFlights = computed(() => const upcomingFlights = computed(() =>
props.flightStats.upcomingFlights.value 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()) .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 } type GroupedFlight = Flight & { _group?: 'upcoming' | 'departed'; _groupHeader?: boolean; _groupLabel?: string }
const groupedItems = computed<GroupedFlight[]>(() => { const groupedItems = computed<GroupedFlight[]>(() => {
@@ -88,7 +88,6 @@ const groupedItems = computed<GroupedFlight[]>(() => {
return result return result
}) })
// When sorting, pass all flights flat; when not sorting, pass grouped (headers will be rendered via #item slot trick)
const allFlights = computed(() => [ const allFlights = computed(() => [
...props.flightStats.upcomingFlights.value, ...props.flightStats.upcomingFlights.value,
...props.flightStats.pastFlights.value, ...props.flightStats.pastFlights.value,
@@ -97,6 +96,34 @@ const allFlights = computed(() => [
const tableItems = computed(() => const tableItems = computed(() =>
isSorting.value ? allFlights.value : groupedItems.value 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> </script>
<template> <template>
@@ -104,14 +131,13 @@ const tableItems = computed(() =>
:headers="headers" :headers="headers"
:custom-key-sort="customKeySort" :custom-key-sort="customKeySort"
:items="tableItems" :items="tableItems"
:items-per-page="25" :items-per-page="ITEMS_PER_PAGE"
v-model:sort-by="sortBy" v-model:sort-by="sortBy"
v-model:page="currentPage"
class="departures-table" class="departures-table"
hover hover
> >
<!-- GROUP HEADER ROW (injected as a fake item) -->
<template #item="{ item, columns }"> <template #item="{ item, columns }">
<!-- Section divider row -->
<template v-if="(item as any)._groupHeader && !isSorting"> <template v-if="(item as any)._groupHeader && !isSorting">
<tr class="section-header-row"> <tr class="section-header-row">
<td :colspan="columns.length" class="section-header-cell"> <td :colspan="columns.length" class="section-header-cell">
@@ -133,34 +159,32 @@ const tableItems = computed(() =>
</tr> </tr>
</template> </template>
<!-- Normal data row -->
<template v-else-if="!(item as any)._groupHeader"> <template v-else-if="!(item as any)._groupHeader">
<tr <tr
class="v-data-table__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"> <td class="v-data-table__td airline-logo-cell">
<AirlineLogo size="32" :airline="(item as any).airline" class="airline-logo-img" /> <AirlineLogo size="32" :airline="(item as any).airline" class="airline-logo-img" />
</td> </td>
<!-- Flight number -->
<td class="v-data-table__td flight-number-cell"> <td class="v-data-table__td flight-number-cell">
<div class="flight-cell"> <div class="flight-cell">
<span class="flight-number">{{ (item as any).flight_number }}</span> <span class="flight-number">{{ (item as any).flight_number }}</span>
</div> </div>
</td> </td>
<!-- Departure airport -->
<td class="v-data-table__td"> <td class="v-data-table__td">
<AirportToolTip :airport="(item as Flight).departure_airport"> <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> </AirportToolTip>
<span class="city-name">{{ (item as Flight).departure_airport.municipality }}</span> <span class="city-name">{{ (item as Flight).departure_airport.municipality }}</span>
</td> </td>
<!-- Arrival airport -->
<td class="v-data-table__td"> <td class="v-data-table__td">
<AirportToolTip :airport="(item as Flight).arrival_airport"> <AirportToolTip :airport="(item as Flight).arrival_airport">
<span class="iata">{{ (item as Flight).arrival_airport.display_code }}</span><br/> <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> <span class="city-name">{{ (item as Flight).arrival_airport.municipality }}</span>
</td> </td>
<!-- Departure date -->
<td class="v-data-table__td"> <td class="v-data-table__td">
<span class="date-cell">{{ (item as Flight).departure_date_display }}</span> <span class="date-cell">{{ (item as Flight).departure_date_display }}</span>
</td> </td>
<!-- Departure time -->
<td class="v-data-table__td"> <td class="v-data-table__td">
<span class="time-cell">{{ (item as Flight).departure_time_display }}</span> <span class="time-cell">{{ (item as Flight).departure_time_display }}</span>
</td> </td>
<!-- Arrival time -->
<td class="v-data-table__td"> <td class="v-data-table__td">
<span class="time-cell">{{ (item as Flight).arrival_time_display }}</span> <span class="time-cell">{{ (item as Flight).arrival_time_display }}</span>
<sup v-if="(item as Flight).arrival_day_difference" class="day-diff"> <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> <span class="mono-tag">{{ (item as Flight).duration_display ?? '—' }}</span>
</td> </td>
<!-- Distance -->
<td class="v-data-table__td"> <td class="v-data-table__td">
<span class="mono-tag distance-cell"> <span class="mono-tag distance-cell">
{{ (item as Flight).distance ? Math.round((item as Flight).distance).toLocaleString() + ' km' : '' }} {{ (item as Flight).distance ? Math.round((item as Flight).distance).toLocaleString() + ' km' : '' }}
</span> </span>
</td> </td>
<!-- Aircraft -->
<td class="v-data-table__td"> <td class="v-data-table__td">
<AircraftToolTip v-if="(item as any).aircraft" :aircraft="(item as any).aircraft"> <AircraftToolTip v-if="(item as any).aircraft" :aircraft="(item as any).aircraft">
<span class="mono-tag">{{ (item as any).aircraft?.designator }}</span> <span class="mono-tag">{{ (item as any).aircraft?.designator }}</span>
</AircraftToolTip> </AircraftToolTip>
</td> </td>
<!-- Class -->
<td class="v-data-table__td "> <td class="v-data-table__td ">
<span class="class-cell"> <span class="class-cell">
<FlightClassBadge :flight="(item as Flight)" /> <FlightClassBadge :flight="(item as Flight)" />
@@ -213,7 +231,6 @@ const tableItems = computed(() =>
</span> </span>
</td> </td>
<!-- Actions -->
<td class="v-data-table__td actions-cell"> <td class="v-data-table__td actions-cell">
<template v-if="canEdit"> <template v-if="canEdit">
<v-menu> <v-menu>
@@ -241,7 +258,6 @@ const tableItems = computed(() =>
</template> </template>
</template> </template>
<!-- Empty state -->
<template #no-data> <template #no-data>
<div class="no-data"> <div class="no-data">
<span>NO FLIGHTS ON RECORD</span> <span>NO FLIGHTS ON RECORD</span>
@@ -251,14 +267,12 @@ const tableItems = computed(() =>
</template> </template>
<style scoped> <style scoped>
/* ── Vuetify table overrides ── */
.departures-table { .departures-table {
background: transparent !important; background: transparent !important;
color: #c8cdd8 !important; color: #c8cdd8 !important;
font-family: 'Barlow', sans-serif !important; font-family: 'Barlow', sans-serif !important;
} }
/* Header row */
:deep(.v-data-table-header__content) { :deep(.v-data-table-header__content) {
font-family: 'Share Tech Mono', monospace !important; font-family: 'Share Tech Mono', monospace !important;
font-size: 0.68rem !important; font-size: 0.68rem !important;
@@ -273,7 +287,6 @@ const tableItems = computed(() =>
padding: 0.75rem 1rem !important; padding: 0.75rem 1rem !important;
} }
/* Body rows — alternating, no borders */
:deep(.v-data-table__tr:nth-child(odd)) { :deep(.v-data-table__tr:nth-child(odd)) {
background: rgba(255,255,255,0.025) !important; background: rgba(255,255,255,0.025) !important;
} }
@@ -293,7 +306,6 @@ const tableItems = computed(() =>
color: #c8cdd8 !important; color: #c8cdd8 !important;
} }
/* Footer / pagination */
:deep(.v-data-table-footer) { :deep(.v-data-table-footer) {
background: transparent !important; background: transparent !important;
border-top: 1px solid rgba(255,255,255,0.06) !important; border-top: 1px solid rgba(255,255,255,0.06) !important;
@@ -310,13 +322,11 @@ const tableItems = computed(() =>
color: #ffc107 !important; color: #ffc107 !important;
} }
/* Sort icon colour */
:deep(.v-data-table-header__sort-icon) { :deep(.v-data-table-header__sort-icon) {
color: #ffc107 !important; color: #ffc107 !important;
opacity: 0.5; opacity: 0.5;
} }
/* ── Section header rows ── */
.section-header-row { .section-header-row {
background: transparent !important; background: transparent !important;
} }
@@ -334,7 +344,6 @@ const tableItems = computed(() =>
position: relative; position: relative;
} }
/* Upcoming = amber accent */
.section-header-inner.upcoming .section-header-icon, .section-header-inner.upcoming .section-header-icon,
.section-header-inner.upcoming .section-header-label { .section-header-inner.upcoming .section-header-label {
color: #ffc107; color: #ffc107;
@@ -344,7 +353,6 @@ const tableItems = computed(() =>
background: linear-gradient(to right, rgba(255,193,7,0.4), transparent); 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-icon,
.section-header-inner.departed .section-header-label { .section-header-inner.departed .section-header-label {
color: #778899; color: #778899;
@@ -383,7 +391,6 @@ const tableItems = computed(() =>
min-width: 2rem; min-width: 2rem;
} }
/* ── Airline + flight number fused cells ── */
:deep(.v-data-table__th:nth-child(1)) { :deep(.v-data-table__th:nth-child(1)) {
width: 50px !important; width: 50px !important;
min-width: 50px !important; min-width: 50px !important;
@@ -406,7 +413,6 @@ const tableItems = computed(() =>
padding-left: 0.5rem !important; padding-left: 0.5rem !important;
} }
/* ── Cell styles ── */
.flight-cell { .flight-cell {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -484,7 +490,6 @@ const tableItems = computed(() =>
gap: 0.5rem; gap: 0.5rem;
} }
/* ── Empty state ── */
.no-data { .no-data {
padding: 3rem; padding: 3rem;
text-align: center; text-align: center;
@@ -506,4 +511,14 @@ const tableItems = computed(() =>
letter-spacing: 0.08em !important; letter-spacing: 0.08em !important;
color: #c8cdd8 !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> </style>
@@ -24,44 +24,46 @@ defineProps<{
</script> </script>
<template> <template>
<!-- Year full width --> <div>
<div class="flight-charts glass"> <!-- Year full width -->
<FlightsPerYearChart :flight-stats="flightStats" /> <div class="flight-charts glass">
</div> <FlightsPerYearChart :flight-stats="flightStats" />
<!-- 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> </div>
</div>
<!-- Airlines + Airports --> <!-- Month + Day of week -->
<div class="flight-charts glass charts-row"> <div class="flight-charts glass charts-row">
<TopAirlinesChart :flight-stats="flightStats" /> <FlightsPerMonthChart :flight-stats="flightStats" />
<TopAirportsChart :flight-stats="flightStats" /> <FlightsPerDayChart :flight-stats="flightStats" />
</div> </div>
<!-- Routes + International vs Domestic --> <!-- Reasons + Class + Seat type -->
<div class="flight-charts glass charts-row"> <div class="flight-charts glass charts-row">
<!-- <FlightClassChart :flight-stats="flightStats" />
<TopRoutesChart :flights="[...flights, ...upcomingFlights]" :upcoming-flights="upcomingFlights" /> <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> </div>
</template> </template>
@@ -1,18 +1,12 @@
<script setup lang="ts"> <script setup lang="ts">
import type { Flight } from '@/Types/types' import type { Flight } from '@/Types/types'
import { computed, ref } from 'vue' import { ref } from 'vue'
import { usePage } from '@inertiajs/vue3' import { usePage } from '@inertiajs/vue3'
const props = defineProps<{ const props = defineProps<{
flights: Flight[] 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<{ const emit = defineEmits<{
change: [filters: { change: [filters: {
years: number[] 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() { function emitFilters() {
emit('change', { emit('change', {
years: selectedYears.value, years: selectedYears.value,
@@ -33,65 +74,20 @@ function emitFilters() {
}) })
} }
// ── Helpers ───────────────────────────────────────────────────────────────────
const page = usePage() const page = usePage()
const airlineLogoUrl = (id: number) => const airlineLogoUrl = (id: number) =>
`${page.props.logo_api_url}/airlines/logos/tail/id/${id}` `${page.props.logo_api_url}/airlines/logos/tail/id/${id}`
const countryFlagClass = (code: string) => const countryFlagClass = (code: string) =>
`fi fi-${code.toLowerCase()}` `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> </script>
<template> <template>
<div class="flight-filters"> <div class="flight-filters">
<v-select <v-select
v-model="selectedYears" v-model="selectedYears"
:items="availableYears" :items="availableOptions.years"
label="Year" label="Year"
multiple clearable hide-details multiple clearable hide-details
density="compact" variant="outlined" density="compact" variant="outlined"
@@ -107,7 +103,7 @@ const availableFlightClasses = computed((): { id: number; name: string }[] => {
<v-select <v-select
v-model="selectedAirlines" v-model="selectedAirlines"
:items="availableAirlines" :items="availableOptions.airlines"
item-title="name" item-value="id" item-title="name" item-value="id"
label="Airline" label="Airline"
multiple clearable hide-details multiple clearable hide-details
@@ -140,7 +136,7 @@ const availableFlightClasses = computed((): { id: number; name: string }[] => {
<v-select <v-select
v-model="selectedCountries" v-model="selectedCountries"
:items="availableCountries" :items="availableOptions.countries"
item-title="name" item-value="code" item-title="name" item-value="code"
label="Country" label="Country"
multiple clearable hide-details multiple clearable hide-details
@@ -169,7 +165,7 @@ const availableFlightClasses = computed((): { id: number; name: string }[] => {
<v-select <v-select
v-model="selectedContinents" v-model="selectedContinents"
:items="availableContinents" :items="availableOptions.continents"
item-title="name" item-value="code" item-title="name" item-value="code"
label="Continent" label="Continent"
multiple clearable hide-details multiple clearable hide-details
@@ -186,7 +182,7 @@ const availableFlightClasses = computed((): { id: number; name: string }[] => {
<v-select <v-select
v-model="selectedFlightClasses" v-model="selectedFlightClasses"
:items="availableFlightClasses" :items="availableOptions.classes"
item-title="name" item-value="id" item-title="name" item-value="id"
label="Flight class" label="Flight class"
multiple clearable hide-details 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(() => [ const mappedFlights = computed(() => [
...props.stats.pastFlights.value, ...props.stats.pastFlights.value,
@@ -41,9 +37,9 @@ const mappedFlights = computed(() => [
<FlightMap :flights="mappedFlights" /> <FlightMap :flights="mappedFlights" />
<FlightFilter :flights="mappedFlights" @change="$emit('filtersChange', $event)" /> <FlightFilter :flights="mappedFlights" @change="$emit('filtersChange', $event)" />
<FlightStatsBar :flights="stats.pastFlights.value" :upcoming-flights="stats.upcomingFlights.value" /> <FlightStatsBar :flights="stats.pastFlights.value" :upcoming-flights="stats.upcomingFlights.value" />
<FlightCharts v-if="chartsVisible" :stats="stats" :flight-stats="stats"/> <FlightCharts :stats="stats" :flight-stats="stats"/>
<div v-else style="width:100%; display:flex; align-items: center;justify-content: center"> <!-- <div v-else style="width:100%; display:flex; align-items: center;justify-content: center">
<PlaneLoader /> <PlaneLoader />
</div> </div>-->
</div> </div>
</template> </template>
+147 -79
View File
@@ -1,64 +1,45 @@
// composables/useFlightStats.ts // composables/useFlightStats.ts
import {computed, ComputedRef, Ref} from 'vue' import { computed, Ref, watch } from 'vue'
import type {Airport, Flight} from '@/Types/types' import type { Airport, Flight } from '@/Types/types'
const flightYear = (f: Flight): number => const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
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 MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] 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 dateCache = new Map<number, { year: number; month: number; day: 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
}
export function getFlightsPerDay(flights: Flight[], upcomingFlights: Flight[]) { function getDateParts(f: Flight): { year: number; month: number; day: number } {
const countByDay = (list: Flight[]) => if (dateCache.has(f.id)) return dateCache.get(f.id)!
DAYS.map((_, i) => list.filter(f => dayIndex(f) === i).length)
return { const tz = f.departure_airport.timezone
days: DAYS, const date = new Date(f.departure_date)
series: [ const fmt = (opts: Intl.DateTimeFormatOptions) =>
{ name: 'Flown', data: countByDay(flights) }, new Intl.DateTimeFormat('en', { timeZone: tz, ...opts }).format(date)
{ name: 'Upcoming', data: countByDay(upcomingFlights) },
], 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 => // ── Per year / month / day ────────────────────────────────────────────────────
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) },
],
}
}
export function getFlightsPerYear(flights: Flight[], upcomingFlights: Flight[]) { export function getFlightsPerYear(flights: Flight[], upcomingFlights: Flight[]) {
console.time('getFlightsPerYear')
const allFlights = [...flights, ...upcomingFlights] const allFlights = [...flights, ...upcomingFlights]
const allYears = new Set<number>() const allYears = new Set(allFlights.map(f => getDateParts(f).year))
allFlights.forEach(f => allYears.add(flightYear(f))) const sorted = [...allYears].sort((a, b) => a - b)
const sorted = [...allYears].sort((a, b) => a - b)
let min = sorted[0] let min = sorted[0]
let max = sorted[sorted.length - 1] 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 years = Array.from({ length: max - min + 1 }, (_, i) => min + i)
const countByYear = (list: Flight[]) => 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, years,
series: [ series: [
{ name: 'Flown', data: countByYear(flights) }, { name: 'Flown', data: countByYear(flights) },
{ name: 'Upcoming', data: countByYear(upcomingFlights) }, { 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) { function groupByName(flights: Flight[], accessor: (f: Flight) => string) {
const counts = new Map<string, number>() const counts = new Map<string, number>()
flights.forEach(f => { flights.forEach(f => {
@@ -94,17 +111,28 @@ function groupByName(flights: Flight[], accessor: (f: Flight) => string) {
} }
export function getFlightReasons(flights: Flight[]) { 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[]) { 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[]) { 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[]) { function countCountries(flights: Flight[]) {
const counts = new Map<string, { count: number; code: string }>() const counts = new Map<string, { count: number; code: string }>()
flights.forEach(f => { flights.forEach(f => {
@@ -126,11 +154,12 @@ function countCountries(flights: Flight[]) {
} }
export function getCountries(flights: Flight[], upcomingFlights: Flight[]) { export function getCountries(flights: Flight[], upcomingFlights: Flight[]) {
console.time('getCountries')
const past = countCountries(flights) const past = countCountries(flights)
const upcoming = countCountries(upcomingFlights) 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 => ({ .map(name => ({
name, name,
code: (past.get(name) ?? upcoming.get(name))!.code, 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)) .sort((a, b) => (b.past + b.upcoming) - (a.past + a.upcoming))
return { const result = {
countries: sorted, countries: sorted,
series: [ series: [
{ name: 'Flights', data: sorted.map(s => s.past) }, { name: 'Flights', data: sorted.map(s => s.past) },
{ name: 'Upcoming', data: sorted.map(s => s.upcoming) }, { name: 'Upcoming', data: sorted.map(s => s.upcoming) },
], ],
} }
console.timeEnd('getCountries')
return result
} }
// ── Continents ────────────────────────────────────────────────────────────────
export function getContinents(flights: Flight[]) { export function getContinents(flights: Flight[]) {
console.time('getContinents')
const counts = new Map<string, number>() const counts = new Map<string, number>()
flights.forEach(f => { flights.forEach(f => {
const continents = new Set<string>() 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)) continents.forEach(c => counts.set(c, (counts.get(c) ?? 0) + 1))
}) })
const sorted = [...counts.entries()].sort((a, b) => b[1] - a[1]) const sorted = [...counts.entries()].sort((a, b) => b[1] - a[1])
return { const result = {
labels: sorted.map(([name]) => name), labels: sorted.map(([name]) => name),
series: sorted.map(([, count]) => count), series: sorted.map(([, count]) => count),
} }
console.timeEnd('getContinents')
return result
} }
// ── Airlines ──────────────────────────────────────────────────────────────────
function countAirlines(flights: Flight[]) { function countAirlines(flights: Flight[]) {
const counts = new Map<string, { count: number; id: number }>() const counts = new Map<string, { count: number; id: number }>()
flights.forEach(f => { flights.forEach(f => {
@@ -178,11 +216,12 @@ function countAirlines(flights: Flight[]) {
} }
export function getTopAirlines(flights: Flight[], upcomingFlights: Flight[]) { export function getTopAirlines(flights: Flight[], upcomingFlights: Flight[]) {
console.time('getTopAirlines')
const past = countAirlines(flights) const past = countAirlines(flights)
const upcoming = countAirlines(upcomingFlights) 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 => ({ .map(name => ({
name, name,
id: (past.get(name) ?? upcoming.get(name))!.id, 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)) .sort((a, b) => (b.past + b.upcoming) - (a.past + a.upcoming))
return { const result = {
airlines: sorted, airlines: sorted,
series: [ series: [
{ name: 'Flights', data: sorted.map(s => s.past) }, { name: 'Flights', data: sorted.map(s => s.past) },
{ name: 'Upcoming', data: sorted.map(s => s.upcoming) }, { name: 'Upcoming', data: sorted.map(s => s.upcoming) },
], ],
} }
console.timeEnd('getTopAirlines')
return result
} }
// ── Airports ──────────────────────────────────────────────────────────────────
interface AirportItem { interface AirportItem {
label: string label: string
fullName: string fullName: string
@@ -214,7 +257,8 @@ function airportLabel(airport: Airport | null | undefined): string | null {
} }
export function getTopAirports(flights: Flight[], upcomingFlights: Flight[]) { 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: '' }) const empty = (): AirportItem => ({ departures: 0, arrivals: 0, upcoming: 0, label: '', fullName: '' })
flights.forEach(f => { 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) (b.departures + b.arrivals + b.upcoming) - (a.departures + a.arrivals + a.upcoming)
) )
return { const result = {
airports: sorted, airports: sorted,
series: [ series: [
{ name: 'Departures', data: sorted.map(s => s.departures) }, { 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) }, { name: 'Upcoming', data: sorted.map(s => s.upcoming) },
], ],
} }
console.timeEnd('getTopAirports')
return result
} }
// ── Flight types ──────────────────────────────────────────────────────────────
export function getFlightTypes(flights: Flight[]) { export function getFlightTypes(flights: Flight[]) {
console.time('getFlightTypes')
const counts = { International: 0, Domestic: 0 } const counts = { International: 0, Domestic: 0 }
flights.forEach(f => { flights.forEach(f => {
const dep = f.departure_airport.region?.country?.id 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) const sorted = Object.entries(counts).filter(([, count]) => count > 0)
return { const result = {
labels: sorted.map(([name]) => name), labels: sorted.map(([name]) => name),
series: sorted.map(([, count]) => count), series: sorted.map(([, count]) => count),
} }
console.timeEnd('getFlightTypes')
return result
} }
// ── Composable ────────────────────────────────────────────────────────────────
export type FlightStats = ReturnType<typeof useFlightStats> export type FlightStats = ReturnType<typeof useFlightStats>
export function useFlightStats(flights: Ref<Flight[]>) { export function useFlightStats(flights: Ref<Flight[]>) {
const now = new Date() const now = new Date()
const pastFlights = computed(() => // Pre-warm the date cache as soon as flights are available so the first
flights.value.filter(f => new Date(f.departure_date) <= now) // filter interaction doesn't pay the Intl.DateTimeFormat cost.
) watch(flights, (list) => {
const upcomingFlights = computed(() => console.time('dateCache warm')
flights.value.filter(f => new Date(f.departure_date) > now) 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 allFlights = computed(() => flights.value)
const perYear = computed(() => getFlightsPerYear(pastFlights.value, upcomingFlights.value)) const perYear = computed(() => getFlightsPerYear(pastFlights.value, upcomingFlights.value))
const perMonth = computed(() => getFlightsPerMonth(pastFlights.value, upcomingFlights.value)) const perMonth = computed(() => getFlightsPerMonth(pastFlights.value, upcomingFlights.value))
const perDay = computed(() => getFlightsPerDay(pastFlights.value, upcomingFlights.value)) const perDay = computed(() => getFlightsPerDay(pastFlights.value, upcomingFlights.value))
const reasons = computed(() => getFlightReasons(allFlights.value)) const reasons = computed(() => getFlightReasons(allFlights.value))
const classes = computed(() => getFlightClasses(allFlights.value)) const classes = computed(() => getFlightClasses(allFlights.value))
const seatTypes = computed(() => getSeatTypes(allFlights.value)) const seatTypes = computed(() => getSeatTypes(allFlights.value))
const countries = computed(() => getCountries(pastFlights.value, upcomingFlights.value)) const countries = computed(() => getCountries(pastFlights.value, upcomingFlights.value))
const continents = computed(() => getContinents(allFlights.value)) const continents = computed(() => getContinents(allFlights.value))
const topAirlines = computed(() => getTopAirlines(pastFlights.value, upcomingFlights.value)) const topAirlines = computed(() => getTopAirlines(pastFlights.value, upcomingFlights.value))
const topAirports = computed(() => getTopAirports(pastFlights.value, upcomingFlights.value)) const topAirports = computed(() => getTopAirports(pastFlights.value, upcomingFlights.value))
const flightTypes = computed(() => getFlightTypes(allFlights.value)) const flightTypes = computed(() => getFlightTypes(allFlights.value))
return { return {
pastFlights, pastFlights,
+1 -1
View File
@@ -135,7 +135,7 @@ const submitForm = useForm({
}) })
function submit() { function submit() {
submitForm.flight_number = form.flight_number submitForm.flight_number = flightNumber.value
submitForm.departure_date = form.departure_date submitForm.departure_date = form.departure_date
submitForm.arrival_date = form.arrival_date submitForm.arrival_date = form.arrival_date
submitForm.from_id = form.from?.value ?? null submitForm.from_id = form.from?.value ?? null
+34 -7
View File
@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import MainLayout from "@/Layouts/MainLayout.vue"; import MainLayout from "@/Layouts/MainLayout.vue";
import { Head } from '@inertiajs/vue3' 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 { Flight, ProfileView, User } from "@/Types/types"
import { router } from '@inertiajs/vue3' import { router } from '@inertiajs/vue3'
import { useFlightStats, FlightStats } from "@/Composables/useFlightStats" import { useFlightStats, FlightStats } from "@/Composables/useFlightStats"
@@ -17,9 +17,12 @@ const props = defineProps<{
user: User user: User
flights: Flight[] flights: Flight[]
canEdit: boolean canEdit: boolean
selectedFlightId: number | null
initialView?: ProfileView initialView?: ProfileView
}>() }>()
const localSelectedFlightId = ref(props.selectedFlightId)
// ── Filter state ────────────────────────────────────────────────────────────── // ── Filter state ──────────────────────────────────────────────────────────────
const selectedYears = ref<number[]>([]) const selectedYears = ref<number[]>([])
const selectedAirlines = ref<number[]>([]) const selectedAirlines = ref<number[]>([])
@@ -34,13 +37,17 @@ function onFiltersChange(filters: {
continents: string[] continents: string[]
flightClasses: number[] flightClasses: number[]
}) { }) {
localSelectedFlightId.value = null
console.time('filter+stats')
selectedYears.value = filters.years selectedYears.value = filters.years
selectedAirlines.value = filters.airlines selectedAirlines.value = filters.airlines
selectedCountries.value = filters.countries selectedCountries.value = filters.countries
selectedContinents.value = filters.continents selectedContinents.value = filters.continents
selectedFlightClasses.value = filters.flightClasses selectedFlightClasses.value = filters.flightClasses
console.timeEnd('filter+stats')
} }
function matchesFilters(f: Flight): boolean { function matchesFilters(f: Flight): boolean {
const date = new Date(f.departure_date) const date = new Date(f.departure_date)
if (selectedYears.value.length && !selectedYears.value.includes(date.getFullYear())) return false 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 const arrCode = f.arrival_airport.region?.continent?.code
if (!selectedContinents.value.includes(depCode ?? '') && !selectedContinents.value.includes(arrCode ?? '')) return false 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 !(selectedFlightClasses.value.length && !selectedFlightClasses.value.includes(f.flight_class?.id ?? -1));
return true
} }
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) 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 ──────────────────────────────────────────────────────────── // ── View switching ────────────────────────────────────────────────────────────
const activeView = ref<ProfileView>(props.initialView ?? 'board') const activeView = ref<ProfileView>(props.initialView ?? 'board')
@@ -73,6 +99,7 @@ const routeNames = {
} as const } as const
function switchView(view: ProfileView) { function switchView(view: ProfileView) {
localSelectedFlightId.value = null
activeView.value = view activeView.value = view
window.history.replaceState( window.history.replaceState(
window.history.state, window.history.state,
@@ -86,10 +113,10 @@ function switchView(view: ProfileView) {
<Head :title="`${user.name}'s Flights`" /> <Head :title="`${user.name}'s Flights`" />
<ProfileLayout :flights="flights" :user="user"> <ProfileLayout :flights="flights" :user="user">
<ProfileViewSwitcher :active-view="activeView" @update:active-view="switchView" /> <ProfileViewSwitcher :active-view="activeView" @update:active-view="switchView" />
<DepartureBoard v-show="activeView === 'board'" :flight-stats="stats" :canEdit="canEdit" /> <DepartureBoard v-if="activeView === 'board'" :flight-id="localSelectedFlightId" :flight-stats="stats" :canEdit="canEdit" />
<BoardingPasses v-show="activeView === 'passes'" :flight-stats="stats" :canEdit="canEdit" /> <BoardingPasses v-if="activeView === 'passes'" :flight-stats="stats" :canEdit="canEdit" />
<FlightMapAndCharts <FlightMapAndCharts
v-show="activeView === 'map'" v-if="activeView === 'map'"
:stats="stats" :stats="stats"
:canEdit="canEdit" :canEdit="canEdit"
@filters-change="onFiltersChange" @filters-change="onFiltersChange"
+2 -1
View File
@@ -73,7 +73,8 @@ Route::domain(config('app.domain'))->group(
Route::get('/u/{username}', [FlightProfileController::class, 'view'])->name('profile.view'); Route::get('/u/{username}', [FlightProfileController::class, 'view'])->name('profile.view');
Route::get('/u/{username}/map', [FlightProfileController::class, 'map'])->name('profile.map'); Route::get('/u/{username}/map', [FlightProfileController::class, 'map'])->name('profile.map');
Route::get('/u/{username}/departure-board', [FlightProfileController::class, 'departureBoard'])->name('profile.departure-board'); Route::get('/u/{username}/departure-board/{flight?}', [FlightProfileController::class, 'departureBoard'])
->name('profile.departure-board');
Route::get('/u/{username}/boarding-passes', [FlightProfileController::class, 'boardingPasses'])->name('profile.boarding-passes'); Route::get('/u/{username}/boarding-passes', [FlightProfileController::class, 'boardingPasses'])->name('profile.boarding-passes');
require __DIR__.'/auth.php'; require __DIR__.'/auth.php';