Compare commits

..
Author SHA1 Message Date
WendelinandClaude Opus 5.5 5f1c8a24fd Capture the camera player's input listeners
The options on a listener object are ignored by addEventListener, so the
listeners didn't capture and missed key presses stopped by dialogs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 17:13:46 +01:00
WendelinandClaude Opus 5.5 a350eaa9a7 Always hide the camera player controls after a few seconds
Hover only keeps the controls after mouse input, as a tapped button stays
hovered on touch screens. Focus only keeps them after keyboard input, as
focus moved by a script can look like keyboard focus. The hide timer also
starts again when the player is added back to the page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 16:55:17 +01:00
5 changed files with 24 additions and 194 deletions

No files matched your search

@@ -1,74 +0,0 @@
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type {
ConditionContext,
VisibilityCondition,
} from "../../panels/lovelace/common/validate-condition";
import { addEntityToCondition } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
import type { ConditionEvaluation } from "../controllers/condition-evaluator-controller";
import { ConditionEvaluatorController } from "../controllers/condition-evaluator-controller";
import { dropInvalidConditions } from "./sanitize";
export interface VisibilitySubscription {
/** Pass each new hass object so client-side conditions check again. */
update(hass: HomeAssistant): void;
/** Close the subscriptions. `onChange` is not called again. */
unsubscribe(): void;
}
/**
* Live visibility of a list of dashboard visibility conditions, for code
* without a Lit host, such as custom cards and plugins. Conditions core
* evaluates are subscribed to; the rest are checked locally. Reports
* `unknown` until core replies.
*/
export const subscribeVisibility = (
hass: HomeAssistant,
conditions: VisibilityCondition[],
onChange: (result: ConditionEvaluation, error?: string) => void,
context: ConditionContext = {}
): VisibilitySubscription => {
// The controller only needs a host to register with and to re-render.
const host: ReactiveControllerHost = {
addController: () => undefined,
removeController: () => undefined,
requestUpdate: () => undefined,
updateComplete: Promise.resolve(true),
};
let active = true;
const controller = new ConditionEvaluatorController(host, {
resubscribeDelay: 0,
onResult: (result, error) => {
if (active) {
onChange(result, error);
}
},
});
const sanitized = dropInvalidConditions(conditions);
const { entity_id: entityId } = context;
// Core-evaluated conditions never see the context, so fold its entity in
// first, as the dashboard mixin does.
const validConditions = entityId
? sanitized.map((condition) => addEntityToCondition(condition, entityId))
: sanitized;
const getContext = () => context;
controller.hostConnected();
controller.observe(validConditions, hass, getContext);
return {
update: (newHass) => {
if (active) {
controller.observe(validConditions, newHass, getContext);
}
},
unsubscribe: () => {
active = false;
controller.hostDisconnected();
},
};
};
+24 -3
View File
@@ -168,6 +168,16 @@ export class HaCameraPlayer extends LitElement {
private _controlsTimeout?: number;
// A pointer type or "keyboard", as hover sticks after a tap on touch
// screens and focus moved by a script can look like keyboard focus
private _lastInput?: string;
// Captured, as dialogs stop the propagation of their key presses
private _inputChanged = (ev: KeyboardEvent | PointerEvent) => {
this._lastInput =
ev.type === "keydown" ? "keyboard" : (ev as PointerEvent).pointerType;
};
private _wheelHintTimeout?: number;
private _videoRequest = 0;
@@ -205,6 +215,12 @@ export class HaCameraPlayer extends LitElement {
"webkitfullscreenchange",
this._fullscreenChanged
);
const inputOptions = { capture: true, passive: true };
document.addEventListener("keydown", this._inputChanged, inputOptions);
document.addEventListener("pointerdown", this._inputChanged, inputOptions);
if (this._controlsVisible) {
this._scheduleHideControls();
}
}
public disconnectedCallback() {
@@ -216,6 +232,8 @@ export class HaCameraPlayer extends LitElement {
"webkitfullscreenchange",
this._fullscreenChanged
);
document.removeEventListener("keydown", this._inputChanged, true);
document.removeEventListener("pointerdown", this._inputChanged, true);
clearTimeout(this._controlsTimeout);
clearTimeout(this._wheelHintTimeout);
this._streamInfoCallbacks.clear();
@@ -533,9 +551,10 @@ export class HaCameraPlayer extends LitElement {
this._controlsTimeout = window.setTimeout(() => {
this._controlsTimeout = undefined;
if (
this._overlay?.querySelector(
".control:hover, ha-camera-stream-badge:hover"
) ||
(this._lastInput === "mouse" &&
this._overlay?.querySelector(
".control:hover, ha-camera-stream-badge:hover"
)) ||
this._hasKeyboardFocus()
) {
this._scheduleHideControls();
@@ -547,6 +566,7 @@ export class HaCameraPlayer extends LitElement {
private _hasKeyboardFocus(): boolean {
return Boolean(
this._lastInput === "keyboard" &&
this.shadowRoot &&
deepActiveElement(this.shadowRoot)?.matches(":focus-visible")
);
@@ -956,6 +976,7 @@ export class HaCameraPlayer extends LitElement {
private _pointerMove(ev: PointerEvent) {
if (ev.pointerType === "mouse" && !this._pointers.size) {
this._lastInput = "mouse";
this._showControls();
}
const pointer = this._pointers.get(ev.pointerId);
-6
View File
@@ -2,10 +2,4 @@ import "@webcomponents/scoped-custom-element-registry/scoped-custom-element-regi
import "../resources/scoped-registry-ready";
import "../layouts/home-assistant";
// Custom cards and plugins can reach the helpers on any page, not only once a
// dashboard has loaded.
Object.assign(window, {
loadCardHelpers: () => import("../panels/lovelace/custom-card-helpers"),
});
import("../resources/append-ha-style");
@@ -9,8 +9,6 @@ export {
showPromptDialog,
} from "../../dialogs/generic/show-dialog-box";
export { importMoreInfoControl } from "../../dialogs/more-info/state_more_info_control";
export { subscribeVisibility } from "../../common/condition/subscribe-visibility";
export { createBadgeElement } from "./create-element/create-badge-element";
export { createCardElement } from "./create-element/create-card-element";
export { createHeaderFooterElement } from "./create-element/create-header-footer-element";
@@ -1,109 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { subscribeVisibility } from "../../../src/common/condition/subscribe-visibility";
import type { VisibilityCondition } from "../../../src/panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../../src/types";
interface CapturedSubscription {
push: (message: { result?: boolean }) => void;
unsub: ReturnType<typeof vi.fn>;
condition: unknown;
}
let subs: CapturedSubscription[];
const tick = () =>
new Promise<void>((resolve) => {
setTimeout(resolve, 10);
});
const createHass = (userId = "user1"): HomeAssistant =>
({
connection: {
subscribeMessage: vi.fn(
(
onChange: CapturedSubscription["push"],
msg: { condition: unknown }
) => {
const unsub = vi.fn();
subs.push({ push: onChange, unsub, condition: msg.condition });
return Promise.resolve(unsub);
}
),
},
states: {},
user: { id: userId },
locale: { time_zone: "local" },
config: { time_zone: "America/New_York" },
}) as unknown as HomeAssistant;
describe("subscribeVisibility", () => {
beforeEach(() => {
subs = [];
});
it("checks client conditions again with each hass passed to update", async () => {
const onChange = vi.fn();
const conditions: VisibilityCondition[] = [
{ condition: "user", users: ["user1"] },
];
const subscription = subscribeVisibility(
createHass("user1"),
conditions,
onChange
);
await tick();
expect(onChange).toHaveBeenLastCalledWith("visible", undefined);
subscription.update(createHass("user2"));
expect(onChange).toHaveBeenLastCalledWith("hidden", undefined);
});
it("closes core subscriptions and stops reporting after unsubscribe", async () => {
const onChange = vi.fn();
const conditions: VisibilityCondition[] = [
{ condition: "state", entity: "light.kitchen", state: "on" },
];
const subscription = subscribeVisibility(
createHass(),
conditions,
onChange
);
await tick();
expect(subs).toHaveLength(1);
subs[0].push({ result: true });
expect(onChange).toHaveBeenLastCalledWith("visible", undefined);
onChange.mockClear();
subscription.unsubscribe();
await tick();
expect(subs[0].unsub).toHaveBeenCalled();
expect(onChange).not.toHaveBeenCalled();
});
it("sends the context entity to core for conditions without one", async () => {
const conditions: VisibilityCondition[] = [
{ condition: "state", state: "on" },
];
subscribeVisibility(createHass(), conditions, vi.fn(), {
entity_id: "light.kitchen",
});
await tick();
expect(subs).toHaveLength(1);
expect(subs[0].condition).toEqual({
condition: "state",
entity_id: "light.kitchen",
state: "on",
});
});
});