Compare commits

..
Author SHA1 Message Date
Aidan Timson 3e56995bf9 Drop hass from the alert card and badge 2026-10-13 15:06:37 +01:00
Aidan Timson 6bf10da9e0 Match the alert card and badge content options to the tile card and entity badge 2026-10-13 15:06:37 +01:00
Aidan Timson 008f13a6dc Use contexts for alert card and badge actions and pictures 2026-10-13 15:06:37 +01:00
Aidan Timson ad5b46425b Add tile card options to the alert card and badge 2026-10-13 15:06:19 +01:00
Aidan Timson de067453b7 Share tile action and picture helpers with the entity badge 2026-10-13 15:06:02 +01:00
Aidan Timson 70cd87b881 Use consumeLocalize in the alert badge 2026-10-13 15:05:31 +01:00
Aidan Timson 60b6192db3 Default the alert badge color to red and show its colors side by side 2026-10-13 14:55:50 +01:00
Aidan Timson 934ba2bc5e Only alert while the alert badge entity is in an alert state 2026-10-13 14:55:50 +01:00
Aidan Timson ff1f0f4dd8 Use shared alert domains in the alert badge 2026-10-13 14:55:50 +01:00
Aidan Timson 1e663770cc Add alert badge 2026-10-13 14:55:50 +01:00
Aidan Timson 5ea845f130 Only offer alert entities in the security alerts picker 2026-10-13 14:55:18 +01:00
Aidan Timson 088136b3b7 Default the alert card color to red 2026-10-13 14:52:30 +01:00
Aidan Timson 3f18dedc45 Show the alert card colors side by side 2026-10-13 14:52:30 +01:00
Aidan Timson 6277031ae1 Only alert while the alert card entity is in an alert state 2026-10-13 14:52:30 +01:00
Aidan Timson f22a80f2ca Share the alert active states with the alert card 2026-10-13 14:52:30 +01:00
Aidan Timson d7afa5afa4 Suggest the alert card when adding a card by entity 2026-10-13 14:52:30 +01:00
Aidan Timson c8f754e289 Add visual editor for the alert card 2026-10-13 14:52:30 +01:00
Aidan Timson e2cb5bb67c Stop alert card pulse when reduced motion is on 2026-10-13 14:52:30 +01:00
28 changed files with 1404 additions and 558 deletions

No files matched your search

-1
View File
@@ -13,7 +13,6 @@ export const canOverrideAlphanumericInput = (composedPath: EventTarget[]) => {
if (
el.tagName === "TEXTAREA" ||
(el as HTMLElement).isContentEditable ||
el.parentElement?.tagName === "HA-SELECT" ||
el.parentElement?.tagName === "HA-DROPDOWN"
) {
+27
View File
@@ -0,0 +1,27 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { computeDomain } from "./compute_domain";
export const ALERT_DOMAINS = [
"alarm_control_panel",
"binary_sensor",
"cover",
"lock",
];
export const DEFAULT_ALERT_COLOR = "red";
export const computeAlertActiveStates = (entityId: string): string[] => {
switch (computeDomain(entityId)) {
case "alarm_control_panel":
return ["triggered"];
case "cover":
return ["open"];
case "lock":
return ["jammed", "unlocked", "open"];
default:
return ["on"];
}
};
export const isAlertActive = (stateObj: HassEntity): boolean =>
computeAlertActiveStates(stateObj.entity_id).includes(stateObj.state);
@@ -0,0 +1,15 @@
import { ALERT_DOMAINS } from "../../../common/entity/alert_active";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { AlertBadgeConfig } from "../badges/types";
import type { BadgeSuggestionProvider } from "./types";
export const alertBadgeSuggestions: BadgeSuggestionProvider<AlertBadgeConfig> =
{
getEntitySuggestion(_hass, entityId) {
if (!ALERT_DOMAINS.includes(computeDomain(entityId))) {
return [];
}
return [{ config: { type: "alert", entity: entityId } }];
},
};
@@ -1,3 +1,4 @@
import { alertBadgeSuggestions } from "./hui-alert-badge-suggestions";
import { entityBadgeSuggestions } from "./hui-entity-badge-suggestions";
import type { BadgeSuggestionProvider } from "./types";
@@ -6,4 +7,5 @@ export const BADGE_SUGGESTION_PROVIDERS: Record<
BadgeSuggestionProvider
> = {
entity: entityBadgeSuggestions,
alert: alertBadgeSuggestions,
};
@@ -0,0 +1,262 @@
import type { ContextType } from "@lit/context";
import { mdiAlertCircle } from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import { computeCssColor } from "../../../common/color/compute-color";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { fireEvent } from "../../../common/dom/fire_event";
import {
ALERT_DOMAINS,
DEFAULT_ALERT_COLOR,
isAlertActive,
} from "../../../common/entity/alert_active";
import { computeDomain } from "../../../common/entity/compute_domain";
import { isValidEntityId } from "../../../common/entity/valid_entity_id";
import "../../../components/ha-badge";
import "../../../components/ha-state-icon";
import "../../../components/ha-svg-icon";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { connectionContext, formattersContext } from "../../../data/context";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import "../../../state-display/state-display";
import type { HomeAssistant, HomeAssistantConnection } from "../../../types";
import {
getTileImageUrl,
hasTileCardAction,
} from "../cards/tile/tile-card-helpers";
import { actionHandler } from "../common/directives/action-handler-directive";
import { findEntities } from "../common/find-entities";
import { hasAction } from "../common/has-action";
import type { LovelaceBadge, LovelaceBadgeEditor } from "../types";
import type { AlertBadgeConfig } from "./types";
export const ALERT_BADGE_DEFAULT_CONFIG: Partial<AlertBadgeConfig> = {
type: "alert",
show_name: true,
show_state: true,
show_icon: true,
};
@customElement("hui-alert-badge")
export class HuiAlertBadge extends LitElement implements LovelaceBadge {
public static async getConfigElement(): Promise<LovelaceBadgeEditor> {
await import("../editor/config-elements/hui-alert-badge-editor");
return document.createElement("hui-alert-badge-editor");
}
public static getStubConfig(
hass: HomeAssistant,
entities: string[],
entitiesFallback: string[]
): AlertBadgeConfig {
const [entity] = findEntities(
hass,
1,
entities,
entitiesFallback,
ALERT_DOMAINS
);
return { type: "alert", entity: entity || "" };
}
public static getDefaultConfig(): Partial<AlertBadgeConfig> {
return ALERT_BADGE_DEFAULT_CONFIG;
}
@state() private _config?: AlertBadgeConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: connectionContext, subscribe: true })
private _connection!: HomeAssistantConnection;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: ContextType<typeof formattersContext>;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
public setConfig(config: AlertBadgeConfig): void {
if (
!isValidEntityId(config.entity) ||
(config.color !== undefined && typeof config.color !== "string") ||
(config.inactive_color !== undefined &&
typeof config.inactive_color !== "string") ||
(config.pulse !== undefined && typeof config.pulse !== "boolean")
) {
throw new Error("Invalid configuration");
}
if (!ALERT_DOMAINS.includes(computeDomain(config.entity))) {
throw new Error(
`Specify an entity from within the ${ALERT_DOMAINS.join(", ")} domains`
);
}
this._config = { ...ALERT_BADGE_DEFAULT_CONFIG, ...config };
}
protected render() {
if (
!this._config ||
!this._connection ||
!this._formatters ||
!this._localize
) {
return nothing;
}
const stateObj = this._stateObj;
if (!stateObj) {
return html`
<ha-badge .label=${this._config.entity} class="error">
<ha-svg-icon slot="icon" .path=${mdiAlertCircle}></ha-svg-icon>
${this._localize("ui.badge.entity.not_found")}
</ha-badge>
`;
}
const active = isAlertActive(stateObj);
const color = active
? (this._config.color ?? DEFAULT_ALERT_COLOR)
: this._config.inactive_color;
const pulse = active && this._config.pulse === true;
const hasColor = color !== undefined && color !== "none";
const name = this._formatters.formatEntityName(stateObj, this._config.name);
const imageUrl = this._config.show_entity_picture
? getTileImageUrl(this._connection, stateObj, 32)
: undefined;
const { show_name: showName, show_state: showState } = this._config;
const content = showState
? html`<state-display
.stateObj=${stateObj}
.content=${this._config.state_content}
.timeFormat=${this._config.time_format}
.name=${name}
></state-display>`
: showName
? name
: undefined;
return html`
<ha-badge
.type=${hasTileCardAction(this._config) ? "button" : "badge"}
.label=${showState && showName ? name : undefined}
.iconOnly=${!content}
class=${classMap({ alert: true, pulse, "no-color": !hasColor })}
style=${styleMap({
"--ha-alert-color":
color && hasColor ? computeCssColor(color) : undefined,
})}
@action=${this._handleAction}
.actionHandler=${actionHandler({
hasHold: hasAction(this._config.hold_action),
hasDoubleClick: hasAction(this._config.double_tap_action),
})}
>
${
!this._config.show_icon
? nothing
: imageUrl
? html`<img slot="icon" src=${imageUrl} aria-hidden />`
: html`<ha-state-icon
slot="icon"
.stateObj=${stateObj}
.icon=${this._config.icon}
></ha-state-icon>`
}
${content}
</ha-badge>
`;
}
private _handleAction(ev: ActionHandlerEvent): void {
fireEvent(this, "hass-action", {
config: this._config!,
action: ev.detail.action!,
});
}
static styles = css`
@keyframes pulse-opacity {
from {
opacity: 0;
}
to {
opacity: var(--ha-alert-pulse-opacity);
}
}
:host {
--ha-alert-pulse-duration: 1s;
--ha-alert-pulse-opacity: 0.3;
--ha-alert-badge-background: var(
--ha-card-background,
var(--card-background-color, white)
);
}
ha-badge.error {
--badge-color: var(--red-color);
}
ha-badge.alert {
display: block;
position: relative;
isolation: isolate;
border-radius: var(
--ha-badge-border-radius,
calc(var(--ha-badge-size, 36px) / 2)
);
background: var(--ha-alert-badge-background);
--ha-card-background: transparent;
--badge-color: var(--ha-alert-color);
}
ha-badge.alert.no-color {
--badge-color: var(--secondary-text-color);
}
ha-badge.alert::before {
position: absolute;
inset: 0;
z-index: -1;
border-radius: inherit;
background-color: var(--ha-alert-color);
content: "";
opacity: var(--ha-alert-pulse-opacity);
pointer-events: none;
}
ha-badge.alert.pulse::before {
animation: pulse-opacity var(--ha-alert-pulse-duration) ease-in-out
infinite alternate;
}
@media (prefers-reduced-motion: reduce) {
ha-badge.alert.pulse::before {
animation: none;
}
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"hui-alert-badge": HuiAlertBadge;
}
}
+6 -24
View File
@@ -8,15 +8,17 @@ import memoizeOne from "memoize-one";
import { computeCssColor } from "../../../common/color/compute-color";
import { hsv2rgb, rgb2hex, rgb2hsv } from "../../../common/color/convert-color";
import { computeDomain } from "../../../common/entity/compute_domain";
import { computeStateDomain } from "../../../common/entity/compute_state_domain";
import { stateActive } from "../../../common/entity/state_active";
import { stateColorCss } from "../../../common/entity/state_color";
import "../../../components/ha-badge";
import "../../../components/ha-state-icon";
import "../../../components/ha-svg-icon";
import { cameraUrlWithWidthHeight } from "../../../data/camera";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import type { HomeAssistant } from "../../../types";
import {
getTileImageUrl,
hasTileCardAction,
} from "../cards/tile/tile-card-helpers";
import { actionHandler } from "../common/directives/action-handler-directive";
import { findEntities } from "../common/find-entities";
import { handleAction } from "../common/handle-action";
@@ -99,12 +101,7 @@ export class HuiEntityBadge extends LitElement implements LovelaceBadge {
}
get hasAction() {
return (
!this._config?.tap_action ||
hasAction(this._config?.tap_action) ||
hasAction(this._config?.hold_action) ||
hasAction(this._config?.double_tap_action)
);
return hasTileCardAction(this._config);
}
private _computeStateColor = memoizeOne(
@@ -138,21 +135,6 @@ export class HuiEntityBadge extends LitElement implements LovelaceBadge {
}
);
private _getImageUrl(stateObj: HassEntity): string | undefined {
const entityPicture =
stateObj.attributes.entity_picture_local ||
stateObj.attributes.entity_picture;
if (!entityPicture) return undefined;
let imageUrl = this.hass!.hassUrl(entityPicture);
if (computeStateDomain(stateObj) === "camera") {
imageUrl = cameraUrlWithWidthHeight(imageUrl, 32, 32);
}
return imageUrl;
}
protected render() {
if (!this._config || !this.hass) {
return nothing;
@@ -195,7 +177,7 @@ export class HuiEntityBadge extends LitElement implements LovelaceBadge {
const showEntityPicture = this._config.show_entity_picture;
const imageUrl = showEntityPicture
? this._getImageUrl(stateObj)
? getTileImageUrl(this.hass, stateObj, 32)
: undefined;
const label = showState && showName ? name : undefined;
+19
View File
@@ -31,6 +31,25 @@ export interface StateLabelBadgeConfig extends LovelaceBadgeConfig {
double_tap_action?: ActionConfig;
}
export interface AlertBadgeConfig extends LovelaceBadgeConfig {
type: "alert";
entity: string;
name?: string | EntityNameItem | EntityNameItem[];
icon?: string;
color?: string;
inactive_color?: string;
pulse?: boolean;
show_name?: boolean;
show_state?: boolean;
show_icon?: boolean;
show_entity_picture?: boolean;
state_content?: string | string[];
time_format?: TimestampRenderingFormat;
tap_action?: ActionConfig;
hold_action?: ActionConfig;
double_tap_action?: ActionConfig;
}
export interface ShortcutBadgeConfig extends LovelaceBadgeConfig {
text?: string;
icon?: string;
@@ -0,0 +1,14 @@
import { ALERT_DOMAINS } from "../../../common/entity/alert_active";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { AlertCardConfig } from "../cards/types";
import type { CardSuggestionProvider } from "./types";
export const alertCardSuggestions: CardSuggestionProvider<AlertCardConfig> = {
getEntitySuggestion(_hass, entityId) {
if (!ALERT_DOMAINS.includes(computeDomain(entityId))) {
return null;
}
return { config: { type: "alert", entity: entityId } };
},
};
@@ -1,4 +1,5 @@
import { alarmPanelCardSuggestions } from "./hui-alarm-panel-card-suggestions";
import { alertCardSuggestions } from "./hui-alert-card-suggestions";
import { calendarCardSuggestions } from "./hui-calendar-card-suggestions";
import { gaugeCardSuggestions } from "./hui-gauge-card-suggestions";
import { historyGraphCardSuggestions } from "./hui-history-graph-card-suggestions";
@@ -19,6 +20,7 @@ export const CARD_SUGGESTION_PROVIDERS: Record<string, CardSuggestionProvider> =
{
tile: tileCardSuggestions,
"alarm-panel": alarmPanelCardSuggestions,
alert: alertCardSuggestions,
calendar: calendarCardSuggestions,
gauge: gaugeCardSuggestions,
humidifier: humidifierCardSuggestions,
+155 -35
View File
@@ -8,6 +8,12 @@ import { consume } from "../../../common/decorators/consume";
import { computeCssColor } from "../../../common/color/compute-color";
import { consumeEntityState } from "../../../common/decorators/consume-context-entry";
import { fireEvent } from "../../../common/dom/fire_event";
import {
ALERT_DOMAINS,
DEFAULT_ALERT_COLOR,
isAlertActive,
} from "../../../common/entity/alert_active";
import { computeDomain } from "../../../common/entity/compute_domain";
import { isValidEntityId } from "../../../common/entity/valid_entity_id";
import "../../../components/ha-card";
import "../../../components/ha-relative-time";
@@ -15,20 +21,61 @@ import "../../../components/ha-state-icon";
import "../../../components/tile/ha-tile-container";
import "../../../components/tile/ha-tile-icon";
import "../../../components/tile/ha-tile-info";
import { formattersContext } from "../../../data/context";
import { connectionContext, formattersContext } from "../../../data/context";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import type { LovelaceCard, LovelaceGridOptions } from "../types";
import "../../../state-display/state-display";
import type { HomeAssistant, HomeAssistantConnection } from "../../../types";
import { findEntities } from "../common/find-entities";
import { hasAction } from "../common/has-action";
import type {
LovelaceCard,
LovelaceCardEditor,
LovelaceGridOptions,
} from "../types";
import {
getTileActionDefaults,
getTileIconActionConfig,
getTileImageUrl,
hasTileCardAction,
hasTileIconAction,
} from "./tile/tile-card-helpers";
import { tileCardStyle } from "./tile/tile-card-style";
import type { AlertCardConfig } from "./types";
@customElement("hui-alert-card")
export class HuiAlertCard extends LitElement implements LovelaceCard {
public static async getConfigElement(): Promise<LovelaceCardEditor> {
await import("../editor/config-elements/hui-alert-card-editor");
return document.createElement("hui-alert-card-editor");
}
public static getStubConfig(
hass: HomeAssistant,
entities: string[],
entitiesFallback: string[]
): AlertCardConfig {
const [entity] = findEntities(
hass,
1,
entities,
entitiesFallback,
ALERT_DOMAINS
);
return { type: "alert", entity: entity || "" };
}
@state() private _config?: AlertCardConfig;
@state()
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: connectionContext, subscribe: true })
private _connection!: HomeAssistantConnection;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: ContextType<typeof formattersContext>;
@@ -37,28 +84,42 @@ export class HuiAlertCard extends LitElement implements LovelaceCard {
if (
!isValidEntityId(config.entity) ||
(config.color !== undefined && typeof config.color !== "string") ||
(config.inactive_color !== undefined &&
typeof config.inactive_color !== "string") ||
(config.pulse !== undefined && typeof config.pulse !== "boolean")
) {
throw new Error("Invalid configuration");
}
this._config = config;
if (!ALERT_DOMAINS.includes(computeDomain(config.entity))) {
throw new Error(
`Specify an entity from within the ${ALERT_DOMAINS.join(", ")} domains`
);
}
this._config = {
...getTileActionDefaults(config.entity),
...config,
};
}
public getCardSize(): number {
return 1;
return this._config?.vertical ? 2 : 1;
}
public getGridOptions(): LovelaceGridOptions {
const vertical = Boolean(this._config?.vertical);
return {
columns: 6,
rows: 1,
min_columns: 6,
min_rows: 1,
rows: vertical ? 2 : 1,
min_columns: vertical ? 3 : 6,
min_rows: vertical ? 2 : 1,
};
}
protected render() {
if (!this._config || !this._formatters) {
if (!this._config || !this._formatters || !this._connection) {
return nothing;
}
@@ -67,57 +128,115 @@ export class HuiAlertCard extends LitElement implements LovelaceCard {
return nothing;
}
const stateDisplay = this._formatters.formatEntityState(stateObj);
const areaName = this._formatters.formatEntityName(stateObj, {
type: "area",
});
const pulse = this._config.pulse === true;
const hasColor =
this._config.color !== undefined && this._config.color !== "none";
const active = isAlertActive(stateObj);
const color = active
? (this._config.color ?? DEFAULT_ALERT_COLOR)
: this._config.inactive_color;
const pulse = active && this._config.pulse === true;
const hasColor = color !== undefined && color !== "none";
const imageUrl = this._config.show_entity_picture
? getTileImageUrl(this._connection, stateObj)
: undefined;
return html`
<ha-card
class=${classMap({ pulse, "no-color": !hasColor })}
style=${styleMap({
"--ha-alert-color":
this._config.color && hasColor
? computeCssColor(this._config.color)
: undefined,
color && hasColor ? computeCssColor(color) : undefined,
"--ha-alert-static-opacity": pulse
? undefined
: "var(--ha-alert-pulse-opacity)",
})}
>
<ha-tile-container
.interactive=${true}
.actionHandlerOptions=${{ hasHold: false, hasDoubleClick: false }}
.vertical=${Boolean(this._config.vertical)}
.interactive=${hasTileCardAction(this._config)}
.actionHandlerOptions=${{
hasHold: hasAction(this._config.hold_action),
hasDoubleClick: hasAction(this._config.double_tap_action),
}}
@action=${this._handleAction}
>
<ha-tile-icon slot="icon">
<ha-state-icon slot="icon" .stateObj=${stateObj}></ha-state-icon>
<ha-tile-icon
slot="icon"
.interactive=${hasTileIconAction(this._config)}
.actionHandlerOptions=${{
hasHold: hasAction(this._config.icon_hold_action),
hasDoubleClick: hasAction(this._config.icon_double_tap_action),
}}
.imageUrl=${imageUrl}
@action=${this._handleIconAction}
>
${
imageUrl
? nothing
: html`<ha-state-icon
slot="icon"
.icon=${this._config.icon}
.stateObj=${stateObj}
></ha-state-icon>`
}
</ha-tile-icon>
<ha-tile-info slot="info">
<span slot="primary"
>${this._formatters.formatEntityName(stateObj)}</span
>${this._formatters.formatEntityName(
stateObj,
this._config.name
)}</span
>
<span slot="secondary">
${stateDisplay} ·
<ha-relative-time
.datetime=${stateObj.last_changed}
.format=${"short"}
></ha-relative-time>
${areaName ? html` · ${areaName}` : nothing}
</span>
${
this._config.hide_state
? nothing
: html`<span slot="secondary">
${
this._config.state_content
? html`<state-display
.stateObj=${stateObj}
.content=${this._config.state_content}
.timeFormat=${this._config.time_format}
></state-display>`
: this._renderDefaultSecondary(stateObj)
}
</span>`
}
</ha-tile-info>
</ha-tile-container>
</ha-card>
`;
}
private _renderDefaultSecondary(stateObj: HassEntity) {
const areaName = this._formatters.formatEntityName(stateObj, {
type: "area",
});
return html`
${this._formatters.formatEntityState(stateObj)} ·
<ha-relative-time
.datetime=${stateObj.last_changed}
.format=${"short"}
></ha-relative-time>
${areaName ? html` · ${areaName}` : nothing}
`;
}
private _handleAction(ev: ActionHandlerEvent): void {
if (ev.detail.action === "tap" && this._config) {
fireEvent(this, "hass-more-info", { entityId: this._config.entity });
}
fireEvent(this, "hass-action", {
config: this._config!,
action: ev.detail.action!,
});
}
private _handleIconAction(ev: ActionHandlerEvent): void {
ev.stopPropagation();
fireEvent(this, "hass-action", {
config: getTileIconActionConfig(this._config!.entity, this._config!),
action: ev.detail.action!,
});
}
static styles = [
@@ -169,7 +288,8 @@ export class HuiAlertCard extends LitElement implements LovelaceCard {
position: relative;
}
@media (prefers-reduced-motion: reduce) {
ha-card::before {
ha-card::before,
ha-card.pulse::before {
animation: none;
opacity: var(--ha-alert-pulse-opacity);
}
+17 -57
View File
@@ -8,7 +8,6 @@ import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { computeCssColor } from "../../../common/color/compute-color";
import { hsv2rgb, rgb2hex, rgb2hsv } from "../../../common/color/convert-color";
import { DOMAINS_TOGGLE } from "../../../common/const";
import { computeDomain } from "../../../common/entity/compute_domain";
import { stateActive } from "../../../common/entity/state_active";
import { stateColorCss } from "../../../common/entity/state_color";
@@ -18,7 +17,6 @@ import "../../../components/tile/ha-tile-badge";
import "../../../components/tile/ha-tile-container";
import "../../../components/tile/ha-tile-icon";
import "../../../components/tile/ha-tile-info";
import { cameraUrlWithWidthHeight } from "../../../data/camera";
import { timerJustFinished } from "../../../data/timer";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import "../../../state-display/state-display";
@@ -39,18 +37,16 @@ import type {
LovelaceGridOptions,
} from "../types";
import { renderTileBadge } from "./tile/badges/tile-badge";
import {
getTileActionDefaults,
getTileIconActionConfig,
getTileImageUrl,
hasTileCardAction,
hasTileIconAction,
} from "./tile/tile-card-helpers";
import { tileCardStyle } from "./tile/tile-card-style";
import type { TileCardConfig } from "./types";
export const getEntityDefaultTileIconAction = (entityId: string) => {
const domain = computeDomain(entityId);
const supportsIconAction =
DOMAINS_TOGGLE.has(domain) ||
["button", "input_button", "scene"].includes(domain);
return supportsIconAction ? "toggle" : "none";
};
@customElement("hui-tile-card")
export class HuiTileCard extends LitElement implements LovelaceCard {
public static async getConfigElement(): Promise<LovelaceCardEditor> {
@@ -124,12 +120,7 @@ export class HuiTileCard extends LitElement implements LovelaceCard {
}
this._config = {
tap_action: {
action: "more-info",
},
icon_tap_action: {
action: getEntityDefaultTileIconAction(config.entity),
},
...getTileActionDefaults(config.entity),
...config,
};
this._featureContext = {
@@ -173,28 +164,12 @@ export class HuiTileCard extends LitElement implements LovelaceCard {
private _handleIconAction(ev: ActionHandlerEvent) {
ev.stopPropagation();
const config = {
entity: this._config!.entity,
tap_action: this._config!.icon_tap_action,
hold_action: this._config!.icon_hold_action,
double_tap_action: this._config!.icon_double_tap_action,
};
handleAction(this, this.hass!, config, ev.detail.action!);
}
private _getImageUrl(entity: HassEntity): string | undefined {
const entityPicture =
entity.attributes.entity_picture_local ||
entity.attributes.entity_picture;
if (!entityPicture) return undefined;
let imageUrl = this.hass!.hassUrl(entityPicture);
if (computeDomain(entity.entity_id) === "camera") {
imageUrl = cameraUrlWithWidthHeight(imageUrl, 80, 80);
}
return imageUrl;
handleAction(
this,
this.hass!,
getTileIconActionConfig(this._config!.entity, this._config!),
ev.detail.action!
);
}
private _computeStateColor = memoizeOne(
@@ -236,21 +211,6 @@ export class HuiTileCard extends LitElement implements LovelaceCard {
}
);
private get _hasCardAction() {
return (
!this._config?.tap_action ||
hasAction(this._config?.tap_action) ||
hasAction(this._config?.hold_action) ||
hasAction(this._config?.double_tap_action)
);
}
private get _hasIconAction() {
return (
!this._config?.icon_tap_action || hasAction(this._config?.icon_tap_action)
);
}
private _featurePosition = memoizeOne((config: TileCardConfig) => {
if (config.vertical) {
return "bottom";
@@ -303,7 +263,7 @@ export class HuiTileCard extends LitElement implements LovelaceCard {
};
const imageUrl = this._config.show_entity_picture
? this._getImageUrl(stateObj)
? getTileImageUrl(this.hass, stateObj)
: undefined;
const featurePosition = this._featurePosition(this._config);
@@ -320,7 +280,7 @@ export class HuiTileCard extends LitElement implements LovelaceCard {
.featurePosition=${featurePosition}
.vertical=${Boolean(this._config.vertical)}
.fixedInfoHeight=${fixedInfoHeight}
.interactive=${this._hasCardAction}
.interactive=${hasTileCardAction(this._config)}
.actionHandlerOptions=${{
hasHold: hasAction(this._config!.hold_action),
hasDoubleClick: hasAction(this._config!.double_tap_action),
@@ -334,7 +294,7 @@ export class HuiTileCard extends LitElement implements LovelaceCard {
hasHold: hasAction(this._config!.icon_hold_action),
hasDoubleClick: hasAction(this._config!.icon_double_tap_action),
}}
.interactive=${this._hasIconAction}
.interactive=${hasTileIconAction(this._config)}
.imageUrl=${imageUrl}
data-domain=${ifDefined(domain)}
data-state=${ifDefined(stateObj?.state)}
@@ -0,0 +1,64 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { DOMAINS_TOGGLE } from "../../../../common/const";
import { computeDomain } from "../../../../common/entity/compute_domain";
import { cameraUrlWithWidthHeight } from "../../../../data/camera";
import type { HomeAssistantConnection } from "../../../../types";
import type { ActionConfigParams } from "../../common/handle-action";
import { hasAction } from "../../common/has-action";
import type { TileActionsConfig } from "../types";
export const getEntityDefaultTileIconAction = (entityId: string) => {
const domain = computeDomain(entityId);
const supportsIconAction =
DOMAINS_TOGGLE.has(domain) ||
["button", "input_button", "scene"].includes(domain);
return supportsIconAction ? "toggle" : "none";
};
export const getTileActionDefaults = (
entityId: string
): Pick<TileActionsConfig, "tap_action" | "icon_tap_action"> => ({
tap_action: { action: "more-info" },
icon_tap_action: { action: getEntityDefaultTileIconAction(entityId) },
});
export const hasTileCardAction = (config?: TileActionsConfig) =>
!config?.tap_action ||
hasAction(config.tap_action) ||
hasAction(config.hold_action) ||
hasAction(config.double_tap_action);
export const hasTileIconAction = (config?: TileActionsConfig) =>
!config?.icon_tap_action || hasAction(config.icon_tap_action);
export const getTileIconActionConfig = (
entity: string,
config: TileActionsConfig
): ActionConfigParams => ({
entity,
tap_action: config.icon_tap_action,
hold_action: config.icon_hold_action,
double_tap_action: config.icon_double_tap_action,
});
export const getTileImageUrl = (
connection: Pick<HomeAssistantConnection, "hassUrl">,
stateObj: HassEntity,
size = 80
): string | undefined => {
const entityPicture =
stateObj.attributes.entity_picture_local ||
stateObj.attributes.entity_picture;
if (!entityPicture) {
return undefined;
}
const imageUrl = connection.hassUrl(entityPicture);
return computeDomain(stateObj.entity_id) === "camera"
? cameraUrlWithWidthHeight(imageUrl, size, size)
: imageUrl;
};
+19 -8
View File
@@ -686,7 +686,16 @@ export interface WeatherForecastCardConfig extends LovelaceCardConfig {
double_tap_action?: ActionConfig;
}
export interface TileCardConfig extends LovelaceCardConfig {
export interface TileActionsConfig {
tap_action?: ActionConfig;
hold_action?: ActionConfig;
double_tap_action?: ActionConfig;
icon_tap_action?: ActionConfig;
icon_hold_action?: ActionConfig;
icon_double_tap_action?: ActionConfig;
}
export interface TileCardConfig extends LovelaceCardConfig, TileActionsConfig {
entity: string;
name?: string | EntityNameItem | EntityNameItem[];
hide_state?: boolean;
@@ -695,12 +704,6 @@ export interface TileCardConfig extends LovelaceCardConfig {
color?: string;
show_entity_picture?: boolean;
vertical?: boolean;
tap_action?: ActionConfig;
hold_action?: ActionConfig;
double_tap_action?: ActionConfig;
icon_tap_action?: ActionConfig;
icon_hold_action?: ActionConfig;
icon_double_tap_action?: ActionConfig;
features?: LovelaceCardFeatureConfig[];
features_position?: LovelaceCardFeaturePosition;
time_format?: TimestampRenderingFormat;
@@ -736,11 +739,19 @@ export interface ShortcutCardConfig extends LovelaceCardConfig {
double_tap_action?: ActionConfig;
}
export interface AlertCardConfig extends LovelaceCardConfig {
export interface AlertCardConfig extends LovelaceCardConfig, TileActionsConfig {
type: "alert";
entity: string;
name?: string | EntityNameItem | EntityNameItem[];
icon?: string;
color?: string;
inactive_color?: string;
pulse?: boolean;
show_entity_picture?: boolean;
hide_state?: boolean;
state_content?: string | string[];
time_format?: TimestampRenderingFormat;
vertical?: boolean;
}
export interface ToggleGroupCardConfig extends LovelaceCardConfig {
@@ -9,6 +9,7 @@ import {
const ALWAYS_LOADED_TYPES = new Set(["error", "entity"]);
const LAZY_LOAD_TYPES = {
alert: () => import("../badges/hui-alert-badge"),
"entity-filter": () => import("../badges/hui-entity-filter-badge"),
shortcut: () => import("../badges/hui-shortcut-badge"),
"state-label": () => import("../badges/hui-state-label-badge"),
@@ -0,0 +1,35 @@
import { mdiAlertOutline } from "@mdi/js";
import { DEFAULT_ALERT_COLOR } from "../../../../common/entity/alert_active";
import type { HaFormSchema } from "../../../../components/ha-form/types";
export const alertSchema = () =>
({
name: "alert",
type: "expandable",
flatten: true,
iconPath: mdiAlertOutline,
schema: [
{
name: "",
type: "grid",
schema: [
{
name: "inactive_color",
selector: {
ui_color: { include_none: true, default_color: "none" },
},
},
{
name: "color",
selector: {
ui_color: {
include_none: true,
default_color: DEFAULT_ALERT_COLOR,
},
},
},
],
},
{ name: "pulse", selector: { boolean: {} } },
],
}) as const satisfies HaFormSchema;
@@ -0,0 +1,242 @@
import { mdiTextShort } from "@mdi/js";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import type { HaFormSchema } from "../../../../components/ha-form/types";
export interface TileContentFormConfig {
hide_state?: boolean;
state_content?: string | string[];
vertical?: boolean;
content_layout?: string;
}
export interface BadgeContentFormConfig {
show_name?: boolean;
show_state?: boolean;
show_icon?: boolean;
state_content?: string | string[];
displayed_elements?: string[];
}
const colorSchema = {
name: "color",
selector: {
ui_color: {
default_color: "state",
include_state: true,
},
},
} as const satisfies HaFormSchema;
export const tileContentSchema = (
localize: LocalizeFunc,
showTimeFormat: boolean,
includeColor = true
) =>
({
name: "content",
flatten: true,
type: "expandable",
iconPath: mdiTextShort,
schema: [
{
name: "name",
selector: {
entity_name: {},
},
context: { entity: "entity" },
},
{
name: "",
type: "grid",
schema: [
{
name: "icon",
selector: {
icon: {},
},
context: { icon_entity: "entity" },
},
...(includeColor ? [colorSchema] : []),
{
name: "show_entity_picture",
selector: {
boolean: {},
},
},
{
name: "hide_state",
selector: {
boolean: {},
},
},
],
},
{
name: "state_content",
visible: { field: "hide_state", operator: "not_eq", value: true },
selector: {
ui_state_content: {
allow_context: true,
},
},
context: {
filter_entity: "entity",
},
},
{
name: "time_format",
visible: showTimeFormat,
selector: {
ui_time_format: {},
},
},
{
name: "content_layout",
required: true,
selector: {
select: {
mode: "box",
options: ["horizontal", "vertical"].map((value) => ({
label: localize(
`ui.panel.lovelace.editor.card.tile.content_layout_options.${value}`
),
value,
image: {
src: `/static/images/form/tile_content_layout_${value}.svg`,
src_dark: `/static/images/form/tile_content_layout_${value}_dark.svg`,
flip_rtl: true,
},
})),
},
},
},
],
}) as const satisfies HaFormSchema;
export const badgeContentSchema = (
localize: LocalizeFunc,
showTimeFormat: boolean,
includeColor = true
) =>
({
name: "content",
type: "expandable",
flatten: true,
iconPath: mdiTextShort,
schema: [
{
name: "name",
selector: {
entity_name: {},
},
context: { entity: "entity" },
},
{
name: "",
type: "grid",
schema: [
...(includeColor ? [colorSchema] : []),
{
name: "icon",
selector: {
icon: {},
},
context: { icon_entity: "entity" },
},
{
name: "show_entity_picture",
selector: {
boolean: {},
},
},
],
},
{
name: "displayed_elements",
selector: {
select: {
mode: "list",
multiple: true,
options: (["name", "state", "icon"] as const).map((value) => ({
value,
label: localize(
`ui.panel.lovelace.editor.badge.entity.displayed_elements_options.${value}`
),
})),
},
},
},
{
name: "state_content",
selector: {
ui_state_content: {
allow_name: true,
},
},
context: {
filter_entity: "entity",
},
},
{
name: "time_format",
visible: showTimeFormat,
selector: {
ui_time_format: {},
},
},
],
}) as const satisfies HaFormSchema;
export const tileContentFormData = <T extends TileContentFormConfig>(
config: T
): T => ({
...config,
content_layout: config.vertical ? "vertical" : "horizontal",
});
export const tileContentConfigFromForm = <T extends TileContentFormConfig>(
value: T
): T => {
const config = { ...value };
if (config.hide_state || !config.state_content) {
delete config.state_content;
}
if (config.content_layout) {
config.vertical = config.content_layout === "vertical";
delete config.content_layout;
}
return config;
};
export const badgeContentFormData = <T extends BadgeContentFormConfig>(
config: T
): T => ({
...config,
displayed_elements: [
...(config.show_name ? ["name"] : []),
...(config.show_state ? ["state"] : []),
...(config.show_icon ? ["icon"] : []),
],
});
export const badgeContentConfigFromForm = <T extends BadgeContentFormConfig>(
value: T
): T => {
const config = { ...value };
if (!config.state_content) {
delete config.state_content;
}
if (config.displayed_elements) {
config.show_name = config.displayed_elements.includes("name");
config.show_state = config.displayed_elements.includes("state");
config.show_icon = config.displayed_elements.includes("icon");
delete config.displayed_elements;
}
return config;
};
@@ -0,0 +1,173 @@
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import {
array,
assert,
assign,
boolean,
object,
optional,
string,
union,
} from "superstruct";
import { fireEvent } from "../../../../common/dom/fire_event";
import { ALERT_DOMAINS } from "../../../../common/entity/alert_active";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/ha-form/ha-form";
import type {
HaFormSchema,
SchemaUnion,
} from "../../../../components/ha-form/types";
import { stateContentHasTimestamp } from "../../../../state-display/state-display";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type { AlertBadgeConfig } from "../../badges/types";
import { ALERT_BADGE_DEFAULT_CONFIG } from "../../badges/hui-alert-badge";
import { timeFormatConfigStruct } from "../../components/types";
import type { LovelaceBadgeEditor } from "../../types";
import { actionConfigStruct } from "../structs/action-struct";
import { baseLovelaceBadgeConfig } from "../structs/base-badge-struct";
import { entityNameStruct } from "../structs/entity-name-struct";
import { alertSchema } from "./alert-schema";
import {
badgeContentConfigFromForm,
badgeContentFormData,
badgeContentSchema,
} from "./content-schema";
import { badgeInteractionsSchema } from "./interactions-schema";
const badgeConfigStruct = assign(
baseLovelaceBadgeConfig,
object({
entity: optional(string()),
name: optional(entityNameStruct),
icon: optional(string()),
color: optional(string()),
inactive_color: optional(string()),
pulse: optional(boolean()),
show_entity_picture: optional(boolean()),
show_name: optional(boolean()),
show_state: optional(boolean()),
show_icon: optional(boolean()),
state_content: optional(union([string(), array(string())])),
time_format: optional(timeFormatConfigStruct),
tap_action: optional(actionConfigStruct),
hold_action: optional(actionConfigStruct),
double_tap_action: optional(actionConfigStruct),
})
);
@customElement("hui-alert-badge-editor")
export class HuiAlertBadgeEditor
extends LitElement
implements LovelaceBadgeEditor
{
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: AlertBadgeConfig;
public setConfig(config: AlertBadgeConfig): void {
assert(config, badgeConfigStruct);
this._config = { ...ALERT_BADGE_DEFAULT_CONFIG, ...config };
}
private _schema = memoizeOne(
(localize: LocalizeFunc, showTimeFormat: boolean) =>
[
{
name: "entity",
required: true,
selector: { entity: { filter: { domain: ALERT_DOMAINS } } },
},
alertSchema(),
badgeContentSchema(localize, showTimeFormat, false),
badgeInteractionsSchema(),
] as const satisfies readonly HaFormSchema[]
);
private _formData = memoizeOne(badgeContentFormData<AlertBadgeConfig>);
protected render() {
if (!this.hass || !this._config) {
return nothing;
}
const entityId = this._config.entity;
const schema = this._schema(
this.hass.localize,
stateContentHasTimestamp(
entityId,
this.hass.states[entityId],
this._config.state_content
)
);
return html`
<ha-form
.hass=${this.hass}
.data=${this._formData(this._config)}
.schema=${schema}
.computeLabel=${this._computeLabelCallback}
.computeHelper=${this._computeHelperCallback}
@value-changed=${this._valueChanged}
></ha-form>
`;
}
private _valueChanged(ev: ValueChangedEvent<AlertBadgeConfig>): void {
ev.stopPropagation();
const config = badgeContentConfigFromForm(ev.detail.value);
fireEvent(this, "config-changed", { config });
}
private _computeLabelCallback = (
schema: SchemaUnion<ReturnType<typeof this._schema>>
) => {
switch (schema.name) {
case "pulse":
case "inactive_color":
return this.hass!.localize(
`ui.panel.lovelace.editor.card.alert.${schema.name}`
);
case "alert":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.alert.alert_section"
);
case "show_entity_picture":
case "state_content":
case "displayed_elements":
return this.hass!.localize(
`ui.panel.lovelace.editor.badge.entity.${schema.name}`
);
default:
return this.hass!.localize(
`ui.panel.lovelace.editor.card.generic.${schema.name}`
);
}
};
private _computeHelperCallback = (
schema: SchemaUnion<ReturnType<typeof this._schema>>
) => {
if (
schema.name === "pulse" ||
schema.name === "color" ||
schema.name === "inactive_color"
) {
return this.hass?.localize(
`ui.panel.lovelace.editor.card.alert.${schema.name}_helper`
);
}
return undefined;
};
}
declare global {
interface HTMLElementTagNameMap {
"hui-alert-badge-editor": HuiAlertBadgeEditor;
}
}
@@ -0,0 +1,183 @@
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import {
array,
assert,
assign,
boolean,
object,
optional,
string,
union,
} from "superstruct";
import { fireEvent } from "../../../../common/dom/fire_event";
import { ALERT_DOMAINS } from "../../../../common/entity/alert_active";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/ha-form/ha-form";
import type {
HaFormSchema,
SchemaUnion,
} from "../../../../components/ha-form/types";
import { stateContentHasTimestamp } from "../../../../state-display/state-display";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type { AlertCardConfig } from "../../cards/types";
import { timeFormatConfigStruct } from "../../components/types";
import type { LovelaceCardEditor } from "../../types";
import { actionConfigStruct } from "../structs/action-struct";
import { baseLovelaceCardConfig } from "../structs/base-card-struct";
import { entityNameStruct } from "../structs/entity-name-struct";
import { alertSchema } from "./alert-schema";
import {
tileContentConfigFromForm,
tileContentFormData,
tileContentSchema,
} from "./content-schema";
import { tileInteractionsSchema } from "./interactions-schema";
const cardConfigStruct = assign(
baseLovelaceCardConfig,
object({
entity: optional(string()),
name: optional(entityNameStruct),
icon: optional(string()),
color: optional(string()),
inactive_color: optional(string()),
pulse: optional(boolean()),
show_entity_picture: optional(boolean()),
hide_state: optional(boolean()),
state_content: optional(union([string(), array(string())])),
time_format: optional(timeFormatConfigStruct),
vertical: optional(boolean()),
tap_action: optional(actionConfigStruct),
hold_action: optional(actionConfigStruct),
double_tap_action: optional(actionConfigStruct),
icon_tap_action: optional(actionConfigStruct),
icon_hold_action: optional(actionConfigStruct),
icon_double_tap_action: optional(actionConfigStruct),
})
);
@customElement("hui-alert-card-editor")
export class HuiAlertCardEditor
extends LitElement
implements LovelaceCardEditor
{
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: AlertCardConfig;
public setConfig(config: AlertCardConfig): void {
assert(config, cardConfigStruct);
this._config = config;
}
private _schema = memoizeOne(
(
localize: LocalizeFunc,
entityId: string | undefined,
showTimeFormat: boolean
) =>
[
{
name: "entity",
required: true,
selector: { entity: { filter: { domain: ALERT_DOMAINS } } },
},
alertSchema(),
tileContentSchema(localize, showTimeFormat, false),
tileInteractionsSchema(entityId),
] as const satisfies readonly HaFormSchema[]
);
protected render() {
if (!this.hass || !this._config) {
return nothing;
}
const entityId = this._config.entity;
const schema = this._schema(
this.hass.localize,
entityId,
!this._config.hide_state &&
Boolean(this._config.state_content) &&
stateContentHasTimestamp(
entityId,
this.hass.states[entityId],
this._config.state_content
)
);
return html`
<ha-form
.hass=${this.hass}
.data=${tileContentFormData(this._config)}
.schema=${schema}
.computeLabel=${this._computeLabelCallback}
.computeHelper=${this._computeHelperCallback}
@value-changed=${this._valueChanged}
></ha-form>
`;
}
private _valueChanged(ev: ValueChangedEvent<AlertCardConfig>): void {
ev.stopPropagation();
const config = tileContentConfigFromForm(ev.detail.value);
fireEvent(this, "config-changed", { config });
}
private _computeLabelCallback = (
schema: SchemaUnion<ReturnType<typeof this._schema>>
) => {
switch (schema.name) {
case "pulse":
case "inactive_color":
return this.hass!.localize(
`ui.panel.lovelace.editor.card.alert.${schema.name}`
);
case "alert":
return this.hass!.localize(
"ui.panel.lovelace.editor.card.alert.alert_section"
);
case "icon_tap_action":
case "icon_hold_action":
case "icon_double_tap_action":
case "show_entity_picture":
case "hide_state":
case "state_content":
case "content_layout":
return this.hass!.localize(
`ui.panel.lovelace.editor.card.tile.${schema.name}`
);
default:
return this.hass!.localize(
`ui.panel.lovelace.editor.card.generic.${schema.name}`
);
}
};
private _computeHelperCallback = (
schema: SchemaUnion<ReturnType<typeof this._schema>>
) => {
if (
schema.name === "pulse" ||
schema.name === "color" ||
schema.name === "inactive_color"
) {
return this.hass?.localize(
`ui.panel.lovelace.editor.card.alert.${schema.name}_helper`
);
}
return undefined;
};
}
declare global {
interface HTMLElementTagNameMap {
"hui-alert-card-editor": HuiAlertCardEditor;
}
}
@@ -1,4 +1,3 @@
import { mdiGestureTap, mdiTextShort } from "@mdi/js";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
@@ -20,7 +19,7 @@ import type {
HaFormSchema,
SchemaUnion,
} from "../../../../components/ha-form/types";
import type { HomeAssistant } from "../../../../types";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import {
DEFAULT_CONFIG,
DISPLAY_TYPES,
@@ -28,11 +27,16 @@ import {
} from "../../badges/hui-entity-badge";
import type { EntityBadgeConfig } from "../../badges/types";
import type { LovelaceBadgeEditor } from "../../types";
import { ACTION_RELATED_CONTEXT } from "../../components/hui-action-editor";
import { actionConfigStruct } from "../structs/action-struct";
import { baseLovelaceBadgeConfig } from "../structs/base-badge-struct";
import { entityNameStruct } from "../structs/entity-name-struct";
import { configElementStyle } from "./config-elements-style";
import {
badgeContentConfigFromForm,
badgeContentFormData,
badgeContentSchema,
} from "./content-schema";
import { badgeInteractionsSchema } from "./interactions-schema";
import { stateContentHasTimestamp } from "../../../../state-display/state-display";
import { timeFormatConfigStruct } from "../../components/types";
@@ -78,148 +82,12 @@ export class HuiEntityBadgeEditor
(localize: LocalizeFunc, showTimeFormat: boolean) =>
[
{ name: "entity", selector: { entity: {} } },
{
name: "content",
type: "expandable",
flatten: true,
iconPath: mdiTextShort,
schema: [
{
name: "name",
selector: {
entity_name: {},
},
context: { entity: "entity" },
},
{
name: "",
type: "grid",
schema: [
{
name: "color",
selector: {
ui_color: {
default_color: "state",
include_state: true,
},
},
},
{
name: "icon",
selector: {
icon: {},
},
context: { icon_entity: "entity" },
},
{
name: "show_entity_picture",
selector: {
boolean: {},
},
},
],
},
{
name: "displayed_elements",
selector: {
select: {
mode: "list",
multiple: true,
options: [
{
value: "name",
label: localize(
`ui.panel.lovelace.editor.badge.entity.displayed_elements_options.name`
),
},
{
value: "state",
label: localize(
`ui.panel.lovelace.editor.badge.entity.displayed_elements_options.state`
),
},
{
value: "icon",
label: localize(
`ui.panel.lovelace.editor.badge.entity.displayed_elements_options.icon`
),
},
],
},
},
},
{
name: "state_content",
selector: {
ui_state_content: {
allow_name: true,
},
},
context: {
filter_entity: "entity",
},
},
...(showTimeFormat
? ([
{
name: "time_format",
selector: {
ui_time_format: {},
},
},
] as const satisfies readonly HaFormSchema[])
: []),
],
},
{
name: "interactions",
type: "expandable",
flatten: true,
iconPath: mdiGestureTap,
schema: [
{
name: "tap_action",
selector: {
ui_action: {
default_action: "more-info",
},
},
context: ACTION_RELATED_CONTEXT,
},
{
name: "",
type: "optional_actions",
flatten: true,
schema: (["hold_action", "double_tap_action"] as const).map(
(action) => ({
name: action,
selector: {
ui_action: {
default_action: "none" as const,
},
},
context: ACTION_RELATED_CONTEXT,
})
),
},
],
},
badgeContentSchema(localize, showTimeFormat),
badgeInteractionsSchema(),
] as const satisfies readonly HaFormSchema[]
);
_displayedElements = memoizeOne((config: EntityBadgeConfig) => {
const elements: string[] = [];
if (config.show_name) {
elements.push("name");
}
if (config.show_state) {
elements.push("state");
}
if (config.show_icon) {
elements.push("icon");
}
return elements;
});
private _formData = memoizeOne(badgeContentFormData<EntityBadgeConfig>);
protected render() {
if (!this.hass || !this._config) {
@@ -238,10 +106,7 @@ export class HuiEntityBadgeEditor
const schema = this._schema(this.hass!.localize, showTimeFormat);
const data = {
...this._config,
displayed_elements: this._displayedElements(this._config),
};
const data = this._formData(this._config);
return html`
<ha-form
@@ -255,24 +120,13 @@ export class HuiEntityBadgeEditor
`;
}
private _valueChanged(ev: CustomEvent): void {
private _valueChanged(ev: ValueChangedEvent<EntityBadgeConfig>): void {
ev.stopPropagation();
if (!this._config || !this.hass) {
return;
}
const config = { ...ev.detail.value } as EntityBadgeConfig;
if (!config.state_content) {
delete config.state_content;
}
if (config.displayed_elements) {
config.show_name = config.displayed_elements.includes("name");
config.show_state = config.displayed_elements.includes("state");
config.show_icon = config.displayed_elements.includes("icon");
delete config.displayed_elements;
}
const config = badgeContentConfigFromForm(ev.detail.value);
fireEvent(this, "config-changed", { config });
}
@@ -1,4 +1,4 @@
import { mdiGestureTap, mdiListBox, mdiTextShort } from "@mdi/js";
import { mdiListBox } from "@mdi/js";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
@@ -30,8 +30,6 @@ import type {
LovelaceCardFeatureConfig,
LovelaceCardFeatureContext,
} from "../../card-features/types";
import { ACTION_RELATED_CONTEXT } from "../../components/hui-action-editor";
import { getEntityDefaultTileIconAction } from "../../cards/hui-tile-card";
import type { TileCardConfig } from "../../cards/types";
import type { LovelaceCardEditor } from "../../types";
import { actionConfigStruct } from "../structs/action-struct";
@@ -39,7 +37,13 @@ import { baseLovelaceCardConfig } from "../structs/base-card-struct";
import { entityNameStruct } from "../structs/entity-name-struct";
import type { EditDetailElementEvent, EditSubElementEvent } from "../types";
import { configElementStyle } from "./config-elements-style";
import {
tileContentConfigFromForm,
tileContentFormData,
tileContentSchema,
} from "./content-schema";
import { getSupportedFeaturesType } from "./hui-card-features-editor";
import { tileInteractionsSchema } from "./interactions-schema";
import { stateContentHasTimestamp } from "../../../../state-display/state-display";
import { timeFormatConfigStruct } from "../../components/types";
@@ -96,147 +100,8 @@ export class HuiTileCardEditor
) =>
[
{ name: "entity", selector: { entity: {} } },
{
name: "content",
flatten: true,
type: "expandable",
iconPath: mdiTextShort,
schema: [
{
name: "name",
selector: {
entity_name: {},
},
context: { entity: "entity" },
},
{
name: "",
type: "grid",
schema: [
{
name: "icon",
selector: {
icon: {},
},
context: { icon_entity: "entity" },
},
{
name: "color",
selector: {
ui_color: {
default_color: "state",
include_state: true,
},
},
},
{
name: "show_entity_picture",
selector: {
boolean: {},
},
},
{
name: "hide_state",
selector: {
boolean: {},
},
},
],
},
{
name: "state_content",
visible: { field: "hide_state", operator: "not_eq", value: true },
selector: {
ui_state_content: {
allow_context: true,
},
},
context: {
filter_entity: "entity",
},
},
{
name: "time_format",
visible: showTimeFormat,
selector: {
ui_time_format: {},
},
},
{
name: "content_layout",
required: true,
selector: {
select: {
mode: "box",
options: ["horizontal", "vertical"].map((value) => ({
label: localize(
`ui.panel.lovelace.editor.card.tile.content_layout_options.${value}`
),
value,
image: {
src: `/static/images/form/tile_content_layout_${value}.svg`,
src_dark: `/static/images/form/tile_content_layout_${value}_dark.svg`,
flip_rtl: true,
},
})),
},
},
},
],
},
{
name: "interactions",
type: "expandable",
flatten: true,
iconPath: mdiGestureTap,
schema: [
{
name: "tap_action",
selector: {
ui_action: {
default_action: "more-info",
},
},
context: ACTION_RELATED_CONTEXT,
},
{
name: "",
type: "divider",
},
{
name: "icon_tap_action",
selector: {
ui_action: {
default_action: entityId
? getEntityDefaultTileIconAction(entityId)
: "more-info",
},
},
context: ACTION_RELATED_CONTEXT,
},
{
name: "",
type: "optional_actions",
flatten: true,
schema: (
[
"hold_action",
"icon_hold_action",
"double_tap_action",
"icon_double_tap_action",
] as const
).map((action) => ({
name: action,
selector: {
ui_action: {
default_action: "none" as const,
},
},
context: ACTION_RELATED_CONTEXT,
})),
},
],
},
tileContentSchema(localize, showTimeFormat),
tileInteractionsSchema(entityId),
] as const satisfies readonly HaFormSchema[]
);
@@ -296,10 +161,7 @@ export class HuiTileCardEditor
const featuresSchema = this._featuresSchema(this.hass.localize, vertical);
const data = {
...this._config,
content_layout: vertical ? "vertical" : "horizontal",
};
const data = tileContentFormData(this._config);
// Default features position to bottom and force it to bottom in vertical mode
if (!data.features_position || vertical) {
@@ -362,24 +224,10 @@ export class HuiTileCardEditor
const newConfig = ev.detail.value as TileCardConfig;
let config: TileCardConfig = {
let config: TileCardConfig = tileContentConfigFromForm({
features: this._config.features,
...newConfig,
};
if (config.hide_state) {
delete config.state_content;
}
if (!config.state_content) {
delete config.state_content;
}
// Convert content_layout to vertical
if (config.content_layout) {
config.vertical = config.content_layout === "vertical";
delete config.content_layout;
}
});
config = orderProperties(config, fieldOrder);
@@ -0,0 +1,94 @@
import { mdiGestureTap } from "@mdi/js";
import type { HaFormSchema } from "../../../../components/ha-form/types";
import { getEntityDefaultTileIconAction } from "../../cards/tile/tile-card-helpers";
import { ACTION_RELATED_CONTEXT } from "../../components/hui-action-editor";
export const tileInteractionsSchema = (entityId: string | undefined) =>
({
name: "interactions",
type: "expandable",
flatten: true,
iconPath: mdiGestureTap,
schema: [
{
name: "tap_action",
selector: {
ui_action: {
default_action: "more-info",
},
},
context: ACTION_RELATED_CONTEXT,
},
{
name: "",
type: "divider",
},
{
name: "icon_tap_action",
selector: {
ui_action: {
default_action: entityId
? getEntityDefaultTileIconAction(entityId)
: "more-info",
},
},
context: ACTION_RELATED_CONTEXT,
},
{
name: "",
type: "optional_actions",
flatten: true,
schema: (
[
"hold_action",
"icon_hold_action",
"double_tap_action",
"icon_double_tap_action",
] as const
).map((action) => ({
name: action,
selector: {
ui_action: {
default_action: "none" as const,
},
},
context: ACTION_RELATED_CONTEXT,
})),
},
],
}) as const satisfies HaFormSchema;
export const badgeInteractionsSchema = () =>
({
name: "interactions",
type: "expandable",
flatten: true,
iconPath: mdiGestureTap,
schema: [
{
name: "tap_action",
selector: {
ui_action: {
default_action: "more-info",
},
},
context: ACTION_RELATED_CONTEXT,
},
{
name: "",
type: "optional_actions",
flatten: true,
schema: (["hold_action", "double_tap_action"] as const).map(
(action) => ({
name: action,
selector: {
ui_action: {
default_action: "none" as const,
},
},
context: ACTION_RELATED_CONTEXT,
})
),
},
],
}) as const satisfies HaFormSchema;
@@ -9,4 +9,8 @@ export const coreBadges: Badge[] = [
type: "shortcut",
showElement: true,
},
{
type: "alert",
showElement: true,
},
];
@@ -141,6 +141,10 @@ export const coreCards: Card[] = [
type: "shortcut",
showElement: true,
},
{
type: "alert",
showElement: true,
},
];
export const energyCards: Card[] = [
@@ -4,6 +4,7 @@ import { css, html, LitElement, nothing, type PropertyValues } from "lit";
import { customElement, property, state } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import { consume } from "../../../common/decorators/consume";
import { ALERT_DOMAINS } from "../../../common/entity/alert_active";
import { computeEntityPickerDisplay } from "../../../common/entity/compute_entity_name_display";
import {
fireEvent,
@@ -94,6 +95,7 @@ export class SecurityAlertsEditor extends LitElement {
"ui.panel.security.editor.add_alert_entity"
)}
.excludeEntities=${this.alertEntities.map(({ entity }) => entity)}
.includeDomains=${ALERT_DOMAINS}
.entityFilter=${this._entityFilter}
@value-changed=${this._add}
></ha-entity-picker>
@@ -1,5 +1,8 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { ensureArray } from "../../../common/array/ensure-array";
import {
computeAlertActiveStates,
isAlertActive,
} from "../../../common/entity/alert_active";
import { computeDomain } from "../../../common/entity/compute_domain";
import type {
SecurityAlertEntityConfig,
@@ -55,26 +58,15 @@ export const computeDefaultSecurityAlertSeverity = (
export const computeDefaultSecurityAlertVisibility = (
entityId: string
): StateCondition[] => {
const condition: StateCondition = {
condition: "state",
entity: entityId,
};
const states = computeAlertActiveStates(entityId);
switch (computeDomain(entityId)) {
case "alarm_control_panel":
condition.state = "triggered";
break;
case "cover":
condition.state = "open";
break;
case "lock":
condition.state = ["jammed", "unlocked", "open"];
break;
default:
condition.state = "on";
}
return [condition];
return [
{
condition: "state",
entity: entityId,
state: states.length === 1 ? states[0] : states,
},
];
};
export const resolveSecurityAlertSeverity = (
@@ -88,8 +80,8 @@ export const isSecurityAlertActive = (
entityId: string
): boolean => {
const stateObj = states[entityId];
const [{ state }] = computeDefaultSecurityAlertVisibility(entityId);
return !!stateObj && !!state && ensureArray(state).includes(stateObj.state);
return !!stateObj && isAlertActive(stateObj);
};
export const filterSecurityAlertEntities = (
@@ -3,6 +3,8 @@ import { ReactiveElement } from "lit";
import { customElement } from "lit/decorators";
import { getAreasFloorHierarchy } from "../../../common/areas/areas-floor-hierarchy";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import { ALERT_DOMAINS } from "../../../common/entity/alert_active";
import { computeDomain } from "../../../common/entity/compute_domain";
import {
findEntities,
generateEntityFilter,
@@ -313,12 +315,16 @@ export class SecurityViewStrategy extends ReactiveElement {
const sidebarSections: LovelaceSectionConfig[] = [];
const alertCards = config.alert_entities?.map((alertEntity) =>
computeSecurityAlertCardConfig(
hass.states[alertEntity.entity],
alertEntity
const alertCards = config.alert_entities
?.filter((alertEntity) =>
ALERT_DOMAINS.includes(computeDomain(alertEntity.entity))
)
);
.map((alertEntity) =>
computeSecurityAlertCardConfig(
hass.states[alertEntity.entity],
alertEntity
)
);
if (alertCards?.length) {
sidebarSections.push({
+14
View File
@@ -10317,6 +10317,16 @@
"available_states": "Available states",
"description": "This card allows you to arm and disarm your alarm control panel integrations."
},
"alert": {
"name": "Alert",
"description": "This card highlights an entity that needs attention, with an optional color and pulsing background.",
"color_helper": "Used while the entity is in an alert state, such as a binary sensor that is on or an unlocked lock.",
"inactive_color": "Inactive color",
"inactive_color_helper": "Used when the entity isn't in an alert state. The background doesn't pulse.",
"pulse": "Pulse",
"pulse_helper": "Animates the colored background while the entity is in an alert state. When reduced motion is on, the background stays tinted instead.",
"alert_section": "Alert"
},
"area": {
"name": "Area",
"color": "[%key:ui::panel::lovelace::editor::card::tile::color%]",
@@ -11111,6 +11121,10 @@
"state_filter": "[%key:ui::panel::lovelace::editor::card::picture-elements::state_filter%]"
},
"badge": {
"alert": {
"name": "Alert",
"description": "A badge that highlights an entity that needs attention, with an optional color and pulsing background."
},
"entity": {
"name": "Entity",
"description": "The Entity badge gives you a quick overview of an entity.",
@@ -1,83 +0,0 @@
import { describe, expect, it } from "vitest";
import { canOverrideAlphanumericInput } from "../../../src/common/dom/can-override-input";
// jsdom does not implement isContentEditable — it is undefined on every element,
// including one carrying contenteditable="true". These stubs therefore describe
// the shape the function actually reads rather than using real elements.
const stub = (props: Record<string, unknown>) =>
props as unknown as EventTarget;
describe("canOverrideAlphanumericInput", () => {
it("allows shortcuts on a plain element", () => {
expect(canOverrideAlphanumericInput([stub({ tagName: "DIV" })])).toBe(true);
});
it("blocks shortcuts in a textarea", () => {
expect(canOverrideAlphanumericInput([stub({ tagName: "TEXTAREA" })])).toBe(
false
);
});
it("blocks shortcuts in a text input", () => {
expect(
canOverrideAlphanumericInput([stub({ tagName: "INPUT", type: "text" })])
).toBe(false);
});
it("allows shortcuts on inputs that are not typed into", () => {
for (const type of ["button", "checkbox", "hidden", "radio", "range"]) {
expect(
canOverrideAlphanumericInput([stub({ tagName: "INPUT", type })])
).toBe(true);
}
});
it("blocks shortcuts in a contenteditable element", () => {
expect(
canOverrideAlphanumericInput([
stub({ tagName: "DIV", isContentEditable: true }),
])
).toBe(false);
});
it("blocks shortcuts when a contenteditable element is the event target inside a shadow root", () => {
expect(
canOverrideAlphanumericInput([
stub({ tagName: "SPAN", isContentEditable: true }),
stub({ tagName: "DIV" }),
stub({ tagName: "MY-CARD" }),
])
).toBe(false);
});
it("blocks shortcuts inside a code editor", () => {
expect(
canOverrideAlphanumericInput([
stub({ tagName: "DIV" }),
stub({ tagName: "HA-CODE-EDITOR" }),
])
).toBe(false);
});
it("blocks shortcuts inside a menu", () => {
expect(
canOverrideAlphanumericInput([
stub({ tagName: "DIV" }),
stub({ tagName: "HA-MENU" }),
])
).toBe(false);
});
it("blocks shortcuts on a select or dropdown child", () => {
expect(
canOverrideAlphanumericInput([
stub({ tagName: "DIV", parentElement: { tagName: "HA-SELECT" } }),
])
).toBe(false);
expect(
canOverrideAlphanumericInput([
stub({ tagName: "DIV", parentElement: { tagName: "HA-DROPDOWN" } }),
])
).toBe(false);
});
});