Add optional label for gauge segment (#12960)

Co-authored-by: Zack Barett <zackbarett@hey.com>
This commit is contained in:
Kristján Bjarni 2022-06-29 15:36:18 +00:00 committed by GitHub
parent 389f50b29a
commit 0f580a91c9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 28 additions and 4 deletions

View File

@ -14,6 +14,7 @@ const getAngle = (value: number, min: number, max: number) => {
export interface LevelDefinition {
level: number;
stroke: string;
label?: string;
}
@customElement("ha-gauge")
@ -38,12 +39,15 @@ export class Gauge extends LitElement {
@state() private _updated = false;
@state() private _segment_label? = "";
protected firstUpdated(changedProperties: PropertyValues) {
super.firstUpdated(changedProperties);
// Wait for the first render for the initial animation to work
afterNextRender(() => {
this._updated = true;
this._angle = getAngle(this.value, this.min, this.max);
this._segment_label = this.getSegmentLabel();
this._rescale_svg();
});
}
@ -52,11 +56,14 @@ export class Gauge extends LitElement {
super.updated(changedProperties);
if (
!this._updated ||
(!changedProperties.has("value") && !changedProperties.has("label"))
(!changedProperties.has("value") &&
!changedProperties.has("label") &&
!changedProperties.has("_segment_label"))
) {
return;
}
this._angle = getAngle(this.value, this.min, this.max);
this._segment_label = this.getSegmentLabel();
this._rescale_svg();
}
@ -121,9 +128,11 @@ export class Gauge extends LitElement {
</svg>
<svg class="text">
<text class="value-text">
${this.valueText || formatNumber(this.value, this.locale)} ${
this.label
}
${
this._segment_label
? this._segment_label
: this.valueText || formatNumber(this.value, this.locale)
} ${this._segment_label ? "" : this.label}
</text>
</svg>`;
}
@ -140,6 +149,18 @@ export class Gauge extends LitElement {
);
}
private getSegmentLabel() {
if (this.levels) {
this.levels.sort((a, b) => a.level - b.level);
for (let i = this.levels.length - 1; i >= 0; i--) {
if (this.value >= this.levels[i].level) {
return this.levels[i].label;
}
}
}
return "";
}
static get styles() {
return css`
:host {

View File

@ -232,6 +232,7 @@ class HuiGaugeCard extends LitElement implements LovelaceCard {
return segments.map((segment) => ({
level: segment?.from,
stroke: segment?.color,
label: segment?.label,
}));
}

View File

@ -185,6 +185,7 @@ export interface SeverityConfig {
export interface GaugeSegment {
from: number;
color: string;
label?: string;
}
export interface GaugeCardConfig extends LovelaceCardConfig {

View File

@ -22,6 +22,7 @@ import { baseLovelaceCardConfig } from "../structs/base-card-struct";
const gaugeSegmentStruct = object({
from: number(),
color: string(),
label: optional(string()),
});
const cardConfigStruct = assign(