Added Charts

This commit is contained in:
2026-04-11 20:49:01 +10:00
parent e83fd3bdca
commit 95624f345c
16 changed files with 979 additions and 386 deletions
@@ -0,0 +1,59 @@
<template>
<Teleport to="body">
<div
v-if="visible"
class="chart-tooltip glass glass-border"
:style="{ top: y + 'px', left: x + 'px' }"
>
<slot />
</div>
</Teleport>
</template>
<script setup lang="ts">
defineProps<{
visible: boolean
x: number
y: number
}>()
</script>
<style>
.chart-tooltip {
position: fixed;
z-index: 9999;
pointer-events: none;
padding: 8px 12px;
font-size: 13px;
min-width: 140px;
}
.ct-sub {
font-size: 11px;
color: #556677;
margin-bottom: 8px;
}
.ct-name {
display: flex;
align-items: center;
gap: 8px;
font-weight: 500;
margin-bottom: 6px;
color: #a0b0c0;
}
.ct-row {
display: flex;
justify-content: space-between;
gap: 16px;
}
.ct-label {
color: #556677;
}
.ct-val {
font-weight: 500;
}
</style>
@@ -0,0 +1,127 @@
<template>
<div class="chart-wrap">
<div class="chart-title">Continents visited</div>
<apexchart
v-if="series.length"
type="donut"
height="280"
:options="chartOptions"
:series="seriesData"
/>
<div v-else class="chart-empty">No continent data available</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { Flight } from '@/Types/types'
const props = defineProps<{
flights: Flight[]
}>()
const series = computed(() => {
const counts = new Map<string, number>()
props.flights.forEach(f => {
const continents = new Set<string>()
const dep = f.departure_airport.region?.continent?.name
const arr = f.arrival_airport.region?.continent?.name
if (dep) continents.add(dep)
if (arr) continents.add(arr)
continents.forEach(c => counts.set(c, (counts.get(c) ?? 0) + 1))
})
return [...counts.entries()]
.sort((a, b) => b[1] - a[1])
.map(([name, count]) => ({ name, count }))
})
const seriesData = computed(() => series.value.map(s => s.count))
const chartOptions = computed(() => ({
chart: {
type: 'donut',
background: 'transparent',
fontFamily: 'inherit',
},
theme: { mode: 'dark' },
labels: series.value.map(s => s.name),
colors: ['#4da6ff', '#ffc107', '#a150d5', '#22c55e', '#f97316', '#e11d48', '#06b6d4'],
dataLabels: {
enabled: true,
formatter: (val: number) => `${Math.round(val)}%`,
style: { fontSize: '12px', fontWeight: 400 },
dropShadow: { enabled: false },
},
plotOptions: {
pie: {
donut: {
size: '60%',
labels: {
show: true,
total: {
show: true,
label: 'Total',
fontSize: '13px',
color: '#556677',
formatter: () => props.flights.length.toString(),
},
value: {
fontSize: '22px',
fontWeight: 500,
color: '#e0e6f0',
},
},
},
},
},
legend: {
position: 'bottom',
labels: { colors: '#778899' },
markers: { width: 8, height: 8, radius: 2 },
itemMargin: { horizontal: 12, vertical: 4 },
},
stroke: { width: 0 },
tooltip: {
theme: 'dark',
y: {
formatter: (val: number) => `${val} flights`,
},
},
}))
</script>
<style scoped>
.chart-wrap {
display: flex;
flex-direction: column;
gap: 4px;
}
.chart-title {
font-size: 13px;
font-weight: 500;
color: #556677;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.chart-empty {
height: 280px;
display: flex;
align-items: center;
justify-content: center;
font-size: 13px;
color: #445566;
}
.charts-row {
display: flex;
gap: 24px;
padding: 16px;
}
.charts-row > * {
flex: 1;
min-width: 0;
}
</style>
@@ -3,7 +3,7 @@
<div class="chart-title">Top countries</div>
<div v-if="series.length" class="chart-outer">
<div class="chart-scroll" :style="{ height: scrollHeight }">
<div class="chart-scroll" :style="{ height: scrollHeight }" @mousemove="onMouseMove" @mouseleave="onMouseLeave">
<apexchart
type="bar"
:height="chartHeight"
@@ -11,6 +11,16 @@
:series="chartSeries"
/>
</div>
<ChartTooltip :visible="!!tooltipItem" :x="tooltipX" :y="tooltipY">
<div class="ct-name">
<span :class="`fi fi-${tooltipItem?.code.toLowerCase()}`" />
{{ tooltipItem?.name }}
</div>
<div class="ct-row"><span class="ct-label">Flights</span><span class="ct-val">{{ tooltipItem?.past }}</span></div>
<div class="ct-row" v-if="tooltipItem?.upcoming"><span class="ct-label">Upcoming</span><span class="ct-val">{{ tooltipItem?.upcoming }}</span></div>
</ChartTooltip>
<div class="chart-footer">
<span class="total-count">{{ totalCountries }}</span>
<span class="total-label">total countries</span>
@@ -24,23 +34,49 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { Flight } from '@/Types/types'
import { useChartTooltip} from "@/Composables/useChartTooltip";
import ChartTooltip from '@/Components/FlightsGoneBy/Charts/ChartTooltip.vue'
const props = defineProps<{
flights: Flight[]
upcomingFlights: Flight[]
maxVisible?: number
}>()
const MAX_VISIBLE = 12
interface CountryItem {
name: string
past: number
upcoming: number
code: string
}
const { tooltipItem, tooltipX, tooltipY, onMouseMove, onMouseLeave } = useChartTooltip<CountryItem>()
const MAX_VISIBLE = computed(() => props?.maxVisible ?? 12)
const BAR_HEIGHT = 32
function countCountries(flights: Flight[]): Map<string, number> {
const counts = new Map<string, number>()
interface CountryItem {
name: string
code: string
past: number
upcoming: number
}
function countCountries(flights: Flight[]): Map<string, { count: number; code: string }> {
const counts = new Map<string, { count: number; code: string }>()
flights.forEach(f => {
const depCountry = f.departure_airport?.region?.country?.name ?? null
const arrCountry = f.arrival_airport?.region?.country?.name ?? null
if (depCountry) counts.set(depCountry, (counts.get(depCountry) ?? 0) + 1)
if (arrCountry && arrCountry !== depCountry) {
counts.set(arrCountry, (counts.get(arrCountry) ?? 0) + 1)
const dep = f.departure_airport?.region?.country
const arr = f.arrival_airport?.region?.country
if (dep?.name) {
const existing = counts.get(dep.name) ?? { count: 0, code: dep.code }
existing.count++
counts.set(dep.name, existing)
}
if (arr?.name && arr.name !== dep?.name) {
const existing = counts.get(arr.name) ?? { count: 0, code: arr.code }
existing.count++
counts.set(arr.name, existing)
}
})
return counts
@@ -49,36 +85,27 @@ function countCountries(flights: Flight[]): Map<string, number> {
const series = computed(() => {
const past = countCountries(props.flights)
const upcoming = countCountries(props.upcomingFlights)
const allCountries = new Set([...past.keys(), ...upcoming.keys()])
return [...allCountries]
.map(name => ({
name,
past: past.get(name) ?? 0,
upcoming: upcoming.get(name) ?? 0,
code: (past.get(name) ?? upcoming.get(name))!.code,
past: past.get(name)?.count ?? 0,
upcoming: upcoming.get(name)?.count ?? 0,
}))
.sort((a, b) => (b.past + b.upcoming) - (a.past + a.upcoming))
})
const totalCountries = computed(() => series.value.length)
const chartHeight = computed(() => series.value.length * BAR_HEIGHT + 40)
const scrollHeight = computed(() => {
const visible = Math.min(series.value.length, MAX_VISIBLE)
const visible = Math.min(series.value.length, MAX_VISIBLE.value)
return `${visible * BAR_HEIGHT + 40}px`
})
const chartSeries = computed(() => [
{
name: 'Flights',
data: series.value.map(s => s.past),
},
{
name: 'Upcoming',
data: series.value.map(s => s.upcoming),
},
{ name: 'Flights', data: series.value.map(s => s.past) },
{ name: 'Upcoming', data: series.value.map(s => s.upcoming) },
])
const chartOptions = computed(() => ({
@@ -89,6 +116,13 @@ const chartOptions = computed(() => ({
toolbar: { show: false },
animations: { enabled: false },
stacked: true,
events: {
mouseMove: (_e: MouseEvent, _chart: unknown, config: { dataPointIndex: number }) => {
if (config.dataPointIndex < 0) { tooltipItem.value = null; return }
tooltipItem.value = series.value[config.dataPointIndex] ?? null
},
mouseLeave: () => { tooltipItem.value = null },
},
},
theme: { mode: 'dark' },
plotOptions: {
@@ -100,9 +134,7 @@ const chartOptions = computed(() => ({
},
},
colors: ['#4da6ff', '#ffc107'],
dataLabels: {
enabled: false,
},
dataLabels: { enabled: false },
xaxis: {
categories: series.value.map(s => s.name),
labels: { show: false },
@@ -111,15 +143,10 @@ const chartOptions = computed(() => ({
},
yaxis: {
labels: {
style: {
colors: '#778899',
fontSize: '12px',
},
style: { colors: '#778899', fontSize: '12px' },
},
},
grid: {
show: false,
},
grid: { show: false },
legend: {
show: true,
position: 'top',
@@ -128,14 +155,7 @@ const chartOptions = computed(() => ({
markers: { width: 8, height: 8, radius: 2 },
itemMargin: { horizontal: 8 },
},
tooltip: {
theme: 'dark',
shared: true,
intersect: false,
y: {
formatter: (val: number) => `${val} flights`,
},
},
tooltip: { enabled: false },
states: {
hover: { filter: { type: 'lighten', value: 0.1 } },
},
@@ -170,18 +190,9 @@ const chartOptions = computed(() => ({
scrollbar-color: #334455 transparent;
}
.chart-scroll::-webkit-scrollbar {
width: 4px;
}
.chart-scroll::-webkit-scrollbar-track {
background: transparent;
}
.chart-scroll::-webkit-scrollbar-thumb {
background: #334455;
border-radius: 2px;
}
.chart-scroll::-webkit-scrollbar { width: 4px; }
.chart-scroll::-webkit-scrollbar-track { background: transparent; }
.chart-scroll::-webkit-scrollbar-thumb { background: #334455; border-radius: 2px; }
.chart-footer {
display: flex;
@@ -0,0 +1,126 @@
<template>
<div class="chart-wrap">
<div class="chart-title">International vs Domestic</div>
<apexchart
v-if="series.length"
type="donut"
height="280"
:options="chartOptions"
:series="seriesData"
/>
<div v-else class="chart-empty">No flight data available</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { Flight } from '@/Types/types'
const props = defineProps<{
flights: Flight[]
}>()
const series = computed(() => {
const counts = { International: 0, Domestic: 0 }
props.flights.forEach(f => {
const dep = f.departure_airport.region?.country?.id
const arr = f.arrival_airport.region?.country?.id
if (dep && arr) {
dep === arr ? counts.Domestic++ : counts.International++
}
})
return Object.entries(counts)
.filter(([, count]) => count > 0)
.map(([name, count]) => ({ name, count }))
})
const seriesData = computed(() => series.value.map(s => s.count))
const chartOptions = computed(() => ({
chart: {
type: 'donut',
background: 'transparent',
fontFamily: 'inherit',
},
theme: { mode: 'dark' },
labels: series.value.map(s => s.name),
colors: ['#4da6ff', '#a150d5'],
dataLabels: {
enabled: true,
formatter: (val: number) => `${Math.round(val)}%`,
style: { fontSize: '12px', fontWeight: 400 },
dropShadow: { enabled: false },
},
plotOptions: {
pie: {
donut: {
size: '60%',
labels: {
show: true,
total: {
show: true,
label: 'Total',
fontSize: '13px',
color: '#556677',
formatter: () => props.flights.length.toString(),
},
value: {
fontSize: '22px',
fontWeight: 500,
color: '#e0e6f0',
},
},
},
},
},
legend: {
position: 'bottom',
labels: { colors: '#778899' },
markers: { width: 8, height: 8, radius: 2 },
itemMargin: { horizontal: 12, vertical: 4 },
},
stroke: { width: 0 },
tooltip: {
theme: 'dark',
y: {
formatter: (val: number) => `${val} flights`,
},
},
}))
</script>
<style scoped>
.chart-wrap {
display: flex;
flex-direction: column;
gap: 4px;
}
.chart-title {
font-size: 13px;
font-weight: 500;
color: #556677;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.chart-empty {
height: 280px;
display: flex;
align-items: center;
justify-content: center;
font-size: 13px;
color: #445566;
}
.charts-row {
display: flex;
gap: 24px;
padding: 16px;
}
.charts-row > * {
flex: 1;
min-width: 0;
}
</style>
@@ -0,0 +1,113 @@
<template>
<div class="chart-wrap">
<div class="chart-title">Flights per day of week</div>
<apexchart
type="bar"
height="220"
:options="chartOptions"
:series="series"
/>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { Flight } from '@/Types/types'
const props = defineProps<{
flights: Flight[]
upcomingFlights: Flight[]
}>()
const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
// JS getDay() is 0=Sun, 1=Mon ... 6=Sat — remap to Mon-first
const dayIndex = (f: Flight): number => {
const date = new Date(f.departure_date)
const localDay = new Intl.DateTimeFormat('en', {
timeZone: f.departure_airport.timezone,
weekday: 'long',
}).format(date)
const idx = DAYS.indexOf(localDay)
return idx === -1 ? 0 : idx
}
const countByDay = (list: Flight[]) =>
DAYS.map((_, i) => list.filter(f => dayIndex(f) === i).length)
const series = computed(() => [
{ name: 'Flown', data: countByDay(props.flights) },
{ name: 'Upcoming', data: countByDay(props.upcomingFlights) },
])
const chartOptions = computed(() => ({
chart: {
type: 'bar',
stacked: true,
toolbar: { show: false },
background: 'transparent',
fontFamily: 'inherit',
},
theme: { mode: 'dark' },
plotOptions: {
bar: {
borderRadius: 3,
borderRadiusWhenStacked: 'last',
columnWidth: '55%',
},
},
colors: ['#4da6ff', '#ffc107'],
dataLabels: { enabled: false },
grid: {
borderColor: 'rgba(255,255,255,0.05)',
yaxis: { lines: { show: true } },
xaxis: { lines: { show: false } },
},
xaxis: {
categories: DAYS,
axisBorder: { show: false },
axisTicks: { show: false },
labels: {
style: { colors: '#445566', fontSize: '12px' },
},
},
yaxis: {
labels: {
style: { colors: '#445566', fontSize: '12px' },
},
},
legend: {
position: 'top',
horizontalAlign: 'right',
labels: { colors: '#778899' },
markers: { width: 8, height: 8, radius: 2 },
itemMargin: { horizontal: 12 },
},
tooltip: {
theme: 'dark',
shared: true,
intersect: false,
},
states: {
hover: { filter: { type: 'lighten', value: 0.1 } },
active: { filter: { type: 'none' } },
},
}))
</script>
<style scoped>
.chart-wrap {
display: flex;
flex-direction: column;
gap: 4px;
}
.chart-title {
font-size: 13px;
font-weight: 500;
color: #556677;
text-transform: uppercase;
letter-spacing: 0.08em;
}
</style>
@@ -19,12 +19,18 @@ const props = defineProps<{
upcomingFlights: Flight[]
}>()
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
const monthIndex = (f: Flight): number => {
const date = new Date(f.departure_date)
return Number(new Intl.DateTimeFormat('en', {
timeZone: f.departure_airport.timezone,
month: 'numeric',
}).format(date)) - 1 // numeric returns 1-12, convert to 0-indexed
}
const countByMonth = (list: Flight[]) =>
MONTHS.map((_, i) =>
list.filter(f => new Date(f.departure_date).getMonth() === i).length
)
MONTHS.map((_, i) => list.filter(f => monthIndex(f) === i).length)
const series = computed(() => [
{ name: 'Flown', data: countByMonth(props.flights) },
@@ -19,10 +19,16 @@ const props = defineProps<{
upcomingFlights: Flight[]
}>()
const flightYear = (f: Flight): number =>
Number(new Intl.DateTimeFormat('en', {
timeZone: f.departure_airport.timezone,
year: 'numeric',
}).format(new Date(f.departure_date)))
const years = computed(() => {
const allYears = new Set<number>()
;[...props.flights, ...props.upcomingFlights].forEach(f =>
allYears.add(new Date(f.departure_date).getFullYear())
allYears.add(flightYear(f))
)
const sorted = [...allYears].sort((a, b) => a - b)
@@ -36,10 +42,9 @@ const years = computed(() => {
return Array.from({ length: max - min + 1 }, (_, i) => min + i)
})
const countByYear = (list: Flight[]) =>
years.value.map(year =>
list.filter(f => new Date(f.departure_date).getFullYear() === year).length
)
years.value.map(year => list.filter(f => flightYear(f) === year).length)
const series = computed(() => [
{ name: 'Flown', data: countByYear(props.flights) },
@@ -3,7 +3,7 @@
<div class="chart-title">Top airlines</div>
<div v-if="series.length" class="chart-outer">
<div class="chart-scroll" :style="{ height: scrollHeight }">
<div class="chart-scroll" :style="{ height: scrollHeight }" @mousemove="onMouseMove" @mouseleave="onMouseLeave">
<apexchart
type="bar"
:height="chartHeight"
@@ -11,6 +11,13 @@
:series="chartSeries"
/>
</div>
<ChartTooltip :visible="!!tooltipItem" :x="tooltipX" :y="tooltipY">
<div class="ct-name"><img :src="`${page.logo_api_url}/airlines/logos/tail/id/${tooltipItem?.id}`" width="24" height="24"/>{{ tooltipItem?.name }}</div>
<div class="ct-row"><span class="ct-label">Flights</span><span class="ct-val">{{ tooltipItem?.past }}</span></div>
<div class="ct-row" v-if="tooltipItem?.upcoming"><span class="ct-label">Upcoming</span><span class="ct-val">{{ tooltipItem?.upcoming }}</span></div>
</ChartTooltip>
<div class="chart-footer">
<span class="total-count">{{ totalAirlines }}</span>
<span class="total-label">total airlines</span>
@@ -23,21 +30,39 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { Flight } from '@/Types/types'
import type {Flight, SharedProps} from '@/Types/types'
import { useChartTooltip } from '@/Composables/useChartTooltip'
import ChartTooltip from '@/Components/FlightsGoneBy/Charts/ChartTooltip.vue'
import {usePage} from "@inertiajs/vue3";
const page = usePage<SharedProps>().props
const props = defineProps<{
flights: Flight[]
upcomingFlights: Flight[]
}>()
interface AirlineItem {
name: string
past: number
upcoming: number
id: number
}
const { tooltipItem, tooltipX, tooltipY, onMouseMove, onMouseLeave } = useChartTooltip<AirlineItem>()
const MAX_VISIBLE = 12
const BAR_HEIGHT = 32
function countAirlines(flights: Flight[]): Map<string, number> {
const counts = new Map<string, number>()
function countAirlines(flights: Flight[]): Map<string, { count: number; id: number }> {
const counts = new Map<string, { count: number; id: number }>()
flights.forEach(f => {
const name = f.airline?.name ?? null
if (name) counts.set(name, (counts.get(name) ?? 0) + 1)
const airline = f.airline
if (!airline?.name) return
const existing = counts.get(airline.name) ?? { count: 0, id: airline.id }
existing.count++
counts.set(airline.name, existing)
})
return counts
}
@@ -45,14 +70,13 @@ function countAirlines(flights: Flight[]): Map<string, number> {
const series = computed(() => {
const past = countAirlines(props.flights)
const upcoming = countAirlines(props.upcomingFlights)
const allAirlines = new Set([...past.keys(), ...upcoming.keys()])
return [...allAirlines]
.map(name => ({
name,
past: past.get(name) ?? 0,
upcoming: upcoming.get(name) ?? 0,
id: (past.get(name) ?? upcoming.get(name))!.id,
past: past.get(name)?.count ?? 0,
upcoming: upcoming.get(name)?.count ?? 0,
}))
.sort((a, b) => (b.past + b.upcoming) - (a.past + a.upcoming))
})
@@ -65,7 +89,7 @@ const scrollHeight = computed(() => {
})
const chartSeries = computed(() => [
{ name: 'Flights', data: series.value.map(s => s.past) },
{ name: 'Flights', data: series.value.map(s => s.past) },
{ name: 'Upcoming', data: series.value.map(s => s.upcoming) },
])
@@ -77,6 +101,13 @@ const chartOptions = computed(() => ({
toolbar: { show: false },
animations: { enabled: false },
stacked: true,
events: {
mouseMove: (_e: MouseEvent, _chart: unknown, config: { dataPointIndex: number }) => {
if (config.dataPointIndex < 0) { tooltipItem.value = null; return }
tooltipItem.value = series.value[config.dataPointIndex] ?? null
},
mouseLeave: () => { tooltipItem.value = null },
},
},
theme: { mode: 'dark' },
plotOptions: {
@@ -97,10 +128,7 @@ const chartOptions = computed(() => ({
},
yaxis: {
labels: {
style: {
colors: '#778899',
fontSize: '12px',
},
style: { colors: '#778899', fontSize: '12px' },
},
},
grid: { show: false },
@@ -112,12 +140,7 @@ const chartOptions = computed(() => ({
markers: { width: 8, height: 8, radius: 2 },
itemMargin: { horizontal: 8 },
},
tooltip: {
theme: 'dark',
shared: true,
intersect: false,
y: { formatter: (val: number) => `${val} flights` },
},
tooltip: { enabled: false },
states: {
hover: { filter: { type: 'lighten', value: 0.1 } },
},
@@ -152,18 +175,9 @@ const chartOptions = computed(() => ({
scrollbar-color: #334455 transparent;
}
.chart-scroll::-webkit-scrollbar {
width: 4px;
}
.chart-scroll::-webkit-scrollbar-track {
background: transparent;
}
.chart-scroll::-webkit-scrollbar-thumb {
background: #334455;
border-radius: 2px;
}
.chart-scroll::-webkit-scrollbar { width: 4px; }
.chart-scroll::-webkit-scrollbar-track { background: transparent; }
.chart-scroll::-webkit-scrollbar-thumb { background: #334455; border-radius: 2px; }
.chart-footer {
display: flex;
@@ -3,7 +3,7 @@
<div class="chart-title">Top airports</div>
<div v-if="series.length" class="chart-outer">
<div class="chart-scroll" :style="{ height: scrollHeight }">
<div class="chart-scroll" :style="{ height: scrollHeight }" @mousemove="onMouseMove" @mouseleave="onMouseLeave">
<apexchart
type="bar"
:height="chartHeight"
@@ -11,6 +11,24 @@
:series="chartSeries"
/>
</div>
<ChartTooltip :visible="!!tooltipItem" :x="tooltipX" :y="tooltipY">
<div class="ct-name">{{ tooltipItem?.fullName }}</div>
<div class="ct-sub">{{ tooltipItem?.label }}</div>
<div class="ct-row">
<span class="ct-label">Departures</span>
<span class="ct-val">{{ tooltipItem?.departures }}</span>
</div>
<div class="ct-row">
<span class="ct-label">Arrivals</span>
<span class="ct-val">{{ tooltipItem?.arrivals }}</span>
</div>
<div v-if="tooltipItem?.upcoming" class="ct-row">
<span class="ct-label">Upcoming</span>
<span class="ct-val">{{ tooltipItem?.upcoming }}</span>
</div>
</ChartTooltip>
<div class="chart-footer">
<span class="total-count">{{ totalAirports }}</span>
<span class="total-label">total airports</span>
@@ -23,79 +41,54 @@
<script setup lang="ts">
import { computed } from 'vue'
import type {Airport, Flight} from '@/Types/types'
import type { Airport, Flight } from '@/Types/types'
import { useChartTooltip } from '@/Composables/useChartTooltip'
import ChartTooltip from '@/Components/FlightsGoneBy/Charts/ChartTooltip.vue'
const props = defineProps<{
flights: Flight[]
upcomingFlights: Flight[]
}>()
const MAX_VISIBLE = 12
const BAR_HEIGHT = 32
interface AirportCounts {
interface AirportItem {
label: string
fullName: string
departures: number
arrivals: number
upcoming: number
}
function buildAirportMap(flights: Flight[], key: 'departures' | 'arrivals' | 'upcoming'): Map<string, AirportCounts> {
const map = new Map<string, AirportCounts>()
const { tooltipItem, tooltipX, tooltipY, onMouseMove, onMouseLeave } = useChartTooltip<AirportItem>()
const empty = (): AirportCounts => ({ departures: 0, arrivals: 0, upcoming: 0 })
flights.forEach(f => {
const depName = f.departure_airport?.iata_code
? `${f.departure_airport.iata_code} ${f.departure_airport.name}`
: f.departure_airport?.name ?? null
const arrName = f.arrival_airport?.iata_code
? `${f.arrival_airport.iata_code} ${f.arrival_airport.name}`
: f.arrival_airport?.name ?? null
if (depName) {
const existing = map.get(depName) ?? empty()
existing[key]++
map.set(depName, existing)
}
if (arrName) {
const existing = map.get(arrName) ?? empty()
if (key !== 'upcoming') existing.arrivals++
else existing[key]++
map.set(arrName, existing)
}
})
return map
}
const MAX_VISIBLE = 12
const BAR_HEIGHT = 32
function airportLabel(airport: Airport | null | undefined): string | null {
if (!airport) return null
return airport.iata_code ?? airport.icao_code ?? airport.name ?? null
}
const series = computed(() => {
const past = new Map<string, AirportCounts & { label: string; fullName: string }>()
const empty = () => ({ departures: 0, arrivals: 0, upcoming: 0, label: '', fullName: '' })
const series = computed((): AirportItem[] => {
const map = new Map<string, AirportItem>()
const empty = (): AirportItem => ({ departures: 0, arrivals: 0, upcoming: 0, label: '', fullName: '' })
props.flights.forEach(f => {
const depLabel = airportLabel(f.departure_airport)
const arrLabel = airportLabel(f.arrival_airport)
if (depLabel) {
const e = past.get(depLabel) ?? empty()
const e = map.get(depLabel) ?? empty()
e.departures++
e.label = depLabel
e.fullName = f.departure_airport?.name ?? depLabel
past.set(depLabel, e)
map.set(depLabel, e)
}
if (arrLabel) {
const e = past.get(arrLabel) ?? empty()
const e = map.get(arrLabel) ?? empty()
e.arrivals++
e.label = arrLabel
e.fullName = f.arrival_airport?.name ?? arrLabel
past.set(arrLabel, e)
map.set(arrLabel, e)
}
})
@@ -104,23 +97,22 @@ const series = computed(() => {
const arrLabel = airportLabel(f.arrival_airport)
if (depLabel) {
const e = past.get(depLabel) ?? empty()
const e = map.get(depLabel) ?? empty()
e.upcoming++
e.label = depLabel
e.fullName = f.departure_airport?.name ?? depLabel
past.set(depLabel, e)
map.set(depLabel, e)
}
if (arrLabel) {
const e = past.get(arrLabel) ?? empty()
const e = map.get(arrLabel) ?? empty()
e.upcoming++
e.label = arrLabel
e.fullName = f.arrival_airport?.name ?? arrLabel
past.set(arrLabel, e)
map.set(arrLabel, e)
}
})
return [...past.entries()]
.map(([, counts]) => ({ ...counts }))
return [...map.values()]
.sort((a, b) =>
(b.departures + b.arrivals + b.upcoming) - (a.departures + a.arrivals + a.upcoming)
)
@@ -135,8 +127,8 @@ const scrollHeight = computed(() => {
const chartSeries = computed(() => [
{ name: 'Departures', data: series.value.map(s => s.departures) },
{ name: 'Arrivals', data: series.value.map(s => s.arrivals) },
{ name: 'Upcoming', data: series.value.map(s => s.upcoming) },
{ name: 'Arrivals', data: series.value.map(s => s.arrivals) },
{ name: 'Upcoming', data: series.value.map(s => s.upcoming) },
])
const chartOptions = computed(() => ({
@@ -147,6 +139,13 @@ const chartOptions = computed(() => ({
toolbar: { show: false },
animations: { enabled: false },
stacked: true,
events: {
mouseMove: (_e: MouseEvent, _chart: unknown, config: { dataPointIndex: number }) => {
if (config.dataPointIndex < 0) { tooltipItem.value = null; return }
tooltipItem.value = series.value[config.dataPointIndex] ?? null
},
mouseLeave: () => { tooltipItem.value = null },
},
},
theme: { mode: 'dark' },
plotOptions: {
@@ -167,10 +166,7 @@ const chartOptions = computed(() => ({
},
yaxis: {
labels: {
style: {
colors: '#778899',
fontSize: '12px',
},
style: { colors: '#778899', fontSize: '12px' },
},
},
grid: { show: false },
@@ -182,36 +178,7 @@ const chartOptions = computed(() => ({
markers: { width: 8, height: 8, radius: 2 },
itemMargin: { horizontal: 8 },
},
tooltip: {
theme: 'dark',
shared: true,
intersect: false,
custom: ({ dataPointIndex }: { dataPointIndex: number }) => {
const airport = series.value[dataPointIndex]
if (!airport) return ''
const rows = [
{ label: 'Departures', value: airport.departures, },
{ label: 'Arrivals', value: airport.arrivals, color: '#a150d5' },
{ label: 'Upcoming', value: airport.upcoming, color: '#ffc107' },
]
.filter(r => r.value > 0)
.map(r => `
<div class="glass" style="display:flex;align-items:center;gap:6px;padding:2px 0">
<span style="width:8px;height:8px;border-radius:2px;background:${r.color};flex-shrink:0"></span>
<span style="color:#778899">${r.label}:</span>
<span style="color:#e0e6f0;margin-left:auto;padding-left:12px">${r.value} flights</span>
</div>
`).join('')
return `
<div class="glass" style="padding:10px 12px;min-width:180px">
<div style="color:#e0e6f0;font-weight:500;margin-bottom:6px">${airport.fullName}</div>
<div style="color:#556677;font-size:11px;margin-bottom:8px">${airport.label}</div>
${rows}
</div>
`
},
},
tooltip: { enabled: false },
states: {
hover: { filter: { type: 'lighten', value: 0.1 } },
},
@@ -246,18 +213,9 @@ const chartOptions = computed(() => ({
scrollbar-color: #334455 transparent;
}
.chart-scroll::-webkit-scrollbar {
width: 4px;
}
.chart-scroll::-webkit-scrollbar-track {
background: transparent;
}
.chart-scroll::-webkit-scrollbar-thumb {
background: #334455;
border-radius: 2px;
}
.chart-scroll::-webkit-scrollbar { width: 4px; }
.chart-scroll::-webkit-scrollbar-track { background: transparent; }
.chart-scroll::-webkit-scrollbar-thumb { background: #334455; border-radius: 2px; }
.chart-footer {
display: flex;
@@ -286,4 +244,10 @@ const chartOptions = computed(() => ({
font-size: 13px;
color: #445566;
}
.ct-sub {
font-size: 11px;
color: #556677;
margin-bottom: 8px;
}
</style>
@@ -1,40 +1,57 @@
<template>
<!-- Year full width -->
<div class="flight-charts glass">
<FlightsPerYearChart :flights="flights" :upcoming-flights="upcomingFlights"/>
<FlightsPerYearChart :flights="flights" :upcoming-flights="upcomingFlights" />
</div>
<div class="flight-charts glass">
<!-- Month + Day of week -->
<div class="flight-charts glass charts-row">
<FlightsPerMonthChart :flights="flights" :upcoming-flights="upcomingFlights" />
<FlightsPerDayChart :flights="flights" :upcoming-flights="upcomingFlights" />
</div>
<!-- Reasons + Class + Seat type -->
<div class="flight-charts glass charts-row">
<FlightReasonsChart :flights="[...flights, ...upcomingFlights]" />
<FlightClassChart :flights="[...flights, ...upcomingFlights]" />
<SeatTypeChart :flights="[...flights, ...upcomingFlights]" />
<FlightClassChart :flights="[...flights, ...upcomingFlights]" />
<SeatTypeChart :flights="[...flights, ...upcomingFlights]" />
</div>
<!-- Countries (tall) + Continents & Flight Type stacked -->
<div class="flight-charts glass charts-row">
<CountriesChart :flights="flights" :upcoming-flights="upcomingFlights" />
<CountriesChart :max-visible="18" :flights="flights" :upcoming-flights="upcomingFlights" class="chart-tall" />
<div class="charts-stack">
<ContinentsChart :flights="flights" :upcoming-flights="upcomingFlights" />
<FlightTypeChart :flights="[...flights, ...upcomingFlights]" :upcoming-flights="upcomingFlights" />
</div>
</div>
<!-- Airlines + Airports -->
<div class="flight-charts glass charts-row">
<TopAirlinesChart :flights="flights" :upcoming-flights="upcomingFlights" />
</div>
<div class="flight-charts glass charts-row">
<TopAirportsChart :flights="flights" :upcoming-flights="upcomingFlights" />
</div>
<!-- Routes + International vs Domestic -->
<div class="flight-charts glass charts-row">
<TopRoutesChart :flights="flights" :upcoming-flights="upcomingFlights" />
<TopRoutesChart :flights="[...flights, ...upcomingFlights]" :upcoming-flights="upcomingFlights" />
</div>
</template>
<script setup lang="ts">
import type { Flight } from '@/Types/types'
import FlightsPerYearChart from "@/Components/FlightsGoneBy/Charts/FlightsPerYearChart.vue";
import FlightsPerMonthChart from "@/Components/FlightsGoneBy/Charts/FlightsPerMonthChart.vue";
import FlightReasonsChart from "@/Components/FlightsGoneBy/Charts/FlightReasonsChart.vue";
import FlightClassChart from "@/Components/FlightsGoneBy/Charts/FlightClassChart.vue";
import SeatTypeChart from "@/Components/FlightsGoneBy/Charts/SeatTypeChart.vue";
import CountriesChart from "@/Components/FlightsGoneBy/Charts/CountriesChart.vue";
import TopAirlinesChart from "@/Components/FlightsGoneBy/Charts/TopAirlinesChart.vue";
import TopAirportsChart from "@/Components/FlightsGoneBy/Charts/TopAirportsChart.vue";
import TopRoutesChart from "@/Components/FlightsGoneBy/Charts/TopRoutesChart.vue";
import FlightsPerYearChart from '@/Components/FlightsGoneBy/Charts/FlightsPerYearChart.vue'
import FlightsPerMonthChart from '@/Components/FlightsGoneBy/Charts/FlightsPerMonthChart.vue'
import FlightsPerDayChart from '@/Components/FlightsGoneBy/Charts/FlightsPerDayChart.vue'
import FlightReasonsChart from '@/Components/FlightsGoneBy/Charts/FlightReasonsChart.vue'
import FlightClassChart from '@/Components/FlightsGoneBy/Charts/FlightClassChart.vue'
import SeatTypeChart from '@/Components/FlightsGoneBy/Charts/SeatTypeChart.vue'
import CountriesChart from '@/Components/FlightsGoneBy/Charts/CountriesChart.vue'
import ContinentsChart from '@/Components/FlightsGoneBy/Charts/ContinentsChart.vue'
import TopAirlinesChart from '@/Components/FlightsGoneBy/Charts/TopAirlinesChart.vue'
import TopAirportsChart from '@/Components/FlightsGoneBy/Charts/TopAirportsChart.vue'
import TopRoutesChart from '@/Components/FlightsGoneBy/Charts/TopRoutesChart.vue'
import FlightTypeChart from '@/Components/FlightsGoneBy/Charts/FlightTypeChart.vue'
defineProps<{
flights: Flight[]
@@ -54,14 +71,29 @@ defineProps<{
.charts-row {
flex-direction: row;
flex-wrap: wrap;
align-items: flex-start;
}
.charts-row > :deep(*) {
flex: 1;
flex: 1 1 300px;
min-width: 0;
}
.chart-tall {
flex: 1 1 300px;
min-width: 0;
}
.charts-stack {
flex: 1 1 300px;
min-width: 0;
display: flex;
flex-direction: column;
gap: 24px;
}
@media (max-width: 768px) {
.charts-row {
flex-direction: column;
@@ -8,14 +8,39 @@
</div>
</template>
<script>
import { defineComponent, ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
<script lang="ts">
import { defineComponent, ref, onMounted, onBeforeUnmount, watch, nextTick, PropType } from 'vue'
import maplibregl from 'maplibre-gl'
import 'maplibre-gl/dist/maplibre-gl.css'
import { SharedProps } from '@/Types/types'
import { usePage } from '@inertiajs/vue3'
import {Flight, Airport, Airline, Region, Country} from "@/Types/types";
function greatCircleGeoJSON(from, to, steps = 64) {
const toRad = d => d * Math.PI / 180
const toDeg = r => r * 180 / Math.PI
interface RouteFlightBucket {
historical: Flight[]
future: Flight[]
}
type LngLat = [number, number]
interface RouteFeatureProperties {
color?: string
routeKey: string
depId: number
arrId: number
}
interface AirportFeatureProperties {
id: number
}
// ── GeoJSON helpers ───────────────────────────────────────────────────────────
const page = usePage<SharedProps>().props
function greatCircleGeoJSON(from: LngLat, to: LngLat, steps = 64): LngLat[] {
const toRad = (d: number): number => d * Math.PI / 180
const toDeg = (r: number): number => r * 180 / Math.PI
const lat1 = toRad(from[1]), lng1 = toRad(from[0])
const lat2 = toRad(to[1]), lng2 = toRad(to[0])
const d = 2 * Math.asin(Math.sqrt(
@@ -23,7 +48,7 @@ function greatCircleGeoJSON(from, to, steps = 64) {
Math.cos(lat1) * Math.cos(lat2) * Math.sin((lng2 - lng1) / 2) ** 2
))
if (d === 0) return [[from[0], from[1]], [to[0], to[1]]]
const points = []
const points: LngLat[] = []
for (let i = 0; i <= steps; i++) {
const f = i / steps
const A = Math.sin((1 - f) * d) / Math.sin(d)
@@ -41,7 +66,7 @@ function greatCircleGeoJSON(from, to, steps = 64) {
return points
}
function airportPopupHTML(airport) {
function airportPopupHTML(airport: Airport): string {
const elevation = airport.elevation_ft !== null
? `<div class="ap-row"><span class="ap-label">Elevation</span><span class="ap-value">${airport.elevation_ft.toLocaleString()} ft</span></div>`
: ''
@@ -68,29 +93,42 @@ function airportPopupHTML(airport) {
</div>`
}
function routePopupHTML(historical, future) {
const groupByDirection = (list) => {
const dirs = new Map()
function routePopupHTML(historical: Flight[], future: Flight[]): string {
interface DirectionGroup {
label: string
airlines: string[]
}
const groupByDirection = (list: Flight[]): DirectionGroup[] => {
const dirs = new Map<string, DirectionGroup>()
list.forEach(f => {
const key = `${f.departure_airport.id}-${f.arrival_airport.id}`
const label = `${f.departure_airport.municipality} to ${f.arrival_airport.municipality}`
if (!dirs.has(key)) dirs.set(key, { label, airlines: [] })
const airline = f.airline?.name
if (airline && !dirs.get(key).airlines.includes(airline)) {
dirs.get(key).airlines.push(airline)
const airline = `<span style="display:inline-flex;align-items:center;gap:6px;">
<img src="${page.logo_api_url}/airlines/logos/tail/id/${f.airline?.id}" width="24" height="24" alt="${f.airline?.IATA_code}" style="flex-shrink:0;" />
${f.airline?.name}
</span>`
if (airline && !dirs.get(key)!.airlines.includes(airline)) {
dirs.get(key)!.airlines.push(airline)
}
})
return [...dirs.values()]
}
const renderSection = (title, list) => {
const renderSection = (title: string, list: Flight[]): string => {
if (!list.length) return ''
const rows = groupByDirection(list).map(({ label, airlines }) => `
const rows = groupByDirection(list).map(({ label, airlines }) => {
return `
<div class="rp-direction">
<div class="rp-route">${label}</div>
<div class="rp-airlines">${airlines.join(', ') || '—'}</div>
</div>`).join('')
<div class="rp-airlines">${airlines.join('<br/> ') || '—'}</div>
</div>`
}).join('')
return `<div class="rp-section"><div class="rp-section-title">${title}</div>${rows}</div>`
}
const divider = historical.length && future.length ? '<div class="rp-divider"></div>' : ''
return `
<div class="rp-tooltip glass">
@@ -105,34 +143,34 @@ export default defineComponent({
props: {
flights: {
type: Array,
default: () => [],
type: Array as PropType<Flight[]>,
default: (): Flight[] => [],
},
},
setup(props) {
const mapContainer = ref(null)
let map = null
let popup = null
let pulseFrame = null
const mapContainer = ref<HTMLDivElement | null>(null)
let map: maplibregl.Map | null = null
let popup: maplibregl.Popup | null = null
let pulseFrame: number | null = null
const PULSE_PHASES = 6
const airportById = new Map()
const routeFlights = new Map()
let selectedAirportId = null
const airportById = new Map<number, Airport>()
const routeFlights = new Map<string, RouteFlightBucket>()
let selectedAirportId: number | null = null
let suppressRoutePopup = false
const isTouchDevice = () => window.matchMedia('(pointer: coarse)').matches
const isTouchDevice = (): boolean => window.matchMedia('(pointer: coarse)').matches
const showPopup = (lngLat, html) => {
popup.setLngLat(lngLat).setHTML(html).addTo(map)
const showPopup = (lngLat: maplibregl.LngLatLike, html: string): void => {
popup!.setLngLat(lngLat).setHTML(html).addTo(map!)
}
// ── Filter ────────────────────────────────────────────────────────────
const applyFilter = () => {
const applyFilter = (): void => {
if (!map || !map.isStyleLoaded()) return
const id = selectedAirportId
const filter = id
const filter: maplibregl.FilterSpecification | null = id
? ['any', ['==', ['get', 'depId'], id], ['==', ['get', 'arrId'], id]]
: null
@@ -152,78 +190,85 @@ export default defineComponent({
}
// ── Route flight lookup ───────────────────────────────────────────────
const buildRouteFlights = () => {
const buildRouteFlights = (): void => {
routeFlights.clear()
const now = new Date()
props.flights.forEach((flight) => {
const key = [flight.departure_airport.id, flight.arrival_airport.id].sort().join('-')
if (!routeFlights.has(key)) routeFlights.set(key, { historical: [], future: [] })
routeFlights.get(key)[new Date(flight.departure_date) > now ? 'future' : 'historical'].push(flight)
routeFlights.get(key)![new Date(flight.departure_date) > now ? 'future' : 'historical'].push(flight)
})
}
interface RoutesGeoJSON {
historical: GeoJSON.FeatureCollection<GeoJSON.LineString, RouteFeatureProperties>
future: GeoJSON.FeatureCollection<GeoJSON.LineString, RouteFeatureProperties>
}
// ── GeoJSON builders ──────────────────────────────────────────────────
const buildRoutesGeoJSON = () => {
const buildRoutesGeoJSON = (): RoutesGeoJSON => {
buildRouteFlights()
const now = new Date()
const routeCounts = new Map()
const routeCounts = new Map<string, number>()
props.flights.forEach((flight) => {
if (new Date(flight.departure_date) > now) return
const key = [flight.departure_airport.id, flight.arrival_airport.id].sort().join('-')
routeCounts.set(key, (routeCounts.get(key) ?? 0) + 1)
})
const routeColor = (count) => {
const routeColor = (count: number): string => {
if (count >= 5) return '#f97316'
if (count >= 3) return '#eab308'
if (count >= 2) return '#22c55e'
return '#a150d5'
}
const historicalFeatures = props.flights
.filter(f => new Date(f.departure_date) <= now)
.map((flight) => {
const key = [flight.departure_airport.id, flight.arrival_airport.id].sort().join('-')
const count = routeCounts.get(key) ?? 1
return {
type: 'Feature',
properties: {
color: routeColor(count), routeKey: key,
depId: flight.departure_airport.id,
arrId: flight.arrival_airport.id,
},
geometry: {
type: 'LineString',
coordinates: greatCircleGeoJSON(
[flight.departure_airport.longitude_deg, flight.departure_airport.latitude_deg],
[flight.arrival_airport.longitude_deg, flight.arrival_airport.latitude_deg],
),
},
}
})
const historicalFeatures: GeoJSON.Feature<GeoJSON.LineString, RouteFeatureProperties>[] =
props.flights
.filter(f => new Date(f.departure_date) <= now)
.map((flight) => {
const key = [flight.departure_airport.id, flight.arrival_airport.id].sort().join('-')
const count = routeCounts.get(key) ?? 1
return {
type: 'Feature',
properties: {
color: routeColor(count), routeKey: key,
depId: flight.departure_airport.id,
arrId: flight.arrival_airport.id,
},
geometry: {
type: 'LineString',
coordinates: greatCircleGeoJSON(
[flight.departure_airport.longitude_deg, flight.departure_airport.latitude_deg],
[flight.arrival_airport.longitude_deg, flight.arrival_airport.latitude_deg],
),
},
}
})
const historicalKeys = new Set(routeCounts.keys())
const futureFeatures = props.flights
.filter((flight) => {
if (new Date(flight.departure_date) <= now) return false
const key = [flight.departure_airport.id, flight.arrival_airport.id].sort().join('-')
return !historicalKeys.has(key)
})
.map((flight) => {
const key = [flight.departure_airport.id, flight.arrival_airport.id].sort().join('-')
return {
type: 'Feature',
properties: { routeKey: key, depId: flight.departure_airport.id, arrId: flight.arrival_airport.id },
geometry: {
type: 'LineString',
coordinates: greatCircleGeoJSON(
[flight.departure_airport.longitude_deg, flight.departure_airport.latitude_deg],
[flight.arrival_airport.longitude_deg, flight.arrival_airport.latitude_deg],
),
},
}
})
const futureFeatures: GeoJSON.Feature<GeoJSON.LineString, RouteFeatureProperties>[] =
props.flights
.filter((flight) => {
if (new Date(flight.departure_date) <= now) return false
const key = [flight.departure_airport.id, flight.arrival_airport.id].sort().join('-')
return !historicalKeys.has(key)
})
.map((flight) => {
const key = [flight.departure_airport.id, flight.arrival_airport.id].sort().join('-')
return {
type: 'Feature',
properties: { routeKey: key, depId: flight.departure_airport.id, arrId: flight.arrival_airport.id },
geometry: {
type: 'LineString',
coordinates: greatCircleGeoJSON(
[flight.departure_airport.longitude_deg, flight.departure_airport.latitude_deg],
[flight.arrival_airport.longitude_deg, flight.arrival_airport.latitude_deg],
),
},
}
})
return {
historical: { type: 'FeatureCollection', features: historicalFeatures },
@@ -231,13 +276,13 @@ export default defineComponent({
}
}
const buildAirportsGeoJSON = () => {
const seen = new Map()
const buildAirportsGeoJSON = (): GeoJSON.FeatureCollection<GeoJSON.Point, AirportFeatureProperties>[] => {
const seen = new Map<number, Airport>()
props.flights.forEach(({ departure_airport: dep, arrival_airport: arr }) => {
if (!seen.has(dep.id)) seen.set(dep.id, dep)
if (!seen.has(arr.id)) seen.set(arr.id, arr)
})
const buckets = Array.from({ length: PULSE_PHASES }, () => [])
const buckets: Airport[][] = Array.from({ length: PULSE_PHASES }, () => [])
;[...seen.values()].forEach(airport => buckets[airport.id % PULSE_PHASES].push(airport))
return buckets.map(airports => ({
type: 'FeatureCollection',
@@ -250,35 +295,35 @@ export default defineComponent({
}
// ── Map layers ────────────────────────────────────────────────────────
const addLayers = () => {
const addLayers = (): void => {
const { historical, future } = buildRoutesGeoJSON()
map.addSource('routes', { type: 'geojson', data: historical })
map.addLayer({
map!.addSource('routes', { type: 'geojson', data: historical })
map!.addLayer({
id: 'routes-line', type: 'line', source: 'routes',
paint: { 'line-color': ['get', 'color'], 'line-opacity': 0.75, 'line-width': 1.8 },
layout: { 'line-join': 'round', 'line-cap': 'round' },
})
map.addLayer({
map!.addLayer({
id: 'routes-hit', type: 'line', source: 'routes',
paint: { 'line-color': 'transparent', 'line-width': 12 },
})
map.addSource('routes-future', { type: 'geojson', data: future })
map.addLayer({
map!.addSource('routes-future', { type: 'geojson', data: future })
map!.addLayer({
id: 'routes-future-line', type: 'line', source: 'routes-future',
paint: { 'line-color': '#ffffff', 'line-opacity': 0.5, 'line-width': 1.5, 'line-dasharray': [3, 3] },
layout: { 'line-join': 'round', 'line-cap': 'round' },
})
map.addLayer({
map!.addLayer({
id: 'routes-future-hit', type: 'line', source: 'routes-future',
paint: { 'line-color': 'transparent', 'line-width': 12 },
})
const airportBuckets = buildAirportsGeoJSON()
airportBuckets.forEach((data, i) => {
map.addSource(`airports-${i}`, { type: 'geojson', data })
map.addLayer({
map!.addSource(`airports-${i}`, { type: 'geojson', data })
map!.addLayer({
id: `airports-pulse-${i}`, type: 'circle', source: `airports-${i}`,
paint: {
'circle-radius': 8, 'circle-color': 'transparent',
@@ -286,7 +331,7 @@ export default defineComponent({
'circle-stroke-opacity': 0.6,
},
})
map.addLayer({
map!.addLayer({
id: `airports-dot-${i}`, type: 'circle', source: `airports-${i}`,
paint: {
'circle-radius': 5, 'circle-color': '#4da6ff',
@@ -305,25 +350,26 @@ export default defineComponent({
})
for (let i = 0; i < PULSE_PHASES; i++) {
// Desktop: hover to show airport popup
map.on('mouseenter', `airports-dot-${i}`, (e) => {
map.getCanvas().style.cursor = 'pointer'
map!.on('mouseenter', `airports-dot-${i}`, (e) => {
map!.getCanvas().style.cursor = 'pointer'
if (isTouch) return
const airport = airportById.get(Number(e.features[0].properties.id))
if (airport) showPopup(e.features[0].geometry.coordinates, airportPopupHTML(airport))
const airport = airportById.get(Number(e.features![0].properties.id))
const geom = e.features![0].geometry
if (airport && geom.type === 'Point') {
showPopup(geom.coordinates as LngLat, airportPopupHTML(airport))
}
})
map.on('mouseleave', `airports-dot-${i}`, () => {
map.getCanvas().style.cursor = ''
map!.on('mouseleave', `airports-dot-${i}`, () => {
map!.getCanvas().style.cursor = ''
if (isTouch) return
popup.remove()
popup!.remove()
})
// Click: select airport, suppress route popup, close any open popup
map.on('click', `airports-dot-${i}`, (e) => {
map!.on('click', `airports-dot-${i}`, (e) => {
suppressRoutePopup = true
popup.remove()
popup!.remove()
const id = Number(e.features[0].properties.id)
const id = Number(e.features![0].properties.id)
selectedAirportId = selectedAirportId === id ? null : id
applyFilter()
@@ -331,65 +377,62 @@ export default defineComponent({
})
}
// Desktop: hover to show route popup
map.on('mouseenter', 'routes-hit', (e) => {
map!.on('mouseenter', 'routes-hit', (e) => {
if (isTouch) return
map.getCanvas().style.cursor = 'pointer'
const rf = routeFlights.get(e.features[0].properties.routeKey)
map!.getCanvas().style.cursor = 'pointer'
const rf = routeFlights.get(e.features![0].properties.routeKey as string)
if (rf) showPopup(e.lngLat, routePopupHTML(rf.historical, rf.future))
})
map.on('mouseleave', 'routes-hit', () => {
map!.on('mouseleave', 'routes-hit', () => {
if (isTouch) return
map.getCanvas().style.cursor = ''
popup.remove()
map!.getCanvas().style.cursor = ''
popup!.remove()
})
// Touch: tap to show route popup (suppressed if airport was just tapped)
map.on('click', 'routes-hit', (e) => {
map!.on('click', 'routes-hit', (e) => {
if (!isTouch) return
if (suppressRoutePopup) return
const rf = routeFlights.get(e.features[0].properties.routeKey)
const rf = routeFlights.get(e.features![0].properties.routeKey as string)
if (rf) showPopup(e.lngLat, routePopupHTML(rf.historical, rf.future))
})
map.on('mouseenter', 'routes-future-hit', (e) => {
map!.on('mouseenter', 'routes-future-hit', (e) => {
if (isTouch) return
map.getCanvas().style.cursor = 'pointer'
const rf = routeFlights.get(e.features[0].properties.routeKey)
map!.getCanvas().style.cursor = 'pointer'
const rf = routeFlights.get(e.features![0].properties.routeKey as string)
if (rf) showPopup(e.lngLat, routePopupHTML(rf.historical, rf.future))
})
map.on('mouseleave', 'routes-future-hit', () => {
map!.on('mouseleave', 'routes-future-hit', () => {
if (isTouch) return
map.getCanvas().style.cursor = ''
popup.remove()
map!.getCanvas().style.cursor = ''
popup!.remove()
})
map.on('click', 'routes-future-hit', (e) => {
map!.on('click', 'routes-future-hit', (e) => {
if (!isTouch) return
if (suppressRoutePopup) return
const rf = routeFlights.get(e.features[0].properties.routeKey)
const rf = routeFlights.get(e.features![0].properties.routeKey as string)
if (rf) showPopup(e.lngLat, routePopupHTML(rf.historical, rf.future))
})
// Tap on empty map: deselect airport and close any popup
map.on('click', (e) => {
const features = map.queryRenderedFeatures(e.point, {
map!.on('click', (e) => {
const features = map!.queryRenderedFeatures(e.point, {
layers: Array.from({ length: PULSE_PHASES }, (_, i) => `airports-dot-${i}`),
})
if (!features.length) {
selectedAirportId = null
applyFilter()
popup.remove()
popup!.remove()
}
})
const period = 2200
const animate = () => {
const animate = (): void => {
const now = Date.now()
for (let i = 0; i < PULSE_PHASES; i++) {
const t = ((now + (i / PULSE_PHASES) * period) % period) / period
map.setPaintProperty(`airports-pulse-${i}`, 'circle-radius', 5 + t * 13)
map!.setPaintProperty(`airports-pulse-${i}`, 'circle-radius', 5 + t * 13)
if (!selectedAirportId) {
map.setPaintProperty(`airports-pulse-${i}`, 'circle-stroke-opacity', 0.7 * (1 - t))
map!.setPaintProperty(`airports-pulse-${i}`, 'circle-stroke-opacity', 0.7 * (1 - t))
}
}
pulseFrame = requestAnimationFrame(animate)
@@ -397,21 +440,21 @@ export default defineComponent({
animate()
}
const fitBounds = () => {
const fitBounds = (): void => {
if (!props.flights.length) return
const lngs = props.flights.flatMap(f => [f.departure_airport.longitude_deg, f.arrival_airport.longitude_deg])
const lats = props.flights.flatMap(f => [f.departure_airport.latitude_deg, f.arrival_airport.latitude_deg])
map.fitBounds(
map!.fitBounds(
[[Math.min(...lngs), Math.min(...lats)], [Math.max(...lngs), Math.max(...lats)]],
{ padding: 60, duration: 0 },
)
}
// ── Map init ──────────────────────────────────────────────────────────
const initMap = () => {
const initMap = (): void => {
nextTick(() => {
map = new maplibregl.Map({
container: mapContainer.value,
container: mapContainer.value!,
style: {
version: 8,
sources: {
@@ -440,17 +483,19 @@ export default defineComponent({
}
// ── Data updates ──────────────────────────────────────────────────────
const updateData = () => {
const updateData = (): void => {
if (!map || !map.isStyleLoaded()) return
airportById.clear()
props.flights.forEach(({ departure_airport: dep, arrival_airport: arr }) => {
airportById.set(dep.id, dep)
airportById.set(arr.id, arr)
})
const { historical, future } = buildRoutesGeoJSON()
map.getSource('routes')?.setData(historical)
map.getSource('routes-future')?.setData(future)
buildAirportsGeoJSON().forEach((data, i) => map.getSource(`airports-${i}`)?.setData(data))
const { historical, future } = buildRoutesGeoJSON();
(map.getSource('routes') as maplibregl.GeoJSONSource)?.setData(historical);
(map.getSource('routes-future') as maplibregl.GeoJSONSource)?.setData(future)
buildAirportsGeoJSON().forEach((data, i) =>
(map!.getSource(`airports-${i}`) as maplibregl.GeoJSONSource)?.setData(data)
)
fitBounds()
}
@@ -465,7 +510,7 @@ export default defineComponent({
watch(() => props.flights, updateData, { deep: true })
onBeforeUnmount(() => {
if (pulseFrame) cancelAnimationFrame(pulseFrame)
if (pulseFrame !== null) cancelAnimationFrame(pulseFrame)
if (map) { map.remove(); map = null }
})
@@ -1,5 +1,5 @@
<template>
<FlightMap :flights="mappedFlights" class="profile-map__map" />
<FlightMap :page="page.props" :flights="mappedFlights" class="profile-map__map" />
<div class="profile-map__toolbar">
<v-select
@@ -88,6 +88,46 @@
<span v-if="index === 2" class="text-caption text-medium-emphasis">+{{ selectedCountries.length - 2 }}</span>
</template>
</v-select>
<v-select
v-model="selectedContinents"
:items="availableContinents"
item-title="name"
item-value="code"
label="Continent"
multiple
clearable
hide-details
density="compact"
variant="outlined"
>
<template #selection="{ item, index }">
<span v-if="index < 2" class="v-select__selection-text">
{{ (item as any).name }}<span v-if="index < Math.min(selectedContinents.length, 2) - 1">,&nbsp;</span>
</span>
<span v-if="index === 2" class="text-caption text-medium-emphasis">+{{ selectedContinents.length - 2 }}</span>
</template>
</v-select>
<v-select
v-model="selectedFlightClasses"
:items="availableFlightClasses"
item-title="name"
item-value="id"
label="Flight class"
multiple
clearable
hide-details
density="compact"
variant="outlined"
>
<template #selection="{ item, index }">
<span v-if="index < 2" class="v-select__selection-text">
{{ (item as any).name }}<span v-if="index < Math.min(selectedFlightClasses.length, 2) - 1">,&nbsp;</span>
</span>
<span v-if="index === 2" class="text-caption text-medium-emphasis">+{{ selectedFlightClasses.length - 2 }}</span>
</template>
</v-select>
</div>
<FlightStatsBar :flights="pastFlights" :upcoming-flights="upcomingFlights" />
@@ -98,25 +138,22 @@
import { computed, ref } from 'vue'
import { usePage } from '@inertiajs/vue3'
import FlightMap from '@/Components/FlightsGoneBy/FlightMap.vue'
import type { Flight } from '@/Types/types'
import FlightStatsBar from "@/Components/FlightsGoneBy/FlightStatsBar.vue";
import FlightCharts from "@/Components/FlightsGoneBy/FlightCharts.vue";
import type { Flight, SharedProps } from '@/Types/types'
import FlightStatsBar from '@/Components/FlightsGoneBy/FlightStatsBar.vue'
import FlightCharts from '@/Components/FlightsGoneBy/FlightCharts.vue'
const props = defineProps<{
flights: Flight[]
}>()
const mappedFlights = computed(() => [
...pastFlights.value,
...upcomingFlights.value,
])
const page = usePage<SharedProps>()
const now = new Date()
const page = usePage()
const now = new Date()
const selectedYears = ref<number[]>([])
const selectedAirlines = ref<number[]>([])
const selectedCountries = ref<string[]>([])
const selectedYears = ref<number[]>([])
const selectedAirlines = ref<number[]>([])
const selectedCountries = ref<string[]>([])
const selectedContinents = ref<string[]>([])
const selectedFlightClasses = ref<number[]>([])
// ── Helpers ───────────────────────────────────────────────────────────────────
@@ -155,49 +192,77 @@ const availableCountries = computed((): { code: string; name: string }[] => {
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))
})
// ── Filter helper ─────────────────────────────────────────────────────────────
function matchesFilters(f: Flight, date: Date): boolean {
if (selectedYears.value.length && !selectedYears.value.includes(date.getFullYear())) return false
if (selectedAirlines.value.length && !selectedAirlines.value.includes(f.airline?.id ?? -1)) return false
if (selectedCountries.value.length) {
const depCode = f.departure_airport.region?.country?.code
const arrCode = f.arrival_airport.region?.country?.code
if (!selectedCountries.value.includes(depCode ?? '') && !selectedCountries.value.includes(arrCode ?? '')) return false
}
if (selectedContinents.value.length) {
const depCode = f.departure_airport.region?.continent?.code
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
}
// ── Filtered flights ──────────────────────────────────────────────────────────
const pastFlights = computed(() => {
return props.flights.filter(f => {
const pastFlights = computed(() =>
props.flights.filter(f => {
const date = new Date(f.departure_date)
if (date > now) return false
if (selectedYears.value.length && !selectedYears.value.includes(date.getFullYear())) return false
if (selectedAirlines.value.length && !selectedAirlines.value.includes(f.airline?.id ?? -1)) return false
if (selectedCountries.value.length) {
const depCode = f.departure_airport.region?.country?.code
const arrCode = f.arrival_airport.region?.country?.code
if (!selectedCountries.value.includes(depCode ?? '') && !selectedCountries.value.includes(arrCode ?? '')) return false
}
return true
return date <= now && matchesFilters(f, date)
})
})
)
const upcomingFlights = computed(() => {
return props.flights.filter(f => {
const upcomingFlights = computed(() =>
props.flights.filter(f => {
const date = new Date(f.departure_date)
if (date <= now) return false
if (selectedYears.value.length && !selectedYears.value.includes(date.getFullYear())) return false
if (selectedAirlines.value.length && !selectedAirlines.value.includes(f.airline?.id ?? -1)) return false
if (selectedCountries.value.length) {
const depCode = f.departure_airport.region?.country?.code
const arrCode = f.arrival_airport.region?.country?.code
if (!selectedCountries.value.includes(depCode ?? '') && !selectedCountries.value.includes(arrCode ?? '')) return false
}
return true
return date > now && matchesFilters(f, date)
})
})
)
// ── Stats ─────────────────────────────────────────────────────────────────────
const mappedFlights = computed(() => [
...pastFlights.value,
...upcomingFlights.value,
])
</script>
<style scoped>
.profile-map__toolbar {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 12px;
}
.profile-map__toolbar .v-select {
flex: 1;
flex: 1 1 160px;
}
</style>
@@ -0,0 +1,18 @@
import { ref } from 'vue'
export function useChartTooltip<T>() {
const tooltipItem = ref<T | null>(null)
const tooltipX = ref(0)
const tooltipY = ref(0)
const onMouseMove = (e: MouseEvent) => {
tooltipX.value = e.clientX + 14
tooltipY.value = e.clientY + 14
}
const onMouseLeave = () => {
tooltipItem.value = null
}
return { tooltipItem, tooltipX, tooltipY, onMouseMove, onMouseLeave }
}
+1
View File
@@ -32,6 +32,7 @@ export interface Region {
continent_id: number
created_at: string | null
updated_at: string | null
continent: Continent
country: Country
}