Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adds support for severity based colors #388

Merged
merged 1 commit into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,23 @@ Note: This card is a wrapper. This means that it's designed to wrap other existi

If you want to use a sensor value instead of a percentage, you can use the `full_value` property to set the maximum value of the sensor. The card will then calculate the percentage based on the sensor value and the `full_value` property.

## Severity

You can set the severity of the fluid level by using the `severity` property. The severity is a list of objects with the following properties:

- `value`: The level at which the severity should be applied
- `color`: The color of the severity. use can use any of the [supported color formats](#supported-color-formats)

```yaml
severity:
- value: 20
color: red
- value: 50
color: yellow
- value: 80
color: green
```

## Support

Hey dude! Help me out for a couple of :beers: or a :coffee:!
Expand Down
17 changes: 13 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"license": "MIT",
"dependencies": {
"@commitlint/config-conventional": "^19.0.3",
"@mdi/js": "^7.4.47",
"colortranslator": "^4.0.0",
"custom-card-helpers": "^1.9.0",
"home-assistant-js-websocket": "^9.1.0",
Expand Down Expand Up @@ -66,4 +67,4 @@
"prettier --write"
]
}
}
}
132 changes: 131 additions & 1 deletion src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
LovelaceCardConfig,
} from 'custom-card-helpers';

import { FluidLevelBackgroundCardConfig, GUIModeChangedEvent } from './types';
import { FluidLevelBackgroundCardConfig, GUIModeChangedEvent, Severity } from './types';
import { localize } from './localize/localize';
import {
BACKGROUND_COLOR,
Expand All @@ -22,6 +22,8 @@ import {
THEME_PRIMARY_COLOR_VARIABLE,
} from './const';
import { getThemeColor } from './utils/theme-parser';
import { parseCssColor } from './utils/color';
import { mdiMinus, mdiPlus } from '@mdi/js';

export interface EditorTab {
slug: string;
Expand Down Expand Up @@ -168,6 +170,10 @@ export class FluidLevelBackgroundCardEditor extends LitElement implements Lovela
return this._config?.full_value ?? FULL_VALUE;
}

get _severity(): Severity[] {
return this._config?.severity || [];
}

private _lastUsedBackgroundColor: number[] | undefined;
private _lastUsedLevelColor: number[] | undefined;

Expand Down Expand Up @@ -353,6 +359,56 @@ export class FluidLevelBackgroundCardEditor extends LitElement implements Lovela
</ha-switch>
</ha-formfield>
</div>
<ha-formfield label=${localize('editor.tab.appearance.labels.use-severity')}>
<ha-switch .checked=${this._severity.length > 0} @change=${this._toggleSeverity}> </ha-switch>
</ha-formfield>
${this.severitySection()}
`;
}

severitySection(): TemplateResult {
if (this._severity.length > 0) {
return html`
<h3>${localize('editor.tab.appearance.choose-severity')}</h3>
<ha-icon-button
.label=${this.hass?.localize('ui.common.add') || 'Add'}
.path=${mdiPlus}
@click=${this._addSeverity}
></ha-icon-button>
${this._severity.map((severity) => this.severityItem(severity))}
`;
}
return html``;
}

severityItem(severity: Severity): TemplateResult {
const severityColor = parseCssColor(severity.color);
const index = this._severity.indexOf(severity);
return html`
<div class="form-row-tripple">
<ha-selector
.hass=${this.hass}
.selector=${{ color_rgb: {} }}
.value=${severityColor}
.index=${index}
@value-changed=${this._severityColorChanged}
></ha-selector>

<ha-textfield
type="number"
.configValue=${'full_value'}
.value=${severity.value}
.index=${index}
@change=${this._severityValueChanged}
></ha-textfield>

<ha-icon-button
.label=${this.hass?.localize('ui.common.remove') || 'Remove'}
.path=${mdiMinus}
.index=${index}
@click=${this._removeSeverity}
></ha-icon-button>
</div>
`;
}

Expand Down Expand Up @@ -381,6 +437,72 @@ export class FluidLevelBackgroundCardEditor extends LitElement implements Lovela
fireEvent(this, 'config-changed', { config: this._config });
}

protected _toggleSeverity(): void {
if (!this._config) {
return;
}
if (this._severity.length > 0) {
this._config = { ...this._config, severity: [] };
} else {
this._config = { ...this._config, severity: [{ color: '#FF0000', value: 0 }] };
}
fireEvent(this, 'config-changed', { config: this._config });
}

protected _addSeverity(): void {
if (!this._config) {
return;
}
this._config = { ...this._config, severity: [...this._severity, { color: '#FF0000', value: 0 }] };
fireEvent(this, 'config-changed', { config: this._config });
}

protected _removeSeverity(ev): void {
if (!this._config) {
return;
}
const [index] = this._getSeverityItemFormEvent(ev);

this._config = { ...this._config, severity: this._severity.filter((_, i) => i !== index) };
fireEvent(this, 'config-changed', { config: this._config });
}

protected _severityColorChanged(ev): void {
if (!this._config) {
return;
}
let severityItem = this._severity[ev.target.index];
const color = ev.detail.value;
const severity = [...this._severity];

severityItem = { ...severityItem, color };
severity[ev.target.index] = severityItem;

this._config = { ...this._config, severity };
fireEvent(this, 'config-changed', { config: this._config });
}

protected _severityValueChanged(ev): void {
if (!this._config) {
return;
}
const index = ev.target.index;
const value = ev.target.value;
let severityItem = this._severity[index];
const severity = [...this._severity];

severityItem = { ...severityItem, value: parseFloat(value) };
severity[index] = severityItem;

this._config = { ...this._config, severity };
fireEvent(this, 'config-changed', { config: this._config });
}

private _getSeverityItemFormEvent(ev): [number, any, Severity] {
const index = ev.target.index;
return [index, ev.target.value, this._severity[index]];
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
protected _handleCardPicked(ev): void {
ev.stopPropagation();
Expand Down Expand Up @@ -547,6 +669,14 @@ export class FluidLevelBackgroundCardEditor extends LitElement implements Lovela
.form-row-dual > :last-child {
margin-inline: 8px;
}
.form-row-tripple {
margin-bottom: 14px;
display: grid;
grid-template-columns: 1fr 1fr 48px;
}
.form-row-tripple > :not(:first-child) {
margin-inline: 8px;
}
.title {
padding-left: 16px;
margin-top: -6px;
Expand Down
15 changes: 13 additions & 2 deletions src/fluid-level-background-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
import './editor';
import './fluid-background';

import type { FluidLevelBackgroundCardConfig } from './types';
import type { FluidLevelBackgroundCardConfig, Severity } from './types';
import { actionHandler } from './action-handler-directive';
import {
BACKGROUND_COLOR,
Expand Down Expand Up @@ -81,6 +81,8 @@ export class FluidLevelBackgroundCard extends LitElement {

@state() protected _full_value: number = FULL_VALUE;

@state() protected _severity: Severity[] = [];

@state() private config!: FluidLevelBackgroundCardConfig;

private _darkModeLastValue!: boolean;
Expand Down Expand Up @@ -121,6 +123,8 @@ export class FluidLevelBackgroundCard extends LitElement {
(config.background_color && parseCssColor(config.background_color)) ||
getThemeColor(THEME_BACKGROUND_COLOR_VARIABLE, BACKGROUND_COLOR);
this._full_value = config.full_value ?? FULL_VALUE;
// set severity from the config sorted by value
this._severity = config.severity ? [...config.severity].sort((a, b) => b.value - a.value) : [];
}

requestUpdate(name?: PropertyKey, oldValue?: unknown): void {
Expand Down Expand Up @@ -156,6 +160,10 @@ export class FluidLevelBackgroundCard extends LitElement {
super.requestUpdate(name, oldValue);
}

if (name === '_severity') {
super.requestUpdate(name, oldValue);
}

if (name === 'config') {
super.requestUpdate(name, oldValue);
}
Expand Down Expand Up @@ -308,6 +316,9 @@ export class FluidLevelBackgroundCard extends LitElement {

private makeFluidBackground(): TemplateResult {
const value = this.getSafeLevelValue(this._level_entity);
const severityColor = this._severity.length > 0 ? this._severity.find((s) => s.value <= value)?.color : undefined;
const levelColor = severityColor ? parseCssColor(severityColor) : this._level_color;

const filling =
this._fill_entity && this.hass.states[this._fill_entity]
? this.hass.states[this._fill_entity].state === 'on'
Expand All @@ -317,7 +328,7 @@ export class FluidLevelBackgroundCard extends LitElement {
.size=${this.size}
.value=${value}
.backgroundColor=${this._background_color || this.backgroundColor}
.levelColor=${this._level_color || LEVEL_COLOR}
.levelColor=${levelColor || LEVEL_COLOR}
.filling=${filling}
></fluid-background>`;
}
Expand Down
4 changes: 3 additions & 1 deletion src/localize/languages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@
"appearance": {
"title": "Appearance",
"choose-colors": "Choose Colors",
"choose-severity": "Choose Severity",
"labels": {
"level-color": "Level Color",
"background-color": "Background Color",
"use-theme-color": "Use Theme Color",
"color-description": "Set the colors you like for the card. If you want to use the theme colors, just check the box. Theme colors are handy for light/dark mode."
"color-description": "Set the colors you like for the card. If you want to use the theme colors, just check the box. Theme colors are handy for light/dark mode.",
"use-severity": "Use Severity"
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/localize/languages/hu.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@
"entities": {
"title": "Entitások*",
"chose-entities": "Válasszon entitásokat",
"choose-severity": "Válasszon súlyosságot",
"labels": {
"level-entity": "Szint Entitás",
"fill-entity": "Töltés Entitás",
"full-value": "Teli Érték",
"full-value-description": "Az érték, amikor a kártya tele van"
"full-value-description": "Az érték, amikor a kártya tele van",
"use-severity": "Használja a súlyosságot"
}
},
"actions": {
Expand Down
4 changes: 3 additions & 1 deletion src/localize/languages/nb.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@
"appearance": {
"title": "Utseende",
"choose-colors": "Velg Farger",
"choose-severity": "Velg Alvorlighetsgrad",
"labels": {
"level-color": "Nivå Farge",
"background-color": "Bakgrunnsfarge",
"use-theme-color": "Bruk Tema Farge",
"color-description": "Sett fargene du liker for kortet. Hvis du vil bruke temafargene, bare merk av i boksen. Temafarger er hendige for lys/mørk modus."
"color-description": "Sett fargene du liker for kortet. Hvis du vil bruke temafargene, bare merk av i boksen. Temafarger er hendige for lys/mørk modus.",
"use-severity": "Bruk Alvorlighetsgrad"
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/localize/languages/ptbr.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@
"appearance": {
"title": "Aparência",
"choose-colors": "Escolha as cores",
"choose-severity": "Escolha a severidade",
"labels": {
"level-color": "Cor do Nível",
"background-color": "Cor de fundo",
"use-theme-color": "Usar cor do tema",
"color-description": "Defina as cores que você gosta para o cartão. Se você quiser usar as cores do tema, basta marcar a caixa. As cores do tema são úteis para o modo claro/escuro."
"color-description": "Defina as cores que você gosta para o cartão. Se você quiser usar as cores do tema, basta marcar a caixa. As cores do tema são úteis para o modo claro/escuro.",
"use-severity": "Usar severidade"
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/localize/languages/ptpt.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@
"appearance": {
"title": "Aparência",
"choose-colors": "Escolha as cores",
"choose-severity": "Escolha a severidade",
"labels": {
"level-color": "Cor do Nível",
"background-color": "Cor de fundo",
"use-theme-color": "Usar cor do tema",
"color-description": "Defina as cores que você gosta para o cartão. Se você quiser usar as cores do tema, basta marcar a caixa. As cores do tema são úteis para o modo claro/escuro."
"color-description": "Defina as cores que você gosta para o cartão. Se você quiser usar as cores do tema, basta marcar a caixa. As cores do tema são úteis para o modo claro/escuro.",
"use-severity": "Usar severidade"
}
}
}
Expand Down
Loading