feat: local time (#7)

Co-authored-by: terraputix <terraputix@mailbox.org>
Reviewed-on: useweb/ombrella#7
This commit is contained in:
2026-02-16 11:41:34 +01:00
co-authored by terraputix
parent 9a7e66d5d9
commit 84eefd538b
16 changed files with 948 additions and 701 deletions
@@ -55,7 +55,7 @@
interface FetchedData {
ensembleResult: EnsembleForecastResult;
timestamps: number[];
utc_offset_seconds: number;
timezone: string;
markAreas: MarkArea[];
}
@@ -102,15 +102,17 @@
forecast_days: 14,
temperature_unit: params.temperature_unit as 'celsius' | 'fahrenheit',
wind_speed_unit: params.wind_speed_unit as 'kmh' | 'ms' | 'mph' | 'kn',
precipitation_unit: params.precipitation_unit as 'mm' | 'inch'
precipitation_unit: params.precipitation_unit as 'mm' | 'inch',
timezone: loc.timezone
});
fetchedData = {
ensembleResult: result,
timestamps: result.timestamps,
utc_offset_seconds: result.utcOffsetSeconds,
timezone: result.timezone,
markAreas: result.markAreas
};
console.log(fetchedData.timezone);
loading = false;
};
@@ -123,7 +125,7 @@
$effect(() => {
if (!fetchedData) return;
const { ensembleResult, timestamps, utc_offset_seconds, markAreas } = fetchedData;
const { ensembleResult, timestamps, timezone, markAreas } = fetchedData;
const _showLegend = showLegend;
const colors = getThemeColors();
@@ -150,7 +152,7 @@
const averageData = average.map((val, idx) => [timestamps[idx], val] as [number, number]);
series.push(buildAverageSeries({ variable, data: averageData, unit }));
series.push(buildCurrentTimeSeries({ utcOffsetSeconds: utc_offset_seconds }));
series.push(buildCurrentTimeSeries());
const daylightSeries = buildDaylightSeries({ markAreas });
if (daylightSeries) {
@@ -167,7 +169,7 @@
subtext: `Compare ${params.hourly?.join(', ') || ''} in models: ${params.models?.join(', ') || ''}`
}
: null,
tooltip: { unit },
tooltip: { unit, timezone },
legend: {
show: _showLegend,
data: [variable + '_average']
@@ -181,7 +183,8 @@
series,
toolbox: false,
showCredit: isLast,
colors
colors,
timezone
});
newOptions.push(option);
@@ -53,13 +53,21 @@
let params = $state({
...defaultParameters,
hourly: ['temperature_2m', 'rain', 'relative_humidity_2m'],
hourly: [
'temperature_2m',
'rain',
'relative_humidity_2m',
'wind_speed_10m',
'wind_direction_10m'
],
models: [
'ecmwf_ifs',
'ecmwf_ifs025',
'meteofrance_seamless',
'ukmo_seamless',
'icon_seamless',
'gem_seamless'
'gem_seamless',
'gfs_seamless'
]
});
@@ -68,7 +76,7 @@
interface FetchedData {
hourly: Record<string, unknown>;
hourly_units: Record<string, string>;
utc_offset_seconds: number;
timezone: string;
markAreas: MarkArea[];
timestamps: number[];
}
@@ -115,13 +123,14 @@
models: modelList,
temperature_unit: params.temperature_unit as 'celsius' | 'fahrenheit',
wind_speed_unit: params.wind_speed_unit as 'kmh' | 'ms' | 'mph' | 'kn',
precipitation_unit: params.precipitation_unit as 'mm' | 'inch'
precipitation_unit: params.precipitation_unit as 'mm' | 'inch',
timezone: loc.timezone
});
fetchedData = {
hourly: result.hourlyFlat,
hourly_units: result.hourlyUnitsFlat,
utc_offset_seconds: result.utcOffsetSeconds,
timezone: result.timezone,
markAreas: result.markAreas,
timestamps: result.timestamps
};
@@ -137,13 +146,7 @@
$effect(() => {
if (!fetchedData) return;
const {
hourly: hourlyData,
hourly_units,
utc_offset_seconds,
markAreas,
timestamps
} = fetchedData;
const { hourly: hourlyData, hourly_units, timezone, markAreas, timestamps } = fetchedData;
const _showLegend = showLegend;
const colors = getThemeColors();
@@ -178,7 +181,7 @@
const averageData = average.map((val, idx) => [timestamps[idx], val] as [number, number]);
series.push(buildAverageSeries({ variable, data: averageData, unit }));
series.push(buildCurrentTimeSeries({ utcOffsetSeconds: utc_offset_seconds }));
series.push(buildCurrentTimeSeries());
const daylightSeries = buildDaylightSeries({ markAreas });
if (daylightSeries) {
@@ -195,7 +198,7 @@
subtext: `Compare ${params.hourly?.join(', ') || ''} in models: ${params.models?.join(', ') || ''}`
}
: null,
tooltip: { unit },
tooltip: { unit, timezone },
legend: { show: _showLegend },
grid: {
hasTitle: isFirst,
@@ -206,7 +209,8 @@
series,
toolbox: false,
showCredit: isLast,
colors
colors,
timezone
});
newOptions.push(option);
+44 -8
View File
@@ -7,16 +7,52 @@ export const defaultParameters = {
export const models = [
{ value: 'best_match', label: 'Best match' },
{ value: 'gfs_seamless', label: 'NCEP GFS Seamless' },
{ value: 'jma_seamless', label: 'JMA Seamless' },
{ value: 'ecmwf_ifs', label: 'ECMWF IFS' },
{ value: 'ecmwf_ifs025', label: 'ECMWF IFS 0.25' },
{ value: 'ecmwf_aifs025_single', label: 'ECMWF AIFS 0.25 Single' },
{ value: 'cma_grapes_global', label: 'CMA GRAPES Global' },
{ value: 'bom_access_global', label: 'BOM ACCESS Global' },
{ value: 'kma_seamless', label: 'KMA Seamless' },
{ value: 'icon_seamless', label: 'DWD ICON Seamless' },
{ value: 'kma_ldps', label: 'KMA LDPS' },
{ value: 'kma_gdps', label: 'KMA GDPS' },
{ value: 'meteofrance_seamless', label: 'Meteo-France Seamless' },
{ value: 'meteofrance_arpege_world', label: 'Meteo-France ARPEGE World' },
{ value: 'meteofrance_arpege_europe', label: 'Meteo-France ARPEGE Europe' },
{ value: 'meteofrance_arome_france', label: 'Meteo-France AROME France' },
{ value: 'meteofrance_arome_france_hd', label: 'Meteo-France AROME France HD' },
{ value: 'knmi_seamless', label: 'KNMI Seamless' },
{ value: 'knmi_harmonie_arome_europe', label: 'KNMI Harmonie Arome Europe' },
{ value: 'knmi_harmonie_arome_netherlands', label: 'KNMI Harmonie Arome Netherlands' },
{ value: 'dmi_seamless', label: 'DMI Seamless' },
{ value: 'dmi_harmonie_arome_europe', label: 'DMI Harmonie Arome Europe' },
{ value: 'ukmo_seamless', label: 'UKMO Seamless' },
{ value: 'ukmo_global_deterministic_10km', label: 'UKMO Global Deterministic 10km' },
{ value: 'ukmo_uk_deterministic_2km', label: 'UKMO UK Deterministic 2km' },
{ value: 'meteoswiss_icon_seamless', label: 'MeteoSwiss ICON Seamless' },
{ value: 'meteoswiss_icon_ch2', label: 'MeteoSwiss ICON CH2' },
{ value: 'meteoswiss_icon_ch1', label: 'MeteoSwiss ICON CH1' },
{ value: 'metno_nordic', label: 'MET Norway Nordic' },
{ value: 'metno_seamless', label: 'MET Norway Seamless' },
{ value: 'gem_hrdps_west', label: 'GEM HRDPS West' },
{ value: 'gem_regional', label: 'GEM Regional' },
{ value: 'gem_global', label: 'GEM Global' },
{ value: 'gem_seamless', label: 'GEM Seamless' },
{ value: 'meteofrance_seamless', label: 'Météo-France Seamless' },
{ value: 'metno_seamless', label: 'MET Norway Seamless (with ECMWF)' },
{ value: 'knmi_seamless', label: 'KNMI Seamless (with ECMWF)' },
{ value: 'dmi_seamless', label: 'DMI Seamless (with ECMWF)' },
{ value: 'ukmo_seamless', label: 'UK Met Office Seamless' }
{ value: 'jma_seamless', label: 'JMA Seamless' },
{ value: 'jma_msm', label: 'JMA MSM' },
{ value: 'jma_gsm', label: 'JMA GSM' },
{ value: 'gfs_seamless', label: 'GFS Seamless' },
{ value: 'gfs_global', label: 'GFS Global' },
{ value: 'gfs_hrrr', label: 'GFS HRRR' },
{ value: 'gfs_graphcast025', label: 'GFS Graphcast 0.25' },
{ value: 'ncep_nbm_conus', label: 'NCEP NBM CONUS' },
{ value: 'ncep_nam_conus', label: 'NCEP NAM CONUS' },
{ value: 'ncep_aigfs025', label: 'NCEP AIGFS 0.25' },
{ value: 'ncep_hgefs025_ensemble_mean', label: 'NCEP HG-EFS 0.25 Ensemble Mean' },
{ value: 'icon_seamless', label: 'ICON Seamless (DWD)' },
{ value: 'icon_global', label: 'ICON Global' },
{ value: 'icon_eu', label: 'ICON EU' },
{ value: 'icon_d2', label: 'ICON-D2' },
{ value: 'italia_meteo_arpae_icon_2i', label: 'Italia Meteo ARPAE ICON 2i' }
];
export const hourly = [
@@ -63,12 +63,14 @@
wind_speed_unit: params.wind_speed_unit as 'kmh' | 'ms' | 'mph' | 'kn',
precipitation_unit: params.precipitation_unit as 'mm' | 'inch',
forecast_days: 7,
past_days: 0
past_days: 0,
timezone: loc.timezone
});
fetchedHourly = {
hourly: result.hourly,
utc_offset_seconds: result.utcOffsetSeconds,
timezone: result.timezone,
timestamps: result.hourlyTimestamps,
hourlyDates: result.hourlyDates,
markAreas: result.markAreas
@@ -76,6 +78,7 @@
fetchedDaily = {
daily: result.daily,
timezone: result.timezone,
dailyDates: result.dailyDates
};
@@ -1,9 +1,11 @@
<script lang="ts">
import { fade } from 'svelte/transition';
import { formatZoned, getRelativeDayLabel, isSameDayInZone } from '$lib/utils/date';
import { getTempStyle } from '../../utils/colors';
import weatherCodes from '../../utils/weather-codes';
import { type FetchedDaily, type WeatherUnits, getDayLabel, getWindArrowRotation } from './types';
import { type FetchedDaily, type WeatherUnits, getWindArrowRotation } from './types';
interface Props {
daily: FetchedDaily | null;
@@ -14,8 +16,6 @@
let { daily, selectedDay, units, onSelectDay }: Props = $props();
const today = new Date();
function getDaylightSeconds(index: number): number {
if (!daily) return 0;
const sunriseTs = daily.daily.sunrise[index];
@@ -43,7 +43,7 @@
<div class="flex gap-1 overflow-x-auto pb-1" style="scrollbar-width: thin">
{#if daily}
{#each daily.dailyDates as time, index (index)}
{@const selected = time.getDate() === selectedDay.getDate()}
{@const selected = isSameDayInZone(time, selectedDay, daily.timezone)}
{@const tempMax = daily.daily.temperature_2m_max[index]}
{@const tempMin = daily.daily.temperature_2m_min[index]}
{@const wCode = daily.daily.weather_code[index]}
@@ -68,10 +68,10 @@
>
<!-- Day label -->
<span class="text-sm font-bold tracking-wide">
{time.toLocaleDateString('en-GB', { weekday: 'short' }).toUpperCase()}
{formatZoned(time, daily.timezone, 'EEE').toUpperCase()}
</span>
<span class="text-[11px] text-muted-foreground">
{getDayLabel(time, today)}
{getRelativeDayLabel(time, daily.timezone)}
</span>
<!-- Weather icon -->
@@ -1,5 +1,5 @@
<script lang="ts">
import { pad } from '$lib/utils/index';
import { formatUtcOffset, formatZoned, getZonedHour, isSameDayInZone } from '$lib/utils/date';
import { getTempStyle } from '../../utils/colors';
import weatherCodes from '../../utils/weather-codes';
@@ -10,8 +10,7 @@
getPrecipUnit,
getTempUnit,
getWindArrowRotation,
getWindUnit,
isCurrentHour
getWindUnit
} from './types';
interface Props {
@@ -54,36 +53,31 @@
}
function timeToFraction(date: Date): number {
const totalMinutes = date.getHours() * 60 + date.getMinutes();
const firstMin = cellData[0].date.getHours() * 60;
const tz = data.timezone;
const hour = getZonedHour(date, tz);
const minutes = parseInt(formatZoned(date, tz, 'mm'), 10);
const totalMinutes = hour * 60 + minutes;
const firstHour = getZonedHour(cellData[0].date, tz);
const firstMin = firstHour * 60;
const step = is3h ? 3 : 1;
const lastMin = cellData[cellData.length - 1].date.getHours() * 60 + step * 60;
const lastHour = getZonedHour(cellData[cellData.length - 1].date, tz);
const lastMin = lastHour * 60 + step * 60;
const range = lastMin - firstMin;
if (range <= 0) return 0;
return Math.max(0, Math.min(1, (totalMinutes - firstMin) / range));
}
function formatTime(date: Date): string {
return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
return formatZoned(date, data.timezone, 'HH:mm');
}
function formatTimezone(offsetSeconds: number): string {
const sign = offsetSeconds >= 0 ? '+' : '-';
const abs = Math.abs(offsetSeconds);
const hours = Math.floor(abs / 3600);
const minutes = Math.floor((abs % 3600) / 60);
return minutes === 0 ? `UTC${sign}${hours}` : `UTC${sign}${hours}:${pad(minutes)}`;
}
let timezoneLabel = $derived(formatTimezone(data.utc_offset_seconds));
let timezoneLabel = $derived(formatUtcOffset(data.utc_offset_seconds));
function findDailyIndex(date: Date): number {
return daily.dailyDates.findIndex(
(dd) =>
dd.getDate() === date.getDate() &&
dd.getMonth() === date.getMonth() &&
dd.getFullYear() === date.getFullYear()
);
return daily.dailyDates.findIndex((dd) => isSameDayInZone(dd, date, data.timezone));
}
function isDaytime(hourDate: Date): boolean {
@@ -97,13 +91,9 @@
}
function getDayIndices(dates: Date[], day: Date): number[] {
const tz = data.timezone;
return dates.reduce<number[]>((acc, d, i) => {
if (
d.getDate() === day.getDate() &&
d.getMonth() === day.getMonth() &&
d.getFullYear() === day.getFullYear() &&
(hourlyInterval === 1 || d.getHours() % 3 === 0)
) {
if (isSameDayInZone(d, day, tz) && (hourlyInterval === 1 || getZonedHour(d, tz) % 3 === 0)) {
acc.push(i);
}
return acc;
@@ -148,12 +138,19 @@
let daytimeFlags = $derived(dayIdx.map((idx) => isDaytime(data.hourlyDates[idx])));
let cellData = $derived(
dayIdx.map((idx, i) => ({
idx,
date: data.hourlyDates[idx],
isNow: isCurrentHour(data.hourlyDates[idx], today),
isDaytime: daytimeFlags[i]
}))
dayIdx.map((idx, i) => {
const date = data.hourlyDates[idx];
const tz = data.timezone;
const isNow =
formatZoned(date, tz, 'yyyy-MM-dd HH') === formatZoned(today, tz, 'yyyy-MM-dd HH');
return {
idx,
date,
isNow,
isDaytime: daytimeFlags[i]
};
})
);
let sunrisePercent = $derived(
@@ -195,7 +192,7 @@
<!-- Header -->
<div class="mb-2 flex flex-wrap items-center justify-between gap-2">
<h3 class="text-lg font-bold">
{selectedDay.toLocaleDateString('en-GB', { weekday: 'long' })} Hourly
{formatZoned(selectedDay, data.timezone, 'EEEE')} Hourly
<span class="ml-1 text-xs font-normal text-muted-foreground">({timezoneLabel})</span>
</h3>
<div class="flex items-center gap-1.5 text-[13px] font-semibold">
@@ -293,10 +290,12 @@
style="left:{leftPct}%;width:{widthPct}%"
>
{#if is3h}
{pad(cell.date.getHours())}
{formatZoned(cell.date, data.timezone, 'HH')}
{:else}
<span class="inline-flex items-baseline gap-1">
<span class="text-[11px] font-semibold">{pad(cell.date.getHours())}</span>
<span class="text-[11px] font-semibold"
>{formatZoned(cell.date, data.timezone, 'HH')}</span
>
<sup
class="text-[9px] font-semibold text-muted-foreground leading-none align-baseline"
>00</sup
@@ -3,8 +3,8 @@
import * as echarts from 'echarts';
import { formatZoned, getRelativeDayLabel } from '$lib/utils/date';
import { buildCurrentTimeSeries, buildDaylightSeries, getThemeColors } from '$lib/utils/echarts';
import { pad } from '$lib/utils/index';
import { ChartContainer, ChartToolbar, EChart } from '$lib/components/charts';
import '$lib/components/charts/echarts.css';
@@ -13,7 +13,6 @@
import {
type FetchedHourly,
type WeatherUnits,
getDayLabel,
getPrecipUnit,
getTempUnit,
getWindDirectionLabel,
@@ -32,7 +31,6 @@
const CHART_GROUP = 'week-meteogram';
const MS_PER_DAY = 24 * 3600 * 1000;
const today = new Date();
let showCharts = $state(false);
let chartComponents: EChart[] = $state([]);
@@ -40,9 +38,17 @@
let chartOptions: Array<Record<string, unknown>> = $state([]);
export function scrollToDay(day: Date): void {
if (chartInstances.length === 0) return;
if (chartInstances.length === 0 || !data) return;
const dayStart = new Date(day.getFullYear(), day.getMonth(), day.getDate()).getTime();
const tz = data.timezone;
const targetDayStr = formatZoned(day, tz, 'yyyy-MM-dd');
const firstHourIdx = data.hourlyDates.findIndex(
(d) => formatZoned(d, tz, 'yyyy-MM-dd') === targetDayStr
);
if (firstHourIdx === -1) return;
const dayStart = data.timestamps[firstHourIdx];
const dayEnd = dayStart + MS_PER_DAY;
const timestamps = data.timestamps;
const rangeStart = timestamps[0];
@@ -90,7 +96,7 @@
$effect(() => {
if (!data) return;
const { hourly, utc_offset_seconds, timestamps, markAreas } = data;
const { hourly, timestamps, markAreas } = data;
const colors = getThemeColors();
const tempUnit = getTempUnit(units);
const precipUnit = getPrecipUnit(units);
@@ -116,7 +122,7 @@
const annotations = (): Array<Record<string, unknown>> => {
const series: Array<Record<string, unknown>> = [];
series.push(buildCurrentTimeSeries({ utcOffsetSeconds: utc_offset_seconds }));
series.push(buildCurrentTimeSeries());
const dl = buildDaylightSeries({ markAreas });
if (dl) series.push(dl);
return series;
@@ -126,7 +132,12 @@
type: 'time',
splitLine: { show: false },
axisLine: { lineStyle: { color: colors.axisLine } },
axisLabel: { color: colors.text, hideOverlap: true, show: showLabel },
axisLabel: {
color: colors.text,
hideOverlap: true,
show: showLabel,
formatter: (value: number) => formatZoned(new Date(value), data.timezone, 'HH:mm')
},
axisTick: { lineStyle: { color: colors.axisLine } }
});
@@ -160,7 +171,14 @@
});
const tooltipBase = (
formatter: (params: Record<string, unknown>[]) => string
formatter: (
params: Array<{
axisValue: number;
seriesName: string;
marker: string;
value: number | number[] | null;
}>
) => string
): Record<string, unknown> => ({
trigger: 'axis',
axisPointer: {
@@ -170,7 +188,13 @@
backgroundColor: colors.tooltipBg,
color: colors.text,
borderColor: colors.tooltipBorder,
borderWidth: 1
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,
@@ -181,7 +205,8 @@
const formatDate = (ts: number): string => {
const date = new Date(ts);
return `<b>${date.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' })} ${pad(date.getHours())}:${pad(date.getMinutes())}</b><br/>`;
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';
@@ -488,11 +513,11 @@
<div class="detailed-charts" in:fade={{ duration: 200 }}>
<div class="charts-header">
<h3 class="charts-title">
{selectedDay.toLocaleDateString('en-GB', { weekday: 'long' })}
{formatZoned(selectedDay, data.timezone, 'EEEE')}
<small>
{getDayLabel(selectedDay, today) !==
selectedDay.toLocaleDateString('en-GB', { weekday: 'long' })
? ` (${getDayLabel(selectedDay, today)})`
{getRelativeDayLabel(selectedDay, data.timezone) !==
formatZoned(selectedDay, data.timezone, 'EEEE')
? ` (${getRelativeDayLabel(selectedDay, data.timezone)})`
: ''}
</small>
</h3>
@@ -1,5 +1,5 @@
<script lang="ts">
import { pad } from '$lib/utils/index';
import { formatZoned } from '$lib/utils/date';
import type { FetchedDaily } from './types';
@@ -23,19 +23,19 @@
});
</script>
{#if sunrise && sunset}
{#if daily && sunrise && sunset}
<div class="sun-info">
<div class="sun-item">
<svg class="fill-foreground" width="24px" height="24px">
<use class="stroke-2" xlink:href="/images/weather-icons/wi-sunrise.svg#Layer_1"></use>
</svg>
<span>{pad(sunrise.getHours())}:{pad(sunrise.getMinutes())}</span>
<span>{formatZoned(sunrise, daily.timezone, 'HH:mm')}</span>
</div>
<div class="sun-item">
<svg class="fill-foreground" width="24px" height="24px">
<use class="stroke-2" xlink:href="/images/weather-icons/wi-sunset.svg#Layer_1"></use>
</svg>
<span>{pad(sunset.getHours())}:{pad(sunset.getMinutes())}</span>
<span>{formatZoned(sunset, daily.timezone, 'HH:mm')}</span>
</div>
</div>
{/if}
+2 -22
View File
@@ -9,6 +9,7 @@ export interface WeatherUnits {
export interface FetchedHourly {
hourly: WeekHourlyData;
utc_offset_seconds: number;
timezone: string;
timestamps: number[];
hourlyDates: Date[];
markAreas: MarkArea[];
@@ -16,6 +17,7 @@ export interface FetchedHourly {
export interface FetchedDaily {
daily: WeekDailyData;
timezone: string;
dailyDates: Date[];
}
@@ -56,25 +58,3 @@ export const getWindDirectionLabel = (deg: number): string => {
];
return dirs[Math.round(deg / 22.5) % 16];
};
export const getDayLabel = (date: Date, today: Date): string => {
const MS_PER_DAY = 24 * 3600 * 1000;
const diff = Math.round(
(new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() -
new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime()) /
MS_PER_DAY
);
if (diff === 0) return 'Today';
if (diff === 1) return 'Tomorrow';
if (diff === -1) return 'Yesterday';
return `${date.getMonth() + 1}-${date.getDate()}`;
};
export const isCurrentHour = (date: Date, now: Date): boolean => {
return (
date.getDate() === now.getDate() &&
date.getMonth() === now.getMonth() &&
date.getFullYear() === now.getFullYear() &&
date.getHours() === now.getHours()
);
};