Skip to content

Commit

Permalink
Simplify and improve handling of entity value display (#208, #212)
Browse files Browse the repository at this point in the history
  • Loading branch information
benct committed Dec 17, 2021
1 parent c0a41ad commit 00bdbde
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 82 deletions.
82 changes: 31 additions & 51 deletions src/entity.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { computeEntity, computeStateDomain, formatDate, formatDateTime, formatTime } from 'custom-card-helpers';
import { computeEntity, computeStateDisplay, formatNumber, secondsToDuration } from 'custom-card-helpers';
import { isObject, isUnavailable } from './util';

export const checkEntity = (config) => {
Expand All @@ -20,67 +20,47 @@ export const entityName = (stateObj, config) => {
);
};

export const entityValue = (stateObj, config) =>
config.attribute !== undefined ? stateObj.attributes[config.attribute] : stateObj.state;

export const entityUnit = (stateObj, config) =>
config.unit === false
? null
: config.attribute !== undefined
? config.unit
: config.unit || stateObj.attributes.unit_of_measurement;

export const entityStateDisplay = (hass, stateObj, config) => {
if (isUnavailable(stateObj)) {
return hass.localize(`state.default.${stateObj.state}`);
}

const domain = computeStateDomain(stateObj);
const computeDisplay = (value) =>
(stateObj.attributes.device_class &&
hass.localize(`component.${domain}.state.${stateObj.attributes.device_class}.${value}`)) ||
hass.localize(`component.${domain}.state._.${value}`) ||
value;

if (config.attribute) {
return config.attribute in stateObj.attributes
? `${computeDisplay(stateObj.attributes[config.attribute])}${config.unit ? ` ${config.unit}` : ''}`
: hass.localize('state.default.unavailable');
}

if (config.unit !== false && (config.unit || stateObj.attributes.unit_of_measurement)) {
return `${stateObj.state} ${config.unit || stateObj.attributes.unit_of_measurement}`;
}
const value = config.attribute ? stateObj.attributes[config.attribute] : stateObj.state;
const unit =
config.unit === false
? undefined
: config.attribute !== undefined
? config.unit
: config.unit || stateObj.attributes.unit_of_measurement;

if (domain === 'input_datetime') {
let date;
if (!stateObj.attributes.has_time) {
date = new Date(stateObj.attributes.year, stateObj.attributes.month - 1, stateObj.attributes.day);
return formatDate(date, hass.language);
if (config.format) {
if (isNaN(parseFloat(value)) || !isFinite(value)) {
return value;
}
if (config.format === 'brightness') {
return `${Math.round((value / 255) * 100)} %`;
}
if (config.format === 'duration') {
return secondsToDuration(value);
}
if (!stateObj.attributes.has_date) {
const now = new Date();
date = new Date(
now.getFullYear(),
now.getMonth(),
now.getDay(),
stateObj.attributes.hour,
stateObj.attributes.minute
);
return formatTime(date, hass.language);
if (config.format.startsWith('precision')) {
const precision = parseInt(config.format.slice(-1), 10);
const formatted = formatNumber(parseFloat(value), hass.language, {
minimumFractionDigits: precision,
maximumFractionDigits: precision,
});
return `${formatted}${unit ? ` ${unit}` : ''}`;
}
return value;
}

date = new Date(
stateObj.attributes.year,
stateObj.attributes.month - 1,
stateObj.attributes.day,
stateObj.attributes.hour,
stateObj.attributes.minute
);
return formatDateTime(date, hass.language);
if (config.attribute) {
return `${isNaN(value) ? value : formatNumber(value, hass.language)}${unit ? ` ${unit}` : ''}`;
}

return computeDisplay(stateObj.state);
const modifiedStateObj = { ...stateObj, attributes: { ...stateObj.attributes, unit_of_measurement: unit } };

return computeStateDisplay(hass.localize, modifiedStateObj, hass.language);
};

export const entityStyles = (config) =>
Expand Down
40 changes: 9 additions & 31 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { LitElement, html, css } from 'lit';
import { handleClick, secondsToDuration, formatNumber } from 'custom-card-helpers';
import { css, html, LitElement } from 'lit';
import { handleClick } from 'custom-card-helpers';

import { checkEntity, entityName, entityStateDisplay, entityStyles, entityUnit, entityValue } from './entity';
import { getEntityIds, hasConfigOrEntitiesChanged, hasGenericSecondaryInfo, isObject, hideUnavailable } from './util';
import { checkEntity, entityName, entityStateDisplay, entityStyles } from './entity';
import { getEntityIds, hasConfigOrEntitiesChanged, hasGenericSecondaryInfo, hideUnavailable, isObject } from './util';
import { style } from './styles';

console.info(
Expand Down Expand Up @@ -118,42 +118,20 @@ class MultipleEntityRow extends LitElement {
if (config.toggle === true) {
return html`<ha-entity-toggle .stateObj="${stateObj}" .hass="${this._hass}"></ha-entity-toggle>`;
}
if (config.format) {
return this.renderFormat(stateObj, config);
}
return entityStateDisplay(this._hass, stateObj, config);
}

renderFormat(stateObj, config) {
const value = entityValue(stateObj, config);

if (['relative', 'total', 'date', 'time', 'datetime'].includes(config.format)) {
if (config.format && ['relative', 'total', 'date', 'time', 'datetime'].includes(config.format)) {
const value = config.attribute ? stateObj.attributes[config.attribute] : stateObj.state;
const timestamp = new Date(value);
if (!(timestamp instanceof Date) || isNaN(timestamp.getTime())) {
return value;
}
return html`<hui-timestamp-display
.hass=${this._hass}
.ts=${timestamp}
.format=${config.format}
.hass=${this._hass}
capitalize
></hui-timestamp-display>`;
}
if (isNaN(parseFloat(value)) || !isFinite(value)) {
return value;
}
if (config.format === 'brightness') {
return `${Math.round((value / 255) * 100)} %`;
}
if (config.format === 'duration') {
return secondsToDuration(value);
}
if (config.format.startsWith('precision')) {
const unit = entityUnit(stateObj, config);
const precision = parseInt(config.format.slice(-1), 10);
const formatted = formatNumber(parseFloat(value).toFixed(precision), this._hass.language);
return `${formatted}${unit ? ` ${unit}` : ''}`;
}
return value;
return entityStateDisplay(this._hass, stateObj, config);
}

renderIcon(stateObj, config) {
Expand Down

0 comments on commit 00bdbde

Please sign in to comment.