mirror of
https://github.com/home-assistant/frontend.git
synced 2026-11-30 16:49:04 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9083641ae7 | ||
|
|
5fc4ad4e0c | ||
|
|
ba33d2897b | ||
|
|
9484d51694 | ||
|
|
55739f2666 | ||
|
|
483b8d1c76 |
No files matched your search
@@ -0,0 +1,74 @@
|
||||
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();
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -163,21 +163,9 @@ 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[],
|
||||
excludedEntityIds?: string[]
|
||||
filters: EntityFilter[]
|
||||
): string[] => {
|
||||
const filterFuncs = filters.map((filter) =>
|
||||
generateEntityFilter(
|
||||
@@ -189,8 +177,5 @@ export const findFilteredEntities = (
|
||||
filter
|
||||
)
|
||||
);
|
||||
return excludeEntities(
|
||||
findEntities(Object.keys(sources.states), filterFuncs),
|
||||
excludedEntityIds
|
||||
);
|
||||
return findEntities(Object.keys(sources.states), filterFuncs);
|
||||
};
|
||||
@@ -22,7 +22,10 @@ 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 } from "../../dialogs/camera/show-dialog-camera-stream-info";
|
||||
import {
|
||||
showCameraStreamInfoDialog,
|
||||
type CameraStreamInfo,
|
||||
} from "../../dialogs/camera/show-dialog-camera-stream-info";
|
||||
import "../ha-camera-stream";
|
||||
import type { HaCameraStream } from "../ha-camera-stream";
|
||||
import "../ha-icon-button";
|
||||
@@ -108,6 +111,8 @@ export class HaCameraPlayer extends LitElement {
|
||||
|
||||
@state() private _capabilities?: CameraCapabilities;
|
||||
|
||||
private _streamInfoCallbacks = new Set<(info: CameraStreamInfo) => void>();
|
||||
|
||||
@state() private _video?: HTMLVideoElement;
|
||||
|
||||
@state() private _muted = false;
|
||||
@@ -213,6 +218,7 @@ export class HaCameraPlayer extends LitElement {
|
||||
);
|
||||
clearTimeout(this._controlsTimeout);
|
||||
clearTimeout(this._wheelHintTimeout);
|
||||
this._streamInfoCallbacks.clear();
|
||||
this._unbindVideo(this._video);
|
||||
this._video = undefined;
|
||||
this._pointers.clear();
|
||||
@@ -252,6 +258,10 @@ 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() {
|
||||
@@ -602,10 +612,26 @@ export class HaCameraPlayer extends LitElement {
|
||||
this._posterSize = ev.detail.size;
|
||||
}
|
||||
|
||||
private _showStreamInfo() {
|
||||
showCameraStreamInfoDialog(this, {
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,15 @@ 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();
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
getPanelIcon,
|
||||
getPanelIconPath,
|
||||
getPanelTitle,
|
||||
getSelectedPanelUrlPath,
|
||||
} from "../data/panel";
|
||||
import type { PersistentNotification } from "../data/persistent_notification";
|
||||
import { subscribeNotifications } from "../data/persistent_notification";
|
||||
@@ -231,12 +232,36 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const selectedPanel = this.hass.panelUrl;
|
||||
|
||||
// prettier-ignore
|
||||
return html`
|
||||
${this._renderHeader()}
|
||||
${this._renderAllPanels(selectedPanel)}`;
|
||||
${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);
|
||||
}
|
||||
|
||||
protected shouldUpdate(changedProps: PropertyValues): boolean {
|
||||
@@ -254,7 +279,20 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (!this.hass || !changedProps.has("hass")) {
|
||||
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")) {
|
||||
return false;
|
||||
}
|
||||
const oldHass = changedProps.get("hass") as HomeAssistant;
|
||||
@@ -355,7 +393,9 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private _renderAllPanels(selectedPanel: string) {
|
||||
private _renderAllPanels() {
|
||||
const sidebarPanels = this._computeSidebarPanels();
|
||||
const selectedPanel = this._computeSelectedPanel(sidebarPanels, this.route);
|
||||
const renderList = (content, cls: string, scrollable: boolean) =>
|
||||
html`<ha-list-nav
|
||||
class=${classMap({
|
||||
@@ -365,7 +405,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
>${content}</ha-list-nav
|
||||
>`;
|
||||
|
||||
if (!this._panelOrder || !this._hiddenPanels) {
|
||||
if (!sidebarPanels) {
|
||||
return html`<div class="panels-list">
|
||||
<div class="wrapper">
|
||||
${renderList(
|
||||
@@ -390,15 +430,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
const defaultPanel = getDefaultPanelUrlPath(this.hass);
|
||||
|
||||
const [beforeSpacer, afterSpacer] = computePanels(
|
||||
this.hass.panels,
|
||||
defaultPanel,
|
||||
this._panelOrder,
|
||||
this._hiddenPanels,
|
||||
this.hass.locale
|
||||
);
|
||||
const [beforeSpacer, afterSpacer] = sidebarPanels;
|
||||
|
||||
// prettier-ignore
|
||||
return html`<div class="panels-list">
|
||||
|
||||
@@ -56,12 +56,6 @@ 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),
|
||||
@@ -81,7 +75,6 @@ declare global {
|
||||
home: HomeFrontendSystemData;
|
||||
energy: EnergyFrontendSystemData;
|
||||
security: SecurityFrontendSystemData;
|
||||
maintenance: MaintenanceFrontendSystemData;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,32 +151,6 @@ 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,
|
||||
>(
|
||||
|
||||
@@ -4,16 +4,6 @@ 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;
|
||||
@@ -25,5 +15,4 @@ export interface LovelaceCardConfig {
|
||||
[key: string]: any;
|
||||
visibility?: VisibilityCondition[];
|
||||
disabled?: boolean;
|
||||
metadata?: LovelaceItemMetadata;
|
||||
}
|
||||
@@ -196,6 +196,21 @@ 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,7 +28,10 @@ import { fetchCloudStatus } from "../../data/cloud";
|
||||
import { apiContext, configContext } from "../../data/context";
|
||||
import { haStyleDialog, haStyleDialogFixedTop } from "../../resources/styles";
|
||||
import { DialogMixin } from "../dialog-mixin";
|
||||
import type { CameraStreamInfoDialogParams } from "./show-dialog-camera-stream-info";
|
||||
import type {
|
||||
CameraStreamInfo,
|
||||
CameraStreamInfoDialogParams,
|
||||
} from "./show-dialog-camera-stream-info";
|
||||
|
||||
// Ordered from the fastest to the most compatible
|
||||
const STREAM_TYPES: { type: CameraStreamType; icon: string }[] = [
|
||||
@@ -53,6 +56,23 @@ 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();
|
||||
}
|
||||
@@ -74,10 +94,10 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.params) {
|
||||
if (!this._info) {
|
||||
return nothing;
|
||||
}
|
||||
const { status, supportedTypes } = this.params;
|
||||
const { status, supportedTypes } = this._info;
|
||||
// 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
|
||||
@@ -161,7 +181,7 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
|
||||
type: CameraStreamType;
|
||||
icon: string;
|
||||
}) {
|
||||
const { status } = this.params!;
|
||||
const { status } = this._info!;
|
||||
const current = !status.connecting && status.type === type;
|
||||
const upgrading = status.upgrading === type;
|
||||
return html`
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type { CameraStreamStatus, StreamType } from "../../data/camera-streams";
|
||||
|
||||
export interface CameraStreamInfoDialogParams {
|
||||
export interface CameraStreamInfo {
|
||||
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
|
||||
|
||||
@@ -2,4 +2,10 @@ 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,8 +514,16 @@ class AddIntegrationDialog extends LitElement {
|
||||
return [...integrations]
|
||||
.filter((item) => !brand || item.domain === brand)
|
||||
.sort(byName)
|
||||
.flatMap((item) => this._brandRows(item))
|
||||
.filter((row) => !brand || !row.is_header);
|
||||
.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 }
|
||||
)
|
||||
);
|
||||
}
|
||||
// A brand shows its integrations here, not itself, like the website
|
||||
if (category) {
|
||||
@@ -1207,17 +1215,11 @@ class AddIntegrationDialog extends LitElement {
|
||||
})}
|
||||
>
|
||||
${
|
||||
!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>`
|
||||
this._stickyBrand
|
||||
? html`<ha-section-title class="sticky">
|
||||
${this._stickyBrand}
|
||||
</ha-section-title>`
|
||||
: nothing
|
||||
}
|
||||
<ha-list-virtualized
|
||||
.rows=${this._filter ? rows : this._withEndSpace(rows)}
|
||||
@@ -1771,7 +1773,7 @@ class AddIntegrationDialog extends LitElement {
|
||||
);
|
||||
}
|
||||
|
||||
// The virtualizer positions rows, so CSS sticky can't hold the brand
|
||||
// The virtualizer positions rows, so CSS sticky can't hold the section title
|
||||
@eventOptions({ passive: true })
|
||||
private _visibilityChanged(ev: HASSDomEvent<HaListVisibilityChangedDetail>) {
|
||||
const rows = this._getRows();
|
||||
@@ -1794,11 +1796,7 @@ class AddIntegrationDialog extends LitElement {
|
||||
return html`<div style="height: var(--ha-space-2)"></div>`;
|
||||
}
|
||||
if (integration.is_header) {
|
||||
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-section-title>${integration.name}</ha-section-title>`;
|
||||
}
|
||||
return html`
|
||||
<ha-integration-list-item
|
||||
|
||||
@@ -26,6 +26,7 @@ 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";
|
||||
@@ -95,6 +96,9 @@ 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;
|
||||
@@ -812,14 +816,33 @@ 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.hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.delete_confirm_text"
|
||||
),
|
||||
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,
|
||||
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 { ContextSubscriptionController } from "../../../common/decorators/consume";
|
||||
import { consume } 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. */
|
||||
@state() private _loadedManifests?: DomainManifestLookup;
|
||||
|
||||
private _manifestsConsumer?: ContextSubscriptionController<DomainManifestLookup>;
|
||||
@consume({ context: manifestsContext, subscribe: true })
|
||||
@state()
|
||||
private _loadedManifests?: DomainManifestLookup;
|
||||
|
||||
@state() private _extraConfigEntries?: ConfigEntry[];
|
||||
|
||||
@@ -432,17 +432,23 @@ 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 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;
|
||||
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;
|
||||
// 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.
|
||||
@@ -461,7 +467,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
|
||||
const showAddEntry =
|
||||
this._manifest?.integration_type !== "hardware" &&
|
||||
!showDependents &&
|
||||
!dependencyOnly &&
|
||||
!dependentsLoading &&
|
||||
!setUpInPanel &&
|
||||
(!this._manifest?.single_config_entry ||
|
||||
@@ -653,7 +659,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
}
|
||||
${
|
||||
normalEntries.length === 0 &&
|
||||
!showDependents &&
|
||||
!dependencyOnly &&
|
||||
!dependentsLoading &&
|
||||
!setUpInPanel &&
|
||||
this._manifest &&
|
||||
@@ -1010,6 +1016,11 @@ 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>`
|
||||
)}
|
||||
@@ -1018,19 +1029,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
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 ||
|
||||
dependencyOnly ||
|
||||
dependentsLoading ||
|
||||
(setUpInPanel && normalEntries.length === 0)
|
||||
? nothing
|
||||
@@ -1077,6 +1076,11 @@ 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>`
|
||||
)}
|
||||
@@ -1084,26 +1088,23 @@ 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,
|
||||
@@ -1199,9 +1200,6 @@ 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)
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
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%;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
saveFrontendSystemData,
|
||||
subscribeFrontendSystemData,
|
||||
type HomeFrontendSystemData,
|
||||
type MaintenanceFrontendSystemData,
|
||||
type SecurityFrontendSystemData,
|
||||
} from "../../data/frontend";
|
||||
import type { LovelaceDashboardStrategyConfig } from "../../data/lovelace/config/types";
|
||||
@@ -55,8 +54,6 @@ class PanelHome extends SubscribeMixin(LitElement) {
|
||||
|
||||
@state() private _securityConfig: SecurityFrontendSystemData = {};
|
||||
|
||||
@state() private _maintenanceConfig: MaintenanceFrontendSystemData = {};
|
||||
|
||||
@state() private _extraActionItems?: ExtraActionItem[];
|
||||
|
||||
@query(".banner") private _banner?: HTMLElement;
|
||||
@@ -65,8 +62,6 @@ class PanelHome extends SubscribeMixin(LitElement) {
|
||||
|
||||
private _securityConfigRevision = 0;
|
||||
|
||||
private _maintenanceConfigRevision = 0;
|
||||
|
||||
public hassSubscribe() {
|
||||
return [
|
||||
subscribeFrontendSystemData(
|
||||
@@ -84,21 +79,6 @@ 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();
|
||||
}
|
||||
}
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -199,13 +179,11 @@ class PanelHome extends SubscribeMixin(LitElement) {
|
||||
|
||||
private async _loadConfig() {
|
||||
const securityConfigRevision = this._securityConfigRevision;
|
||||
const maintenanceConfigRevision = this._maintenanceConfigRevision;
|
||||
const [translationsResult, homeResult, securityResult, maintenanceResult] =
|
||||
const [translationsResult, homeResult, securityResult] =
|
||||
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") {
|
||||
@@ -236,19 +214,6 @@ 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(
|
||||
@@ -435,7 +400,6 @@ 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,8 +29,6 @@ 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;
|
||||
@@ -48,7 +46,7 @@ export class HuiViewBadges extends LitElement {
|
||||
|
||||
private _checkAllHidden() {
|
||||
const allHidden =
|
||||
!this.editMode && this.badges.every((section) => section.hidden);
|
||||
!this.lovelace.editMode && this.badges.every((section) => section.hidden);
|
||||
this.toggleAttribute("hidden", allHidden);
|
||||
}
|
||||
|
||||
@@ -73,7 +71,7 @@ export class HuiViewBadges extends LitElement {
|
||||
}
|
||||
|
||||
willUpdate(changedProperties: PropertyValues<this>): void {
|
||||
if (changedProperties.has("badges") || changedProperties.has("editMode")) {
|
||||
if (changedProperties.has("badges") || changedProperties.has("lovelace")) {
|
||||
this._checkAllHidden();
|
||||
}
|
||||
}
|
||||
@@ -127,7 +125,7 @@ export class HuiViewBadges extends LitElement {
|
||||
render() {
|
||||
if (!this.lovelace) return nothing;
|
||||
|
||||
const editMode = this.editMode;
|
||||
const editMode = this.lovelace.editMode;
|
||||
|
||||
const badges = this.badges;
|
||||
|
||||
|
||||
@@ -326,10 +326,13 @@ 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 },
|
||||
this._config.hidden_entities
|
||||
);
|
||||
const maintenanceEntities = findMaintenanceEntities({
|
||||
states,
|
||||
entities,
|
||||
devices,
|
||||
areas,
|
||||
floors,
|
||||
});
|
||||
|
||||
const lowBatteryEntities = filterLowBatteryEntities(
|
||||
states,
|
||||
|
||||
@@ -768,7 +768,6 @@ 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;
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
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,6 +9,8 @@ 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,9 +18,8 @@ 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 { strategyEditMode, type Lovelace } from "../types";
|
||||
import type { Lovelace } from "../types";
|
||||
|
||||
const CARD_SORTABLE_OPTIONS: HaSortableOptions = {
|
||||
delay: 100,
|
||||
@@ -80,8 +79,6 @@ 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
|
||||
@@ -107,7 +104,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();
|
||||
@@ -129,7 +126,6 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
|
||||
"full-width": columns === "full",
|
||||
hidden: !editMode && card.hidden,
|
||||
})}"
|
||||
?inert=${generatedEditMode && !cardConfig.metadata?.hideable}
|
||||
.sortableData=${cardPath}
|
||||
>
|
||||
${
|
||||
@@ -145,20 +141,7 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
|
||||
${card}
|
||||
</hui-card-edit-mode>
|
||||
`
|
||||
: 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
|
||||
: card
|
||||
}
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -25,7 +25,6 @@ import type {
|
||||
LovelaceSectionStrategy,
|
||||
LovelaceStrategy,
|
||||
LovelaceStrategyDependency,
|
||||
LovelaceStrategyGenerateOptions,
|
||||
LovelaceViewStrategy,
|
||||
} from "./types";
|
||||
|
||||
@@ -158,8 +157,7 @@ const generateStrategy = async <T extends LovelaceStrategyConfigType>(
|
||||
configType: T,
|
||||
renderError: (err: string | Error) => StrategyConfig<T>,
|
||||
strategyConfig: LovelaceStrategyConfig,
|
||||
hass: HomeAssistant,
|
||||
options?: LovelaceStrategyGenerateOptions
|
||||
hass: HomeAssistant
|
||||
): Promise<StrategyConfig<T>> => {
|
||||
const strategyType = strategyConfig.type;
|
||||
if (!strategyType) {
|
||||
@@ -189,7 +187,7 @@ const generateStrategy = async <T extends LovelaceStrategyConfigType>(
|
||||
|
||||
const config = cleanLegacyStrategyConfig(strategyConfig);
|
||||
|
||||
return await strategy.generate(config, hass, options);
|
||||
return await strategy.generate(config, hass);
|
||||
} catch (err: any) {
|
||||
if (err.message !== "timeout") {
|
||||
// eslint-disable-next-line
|
||||
@@ -231,8 +229,7 @@ export const generateLovelaceDashboardStrategy = async (
|
||||
|
||||
export const generateLovelaceViewStrategy = async (
|
||||
config: LovelaceStrategyViewConfig,
|
||||
hass: HomeAssistant,
|
||||
options?: LovelaceStrategyGenerateOptions
|
||||
hass: HomeAssistant
|
||||
): Promise<LovelaceViewConfig> => {
|
||||
const { strategy, ...base } = config;
|
||||
const generated = await generateStrategy(
|
||||
@@ -246,8 +243,7 @@ export const generateLovelaceViewStrategy = async (
|
||||
],
|
||||
}),
|
||||
strategy,
|
||||
hass,
|
||||
options
|
||||
hass
|
||||
);
|
||||
return {
|
||||
...base,
|
||||
|
||||
@@ -21,7 +21,6 @@ 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;
|
||||
@@ -107,7 +106,6 @@ 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,7 +60,6 @@ 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;
|
||||
@@ -371,9 +370,7 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
|
||||
const hasSecurity =
|
||||
hass.panels.security && findSecurityEntities(hass).length > 0;
|
||||
const hasMaintenance =
|
||||
hass.panels.maintenance &&
|
||||
findMaintenanceEntities(hass, config.maintenance_hidden_entities).length >
|
||||
0;
|
||||
hass.panels.maintenance && findMaintenanceEntities(hass).length > 0;
|
||||
|
||||
const alertEntities = config.alert_entities ?? [];
|
||||
const alertSeverityEntities = filterSecurityAlertEntities(
|
||||
@@ -471,9 +468,6 @@ 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
|
||||
|
||||
@@ -9,17 +9,8 @@ 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,
|
||||
options?: LovelaceStrategyGenerateOptions
|
||||
): Promise<T>;
|
||||
generate(config: LovelaceStrategyConfig, hass: HomeAssistant): Promise<T>;
|
||||
shouldRegenerate?(
|
||||
config: LovelaceStrategyConfig,
|
||||
oldHass: HomeAssistant,
|
||||
|
||||
@@ -48,21 +48,8 @@ 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,7 +88,6 @@ 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 && !this.isStrategy;
|
||||
const editMode = this.lovelace.editMode;
|
||||
const hasSidebar =
|
||||
this._config?.sidebar && (this._sidebarVisible || editMode);
|
||||
const singleColumn = this._maxColumns <= 1;
|
||||
@@ -239,7 +239,6 @@ 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>
|
||||
@@ -371,7 +370,6 @@ 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=${
|
||||
@@ -385,7 +383,6 @@ 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,7 +94,6 @@ 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>
|
||||
|
||||
@@ -26,8 +26,6 @@ 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;
|
||||
@@ -54,16 +52,12 @@ export class HuiViewFooter extends LitElement {
|
||||
if (changedProperties.has("hass")) {
|
||||
this.card.hass = this.hass;
|
||||
}
|
||||
if (changedProperties.has("editMode")) {
|
||||
this.card.preview = this.editMode;
|
||||
if (changedProperties.has("lovelace")) {
|
||||
this.card.preview = this.lovelace.editMode;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!this.hasUpdated ||
|
||||
changedProperties.has("editMode") ||
|
||||
changedProperties.has("card")
|
||||
) {
|
||||
if (changedProperties.has("lovelace") || changedProperties.has("card")) {
|
||||
this._checkHidden();
|
||||
}
|
||||
}
|
||||
@@ -75,7 +69,8 @@ export class HuiViewFooter extends LitElement {
|
||||
|
||||
private _checkHidden() {
|
||||
const hidden =
|
||||
!this.editMode && (!this.card || this.card.hasAttribute("hidden"));
|
||||
!this.lovelace?.editMode &&
|
||||
(!this.card || this.card.hasAttribute("hidden"));
|
||||
this.toggleAttribute("hidden", hidden);
|
||||
this.toggleAttribute("sticky", Boolean(this.card));
|
||||
}
|
||||
@@ -83,7 +78,7 @@ export class HuiViewFooter extends LitElement {
|
||||
private _createCardElement(cardConfig: LovelaceCardConfig) {
|
||||
const element = document.createElement("hui-card");
|
||||
element.hass = this.hass;
|
||||
element.preview = this.editMode;
|
||||
element.preview = this.lovelace.editMode;
|
||||
element.layout = "grid";
|
||||
element.config = cardConfig;
|
||||
element.addEventListener("card-updated", (ev: Event) => {
|
||||
@@ -155,7 +150,7 @@ export class HuiViewFooter extends LitElement {
|
||||
render() {
|
||||
if (!this.lovelace) return nothing;
|
||||
|
||||
const editMode = this.editMode;
|
||||
const editMode = Boolean(this.lovelace?.editMode);
|
||||
const card = this.card;
|
||||
|
||||
if (!editMode && !card) {
|
||||
|
||||
@@ -33,8 +33,6 @@ 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[] = [];
|
||||
@@ -46,7 +44,7 @@ export class HuiViewHeader extends LitElement {
|
||||
private _checkHidden() {
|
||||
const allHidden =
|
||||
!this.card &&
|
||||
!this.editMode &&
|
||||
!this.lovelace.editMode &&
|
||||
this.badges.every((badges) => badges.hidden);
|
||||
this.toggleAttribute("hidden", allHidden);
|
||||
}
|
||||
@@ -81,15 +79,15 @@ export class HuiViewHeader extends LitElement {
|
||||
willUpdate(changedProperties: PropertyValues<this>): void {
|
||||
if (
|
||||
changedProperties.has("badges") ||
|
||||
changedProperties.has("editMode") ||
|
||||
changedProperties.has("lovelace") ||
|
||||
changedProperties.has("card")
|
||||
) {
|
||||
this._checkHidden();
|
||||
}
|
||||
|
||||
if (changedProperties.has("config") || changedProperties.has("editMode")) {
|
||||
if (changedProperties.has("config") || changedProperties.has("lovelace")) {
|
||||
this._dragScrollController.enabled =
|
||||
!this.editMode && this.config?.badges_wrap === "scroll";
|
||||
!this.lovelace.editMode && this.config?.badges_wrap === "scroll";
|
||||
}
|
||||
|
||||
if (changedProperties.has("config")) {
|
||||
@@ -106,8 +104,8 @@ export class HuiViewHeader extends LitElement {
|
||||
if (changedProperties.has("hass")) {
|
||||
this.card.hass = this.hass;
|
||||
}
|
||||
if (changedProperties.has("editMode")) {
|
||||
this.card.preview = this.editMode;
|
||||
if (changedProperties.has("lovelace")) {
|
||||
this.card.preview = this.lovelace.editMode;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,7 +113,7 @@ export class HuiViewHeader extends LitElement {
|
||||
private _createCardElement(cardConfig: LovelaceCardConfig) {
|
||||
const element = document.createElement("hui-card");
|
||||
element.hass = this.hass;
|
||||
element.preview = this.editMode;
|
||||
element.preview = this.lovelace.editMode;
|
||||
element.config = cardConfig;
|
||||
element.load();
|
||||
return element;
|
||||
@@ -165,7 +163,7 @@ export class HuiViewHeader extends LitElement {
|
||||
render() {
|
||||
if (!this.lovelace) return nothing;
|
||||
|
||||
const editMode = this.editMode;
|
||||
const editMode = Boolean(this.lovelace?.editMode);
|
||||
|
||||
const card = this.card;
|
||||
|
||||
@@ -256,7 +254,6 @@ 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,8 +25,6 @@ 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;
|
||||
@@ -76,7 +74,7 @@ export class HuiViewSidebar extends ConditionalListenerMixin<LovelaceViewSidebar
|
||||
<hui-section
|
||||
.config=${section}
|
||||
.hass=${this.hass}
|
||||
.preview=${this.editMode}
|
||||
.preview=${this.lovelace.editMode}
|
||||
.path=${sectionPath}
|
||||
></hui-section>
|
||||
`;
|
||||
|
||||
@@ -65,7 +65,7 @@ import {
|
||||
checkStrategyShouldRegenerate,
|
||||
generateLovelaceViewStrategy,
|
||||
} from "../strategies/get-strategy";
|
||||
import { strategyEditMode, type Lovelace } from "../types";
|
||||
import type { Lovelace } from "../types";
|
||||
import { PANEL_VIEW_LAYOUT, SIDEBAR_VIEW_LAYOUT } from "./const";
|
||||
import { getViewType } from "./get-view-type";
|
||||
|
||||
@@ -119,8 +119,6 @@ export class HUIView extends ReactiveElement {
|
||||
|
||||
private _layoutElementType?: string;
|
||||
|
||||
private _initializeConfigRevision = 0;
|
||||
|
||||
private _layoutElement?: LovelaceViewElement;
|
||||
|
||||
private _config?: LovelaceViewConfig;
|
||||
@@ -370,14 +368,6 @@ 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;
|
||||
@@ -388,7 +378,7 @@ export class HUIView extends ReactiveElement {
|
||||
private _createCardElement(cardConfig: LovelaceCardConfig) {
|
||||
const element = document.createElement("hui-card");
|
||||
element.hass = this.hass;
|
||||
element.preview = this._preview;
|
||||
element.preview = this.lovelace.editMode;
|
||||
element.config = cardConfig;
|
||||
element.addEventListener("card-updated", (ev: Event) => {
|
||||
ev.stopPropagation();
|
||||
@@ -401,7 +391,7 @@ export class HUIView extends ReactiveElement {
|
||||
public createBadgeElement(badgeConfig: LovelaceBadgeConfig) {
|
||||
const element = document.createElement("hui-badge");
|
||||
element.hass = this.hass;
|
||||
element.preview = this._preview;
|
||||
element.preview = this.lovelace.editMode;
|
||||
element.config = badgeConfig;
|
||||
element.addEventListener("badge-updated", (ev: Event) => {
|
||||
ev.stopPropagation();
|
||||
@@ -416,9 +406,8 @@ 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._preview;
|
||||
element.preview = this.lovelace.editMode;
|
||||
element.addEventListener(
|
||||
"ll-rebuild",
|
||||
(ev: Event) => {
|
||||
@@ -460,9 +449,7 @@ export class HUIView extends ReactiveElement {
|
||||
(changedProperties.has("lovelace") &&
|
||||
(!oldLovelace ||
|
||||
this.lovelace.config.views[this.index] !==
|
||||
oldLovelace.config.views[this.index] ||
|
||||
(this._isStrategy &&
|
||||
strategyEditMode(this.lovelace) !== strategyEditMode(oldLovelace))))
|
||||
oldLovelace.config.views[this.index]))
|
||||
) {
|
||||
this._initializeConfig();
|
||||
return;
|
||||
@@ -478,7 +465,6 @@ export class HUIView extends ReactiveElement {
|
||||
if (
|
||||
this.hass.config.state === "RUNNING" &&
|
||||
(oldHass.config.state !== "RUNNING" ||
|
||||
oldHass.localize !== this.hass.localize ||
|
||||
checkStrategyShouldRegenerate(
|
||||
"view",
|
||||
viewConfig.strategy,
|
||||
@@ -530,16 +516,16 @@ export class HUIView extends ReactiveElement {
|
||||
try {
|
||||
element.hass = this.hass;
|
||||
element.lovelace = this.lovelace;
|
||||
element.preview = this._preview;
|
||||
element.preview = this.lovelace.editMode;
|
||||
} catch (e: any) {
|
||||
this._rebuildSection(element, createErrorSectionConfig(e.message));
|
||||
}
|
||||
});
|
||||
this._cards.forEach((element) => {
|
||||
element.preview = this._preview;
|
||||
element.preview = this.lovelace.editMode;
|
||||
});
|
||||
this._badges.forEach((element) => {
|
||||
element.preview = this._preview;
|
||||
element.preview = this.lovelace.editMode;
|
||||
});
|
||||
}
|
||||
if (changedProperties.has("_cards")) {
|
||||
@@ -557,8 +543,7 @@ export class HUIView extends ReactiveElement {
|
||||
if (isStrategyView(config)) {
|
||||
const strategyConfig = await generateLovelaceViewStrategy(
|
||||
config,
|
||||
this.hass!,
|
||||
{ editMode: strategyEditMode(this.lovelace) }
|
||||
this.hass!
|
||||
);
|
||||
const generatedConfig = normalizeViewConfig(strategyConfig);
|
||||
return {
|
||||
@@ -611,18 +596,11 @@ 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) {
|
||||
|
||||
@@ -1,9 +1,170 @@
|
||||
import { customElement } from "lit/decorators";
|
||||
import { HaHomeSummaryPanelBase } from "../home/ha-home-summary-panel-base";
|
||||
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",
|
||||
},
|
||||
};
|
||||
|
||||
@customElement("ha-panel-maintenance")
|
||||
class PanelMaintenance extends HaHomeSummaryPanelBase<"maintenance"> {
|
||||
protected readonly _systemDataKey = "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%;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -14,10 +14,6 @@ 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";
|
||||
@@ -25,7 +21,6 @@ import { findBatteryChargingEntity } from "../../../data/entity/entity_registry"
|
||||
|
||||
export interface MaintenanceViewStrategyConfig {
|
||||
type: "maintenance";
|
||||
hidden?: string[];
|
||||
}
|
||||
|
||||
export const maintenanceEntityFilters: EntityFilter[] = [
|
||||
@@ -40,10 +35,8 @@ export const maintenanceEntityFilters: EntityFilter[] = [
|
||||
];
|
||||
|
||||
export const findMaintenanceEntities = (
|
||||
sources: EntityFilterSources,
|
||||
hiddenEntities?: string[]
|
||||
): string[] =>
|
||||
findFilteredEntities(sources, maintenanceEntityFilters, hiddenEntities);
|
||||
sources: EntityFilterSources
|
||||
): string[] => findFilteredEntities(sources, maintenanceEntityFilters);
|
||||
|
||||
const LOW_BATTERY_THRESHOLD = 20;
|
||||
|
||||
@@ -107,29 +100,26 @@ export const filterUnavailableBatteryEntities = (
|
||||
const computeMaintenanceTileCard = (
|
||||
states: HomeAssistant["states"],
|
||||
entities: HomeAssistant["entities"],
|
||||
entityId: string,
|
||||
editMode: boolean
|
||||
entityId: string
|
||||
): 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";
|
||||
const card: TileCardConfig = {
|
||||
return {
|
||||
type: "tile",
|
||||
entity: entityId,
|
||||
name: !entities[entityId]?.device_id
|
||||
? { type: "entity" }
|
||||
: isProblem
|
||||
? [{ type: "device" }, { type: "entity" }]
|
||||
: { type: "device" },
|
||||
name: isProblem
|
||||
? [{ type: "device" }, { type: "entity" }]
|
||||
: { type: "device" },
|
||||
};
|
||||
return editMode
|
||||
? { ...card, metadata: { id: entityId, hideable: true } }
|
||||
: card;
|
||||
};
|
||||
|
||||
const processAreasForBattery = (
|
||||
areaIds: string[],
|
||||
hass: HomeAssistant,
|
||||
entities: string[],
|
||||
editMode: boolean
|
||||
entities: string[]
|
||||
): LovelaceCardConfig[] => {
|
||||
const cards: LovelaceCardConfig[] = [];
|
||||
|
||||
@@ -152,12 +142,7 @@ const processAreasForBattery = (
|
||||
|
||||
for (const entityId of areaBatteryEntities) {
|
||||
areaCards.push(
|
||||
computeMaintenanceTileCard(
|
||||
hass.states,
|
||||
hass.entities,
|
||||
entityId,
|
||||
editMode
|
||||
)
|
||||
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -182,8 +167,7 @@ const processAreasForBattery = (
|
||||
|
||||
const processUnassignedEntities = (
|
||||
hass: HomeAssistant,
|
||||
entities: string[],
|
||||
editMode: boolean
|
||||
entities: string[]
|
||||
): LovelaceCardConfig[] => {
|
||||
const unassignedFilter = generateEntityFilter(
|
||||
hass.states,
|
||||
@@ -200,7 +184,7 @@ const processUnassignedEntities = (
|
||||
|
||||
for (const entityId of unassignedEntities) {
|
||||
cards.push(
|
||||
computeMaintenanceTileCard(hass.states, hass.entities, entityId, editMode)
|
||||
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -209,27 +193,17 @@ 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,
|
||||
options?: LovelaceStrategyGenerateOptions
|
||||
_config: MaintenanceViewStrategyConfig,
|
||||
hass: HomeAssistant
|
||||
): 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, config.hidden);
|
||||
const entities = findMaintenanceEntities(hass);
|
||||
|
||||
const floorCount =
|
||||
hierarchy.floors.length + (hierarchy.areas.length ? 1 : 0);
|
||||
@@ -255,12 +229,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
|
||||
],
|
||||
};
|
||||
|
||||
const areaCards = processAreasForBattery(
|
||||
areaIds,
|
||||
hass,
|
||||
entities,
|
||||
editMode
|
||||
);
|
||||
const areaCards = processAreasForBattery(areaIds, hass, entities);
|
||||
|
||||
if (areaCards.length > 0) {
|
||||
section.cards!.push(...areaCards);
|
||||
@@ -286,12 +255,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
|
||||
],
|
||||
};
|
||||
|
||||
const areaCards = processAreasForBattery(
|
||||
hierarchy.areas,
|
||||
hass,
|
||||
entities,
|
||||
editMode
|
||||
);
|
||||
const areaCards = processAreasForBattery(hierarchy.areas, hass, entities);
|
||||
|
||||
if (areaCards.length > 0) {
|
||||
section.cards!.push(...areaCards);
|
||||
@@ -300,7 +264,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
|
||||
}
|
||||
|
||||
// Process unassigned entities
|
||||
const unassignedCards = processUnassignedEntities(hass, entities, editMode);
|
||||
const unassignedCards = processUnassignedEntities(hass, entities);
|
||||
|
||||
if (unassignedCards.length > 0) {
|
||||
const section: LovelaceSectionRawConfig = {
|
||||
|
||||
@@ -3098,13 +3098,6 @@
|
||||
"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.",
|
||||
@@ -8273,6 +8266,7 @@
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -710,23 +710,15 @@ describe("generateEntityFilter", () => {
|
||||
});
|
||||
|
||||
describe("findFilteredEntities", () => {
|
||||
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" }]);
|
||||
it("should match entities against any of the filters", () => {
|
||||
const entities = findFilteredEntities(mockHass, [
|
||||
{ domain: "light" },
|
||||
{ domain: "switch" },
|
||||
]);
|
||||
|
||||
expect(entities).toContain("light.living_room");
|
||||
expect(entities).toContain("light.bedroom");
|
||||
expect(entities).toContain("switch.kitchen");
|
||||
expect(entities).not.toContain("sensor.temperature");
|
||||
});
|
||||
});
|
||||
+44
-1
@@ -1,5 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getConfigSubpageTitle } from "../../src/data/panel";
|
||||
import {
|
||||
getConfigSubpageTitle,
|
||||
getSelectedPanelUrlPath,
|
||||
} from "../../src/data/panel";
|
||||
import type { PageNavigation } from "../../src/layouts/hass-tabs-subpage";
|
||||
import type { HomeAssistant } from "../../src/types";
|
||||
|
||||
@@ -83,3 +86,43 @@ 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,60 +280,4 @@ 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 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user