Format duration object (#13538)

This commit is contained in:
Bram Kragten 2022-08-31 18:24:24 +02:00 committed by GitHub
parent 229bc26327
commit 030b2b921a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 4 deletions

View File

@ -0,0 +1,28 @@
import { HaDurationData } from "../../components/ha-duration-input";
const leftPad = (num: number) => (num < 10 ? `0${num}` : num);
export const formatDuration = (duration: HaDurationData) => {
const d = duration.days || 0;
const h = duration.hours || 0;
const m = duration.minutes || 0;
const s = duration.seconds || 0;
const ms = duration.milliseconds || 0;
if (d > 0) {
return `${d} days ${h}:${leftPad(m)}:${leftPad(s)}`;
}
if (h > 0) {
return `${h}:${leftPad(m)}:${leftPad(s)}`;
}
if (m > 0) {
return `${m}:${leftPad(s)}`;
}
if (s > 0) {
return `${s} seconds`;
}
if (ms > 0) {
return `${ms} milliseconds`;
}
return null;
};

View File

@ -1,3 +1,4 @@
import { formatDuration } from "../common/datetime/format_duration";
import secondsToDuration from "../common/datetime/seconds_to_duration";
import { ensureArray } from "../common/ensure-array";
import { computeStateName } from "../common/entity/compute_state_name";
@ -98,7 +99,7 @@ export const describeAction = <T extends ActionType>(
computeEntityRegistryName(hass, entityReg) || targetThing
);
} else {
targets.push(targetThing);
targets.push("unknown entity");
}
}
} else if (key === "device_id") {
@ -106,14 +107,14 @@ export const describeAction = <T extends ActionType>(
if (device) {
targets.push(computeDeviceName(device, hass));
} else {
targets.push(targetThing);
targets.push("unknown device");
}
} else if (key === "area_id") {
const area = hass.areas[targetThing];
if (area?.name) {
targets.push(area.name);
} else {
targets.push(targetThing);
targets.push("unknown area");
}
} else {
targets.push(targetThing);
@ -140,7 +141,7 @@ export const describeAction = <T extends ActionType>(
? "based on a template"
: `for ${config.delay}`;
} else {
duration = `for ${JSON.stringify(config.delay)}`;
duration = `for ${formatDuration(config.delay)}`;
}
return `Delay ${duration}`;