Format number attribute for media player (#18949)

This commit is contained in:
Paul Bottein 2023-12-08 10:14:55 +01:00 committed by GitHub
parent 80edeebab9
commit b855b3e103
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 9 deletions

View File

@ -1,5 +1,6 @@
import { HassConfig, HassEntity } from "home-assistant-js-websocket";
import {
DOMAIN_ATTRIBUTES_FORMATERS,
DOMAIN_ATTRIBUTES_UNITS,
TEMPERATURE_ATTRIBUTES,
} from "../../data/entity_attributes";
@ -14,11 +15,10 @@ import { formatNumber } from "../number/format_number";
import { capitalizeFirstLetter } from "../string/capitalize-first-letter";
import { isDate } from "../string/is_date";
import { isTimestamp } from "../string/is_timestamp";
import { blankBeforePercent } from "../translations/blank_before_percent";
import { blankBeforeUnit } from "../translations/blank_before_unit";
import { LocalizeFunc } from "../translations/localize";
import { computeDomain } from "./compute_domain";
import { computeStateDomain } from "./compute_state_domain";
import { blankBeforeUnit } from "../translations/blank_before_unit";
export const computeAttributeValueDisplay = (
localize: LocalizeFunc,
@ -39,19 +39,18 @@ export const computeAttributeValueDisplay = (
// Number value, return formatted number
if (typeof attributeValue === "number") {
const formattedValue = formatNumber(attributeValue, locale);
const domain = computeStateDomain(stateObj);
const formatter = DOMAIN_ATTRIBUTES_FORMATERS[domain]?.[attribute];
const formattedValue = formatter
? formatter(attributeValue, locale)
: formatNumber(attributeValue, locale);
let unit = DOMAIN_ATTRIBUTES_UNITS[domain]?.[attribute] as
| string
| undefined;
if (domain === "light" && attribute === "brightness") {
const percentage = Math.round((attributeValue / 255) * 100);
return `${percentage}${blankBeforePercent(locale)}%`;
}
if (domain === "weather") {
unit = getWeatherUnit(config, stateObj as WeatherEntity, attribute);
}

View File

@ -1,3 +1,6 @@
import { formatDuration } from "../common/datetime/duration";
import { FrontendLocaleData } from "./translation";
export const STATE_ATTRIBUTES = [
"entity_id",
"assumed_state",
@ -64,6 +67,7 @@ export const DOMAIN_ATTRIBUTES_UNITS = {
color_temp_kelvin: "K",
min_color_temp_kelvin: "K",
max_color_temp_kelvin: "K",
brightness: "%",
},
sun: {
elevation: "°",
@ -74,4 +78,22 @@ export const DOMAIN_ATTRIBUTES_UNITS = {
sensor: {
battery_level: "%",
},
media_player: {
volume_level: "%",
},
} as const satisfies Record<string, Record<string, string>>;
type Formatter = (value: number, locale: FrontendLocaleData) => string;
export const DOMAIN_ATTRIBUTES_FORMATERS: Record<
string,
Record<string, Formatter>
> = {
light: {
brightness: (value) => Math.round((value / 255) * 100).toString(),
},
media_player: {
volume_level: (value) => Math.round(value * 100).toString(),
media_duration: (value) => formatDuration(value.toString(), "s"),
},
};