Skip to content

Commit 1d2bdae

Browse files
author
Jens Lorenz
committed
fix: refactor to reduce codacy findings
1 parent 999253e commit 1d2bdae

3 files changed

Lines changed: 47 additions & 50 deletions

File tree

src/cards/SummaryCard.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -92,15 +92,14 @@ class Simon42SummaryCard extends LitElement {
9292
private _count = 0;
9393
private _config!: SummaryCardConfig;
9494
private _relevantEntityIds: Set<string> | null = null;
95-
private _batteryPair: { status: BatteryStatus, group: BatteryStatusGroup } | null = null;
95+
private _batteryPair!: { status: BatteryStatus, group: BatteryStatusGroup };
9696

9797
static styles = CSS_STYLES;
9898

9999
setConfig(config: SummaryCardConfig): void {
100100
this._config = config;
101101
this._count = 0;
102102
this._relevantEntityIds = null;
103-
this._batteryPair = null;
104103
}
105104

106105
protected willUpdate(changedProps: PropertyValues): void {
@@ -112,7 +111,6 @@ class Simon42SummaryCard extends LitElement {
112111
if (!oldHass || oldHass.entities !== this.hass.entities) {
113112
this._count = 0;
114113
this._relevantEntityIds = null;
115-
this._batteryPair = null;
116114
debugLog(`summary-${this._config.summary_type}: cache invalidated (registry changed)`);
117115
}
118116

@@ -195,7 +193,7 @@ class Simon42SummaryCard extends LitElement {
195193
this._batteryPair = { status, group };
196194
if (group.entities.length > 0) break;
197195
}
198-
result = this._batteryPair?.group.entities || [];
196+
result = this._batteryPair.group.entities;
199197
break;
200198
}
201199

@@ -298,8 +296,8 @@ class Simon42SummaryCard extends LitElement {
298296
};
299297

300298
case 'batteries': {
301-
const status = this._batteryPair?.status || 'good';
302-
const display = getBatteryStatusDisplay(this._config)[status];
299+
const status = this._batteryPair.status || 'good';
300+
const display = getBatteryStatusDisplay(this._config, status);
303301
return {
304302
icon: display.icon,
305303
name: status !== 'good'

src/utils/battery-utils.ts

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,20 @@ type BatteryConfig = Pick<
2323
* Returns the display configuration for each battery status.
2424
* Thresholds are taken from the config, with defaults if not set.
2525
*/
26-
export function getBatteryStatusDisplay(config: BatteryConfig): Record<BatteryStatus, BatteryStatusDisplay> {
26+
export function getBatteryStatusDisplay(config: BatteryConfig, status: BatteryStatus): BatteryStatusDisplay {
2727
const criticalThreshold = config.battery_critical_threshold ?? 20;
2828
const lowThreshold = config.battery_low_threshold ?? 50;
2929

30-
return {
31-
unknown: { icon: 'mdi:battery-unknown', color: 'white', info: null },
32-
critical: { icon: 'mdi:battery-alert', color: 'red', info: `< ${criticalThreshold}%` },
33-
low: { icon: 'mdi:battery-20', color: 'yellow', info: `${criticalThreshold}% - ${lowThreshold}%` },
34-
good: { icon: 'mdi:battery', color: 'green', info: `> ${lowThreshold}%` },
35-
};
30+
switch (status) {
31+
case 'unknown':
32+
return { icon: 'mdi:battery-unknown', color: 'white', info: null, };
33+
case 'critical':
34+
return { icon: 'mdi:battery-alert', color: 'red', info: `< ${criticalThreshold}%`, };
35+
case 'low':
36+
return { icon: 'mdi:battery-20', color: 'yellow', info: `${criticalThreshold}% - ${lowThreshold}%`, };
37+
case 'good':
38+
return { icon: 'mdi:battery', color: 'green', info: `> ${lowThreshold}%`, };
39+
}
3640
}
3741

3842
export function buildBatteryStatusGroups(hass: HomeAssistant, config: BatteryConfig): Record<BatteryStatus, BatteryStatusGroup> {
@@ -46,26 +50,22 @@ export function buildBatteryStatusGroups(hass: HomeAssistant, config: BatteryCon
4650
const criticalThreshold = config.battery_critical_threshold ?? 20;
4751
const lowThreshold = config.battery_low_threshold ?? 50;
4852

49-
const isBinarySensor = (entityId: string) => entityId.startsWith('binary_sensor.');
50-
const isUnavailableOrUnknown = (state: string) => (state === 'unavailable' || state === 'unknown');
51-
5253
for (const entityId of filterBatteryEntities(hass, config)) {
53-
let key: BatteryStatus;
54+
let group: BatteryStatusGroup;
5455

55-
const state = hass.states[entityId];
56-
if (config.show_unknown_battery_group && isUnavailableOrUnknown(state.state)) {
57-
key = 'unknown';
58-
} else if (isBinarySensor(entityId)) {
59-
key = state.state === 'on' ? 'critical' : 'good';
56+
const state = hass.states[entityId].state;
57+
if (config.show_unknown_battery_group && (state === 'unavailable' || state === 'unknown')) {
58+
group = batteryGroups.unknown;
59+
} else if (entityId.startsWith('binary_sensor.')) {
60+
group = state === 'on' ? batteryGroups.critical : batteryGroups.good;
6061
} else {
61-
const value = parseFloat(state.state);
62-
if (isNaN(value)) key = 'critical';
63-
else if (value < criticalThreshold) key = 'critical';
64-
else if (value <= lowThreshold) key = 'low';
65-
else key = 'good';
62+
const value = parseFloat(state);
63+
if (isNaN(value)) group = batteryGroups.critical;
64+
else if (value < criticalThreshold) group = batteryGroups.critical;
65+
else if (value <= lowThreshold) group = batteryGroups.low;
66+
else group = batteryGroups.good;
6667
}
67-
68-
batteryGroups[key].entities.push(entityId);
68+
group.entities.push(entityId);
6969
}
7070

7171
return batteryGroups;

src/views/BatteriesViewStrategy.ts

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,46 +3,47 @@
33
// ====================================================================
44

55
import type { HomeAssistant } from '../types/homeassistant';
6-
import type { LovelaceViewConfig, LovelaceSectionConfig } from '../types/lovelace';
6+
import type { LovelaceViewConfig, LovelaceSectionConfig, LovelaceCardConfig } from '../types/lovelace';
77
import { Registry } from '../Registry';
88
import { type BatteryStatus, type BatteryStatusGroup, buildBatteryStatusGroups, getBatteryStatusDisplay } from '../utils/battery-utils';
99
import { localize } from '../utils/localize';
1010

1111
type BatteryStatusKeys = BatteryStatus[];
12+
type BatteryStatusKeyList = BatteryStatusKeys[];
1213

1314
/**
1415
* Smart Grid Layout:
1516
* Groups battery status groups into 1-3 grid sections based on their entity counts, to optimize visual balance and minimize empty space.
1617
* - If all groups have very few entities, they are combined into a single section.
1718
* - If one group has significantly more entities than the others, it gets its own section, while smaller groups are combined.
1819
*/
19-
function smartGridGrouping(batteryGroups: Record<BatteryStatus, BatteryStatusGroup>): BatteryStatusKeys[] {
20+
function smartGridGrouping(batteryGroups: Record<BatteryStatus, BatteryStatusGroup>): BatteryStatusKeyList {
2021

2122
// Determine the maximum entity count among groups with entities (ignoring empty groups)
2223
const maxEntities = [...Object.values(batteryGroups)]
2324
.filter((group) => group.entities.length > 0)
2425
.reduce((max, group) => Math.max(max, group.entities.length), 0);
2526

26-
// Loop through each group and assign to grid groups based on count relative to maxEntities
27+
// Loop through each group and assign it to a grid group based on its count relative to maxEntities
2728
let numEntities = 0;
28-
let groupKeys: BatteryStatusKeys[] = [];
29+
let statusKeyList: BatteryStatusKeyList = [];
2930
for (const [key, group] of Object.entries(batteryGroups) as Array<[BatteryStatus, BatteryStatusGroup]>) {
30-
numEntities += group.entities.length;
31-
if (numEntities === 0) continue;
31+
if (group.entities.length === 0) continue;
3232

3333
// If adding this group would exceed 75% of maxEntities, start a new grid group
34-
if (groupKeys.length !== 0 && (numEntities <= maxEntities * 0.75)) {
35-
groupKeys[groupKeys.length - 1].push(key);
34+
numEntities += group.entities.length;
35+
if (statusKeyList.length !== 0 && (numEntities <= maxEntities * 0.75)) {
36+
statusKeyList[statusKeyList.length - 1].push(key);
3637
} else {
37-
groupKeys.push([key]);
38+
statusKeyList.push([key]);
3839
}
3940
}
4041

41-
// If we still ended up still with 4 groups, merge the first and last two groups to a 2-column grid
42-
if (groupKeys.length === 4) {
43-
return [[groupKeys[0][0], groupKeys[1][0]], [groupKeys[2][0], groupKeys[3][0]]];
42+
// If we still end up with 4 groups, merge them into a 2-column grid
43+
if (statusKeyList.length === 4) {
44+
return [[statusKeyList[0][0], statusKeyList[1][0]], [statusKeyList[2][0], statusKeyList[3][0]]];
4445
}
45-
return groupKeys;
46+
return statusKeyList;
4647
}
4748

4849
class Simon42ViewBatteriesStrategy extends HTMLElement {
@@ -52,19 +53,17 @@ class Simon42ViewBatteriesStrategy extends HTMLElement {
5253

5354
const strategyConfig = config.config || {};
5455
const batteryGroups = buildBatteryStatusGroups(hass, strategyConfig);
55-
const batteryGroupStyles = getBatteryStatusDisplay(strategyConfig);
5656

5757
const sections: LovelaceSectionConfig[] = [];
5858

5959
// Build sections based on grid groups
60-
for (const gridGroupKeys of smartGridGrouping(batteryGroups)) {
61-
const cards: any[] = [];
60+
for (const statusKeyList of smartGridGrouping(batteryGroups)) {
61+
const cards: LovelaceCardConfig[] = [];
6262

6363
// Build sections based on grid groups
64-
for (const key of gridGroupKeys) {
64+
for (const status of statusKeyList) {
6565

66-
const entities = batteryGroups[key].entities;
67-
if (!entities || entities.length === 0) continue;
66+
const entities = batteryGroups[status]!.entities;
6867

6968
entities.sort((a: string, b: string) => {
7069
const valA = parseFloat(hass.states[a]?.state);
@@ -74,11 +73,11 @@ class Simon42ViewBatteriesStrategy extends HTMLElement {
7473
return valA - valB;
7574
});
7675

77-
const style = batteryGroupStyles[key];
76+
const style = getBatteryStatusDisplay(strategyConfig, status);
7877
const oneOrMany = entities.length === 1 ? 'battery_one' : 'battery_many';
7978
cards.push({
8079
type: 'heading',
81-
heading: `${localize('batteries.' + key)} ` + (style.info ? `(${style.info})` : '') +
80+
heading: `${localize('batteries.' + status)} ` + (style.info ? `(${style.info})` : '') +
8281
` - ${entities.length} ${localize('batteries.' + oneOrMany)}`,
8382
heading_style: 'title',
8483
icon: style.icon,

0 commit comments

Comments
 (0)