remove echarts, use canvas

This commit is contained in:
Vincent van der Wal
2026-07-19 15:25:04 +02:00
parent 6d81af8df5
commit e031716ce6
37 changed files with 1483 additions and 2510 deletions
@@ -2,13 +2,11 @@
import { fade } from 'svelte/transition';
import { formatZoned, getRelativeDayLabel } from '$lib/utils/date';
import { buildCurrentTimeSeries, buildDaylightSeries, getThemeColors } from '$lib/utils/echarts';
import { ChartContainer, ChartToolbar, EChart } from '$lib/components/charts';
import { echarts } from '$lib/components/charts/echarts';
import '$lib/components/charts/echarts.css';
import { ChartContainer, ChartToolbar } from '$lib/components/charts';
import { CanvasChart, type ChartSeries } from '$lib/charts';
import { getColor } from '../../utils/colors';
import {
type FetchedHourly,
type WeatherUnits,
@@ -18,8 +16,6 @@
getWindUnit
} from './types';
import type { ECharts } from 'echarts';
interface Props {
data: FetchedHourly;
selectedDay: Date;
@@ -31,15 +27,18 @@
let { data, selectedDay, units, loading, onResetZoom }: Props = $props();
const CHART_GROUP = 'week-meteogram';
const MS_PER_DAY = 24 * 3600 * 1000;
const SECONDS_PER_DAY = 24 * 3600;
let showCharts = $state(false);
let chartComponents: EChart[] = $state([]);
let chartInstances: ECharts[] = $state([]);
let chartOptions: Array<Record<string, unknown>> = $state([]);
let chartComponents: CanvasChart[] = $state([]);
// Timestamps from the service are in milliseconds; CanvasChart uses seconds.
let timestampsSec = $derived(data.timestamps.map((t) => t / 1000));
let liveCharts = $derived(chartComponents.filter((chart) => chart != null));
export function scrollToDay(day: Date): void {
if (chartInstances.length === 0 || !data) return;
if (!data || liveCharts.length === 0) return;
const tz = data.timezone;
const targetDayStr = formatZoned(day, tz, 'yyyy-MM-dd');
@@ -49,436 +48,150 @@
if (firstHourIdx === -1) return;
const dayStart = data.timestamps[firstHourIdx];
const dayEnd = dayStart + MS_PER_DAY;
const timestamps = data.timestamps;
const rangeStart = timestamps[0];
const rangeEnd = timestamps[timestamps.length - 1];
const totalRange = rangeEnd - rangeStart;
if (totalRange <= 0) return;
const startPct = Math.max(0, ((dayStart - rangeStart) / totalRange) * 100);
const endPct = Math.min(100, ((dayEnd - rangeStart) / totalRange) * 100);
for (const chart of chartInstances) {
if (chart && !chart.isDisposed()) {
chart.dispatchAction({ type: 'dataZoom', start: startPct, end: endPct });
}
}
const dayStart = data.timestamps[firstHourIdx] / 1000;
// Charts share the group, so setting the range on one syncs all of them
liveCharts[0].setRange(dayStart, dayStart + SECONDS_PER_DAY);
}
function resetZoom(): void {
for (const chart of chartInstances) {
if (chart && !chart.isDisposed()) {
chart.dispatchAction({ type: 'dataZoom', start: 0, end: 100 });
}
}
liveCharts[0]?.resetRange();
onResetZoom?.();
}
function handleChartReady(chart: ECharts): void {
chart.group = CHART_GROUP;
chartInstances = [...chartInstances, chart];
if (chartInstances.length === 3) {
echarts.connect(CHART_GROUP);
// Zoom to the selected day once all three charts are mounted
let scrolledOnMount = false;
$effect(() => {
if (!showCharts) {
scrolledOnMount = false;
return;
}
if (!scrolledOnMount && liveCharts.length === 3 && data) {
scrolledOnMount = true;
requestAnimationFrame(() => scrollToDay(selectedDay));
}
});
// ─── Series Building ────────────────────────────────────────────────────────
let tempUnit = $derived(getTempUnit(units));
let precipUnit = $derived(getPrecipUnit(units));
let windUnit = $derived(getWindUnit(units));
interface ChartDef {
title: string;
unit: string;
unitRight?: string;
yMin?: number;
yMinRight?: number;
yMaxRight?: number;
invertRight?: boolean;
showCredit?: boolean;
series: ChartSeries[];
}
$effect(() => {
if (!data) return;
let chartDefs = $derived.by((): ChartDef[] => {
if (!data) return [];
const { hourly, timestamps, markAreas } = data;
const colors = getThemeColors();
const tempUnit = getTempUnit(units);
const precipUnit = getPrecipUnit(units);
const windUnit = getWindUnit(units);
const { hourly } = data;
const temps = hourly.temperature_2m;
const precip = hourly.precipitation;
const precipProb = hourly.precipitation_probability;
const cloudCov = hourly.cloud_cover;
const windSpeed = hourly.windspeed_10m;
const humidity = hourly.relative_humidity_2m;
const validTemps = temps.filter((t: number) => t !== null && !isNaN(t));
const minTemp = Math.min(...validTemps);
const maxTemp = Math.max(...validTemps);
const tempData = temps.map((v: number, i: number) => [timestamps[i], v]);
const cloudData = cloudCov.map((v: number, i: number) => [timestamps[i], v]);
const precipData = precip.map((v: number, i: number) => [timestamps[i], v]);
const precipProbData = precipProb.map((v: number, i: number) => [timestamps[i], v]);
const windData = windSpeed.map((v: number, i: number) => [timestamps[i], v]);
const humidityData = humidity.map((v: number, i: number) => [timestamps[i], v]);
const annotations = (): Array<Record<string, unknown>> => {
const series: Array<Record<string, unknown>> = [];
series.push(buildCurrentTimeSeries());
const dl = buildDaylightSeries({ markAreas });
if (dl) series.push(dl);
return series;
};
const timeXAxis = (showLabel: boolean): Record<string, unknown> => ({
type: 'time',
splitLine: { show: false },
axisLine: { lineStyle: { color: colors.axisLine } },
axisLabel: {
color: colors.text,
hideOverlap: true,
show: showLabel,
formatter: (value: number) => formatZoned(new Date(value), data.timezone, 'HH:mm')
},
axisTick: { lineStyle: { color: colors.axisLine } }
});
const insideZoom = (): Record<string, unknown> => ({
type: 'inside',
xAxisIndex: 0,
filterMode: 'none',
zoomOnMouseWheel: true,
moveOnMouseMove: true,
moveOnMouseWheel: false
});
const sliderZoom = (): Record<string, unknown> => ({
type: 'slider',
xAxisIndex: 0,
filterMode: 'none',
height: 20,
bottom: 4,
borderColor: colors.axisLine,
fillerColor: 'rgba(100, 140, 200, 0.2)',
handleStyle: { color: colors.text },
textStyle: { color: colors.text, fontSize: 10 },
dataBackground: {
lineStyle: { color: colors.axisLine },
areaStyle: { color: colors.splitLine }
},
selectedDataBackground: {
lineStyle: { color: colors.axisLine },
areaStyle: { color: 'rgba(100, 140, 200, 0.15)' }
}
});
const tooltipBase = (
formatter: (
params: Array<{
axisValue: number;
seriesName: string;
marker: string;
value: number | number[] | null;
}>
) => string
): Record<string, unknown> => ({
trigger: 'axis',
axisPointer: {
type: 'cross',
animation: false,
label: {
backgroundColor: colors.tooltipBg,
color: colors.text,
borderColor: colors.tooltipBorder,
borderWidth: 1,
formatter: (params: { axisDimension: string; value: number }) => {
if (params.axisDimension === 'x') {
return formatZoned(new Date(params.value), data.timezone, 'EEE d MMM HH:mm');
}
return params.value.toFixed(1);
}
}
},
backgroundColor: colors.tooltipBg,
borderColor: colors.tooltipBorder,
textStyle: { color: colors.text },
formatter
});
const formatDate = (ts: number): string => {
const date = new Date(ts);
const dateStr = formatZoned(date, data.timezone, 'EEE d MMM HH:mm');
return `<b>${dateStr}</b><br/>`;
};
const isAnnotation = (name: string): boolean => name === 'Daylight' || name === 'Current Time';
const tempOption: Record<string, unknown> = {
title: {
text: 'Temperature & Cloud Cover',
left: 'left',
textStyle: { fontWeight: 'normal', fontSize: 16, color: colors.text }
},
tooltip: tooltipBase((params) => {
if (!params?.length) return '';
let html = formatDate(params[0].axisValue as number);
for (const item of params) {
const name = item.seriesName as string;
if (isAnnotation(name)) continue;
const val = (item.value as [number, number])?.[1];
if (val == null) continue;
if (name === 'Temperature')
html += `${item.marker} ${name}: <b>${val.toFixed(1)} ${tempUnit}</b><br/>`;
else if (name === 'Cloud Cover')
html += `${item.marker} ${name}: <b>${val.toFixed(0)}%</b><br/>`;
}
return html;
}),
legend: {
show: true,
bottom: 0,
textStyle: { color: colors.text },
data: ['Temperature', 'Cloud Cover']
},
grid: { left: 60, right: 60, top: 50, bottom: 40 },
dataZoom: [insideZoom()],
xAxis: timeXAxis(false),
yAxis: [
{
type: 'value',
name: tempUnit,
nameTextStyle: { color: colors.text },
axisLine: { show: false },
axisLabel: { color: colors.text },
splitLine: { lineStyle: { color: colors.splitLine } }
},
{ type: 'value', min: 0, max: 250, inverse: true, show: false }
],
const tempChart: ChartDef = {
title: 'Temperature & Cloud Cover',
unit: tempUnit,
// Hidden inverted right axis (0-250) so cloud cover hangs from the top,
// occupying at most the upper 40% of the plot
yMinRight: 0,
yMaxRight: 250,
invertRight: true,
series: [
{
name: 'Temperature',
type: 'line',
data: tempData,
smooth: true,
showSymbol: false,
lineStyle: { width: 3, color: '#ef6c00' },
itemStyle: { color: '#ef6c00' },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: getColor(maxTemp, String(units.temperature_unit)) + '88'
},
{
offset: 0.5,
color: getColor((maxTemp + minTemp) / 2, String(units.temperature_unit)) + '44'
},
{
offset: 1,
color: getColor(minTemp, String(units.temperature_unit)) + '08'
}
])
},
z: 5
},
{
name: 'Cloud Cover',
type: 'line',
data: cloudData,
smooth: true,
showSymbol: false,
yAxisIndex: 1,
lineStyle: { width: 0 },
itemStyle: { color: colors.text },
areaStyle: { color: 'rgba(150, 150, 150, 0.25)', origin: 'start' },
z: 1,
silent: true
color: 'rgb(150, 150, 150)',
data: hourly.cloud_cover,
width: 0,
fill: true,
fillOpacity: 0.25,
axis: 'right',
format: (v) => `${v.toFixed(0)}%`
},
...annotations()
],
textStyle: { color: colors.text }
{
name: 'Temperature',
type: 'line',
color: '#ef6c00',
data: hourly.temperature_2m,
width: 3,
fill: true,
fillOpacity: 0.2,
format: (v) => `${v.toFixed(1)} ${tempUnit}`
}
]
};
const precipOption: Record<string, unknown> = {
title: {
text: 'Precipitation & Probability',
left: 'left',
textStyle: { fontWeight: 'normal', fontSize: 16, color: colors.text }
},
tooltip: tooltipBase((params) => {
if (!params?.length) return '';
let html = formatDate(params[0].axisValue as number);
for (const item of params) {
const name = item.seriesName as string;
if (isAnnotation(name)) continue;
const val = (item.value as [number, number])?.[1];
if (val == null) continue;
if (name === 'Precipitation')
html += `${item.marker} ${name}: <b>${val.toFixed(1)} ${precipUnit}</b><br/>`;
else if (name === 'Precip. Probability')
html += `${item.marker} ${name}: <b>${val.toFixed(0)}%</b><br/>`;
}
return html;
}),
legend: {
show: true,
bottom: 0,
textStyle: { color: colors.text },
data: ['Precipitation', 'Precip. Probability']
},
grid: { left: 60, right: 60, top: 50, bottom: 40 },
dataZoom: [insideZoom()],
xAxis: timeXAxis(false),
yAxis: [
{
type: 'value',
name: precipUnit,
min: 0,
nameTextStyle: { color: colors.text },
axisLine: { show: false },
axisLabel: { color: colors.text },
splitLine: { lineStyle: { color: colors.splitLine } }
},
{
type: 'value',
name: '%',
min: 0,
max: 100,
nameTextStyle: { color: colors.text },
axisLine: { show: false },
axisLabel: { color: colors.text },
splitLine: { show: false }
}
],
const precipChart: ChartDef = {
title: 'Precipitation & Probability',
unit: precipUnit,
unitRight: '%',
yMin: 0,
yMinRight: 0,
yMaxRight: 100,
series: [
{
name: 'Precipitation',
type: 'bar',
data: precipData,
barMaxWidth: 8,
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(30, 136, 229, 0.9)' },
{ offset: 1, color: 'rgba(30, 136, 229, 0.4)' }
])
},
yAxisIndex: 0,
z: 5
color: 'rgba(30, 136, 229, 0.8)',
data: hourly.precipitation,
format: (v) => `${v.toFixed(1)} ${precipUnit}`
},
{
name: 'Precip. Probability',
type: 'line',
data: precipProbData,
smooth: true,
showSymbol: false,
lineStyle: { width: 2, type: 'dashed', color: '#5c6bc0' },
itemStyle: { color: '#5c6bc0' },
yAxisIndex: 1,
z: 4
},
...annotations()
],
textStyle: { color: colors.text }
color: '#5c6bc0',
data: hourly.precipitation_probability,
width: 2,
dashed: true,
axis: 'right',
format: (v) => `${v.toFixed(0)}%`
}
]
};
const windOption: Record<string, unknown> = {
title: {
text: 'Wind Speed & Humidity',
left: 'left',
textStyle: { fontWeight: 'normal', fontSize: 16, color: colors.text }
},
tooltip: tooltipBase((params) => {
if (!params?.length) return '';
let html = formatDate(params[0].axisValue as number);
for (const item of params) {
const name = item.seriesName as string;
if (isAnnotation(name)) continue;
const val = (item.value as [number, number])?.[1];
if (val == null) continue;
if (name === 'Wind Speed') {
const idx = timestamps.indexOf(
(params[0] as Record<string, unknown>).axisValue as number
);
const windDir = idx >= 0 ? hourly.winddirection_10m[idx] : null;
html += `${item.marker} ${name}: <b>${val.toFixed(0)} ${windUnit}</b>`;
if (windDir != null && !isNaN(windDir)) html += ` (${getWindDirectionLabel(windDir)})`;
html += '<br/>';
} else if (name === 'Humidity') {
html += `${item.marker} ${name}: <b>${val.toFixed(0)}%</b><br/>`;
}
}
return html;
}),
legend: {
show: true,
bottom: 28,
textStyle: { color: colors.text },
data: ['Wind Speed', 'Humidity']
},
grid: { left: 60, right: 60, top: 50, bottom: 60 },
dataZoom: [insideZoom(), sliderZoom()],
xAxis: timeXAxis(true),
yAxis: [
{
type: 'value',
name: windUnit,
min: 0,
nameTextStyle: { color: colors.text },
axisLine: { show: false },
axisLabel: { color: colors.text },
splitLine: { lineStyle: { color: colors.splitLine } }
},
{
type: 'value',
name: '%',
min: 0,
max: 100,
nameTextStyle: { color: colors.text },
axisLine: { show: false },
axisLabel: { color: colors.text },
splitLine: { show: false }
}
],
const windChart: ChartDef = {
title: 'Wind Speed & Humidity',
unit: windUnit,
unitRight: '%',
yMin: 0,
yMinRight: 0,
yMaxRight: 100,
showCredit: true,
series: [
{
name: 'Wind Speed',
type: 'line',
data: windData,
smooth: true,
showSymbol: false,
lineStyle: { width: 2, color: '#26a69a' },
itemStyle: { color: '#26a69a' },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(38, 166, 154, 0.25)' },
{ offset: 1, color: 'rgba(38, 166, 154, 0.02)' }
])
},
yAxisIndex: 0,
z: 5
color: '#26a69a',
data: hourly.windspeed_10m,
width: 2,
fill: true,
fillOpacity: 0.15,
format: (v, i) => {
const dir = hourly.winddirection_10m[i];
const dirLabel = dir != null && !isNaN(dir) ? ` (${getWindDirectionLabel(dir)})` : '';
return `${v.toFixed(0)} ${windUnit}${dirLabel}`;
}
},
{
name: 'Humidity',
type: 'line',
data: humidityData,
smooth: true,
showSymbol: false,
lineStyle: { width: 2, type: 'dotted', color: '#8d6e63' },
itemStyle: { color: '#8d6e63' },
yAxisIndex: 1,
z: 4
},
...annotations()
],
graphic: [
{
type: 'text',
right: 10,
bottom: 30,
style: {
text: 'Open-Meteo.com',
fontSize: 10,
fill: colors.text,
opacity: 0.4
},
cursor: 'pointer'
color: '#8d6e63',
data: hourly.relative_humidity_2m,
width: 2,
dashed: true,
axis: 'right',
format: (v) => `${v.toFixed(0)}%`
}
],
textStyle: { color: colors.text }
]
};
chartOptions = [tempOption, precipOption, windOption];
return [tempChart, precipChart, windChart];
});
</script>
@@ -520,19 +233,30 @@
</div>
<ChartContainer {loading} chartCount={3} chartHeight={300}>
{#each chartOptions as option, i (i)}
<EChart
{option}
notMerge
height={i === 2 ? '320px' : '300px'}
onChartReady={handleChartReady}
{#each chartDefs as def, i (def.title)}
<CanvasChart
bind:this={chartComponents[i]}
timestamps={timestampsSec}
timezone={data.timezone}
series={def.series}
bands={data.daylightBands}
unit={def.unit}
unitRight={def.unitRight}
yMin={def.yMin}
yMinRight={def.yMinRight}
yMaxRight={def.yMaxRight}
invertRight={def.invertRight}
title={def.title}
showCredit={def.showCredit}
showLegend
height={300}
group={CHART_GROUP}
/>
{/each}
</ChartContainer>
<div class="mt-6 md:mt-10">
<ChartToolbar charts={chartInstances} fileName="week-forecast" />
<ChartToolbar charts={liveCharts} fileName="week-forecast" />
</div>
</div>
{/if}