Compare commits

..
Author SHA1 Message Date
Aidan Timson 9083641ae7 Let custom cards subscribe to visibility conditions (#56284)
* Let custom cards subscribe to visibility on any page

* Send the context entity to core-evaluated conditions
2026-11-30 18:12:32 +02:00
8 changed files with 209 additions and 109 deletions

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();
},
};
};
-47
View File
@@ -1,47 +0,0 @@
/**
* How long after the full screen button the companion apps hide the page for
* the change, and after that how long they keep it hidden. A later hide ends
* streams as usual.
*/
export const FULLSCREEN_ENTER_TIME = 1000;
let enterStart = 0;
let enterId = 0;
// The last entering each stream let a hidden page through for
const claimedEnters = new WeakMap<object, number>();
/**
* Marks that the full screen button was pressed to enter full screen. The
* companion apps hide the page for a moment then, which shouldn't end a
* stream. Leaving full screen isn't marked, so locking the phone or leaving
* the app right after it always ends the streams.
*/
export const startEnteringFullscreen = () => {
enterId++;
enterStart = Date.now();
};
/** Ends it early, like when the browser denies full screen. */
export const cancelEnteringFullscreen = () => {
enterStart = 0;
};
export const isEnteringFullscreen = () =>
Date.now() - enterStart < FULLSCREEN_ENTER_TIME;
/**
* Whether the page is hidden by entering full screen, which hides it only
* once. Any later hiding is the user leaving, so each stream gets true only
* once per entering.
*/
export const claimFullscreenEnterHide = (stream: object): boolean => {
if (!isEnteringFullscreen() || claimedEnters.get(stream) === enterId) {
return false;
}
claimedEnters.set(stream, enterId);
// Counts from here, so the video still plays on when the page shows again
enterStart = Date.now();
return true;
};
+8 -38
View File
@@ -17,17 +17,11 @@ import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import { storage } from "../../common/decorators/storage";
import { deepActiveElement } from "../../common/dom/deep-active-element";
import { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
import {
cancelEnteringFullscreen,
isEnteringFullscreen,
startEnteringFullscreen,
} from "../../common/dom/entering-fullscreen";
import { ctrlOrCmdLabel } from "../../common/keyboard/ctrl-or-cmd";
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 { isExternal } from "../../data/external";
import {
showCameraStreamInfoDialog,
type CameraStreamInfo,
@@ -148,10 +142,6 @@ export class HaCameraPlayer extends LitElement {
// full screen player
@state() private _paused = false;
// Playing when its button entered full screen, so a pause meanwhile is the
// companion app's
private _playingBeforeFullscreen = false;
@query("ha-camera-stream") private _stream?: HaCameraStream;
@query(".player") private _player?: HTMLElement;
@@ -205,7 +195,7 @@ export class HaCameraPlayer extends LitElement {
public connectedCallback() {
super.connectedCallback();
document.addEventListener("visibilitychange", this._visibilityChanged);
document.addEventListener("visibilitychange", this._requestWakeLock);
// The first update requests it, once keep-awake is set
if (this.hasUpdated) {
this._requestWakeLock();
@@ -219,7 +209,7 @@ export class HaCameraPlayer extends LitElement {
public disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener("visibilitychange", this._visibilityChanged);
document.removeEventListener("visibilitychange", this._requestWakeLock);
this._releaseWakeLock();
document.removeEventListener("fullscreenchange", this._fullscreenChanged);
document.removeEventListener(
@@ -495,11 +485,6 @@ export class HaCameraPlayer extends LitElement {
</div>`;
}
private _visibilityChanged = () => {
this._requestWakeLock();
this._resumeAfterEnteringFullscreen();
};
/**
* Browsers release the lock when the page is hidden, so it is requested
* again whenever the page shows.
@@ -735,7 +720,6 @@ export class HaCameraPlayer extends LitElement {
this._paused = Boolean(
video?.paused && (video.srcObject || video.currentSrc)
);
this._resumeAfterEnteringFullscreen();
};
private _toggleMute() {
@@ -787,24 +771,15 @@ export class HaCameraPlayer extends LitElement {
("webkitFullscreenElement" in document
? (document.webkitFullscreenElement as Element | null)
: null);
this._fullscreen = Boolean(
const fullscreen = Boolean(
this._player && fullscreenElement === this._player
);
this._resumeAfterEnteringFullscreen();
};
// The companion apps pause the video while entering full screen
private _resumeAfterEnteringFullscreen() {
if (
isExternal &&
this._playingBeforeFullscreen &&
this._paused &&
document.visibilityState === "visible" &&
isEnteringFullscreen()
) {
this._ensurePlaying();
if (fullscreen !== this._fullscreen) {
this._fullscreen = fullscreen;
// The size changes, so the zoomed in area would be off
this._zoom = ZOOM_PAN_IDENTITY;
}
}
};
private async _toggleFullscreen() {
const player = this._player;
@@ -820,10 +795,6 @@ export class HaCameraPlayer extends LitElement {
}
return;
}
this._playingBeforeFullscreen = Boolean(
this._video && !this._video.paused
);
startEnteringFullscreen();
if (player.requestFullscreen) {
await player.requestFullscreen();
} else if ("webkitRequestFullscreen" in player) {
@@ -837,7 +808,6 @@ export class HaCameraPlayer extends LitElement {
}
} catch (_err: unknown) {
// Denied by the browser
cancelEnteringFullscreen();
}
}
+5 -12
View File
@@ -9,10 +9,6 @@ import { consume } from "../common/decorators/consume";
import { isComponentLoaded } from "../common/config/is_component_loaded";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import {
claimFullscreenEnterHide,
FULLSCREEN_ENTER_TIME,
} from "../common/dom/entering-fullscreen";
import type { LocalizeFunc } from "../common/translations/localize";
import { nextRender } from "../common/util/render-status";
import { fetchStreamUrl } from "../data/camera";
@@ -105,19 +101,16 @@ export class HaHLSPlayer extends LitElement {
return;
}
if (document.hidden) {
if (isExternal && !claimFullscreenEnterHide(this)) {
if (isExternal) {
// The companion apps pause JavaScript timers while in the background,
// so a delayed clean up would not run until the app is opened again
this._cleanUp();
return;
}
this._hiddenCleanupTimeout = window.setTimeout(
() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
},
isExternal ? FULLSCREEN_ENTER_TIME : HIDDEN_CLEANUP_DELAY
);
this._hiddenCleanupTimeout = window.setTimeout(() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
}, HIDDEN_CLEANUP_DELAY);
} else if (this._hiddenCleanupTimeout) {
// stream was not cleaned up yet, just cancel the cleanup
clearTimeout(this._hiddenCleanupTimeout);
+5 -12
View File
@@ -8,10 +8,6 @@ import { styleMap } from "lit/directives/style-map";
import { consume } from "../common/decorators/consume";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import {
claimFullscreenEnterHide,
FULLSCREEN_ENTER_TIME,
} from "../common/dom/entering-fullscreen";
import type { LocalizeFunc } from "../common/translations/localize";
import {
addWebRtcCandidate,
@@ -246,19 +242,16 @@ export class HaWebRtcPlayer extends LitElement {
return;
}
if (document.hidden) {
if (isExternal && !claimFullscreenEnterHide(this)) {
if (isExternal) {
// The companion apps pause JavaScript timers while in the background,
// so a delayed clean up would not run until the app is opened again
this._cleanUp();
return;
}
this._hiddenCleanupTimeout = window.setTimeout(
() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
},
isExternal ? FULLSCREEN_ENTER_TIME : HIDDEN_CLEANUP_DELAY
);
this._hiddenCleanupTimeout = window.setTimeout(() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
}, HIDDEN_CLEANUP_DELAY);
} else if (this._hiddenCleanupTimeout) {
// stream was not cleaned up yet, just cancel the cleanup
clearTimeout(this._hiddenCleanupTimeout);
+6
View File
@@ -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");
@@ -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";
@@ -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",
});
});
});