feat!: release v2 (#6545)

Co-authored-by: Artur <145776561+arturict@users.noreply.github.com>
Co-authored-by: arturict <arturict@users.noreply.github.com>
Co-authored-by: Thomas <thomas@ajnart.fr>
Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com>
Co-authored-by: Danura30082 <danura30082+github@gmail.com>
Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com>
Co-authored-by: ajnart <thomas@ajnart.fr>
Co-authored-by: ajnart <thomas@ajnart.dev>
Co-authored-by: chenjun <chenjun@foxmail.com>
Co-authored-by: Wikibear <wikibear@users.noreply.github.com>
Co-authored-by: Bergasha <bergasha@gmail.com>
Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com>
Co-authored-by: Lucas Araujo <lucas.lra@gmail.com>
Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com>
Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social>
Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com>
Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com>
Co-authored-by: thrawnx <tight.bulb9384@fastmail.com>
Co-authored-by: Chris <58918656+nordada@users.noreply.github.com>
Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com>
Co-authored-by: Yanis <naamaneyanis@gmail.com>
Co-authored-by: Wikibear <me@sej.de>
Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386 -139176

No files matched your search

+445
View File
@@ -0,0 +1,445 @@
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, useI18n } from "@homarr/translation/client";
import { iconSizes, zoomCompensatedSize } from "@homarr/ui";
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 = useI18n("widget.weather");
const tCommon = useI18n("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%">
<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 style={iconSizes.lg} aria-hidden />}
label={t("advanced.nextHourPrecipitation")}
value={t("advanced.precipitationValue", {
amount: nextHour?.precipitation?.toFixed(1) ?? "?",
probability: nextHour?.precipitationProbability ?? "?",
})}
/>
{options.showHumidity && (
<MetricCard
icon={<IconDroplets style={iconSizes.lg} aria-hidden />}
label={t("advanced.currentHumidity")}
value={`${weather.current.relativeHumidity}%`}
/>
)}
<MetricCard
icon={<IconWind style={iconSizes.lg} 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 style={iconSizes.lg} aria-hidden />}
label={t("advanced.todayUv")}
value={today?.uvIndex?.toFixed(1) ?? "?"}
/>
<MetricCard
icon={<IconSunrise style={iconSizes.lg} aria-hidden />}
label={t("dailyForecast.sunrise")}
value={getPreferredTime(today?.sunriseAt, locale, weather.timezone)}
/>
<MetricCard
icon={<IconSunset style={iconSizes.lg} 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}
style={zoomCompensatedSize(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 style={iconSizes.sm} aria-hidden />
<Text className={classes.dailyCardFact} fz={11}>
{day.precipitationProbability ?? "?"}%
</Text>
</Group>
<Group gap={3} wrap="nowrap">
<IconWind style={iconSizes.sm} 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 = useI18n("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>
);
};
+10 -5
View File
@@ -1,13 +1,17 @@
import type { CSSProperties } from "react";
import "../widgets-common.css";
import { WeatherIcon } from "./icon";
interface AnimatedWeatherIconProps {
animated?: boolean;
code: number;
isDay?: boolean;
size?: string | number;
style?: CSSProperties;
}
const getAnimationClass = (code: number): string => {
if (code === 0) return "weather-anim-sun";
if ([1, 2, 3].includes(code)) return "weather-anim-cloud";
@@ -18,11 +22,12 @@ const getAnimationClass = (code: number): string => {
return "";
};
export const AnimatedWeatherIcon = ({ code, size = 26 }: AnimatedWeatherIconProps) => {
export const AnimatedWeatherIcon = ({ animated = false, code, isDay, size = 26, style }: 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}`} data-is-day={isDay === false ? "false" : "true"}>
<WeatherIcon code={code} isDay={isDay} size={size} style={style} />
</span>
);
};
+178
View File
@@ -0,0 +1,178 @@
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, useI18n } from "@homarr/translation/client";
import { zoomCompensatedSize } from "@homarr/ui";
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 = useI18n("widget.weather");
const tCommon = useI18n("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}
style={zoomCompensatedSize(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}
style={zoomCompensatedSize(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>
);
};
@@ -0,0 +1,135 @@
.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: transparent;
border: 0.0625rem solid rgb(from var(--mantine-color-secondaryColor-filled) r g b / calc(var(--opacity, 1) * 0.45));
}
.dailyCard {
transition:
background-color 120ms ease,
border-color 120ms ease;
}
.dailyCardButton:hover .dailyCard,
.dailyCardButton:focus-visible .dailyCard {
background-color: transparent;
border-color: rgb(from var(--mantine-color-secondaryColor-filled) r g b / calc(var(--opacity, 1) * 0.72));
}
.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: transparent;
}
.detailsButton,
.forecastButton,
.dailyCardButton {
color: inherit;
border-radius: var(--mantine-radius-sm);
}
.detailsButton {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 1.5rem;
min-height: 1.5rem;
}
.forecastButton,
.dailyCardButton {
display: block;
}
.dailyCardButton,
.dailyCard {
width: 100%;
height: 100%;
}
.detailsButton:focus-visible,
.forecastButton:focus-visible,
.dailyCardButton:focus-visible {
outline: 0.125rem solid var(--mantine-primary-color-filled);
outline-offset: 0.125rem;
}
@media (any-pointer: coarse) {
.detailsButton,
.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;
}
}
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
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 values", () => {
expect(getPreferredUnit(0)).toBe("0.0°C");
expect(getPreferredUnit(0, true, true)).toBe("32°F");
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.each([
["dddd, MMMM D", "Monday, August 3"],
["dddd, D MMMM", "Monday, 3 August"],
["MMM D", "Aug 3"],
["D MMM", "3 Aug"],
["DD/MM/YYYY", "03/08/2026"],
["MM/DD/YYYY", "08/03/2026"],
["DD/MM", "03/08"],
["MM/DD", "08/03"],
] as const)("honors the saved %s date format", (pattern, expected) => {
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 minimal and static while preserving saved false values", () => {
const options = definition.createOptions();
expect(options.showCity.defaultValue).toBe(false);
expect(options.hasForecast.defaultValue).toBe(false);
expect(options.forecastDayCount.defaultValue).toBe(3);
expect(options.animateIcons.defaultValue).toBe(false);
expect(options.showHumidity.defaultValue).toBe(false);
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,
});
});
});
+34 -210
View File
@@ -1,228 +1,52 @@
"use client";
import { Box, Group, HoverCard, Stack, Text } from "@mantine/core";
import { IconArrowDownRight, IconArrowUpRight, IconDroplets, IconMapPin, IconWind } from "@tabler/icons-react";
import combineClasses from "clsx";
import dayjs from "dayjs";
import { Box, Center, Text } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { metricToImperial } from "@homarr/common";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { WidgetEmptyState } from "../common/empty-state";
import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";
import { WidgetQueryLoadingState } from "../common/query-state-indicator";
import type { WidgetComponentProps } from "../definition";
import { AnimatedWeatherIcon } from "./animated-icon";
import { WeatherDescription } from "./icon";
import { AdvancedWeather } from "./advanced";
import classes from "./component.module.css";
import { CompactWeather } from "./compact";
export default function WeatherWidget({ isEditMode, options }: WidgetComponentProps<"weather">) {
export default function WeatherWidget({
isEditMode,
options,
width,
height,
displayMode,
}: WidgetComponentProps<"weather">) {
const t = useI18n("widget.weather");
const input = {
latitude: options.location.latitude,
longitude: options.location.longitude,
};
const { data: weather } = clientApi.widget.weather.atLocation.useQuery(input);
const weatherQuery = clientApi.widget.weather.atLocation.useQuery(input);
const weather = getUsableWidgetQueryData(weatherQuery);
if (!weather) return <WidgetEmptyState />;
return (
<Stack
align="center"
gap="sm"
justify="center"
w="100%"
h="100%"
style={{ pointerEvents: isEditMode ? "none" : undefined }}
>
{options.hasForecast ? (
<WeeklyForecast weather={weather} options={options} />
) : (
<DailyWeather weather={weather} options={options} />
)}
</Stack>
);
}
interface WeatherProps extends Pick<WidgetComponentProps<"weather">, "options"> {
weather: NonNullable<RouterOutputs["widget"]["weather"]["atLocation"]>;
}
const DailyWeather = ({ options, weather }: WeatherProps) => {
const t = useScopedI18n("widget.weather");
const tCommon = useScopedI18n("common");
return (
<>
<Group className="weather-day-group" gap="sm">
<HoverCard>
<HoverCard.Target>
<Box>
<AnimatedWeatherIcon size={30} code={weather.current.weathercode} />
</Box>
</HoverCard.Target>
<HoverCard.Dropdown>
<WeatherDescription weatherOnly weatherCode={weather.current.weathercode} />
</HoverCard.Dropdown>
</HoverCard>
<Text fz={30}>
{getPreferredUnit(
weather.current.temperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
if (isInitialWidgetQueryPending(weatherQuery)) return <WidgetQueryLoadingState />;
if (!weather) {
return (
<Center h="100%" w="100%" p="sm">
<Text c="dimmed" size="sm" ta="center">
{t("disabled")}
</Text>
</Group>
<Stack gap="xs" align="center">
{options.showCurrentWindSpeed && (
<Group className="weather-current-wind-speed-group" wrap="nowrap" gap="xs">
<IconWind size={16} />
<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={16} />
<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={16} />
<Text fz={16}>
{getPreferredUnit(
weather.daily[0]?.maxTemp,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
</Group>
<Group gap="xs" wrap="nowrap">
<IconArrowDownRight size={16} />
<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={16} />
<Text fz={16} style={{ whiteSpace: "nowrap" }}>
{options.location.name}
</Text>
</Group>
</>
)}
</>
);
};
</Center>
);
}
const WeeklyForecast = ({ options, weather }: WeatherProps) => {
return (
<>
<Group className="weather-forecast-city-temp-group" wrap="nowrap" gap="md">
{options.showCity && (
<Group gap="xs" wrap="nowrap">
<IconMapPin size={16} />
<Text fz={16} style={{ whiteSpace: "nowrap" }}>
{options.location.name}
</Text>
</Group>
<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} />
)}
<Group gap="xs" wrap="nowrap">
<HoverCard>
<HoverCard.Target>
<Box>
<AnimatedWeatherIcon size={16} code={weather.current.weathercode} />
</Box>
</HoverCard.Target>
<HoverCard.Dropdown>
<WeatherDescription weatherOnly weatherCode={weather.current.weathercode} />
</HoverCard.Dropdown>
</HoverCard>
<Text fz={16}>
{getPreferredUnit(
weather.current.temperature,
options.isFormatFahrenheit,
options.disableTemperatureDecimals,
)}
</Text>
</Group>
</Group>
<Forecast weather={weather} options={options} />
</>
);
};
function Forecast({ weather, options }: WeatherProps) {
const dateFormat = options.dateFormat;
return (
<Group className="weather-forecast-days-group" w="100%" justify="space-evenly" wrap="nowrap" pb="sm">
{weather.daily.slice(0, options.forecastDayCount).map((dayWeather, index) => (
<HoverCard key={dayWeather.time} withArrow shadow="md">
<HoverCard.Target>
<Stack
className={combineClasses(
"weather-forecast-day-stack",
`weather-forecast-day${index}`,
`weather-forecast-weekday${dayjs(dayWeather.time).day()}`,
)}
gap="0"
align="center"
>
<Text fz="xl">{dayjs(dayWeather.time).format("dd")}</Text>
<AnimatedWeatherIcon size={16} code={dayWeather.weatherCode} />
<Text fz={16}>
{getPreferredUnit(dayWeather.maxTemp, options.isFormatFahrenheit, options.disableTemperatureDecimals)}
</Text>
</Stack>
</HoverCard.Target>
<HoverCard.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={dayjs(dayWeather.sunrise).format("HH:mm")}
sunset={dayjs(dayWeather.sunset).format("HH:mm")}
maxWindSpeed={dayWeather.maxWindSpeed}
maxWindGusts={dayWeather.maxWindGusts}
humidity={dayWeather.humidity}
/>
</HoverCard.Dropdown>
</HoverCard>
))}
</Group>
</Box>
</Box>
);
}
const getPreferredUnit = (value?: number, isFahrenheit = false, disableTemperatureDecimals = false): string =>
value
? isFahrenheit
? `${(value * (9 / 5) + 32).toFixed(disableTemperatureDecimals ? 0 : 1)}°F`
: `${value.toFixed(disableTemperatureDecimals ? 0 : 1)}°C`
: "?";
+162
View File
@@ -0,0 +1,162 @@
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, useI18n } from "@homarr/translation/client";
import { iconSizes, zoomCompensatedSize } from "@homarr/ui";
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 = useI18n("widget.weather");
const tCommon = useI18n("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} style={zoomCompensatedSize(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 style={iconSizes.md} aria-hidden />}
label={t("advanced.detailLabel.feelsLike")}
value={`${getPreferredUnit(day.maxApparentTemperature, isFahrenheit, disableTemperatureDecimals)} / ${getPreferredUnit(day.minApparentTemperature, isFahrenheit, disableTemperatureDecimals)}`}
/>
<DetailMetric
icon={<IconDroplets style={iconSizes.md} aria-hidden />}
label={t("advanced.detailLabel.precipitation")}
value={`${day.precipitationProbability ?? "?"}% · ${day.precipitation?.toFixed(1) ?? "?"} mm`}
/>
{showHumidity && (
<DetailMetric
icon={<IconGauge style={iconSizes.md} aria-hidden />}
label={t("advanced.detailLabel.humidity")}
value={`${day.averageHumidity ?? "?"}%`}
/>
)}
<DetailMetric
icon={<IconWind style={iconSizes.md} aria-hidden />}
label={t("advanced.detailLabel.wind")}
value={`${getPreferredWindSpeed(day.maxWindSpeed, useImperialSpeed)} / ${getPreferredWindSpeed(day.maxWindGusts, useImperialSpeed)} ${speedUnit}`}
/>
<DetailMetric
icon={<IconSunHigh style={iconSizes.md} 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 style={iconSizes.md} aria-hidden />}
label={t("dailyForecast.sunrise")}
value={getPreferredTime(day.sunriseAt, locale, timeZone)}
/>
<SolarMetric
icon={<IconSunset style={iconSizes.md} aria-hidden />}
label={t("dailyForecast.sunset")}
value={getPreferredTime(day.sunsetAt, locale, timeZone)}
/>
<SolarMetric
icon={<IconSunHigh style={iconSizes.md} 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),
}));
+81 -18
View File
@@ -1,3 +1,4 @@
import type { CSSProperties } from "react";
import { List, Stack, Text } from "@mantine/core";
import {
IconCloud,
@@ -14,32 +15,39 @@ import {
IconTemperaturePlus,
IconWind,
} from "@tabler/icons-react";
import dayjs from "dayjs";
import { metricToImperial } from "@homarr/common";
import type { TranslationObject } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
import type { TablerIcon } from "@homarr/ui";
import type { WidgetProps } from "../definition";
interface WeatherIconProps {
code: number;
isDay?: boolean;
size?: string | number;
style?: CSSProperties;
}
/**
* Icon which should be displayed when specific code is defined
* @param code weather code from api
* @param size size of the icon, accepts relative sizes too
* @param style CSS overrides (e.g. from `zoomCompensatedSize`) - prefer this over `size` for a
* board-zoom-safe size, since `size` becomes a raw SVG width/height attribute that `var()` isn't
* guaranteed to resolve inside (see `iconSizes` in @homarr/ui).
* @returns Icon corresponding to the weather code
*/
export const WeatherIcon = ({ code, size = 50 }: WeatherIconProps) => {
export const WeatherIcon = ({ code, isDay = true, size = 50, style }: WeatherIconProps) => {
if (code === 0 && !isDay) return <IconMoon style={{ float: "left", ...style }} size={size} />;
const { icon: Icon } = weatherDefinitions.find((definition) => definition.codes.includes(code)) ?? unknownWeather;
return <Icon style={{ float: "left" }} size={size} />;
return <Icon style={{ float: "left", ...style }} size={size} />;
};
export const getWeatherKind = (code: number) =>
(weatherDefinitions.find((definition) => definition.codes.includes(code)) ?? unknownWeather).name;
interface WeatherDescriptionProps {
weatherOnly?: boolean;
useImperialSpeed?: boolean;
@@ -82,29 +90,40 @@ export const WeatherDescription = ({
maxWindGusts,
humidity,
}: WeatherDescriptionProps) => {
const t = useScopedI18n("widget.weather");
const tCommon = useScopedI18n("common");
const t = useI18n("widget.weather");
const tCommon = useI18n("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">{dayjs(time).format(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={15} />}>{`${tCommon("information.max")}: ${maxTemp}`}</List.Item>
<List.Item icon={<IconTemperatureMinus size={15} />}>{`${tCommon("information.min")}: ${minTemp}`}</List.Item>
<List.Item icon={<IconSun size={15} />}>{`${t("dailyForecast.sunrise")}: ${sunrise}`}</List.Item>
<List.Item icon={<IconMoon size={15} />}>{`${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={15} />}>{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={15} />}>
<List.Item icon={<IconWind size="var(--mantine-font-size-sm)" />}>
{t("dailyForecast.maxWindSpeed", {
maxWindSpeed: (useImperialSpeed ? metricToImperial(maxWindSpeed) : maxWindSpeed).toFixed(1),
unit: useImperialSpeed ? tCommon("unit.speed.milesPerHour") : tCommon("unit.speed.kilometersPerHour"),
@@ -112,7 +131,7 @@ export const WeatherDescription = ({
</List.Item>
)}
{maxWindGusts !== undefined && (
<List.Item icon={<IconWind size={15} />}>
<List.Item icon={<IconWind size="var(--mantine-font-size-sm)" />}>
{t("dailyForecast.maxWindGusts", {
maxWindGusts: (useImperialSpeed ? metricToImperial(maxWindGusts) : maxWindGusts).toFixed(1),
unit: useImperialSpeed ? tCommon("unit.speed.milesPerHour") : tCommon("unit.speed.kilometersPerHour"),
@@ -124,6 +143,50 @@ export const WeatherDescription = ({
);
};
export const formatWeatherDate = (
value: string | undefined,
locale: string,
pattern: WidgetProps<"weather">["options"]["dateFormat"] | undefined,
) => {
if (!value) return "?";
const resolvedPattern = pattern ?? "dddd, MMMM D";
const date = new Date(/^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00Z` : value);
if (Number.isNaN(date.getTime())) return "?";
const parts = new Intl.DateTimeFormat(locale, {
weekday: "long",
year: "numeric",
month: resolvedPattern.includes("MMMM") ? "long" : resolvedPattern.includes("MMM") ? "short" : "2-digit",
day: resolvedPattern.includes("DD") ? "2-digit" : "numeric",
timeZone: "UTC",
})
.formatToParts(date)
.reduce<Record<string, string>>((result, part) => {
if (part.type !== "literal") result[part.type] = part.value;
return result;
}, {});
switch (resolvedPattern) {
case "dddd, D MMMM":
return `${parts.weekday}, ${parts.day} ${parts.month}`;
case "MMM D":
return `${parts.month} ${parts.day}`;
case "D MMM":
return `${parts.day} ${parts.month}`;
case "DD/MM/YYYY":
return `${parts.day}/${parts.month}/${parts.year}`;
case "MM/DD/YYYY":
return `${parts.month}/${parts.day}/${parts.year}`;
case "DD/MM":
return `${parts.day}/${parts.month}`;
case "MM/DD":
return `${parts.month}/${parts.day}`;
case "dddd, MMMM D":
default:
return `${parts.weekday}, ${parts.month} ${parts.day}`;
}
};
interface WeatherDefinitionType {
icon: TablerIcon;
name: keyof TranslationObject["widget"]["weather"]["kind"];
+20 -5
View File
@@ -2,17 +2,32 @@ import { IconCloud } from "@tabler/icons-react";
import dayjs from "dayjs";
import { z } from "zod/v4";
import { createWidgetDefinition } from "../definition";
import { createWidgetDefinition, widgetQueryInputMatches } from "../definition";
import { optionsBuilder } from "../options";
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)) {
return false;
}
return widgetQueryInputMatches(input, {
latitude: location.latitude,
longitude: location.longitude,
});
},
createOptions() {
return optionsBuilder.from(
(factory) => ({
isFormatFahrenheit: factory.switch(),
disableTemperatureDecimals: factory.switch(),
showCurrentWindSpeed: factory.switch({ withDescription: true }),
animateIcons: factory.switch(),
showHumidity: factory.switch({ defaultValue: false }),
showCurrentWindSpeed: factory.switch(),
useImperialSpeed: factory.switch(),
location: factory.location({
defaultValue: {
@@ -35,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: false }),
hasForecast: factory.switch({ defaultValue: false }),
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,
});