Compare commits

..
Author SHA1 Message Date
Maarten Lakerveld 4171b95acb Hide maintenance entities through Lovelace edit mode
Admins can hide entities from the maintenance page and the Home maintenance summary. The hidden ids are stored as the strategy's `hidden` option in frontend system data. The maintenance panel becomes a subclass of a new HaHomeSummaryPanelBase that holds loading, saving and edit mode, so the climate and lights pages can reuse them.

The pencil turns on real Lovelace edit mode, and the panel hands hui-view the strategy view instead of a generated one. Lovelace already knows which content a strategy generated: sections view, header, footer, sidebar and badges now skip their layout tools for a strategy view, its sections count as strategy content, and its cards aren't previewed.

In edit mode a strategy can set `metadata` on the cards it generates, only for the controls that apply. The maintenance tiles get `{ id, hideable: true }`, and grid sections wrap such cards in a show/hide toggle that fires `item-visibility-changed`. Other generated cards are inert while editing. While editing, the panel leaves `hidden` out so hidden tiles show, dimmed from `lovelace.hiddenIds`.

The panel sets `strategyEditSupport` on Lovelace to say it applies these controls. Only then does hui-view pass `editMode` to the view strategy and regenerate it when edit mode changes, and only then do grid sections show the toggles and make the other generated cards inert. A strategy view on a regular dashboard gets no controls that nothing would save.

A toggle saves and hands the view a new Lovelace object with the same config, so nothing rebuilds and focus stays on the toggle.

The view container now uses min-height: 100%, the value the climate and lights panels get once they move onto the base.

This replaces #55610, reverted in #55979, which faked edit mode with an entity-visibility wrapper card that any YAML dashboard could use.
2026-11-30 15:36:20 +01:00
41 changed files with 859 additions and 695 deletions

No files matched your search

@@ -1,74 +0,0 @@
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type {
ConditionContext,
VisibilityCondition,
} from "../../panels/lovelace/common/validate-condition";
import { addEntityToCondition } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
import type { ConditionEvaluation } from "../controllers/condition-evaluator-controller";
import { ConditionEvaluatorController } from "../controllers/condition-evaluator-controller";
import { dropInvalidConditions } from "./sanitize";
export interface VisibilitySubscription {
/** Pass each new hass object so client-side conditions check again. */
update(hass: HomeAssistant): void;
/** Close the subscriptions. `onChange` is not called again. */
unsubscribe(): void;
}
/**
* Live visibility of a list of dashboard visibility conditions, for code
* without a Lit host, such as custom cards and plugins. Conditions core
* evaluates are subscribed to; the rest are checked locally. Reports
* `unknown` until core replies.
*/
export const subscribeVisibility = (
hass: HomeAssistant,
conditions: VisibilityCondition[],
onChange: (result: ConditionEvaluation, error?: string) => void,
context: ConditionContext = {}
): VisibilitySubscription => {
// The controller only needs a host to register with and to re-render.
const host: ReactiveControllerHost = {
addController: () => undefined,
removeController: () => undefined,
requestUpdate: () => undefined,
updateComplete: Promise.resolve(true),
};
let active = true;
const controller = new ConditionEvaluatorController(host, {
resubscribeDelay: 0,
onResult: (result, error) => {
if (active) {
onChange(result, error);
}
},
});
const sanitized = dropInvalidConditions(conditions);
const { entity_id: entityId } = context;
// Core-evaluated conditions never see the context, so fold its entity in
// first, as the dashboard mixin does.
const validConditions = entityId
? sanitized.map((condition) => addEntityToCondition(condition, entityId))
: sanitized;
const getContext = () => context;
controller.hostConnected();
controller.observe(validConditions, hass, getContext);
return {
update: (newHass) => {
if (active) {
controller.observe(validConditions, newHass, getContext);
}
},
unsubscribe: () => {
active = false;
controller.hostDisconnected();
},
};
};
+17 -2
View File
@@ -163,9 +163,21 @@ export const findEntities = (
return results;
};
export const excludeEntities = (
entityIds: string[],
excludedEntityIds?: string[]
): string[] => {
if (!excludedEntityIds?.length) {
return entityIds;
}
const excluded = new Set(excludedEntityIds);
return entityIds.filter((entityId) => !excluded.has(entityId));
};
export const findFilteredEntities = (
sources: EntityFilterSources,
filters: EntityFilter[]
filters: EntityFilter[],
excludedEntityIds?: string[]
): string[] => {
const filterFuncs = filters.map((filter) =>
generateEntityFilter(
@@ -177,5 +189,8 @@ export const findFilteredEntities = (
filter
)
);
return findEntities(Object.keys(sources.states), filterFuncs);
return excludeEntities(
findEntities(Object.keys(sources.states), filterFuncs),
excludedEntityIds
);
};
+3 -29
View File
@@ -22,10 +22,7 @@ import type { LocalizeFunc } from "../../common/translations/localize";
import { nextRender } from "../../common/util/render-status";
import type { CameraCapabilities, CameraEntity } from "../../data/camera";
import type { CameraStreamStatus } from "../../data/camera-streams";
import {
showCameraStreamInfoDialog,
type CameraStreamInfo,
} from "../../dialogs/camera/show-dialog-camera-stream-info";
import { showCameraStreamInfoDialog } from "../../dialogs/camera/show-dialog-camera-stream-info";
import "../ha-camera-stream";
import type { HaCameraStream } from "../ha-camera-stream";
import "../ha-icon-button";
@@ -111,8 +108,6 @@ export class HaCameraPlayer extends LitElement {
@state() private _capabilities?: CameraCapabilities;
private _streamInfoCallbacks = new Set<(info: CameraStreamInfo) => void>();
@state() private _video?: HTMLVideoElement;
@state() private _muted = false;
@@ -218,7 +213,6 @@ export class HaCameraPlayer extends LitElement {
);
clearTimeout(this._controlsTimeout);
clearTimeout(this._wheelHintTimeout);
this._streamInfoCallbacks.clear();
this._unbindVideo(this._video);
this._video = undefined;
this._pointers.clear();
@@ -258,10 +252,6 @@ export class HaCameraPlayer extends LitElement {
this._unbindVideo(changedProps.get("_video") as HTMLVideoElement);
this._bindVideo(this._video);
}
if (changedProps.has("_status") || changedProps.has("_capabilities")) {
const info = this._streamInfo();
this._streamInfoCallbacks.forEach((callback) => callback(info));
}
}
protected render() {
@@ -612,26 +602,10 @@ export class HaCameraPlayer extends LitElement {
this._posterSize = ev.detail.size;
}
private _streamInfo(): CameraStreamInfo {
return {
status: this._status,
supportedTypes: this._capabilities?.frontend_stream_types,
};
}
private _subscribeStreamInfo = (
callback: (info: CameraStreamInfo) => void
) => {
this._streamInfoCallbacks.add(callback);
callback(this._streamInfo());
return () => {
this._streamInfoCallbacks.delete(callback);
};
};
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
subscribe: this._subscribeStreamInfo,
status: this._status,
supportedTypes: this._capabilities?.frontend_stream_types,
});
}
-9
View File
@@ -73,15 +73,6 @@ export class HaDropdown extends Dropdown {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/naming-convention
private override async showMenu() {
// Flip away from the safe areas instead of opening into them, where the
// max-height below would squeeze the menu.
const styles = getComputedStyle(this);
// @ts-ignore flipPadding is typed as a number, floating-ui accepts sides
this.popup.flipPadding = {
top: parseFloat(styles.getPropertyValue("--safe-area-inset-top")) || 0,
bottom:
parseFloat(styles.getPropertyValue("--safe-area-inset-bottom")) || 0,
};
// @ts-ignore
await super.showMenu();
const triggerElement = this.getTrigger();
+15 -47
View File
@@ -23,7 +23,6 @@ import {
getPanelIcon,
getPanelIconPath,
getPanelTitle,
getSelectedPanelUrlPath,
} from "../data/panel";
import type { PersistentNotification } from "../data/persistent_notification";
import { subscribeNotifications } from "../data/persistent_notification";
@@ -232,36 +231,12 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
return nothing;
}
const selectedPanel = this.hass.panelUrl;
// prettier-ignore
return html`
${this._renderHeader()}
${this._renderAllPanels()}`;
}
private _computeSidebarPanels(): [PanelInfo[], PanelInfo[]] | undefined {
if (!this._panelOrder || !this._hiddenPanels) {
return undefined;
}
return computePanels(
this.hass.panels,
getDefaultPanelUrlPath(this.hass),
this._panelOrder,
this._hiddenPanels,
this.hass.locale
);
}
private _computeSelectedPanel(
sidebarPanels: [PanelInfo[], PanelInfo[]] | undefined,
route: Route | undefined
): string {
if (!route) {
return this.hass.panelUrl;
}
const urlPaths = (sidebarPanels ?? [[], []])
.flat()
.map((panel) => panel.url_path);
return getSelectedPanelUrlPath(urlPaths, route.path);
${this._renderAllPanels(selectedPanel)}`;
}
protected shouldUpdate(changedProps: PropertyValues): boolean {
@@ -279,20 +254,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
) {
return true;
}
if (!this.hass) {
return false;
}
if (changedProps.has("route")) {
const sidebarPanels = this._computeSidebarPanels();
const oldRoute = changedProps.get("route") as Route | undefined;
if (
this._computeSelectedPanel(sidebarPanels, oldRoute) !==
this._computeSelectedPanel(sidebarPanels, this.route)
) {
return true;
}
}
if (!changedProps.has("hass")) {
if (!this.hass || !changedProps.has("hass")) {
return false;
}
const oldHass = changedProps.get("hass") as HomeAssistant;
@@ -393,9 +355,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
</div>`;
}
private _renderAllPanels() {
const sidebarPanels = this._computeSidebarPanels();
const selectedPanel = this._computeSelectedPanel(sidebarPanels, this.route);
private _renderAllPanels(selectedPanel: string) {
const renderList = (content, cls: string, scrollable: boolean) =>
html`<ha-list-nav
class=${classMap({
@@ -405,7 +365,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
>${content}</ha-list-nav
>`;
if (!sidebarPanels) {
if (!this._panelOrder || !this._hiddenPanels) {
return html`<div class="panels-list">
<div class="wrapper">
${renderList(
@@ -430,7 +390,15 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
</div>`;
}
const [beforeSpacer, afterSpacer] = sidebarPanels;
const defaultPanel = getDefaultPanelUrlPath(this.hass);
const [beforeSpacer, afterSpacer] = computePanels(
this.hass.panels,
defaultPanel,
this._panelOrder,
this._hiddenPanels,
this.hass.locale
);
// prettier-ignore
return html`<div class="panels-list">
+33
View File
@@ -56,6 +56,12 @@ export interface SecurityFrontendSystemData {
favorite_entities?: string[];
}
export interface MaintenanceFrontendSystemData {
hidden?: string[];
}
export type HomeSummaryPanelSystemDataKey = "maintenance";
export interface EnergyFrontendSystemData {
// Stable "<view>.<card-type>" keys of energy dashboard cards the user has
// hidden. An absent key or array means nothing is hidden (all cards visible),
@@ -75,6 +81,7 @@ declare global {
home: HomeFrontendSystemData;
energy: EnergyFrontendSystemData;
security: SecurityFrontendSystemData;
maintenance: MaintenanceFrontendSystemData;
}
}
@@ -151,6 +158,32 @@ export const saveFrontendSystemData = async <
value,
});
const pendingSystemDataSaves = new Map<ValidSystemDataKey, Promise<void>>();
export const queueFrontendSystemDataSave = <
SystemDataKey extends ValidSystemDataKey,
>(
conn: Connection,
key: SystemDataKey,
value: FrontendSystemData[SystemDataKey]
): Promise<void> => {
const save = (pendingSystemDataSaves.get(key) ?? Promise.resolve())
.catch(() => undefined)
.then(() => saveFrontendSystemData(conn, key, value));
pendingSystemDataSaves.set(key, save);
return save;
};
export const fetchFrontendSystemDataAfterSaves = async <
SystemDataKey extends ValidSystemDataKey,
>(
conn: Connection,
key: SystemDataKey
): Promise<FrontendSystemData[SystemDataKey] | null> => {
await pendingSystemDataSaves.get(key)?.catch(() => undefined);
return fetchFrontendSystemData(conn, key);
};
export const subscribeFrontendSystemData = <
SystemDataKey extends ValidSystemDataKey,
>(
+11
View File
@@ -4,6 +4,16 @@ import type {
LovelaceLayoutOptions,
} from "../../../panels/lovelace/types";
/**
* Set by a strategy on the cards it generates in edit mode, for the controls
* the panel showing them applies: `hideable` adds a show/hide toggle that
* fires `item-visibility-changed` with `id`.
*/
export interface LovelaceItemMetadata {
id: string;
hideable?: boolean;
}
export interface LovelaceCardConfig {
index?: number;
view_index?: number;
@@ -15,4 +25,5 @@ export interface LovelaceCardConfig {
[key: string]: any;
visibility?: VisibilityCondition[];
disabled?: boolean;
metadata?: LovelaceItemMetadata;
}
-15
View File
@@ -196,21 +196,6 @@ export const getPanelIconPath = (panel: PanelInfo): string | undefined => {
export const FIXED_PANELS = [PROFILE_PANEL, "config", NOT_FOUND_PANEL];
// A panel's url_path can span several segments (e.g. "config/logs"), so the
// most specific url_path matching the path wins over its first segment.
export const getSelectedPanelUrlPath = (
urlPaths: string[],
path: string
): string =>
urlPaths.reduce(
(selected, urlPath) =>
urlPath.length > selected.length &&
(path === `/${urlPath}` || path.startsWith(`/${urlPath}/`))
? urlPath
: selected,
path.split("/")[1] ?? ""
);
export interface PanelMutableParams {
title?: string | null;
icon?: string | null;
@@ -28,10 +28,7 @@ import { fetchCloudStatus } from "../../data/cloud";
import { apiContext, configContext } from "../../data/context";
import { haStyleDialog, haStyleDialogFixedTop } from "../../resources/styles";
import { DialogMixin } from "../dialog-mixin";
import type {
CameraStreamInfo,
CameraStreamInfoDialogParams,
} from "./show-dialog-camera-stream-info";
import type { CameraStreamInfoDialogParams } from "./show-dialog-camera-stream-info";
// Ordered from the fastest to the most compatible
const STREAM_TYPES: { type: CameraStreamType; icon: string }[] = [
@@ -56,23 +53,6 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
@state() private _cloudIceServers = false;
@state() private _info?: CameraStreamInfo;
private _unsubscribe?: () => void;
public connectedCallback() {
super.connectedCallback();
this._unsubscribe = this.params?.subscribe((info) => {
this._info = info;
});
}
public disconnectedCallback() {
this._unsubscribe?.();
this._unsubscribe = undefined;
super.disconnectedCallback();
}
protected firstUpdated() {
this._fetchCloudIceServers();
}
@@ -94,10 +74,10 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
}
protected render() {
if (!this._info) {
if (!this.params) {
return nothing;
}
const { status, supportedTypes } = this._info;
const { status, supportedTypes } = this.params;
// Without a video stream, still images are all the camera has
const stillImagesOnly = supportedTypes?.length === 0;
// MJPEG is only the fallback, only worth explaining while it shows
@@ -181,7 +161,7 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
type: CameraStreamType;
icon: string;
}) {
const { status } = this._info!;
const { status } = this.params!;
const current = !status.connecting && status.type === type;
const upgrading = status.upgrading === type;
return html`
@@ -1,17 +1,12 @@
import { fireEvent } from "../../common/dom/fire_event";
import type { CameraStreamStatus, StreamType } from "../../data/camera-streams";
export interface CameraStreamInfo {
export interface CameraStreamInfoDialogParams {
status: CameraStreamStatus;
/** The stream types the camera supports, undefined while unknown */
supportedTypes?: StreamType[];
}
export interface CameraStreamInfoDialogParams {
/** Calls back with the current info right away and on every change */
subscribe: (callback: (info: CameraStreamInfo) => void) => () => void;
}
export const showCameraStreamInfoDialog = (
element: HTMLElement,
params: CameraStreamInfoDialogParams
-6
View File
@@ -2,10 +2,4 @@ import "@webcomponents/scoped-custom-element-registry/scoped-custom-element-regi
import "../resources/scoped-registry-ready";
import "../layouts/home-assistant";
// Custom cards and plugins can reach the helpers on any page, not only once a
// dashboard has loaded.
Object.assign(window, {
loadCardHelpers: () => import("../panels/lovelace/custom-card-helpers"),
});
import("../resources/append-ha-style");
@@ -514,16 +514,8 @@ class AddIntegrationDialog extends LitElement {
return [...integrations]
.filter((item) => !brand || item.domain === brand)
.sort(byName)
.flatMap((item) =>
this._brandRows(item)
.filter((row) => !row.is_header)
// The brand on the second line, so its entries read as a group
.map((row) =>
brand || !this._isBrand(item)
? row
: { ...row, description: item.name }
)
);
.flatMap((item) => this._brandRows(item))
.filter((row) => !brand || !row.is_header);
}
// A brand shows its integrations here, not itself, like the website
if (category) {
@@ -1215,11 +1207,17 @@ class AddIntegrationDialog extends LitElement {
})}
>
${
this._stickyBrand
? html`<ha-section-title class="sticky">
${this._stickyBrand}
</ha-section-title>`
: nothing
!this._stickyBrand
? nothing
: this._filter
? html`<ha-section-title class="sticky">
${this._stickyBrand}
</ha-section-title>`
: html`<ha-integration-list-title
class="sticky raised"
>
${this._stickyBrand}
</ha-integration-list-title>`
}
<ha-list-virtualized
.rows=${this._filter ? rows : this._withEndSpace(rows)}
@@ -1773,7 +1771,7 @@ class AddIntegrationDialog extends LitElement {
);
}
// The virtualizer positions rows, so CSS sticky can't hold the section title
// The virtualizer positions rows, so CSS sticky can't hold the brand
@eventOptions({ passive: true })
private _visibilityChanged(ev: HASSDomEvent<HaListVisibilityChangedDetail>) {
const rows = this._getRows();
@@ -1796,7 +1794,11 @@ class AddIntegrationDialog extends LitElement {
return html`<div style="height: var(--ha-space-2)"></div>`;
}
if (integration.is_header) {
return html`<ha-section-title>${integration.name}</ha-section-title>`;
return this._filter
? html`<ha-section-title>${integration.name}</ha-section-title>`
: html`<ha-integration-list-title>
${integration.name}
</ha-integration-list-title>`;
}
return html`
<ha-integration-list-item
@@ -26,7 +26,6 @@ import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import memoizeOne from "memoize-one";
import { navigate } from "../../../common/navigate";
import { formatListWithAnds } from "../../../common/string/format-list";
import { copyToClipboard } from "../../../common/util/copy-clipboard";
import "../../../components/ha-dropdown";
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
@@ -96,9 +95,6 @@ export class HaConfigEntryRow extends LitElement {
@property({ attribute: false }) public data!: ConfigEntryData;
/** The loaded integrations that lose this integration with this entry. */
@property({ attribute: false }) public dependents?: IntegrationManifest[];
@state() private _expanded = true;
@state() private _devicesExpanded = true;
@@ -816,33 +812,14 @@ export class HaConfigEntryRow extends LitElement {
const applicationCredentialsId =
await this._applicationCredentialForRemove(entryId);
const text = this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_text"
);
const confirmed = await showConfirmationDialog(this, {
title: this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_title",
{ title: this.data.entry.title }
),
text: this.dependents?.length
? html`${text}<br /><br />${this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_dependents",
{
count: this.dependents.length,
integrations: formatListWithAnds(
this.hass.locale,
this.dependents.map((manifest) =>
domainToName(this.hass.localize, manifest.domain, manifest)
)
),
name: domainToName(
this.hass.localize,
this.data.entry.domain,
this.manifest
),
}
)}`
: text,
text: this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_text"
),
confirmText: this.hass!.localize("ui.common.delete"),
dismissText: this.hass!.localize("ui.common.cancel"),
destructive: true,
@@ -21,7 +21,7 @@ import memoizeOne from "memoize-one";
import { ensureArray } from "../../../common/array/ensure-array";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import { QueryParamsController } from "../../../common/controllers/query-params-controller";
import { consume } from "../../../common/decorators/consume";
import { ContextSubscriptionController } from "../../../common/decorators/consume";
import type { HASSDomTargetEvent } from "../../../common/dom/fire_event";
import { computeDeviceNameDisplay } from "../../../common/entity/compute_device_name";
import {
@@ -176,9 +176,9 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
@state() private _manifest?: IntegrationManifest;
/** The manifests of all loaded integrations, to find the dependents. */
@consume({ context: manifestsContext, subscribe: true })
@state()
private _loadedManifests?: DomainManifestLookup;
@state() private _loadedManifests?: DomainManifestLookup;
private _manifestsConsumer?: ContextSubscriptionController<DomainManifestLookup>;
@state() private _extraConfigEntries?: ConfigEntry[];
@@ -432,23 +432,17 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
this.domain
);
const dependents = this._getDependents(
this.domain,
this._loadedManifests,
this.hass.localize,
this.hass.locale.language
);
// Without the dependents, a dependency looks like a YAML integration.
const dependencyOnly =
normalEntries.length === 0 &&
dependents.length > 0 &&
!this._manifest?.config_flow;
// Deleting the last entry in use leaves the dependents without it.
const entriesInUse = configEntries.filter(
(entry) => entry.source !== "ignore" && !entry.disabled_by
);
const lastEntryId =
entriesInUse.length === 1 ? entriesInUse[0].entry_id : undefined;
const dependents =
this._manifest && !this._manifest.config_flow
? this._getDependents(
this.domain,
this._loadedManifests,
this.hass.localize,
this.hass.locale.language
)
: [];
const showDependents = normalEntries.length === 0 && dependents.length > 0;
// Hold back the YAML texts and "Add entry" until the manifest and the
// dependents are known. Entries do not wait, so a failed request cannot
// hide them.
@@ -467,7 +461,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
const showAddEntry =
this._manifest?.integration_type !== "hardware" &&
!dependencyOnly &&
!showDependents &&
!dependentsLoading &&
!setUpInPanel &&
(!this._manifest?.single_config_entry ||
@@ -659,7 +653,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
}
${
normalEntries.length === 0 &&
!dependencyOnly &&
!showDependents &&
!dependentsLoading &&
!setUpInPanel &&
this._manifest &&
@@ -1016,11 +1010,6 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
.diagnosticHandler=${this._diagnosticHandler}
.entities=${this._entities}
.data=${data}
.dependents=${
data.entry.entry_id === lastEntryId
? dependents
: undefined
}
data-entry-id=${data.entry.entry_id}
></ha-config-entry-row>`
)}
@@ -1029,7 +1018,19 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
: nothing
}
${
dependencyOnly ||
showDependents
? html`<div class="section">
<h3 class="section-header">
${this.hass.localize(
"ui.panel.config.integrations.integration_page.used_by"
)}
</h3>
${this._renderDependents(dependents)}
</div>`
: nothing
}
${
showDependents ||
dependentsLoading ||
(setUpInPanel && normalEntries.length === 0)
? nothing
@@ -1076,11 +1077,6 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
.diagnosticHandler=${this._diagnosticHandler}
.entities=${this._entities}
.data=${data}
.dependents=${
data.entry.entry_id === lastEntryId
? dependents
: undefined
}
data-entry-id=${data.entry.entry_id}
></ha-config-entry-row>`
)}
@@ -1088,23 +1084,26 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
}
</div>`
}
${
dependents.length
? html`<div class="section">
<h3 class="section-header">
${this.hass.localize(
"ui.panel.config.integrations.integration_page.used_by"
)}
</h3>
${this._renderDependents(dependents)}
</div>`
: nothing
}
</div>
</hass-subpage>
`;
}
// Only an integration without a config flow needs the loaded manifests, so
// other integration pages do not make the context fetch them.
private _watchLoadedManifests(): void {
if (this._manifestsConsumer) {
return;
}
this._manifestsConsumer = new ContextSubscriptionController(
this,
manifestsContext,
(manifests) => {
this._loadedManifests = manifests;
}
);
}
private _getDependents = memoizeOne(
(
domain: string,
@@ -1200,6 +1199,9 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
return;
}
this._manifest = await fetchIntegrationManifest(this.hass, this.domain);
if (!this._manifest.config_flow) {
this._watchLoadedManifests();
}
if (
this._manifest.integration_type &&
!["device", "hub", "service"].includes(this._manifest.integration_type)
@@ -0,0 +1,269 @@
import { mdiPencil } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { property, state } from "lit/decorators";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { deepEqual } from "../../common/util/deep-equal";
import "../../components/ha-button";
import "../../components/ha-icon-button";
import "../../components/ha-top-app-bar-fixed";
import {
fetchFrontendSystemDataAfterSaves,
queueFrontendSystemDataSave,
type HomeSummaryPanelSystemDataKey,
} from "../../data/frontend";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { showToast } from "../../util/toast";
import type { Lovelace } from "../lovelace/types";
import "../lovelace/views/hui-view";
import "../lovelace/views/hui-view-background";
import "../lovelace/views/hui-view-container";
export abstract class HaHomeSummaryPanelBase<
K extends HomeSummaryPanelSystemDataKey,
> extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow = false;
@state() private _lovelace?: Lovelace;
@state() private _config?: FrontendSystemData[K];
@state() private _editMode = false;
@state() private _searchParams = new URLSearchParams(window.location.search);
protected abstract readonly _systemDataKey: K;
private _childPanelReady?: ChildPanelReady;
private _loadConfigPromise?: Promise<void>;
private _loadConfigRevision = 0;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (!this.hasUpdated) {
this._setup();
return;
}
if (!changedProps.has("hass")) {
return;
}
const oldHass = changedProps.get("hass") as this["hass"];
if (
oldHass &&
this.hass.config.state === "RUNNING" &&
oldHass.config.state !== "RUNNING"
) {
this._setup();
}
}
private async _setup() {
this._loadConfigPromise = this._loadConfig();
await Promise.all([
this.hass.loadFragmentTranslation("lovelace"),
this._loadConfigPromise,
]);
this._setLovelace();
}
private async _loadConfig() {
const revision = ++this._loadConfigRevision;
this._config = undefined;
try {
const data = await fetchFrontendSystemDataAfterSaves(
this.hass.connection,
this._systemDataKey
);
if (revision !== this._loadConfigRevision) {
return;
}
this._config = data || ({} as FrontendSystemData[K]);
} catch (err) {
if (revision !== this._loadConfigRevision) {
return;
}
this._editMode = false;
const key: HomeSummaryPanelSystemDataKey = this._systemDataKey;
// eslint-disable-next-line no-console
console.error(`Failed to load ${key} configuration:`, err);
showToast(this, {
message: this.hass.localize(`ui.panel.${key}.editor.load_failed`),
duration: 0,
dismissable: true,
});
}
}
protected render() {
const key: HomeSummaryPanelSystemDataKey = this._systemDataKey;
return html`
<ha-top-app-bar-fixed
.narrow=${this.narrow}
.backButton=${this._searchParams.has("historyBack")}
>
<div slot="title">${this.hass.localize(`panel.${key}`)}</div>
${
!this.hass.user?.is_admin
? nothing
: this._editMode
? html`<ha-button
slot="actionItems"
appearance="filled"
size="s"
@click=${this._exitEditMode}
>
${this.hass.localize("ui.panel.lovelace.menu.exit_edit_mode")}
</ha-button>`
: this._config
? html`<ha-icon-button
slot="actionItems"
.path=${mdiPencil}
.label=${this.hass.localize(`ui.panel.${key}.editor.title`)}
@click=${this._enterEditMode}
></ha-icon-button>`
: nothing
}
${
this._lovelace
? html`
<hui-view-container .hass=${this.hass}>
<hui-view-background .hass=${this.hass}>
</hui-view-background>
<hui-view
.hass=${this.hass}
.narrow=${this.narrow}
.lovelace=${this._lovelace}
.index=${0}
@item-visibility-changed=${this._visibilityChanged}
></hui-view>
</hui-view-container>
`
: nothing
}
</ha-top-app-bar-fixed>
`;
}
private async _setLovelace() {
if (this._loadConfigPromise) {
await this._loadConfigPromise;
}
const view: LovelaceStrategyViewConfig = {
strategy: {
type: this._systemDataKey,
hidden: this._editMode ? undefined : this._config?.hidden,
},
};
const config =
this._lovelace && deepEqual(view, this._lovelace.config.views[0])
? this._lovelace.config
: { views: [view] };
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = {
config,
rawConfig: config,
editMode: this._editMode,
hiddenIds: this._config?.hidden,
strategyEditSupport: true,
urlPath: this._systemDataKey,
mode: "generated",
locale: this.hass.locale,
enableFullEditMode: () => undefined,
saveConfig: async () => undefined,
deleteConfig: async () => undefined,
setEditMode: this._setEditMode,
showToast: () => undefined,
};
}
private _setEditMode = (editMode: boolean) => {
this._editMode = editMode;
if (!editMode && !this._config) {
this._loadConfigPromise = this._loadConfig();
}
this._setLovelace();
};
private _enterEditMode = () => {
this._setEditMode(true);
};
private _exitEditMode = () => {
this._setEditMode(false);
};
private _visibilityChanged = (
ev: HASSDomEvent<HASSDomEvents["item-visibility-changed"]>
) => {
if (!this._config) {
return;
}
const { id, hidden } = ev.detail;
const hiddenIds = (this._config.hidden ?? []).filter(
(hiddenId) => hiddenId !== id
);
if (hidden) {
hiddenIds.push(id);
}
this._saveConfig({
...this._config,
hidden: hiddenIds.length ? hiddenIds : undefined,
});
this._setLovelace();
};
private _saveConfig(config: FrontendSystemData[K]): Promise<void> {
this._config = config;
const key: HomeSummaryPanelSystemDataKey = this._systemDataKey;
return queueFrontendSystemDataSave(
this.hass.connection,
this._systemDataKey,
config
).catch(async (err) => {
// eslint-disable-next-line no-console
console.error(`Failed to save ${key} configuration:`, err);
showToast(this, {
message: this.hass.localize(`ui.panel.${key}.editor.save_failed`),
duration: 0,
dismissable: true,
});
if (config !== this._config) {
return;
}
await this._loadConfig();
await this._setLovelace();
});
}
static get styles(): CSSResultGroup {
return [
haStyle,
css`
:host {
user-select: none;
}
hui-view-container {
position: relative;
display: flex;
min-height: 100%;
box-sizing: border-box;
}
hui-view {
flex: 1 1 100%;
max-width: 100%;
}
`,
];
}
}
+37 -1
View File
@@ -17,6 +17,7 @@ import {
saveFrontendSystemData,
subscribeFrontendSystemData,
type HomeFrontendSystemData,
type MaintenanceFrontendSystemData,
type SecurityFrontendSystemData,
} from "../../data/frontend";
import type { LovelaceDashboardStrategyConfig } from "../../data/lovelace/config/types";
@@ -54,6 +55,8 @@ class PanelHome extends SubscribeMixin(LitElement) {
@state() private _securityConfig: SecurityFrontendSystemData = {};
@state() private _maintenanceConfig: MaintenanceFrontendSystemData = {};
@state() private _extraActionItems?: ExtraActionItem[];
@query(".banner") private _banner?: HTMLElement;
@@ -62,6 +65,8 @@ class PanelHome extends SubscribeMixin(LitElement) {
private _securityConfigRevision = 0;
private _maintenanceConfigRevision = 0;
public hassSubscribe() {
return [
subscribeFrontendSystemData(
@@ -79,6 +84,21 @@ class PanelHome extends SubscribeMixin(LitElement) {
}
}
),
subscribeFrontendSystemData(
this.hass.connection,
"maintenance",
({ value }) => {
this._maintenanceConfigRevision++;
const config = value || {};
if (deepEqual(config, this._maintenanceConfig)) {
return;
}
this._maintenanceConfig = config;
if (this.hasUpdated) {
this._setLovelace();
}
}
),
];
}
@@ -179,11 +199,13 @@ class PanelHome extends SubscribeMixin(LitElement) {
private async _loadConfig() {
const securityConfigRevision = this._securityConfigRevision;
const [translationsResult, homeResult, securityResult] =
const maintenanceConfigRevision = this._maintenanceConfigRevision;
const [translationsResult, homeResult, securityResult, maintenanceResult] =
await Promise.allSettled([
this.hass.loadFragmentTranslation("lovelace"),
fetchFrontendSystemData(this.hass.connection, "home"),
fetchFrontendSystemData(this.hass.connection, "security"),
fetchFrontendSystemData(this.hass.connection, "maintenance"),
]);
if (translationsResult.status === "rejected") {
@@ -214,6 +236,19 @@ class PanelHome extends SubscribeMixin(LitElement) {
} else if (securityConfigRevision === this._securityConfigRevision) {
this._securityConfig = securityResult.value || {};
}
if (maintenanceResult.status === "rejected") {
// eslint-disable-next-line no-console
console.error(
"Failed to load maintenance configuration:",
maintenanceResult.reason
);
if (maintenanceConfigRevision === this._maintenanceConfigRevision) {
this._maintenanceConfig = {};
}
} else if (maintenanceConfigRevision === this._maintenanceConfigRevision) {
this._maintenanceConfig = maintenanceResult.value || {};
}
}
private _debounceRegenerateStrategy = debounce(
@@ -400,6 +435,7 @@ class PanelHome extends SubscribeMixin(LitElement) {
strategy: {
type: "home",
alert_entities: this._securityConfig.alert_entities,
maintenance_hidden_entities: this._maintenanceConfig.hidden,
favorite_entities: this._config?.favorite_entities,
home_panel: true,
hide_welcome_message: this._config?.hide_welcome_message,
@@ -29,6 +29,8 @@ const BADGE_SORTABLE_OPTIONS: HaSortableOptions = {
export class HuiViewBadges extends LitElement {
@property({ attribute: false }) public lovelace!: Lovelace;
@property({ attribute: false }) public editMode = false;
@property({ attribute: false }) public badges: HuiBadge[] = [];
@property({ attribute: false }) public path!: ConfigPath;
@@ -46,7 +48,7 @@ export class HuiViewBadges extends LitElement {
private _checkAllHidden() {
const allHidden =
!this.lovelace.editMode && this.badges.every((section) => section.hidden);
!this.editMode && this.badges.every((section) => section.hidden);
this.toggleAttribute("hidden", allHidden);
}
@@ -71,7 +73,7 @@ export class HuiViewBadges extends LitElement {
}
willUpdate(changedProperties: PropertyValues<this>): void {
if (changedProperties.has("badges") || changedProperties.has("lovelace")) {
if (changedProperties.has("badges") || changedProperties.has("editMode")) {
this._checkAllHidden();
}
}
@@ -125,7 +127,7 @@ export class HuiViewBadges extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = this.lovelace.editMode;
const editMode = this.editMode;
const badges = this.badges;
@@ -326,13 +326,10 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
: localize("ui.card.home-summary.no_media_playing");
}
case "maintenance": {
const maintenanceEntities = findMaintenanceEntities({
states,
entities,
devices,
areas,
floors,
});
const maintenanceEntities = findMaintenanceEntities(
{ states, entities, devices, areas, floors },
this._config.hidden_entities
);
const lowBatteryEntities = filterLowBatteryEntities(
states,
+1
View File
@@ -768,6 +768,7 @@ export interface HeadingCardConfig extends LovelaceCardConfig {
export interface HomeSummaryCard extends LovelaceCardConfig {
summary: HomeSummary;
alert_entities?: SecurityAlertEntityConfig[];
hidden_entities?: string[];
vertical?: boolean;
tap_action?: ActionConfig;
hold_action?: ActionConfig;
@@ -0,0 +1,127 @@
import { mdiEye, mdiEyeOff } from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
import type { CSSResultGroup } from "lit";
import { LitElement, css, html } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-svg-icon";
import { formattersContext } from "../../../data/context";
import type { HomeAssistantFormatters } from "../../../types";
@customElement("hui-card-visibility-edit-mode")
export class HuiCardVisibilityEditMode extends LitElement {
@property({ attribute: false }) public itemId!: string;
@property({ type: Boolean, reflect: true, attribute: "item-hidden" })
public itemHidden = false;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@state()
@consumeEntityState({ entityIdPath: ["itemId"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: HomeAssistantFormatters;
protected render() {
const name = this._stateObj
? this._formatters.formatEntityName(this._stateObj)
: this.itemId;
return html`
<div class="card-wrapper" inert><slot></slot></div>
<button
class="control"
aria-label=${this._localize(
`ui.components.items-display-editor.${this.itemHidden ? "show" : "hide"}`,
{ label: name }
)}
@click=${this._toggle}
>
<ha-svg-icon
.path=${this.itemHidden ? mdiEyeOff : mdiEye}
></ha-svg-icon>
</button>
`;
}
private _toggle(): void {
fireEvent(this, "item-visibility-changed", {
id: this.itemId,
hidden: !this.itemHidden,
});
}
static styles: CSSResultGroup = css`
:host {
display: block;
position: relative;
height: 100%;
border-radius: var(--ha-card-border-radius, var(--ha-border-radius-lg));
}
.card-wrapper {
height: 100%;
}
:host([item-hidden]) .card-wrapper {
opacity: 0.8;
}
:host([item-hidden])::after {
content: "";
position: absolute;
inset: 0;
border: 2px dotted var(--secondary-text-color);
border-radius: inherit;
pointer-events: none;
}
.control {
position: absolute;
inset: 0;
z-index: 1;
display: flex;
align-items: flex-end;
justify-content: flex-end;
margin: 0;
padding: var(--ha-space-2);
border: none;
background: none;
border-radius: inherit;
cursor: pointer;
color: var(--primary-text-color);
}
.control:focus-visible {
outline: 2px solid var(--primary-color);
}
.control ha-svg-icon {
display: flex;
padding: var(--ha-space-1);
border-radius: var(--ha-border-radius-circle);
background: var(--secondary-background-color);
box-shadow: var(--ha-box-shadow-s);
--mdc-icon-size: 20px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"hui-card-visibility-edit-mode": HuiCardVisibilityEditMode;
}
interface GlobalEventHandlersEventMap {
"item-visibility-changed": HASSDomEvent<
HASSDomEvents["item-visibility-changed"]
>;
}
interface HASSDomEvents {
"item-visibility-changed": { id: string; hidden: boolean };
}
}
@@ -9,8 +9,6 @@ export {
showPromptDialog,
} from "../../dialogs/generic/show-dialog-box";
export { importMoreInfoControl } from "../../dialogs/more-info/state_more_info_control";
export { subscribeVisibility } from "../../common/condition/subscribe-visibility";
export { createBadgeElement } from "./create-element/create-badge-element";
export { createCardElement } from "./create-element/create-card-element";
export { createHeaderFooterElement } from "./create-element/create-header-footer-element";
@@ -18,8 +18,9 @@ import type { HomeAssistant } from "../../../types";
import type { HuiCard } from "../cards/hui-card";
import { computeCardGridSize } from "../common/compute-card-grid-size";
import "../components/hui-card-edit-mode";
import "../components/hui-card-visibility-edit-mode";
import { moveAtPath } from "../editor/lovelace-path";
import type { Lovelace } from "../types";
import { strategyEditMode, type Lovelace } from "../types";
const CARD_SORTABLE_OPTIONS: HaSortableOptions = {
delay: 100,
@@ -79,6 +80,8 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
const cardsConfig = this._config?.cards ?? [];
const editMode = Boolean(this.lovelace?.editMode && !this.isStrategy);
const generatedEditMode =
strategyEditMode(this.lovelace) && this.isStrategy;
const sortableOptions = this.importOnly
? IMPORT_MODE_CARD_SORTABLE_OPTIONS
@@ -104,7 +107,7 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
${repeat(
cardsConfig,
(cardConfig) => this._getKey(cardConfig),
(_cardConfig, idx) => {
(cardConfig, idx) => {
const card = this.cards![idx];
card.layout = "grid";
const gridOptions = card.getGridOptions();
@@ -126,6 +129,7 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
"full-width": columns === "full",
hidden: !editMode && card.hidden,
})}"
?inert=${generatedEditMode && !cardConfig.metadata?.hideable}
.sortableData=${cardPath}
>
${
@@ -141,7 +145,20 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
${card}
</hui-card-edit-mode>
`
: card
: generatedEditMode && cardConfig.metadata?.hideable
? html`
<hui-card-visibility-edit-mode
.itemId=${cardConfig.metadata.id}
.itemHidden=${Boolean(
this.lovelace?.hiddenIds?.includes(
cardConfig.metadata.id
)
)}
>
${card}
</hui-card-visibility-edit-mode>
`
: card
}
</div>
`;
@@ -25,6 +25,7 @@ import type {
LovelaceSectionStrategy,
LovelaceStrategy,
LovelaceStrategyDependency,
LovelaceStrategyGenerateOptions,
LovelaceViewStrategy,
} from "./types";
@@ -157,7 +158,8 @@ const generateStrategy = async <T extends LovelaceStrategyConfigType>(
configType: T,
renderError: (err: string | Error) => StrategyConfig<T>,
strategyConfig: LovelaceStrategyConfig,
hass: HomeAssistant
hass: HomeAssistant,
options?: LovelaceStrategyGenerateOptions
): Promise<StrategyConfig<T>> => {
const strategyType = strategyConfig.type;
if (!strategyType) {
@@ -187,7 +189,7 @@ const generateStrategy = async <T extends LovelaceStrategyConfigType>(
const config = cleanLegacyStrategyConfig(strategyConfig);
return await strategy.generate(config, hass);
return await strategy.generate(config, hass, options);
} catch (err: any) {
if (err.message !== "timeout") {
// eslint-disable-next-line
@@ -229,7 +231,8 @@ export const generateLovelaceDashboardStrategy = async (
export const generateLovelaceViewStrategy = async (
config: LovelaceStrategyViewConfig,
hass: HomeAssistant
hass: HomeAssistant,
options?: LovelaceStrategyGenerateOptions
): Promise<LovelaceViewConfig> => {
const { strategy, ...base } = config;
const generated = await generateStrategy(
@@ -243,7 +246,8 @@ export const generateLovelaceViewStrategy = async (
],
}),
strategy,
hass
hass,
options
);
return {
...base,
@@ -21,6 +21,7 @@ import type { HomeOverviewViewStrategyConfig } from "./home-overview-view-strate
export interface HomeDashboardStrategyConfig {
type: "home";
alert_entities?: SecurityAlertEntityConfig[];
maintenance_hidden_entities?: string[];
favorite_entities?: string[];
home_panel?: boolean;
hide_welcome_message?: boolean;
@@ -106,6 +107,7 @@ export class HomeDashboardStrategy extends ReactiveElement {
strategy: {
type: "home-overview",
alert_entities: config.alert_entities,
maintenance_hidden_entities: config.maintenance_hidden_entities,
favorite_entities: config.favorite_entities,
home_panel: config.home_panel,
hide_welcome_message: config.hide_welcome_message,
@@ -60,6 +60,7 @@ import { OTHER_DEVICES_FILTERS } from "./helpers/other-devices-filters";
export interface HomeOverviewViewStrategyConfig {
type: "home-overview";
alert_entities?: SecurityAlertEntityConfig[];
maintenance_hidden_entities?: string[];
favorite_entities?: string[];
home_panel?: boolean;
hide_welcome_message?: boolean;
@@ -370,7 +371,9 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
const hasSecurity =
hass.panels.security && findSecurityEntities(hass).length > 0;
const hasMaintenance =
hass.panels.maintenance && findMaintenanceEntities(hass).length > 0;
hass.panels.maintenance &&
findMaintenanceEntities(hass, config.maintenance_hidden_entities).length >
0;
const alertEntities = config.alert_entities ?? [];
const alertSeverityEntities = filterSecurityAlertEntities(
@@ -468,6 +471,9 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
? ({
type: "home-summary",
summary: "maintenance",
hidden_entities: config.maintenance_hidden_entities?.length
? config.maintenance_hidden_entities
: undefined,
tap_action: {
action: "navigate",
navigation_path: config.home_panel
+10 -1
View File
@@ -9,8 +9,17 @@ import type { LovelaceGenericElementEditor } from "../types";
export type LovelaceStrategyDependency =
"entities" | "devices" | "areas" | "floors" | "labels" | "panels";
export interface LovelaceStrategyGenerateOptions {
/** The result is shown in edit mode, so it may carry `metadata`. */
editMode?: boolean;
}
export interface LovelaceStrategy<T = any> {
generate(config: LovelaceStrategyConfig, hass: HomeAssistant): Promise<T>;
generate(
config: LovelaceStrategyConfig,
hass: HomeAssistant,
options?: LovelaceStrategyGenerateOptions
): Promise<T>;
shouldRegenerate?(
config: LovelaceStrategyConfig,
oldHass: HomeAssistant,
+13
View File
@@ -48,8 +48,21 @@ export interface Lovelace {
* window's history and scroll position.
*/
embedded?: boolean;
/**
* Ids of the generated items that are hidden. In edit mode they are still
* shown, with their visibility toggle off.
*/
hiddenIds?: string[];
/**
* The host applies the controls that generated items declare in their
* `metadata`, so strategies add it in edit mode.
*/
strategyEditSupport?: boolean;
}
export const strategyEditMode = (lovelace?: Lovelace): boolean =>
Boolean(lovelace?.editMode && lovelace.strategyEditSupport);
export interface LovelaceBadge extends HTMLElement {
hass?: HomeAssistant;
preview?: boolean;
@@ -88,6 +88,7 @@ export class MasonryView extends LitElement implements LovelaceViewElement {
<hui-view-badges
.badges=${this.badges}
.lovelace=${this.lovelace}
.editMode=${Boolean(this.lovelace?.editMode)}
.path=${[...this.path!, "badges"]}
show-add-label
></hui-view-badges>
@@ -191,7 +191,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
if (!this.lovelace) return nothing;
const sections = this.sections;
const editMode = this.lovelace.editMode;
const editMode = this.lovelace.editMode && !this.isStrategy;
const hasSidebar =
this._config?.sidebar && (this._sidebarVisible || editMode);
const singleColumn = this._maxColumns <= 1;
@@ -239,6 +239,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
.hass=${this.hass}
.badges=${this.badges}
.lovelace=${this.lovelace}
.editMode=${editMode}
.path=${this.path!}
.config=${this._config?.header}
></hui-view-header>
@@ -370,6 +371,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
.hass=${this.hass}
.badges=${this.badges}
.lovelace=${this.lovelace}
.editMode=${editMode}
.path=${this.path!}
.config=${this._config.sidebar}
@sidebar-visibility-changed=${
@@ -383,6 +385,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
<hui-view-footer
.hass=${this.hass}
.lovelace=${this.lovelace}
.editMode=${editMode}
.path=${this.path!}
.config=${this._config?.footer}
></hui-view-footer>
@@ -94,6 +94,7 @@ export class SideBarView extends LitElement implements LovelaceViewElement {
<hui-view-badges
.badges=${this.badges}
.lovelace=${this.lovelace}
.editMode=${Boolean(this.lovelace?.editMode)}
.path=${[...this.path!, "badges"]}
show-add-label
></hui-view-badges>
+12 -7
View File
@@ -26,6 +26,8 @@ export class HuiViewFooter extends LitElement {
@property({ attribute: false }) public lovelace!: Lovelace;
@property({ attribute: false }) public editMode = false;
@property({ attribute: false }) public card?: HuiCard;
@property({ attribute: false }) public config?: LovelaceViewFooterConfig;
@@ -52,12 +54,16 @@ export class HuiViewFooter extends LitElement {
if (changedProperties.has("hass")) {
this.card.hass = this.hass;
}
if (changedProperties.has("lovelace")) {
this.card.preview = this.lovelace.editMode;
if (changedProperties.has("editMode")) {
this.card.preview = this.editMode;
}
}
if (changedProperties.has("lovelace") || changedProperties.has("card")) {
if (
!this.hasUpdated ||
changedProperties.has("editMode") ||
changedProperties.has("card")
) {
this._checkHidden();
}
}
@@ -69,8 +75,7 @@ export class HuiViewFooter extends LitElement {
private _checkHidden() {
const hidden =
!this.lovelace?.editMode &&
(!this.card || this.card.hasAttribute("hidden"));
!this.editMode && (!this.card || this.card.hasAttribute("hidden"));
this.toggleAttribute("hidden", hidden);
this.toggleAttribute("sticky", Boolean(this.card));
}
@@ -78,7 +83,7 @@ export class HuiViewFooter extends LitElement {
private _createCardElement(cardConfig: LovelaceCardConfig) {
const element = document.createElement("hui-card");
element.hass = this.hass;
element.preview = this.lovelace.editMode;
element.preview = this.editMode;
element.layout = "grid";
element.config = cardConfig;
element.addEventListener("card-updated", (ev: Event) => {
@@ -150,7 +155,7 @@ export class HuiViewFooter extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = Boolean(this.lovelace?.editMode);
const editMode = this.editMode;
const card = this.card;
if (!editMode && !card) {
+11 -8
View File
@@ -33,6 +33,8 @@ export class HuiViewHeader extends LitElement {
@property({ attribute: false }) public lovelace!: Lovelace;
@property({ attribute: false }) public editMode = false;
@property({ attribute: false }) public card?: HuiCard;
@property({ attribute: false }) public badges: HuiBadge[] = [];
@@ -44,7 +46,7 @@ export class HuiViewHeader extends LitElement {
private _checkHidden() {
const allHidden =
!this.card &&
!this.lovelace.editMode &&
!this.editMode &&
this.badges.every((badges) => badges.hidden);
this.toggleAttribute("hidden", allHidden);
}
@@ -79,15 +81,15 @@ export class HuiViewHeader extends LitElement {
willUpdate(changedProperties: PropertyValues<this>): void {
if (
changedProperties.has("badges") ||
changedProperties.has("lovelace") ||
changedProperties.has("editMode") ||
changedProperties.has("card")
) {
this._checkHidden();
}
if (changedProperties.has("config") || changedProperties.has("lovelace")) {
if (changedProperties.has("config") || changedProperties.has("editMode")) {
this._dragScrollController.enabled =
!this.lovelace.editMode && this.config?.badges_wrap === "scroll";
!this.editMode && this.config?.badges_wrap === "scroll";
}
if (changedProperties.has("config")) {
@@ -104,8 +106,8 @@ export class HuiViewHeader extends LitElement {
if (changedProperties.has("hass")) {
this.card.hass = this.hass;
}
if (changedProperties.has("lovelace")) {
this.card.preview = this.lovelace.editMode;
if (changedProperties.has("editMode")) {
this.card.preview = this.editMode;
}
}
}
@@ -113,7 +115,7 @@ export class HuiViewHeader extends LitElement {
private _createCardElement(cardConfig: LovelaceCardConfig) {
const element = document.createElement("hui-card");
element.hass = this.hass;
element.preview = this.lovelace.editMode;
element.preview = this.editMode;
element.config = cardConfig;
element.load();
return element;
@@ -163,7 +165,7 @@ export class HuiViewHeader extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = Boolean(this.lovelace?.editMode);
const editMode = this.editMode;
const card = this.card;
@@ -254,6 +256,7 @@ export class HuiViewHeader extends LitElement {
<hui-view-badges
.badges=${this.badges}
.lovelace=${this.lovelace!}
.editMode=${this.editMode}
.path=${[...this.path, "badges"]}
.showAddLabel=${this.badges.length === 0}
></hui-view-badges>
@@ -25,6 +25,8 @@ export class HuiViewSidebar extends ConditionalListenerMixin<LovelaceViewSidebar
@property({ attribute: false }) public lovelace!: Lovelace;
@property({ attribute: false }) public editMode = false;
@property({ attribute: false }) public config?: LovelaceViewSidebarConfig;
@property({ attribute: false }) public path!: ConfigPath;
@@ -74,7 +76,7 @@ export class HuiViewSidebar extends ConditionalListenerMixin<LovelaceViewSidebar
<hui-section
.config=${section}
.hass=${this.hass}
.preview=${this.lovelace.editMode}
.preview=${this.editMode}
.path=${sectionPath}
></hui-section>
`;
+31 -9
View File
@@ -65,7 +65,7 @@ import {
checkStrategyShouldRegenerate,
generateLovelaceViewStrategy,
} from "../strategies/get-strategy";
import type { Lovelace } from "../types";
import { strategyEditMode, type Lovelace } from "../types";
import { PANEL_VIEW_LAYOUT, SIDEBAR_VIEW_LAYOUT } from "./const";
import { getViewType } from "./get-view-type";
@@ -119,6 +119,8 @@ export class HUIView extends ReactiveElement {
private _layoutElementType?: string;
private _initializeConfigRevision = 0;
private _layoutElement?: LovelaceViewElement;
private _config?: LovelaceViewConfig;
@@ -368,6 +370,14 @@ export class HUIView extends ReactiveElement {
};
}
private get _isStrategy(): boolean {
return isStrategyView(this.lovelace.config.views[this.index]);
}
private get _preview(): boolean {
return this.lovelace.editMode && !this._isStrategy;
}
private _getCardConfig(path: ConfigPath): LovelaceCardConfig | undefined {
if (isStrategyView(this.lovelace.config.views[this.index])) {
return undefined;
@@ -378,7 +388,7 @@ export class HUIView extends ReactiveElement {
private _createCardElement(cardConfig: LovelaceCardConfig) {
const element = document.createElement("hui-card");
element.hass = this.hass;
element.preview = this.lovelace.editMode;
element.preview = this._preview;
element.config = cardConfig;
element.addEventListener("card-updated", (ev: Event) => {
ev.stopPropagation();
@@ -391,7 +401,7 @@ export class HUIView extends ReactiveElement {
public createBadgeElement(badgeConfig: LovelaceBadgeConfig) {
const element = document.createElement("hui-badge");
element.hass = this.hass;
element.preview = this.lovelace.editMode;
element.preview = this._preview;
element.config = badgeConfig;
element.addEventListener("badge-updated", (ev: Event) => {
ev.stopPropagation();
@@ -406,8 +416,9 @@ export class HUIView extends ReactiveElement {
const element = document.createElement("hui-section");
element.hass = this.hass;
element.lovelace = this.lovelace;
element.insideStrategy = this._isStrategy;
element.config = sectionConfig;
element.preview = this.lovelace.editMode;
element.preview = this._preview;
element.addEventListener(
"ll-rebuild",
(ev: Event) => {
@@ -449,7 +460,9 @@ export class HUIView extends ReactiveElement {
(changedProperties.has("lovelace") &&
(!oldLovelace ||
this.lovelace.config.views[this.index] !==
oldLovelace.config.views[this.index]))
oldLovelace.config.views[this.index] ||
(this._isStrategy &&
strategyEditMode(this.lovelace) !== strategyEditMode(oldLovelace))))
) {
this._initializeConfig();
return;
@@ -465,6 +478,7 @@ export class HUIView extends ReactiveElement {
if (
this.hass.config.state === "RUNNING" &&
(oldHass.config.state !== "RUNNING" ||
oldHass.localize !== this.hass.localize ||
checkStrategyShouldRegenerate(
"view",
viewConfig.strategy,
@@ -516,16 +530,16 @@ export class HUIView extends ReactiveElement {
try {
element.hass = this.hass;
element.lovelace = this.lovelace;
element.preview = this.lovelace.editMode;
element.preview = this._preview;
} catch (e: any) {
this._rebuildSection(element, createErrorSectionConfig(e.message));
}
});
this._cards.forEach((element) => {
element.preview = this.lovelace.editMode;
element.preview = this._preview;
});
this._badges.forEach((element) => {
element.preview = this.lovelace.editMode;
element.preview = this._preview;
});
}
if (changedProperties.has("_cards")) {
@@ -543,7 +557,8 @@ export class HUIView extends ReactiveElement {
if (isStrategyView(config)) {
const strategyConfig = await generateLovelaceViewStrategy(
config,
this.hass!
this.hass!,
{ editMode: strategyEditMode(this.lovelace) }
);
const generatedConfig = normalizeViewConfig(strategyConfig);
return {
@@ -596,11 +611,18 @@ export class HUIView extends ReactiveElement {
}
private async _initializeConfig() {
const revision = ++this._initializeConfigRevision;
const rawConfig = this.lovelace.config.views[this.index];
const isStrategy = isStrategyView(rawConfig);
const viewConfig = await this._generateConfig(rawConfig);
if (this._layoutElement) {
await customElements.whenDefined(this._layoutElement.localName);
}
if (revision !== this._initializeConfigRevision) {
return;
}
this._setConfig(viewConfig, isStrategy);
await customElements.whenDefined(this._layoutElement!.localName);
if (this._layoutElement instanceof ReactiveElement) {
+4 -165
View File
@@ -1,170 +1,9 @@
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import "../../components/ha-top-app-bar-fixed";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
import type { Lovelace } from "../lovelace/types";
import "../lovelace/views/hui-view";
import "../lovelace/views/hui-view-background";
import "../lovelace/views/hui-view-container";
const MAINTENANCE_LOVELACE_VIEW_CONFIG: LovelaceStrategyViewConfig = {
strategy: {
type: "maintenance",
},
};
import { customElement } from "lit/decorators";
import { HaHomeSummaryPanelBase } from "../home/ha-home-summary-panel-base";
@customElement("ha-panel-maintenance")
class PanelMaintenance extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow = false;
@state() private _viewIndex = 0;
@state() private _lovelace?: Lovelace;
@state() private _searchParams = new URLSearchParams(window.location.search);
private _childPanelReady?: ChildPanelReady;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Initial setup
if (!this.hasUpdated) {
this._setup();
return;
}
if (!changedProps.has("hass")) {
return;
}
const oldHass = changedProps.get("hass") as this["hass"];
if (oldHass && oldHass.localize !== this.hass.localize) {
this._setLovelace();
return;
}
if (oldHass && this.hass) {
// If the entity registry changed, ask the user if they want to refresh the config
if (
oldHass.entities !== this.hass.entities ||
oldHass.devices !== this.hass.devices ||
oldHass.areas !== this.hass.areas ||
oldHass.floors !== this.hass.floors ||
oldHass.panels !== this.hass.panels
) {
if (this.hass.config.state === "RUNNING") {
this._debounceRegistriesChanged();
return;
}
}
// If ha started, refresh the config
if (
this.hass.config.state === "RUNNING" &&
oldHass.config.state !== "RUNNING"
) {
this._setLovelace();
}
}
}
private async _setup() {
await this.hass.loadFragmentTranslation("lovelace");
this._setLovelace();
}
private _debounceRegistriesChanged = debounce(
() => this._registriesChanged(),
200
);
private _registriesChanged = async () => {
this._setLovelace();
};
protected render() {
return html`
<ha-top-app-bar-fixed
.narrow=${this.narrow}
.backButton=${this._searchParams.has("historyBack")}
>
<div slot="title">${this.hass.localize("panel.maintenance")}</div>
${
this._lovelace
? html`
<hui-view-container .hass=${this.hass}>
<hui-view-background .hass=${this.hass}>
</hui-view-background>
<hui-view
.hass=${this.hass}
.narrow=${this.narrow}
.lovelace=${this._lovelace}
.index=${this._viewIndex}
></hui-view>
</hui-view-container>
`
: nothing
}
</ha-top-app-bar-fixed>
`;
}
private async _setLovelace() {
const viewConfig = await generateLovelaceViewStrategy(
MAINTENANCE_LOVELACE_VIEW_CONFIG,
this.hass
);
const config = { views: [viewConfig] };
const rawConfig = { views: [MAINTENANCE_LOVELACE_VIEW_CONFIG] };
if (deepEqual(config, this._lovelace?.config)) {
return;
}
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = {
config: config,
rawConfig: rawConfig,
editMode: false,
urlPath: "maintenance",
mode: "generated",
locale: this.hass.locale,
enableFullEditMode: () => undefined,
saveConfig: async () => undefined,
deleteConfig: async () => undefined,
setEditMode: () => undefined,
showToast: () => undefined,
};
}
static get styles(): CSSResultGroup {
return [
haStyle,
css`
:host {
user-select: none;
}
hui-view-container {
position: relative;
display: flex;
box-sizing: border-box;
}
hui-view {
flex: 1 1 100%;
max-width: 100%;
}
`,
];
}
class PanelMaintenance extends HaHomeSummaryPanelBase<"maintenance"> {
protected readonly _systemDataKey = "maintenance";
}
declare global {
@@ -14,6 +14,10 @@ import type { LovelaceSectionRawConfig } from "../../../data/lovelace/config/sec
import type { LovelaceViewConfig } from "../../../data/lovelace/config/view";
import type { HomeAssistant } from "../../../types";
import type { TileCardConfig } from "../../lovelace/cards/types";
import type {
LovelaceStrategyDependency,
LovelaceStrategyGenerateOptions,
} from "../../lovelace/strategies/types";
import { BINARY_STATE_ON } from "../../../common/const";
import { computeDomain } from "../../../common/entity/compute_domain";
import { getDeviceEntityDisplayLookup } from "../../../data/device/device_registry";
@@ -21,6 +25,7 @@ import { findBatteryChargingEntity } from "../../../data/entity/entity_registry"
export interface MaintenanceViewStrategyConfig {
type: "maintenance";
hidden?: string[];
}
export const maintenanceEntityFilters: EntityFilter[] = [
@@ -35,8 +40,10 @@ export const maintenanceEntityFilters: EntityFilter[] = [
];
export const findMaintenanceEntities = (
sources: EntityFilterSources
): string[] => findFilteredEntities(sources, maintenanceEntityFilters);
sources: EntityFilterSources,
hiddenEntities?: string[]
): string[] =>
findFilteredEntities(sources, maintenanceEntityFilters, hiddenEntities);
const LOW_BATTERY_THRESHOLD = 20;
@@ -100,26 +107,29 @@ export const filterUnavailableBatteryEntities = (
const computeMaintenanceTileCard = (
states: HomeAssistant["states"],
entities: HomeAssistant["entities"],
entityId: string
entityId: string,
editMode: boolean
): TileCardConfig => {
const deviceId = entities[entityId]?.device_id;
if (!deviceId) {
return { type: "tile", entity: entityId, name: { type: "entity" } };
}
const isProblem = states[entityId]?.attributes?.device_class === "problem";
return {
const card: TileCardConfig = {
type: "tile",
entity: entityId,
name: isProblem
? [{ type: "device" }, { type: "entity" }]
: { type: "device" },
name: !entities[entityId]?.device_id
? { type: "entity" }
: isProblem
? [{ type: "device" }, { type: "entity" }]
: { type: "device" },
};
return editMode
? { ...card, metadata: { id: entityId, hideable: true } }
: card;
};
const processAreasForBattery = (
areaIds: string[],
hass: HomeAssistant,
entities: string[]
entities: string[],
editMode: boolean
): LovelaceCardConfig[] => {
const cards: LovelaceCardConfig[] = [];
@@ -142,7 +152,12 @@ const processAreasForBattery = (
for (const entityId of areaBatteryEntities) {
areaCards.push(
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
computeMaintenanceTileCard(
hass.states,
hass.entities,
entityId,
editMode
)
);
}
@@ -167,7 +182,8 @@ const processAreasForBattery = (
const processUnassignedEntities = (
hass: HomeAssistant,
entities: string[]
entities: string[],
editMode: boolean
): LovelaceCardConfig[] => {
const unassignedFilter = generateEntityFilter(
hass.states,
@@ -184,7 +200,7 @@ const processUnassignedEntities = (
for (const entityId of unassignedEntities) {
cards.push(
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
computeMaintenanceTileCard(hass.states, hass.entities, entityId, editMode)
);
}
@@ -193,17 +209,27 @@ const processUnassignedEntities = (
@customElement("maintenance-view-strategy")
export class MaintenanceViewStrategy extends ReactiveElement {
static registryDependencies: readonly LovelaceStrategyDependency[] = [
"entities",
"devices",
"areas",
"floors",
"panels",
];
static async generate(
_config: MaintenanceViewStrategyConfig,
hass: HomeAssistant
config: MaintenanceViewStrategyConfig,
hass: HomeAssistant,
options?: LovelaceStrategyGenerateOptions
): Promise<LovelaceViewConfig> {
const editMode = Boolean(options?.editMode);
const areas = Object.values(hass.areas);
const floors = Object.values(hass.floors);
const hierarchy = getAreasFloorHierarchy(floors, areas);
const sections: LovelaceSectionRawConfig[] = [];
const entities = findMaintenanceEntities(hass);
const entities = findMaintenanceEntities(hass, config.hidden);
const floorCount =
hierarchy.floors.length + (hierarchy.areas.length ? 1 : 0);
@@ -229,7 +255,12 @@ export class MaintenanceViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForBattery(areaIds, hass, entities);
const areaCards = processAreasForBattery(
areaIds,
hass,
entities,
editMode
);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -255,7 +286,12 @@ export class MaintenanceViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForBattery(hierarchy.areas, hass, entities);
const areaCards = processAreasForBattery(
hierarchy.areas,
hass,
entities,
editMode
);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -264,7 +300,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
}
// Process unassigned entities
const unassignedCards = processUnassignedEntities(hass, entities);
const unassignedCards = processUnassignedEntities(hass, entities, editMode);
if (unassignedCards.length > 0) {
const section: LovelaceSectionRawConfig = {
+7 -1
View File
@@ -3098,6 +3098,13 @@
"save_failed": "Failed to save security and safety page configuration"
}
},
"maintenance": {
"editor": {
"title": "Edit visible entities",
"load_failed": "Failed to load maintenance page configuration",
"save_failed": "Failed to save maintenance page configuration"
}
},
"my": {
"not_supported": "This redirect is not supported by your Home Assistant instance. Check the {link} for the supported redirects and the version they where introduced.",
"component_not_loaded": "This redirect is not supported by your Home Assistant instance. You need the integration {integration} to use this redirect.",
@@ -8266,7 +8273,6 @@
"delete": "Delete",
"delete_confirm_title": "Delete {title}?",
"delete_confirm_text": "Its devices and entities will be permanently deleted.",
"delete_confirm_dependents": "{integrations} {count, plural,\n one {depends}\n other {depend}\n} on {name} and may stop working.",
"enable_debug_logging": "Enable debug logging",
"reconfigure": "Reconfigure",
"reload": "Reload",
@@ -1,109 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { subscribeVisibility } from "../../../src/common/condition/subscribe-visibility";
import type { VisibilityCondition } from "../../../src/panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../../src/types";
interface CapturedSubscription {
push: (message: { result?: boolean }) => void;
unsub: ReturnType<typeof vi.fn>;
condition: unknown;
}
let subs: CapturedSubscription[];
const tick = () =>
new Promise<void>((resolve) => {
setTimeout(resolve, 10);
});
const createHass = (userId = "user1"): HomeAssistant =>
({
connection: {
subscribeMessage: vi.fn(
(
onChange: CapturedSubscription["push"],
msg: { condition: unknown }
) => {
const unsub = vi.fn();
subs.push({ push: onChange, unsub, condition: msg.condition });
return Promise.resolve(unsub);
}
),
},
states: {},
user: { id: userId },
locale: { time_zone: "local" },
config: { time_zone: "America/New_York" },
}) as unknown as HomeAssistant;
describe("subscribeVisibility", () => {
beforeEach(() => {
subs = [];
});
it("checks client conditions again with each hass passed to update", async () => {
const onChange = vi.fn();
const conditions: VisibilityCondition[] = [
{ condition: "user", users: ["user1"] },
];
const subscription = subscribeVisibility(
createHass("user1"),
conditions,
onChange
);
await tick();
expect(onChange).toHaveBeenLastCalledWith("visible", undefined);
subscription.update(createHass("user2"));
expect(onChange).toHaveBeenLastCalledWith("hidden", undefined);
});
it("closes core subscriptions and stops reporting after unsubscribe", async () => {
const onChange = vi.fn();
const conditions: VisibilityCondition[] = [
{ condition: "state", entity: "light.kitchen", state: "on" },
];
const subscription = subscribeVisibility(
createHass(),
conditions,
onChange
);
await tick();
expect(subs).toHaveLength(1);
subs[0].push({ result: true });
expect(onChange).toHaveBeenLastCalledWith("visible", undefined);
onChange.mockClear();
subscription.unsubscribe();
await tick();
expect(subs[0].unsub).toHaveBeenCalled();
expect(onChange).not.toHaveBeenCalled();
});
it("sends the context entity to core for conditions without one", async () => {
const conditions: VisibilityCondition[] = [
{ condition: "state", state: "on" },
];
subscribeVisibility(createHass(), conditions, vi.fn(), {
entity_id: "light.kitchen",
});
await tick();
expect(subs).toHaveLength(1);
expect(subs[0].condition).toEqual({
condition: "state",
entity_id: "light.kitchen",
state: "on",
});
});
});
+15 -7
View File
@@ -710,15 +710,23 @@ describe("generateEntityFilter", () => {
});
describe("findFilteredEntities", () => {
it("should match entities against any of the filters", () => {
const entities = findFilteredEntities(mockHass, [
{ domain: "light" },
{ domain: "switch" },
]);
it("should match any filter and drop excluded entities", () => {
const entities = findFilteredEntities(
mockHass,
[{ domain: "light" }, { domain: "switch" }],
["light.bedroom"]
);
expect(entities).toContain("light.living_room");
expect(entities).toContain("switch.kitchen");
expect(entities).not.toContain("light.bedroom");
expect(entities).not.toContain("sensor.temperature");
});
it("should return every match when nothing is excluded", () => {
const entities = findFilteredEntities(mockHass, [{ domain: "light" }]);
expect(entities).toContain("light.living_room");
expect(entities).toContain("light.bedroom");
expect(entities).toContain("switch.kitchen");
expect(entities).not.toContain("sensor.temperature");
});
});
+1 -44
View File
@@ -1,8 +1,5 @@
import { describe, expect, it } from "vitest";
import {
getConfigSubpageTitle,
getSelectedPanelUrlPath,
} from "../../src/data/panel";
import { getConfigSubpageTitle } from "../../src/data/panel";
import type { PageNavigation } from "../../src/layouts/hass-tabs-subpage";
import type { HomeAssistant } from "../../src/types";
@@ -86,43 +83,3 @@ describe("getConfigSubpageTitle", () => {
).toBeUndefined();
});
});
describe("getSelectedPanelUrlPath", () => {
const urlPaths = ["lovelace", "history", "config/logs", "config/logs/raw"];
it("falls back to the first path segment", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/automation")).toBe(
"config"
);
expect(getSelectedPanelUrlPath(urlPaths, "/profile/general")).toBe(
"profile"
);
});
it("selects a panel whose url_path has several segments", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs")).toBe(
"config/logs"
);
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs/details")).toBe(
"config/logs"
);
});
it("prefers the most specific url_path", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs/raw")).toBe(
"config/logs/raw"
);
});
it("only matches whole segments", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/logsfoo")).toBe("config");
});
it("keeps matching single segment panels on their subpaths", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/lovelace/0")).toBe("lovelace");
});
it("returns an empty url_path for the root path", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/")).toBe("");
});
});
@@ -280,4 +280,60 @@ describe("MaintenanceViewStrategy.generate", () => {
},
]);
});
const createBatteryHass = () =>
createMockHass({
"sensor.car_target_charge": createMockEntityState(
"sensor.car_target_charge",
"80",
{ device_class: "battery" }
),
"sensor.remote_battery": createMockEntityState(
"sensor.remote_battery",
"80",
{ device_class: "battery" }
),
});
it("leaves hidden entities out of the view", async () => {
const view = await MaintenanceViewStrategy.generate(
{ type: "maintenance", hidden: ["sensor.car_target_charge"] },
createBatteryHass()
);
const section = view.sections?.[0] as LovelaceSectionConfig;
expect(section.cards?.slice(1)).toEqual([
{
type: "tile",
entity: "sensor.remote_battery",
name: { type: "entity" },
},
]);
});
it("adds visibility metadata to the tiles only in edit mode", async () => {
const hass = createBatteryHass();
const tiles = async (editMode: boolean) =>
(
(
await MaintenanceViewStrategy.generate(
{ type: "maintenance" },
hass,
{
editMode,
}
)
).sections?.[0] as LovelaceSectionConfig
).cards?.slice(1);
expect((await tiles(false))?.map((card) => card.metadata)).toEqual([
undefined,
undefined,
]);
expect((await tiles(true))?.map((card) => card.metadata)).toEqual([
{ id: "sensor.car_target_charge", hideable: true },
{ id: "sensor.remote_battery", hideable: true },
]);
});
});