Skip to content

Commit

Permalink
feat: fix consumable feature by adding custom ha-bar component
Browse files Browse the repository at this point in the history
  • Loading branch information
itsteddyyo committed Sep 19, 2024
1 parent 870c673 commit 0b674db
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/consumable-feature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { classMap } from "lit/directives/class-map.js";
import { mdiRestore } from "@mdi/js";
import { HassEntity } from "home-assistant-js-websocket";
import { C_HomeAssistant } from "./util/types";
import "./homeassistant/ha-bar";

interface ConsumableConfig {
title: string;
Expand Down Expand Up @@ -98,7 +99,8 @@ class ConsumableFeature extends LitElement {
margin: 0 12px 12px 12px;
--control-button-group-spacing: 12px;
}
secondary {
.secondary {
max-width: 200px;
font-weight: 400;
font-size: 12px;
line-height: 16px;
Expand Down
17 changes: 17 additions & 0 deletions src/homeassistant/calculate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const normalize = (value: number, min: number, max: number): number => {
if (isNaN(value) || isNaN(min) || isNaN(max)) {
// Not a number, return 0
return 0;
}
if (value > max) return max;
if (value < min) return min;
return value;
};

export const getValueInPercentage = (value: number, min: number, max: number): number => {
const newMax = max - min;
const newVal = value - min;
return (100 * newVal) / newMax;
};

export const roundWithOneDecimal = (value: number): number => Math.round(value * 10) / 10;
51 changes: 51 additions & 0 deletions src/homeassistant/ha-bar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { css, CSSResultGroup, LitElement, svg, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators.js";
import { getValueInPercentage, normalize, roundWithOneDecimal } from "./calculate";

@customElement("ha-bar")
export class HaBar extends LitElement {
@property({ type: Number }) public min = 0;

@property({ type: Number }) public max = 100;

@property({ type: Number }) public value!: number;

protected render(): TemplateResult {
const valuePrecentage = roundWithOneDecimal(getValueInPercentage(normalize(this.value, this.min, this.max), this.min, this.max));

return svg`
<svg>
<g>
<rect/>
<rect width="${valuePrecentage}%"/>
</g>
</svg>
`;
}

static get styles(): CSSResultGroup {
return css`
rect {
height: 100%;
}
rect:first-child {
width: 100%;
fill: var(--ha-bar-background-color, var(--secondary-background-color));
}
rect:last-child {
fill: var(--ha-bar-primary-color, var(--primary-color));
}
svg {
border-radius: var(--ha-bar-border-radius, 4px);
height: 12px;
width: 100%;
}
`;
}
}

declare global {
interface HTMLElementTagNameMap {
"ha-bar": HaBar;
}
}

0 comments on commit 0b674db

Please sign in to comment.