feat: add temperature unit preference
This commit is contained in:
@@ -11,12 +11,19 @@ import type {
|
||||
import { translate, type Language } from "@/lib/i18n";
|
||||
import { getProvinceFromTeryt, normalizeProvinceName } from "@/lib/provinces";
|
||||
import type { CurrentWeatherCondition } from "@/types/imgw-current";
|
||||
import type { WindSpeedUnit } from "@/types/units";
|
||||
import type { TemperatureUnit, WindSpeedUnit } from "@/types/units";
|
||||
|
||||
const locales: Record<Language, string> = { pl: "pl-PL", en: "en-GB" };
|
||||
export const DEFAULT_TEMPERATURE_UNIT: TemperatureUnit = "c";
|
||||
export const TEMPERATURE_UNITS: TemperatureUnit[] = ["c", "f"];
|
||||
export const DEFAULT_WIND_SPEED_UNIT: WindSpeedUnit = "ms";
|
||||
export const WIND_SPEED_UNITS: WindSpeedUnit[] = ["ms", "kmh", "mph"];
|
||||
|
||||
const temperatureUnitLabels: Record<TemperatureUnit, string> = {
|
||||
c: "°C",
|
||||
f: "°F",
|
||||
};
|
||||
|
||||
const windSpeedUnitLabels: Record<WindSpeedUnit, string> = {
|
||||
ms: "m/s",
|
||||
kmh: "km/h",
|
||||
@@ -105,8 +112,28 @@ export function normalizeWarning(raw: RawWarning, kind: WarningKind, index: numb
|
||||
};
|
||||
}
|
||||
|
||||
export function formatTemperature(value: number | null, language: Language = "pl") {
|
||||
return value === null ? translate(language, "common.noData") : `${Math.round(value)}°`;
|
||||
export function isTemperatureUnit(value: unknown): value is TemperatureUnit {
|
||||
return typeof value === "string" && TEMPERATURE_UNITS.includes(value as TemperatureUnit);
|
||||
}
|
||||
|
||||
export function getTemperatureUnitLabel(unit: TemperatureUnit) {
|
||||
return temperatureUnitLabels[unit];
|
||||
}
|
||||
|
||||
export function convertTemperature(value: number, unit: TemperatureUnit) {
|
||||
if (unit === "f") return (value * 9) / 5 + 32;
|
||||
return value;
|
||||
}
|
||||
|
||||
export function formatTemperatureValue(value: number, language: Language = "pl", unit: TemperatureUnit = DEFAULT_TEMPERATURE_UNIT) {
|
||||
const formattedValue = new Intl.NumberFormat(locales[language], {
|
||||
maximumFractionDigits: 0,
|
||||
}).format(value);
|
||||
return `${formattedValue}${getTemperatureUnitLabel(unit)}`;
|
||||
}
|
||||
|
||||
export function formatTemperature(value: number | null, language: Language = "pl", unit: TemperatureUnit = DEFAULT_TEMPERATURE_UNIT) {
|
||||
return value === null ? translate(language, "common.noData") : formatTemperatureValue(convertTemperature(value, unit), language, unit);
|
||||
}
|
||||
|
||||
export function formatPressure(value: number | null, language: Language = "pl") {
|
||||
|
||||
Reference in New Issue
Block a user