Get state translations from backend (#5581)

* Get state translations from backend

* Fix tests
This commit is contained in:
Paulus Schoutsen 2020-04-21 08:15:13 -07:00 committed by GitHub
parent b4b90ca59d
commit d27a17cf8e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 52 additions and 104 deletions

View File

@ -4,32 +4,24 @@ import { formatDateTime } from "../datetime/format_date_time";
import { formatTime } from "../datetime/format_time"; import { formatTime } from "../datetime/format_time";
import { LocalizeFunc } from "../translations/localize"; import { LocalizeFunc } from "../translations/localize";
import { computeStateDomain } from "./compute_state_domain"; import { computeStateDomain } from "./compute_state_domain";
import { UNKNOWN, UNAVAILABLE } from "../../data/entity";
export const computeStateDisplay = ( export const computeStateDisplay = (
localize: LocalizeFunc, localize: LocalizeFunc,
stateObj: HassEntity, stateObj: HassEntity,
language: string language: string
): string => { ): string => {
let display: string | undefined; if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
return localize(`state.default.${stateObj.state}`);
}
if (stateObj.attributes.unit_of_measurement) {
return `${stateObj.state} ${stateObj.attributes.unit_of_measurement}`;
}
const domain = computeStateDomain(stateObj); const domain = computeStateDomain(stateObj);
if (domain === "binary_sensor") { if (domain === "input_datetime") {
// Try device class translation, then default binary sensor translation
if (stateObj.attributes.device_class) {
display = localize(
`state.${domain}.${stateObj.attributes.device_class}.${stateObj.state}`
);
}
if (!display) {
display = localize(`state.${domain}.default.${stateObj.state}`);
}
} else if (
stateObj.attributes.unit_of_measurement &&
!["unknown", "unavailable"].includes(stateObj.state)
) {
display = stateObj.state + " " + stateObj.attributes.unit_of_measurement;
} else if (domain === "input_datetime") {
let date: Date; let date: Date;
if (!stateObj.attributes.has_time) { if (!stateObj.attributes.has_time) {
date = new Date( date = new Date(
@ -37,8 +29,9 @@ export const computeStateDisplay = (
stateObj.attributes.month - 1, stateObj.attributes.month - 1,
stateObj.attributes.day stateObj.attributes.day
); );
display = formatDate(date, language); return formatDate(date, language);
} else if (!stateObj.attributes.has_date) { }
if (!stateObj.attributes.has_date) {
const now = new Date(); const now = new Date();
date = new Date( date = new Date(
// Due to bugs.chromium.org/p/chromium/issues/detail?id=797548 // Due to bugs.chromium.org/p/chromium/issues/detail?id=797548
@ -49,38 +42,22 @@ export const computeStateDisplay = (
stateObj.attributes.hour, stateObj.attributes.hour,
stateObj.attributes.minute stateObj.attributes.minute
); );
display = formatTime(date, language); return formatTime(date, language);
} else {
date = new Date(
stateObj.attributes.year,
stateObj.attributes.month - 1,
stateObj.attributes.day,
stateObj.attributes.hour,
stateObj.attributes.minute
);
display = formatDateTime(date, language);
} }
} else if (domain === "zwave") {
if (["initializing", "dead"].includes(stateObj.state)) { date = new Date(
display = localize( stateObj.attributes.year,
`state.zwave.query_stage.${stateObj.state}`, stateObj.attributes.month - 1,
"query_stage", stateObj.attributes.day,
stateObj.attributes.query_stage stateObj.attributes.hour,
); stateObj.attributes.minute
} else { );
display = localize(`state.zwave.default.${stateObj.state}`); return formatDateTime(date, language);
}
} else {
display = localize(`state.${domain}.${stateObj.state}`);
} }
// Fall back to default, component backend translation, or raw state if nothing else matches. const deviceClass = stateObj.attributes.device_class || "_";
if (!display) { return (
display = localize(`component.${domain}.state.${deviceClass}.${stateObj.state}`) ||
localize(`state.default.${stateObj.state}`) || stateObj.state
localize(`component.${domain}.state.${stateObj.state}`) || );
stateObj.state;
}
return display;
}; };

View File

@ -18,6 +18,7 @@ import { stateIcon } from "../../common/entity/state_icon";
import { timerTimeRemaining } from "../../common/entity/timer_time_remaining"; import { timerTimeRemaining } from "../../common/entity/timer_time_remaining";
import { HomeAssistant } from "../../types"; import { HomeAssistant } from "../../types";
import "../ha-label-badge"; import "../ha-label-badge";
import { computeStateDisplay } from "../../common/entity/compute_state_display";
@customElement("ha-state-label-badge") @customElement("ha-state-label-badge")
export class HaStateLabelBadge extends LitElement { export class HaStateLabelBadge extends LitElement {
@ -108,8 +109,13 @@ export class HaStateLabelBadge extends LitElement {
default: default:
return state.state === "unknown" return state.state === "unknown"
? "-" ? "-"
: this.hass!.localize(`component.${domain}.state.${state.state}`) || : state.attributes.unit_of_measurement
state.state; ? state.state
: computeStateDisplay(
this.hass!.localize,
state,
this.hass!.language
);
} }
} }

View File

@ -92,7 +92,7 @@ class HaConfigZwave extends LocalizeMixin(EventsMixin(PolymerElement)) {
on-click="_backTapped" on-click="_backTapped"
></ha-paper-icon-button-arrow-prev> ></ha-paper-icon-button-arrow-prev>
<div main-title=""> <div main-title="">
[[localize('ui.panel.config.zwave.caption')]] [[localize('component.zwave.title')]]
</div> </div>
</app-toolbar> </app-toolbar>
</app-header> </app-header>

View File

@ -59,7 +59,7 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
}); });
this.hass!.connection.subscribeEvents( this.hass!.connection.subscribeEvents(
debounce(() => { debounce(() => {
this._refetchCachedHassTranslations(false); this._refetchCachedHassTranslations(false, false);
}, 500), }, 500),
"component_loaded" "component_loaded"
); );
@ -68,7 +68,7 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
protected hassReconnected() { protected hassReconnected() {
super.hassReconnected(); super.hassReconnected();
this._refetchCachedHassTranslations(true); this._refetchCachedHassTranslations(true, false);
this._applyTranslations(this.hass!); this._applyTranslations(this.hass!);
} }
@ -94,7 +94,7 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
saveTranslationPreferences(this.hass, { language }); saveTranslationPreferences(this.hass, { language });
} }
this._applyTranslations(this.hass); this._applyTranslations(this.hass);
this._refetchCachedHassTranslations(true); this._refetchCachedHassTranslations(true, true);
} }
private _applyTranslations(hass: HomeAssistant) { private _applyTranslations(hass: HomeAssistant) {
@ -227,10 +227,16 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
this._updateHass(changes); this._updateHass(changes);
} }
private _refetchCachedHassTranslations(includeConfigFlow: boolean) { private _refetchCachedHassTranslations(
includeConfigFlow: boolean,
clearIntegrations: boolean
) {
for (const [category, cache] of Object.entries( for (const [category, cache] of Object.entries(
this.__loadedTranslations this.__loadedTranslations
)) { )) {
if (clearIntegrations) {
cache.integrations = [];
}
if (cache.setup) { if (cache.setup) {
this._loadHassTranslations( this._loadHassTranslations(
this.hass!.language, this.hass!.language,

View File

@ -1755,7 +1755,6 @@
} }
}, },
"zwave": { "zwave": {
"caption": "Z-Wave",
"description": "Manage your Z-Wave network", "description": "Manage your Z-Wave network",
"learn_more": "Learn more about Z-Wave", "learn_more": "Learn more about Z-Wave",
"common": { "common": {

View File

@ -14,7 +14,7 @@ describe("computeStateDisplay", () => {
}; };
assert.strictEqual( assert.strictEqual(
computeStateDisplay(localize, stateObj, "en"), computeStateDisplay(localize, stateObj, "en"),
"state.binary_sensor.default.off" "component.binary_sensor.state._.off"
); );
}); });
@ -28,7 +28,7 @@ describe("computeStateDisplay", () => {
}; };
assert.strictEqual( assert.strictEqual(
computeStateDisplay(localize, stateObj, "en"), computeStateDisplay(localize, stateObj, "en"),
"state.binary_sensor.moisture.off" "component.binary_sensor.state.moisture.off"
); );
}); });
@ -48,7 +48,7 @@ describe("computeStateDisplay", () => {
}; };
assert.strictEqual( assert.strictEqual(
computeStateDisplay(altLocalize, stateObj, "en"), computeStateDisplay(altLocalize, stateObj, "en"),
"state.binary_sensor.default.off" "component.binary_sensor.state.invalid_device_class.off"
); );
}); });
@ -105,7 +105,7 @@ describe("computeStateDisplay", () => {
it("Localizes sensor value with component translation", () => { it("Localizes sensor value with component translation", () => {
const altLocalize = (message, ...args) => { const altLocalize = (message, ...args) => {
if (message !== "component.sensor.state.custom_state") { if (message !== "component.sensor.state._.custom_state") {
return ""; return "";
} }
return localize(message, ...args); return localize(message, ...args);
@ -117,7 +117,7 @@ describe("computeStateDisplay", () => {
}; };
assert.strictEqual( assert.strictEqual(
computeStateDisplay(altLocalize, stateObj, "en"), computeStateDisplay(altLocalize, stateObj, "en"),
"component.sensor.state.custom_state" "component.sensor.state._.custom_state"
); );
}); });
@ -184,46 +184,6 @@ describe("computeStateDisplay", () => {
); );
}); });
it("Localizes zwave ready", () => {
const stateObj: any = {
entity_id: "zwave.test",
state: "ready",
attributes: {
query_stage: "Complete",
},
};
assert.strictEqual(
computeStateDisplay(localize, stateObj, "en"),
"state.zwave.default.ready"
);
});
it("Localizes zwave initializing", () => {
const stateObj: any = {
entity_id: "zwave.test",
state: "initializing",
attributes: {
query_stage: "Probe",
},
};
assert.strictEqual(
computeStateDisplay(localize, stateObj, "en"),
"state.zwave.query_stage.initializing: query_stage,Probe"
);
});
it("Localizes cover open", () => {
const stateObj: any = {
entity_id: "cover.test",
state: "open",
attributes: {},
};
assert.strictEqual(
computeStateDisplay(localize, stateObj, "en"),
"state.cover.open"
);
});
it("Localizes unavailable", () => { it("Localizes unavailable", () => {
const altLocalize = (message, ...args) => { const altLocalize = (message, ...args) => {
if (message === "state.sensor.unavailable") { if (message === "state.sensor.unavailable") {