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
@@ -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()
);
};