feat: expand utility widgets (#6638)

This commit is contained in:
Thomas authored and GitHub committed 2026-08-20 16:26:04 +02:00
1 parent 53b518960c
commit 58a24569ce
86 files changed
+7660 -751

No files matched your search

+440
View File
@@ -0,0 +1,440 @@
import type { ReactNode } from "react";
import { useId } from "react";
import { CompositeChart } from "@mantine/charts";
import {
Box,
Group,
Paper,
Popover,
ScrollArea,
SimpleGrid,
Stack,
Text,
UnstyledButton,
VisuallyHidden,
} from "@mantine/core";
import { IconDroplets, IconMapPin, IconSunHigh, IconSunrise, IconSunset, IconWind } from "@tabler/icons-react";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import type { WidgetProps } from "../definition";
import { AnimatedWeatherIcon } from "./animated-icon";
import classes from "./component.module.css";
import { DailyWeatherDetails } from "./details";
import type { HourlyChartRow, WeatherData } from "./format";
import {
getHourlyChartData,
getPreferredDate,
getPreferredTime,
getPreferredUnit,
getPreferredWindSpeed,
} from "./format";
import { getWeatherKind, WeatherDescription } from "./icon";
import { getAdvancedWeatherLayout } from "./layout";
interface AdvancedWeatherProps {
height: number;
options: WidgetProps<"weather">["options"];
weather: WeatherData;
width: number;
}
interface MetricCardProps {
icon: ReactNode;
label: string;
value: ReactNode;
}
interface WeatherChartDatum {
detailLabel: string;
observedAt: string;
precipitationProbability: number;
precipitationSummary: string;
temperature: number;
temperatureSummary: string;
tooltipLabel: string;
}
interface HourlyChartTooltipProps {
active?: boolean;
payload?: Array<{ payload?: WeatherChartDatum }>;
}
const HourlyChartTooltip = ({ active, payload }: HourlyChartTooltipProps) => {
const datum = payload?.[0]?.payload;
if (!active || !datum) return null;
return (
<Paper p="xs" radius="sm" shadow="md" withBorder>
<Text size="sm" fw={600} mb={4}>
{datum.tooltipLabel}
</Text>
<Text size="xs">
{datum.temperatureSummary} · {datum.precipitationSummary}
</Text>
<Text size="xs">{datum.detailLabel}</Text>
</Paper>
);
};
const MetricCard = ({ icon, label, value }: MetricCardProps) => (
<Paper className={classes.metricCard} p="sm" radius="md">
<Group gap="xs" wrap="nowrap" align="flex-start">
{icon}
<Stack gap={0} miw={0}>
<Text size="xs" c="dimmed">
{label}
</Text>
<Text size="sm" fw={600} truncate>
{value}
</Text>
</Stack>
</Group>
</Paper>
);
export const AdvancedWeather = ({ height, options, weather, width }: AdvancedWeatherProps) => {
const headingId = useId();
const chartId = useId();
const locale = useCurrentIntlLocale();
const t = useScopedI18n("widget.weather");
const tCommon = useScopedI18n("common");
const layout = getAdvancedWeatherLayout(width, height);
const today = weather.daily[0];
const observedAt = Date.parse(weather.current.observedAt);
const nextHour = weather.hourly.find((hour) => Date.parse(hour.observedAt) > observedAt) ?? weather.hourly[0];
const hourly = getHourlyChartData(weather, options.isFormatFahrenheit);
const speedUnit = options.useImperialSpeed
? tCommon("unit.speed.milesPerHour")
: tCommon("unit.speed.kilometersPerHour");
const temperatureUnit = options.isFormatFahrenheit ? "°F" : "°C";
const chartData = hourly.map<WeatherChartDatum>((hour) => {
const condition = hour.weatherCode === null ? t("kind.unknown") : t(`kind.${getWeatherKind(hour.weatherCode)}`);
const temperature = hour.temperature === null ? "?" : hour.temperature.toFixed(1);
const precipitationProbability = hour.precipitationProbability ?? "?";
let detailLabel = t("advanced.hourlyTooltipWithoutHumidity", {
amount: hour.precipitation?.toFixed(1) ?? "?",
feelsLike: hour.apparentTemperature?.toFixed(1) ?? "?",
speed: getPreferredWindSpeed(hour.windSpeed, options.useImperialSpeed),
speedUnit,
temperatureUnit,
});
if (options.showHumidity) {
detailLabel = t("advanced.hourlyTooltip", {
amount: hour.precipitation?.toFixed(1) ?? "?",
feelsLike: hour.apparentTemperature?.toFixed(1) ?? "?",
humidity: hour.relativeHumidity ?? "?",
speed: getPreferredWindSpeed(hour.windSpeed, options.useImperialSpeed),
speedUnit,
temperatureUnit,
});
}
return {
detailLabel,
observedAt: hour.observedAt,
precipitationProbability: hour.precipitationProbability ?? Number.NaN,
precipitationSummary: `${t("advanced.precipitationChance")}: ${precipitationProbability}%`,
temperature: hour.temperature ?? Number.NaN,
temperatureSummary: `${t("advanced.temperature")}: ${temperature}${temperatureUnit}`,
tooltipLabel: `${getPreferredTime(hour.observedAt, locale, weather.timezone)} · ${condition}`,
};
});
const ticks = hourly.filter((_, index) => index % layout.hourlyTickStep === 0).map((hour) => hour.observedAt);
return (
<ScrollArea h="100%" w="100%" type="auto" offsetScrollbars scrollbarSize={6}>
<Stack className={classes.advancedRoot} gap="md" p="md">
<Group justify="space-between" align="flex-start" gap="md" wrap="wrap">
<Group gap="md" wrap="nowrap">
<AnimatedWeatherIcon
animated={options.animateIcons}
code={weather.current.weatherCode}
isDay={weather.current.isDay}
size={56}
/>
<Stack gap={2}>
<Text fz={32} fw={700} lh={1}>
{getPreferredUnit(
weather.current.temperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
<WeatherDescription weatherOnly weatherCode={weather.current.weatherCode} />
<Text size="sm" c="dimmed">
{t("advanced.feelsLike", {
temperature: getPreferredUnit(
weather.current.apparentTemperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
),
})}
</Text>
</Stack>
</Group>
<Stack gap={2} align="flex-end" className={classes.locationSummary}>
<Group gap={5} wrap="nowrap" maw="100%">
<IconMapPin size="var(--mantine-font-size-md)" aria-hidden />
<Text size="sm" fw={600} truncate>
{options.location.name}
</Text>
</Group>
<Text size="xs" c="dimmed">
{t("advanced.observedAt", {
time: getPreferredTime(weather.current.observedAt, locale, weather.timezone),
})}
</Text>
{today && (
<Text size="sm">
{t("advanced.highLow", {
maximum: getPreferredUnit(
today.maxTemperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
),
minimum: getPreferredUnit(
today.minTemperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
),
})}
</Text>
)}
</Stack>
</Group>
<SimpleGrid cols={layout.metricColumns} spacing="xs">
<MetricCard
icon={<IconDroplets size={18} aria-hidden />}
label={t("advanced.nextHourPrecipitation")}
value={t("advanced.precipitationValue", {
amount: nextHour?.precipitation?.toFixed(1) ?? "?",
probability: nextHour?.precipitationProbability ?? "?",
})}
/>
{options.showHumidity && (
<MetricCard
icon={<IconDroplets size={18} aria-hidden />}
label={t("advanced.currentHumidity")}
value={`${weather.current.relativeHumidity}%`}
/>
)}
<MetricCard
icon={<IconWind size={18} aria-hidden />}
label={t("advanced.currentWind")}
value={t("advanced.windValue", {
gusts: getPreferredWindSpeed(weather.current.windGusts, options.useImperialSpeed),
speed: getPreferredWindSpeed(weather.current.windSpeed, options.useImperialSpeed),
unit: speedUnit,
})}
/>
<MetricCard
icon={<IconSunHigh size={18} aria-hidden />}
label={t("advanced.todayUv")}
value={today?.uvIndex?.toFixed(1) ?? "?"}
/>
<MetricCard
icon={<IconSunrise size={18} aria-hidden />}
label={t("dailyForecast.sunrise")}
value={getPreferredTime(today?.sunriseAt, locale, weather.timezone)}
/>
<MetricCard
icon={<IconSunset size={18} aria-hidden />}
label={t("dailyForecast.sunset")}
value={getPreferredTime(today?.sunsetAt, locale, weather.timezone)}
/>
</SimpleGrid>
{chartData.length > 0 && (
<Box component="figure" m={0} aria-labelledby={chartId}>
<Text id={chartId} component="figcaption" size="sm" fw={600} mb="xs">
{t("advanced.hourlyForecast")}
</Text>
<Box aria-hidden>
<CompositeChart
h={layout.chartHeight}
data={chartData}
dataKey="observedAt"
series={[
{ name: "temperature", label: t("advanced.temperature"), color: "orange.6", type: "area" },
{
name: "precipitationProbability",
label: t("advanced.precipitationChance"),
color: "blue.5",
type: "bar",
yAxisId: "right",
},
]}
curveType="monotone"
gridAxis="y"
tickLine="none"
withDots={false}
withLegend
withRightYAxis={layout.showChartAxes}
withYAxis={layout.showChartAxes}
yAxisProps={{ width: 38, tickFormatter: (value: number) => `${value}°` }}
rightYAxisProps={{ width: 38, domain: [0, 100], tickFormatter: (value: number) => `${value}%` }}
xAxisProps={{
ticks,
interval: 0,
tickFormatter: (value: string) => getPreferredTime(value, locale, weather.timezone),
}}
tooltipAnimationDuration={0}
tooltipProps={{ content: <HourlyChartTooltip /> }}
/>
</Box>
<VisuallyHidden>
<HourlyWeatherTable
hourly={hourly}
locale={locale}
speedUnit={speedUnit}
temperatureUnit={temperatureUnit}
timeZone={weather.timezone}
useImperialSpeed={options.useImperialSpeed}
showHumidity={options.showHumidity}
/>
</VisuallyHidden>
</Box>
)}
<Text id={headingId} component="h3" size="sm" fw={600} m={0}>
{t("advanced.forecast")}
</Text>
<SimpleGrid aria-labelledby={headingId} cols={layout.dailyColumns} spacing="xs">
{weather.daily.map((day) => (
<Popover key={day.date} position="bottom" withArrow shadow="md" offset={10}>
<Popover.Target>
<UnstyledButton
className={classes.dailyCardButton}
aria-label={t("detailsFor", {
date: getPreferredDate(day.date, locale, { weekday: "long", month: "short", day: "numeric" }),
})}
>
<Paper className={classes.dailyCard} p="sm" radius="md">
<Stack gap="sm">
<Group justify="space-between" align="flex-start" wrap="nowrap">
<Stack gap={0} miw={0}>
<Text size="sm" fw={700} tt="capitalize">
{getPreferredDate(day.date, locale, { weekday: "short" })}
</Text>
<Text size="xs" c="dimmed">
{getPreferredDate(day.date, locale, { month: "short", day: "numeric" })}
</Text>
</Stack>
<AnimatedWeatherIcon animated={options.animateIcons} code={day.weatherCode} size={28} />
</Group>
<Text size="sm" fw={500} lineClamp={1}>
{t(`kind.${getWeatherKind(day.weatherCode)}`)}
</Text>
<Group gap="xs" align="baseline" wrap="nowrap">
<Text fz="lg" fw={700}>
{getPreferredUnit(
day.maxTemperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
<Text size="sm" c="dimmed" fw={500}>
{getPreferredUnit(
day.minTemperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
</Group>
<Group className={classes.dailyCardFacts} justify="space-between" gap={4} wrap="nowrap">
<Group gap={3} wrap="nowrap">
<IconDroplets size={14} aria-hidden />
<Text className={classes.dailyCardFact} fz={11}>
{day.precipitationProbability ?? "?"}%
</Text>
</Group>
<Group gap={3} wrap="nowrap">
<IconWind size={14} aria-hidden />
<Text className={classes.dailyCardFact} fz={11}>
{getPreferredWindSpeed(day.maxWindSpeed, options.useImperialSpeed)} {speedUnit}
</Text>
</Group>
</Group>
</Stack>
</Paper>
</UnstyledButton>
</Popover.Target>
<Popover.Dropdown className={classes.dailyDetailsDropdown}>
<DailyWeatherDetails
animateIcons={options.animateIcons}
day={day}
dateFormat={options.dateFormat}
disableTemperatureDecimals={options.disableTemperatureDecimals}
isFahrenheit={options.isFormatFahrenheit}
showHumidity={options.showHumidity}
timeZone={weather.timezone}
useImperialSpeed={options.useImperialSpeed}
/>
</Popover.Dropdown>
</Popover>
))}
</SimpleGrid>
</Stack>
</ScrollArea>
);
};
interface HourlyDetailProps {
locale: string;
showHumidity: boolean;
speedUnit: string;
temperatureUnit: string;
timeZone: string;
useImperialSpeed: boolean;
}
const HourlyWeatherTable = ({
hourly,
locale,
showHumidity,
speedUnit,
temperatureUnit,
timeZone,
useImperialSpeed,
}: HourlyDetailProps & { hourly: HourlyChartRow[] }) => {
const t = useScopedI18n("widget.weather");
return (
<table>
<caption>{t("advanced.hourlyForecast")}</caption>
<thead>
<tr>
<th>{t("advanced.time")}</th>
<th>{t("advanced.conditions")}</th>
<th>{t("advanced.temperature")}</th>
<th>{t("advanced.feelsLikeLabel")}</th>
<th>{t("advanced.precipitationChance")}</th>
{showHumidity && <th>{t("advanced.humidity")}</th>}
<th>{t("advanced.wind", { unit: speedUnit })}</th>
</tr>
</thead>
<tbody>
{hourly.map((hour) => (
<tr key={hour.observedAt}>
<td>{getPreferredTime(hour.observedAt, locale, timeZone)}</td>
<td>{hour.weatherCode === null ? t("kind.unknown") : t(`kind.${getWeatherKind(hour.weatherCode)}`)}</td>
<td>{hour.temperature === null ? "?" : `${hour.temperature.toFixed(1)}${temperatureUnit}`}</td>
<td>
{hour.apparentTemperature === null ? "?" : `${hour.apparentTemperature.toFixed(1)}${temperatureUnit}`}
</td>
<td>{hour.precipitationProbability === null ? "?" : `${hour.precipitationProbability}%`}</td>
{showHumidity && <td>{hour.relativeHumidity === null ? "?" : `${hour.relativeHumidity}%`}</td>}
<td>
{getPreferredWindSpeed(hour.windSpeed, useImperialSpeed)} /{" "}
{getPreferredWindSpeed(hour.windGusts, useImperialSpeed)} {speedUnit}
</td>
</tr>
))}
</tbody>
</table>
);
};
@@ -3,7 +3,9 @@ import "../widgets-common.css";
import { WeatherIcon } from "./icon";
interface AnimatedWeatherIconProps {
animated?: boolean;
code: number;
isDay?: boolean;
size?: string | number;
}
@@ -17,10 +19,12 @@ const getAnimationClass = (code: number): string => {
return "";
};
export const AnimatedWeatherIcon = ({ code, size = 26 }: AnimatedWeatherIconProps) => {
export const AnimatedWeatherIcon = ({ animated = false, code, isDay, size = 26 }: AnimatedWeatherIconProps) => {
let animationClass = "";
if (animated && (code !== 0 || isDay !== false)) animationClass = getAnimationClass(code);
return (
<span className={`weather-anim-wrapper ${getAnimationClass(code)}`}>
<WeatherIcon code={code} size={size} />
<span className={`weather-anim-wrapper ${animationClass}`}>
<WeatherIcon code={code} isDay={isDay} size={size} />
</span>
);
};
+173
View File
@@ -0,0 +1,173 @@
import { useMemo } from "react";
import { Group, Popover, Stack, Text, UnstyledButton } from "@mantine/core";
import { IconArrowDownRight, IconArrowUpRight, IconDroplets, IconMapPin, IconWind } from "@tabler/icons-react";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import type { WidgetProps } from "../definition";
import { AnimatedWeatherIcon } from "./animated-icon";
import classes from "./component.module.css";
import { DailyWeatherDetails } from "./details";
import type { WeatherData } from "./format";
import { getPreferredDate, getPreferredUnit, getPreferredWindSpeed } from "./format";
import { formatWeatherDate, WeatherDescription } from "./icon";
import { getCompactWeatherLayout } from "./layout";
interface CompactWeatherProps {
height: number;
isEditMode: boolean;
options: WidgetProps<"weather">["options"];
weather: WeatherData;
width: number;
}
export const CompactWeather = ({ height, isEditMode, options, weather, width }: CompactWeatherProps) => {
const locale = useCurrentIntlLocale();
const t = useScopedI18n("widget.weather");
const tCommon = useScopedI18n("common");
const layout = useMemo(
() => getCompactWeatherLayout(width, height, options.hasForecast, options.forecastDayCount),
[height, options.forecastDayCount, options.hasForecast, width],
);
const today = weather.daily[0];
const speedUnit = options.useImperialSpeed
? tCommon("unit.speed.milesPerHour")
: tCommon("unit.speed.kilometersPerHour");
const contentGap = layout.tier === "micro" ? 2 : 4;
const contentPadding = layout.tier === "roomy" ? "xs" : 4;
return (
<Stack
className={classes.compactRoot}
data-tier={layout.tier}
align="center"
justify="center"
gap={contentGap}
h="100%"
w="100%"
p={contentPadding}
>
<Group className="weather-day-group" gap={layout.tier === "micro" ? 2 : "xs"} wrap="nowrap" justify="center">
<Popover position="bottom" withArrow shadow="md">
<Popover.Target>
<UnstyledButton className={classes.detailsButton} aria-label={t("details")} disabled={isEditMode}>
<AnimatedWeatherIcon
animated={options.animateIcons}
code={weather.current.weatherCode}
isDay={weather.current.isDay}
size={layout.tier === "micro" ? 18 : 32}
/>
</UnstyledButton>
</Popover.Target>
<Popover.Dropdown>
<WeatherDescription weatherOnly weatherCode={weather.current.weatherCode} />
</Popover.Dropdown>
</Popover>
<Stack gap={0} align={layout.tier === "micro" ? "center" : "flex-start"}>
<Text fz={layout.tier === "micro" ? 22 : 30} fw={600} lh={1.05}>
{getPreferredUnit(
weather.current.temperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
{layout.showCondition && <WeatherDescription weatherOnly weatherCode={weather.current.weatherCode} />}
</Stack>
</Group>
{layout.showHighLow && today && (
<Group className="weather-max-min-temp-group" gap="sm" wrap="nowrap">
<Group gap={3} wrap="nowrap">
<IconArrowUpRight size="var(--mantine-font-size-md)" aria-hidden />
<Text size="sm">
{getPreferredUnit(today.maxTemperature, options.isFormatFahrenheit, options.disableTemperatureDecimals)}
</Text>
</Group>
<Group gap={3} wrap="nowrap">
<IconArrowDownRight size="var(--mantine-font-size-md)" aria-hidden />
<Text size="sm">
{getPreferredUnit(today.minTemperature, options.isFormatFahrenheit, options.disableTemperatureDecimals)}
</Text>
</Group>
</Group>
)}
{layout.showSecondary && !options.hasForecast && (
<Group className={classes.compactMetrics} gap="sm" justify="center" wrap="wrap">
{options.showHumidity && (
<Group className="weather-humidity-group" gap={4} wrap="nowrap">
<IconDroplets size="var(--mantine-font-size-sm)" aria-hidden />
<Text size="sm">{weather.current.relativeHumidity}%</Text>
</Group>
)}
{options.showCurrentWindSpeed && (
<Group className="weather-current-wind-speed-group" gap={4} wrap="nowrap">
<IconWind size="var(--mantine-font-size-sm)" aria-hidden />
<Text size="sm">
{getPreferredWindSpeed(weather.current.windSpeed, options.useImperialSpeed)} {speedUnit}
</Text>
</Group>
)}
</Group>
)}
{layout.forecastDays > 0 && (
<Group className="weather-forecast-days-group" w="100%" justify="space-evenly" wrap="nowrap" gap={2}>
{weather.daily.slice(0, layout.forecastDays).map((day, index) => (
<Popover key={day.date} position="bottom" withArrow shadow="md">
<Popover.Target>
<UnstyledButton
className={classes.forecastButton}
aria-label={t("detailsFor", {
date: formatWeatherDate(day.date, locale, options.dateFormat),
})}
disabled={isEditMode}
>
<Stack
component="span"
className={`weather-forecast-day-stack weather-forecast-day${index}`}
gap={0}
align="center"
>
<Text component="span" size="sm" fw={600} tt="capitalize">
{getPreferredDate(day.date, locale, { weekday: "short" })}
</Text>
<AnimatedWeatherIcon animated={options.animateIcons} code={day.weatherCode} size={18} />
<Text component="span" size="sm">
{getPreferredUnit(
day.maxTemperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
</Stack>
</UnstyledButton>
</Popover.Target>
<Popover.Dropdown className={classes.dailyDetailsDropdown}>
<DailyWeatherDetails
animateIcons={options.animateIcons}
day={day}
dateFormat={options.dateFormat}
disableTemperatureDecimals={options.disableTemperatureDecimals}
isFahrenheit={options.isFormatFahrenheit}
showHumidity={options.showHumidity}
timeZone={weather.timezone}
useImperialSpeed={options.useImperialSpeed}
/>
</Popover.Dropdown>
</Popover>
))}
</Group>
)}
{layout.showCity && options.showCity && (
<Group className="weather-city-group" gap={4} wrap="nowrap" maw="100%">
<IconMapPin size="var(--mantine-font-size-sm)" aria-hidden />
<Text size="sm" truncate>
{options.location.name}
</Text>
</Group>
)}
</Stack>
);
};
+118 -10
View File
@@ -1,5 +1,85 @@
.weatherSurface {
overflow: hidden;
}
.weatherContent {
min-width: 0;
min-height: 0;
}
.compactRoot {
overflow: hidden;
}
.compactRoot[data-tier="micro"] {
flex-direction: row;
}
.compactMetrics {
min-width: 0;
}
.advancedRoot {
min-width: 0;
}
.locationSummary {
max-width: min(100%, 20rem);
}
.metricCard,
.dailyCard,
.detailMetric,
.solarDetails {
background: color-mix(in srgb, var(--mantine-color-body) 72%, transparent);
border: 0.0625rem solid color-mix(in srgb, var(--mantine-color-default-border) 72%, transparent);
}
.dailyCard {
transition:
background-color 120ms ease,
border-color 120ms ease;
}
.dailyCardButton:hover .dailyCard,
.dailyCardButton:focus-visible .dailyCard {
background: color-mix(in srgb, var(--mantine-primary-color-light) 30%, var(--mantine-color-body));
border-color: color-mix(in srgb, var(--mantine-primary-color-filled) 45%, var(--mantine-color-default-border));
}
.dailyDetailsDropdown {
width: min(24.375rem, calc(100vw - 2rem));
padding: var(--mantine-spacing-sm);
}
.dailyDetails {
min-width: 0;
}
.dailyDetailsTemperature {
flex-shrink: 0;
max-width: 8.25rem;
}
.dailyCardFacts {
min-width: 0;
}
.dailyCardFact {
white-space: nowrap;
}
.detailMetric {
min-width: 0;
}
.solarDetails {
background: color-mix(in srgb, var(--mantine-color-yellow-light) 24%, var(--mantine-color-body));
}
.detailsButton,
.forecastButton {
.forecastButton,
.dailyCardButton {
color: inherit;
border-radius: var(--mantine-radius-sm);
}
@@ -8,24 +88,52 @@
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 24px;
min-height: 24px;
min-width: 1.5rem;
min-height: 1.5rem;
}
.forecastButton {
.forecastButton,
.dailyCardButton {
display: block;
}
.dailyCardButton,
.dailyCard {
width: 100%;
height: 100%;
}
.detailsButton:focus-visible,
.forecastButton:focus-visible {
outline: 2px solid var(--mantine-primary-color-filled);
outline-offset: 2px;
.forecastButton:focus-visible,
.dailyCardButton:focus-visible {
outline: 0.125rem solid var(--mantine-primary-color-filled);
outline-offset: 0.125rem;
}
.errorIndicator {
z-index: 2;
}
@media (any-pointer: coarse) {
.detailsButton,
.forecastButton {
min-width: 44px;
min-height: 44px;
.forecastButton,
.dailyCardButton {
min-width: 2.75rem;
min-height: 2.75rem;
}
}
@media (prefers-reduced-motion: reduce) {
.dailyCard {
transition: none;
}
}
@media (forced-colors: active) {
.metricCard,
.dailyCard,
.detailMetric,
.solarDetails {
border: 0.0625rem solid CanvasText;
}
}
+66 -9
View File
@@ -1,26 +1,25 @@
import { describe, expect, it } from "vitest";
import { getPreferredTime, getPreferredUnit, getPreferredWindSpeed, getVisibleForecastDays } from "./component";
import { reduceWidgetOptionsWithDefinition } from "../manifest";
import { definition } from ".";
import { getPreferredTime, getPreferredUnit, getPreferredWindSpeed } from "./format";
import { formatWeatherDate } from "./icon";
import { getAdvancedWeatherLayout, getCompactWeatherLayout } from "./layout";
describe("weather formatting", () => {
it("preserves valid zero temperatures", () => {
it("preserves valid zero values", () => {
expect(getPreferredUnit(0)).toBe("0.0°C");
expect(getPreferredUnit(0, true, true)).toBe("32°F");
expect(getPreferredWindSpeed(0)).toBe("0.0");
});
it("keeps zero wind speeds and missing forecast values truthful", () => {
expect(getPreferredWindSpeed(0)).toBe("0.0");
it("keeps missing and invalid values truthful", () => {
expect(getPreferredUnit(null)).toBe("?");
expect(getPreferredWindSpeed(undefined)).toBe("?");
expect(getPreferredTime(undefined, "en-US")).toBe("?");
expect(getPreferredTime("invalid", "en-US")).toBe("?");
});
it("limits compact forecasts by both axes", () => {
expect(getVisibleForecastDays(7, 120, 100)).toBe(2);
expect(getVisibleForecastDays(7, 600, 100)).toBe(3);
});
it.each([
["dddd, MMMM D", "Monday, August 3"],
["dddd, D MMMM", "Monday, 3 August"],
@@ -34,3 +33,61 @@ describe("weather formatting", () => {
expect(formatWeatherDate("2026-08-03", "en-US", pattern)).toBe(expected);
});
});
describe("weather layout", () => {
it("keeps micro widgets focused on current temperature", () => {
expect(getCompactWeatherLayout(120, 100, true, 7)).toEqual({
tier: "micro",
forecastDays: 0,
showCity: false,
showCondition: false,
showHighLow: false,
showSecondary: false,
});
});
it("caps compact forecasts by size and saved preference", () => {
expect(getCompactWeatherLayout(200, 200, true, 7).forecastDays).toBe(2);
expect(getCompactWeatherLayout(424, 200, true, 3).forecastDays).toBe(3);
expect(getCompactWeatherLayout(640, 360, true, 7).forecastDays).toBe(7);
expect(getCompactWeatherLayout(640, 360, false, 7).forecastDays).toBe(0);
});
it("adapts the advanced view to mobile and desktop surfaces", () => {
expect(getAdvancedWeatherLayout(374, 624)).toMatchObject({
dailyColumns: 2,
hourlyTickStep: 6,
showChartAxes: false,
});
expect(getAdvancedWeatherLayout(800, 560)).toMatchObject({
chartHeight: 200,
dailyColumns: 4,
hourlyTickStep: 3,
showChartAxes: true,
});
});
});
describe("weather defaults", () => {
it("starts rich and static while preserving saved false values", () => {
const options = definition.createOptions();
expect(options.showCity.defaultValue).toBe(true);
expect(options.hasForecast.defaultValue).toBe(true);
expect(options.forecastDayCount.defaultValue).toBe(3);
expect(options.animateIcons.defaultValue).toBe(false);
expect(options.showHumidity.defaultValue).toBe(true);
const reduced = reduceWidgetOptionsWithDefinition(definition, {} as never, {
showCity: false,
hasForecast: false,
showHumidity: false,
isFormatFahrenheit: true,
});
expect(reduced).toMatchObject({
showCity: false,
hasForecast: false,
showHumidity: false,
isFormatFahrenheit: true,
});
});
});
+13 -427
View File
@@ -1,32 +1,17 @@
"use client";
import { useId } from "react";
import { Box, Group, Popover, Stack, Table, Text, UnstyledButton } from "@mantine/core";
import {
IconArrowDownRight,
IconArrowUpRight,
IconDroplets,
IconMapPin,
IconSunrise,
IconSunset,
IconWind,
} from "@tabler/icons-react";
import combineClasses from "clsx";
import dayjs from "dayjs";
import { Box } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { metricToImperial } from "@homarr/common";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import { useScopedI18n } from "@homarr/translation/client";
import { WidgetEmptyState } from "../common/empty-state";
import { formatLocalizedDate, formatLocalizedTime } from "../common/locale";
import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";
import { WidgetQueryErrorIndicator, WidgetQueryLoadingState } from "../common/query-state-indicator";
import type { WidgetComponentProps } from "../definition";
import { AnimatedWeatherIcon } from "./animated-icon";
import { formatWeatherDate, WeatherDescription } from "./icon";
import { AdvancedWeather } from "./advanced";
import classes from "./component.module.css";
import { CompactWeather } from "./compact";
export default function WeatherWidget({
isEditMode,
@@ -46,419 +31,20 @@ export default function WeatherWidget({
if (isInitialWidgetQueryPending(weatherQuery)) return <WidgetQueryLoadingState />;
if (!weather) return <WidgetEmptyState />;
const content =
displayMode === "advanced" ? (
<AdvancedWeather weather={weather} options={options} />
) : (
<Stack
align="center"
gap="sm"
justify="center"
w="100%"
h="100%"
style={{ pointerEvents: isEditMode ? "none" : undefined }}
>
{options.hasForecast ? (
<WeeklyForecast
weather={weather}
options={options}
isEditMode={isEditMode}
maxDays={getVisibleForecastDays(options.forecastDayCount, width, height)}
/>
) : (
<DailyWeather weather={weather} options={options} isEditMode={isEditMode} />
)}
</Stack>
);
return (
<Box h="100%" w="100%" pos="relative">
{content}
<Box className={classes.weatherSurface} h="100%" w="100%" pos="relative">
<Box className={classes.weatherContent} h="100%" w="100%" pos="relative">
{displayMode === "advanced" ? (
<AdvancedWeather height={height} options={options} weather={weather} width={width} />
) : (
<CompactWeather height={height} isEditMode={isEditMode} options={options} weather={weather} width={width} />
)}
</Box>
{weatherQuery.error && (
<Box pos="absolute" top={4} right={4}>
<Box pos="absolute" top={4} right={4} className={classes.errorIndicator}>
<WidgetQueryErrorIndicator error={weatherQuery.error} label={t("name")} />
</Box>
)}
</Box>
);
}
interface WeatherProps extends Pick<WidgetComponentProps<"weather">, "options"> {
weather: NonNullable<RouterOutputs["widget"]["weather"]["atLocation"]>;
}
interface CompactWeatherProps extends WeatherProps {
isEditMode: boolean;
}
const AdvancedWeather = ({ options, weather }: WeatherProps) => {
const forecastHeadingId = useId();
const locale = useCurrentIntlLocale();
const t = useScopedI18n("widget.weather");
const tCommon = useScopedI18n("common");
return (
<Stack h="100%" w="100%" gap="sm" p="md" style={{ overflow: "hidden" }}>
<Group justify="space-between" align="center" gap="sm" wrap="wrap">
<Group gap="sm" wrap="nowrap">
<AnimatedWeatherIcon size={42} code={weather.current.weathercode} />
<Stack gap={0}>
<Text fz="xl" fw={700} lh={1.1}>
{getPreferredUnit(
weather.current.temperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
<WeatherDescription weatherOnly weatherCode={weather.current.weathercode} />
</Stack>
</Group>
<Group gap="lg" wrap="wrap">
<Group gap={5} wrap="nowrap">
<IconMapPin size="var(--mantine-font-size-md)" aria-hidden />
<Text size="sm">{options.location.name}</Text>
</Group>
<Group gap={5} wrap="nowrap">
<IconWind size="var(--mantine-font-size-md)" aria-hidden />
<Text size="sm">
{t("currentWindSpeed", {
currentWindSpeed: getPreferredWindSpeed(weather.current.windspeed, options.useImperialSpeed),
unit: options.useImperialSpeed
? tCommon("unit.speed.milesPerHour")
: tCommon("unit.speed.kilometersPerHour"),
})}
</Text>
</Group>
</Group>
</Group>
<Text id={forecastHeadingId} component="h3" size="sm" fw={600}>
{t("advanced.forecast")}
</Text>
<Table.ScrollContainer
minWidth={680}
maxHeight="100%"
style={{ flex: 1, minHeight: 0 }}
scrollAreaProps={{ type: "auto", offsetScrollbars: "present" }}
>
<Table
aria-labelledby={forecastHeadingId}
striped
highlightOnHover
verticalSpacing="xs"
horizontalSpacing="sm"
stickyHeader
>
<Table.Thead>
<Table.Tr>
<Table.Th>{t("advanced.day")}</Table.Th>
<Table.Th>{t("advanced.conditions")}</Table.Th>
<Table.Th>{t("advanced.temperature")}</Table.Th>
<Table.Th>{t("advanced.humidity")}</Table.Th>
<Table.Th>
{t("advanced.wind", {
unit: options.useImperialSpeed
? tCommon("unit.speed.milesPerHour")
: tCommon("unit.speed.kilometersPerHour"),
})}
</Table.Th>
<Table.Th>{t("advanced.sun")}</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{weather.daily.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={6}>
<Text size="sm" c="dimmed" ta="center">
{t("advanced.noForecast")}
</Text>
</Table.Td>
</Table.Tr>
) : (
weather.daily.map((dayWeather) => (
<Table.Tr key={dayWeather.time}>
<Table.Td>
<Stack gap={0}>
<Text size="sm" fw={600} tt="capitalize">
{formatLocalizedDate(dayWeather.time, locale, { weekday: "short" })}
</Text>
<Text size="xs" c="dimmed">
{formatLocalizedDate(dayWeather.time, locale, { month: "short", day: "numeric" })}
</Text>
</Stack>
</Table.Td>
<Table.Td>
<Group gap="xs" wrap="nowrap">
<AnimatedWeatherIcon size={20} code={dayWeather.weatherCode} />
<WeatherDescription weatherOnly weatherCode={dayWeather.weatherCode} />
</Group>
</Table.Td>
<Table.Td>
<Group gap={4} wrap="nowrap">
<IconArrowUpRight size="var(--mantine-font-size-sm)" aria-hidden />
<Text size="sm">
{getPreferredUnit(
dayWeather.maxTemp,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
<Text size="sm" c="dimmed">
/
</Text>
<IconArrowDownRight size="var(--mantine-font-size-sm)" aria-hidden />
<Text size="sm">
{getPreferredUnit(
dayWeather.minTemp,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
</Group>
</Table.Td>
<Table.Td>
<Group gap={5} wrap="nowrap">
<IconDroplets size="var(--mantine-font-size-sm)" aria-hidden />
<Text size="sm">{dayWeather.humidity === undefined ? "?" : `${dayWeather.humidity}%`}</Text>
</Group>
</Table.Td>
<Table.Td>
<Group gap={5} wrap="nowrap">
<IconWind size="var(--mantine-font-size-sm)" aria-hidden />
<Text size="sm">
{getPreferredWindSpeed(dayWeather.maxWindSpeed, options.useImperialSpeed)} /{" "}
{getPreferredWindSpeed(dayWeather.maxWindGusts, options.useImperialSpeed)}
</Text>
</Group>
</Table.Td>
<Table.Td>
<Group gap="xs" wrap="nowrap">
<Group gap={3} wrap="nowrap">
<IconSunrise size="var(--mantine-font-size-sm)" aria-hidden />
<Text size="sm">{getPreferredTime(dayWeather.sunrise, locale)}</Text>
</Group>
<Text size="sm" c="dimmed">
/
</Text>
<Group gap={3} wrap="nowrap">
<IconSunset size="var(--mantine-font-size-sm)" aria-hidden />
<Text size="sm">{getPreferredTime(dayWeather.sunset, locale)}</Text>
</Group>
</Group>
</Table.Td>
</Table.Tr>
))
)}
</Table.Tbody>
</Table>
</Table.ScrollContainer>
</Stack>
);
};
const DailyWeather = ({ options, weather, isEditMode }: CompactWeatherProps) => {
const t = useScopedI18n("widget.weather");
const tCommon = useScopedI18n("common");
return (
<>
<Group className="weather-day-group" gap="sm">
<Popover position="bottom" withArrow shadow="md">
<Popover.Target>
<UnstyledButton className={classes.detailsButton} aria-label={t("details")} disabled={isEditMode}>
<AnimatedWeatherIcon size={30} code={weather.current.weathercode} />
</UnstyledButton>
</Popover.Target>
<Popover.Dropdown>
<WeatherDescription weatherOnly weatherCode={weather.current.weathercode} />
</Popover.Dropdown>
</Popover>
<Text fz={30}>
{getPreferredUnit(
weather.current.temperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
</Group>
<Stack gap="xs" align="center">
{options.showCurrentWindSpeed && (
<Group className="weather-current-wind-speed-group" wrap="nowrap" gap="xs">
<IconWind size="var(--mantine-font-size-md)" />
<Text fz={16}>
{t("currentWindSpeed", {
currentWindSpeed: (options.useImperialSpeed
? metricToImperial(weather.current.windspeed)
: weather.current.windspeed
).toFixed(1),
unit: options.useImperialSpeed
? tCommon("unit.speed.milesPerHour")
: tCommon("unit.speed.kilometersPerHour"),
})}
</Text>
</Group>
)}
{weather.daily[0]?.humidity !== undefined && (
<Group className="weather-humidity-group" wrap="nowrap" gap="xs">
<IconDroplets size="var(--mantine-font-size-md)" />
<Text fz={16}>{t("dailyForecast.humidity", { humidity: weather.daily[0].humidity })}</Text>
</Group>
)}
<Group className="weather-max-min-temp-group" wrap="nowrap" gap="sm">
<Group gap="xs" wrap="nowrap">
<IconArrowUpRight size="var(--mantine-font-size-md)" />
<Text fz={16}>
{getPreferredUnit(
weather.daily[0]?.maxTemp,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
</Group>
<Group gap="xs" wrap="nowrap">
<IconArrowDownRight size="var(--mantine-font-size-md)" />
<Text fz={16}>
{getPreferredUnit(
weather.daily[0]?.minTemp,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
</Group>
</Group>
</Stack>
{options.showCity && (
<>
<Group className="weather-city-group" wrap="nowrap" gap="xs">
<IconMapPin size="var(--mantine-font-size-md)" />
<Text fz={16} style={{ whiteSpace: "nowrap" }}>
{options.location.name}
</Text>
</Group>
</>
)}
</>
);
};
const WeeklyForecast = ({ options, weather, isEditMode, maxDays }: CompactWeatherProps & { maxDays: number }) => {
const t = useScopedI18n("widget.weather");
return (
<>
<Group className="weather-forecast-city-temp-group" wrap="nowrap" gap="md">
{options.showCity && (
<Group gap="xs" wrap="nowrap">
<IconMapPin size="var(--mantine-font-size-md)" />
<Text fz={16} style={{ whiteSpace: "nowrap" }}>
{options.location.name}
</Text>
</Group>
)}
<Group gap="xs" wrap="nowrap">
<Popover position="bottom" withArrow shadow="md">
<Popover.Target>
<UnstyledButton className={classes.detailsButton} aria-label={t("details")} disabled={isEditMode}>
<AnimatedWeatherIcon size={16} code={weather.current.weathercode} />
</UnstyledButton>
</Popover.Target>
<Popover.Dropdown>
<WeatherDescription weatherOnly weatherCode={weather.current.weathercode} />
</Popover.Dropdown>
</Popover>
<Text fz={16}>
{getPreferredUnit(
weather.current.temperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
</Group>
</Group>
<Forecast weather={weather} options={options} isEditMode={isEditMode} maxDays={maxDays} />
</>
);
};
function Forecast({ weather, options, isEditMode, maxDays }: CompactWeatherProps & { maxDays: number }) {
const dateFormat = options.dateFormat;
const t = useScopedI18n("widget.weather");
const locale = useCurrentIntlLocale();
return (
<Group className="weather-forecast-days-group" w="100%" justify="space-evenly" wrap="nowrap" pb="sm">
{weather.daily.slice(0, maxDays).map((dayWeather, index) => (
<Popover key={dayWeather.time} position="bottom" withArrow shadow="md">
<Popover.Target>
<UnstyledButton
className={classes.forecastButton}
aria-label={t("detailsFor", { date: formatWeatherDate(dayWeather.time, locale, dateFormat) })}
disabled={isEditMode}
>
<Stack
component="span"
className={combineClasses(
"weather-forecast-day-stack",
`weather-forecast-day${index}`,
`weather-forecast-weekday${dayjs(dayWeather.time).day()}`,
)}
gap="0"
align="center"
>
<Text component="span" fz="xl">
{formatLocalizedDate(dayWeather.time, locale, { weekday: "short" })}
</Text>
<AnimatedWeatherIcon size={16} code={dayWeather.weatherCode} />
<Text component="span" fz={16}>
{getPreferredUnit(dayWeather.maxTemp, options.isFormatFahrenheit, options.disableTemperatureDecimals)}
</Text>
</Stack>
</UnstyledButton>
</Popover.Target>
<Popover.Dropdown>
<WeatherDescription
useImperialSpeed={options.useImperialSpeed}
dateFormat={dateFormat}
time={dayWeather.time}
weatherCode={dayWeather.weatherCode}
maxTemp={getPreferredUnit(
dayWeather.maxTemp,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
minTemp={getPreferredUnit(
dayWeather.minTemp,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
sunrise={getPreferredTime(dayWeather.sunrise, locale)}
sunset={getPreferredTime(dayWeather.sunset, locale)}
maxWindSpeed={dayWeather.maxWindSpeed}
maxWindGusts={dayWeather.maxWindGusts}
humidity={dayWeather.humidity}
/>
</Popover.Dropdown>
</Popover>
))}
</Group>
);
}
export const getPreferredUnit = (value?: number, isFahrenheit = false, disableTemperatureDecimals = false): string =>
value !== undefined
? isFahrenheit
? `${(value * (9 / 5) + 32).toFixed(disableTemperatureDecimals ? 0 : 1)}°F`
: `${value.toFixed(disableTemperatureDecimals ? 0 : 1)}°C`
: "?";
export const getPreferredWindSpeed = (value: number | undefined, useImperialSpeed = false): string =>
value === undefined ? "?" : (useImperialSpeed ? metricToImperial(value) : value).toFixed(1);
export const getPreferredTime = (value: string | undefined, locale = "en-US"): string =>
value ? formatLocalizedTime(value, locale) : "?";
export const getVisibleForecastDays = (configuredDays: number, width: number, height: number): number => {
const widthBudget = Math.max(1, Math.floor(width / 58));
const heightBudget = height < 120 ? 3 : configuredDays;
return Math.min(configuredDays, widthBudget, heightBudget);
};
+161
View File
@@ -0,0 +1,161 @@
import type { ReactNode } from "react";
import { Group, Paper, SimpleGrid, Stack, Text, ThemeIcon } from "@mantine/core";
import {
IconDroplets,
IconGauge,
IconSunHigh,
IconSunrise,
IconSunset,
IconTemperature,
IconWind,
} from "@tabler/icons-react";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import type { WidgetProps } from "../definition";
import { AnimatedWeatherIcon } from "./animated-icon";
import classes from "./component.module.css";
import type { DailyWeatherData } from "./format";
import { getPreferredDaylightDuration, getPreferredTime, getPreferredUnit, getPreferredWindSpeed } from "./format";
import { formatWeatherDate, getWeatherKind } from "./icon";
interface DailyWeatherDetailsProps {
animateIcons: boolean;
day: DailyWeatherData;
disableTemperatureDecimals: boolean;
isFahrenheit: boolean;
dateFormat: WidgetProps<"weather">["options"]["dateFormat"];
showHumidity: boolean;
timeZone: string;
useImperialSpeed: boolean;
}
interface DetailMetricProps {
icon: ReactNode;
label: string;
value: ReactNode;
}
const DetailMetric = ({ icon, label, value }: DetailMetricProps) => (
<Paper className={classes.detailMetric} p="xs" radius="md">
<Group gap="xs" wrap="nowrap" align="flex-start">
<ThemeIcon variant="light" size={28} radius="md">
{icon}
</ThemeIcon>
<Stack gap={0} miw={0}>
<Text size="xs" c="dimmed" lh={1.25}>
{label}
</Text>
<Text size="sm" fw={600} lh={1.35}>
{value}
</Text>
</Stack>
</Group>
</Paper>
);
const SolarMetric = ({ icon, label, value }: DetailMetricProps) => (
<Stack gap={2} align="center" ta="center">
<ThemeIcon variant="transparent" color="yellow" size={22}>
{icon}
</ThemeIcon>
<Text size="xs" c="dimmed">
{label}
</Text>
<Text size="sm" fw={600}>
{value}
</Text>
</Stack>
);
export const DailyWeatherDetails = ({
animateIcons,
day,
dateFormat,
disableTemperatureDecimals,
isFahrenheit,
showHumidity,
timeZone,
useImperialSpeed,
}: DailyWeatherDetailsProps) => {
const locale = useCurrentIntlLocale();
const t = useScopedI18n("widget.weather");
const tCommon = useScopedI18n("common");
const speedUnit = useImperialSpeed ? tCommon("unit.speed.milesPerHour") : tCommon("unit.speed.kilometersPerHour");
return (
<Stack gap="sm" className={classes.dailyDetails}>
<Group justify="space-between" align="center" gap="md" wrap="nowrap">
<Group gap="sm" wrap="nowrap" miw={0}>
<ThemeIcon variant="light" size={46} radius="xl">
<AnimatedWeatherIcon animated={animateIcons} code={day.weatherCode} size={28} />
</ThemeIcon>
<Stack gap={0} miw={0}>
<Text fw={700} truncate>
{formatWeatherDate(day.date, locale, dateFormat)}
</Text>
<Text size="sm" c="dimmed">
{t(`kind.${getWeatherKind(day.weatherCode)}`)}
</Text>
</Stack>
</Group>
<Text size="sm" fw={600} ta="right" className={classes.dailyDetailsTemperature}>
{t("advanced.highLow", {
maximum: getPreferredUnit(day.maxTemperature, isFahrenheit, disableTemperatureDecimals),
minimum: getPreferredUnit(day.minTemperature, isFahrenheit, disableTemperatureDecimals),
})}
</Text>
</Group>
<SimpleGrid cols={2} spacing={6}>
<DetailMetric
icon={<IconTemperature size={16} aria-hidden />}
label={t("advanced.detailLabel.feelsLike")}
value={`${getPreferredUnit(day.maxApparentTemperature, isFahrenheit, disableTemperatureDecimals)} / ${getPreferredUnit(day.minApparentTemperature, isFahrenheit, disableTemperatureDecimals)}`}
/>
<DetailMetric
icon={<IconDroplets size={16} aria-hidden />}
label={t("advanced.detailLabel.precipitation")}
value={`${day.precipitationProbability ?? "?"}% · ${day.precipitation?.toFixed(1) ?? "?"} mm`}
/>
{showHumidity && (
<DetailMetric
icon={<IconGauge size={16} aria-hidden />}
label={t("advanced.detailLabel.humidity")}
value={`${day.averageHumidity ?? "?"}%`}
/>
)}
<DetailMetric
icon={<IconWind size={16} aria-hidden />}
label={t("advanced.detailLabel.wind")}
value={`${getPreferredWindSpeed(day.maxWindSpeed, useImperialSpeed)} / ${getPreferredWindSpeed(day.maxWindGusts, useImperialSpeed)} ${speedUnit}`}
/>
<DetailMetric
icon={<IconSunHigh size={16} aria-hidden />}
label={t("advanced.detailLabel.uv")}
value={day.uvIndex?.toFixed(1) ?? "?"}
/>
</SimpleGrid>
<Paper className={classes.solarDetails} p="xs" radius="md">
<SimpleGrid cols={3} spacing="xs">
<SolarMetric
icon={<IconSunrise size={17} aria-hidden />}
label={t("dailyForecast.sunrise")}
value={getPreferredTime(day.sunriseAt, locale, timeZone)}
/>
<SolarMetric
icon={<IconSunset size={17} aria-hidden />}
label={t("dailyForecast.sunset")}
value={getPreferredTime(day.sunsetAt, locale, timeZone)}
/>
<SolarMetric
icon={<IconSunHigh size={17} aria-hidden />}
label={t("advanced.detailLabel.daylight")}
value={getPreferredDaylightDuration(day.daylightDuration)}
/>
</SimpleGrid>
</Paper>
</Stack>
);
};
+60
View File
@@ -0,0 +1,60 @@
import type { RouterOutputs } from "@homarr/api";
import { formatDuration, metricToImperial } from "@homarr/common";
import { formatLocalizedDate, formatLocalizedTime } from "../common/locale";
export type WeatherData = NonNullable<RouterOutputs["widget"]["weather"]["atLocation"]>;
export type DailyWeatherData = WeatherData["daily"][number];
export const toPreferredTemperature = (value: number | null | undefined, isFahrenheit = false): number | null => {
if (value === null || value === undefined) return null;
if (isFahrenheit) return value * (9 / 5) + 32;
return value;
};
export const getPreferredUnit = (
value: number | null | undefined,
isFahrenheit = false,
disableTemperatureDecimals = false,
): string => {
const preferred = toPreferredTemperature(value, isFahrenheit);
if (preferred === null) return "?";
return `${preferred.toFixed(disableTemperatureDecimals ? 0 : 1)}°${isFahrenheit ? "F" : "C"}`;
};
export const getPreferredWindSpeed = (value: number | null | undefined, useImperialSpeed = false): string => {
if (value === null || value === undefined) return "?";
return (useImperialSpeed ? metricToImperial(value) : value).toFixed(1);
};
export const getPreferredTime = (value: string | null | undefined, locale = "en-US", timeZone?: string): string => {
if (!value) return "?";
return formatLocalizedTime(value, locale, { timeZone });
};
export const getPreferredDate = (value: string, locale: string, options: Intl.DateTimeFormatOptions): string =>
formatLocalizedDate(value, locale, options);
export const getPreferredDaylightDuration = (value: number | null | undefined): string => {
if (value === null || value === undefined) return "?";
return formatDuration(value * 1000);
};
export interface HourlyChartRow {
observedAt: string;
temperature: number | null;
apparentTemperature: number | null;
precipitationProbability: number | null;
precipitation: number | null;
weatherCode: number | null;
relativeHumidity: number | null;
windSpeed: number | null;
windGusts: number | null;
}
export const getHourlyChartData = (weather: WeatherData, isFahrenheit: boolean): HourlyChartRow[] =>
weather.hourly.map((hour) => ({
...hour,
temperature: toPreferredTemperature(hour.temperature, isFahrenheit),
apparentTemperature: toPreferredTemperature(hour.apparentTemperature, isFahrenheit),
}));
+25 -10
View File
@@ -23,6 +23,7 @@ import type { WidgetProps } from "../definition";
interface WeatherIconProps {
code: number;
isDay?: boolean;
size?: string | number;
}
@@ -32,12 +33,16 @@ interface WeatherIconProps {
* @param size size of the icon, accepts relative sizes too
* @returns Icon corresponding to the weather code
*/
export const WeatherIcon = ({ code, size = 50 }: WeatherIconProps) => {
export const WeatherIcon = ({ code, isDay = true, size = 50 }: WeatherIconProps) => {
if (code === 0 && !isDay) return <IconMoon style={{ float: "left" }} size={size} />;
const { icon: Icon } = weatherDefinitions.find((definition) => definition.codes.includes(code)) ?? unknownWeather;
return <Icon style={{ float: "left" }} size={size} />;
};
export const getWeatherKind = (code: number) =>
(weatherDefinitions.find((definition) => definition.codes.includes(code)) ?? unknownWeather).name;
interface WeatherDescriptionProps {
weatherOnly?: boolean;
useImperialSpeed?: boolean;
@@ -84,23 +89,33 @@ export const WeatherDescription = ({
const tCommon = useScopedI18n("common");
const locale = useCurrentIntlLocale();
const { name } = weatherDefinitions.find((definition) => definition.codes.includes(weatherCode)) ?? unknownWeather;
const name = getWeatherKind(weatherCode);
if (weatherOnly) {
return <Text fz="16px">{t(`kind.${name}`)}</Text>;
return <Text fz="md">{t(`kind.${name}`)}</Text>;
}
return (
<Stack align="center" gap="0">
<Text fz="24px">{formatWeatherDate(time, locale, dateFormat)}</Text>
<Text fz="16px">{t(`kind.${name}`)}</Text>
<Text fz="xl">{formatWeatherDate(time, locale, dateFormat)}</Text>
<Text fz="md">{t(`kind.${name}`)}</Text>
<List>
<List.Item icon={<IconTemperaturePlus size="var(--mantine-font-size-sm)" />}>{`${tCommon("information.max")}: ${maxTemp}`}</List.Item>
<List.Item icon={<IconTemperatureMinus size="var(--mantine-font-size-sm)" />}>{`${tCommon("information.min")}: ${minTemp}`}</List.Item>
<List.Item icon={<IconSun size="var(--mantine-font-size-sm)" />}>{`${t("dailyForecast.sunrise")}: ${sunrise}`}</List.Item>
<List.Item icon={<IconMoon size="var(--mantine-font-size-sm)" />}>{`${t("dailyForecast.sunset")}: ${sunset}`}</List.Item>
<List.Item
icon={<IconTemperaturePlus size="var(--mantine-font-size-sm)" />}
>{`${tCommon("information.max")}: ${maxTemp}`}</List.Item>
<List.Item
icon={<IconTemperatureMinus size="var(--mantine-font-size-sm)" />}
>{`${tCommon("information.min")}: ${minTemp}`}</List.Item>
<List.Item
icon={<IconSun size="var(--mantine-font-size-sm)" />}
>{`${t("dailyForecast.sunrise")}: ${sunrise}`}</List.Item>
<List.Item
icon={<IconMoon size="var(--mantine-font-size-sm)" />}
>{`${t("dailyForecast.sunset")}: ${sunset}`}</List.Item>
{humidity !== undefined && (
<List.Item icon={<IconDroplets size="var(--mantine-font-size-sm)" />}>{t("dailyForecast.humidity", { humidity })}</List.Item>
<List.Item icon={<IconDroplets size="var(--mantine-font-size-sm)" />}>
{t("dailyForecast.humidity", { humidity })}
</List.Item>
)}
{maxWindSpeed !== undefined && (
<List.Item icon={<IconWind size="var(--mantine-font-size-sm)" />}>
+6 -3
View File
@@ -9,6 +9,7 @@ export const { definition, componentLoader } = createWidgetDefinition("weather",
icon: IconCloud,
supportsAdvancedFocus: true,
queryKey: [["widget", "weather", "atLocation"]],
refetchInterval: 600,
queryMatcher: ({ input }, scope) => {
const location = scope.options.location;
if (location === null || typeof location !== "object" || !("latitude" in location) || !("longitude" in location)) {
@@ -24,6 +25,8 @@ export const { definition, componentLoader } = createWidgetDefinition("weather",
(factory) => ({
isFormatFahrenheit: factory.switch(),
disableTemperatureDecimals: factory.switch(),
animateIcons: factory.switch(),
showHumidity: factory.switch({ defaultValue: true, withDescription: true }),
showCurrentWindSpeed: factory.switch({ withDescription: true }),
useImperialSpeed: factory.switch(),
location: factory.location({
@@ -47,10 +50,10 @@ export const { definition, componentLoader } = createWidgetDefinition("weather",
defaultValue: "dddd, MMMM D",
withDescription: true,
}),
showCity: factory.switch(),
hasForecast: factory.switch(),
showCity: factory.switch({ defaultValue: true }),
hasForecast: factory.switch({ defaultValue: true }),
forecastDayCount: factory.slider({
defaultValue: 5,
defaultValue: 3,
validate: z.number().min(1).max(7),
step: 1,
withDescription: true,
+69
View File
@@ -0,0 +1,69 @@
export type CompactWeatherTier = "micro" | "compact" | "standard" | "roomy";
export interface CompactWeatherLayout {
tier: CompactWeatherTier;
forecastDays: number;
showCity: boolean;
showCondition: boolean;
showHighLow: boolean;
showSecondary: boolean;
}
const compactWeatherBreakpoints = [
{ tier: "roomy", minWidth: 500, minHeight: 280 },
{ tier: "standard", minWidth: 280, minHeight: 180 },
{ tier: "compact", minWidth: 160, minHeight: 120 },
{ tier: "micro", minWidth: 0, minHeight: 0 },
] as const satisfies readonly { tier: CompactWeatherTier; minWidth: number; minHeight: number }[];
export const getCompactWeatherLayout = (
width: number,
height: number,
hasForecast: boolean,
configuredDays: number,
): CompactWeatherLayout => {
const breakpoint = compactWeatherBreakpoints.find(
({ minHeight, minWidth }) => width >= minWidth && height >= minHeight,
);
const tier = breakpoint?.tier ?? "micro";
if (tier === "micro") {
return {
tier: "micro",
forecastDays: 0,
showCity: false,
showCondition: false,
showHighLow: false,
showSecondary: false,
};
}
if (tier === "compact") {
return {
tier: "compact",
forecastDays: hasForecast ? Math.min(configuredDays, Math.max(1, Math.floor(width / 92))) : 0,
showCity: width >= 220,
showCondition: true,
showHighLow: true,
showSecondary: false,
};
}
const availableForecastWidth = Math.max(0, width - 24);
return {
tier,
forecastDays: hasForecast ? Math.min(configuredDays, Math.max(1, Math.floor(availableForecastWidth / 64))) : 0,
showCity: true,
showCondition: true,
showHighLow: true,
showSecondary: true,
};
};
export const getAdvancedWeatherLayout = (width: number, height: number) => ({
chartHeight: height >= 520 ? 200 : 150,
dailyColumns: width >= 700 ? 4 : width >= 480 ? 3 : width >= 320 ? 2 : 1,
hourlyTickStep: width >= 520 ? 3 : 6,
metricColumns: width >= 700 ? 3 : width >= 420 ? 2 : 1,
showChartAxes: width >= 520,
});