Improve stripPrefixFromEntityName to handle colon and space separator (#11691)

This commit is contained in:
Brandon Rothweiler 2022-02-15 04:03:58 -05:00 committed by GitHub
parent 9c8d683a19
commit d049990f04
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 14 deletions

View File

@ -1,24 +1,32 @@
const SUFFIXES = [" ", ": "];
/**
* Strips a device name from an entity name.
* @param entityName the entity name
* @param lowerCasedPrefixWithSpaceSuffix the prefix to strip, lower cased with a space suffix
* @param lowerCasedPrefix the prefix to strip, lower cased
* @returns
*/
export const stripPrefixFromEntityName = (
entityName: string,
lowerCasedPrefixWithSpaceSuffix: string
lowerCasedPrefix: string
) => {
if (!entityName.toLowerCase().startsWith(lowerCasedPrefixWithSpaceSuffix)) {
return undefined;
const lowerCasedEntityName = entityName.toLowerCase();
for (const suffix of SUFFIXES) {
const lowerCasedPrefixWithSuffix = `${lowerCasedPrefix}${suffix}`;
if (lowerCasedEntityName.startsWith(lowerCasedPrefixWithSuffix)) {
const newName = entityName.substring(lowerCasedPrefixWithSuffix.length);
// If first word already has an upper case letter (e.g. from brand name)
// leave as-is, otherwise capitalize the first word.
return hasUpperCase(newName.substr(0, newName.indexOf(" ")))
? newName
: newName[0].toUpperCase() + newName.slice(1);
}
}
const newName = entityName.substring(lowerCasedPrefixWithSpaceSuffix.length);
// If first word already has an upper case letter (e.g. from brand name)
// leave as-is, otherwise capitalize the first word.
return hasUpperCase(newName.substr(0, newName.indexOf(" ")))
? newName
: newName[0].toUpperCase() + newName.slice(1);
return undefined;
};
const hasUpperCase = (str: string): boolean => str.toLowerCase() !== str;

View File

@ -165,7 +165,7 @@ export class HaDeviceEntitiesCard extends LitElement {
const stateObj = this.hass.states[entry.entity_id];
const name = stripPrefixFromEntityName(
computeStateName(stateObj),
`${this.deviceName} `.toLowerCase()
this.deviceName.toLowerCase()
);
if (name) {
config.name = name;
@ -198,7 +198,7 @@ export class HaDeviceEntitiesCard extends LitElement {
${name
? stripPrefixFromEntityName(
name,
`${this.deviceName} `.toLowerCase()
this.deviceName.toLowerCase()
) || name
: entry.entity_id}
</div>

View File

@ -97,7 +97,7 @@ export const computeCards = (
const entities: Array<string | LovelaceRowConfig> = [];
const titlePrefix = entityCardOptions.title
? `${entityCardOptions.title} `.toLowerCase()
? entityCardOptions.title.toLowerCase()
: undefined;
const footerEntities: ButtonsHeaderFooterConfig["entities"] = [];