Compare commits

...
Author SHA1 Message Date
Petar Petrov 81ed1e7c36 Rerender logbook rows when the brands token changes
Rows also narrow the config context and build the cause values once per filter run.
2026-12-01 17:27:11 +02:00
Petar Petrov 4f24c67e23 Drop hass from the logbook renderer
Logbook rows read their values from contexts, and the logbook helpers take separate values instead of hass.
2026-12-01 17:13:23 +02:00
16 changed files with 399 additions and 181 deletions

No files matched your search

-4
View File
@@ -4,15 +4,12 @@ import { customElement, property } from "lit/decorators";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../common/translations/localize";
import type { LogbookEntry } from "../../data/logbook";
import type { HomeAssistant } from "../../types";
import "./hat-logbook-note";
import "../../panels/logbook/ha-logbook-renderer";
import type { TraceExtended } from "../../data/trace";
@customElement("ha-trace-logbook")
export class HaTraceLogbook extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow = false;
@property({ attribute: false }) public trace!: TraceExtended;
@@ -26,7 +23,6 @@ export class HaTraceLogbook extends LitElement {
return this.logbookEntries.length
? html`
<ha-logbook-renderer
.hass=${this.hass}
.entries=${this.logbookEntries}
.narrow=${this.narrow}
no-detail
@@ -566,7 +566,6 @@ export class HaTracePathDetails extends LitElement {
return entries.length
? html`
<ha-logbook-renderer
.hass=${this.hass}
.entries=${entries}
.narrow=${this.narrow}
no-detail
+17 -7
View File
@@ -4,7 +4,7 @@ import type { TimestampStateDomain } from "../common/const";
import { computeDomain } from "../common/entity/compute_domain";
import { computeStateDomain } from "../common/entity/compute_state_domain";
import type { LocalizeFunc } from "../common/translations/localize";
import type { HomeAssistant } from "../types";
import type { HomeAssistant, HomeAssistantFormatters } from "../types";
import { UNAVAILABLE, UNKNOWN } from "./entity/entity";
import { isNumericEntity } from "./history";
@@ -316,24 +316,34 @@ const STATE_ACTION_MESSAGES: Record<
const RESTORABLE_BUTTON_DOMAINS = new Set(["button", "input_button"]);
export interface LogbookStateMessageValues {
localize: LocalizeFunc;
formatEntityState: HomeAssistantFormatters["formatEntityState"];
formatEntityAttributeValue: HomeAssistantFormatters["formatEntityAttributeValue"];
}
export const localizeStateMessage = (
hass: HomeAssistant,
values: LogbookStateMessageValues,
state: string,
stateObj: HassEntity,
domain: string,
entry?: LogbookEntry
): string => {
if (state === UNKNOWN || state === UNAVAILABLE) {
return hass.formatEntityState(stateObj, state);
return values.formatEntityState(stateObj, state);
}
// Events show the triggered event type, falling back to a generic label when
// the type is unknown (the timestamp state is meaningless on its own).
if (domain === "event") {
const eventType = entry?.attributes?.event_type;
if (eventType != null) {
return hass.formatEntityAttributeValue(stateObj, "event_type", eventType);
return values.formatEntityAttributeValue(
stateObj,
"event_type",
eventType
);
}
return hass.localize(`${LOGBOOK_LOCALIZE_PATH}.detected_event_no_type`);
return values.localize(`${LOGBOOK_LOCALIZE_PATH}.detected_event_no_type`);
}
const actionKey: LogbookActionMessage | undefined =
STATE_ACTION_MESSAGES[domain as keyof typeof STATE_ACTION_MESSAGES];
@@ -346,11 +356,11 @@ export const localizeStateMessage = (
actionKey &&
(!RESTORABLE_BUTTON_DOMAINS.has(domain) || matchesEntryTime)
) {
return hass.localize(`${LOGBOOK_LOCALIZE_PATH}.${actionKey}`);
return values.localize(`${LOGBOOK_LOCALIZE_PATH}.${actionKey}`);
}
// Every other domain reuses the backend state translation, so the logbook
// speaks the same vocabulary as the rest of the UI.
return hass.formatEntityState(stateObj, state);
return values.formatEntityState(stateObj, state);
};
export const filterLogbookCompatibleEntities = (entity) => {
@@ -392,7 +392,6 @@ export class HaAutomationTrace extends LitElement {
: this._view === "logbook"
? html`
<ha-trace-logbook
.hass=${this.hass}
.narrow=${this.narrow}
.trace=${this._trace}
.logbookEntries=${this._logbookEntries}
@@ -360,7 +360,6 @@ export class HaScriptTrace extends LitElement {
: this._view === "logbook"
? html`
<ha-trace-logbook
.hass=${this.hass}
.narrow=${this.narrow}
.trace=${this._trace}
.logbookEntries=${this._logbookEntries}
@@ -108,7 +108,7 @@ class HaPanelToolsActionHistory extends LitElement {
userIdToName: Record<string, string>,
systemUserIds: Set<string>,
services: HomeAssistant["services"],
_entities: HomeAssistant["entities"],
entities: HomeAssistant["entities"],
devices: HomeAssistant["devices"],
areas: HomeAssistant["areas"],
floors: HomeAssistant["floors"]
@@ -118,7 +118,15 @@ class HaPanelToolsActionHistory extends LitElement {
const user = computeUserCause(call, userIdToName, systemUserIds);
// Names come from the registries, which are inputs. The states are
// not, so the rows are not rebuilt on every state change.
const cause = computeContextCause(this.hass, call) ?? user;
const cause =
computeContextCause(
{
states: this.hass.states,
registries: { entities, devices, areas, floors },
localize,
},
call
) ?? user;
const data = call.service_data;
return {
id: String(index),
+36 -4
View File
@@ -7,6 +7,7 @@ import memoizeOne from "memoize-one";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { formatDateTimeWithSeconds } from "../../common/datetime/format_date_time";
import { fireEvent } from "../../common/dom/fire_event";
import { computeRTL } from "../../common/util/compute_rtl";
import "../../components/ha-adaptive-dialog";
import "../../components/ha-alert";
import "../../components/ha-icon";
@@ -26,7 +27,7 @@ import type { HomeAssistant } from "../../types";
import "./ha-logbook-chain";
import type { LogbookChain } from "./logbook-chain-resolver";
import { resolveLogbookChain } from "./logbook-chain-resolver";
import type { LogbookItem } from "./logbook-entry-model";
import type { LogbookItem, LogbookItemValues } from "./logbook-entry-model";
import { computeLogbookItem } from "./logbook-entry-model";
import { renderLogbookGlyph, transitionArrow } from "./logbook-entry-templates";
import type { LogbookDetailDialogParams } from "./show-dialog-logbook-detail";
@@ -137,7 +138,7 @@ class DialogLogbookDetail
}
const { entry } = this._params;
const item = computeLogbookItem(this.hass, entry);
const item = computeLogbookItem(this._itemValues(), entry);
return html`
<ha-adaptive-dialog
@@ -153,6 +154,29 @@ class DialogLogbookDetail
`;
}
private _isRTL() {
return computeRTL(
this.hass.language,
this.hass.translationMetadata.translations
);
}
private _itemValues(): LogbookItemValues {
return {
states: this.hass.states,
registries: {
entities: this.hass.entities,
devices: this.hass.devices,
areas: this.hass.areas,
floors: this.hass.floors,
},
isRTL: this._isRTL(),
localize: this.hass.localize,
formatEntityState: this.hass.formatEntityState,
formatEntityAttributeValue: this.hass.formatEntityAttributeValue,
};
}
private _renderFacts(item: LogbookItem, entry: LogbookEntry) {
const stateObj = entry.entity_id
? this.hass.states[entry.entity_id]
@@ -176,7 +200,7 @@ class DialogLogbookDetail
? html`<span class="old-state"
>${transition.oldState}</span
><span class="arrow"
>${transitionArrow(this.hass)}</span
>${transitionArrow(this._isRTL())}</span
>`
: nothing
}<span class="new-state">${transition.newState}</span>
@@ -242,7 +266,15 @@ class DialogLogbookDetail
// icon either, so fall back to the chain's own integration glyph.
private _renderSubjectIcon(item: LogbookItem, entry: LogbookEntry) {
if (item.glyph.type !== "brand") {
return renderLogbookGlyph(this.hass, entry, item.glyph);
return renderLogbookGlyph(
{
config: this.hass.config,
hassUrl: this.hass.auth.data.hassUrl,
darkMode: this.hass.themes?.darkMode,
},
entry,
item.glyph
);
}
return item.glyph.icon
? html`<ha-icon .icon=${item.glyph.icon}></ha-icon>`
+35 -6
View File
@@ -7,6 +7,7 @@ import { styleMap } from "lit/directives/style-map";
import { formatTimeWithMilliseconds } from "../../common/datetime/format_time";
import { fireEvent } from "../../common/dom/fire_event";
import { isNavigationClick } from "../../common/dom/is-navigation-click";
import { computeRTL } from "../../common/util/compute_rtl";
import { navigate } from "../../common/navigate";
import "../../components/ha-icon-next";
import "../../components/ha-state-icon";
@@ -18,7 +19,7 @@ import type { TraceContexts } from "../../data/trace";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import type { LogbookChain } from "./logbook-chain-resolver";
import type { LogbookCause } from "./logbook-entry-model";
import type { LogbookCause, LogbookItemValues } from "./logbook-entry-model";
import {
computeLogbookItem,
computeRunTraceLink,
@@ -28,6 +29,7 @@ import {
isSameLogbookEntry,
nodeColor,
} from "./logbook-entry-model";
import type { LogbookBrandValues } from "./logbook-entry-templates";
import {
renderLogbookCauseIcon,
renderLogbookGlyph,
@@ -169,7 +171,7 @@ class HaLogbookChain extends LitElement {
: undefined;
const secondary = isState
? origin.entityId
? entityDisplay(this.hass, origin.entityId).secondary
? entityDisplay(this._itemValues(), origin.entityId).secondary
: undefined
: this._actionUsedText(originRow);
const isAvatar = origin.type === "user" && !origin.systemUser;
@@ -242,6 +244,33 @@ class HaLogbookChain extends LitElement {
return renderLogbookCauseIcon(origin);
}
private _itemValues(): LogbookItemValues {
return {
states: this.hass.states,
registries: {
entities: this.hass.entities,
devices: this.hass.devices,
areas: this.hass.areas,
floors: this.hass.floors,
},
isRTL: computeRTL(
this.hass.language,
this.hass.translationMetadata.translations
),
localize: this.hass.localize,
formatEntityState: this.hass.formatEntityState,
formatEntityAttributeValue: this.hass.formatEntityAttributeValue,
};
}
private _brandValues(): LogbookBrandValues {
return {
config: this.hass.config,
hassUrl: this.hass.auth.data.hassUrl,
darkMode: this.hass.themes?.darkMode,
};
}
private _formatTimeWithMs(when: number) {
return formatTimeWithMilliseconds(
new Date(when),
@@ -251,14 +280,14 @@ class HaLogbookChain extends LitElement {
}
private _renderRunNode(row: LogbookEntry) {
const item = computeLogbookItem(this.hass, row);
const item = computeLogbookItem(this._itemValues(), row);
const time = this._formatTimeWithMs(item.when);
const traceLink = computeRunTraceLink(this.traceContexts, row);
return this._renderRow(
row.entity_id,
html`
<span class="chain-node run">
${renderLogbookGlyph(this.hass, row, item.glyph)}
${renderLogbookGlyph(this._brandValues(), row, item.glyph)}
</span>
<span class="chain-content">
<span class="name">${item.name}</span>
@@ -277,7 +306,7 @@ class HaLogbookChain extends LitElement {
}
private _renderEffectNode(row: LogbookEntry) {
const item = computeLogbookItem(this.hass, row);
const item = computeLogbookItem(this._itemValues(), row);
const stateObj = row.entity_id
? this.hass.states[row.entity_id]
: undefined;
@@ -293,7 +322,7 @@ class HaLogbookChain extends LitElement {
class="chain-node"
style=${color ? styleMap({ "--node-color": color }) : nothing}
>
${renderLogbookGlyph(this.hass, row, item.glyph)}
${renderLogbookGlyph(this._brandValues(), row, item.glyph)}
</span>
<span class="chain-content">
<span class="name">${item.name}</span>
+96 -18
View File
@@ -1,6 +1,8 @@
import type { ContextType } from "@lit/context";
import type { HassConfig, HassEntities } from "home-assistant-js-websocket";
import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { ifDefined } from "lit/directives/if-defined";
import { styleMap } from "lit/directives/style-map";
@@ -8,17 +10,31 @@ import { computeTimelineColor } from "../../components/chart/timeline-color";
import { computeDomain } from "../../common/entity/compute_domain";
import { formatTimeWithSeconds } from "../../common/datetime/format_time";
import { useAmPm } from "../../common/datetime/use_am_pm";
import { consume } from "../../common/decorators/consume";
import { transform } from "../../common/decorators/transform";
import { fireEvent } from "../../common/dom/fire_event";
import { computeRTL } from "../../common/util/compute_rtl";
import "../../components/ha-icon-next";
import "../../components/ha-tooltip";
import {
brandsAccessTokenContext,
configContext,
connectionContext,
formattersContext,
internationalizationContext,
registriesContext,
statesContext,
uiContext,
} from "../../data/context";
import { UNAVAILABLE } from "../../data/entity/entity";
import type { LogbookEntry } from "../../data/logbook";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import type { HomeAssistantConfig, HomeAssistantUI } from "../../types";
import type {
LogbookCause,
LogbookCauseType,
LogbookItem,
LogbookItemValues,
LogbookNameDetail,
LogbookValue,
} from "./logbook-entry-model";
@@ -27,6 +43,7 @@ import {
computeLogbookItem,
nodeColor,
} from "./logbook-entry-model";
import type { LogbookBrandValues } from "./logbook-entry-templates";
import {
renderLogbookCauseIcon,
renderLogbookGlyph,
@@ -38,6 +55,7 @@ type EntryLayout = "timeline" | "list" | "inline";
interface LogbookRenderItem extends LogbookItem {
renderedTime: string;
renderedValue: TemplateResult | string;
isRTL: boolean;
}
export interface LogbookEntrySelectedDetail {
@@ -52,8 +70,6 @@ declare global {
@customElement("ha-logbook-entry")
class HaLogbookEntry extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public item!: LogbookEntry;
@property({ attribute: false }) public userIdToName: Record<string, string> =
@@ -82,6 +98,45 @@ class HaLogbookEntry extends LitElement {
@property({ type: Boolean, attribute: "show-cause" }) public showCause =
false;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: ContextType<typeof formattersContext>;
@state()
@consume({ context: registriesContext, subscribe: true })
private _registries!: ContextType<typeof registriesContext>;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _config!: HassConfig;
@consume({ context: connectionContext, subscribe: true })
private _connection!: ContextType<typeof connectionContext>;
@state()
@consume({ context: brandsAccessTokenContext, subscribe: true })
// @ts-ignore re-render trigger only, its value is never read
private _brandsAccessToken?: string;
@state()
@consume({ context: uiContext, subscribe: true })
@transform<HomeAssistantUI, boolean | undefined>({
transformer: ({ themes }) => themes?.darkMode,
})
private _darkMode?: boolean;
// Not reactive: rows keep the names they rendered with instead of
// rerendering on every state change.
@consume({ context: statesContext, subscribe: true })
private _states?: HassEntities | null;
// Reading custom properties forces a style recalc, costly to repeat per row
// while scrolling — resolve once and cache.
private _computedStyle?: CSSStyleDeclaration;
@@ -90,7 +145,11 @@ class HaLogbookEntry extends LitElement {
const entry = this.item;
const seenEntityIds: string[] = [];
const item = computeLogbookItem(this.hass, entry, {
const isRTL = computeRTL(
this._i18n.language,
this._i18n.translationMetadata.translations
);
const item = computeLogbookItem(this._itemValues(isRTL), entry, {
nameDetail: this.nameDetail,
userIdToName: this.userIdToName,
systemUserIds: this.systemUserIds,
@@ -103,14 +162,15 @@ class HaLogbookEntry extends LitElement {
const renderedTime = formatTimeWithSeconds(
new Date(item.when),
this.hass.locale,
this.hass.config
this._i18n.locale,
this._config
);
const ctx: LogbookRenderItem = {
...item,
renderedTime,
renderedValue: this._renderValue(item.value, seenEntityIds),
isRTL,
};
const clickable = !this.noDetail;
@@ -125,7 +185,7 @@ class HaLogbookEntry extends LitElement {
[`node-${node}`]: true,
"last-of-day": this.lastOfDay,
[`category-${ctx.category}`]: true,
"time-am-pm": useAmPm(this.hass.locale),
"time-am-pm": useAmPm(this._i18n.locale),
clickable,
})}"
role=${ifDefined(clickable ? "button" : undefined)}
@@ -164,6 +224,25 @@ class HaLogbookEntry extends LitElement {
`;
}
private _itemValues(isRTL: boolean): LogbookItemValues {
return {
states: this._states ?? {},
registries: this._registries,
isRTL,
localize: this._i18n.localize,
formatEntityState: this._formatters.formatEntityState,
formatEntityAttributeValue: this._formatters.formatEntityAttributeValue,
};
}
private _brandValues(): LogbookBrandValues {
return {
config: this._config,
hassUrl: this._connection.hassUrl(),
darkMode: this._darkMode,
};
}
private _rowClicked() {
if (this.noDetail) {
return;
@@ -213,7 +292,7 @@ class HaLogbookEntry extends LitElement {
ctx.renderedValue
? valueIsState
? html`<span class="arrow"
>${transitionArrow(this.hass)}</span
>${transitionArrow(ctx.isRTL)}</span
>`
: " "
: nothing
@@ -265,7 +344,7 @@ class HaLogbookEntry extends LitElement {
}
private _renderCauseLine(cause: LogbookCause) {
const { localize } = this.hass;
const { localize } = this._i18n;
if (cause.entityId) {
const prefixMap: Partial<Record<LogbookCauseType, string>> = {
automation: localize("ui.components.logbook.cause.by_automation", {
@@ -284,7 +363,7 @@ class HaLogbookEntry extends LitElement {
</span>`;
}
return html`<span class="cause-line"
>${computeCausePhrase(this.hass.localize, cause)}</span
>${computeCausePhrase(localize, cause)}</span
>`;
}
@@ -313,11 +392,10 @@ class HaLogbookEntry extends LitElement {
entityId: string | undefined,
entityName: string | undefined
) {
const stateObj = entityId ? this._states?.[entityId] : undefined;
return (
entityName ||
(entityId && entityId in this.hass.states
? this.hass.formatEntityName(this.hass.states[entityId])
: entityId)
(stateObj ? this._formatters.formatEntityName(stateObj) : entityId)
);
}
@@ -328,7 +406,8 @@ class HaLogbookEntry extends LitElement {
if (message.indexOf(".") !== -1) {
const messageParts = message.split(" ");
for (let i = 0, size = messageParts.length; i < size; i++) {
if (messageParts[i] in this.hass.states) {
const stateObj = this._states?.[messageParts[i]];
if (stateObj) {
const entityId = messageParts[i];
if (seenEntities.includes(entityId)) {
return "";
@@ -337,8 +416,7 @@ class HaLogbookEntry extends LitElement {
const messageEnd = messageParts.splice(i);
messageEnd.shift();
return html`${messageParts.join(" ")}
${this.hass.formatEntityName(this.hass.states[entityId])}
${messageEnd.join(" ")}`;
${this._formatters.formatEntityName(stateObj)} ${messageEnd.join(" ")}`;
}
}
}
@@ -374,7 +452,7 @@ class HaLogbookEntry extends LitElement {
const unavailable =
item.glyph.type === "state" && item.glyph.stateObj.state === UNAVAILABLE;
return html`<div class="node-glyph" style=${style}>
${renderLogbookGlyph(this.hass, this.item, item.glyph)}
${renderLogbookGlyph(this._brandValues(), this.item, item.glyph)}
${unavailable ? html`<span class="node-badge"></span>` : nothing}
</div>`;
}
+33 -18
View File
@@ -1,18 +1,23 @@
import type { ContextType } from "@lit/context";
import type { VisibilityChangedEvent } from "@lit-labs/virtualizer";
import type { HassConfig } from "home-assistant-js-websocket";
import memoizeOne from "memoize-one";
import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, eventOptions, property, state } from "lit/decorators";
import { formatDate } from "../../common/datetime/format_date";
import { capitalizeFirstLetter } from "../../common/string/capitalize-first-letter";
import { consume } from "../../common/decorators/consume";
import { restoreScroll } from "../../common/decorators/restore-scroll";
import { transform } from "../../common/decorators/transform";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { fireEvent } from "../../common/dom/fire_event";
import { configContext, internationalizationContext } from "../../data/context";
import type { LogbookEntry } from "../../data/logbook";
import type { TraceContexts } from "../../data/trace";
import { haStyle, haStyleScrollbar } from "../../resources/styles";
import { loadVirtualizer } from "../../resources/virtualizer";
import type { HomeAssistant } from "../../types";
import type { HomeAssistantConfig } from "../../types";
import "./ha-logbook-entry";
import type { LogbookEntrySelectedDetail } from "./ha-logbook-entry";
import type { LogbookNameDetail } from "./logbook-entry-model";
@@ -27,8 +32,6 @@ declare global {
@customElement("ha-logbook-renderer")
class HaLogbookRenderer extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public userIdToName: Record<string, string> =
{};
@@ -62,24 +65,29 @@ class HaLogbookRenderer extends LitElement {
@state() private _firstVisibleIndex = 0;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _config!: HassConfig;
protected willUpdate(changedProps: PropertyValues<this>) {
if (
(!this.hasUpdated && this.virtualize) ||
(changedProps.has("virtualize") && this.virtualize)
) {
this.hass.loadBackendTranslation("services");
this.hass.loadBackendTranslation("title");
this._i18n.loadBackendTranslation("services");
this._i18n.loadBackendTranslation("title");
loadVirtualizer();
}
}
protected shouldUpdate(changedProps: PropertyValues<this>) {
const oldHass = changedProps.get("hass") as HomeAssistant | undefined;
const languageChanged =
oldHass === undefined ||
oldHass.locale !== this.hass.locale ||
oldHass.localize !== this.hass.localize;
return (
changedProps.has("entries") ||
changedProps.has("traceContexts") ||
@@ -87,7 +95,8 @@ class HaLogbookRenderer extends LitElement {
changedProps.has("userIdToName") ||
changedProps.has("systemUserIds") ||
changedProps.has("_firstVisibleIndex" as never) ||
languageChanged
changedProps.has("_i18n" as never) ||
changedProps.has("_config" as never)
);
}
@@ -95,7 +104,7 @@ class HaLogbookRenderer extends LitElement {
if (!this.entries?.length) {
return html`
<div class="container no-entries">
${this.hass.localize("ui.components.logbook.entries_not_found")}
${this._i18n.localize("ui.components.logbook.entries_not_found")}
</div>
`;
}
@@ -128,7 +137,9 @@ class HaLogbookRenderer extends LitElement {
.renderItem=${
this._getRenderRow(
this.userIdToName,
this.systemUserIds
this.systemUserIds,
this._i18n,
this._config
) as any
}
>
@@ -142,7 +153,12 @@ class HaLogbookRenderer extends LitElement {
// Memoized on every input the rows render from, so the virtualizer sees a
// new renderItem and refreshes already-rendered rows when one changes.
private _getRenderRow = memoizeOne(
(_userIdToName: Record<string, string>, _systemUserIds: Set<string>) =>
(
_userIdToName: Record<string, string>,
_systemUserIds: Set<string>,
_i18n: ContextType<typeof internationalizationContext>,
_config: HassConfig
) =>
(item: LogbookEntry, index: number) =>
this._renderItem(item, index)
);
@@ -165,7 +181,6 @@ class HaLogbookRenderer extends LitElement {
: nothing
}
<ha-logbook-entry
.hass=${this.hass}
.item=${item}
.userIdToName=${this.userIdToName}
.systemUserIds=${this.systemUserIds}
@@ -203,9 +218,9 @@ class HaLogbookRenderer extends LitElement {
const d = new Date(date);
d.setHours(0, 0, 0, 0);
const diffDays = Math.round((today.getTime() - d.getTime()) / 86400000);
const fullDate = formatDate(date, this.hass.locale, this.hass.config);
const fullDate = formatDate(date, this._i18n.locale, this._config);
if (diffDays === 0 || diffDays === 1) {
const rtf = new Intl.RelativeTimeFormat(this.hass.locale.language, {
const rtf = new Intl.RelativeTimeFormat(this._i18n.locale.language, {
numeric: "auto",
});
const rel = rtf.format(diffDays === 0 ? 0 : -1, "day");
+11 -2
View File
@@ -149,7 +149,6 @@ export class HaLogbook extends LitElement {
return html`
<ha-logbook-renderer
.hass=${this.hass}
.narrow=${this.narrow}
.virtualize=${this.virtualize}
.noIcon=${this.noIcon}
@@ -192,11 +191,21 @@ export class HaLogbook extends LitElement {
return entries;
}
const causes = new Set(causeFilter);
const causeValues = {
states: this.hass.states,
registries: {
entities: this.hass.entities,
devices: this.hass.devices,
areas: this.hass.areas,
floors: this.hass.floors,
},
localize: this.hass.localize,
};
return entries.filter((entry) =>
causes.has(
computeLogbookCauseKey(
entry,
computeRowCause(this.hass, entry, userIdToName, systemUserIds),
computeRowCause(causeValues, entry, userIdToName, systemUserIds),
personUserIds
)
)
+13 -3
View File
@@ -1,7 +1,7 @@
import type { LogbookEntry } from "../../data/logbook";
import { getLogbookDataFromServer } from "../../data/logbook";
import type { HomeAssistant } from "../../types";
import type { LogbookCause } from "./logbook-entry-model";
import type { LogbookCause, LogbookCauseValues } from "./logbook-entry-model";
import {
computeContextCause,
computeLogbookCause,
@@ -110,6 +110,16 @@ export const resolveLogbookChain = async (
): Promise<LogbookChain> => {
const userIdToName = options.userIdToName ?? {};
const { systemUserIds } = options;
const causeValues: LogbookCauseValues = {
states: hass.states,
registries: {
entities: hass.entities,
devices: hass.devices,
areas: hass.areas,
floors: hass.floors,
},
localize: hass.localize,
};
let rows: LogbookEntry[] = [];
if (entry.context_id) {
@@ -137,7 +147,7 @@ export const resolveLogbookChain = async (
let syntheticRun: LogbookCause | undefined;
if (runRow) {
const runCause = computeLogbookCause(
hass,
causeValues,
runRow,
userIdToName,
systemUserIds
@@ -155,7 +165,7 @@ export const resolveLogbookChain = async (
}
} else {
const userCause = computeUserCause(entry, userIdToName, systemUserIds);
const contextCause = computeContextCause(hass, entry);
const contextCause = computeContextCause(causeValues, entry);
if (isRunCause(contextCause)) {
syntheticRun = contextCause;
if (userCause) {
+57 -31
View File
@@ -1,5 +1,5 @@
import { isSameDay } from "date-fns";
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
import { computeDomain } from "../../common/entity/compute_domain";
import { computeEntityNameParts } from "../../common/entity/compute_entity_name_display";
import { stateColorCss } from "../../common/entity/state_color";
@@ -7,9 +7,11 @@ import type {
LocalizeFunc,
LocalizeKeys,
} from "../../common/translations/localize";
import { computeRTL } from "../../common/util/compute_rtl";
import { domainToName } from "../../data/integration";
import type { LogbookEntry } from "../../data/logbook";
import type {
LogbookEntry,
LogbookStateMessageValues,
} from "../../data/logbook";
import {
createHistoricState,
logbookUserCauseKey,
@@ -18,7 +20,7 @@ import {
} from "../../data/logbook";
import type { TraceContexts } from "../../data/trace";
import { getTraceUrl } from "../../data/trace";
import type { HomeAssistant } from "../../types";
import type { HomeAssistantRegistries } from "../../types";
export type LogbookEntryCategory = "entity" | "automation" | "integration";
@@ -58,17 +60,45 @@ export const isRunRow = (item: LogbookEntry): boolean =>
// device ▸ device ▸ entity), `area` (area ▸ parent device ▸ device ▸ entity).
export type LogbookNameDetail = "none" | "entity" | "device" | "area";
export interface LogbookEntityValues {
states: HassEntities;
registries: HomeAssistantRegistries;
}
export interface LogbookDisplayValues extends LogbookEntityValues {
isRTL: boolean;
}
export interface LogbookCauseValues extends LogbookEntityValues {
localize: LocalizeFunc;
}
export interface LogbookItemValues
extends LogbookDisplayValues, LogbookCauseValues, LogbookStateMessageValues {}
export interface EntityDisplay {
primary?: string;
secondary?: string;
}
const entityPrimaryName = (
{ states, registries }: LogbookEntityValues,
entityId: string
): string | undefined => {
const stateObj = states[entityId] as HassEntity | undefined;
if (!stateObj) {
return undefined;
}
const { entity, device } = computeEntityNameParts(stateObj, registries);
return entity || device || entityId;
};
export const entityDisplay = (
hass: HomeAssistant,
{ states, registries, isRTL }: LogbookDisplayValues,
entityId: string,
nameDetail?: LogbookNameDetail
): EntityDisplay => {
const stateObj = hass.states[entityId] as HassEntity | undefined;
const stateObj = states[entityId] as HassEntity | undefined;
if (!stateObj) {
return {};
}
@@ -78,7 +108,7 @@ export const entityDisplay = (
device: deviceName,
parent_device: parentDeviceName,
area: areaName,
} = computeEntityNameParts(stateObj, hass);
} = computeEntityNameParts(stateObj, registries);
const primary = entityName || deviceName || entityId;
@@ -101,10 +131,6 @@ export const entityDisplay = (
}
const filtered = parts.filter(Boolean) as string[];
const isRTL = computeRTL(
hass.language,
hass.translationMetadata.translations
);
const secondary = filtered.length
? filtered.join(isRTL ? " ◂ " : " ▸ ")
: undefined;
@@ -204,7 +230,7 @@ export const computeUserCause = (
};
export const computeContextCause = (
hass: HomeAssistant,
values: LogbookCauseValues,
item: LogbookEntry
): LogbookCause | undefined => {
if (
@@ -213,7 +239,7 @@ export const computeContextCause = (
) {
const name =
(item.context_entity_id
? entityDisplay(hass, item.context_entity_id).primary
? entityPrimaryName(values, item.context_entity_id)
: undefined) ?? item.context_name;
if (name) {
return {
@@ -231,13 +257,13 @@ export const computeContextCause = (
return {
type: "integration",
brandDomain: item.context_domain,
name: domainToName(hass.localize, item.context_domain),
name: domainToName(values.localize, item.context_domain),
};
}
if (item.context_state && item.context_entity_id) {
const name =
entityDisplay(hass, item.context_entity_id).primary ??
entityPrimaryName(values, item.context_entity_id) ??
item.context_entity_id_name;
if (name) {
return { type: "state", name, entityId: item.context_entity_id };
@@ -253,8 +279,8 @@ export const computeContextCause = (
const { platform, entityId } = parseTriggerSource(item.source);
if (platform === "state" || platform === "numeric_state") {
const name = entityId
? (entityDisplay(hass, entityId).primary ?? entityId)
: hass.localize(
? (entityPrimaryName(values, entityId) ?? entityId)
: values.localize(
`ui.components.logbook.trigger_type.${platform}` as LocalizeKeys
) || platform;
return { type: "state", name, entityId };
@@ -269,7 +295,7 @@ export const computeContextCause = (
return {
type: "homeassistant",
name:
hass.localize(`ui.components.logbook.${key}` as LocalizeKeys) ||
values.localize(`ui.components.logbook.${key}` as LocalizeKeys) ||
item.source,
};
}
@@ -277,7 +303,7 @@ export const computeContextCause = (
return {
type: "integration",
name:
hass.localize(
values.localize(
`ui.components.logbook.trigger_type.${platform}` as LocalizeKeys
) || platform,
};
@@ -298,13 +324,13 @@ export const computeContextCause = (
};
export const computeLogbookCause = (
hass: HomeAssistant,
values: LogbookCauseValues,
item: LogbookEntry,
userIdToName: Record<string, string>,
systemUserIds?: Set<string>
): LogbookCause | undefined =>
computeUserCause(item, userIdToName, systemUserIds) ??
computeContextCause(hass, item);
computeContextCause(values, item);
export const computeCausePhrase = (
localize: LocalizeFunc,
@@ -345,12 +371,12 @@ export const isRunCause = (cause?: LogbookCause): boolean =>
// A row shows the run over the user who started it; the dialog shows both.
export const computeRowCause = (
hass: HomeAssistant,
values: LogbookCauseValues,
item: LogbookEntry,
userIdToName: Record<string, string>,
systemUserIds?: Set<string>
): LogbookCause | undefined => {
const contextCause = computeContextCause(hass, item);
const contextCause = computeContextCause(values, item);
if (isRunCause(contextCause)) {
return contextCause;
}
@@ -409,7 +435,7 @@ export interface LogbookValue {
}
const computeLogbookValue = (
hass: HomeAssistant,
values: LogbookStateMessageValues,
item: LogbookEntry,
domain: string | undefined,
stateObj: HassEntity | undefined
@@ -417,7 +443,7 @@ const computeLogbookValue = (
if (item.entity_id && item.state) {
return {
text: stateObj
? localizeStateMessage(hass, item.state, stateObj, domain!, item)
? localizeStateMessage(values, item.state, stateObj, domain!, item)
: item.state,
type: "state",
};
@@ -432,7 +458,7 @@ const computeLogbookValue = (
isRunMessage(domain, item.message);
if (isAutomationRun) {
return {
text: hass.localize(
text: values.localize(
domain === "script"
? "ui.components.logbook.script_ran"
: "ui.components.logbook.automation_triggered"
@@ -471,7 +497,7 @@ export interface BuildLogbookItemOptions {
}
export const computeLogbookItem = (
hass: HomeAssistant,
values: LogbookItemValues,
entry: LogbookEntry,
opts: BuildLogbookItemOptions = {}
): LogbookItem => {
@@ -480,14 +506,14 @@ export const computeLogbookItem = (
? computeDomain(entry.entity_id)
: entry.domain;
const currentStateObj = entry.entity_id
? hass.states[entry.entity_id]
? values.states[entry.entity_id]
: undefined;
const historicStateObj = currentStateObj
? createHistoricState(currentStateObj, entry.state)
: undefined;
const display = entry.entity_id
? entityDisplay(hass, entry.entity_id, opts.nameDetail)
? entityDisplay(values, entry.entity_id, opts.nameDetail)
: undefined;
return {
@@ -496,9 +522,9 @@ export const computeLogbookItem = (
entityId: entry.entity_id,
name: display?.primary ?? entry.name,
context: display?.secondary,
value: computeLogbookValue(hass, entry, domain, historicStateObj),
value: computeLogbookValue(values, entry, domain, historicStateObj),
cause: computeRowCause(
hass,
values,
entry,
opts.userIdToName ?? {},
opts.systemUserIds
+13 -16
View File
@@ -7,9 +7,9 @@ import {
mdiScriptText,
mdiStateMachine,
} from "@mdi/js";
import type { HassConfig } from "home-assistant-js-websocket";
import { html } from "lit";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { computeRTL } from "../../common/util/compute_rtl";
import "../../components/entity/state-badge";
import "../../components/ha-domain-icon";
import "../../components/ha-state-icon";
@@ -18,7 +18,6 @@ import "../../components/user/ha-user-badge";
import { mdiHomeAssistant } from "../../resources/home-assistant-logo-svg";
import type { LogbookEntry } from "../../data/logbook";
import type { User } from "../../data/user";
import type { HomeAssistant } from "../../types";
import { brandsUrl } from "../../util/brands-url";
import type { LogbookCause, LogbookGlyph } from "./logbook-entry-model";
@@ -89,8 +88,14 @@ export const renderLogbookCauseIcon = (cause: LogbookCause) => {
></ha-svg-icon>`;
};
export interface LogbookBrandValues {
config: HassConfig;
hassUrl: string;
darkMode?: boolean;
}
const brandImage = (
hass: HomeAssistant,
{ config, hassUrl, darkMode }: LogbookBrandValues,
entry: LogbookEntry,
domain?: string
): string | undefined => {
@@ -98,25 +103,17 @@ const brandImage = (
!domain ||
entry.icon ||
entry.state ||
!isComponentLoaded(hass.config, domain)
!isComponentLoaded(config, domain)
) {
return undefined;
}
return brandsUrl(
{
domain,
type: "icon",
darkOptimized: hass.themes?.darkMode,
},
hass.auth.data.hassUrl
);
return brandsUrl({ domain, type: "icon", darkOptimized: darkMode }, hassUrl);
};
export const transitionArrow = (hass: HomeAssistant) =>
computeRTL(hass.language, hass.translationMetadata.translations) ? "←" : "→";
export const transitionArrow = (isRTL: boolean) => (isRTL ? "←" : "→");
export const renderLogbookGlyph = (
hass: HomeAssistant,
brand: LogbookBrandValues,
entry: LogbookEntry,
glyph: LogbookGlyph
) => {
@@ -133,7 +130,7 @@ export const renderLogbookGlyph = (
}
return html`<state-badge
.overrideIcon=${glyph.icon}
.overrideImage=${brandImage(hass, entry, glyph.domain)}
.overrideImage=${brandImage(brand, entry, glyph.domain)}
.stateColor=${false}
></state-badge>`;
};
+7 -7
View File
@@ -5,14 +5,14 @@ import {
localizeTriggerSource,
parseTriggerSource,
} from "../../src/data/logbook";
import type { HomeAssistant } from "../../src/types";
import type { LogbookStateMessageValues } from "../../src/data/logbook";
const fakeLocalize = ((key: string) => `<${key}>`) as any;
const fakeHass = {
const fakeValues = {
localize: fakeLocalize,
formatEntityState: (_stateObj, state: string) => `<state:${state}>`,
} as unknown as HomeAssistant;
} as unknown as LogbookStateMessageValues;
const fakeStateObj = {
entity_id: "button.restart",
@@ -25,7 +25,7 @@ describe("localizeStateMessage", () => {
"preserves the %s lifecycle state for timestamp entities",
(state) => {
expect(
localizeStateMessage(fakeHass, state, fakeStateObj, "button")
localizeStateMessage(fakeValues, state, fakeStateObj, "button")
).toBe(`<state:${state}>`);
}
);
@@ -33,7 +33,7 @@ describe("localizeStateMessage", () => {
it("uses the action label for a timestamp state", () => {
expect(
localizeStateMessage(
fakeHass,
fakeValues,
"2026-09-15T11:05:05+00:00",
fakeStateObj,
"button",
@@ -48,7 +48,7 @@ describe("localizeStateMessage", () => {
it("does not treat a restored timestamp with inherited context as a new action", () => {
const restoredState = "2026-09-15T10:55:25+00:00";
expect(
localizeStateMessage(fakeHass, restoredState, fakeStateObj, "button", {
localizeStateMessage(fakeValues, restoredState, fakeStateObj, "button", {
name: "Restart",
when: Date.parse("2026-09-15T11:05:05+00:00") / 1000,
context_domain: "homeassistant",
@@ -60,7 +60,7 @@ describe("localizeStateMessage", () => {
it("keeps the action label for a producer timestamp", () => {
expect(
localizeStateMessage(
fakeHass,
fakeValues,
"2026-09-15T10:55:25+00:00",
fakeStateObj,
"image",
+71 -60
View File
@@ -10,6 +10,7 @@ import {
isSameLogbookEntry,
} from "../../../src/panels/logbook/logbook-entry-model";
import type { LogbookEntry } from "../../../src/data/logbook";
import type { LogbookItemValues } from "../../../src/panels/logbook/logbook-entry-model";
import type { HomeAssistant } from "../../../src/types";
import {
mockArea,
@@ -18,17 +19,25 @@ import {
mockStateObj,
} from "../../common/entity/context/context-mock";
const baseHass = (partial: Partial<HomeAssistant>): HomeAssistant =>
({
language: "en",
translationMetadata: { translations: {} },
states: {},
entities: {},
devices: {},
areas: {},
floors: {},
...partial,
}) as unknown as HomeAssistant;
const baseValues = ({
states = {},
entities = {},
devices = {},
areas = {},
floors = {},
localize = (() => "") as HomeAssistant["localize"],
formatEntityState = ((_stateObj, state) =>
state ?? "") as HomeAssistant["formatEntityState"],
formatEntityAttributeValue = (() =>
"") as HomeAssistant["formatEntityAttributeValue"],
}: Partial<HomeAssistant>): LogbookItemValues => ({
states,
registries: { entities, devices, areas, floors },
isRTL: false,
localize,
formatEntityState,
formatEntityAttributeValue,
});
const entry = (partial: Partial<LogbookEntry>): LogbookEntry => ({
when: 0,
@@ -76,7 +85,7 @@ describe("classifyLogbookEntry", () => {
});
describe("entityDisplay", () => {
const hass = baseHass({
const values = baseValues({
states: {
"sensor.allee_battery": mockStateObj({
entity_id: "sensor.allee_battery",
@@ -102,42 +111,42 @@ describe("entityDisplay", () => {
});
it("shows 'Area ▸ Device' with no name detail (defaults to full)", () => {
expect(entityDisplay(hass, "sensor.allee_battery")).toEqual({
expect(entityDisplay(values, "sensor.allee_battery")).toEqual({
primary: "Battery state",
secondary: "Allée ▸ Caméra Allée",
});
});
it("shows 'Area ▸ Device' for the 'area' name detail", () => {
expect(entityDisplay(hass, "sensor.allee_battery", "area")).toEqual({
expect(entityDisplay(values, "sensor.allee_battery", "area")).toEqual({
primary: "Battery state",
secondary: "Allée ▸ Caméra Allée",
});
});
it("shows the device only for the 'device' name detail", () => {
expect(entityDisplay(hass, "sensor.allee_battery", "device")).toEqual({
expect(entityDisplay(values, "sensor.allee_battery", "device")).toEqual({
primary: "Battery state",
secondary: "Caméra Allée",
});
});
it("shows no context for the 'entity' name detail", () => {
expect(entityDisplay(hass, "sensor.allee_battery", "entity")).toEqual({
expect(entityDisplay(values, "sensor.allee_battery", "entity")).toEqual({
primary: "Battery state",
secondary: undefined,
});
});
it("shows no context for the 'none' name detail", () => {
expect(entityDisplay(hass, "sensor.allee_battery", "none")).toEqual({
expect(entityDisplay(values, "sensor.allee_battery", "none")).toEqual({
primary: "Battery state",
secondary: undefined,
});
});
it("drops the device from context when the entity uses the device name", () => {
const h = baseHass({
const h = baseValues({
states: { "sensor.desk": mockStateObj({ entity_id: "sensor.desk" }) },
entities: {
"sensor.desk": mockEntity({
@@ -163,7 +172,7 @@ describe("entityDisplay", () => {
});
describe("with a parent device", () => {
const h = baseHass({
const h = baseValues({
states: {
"sensor.outlet_1_power": mockStateObj({
entity_id: "sensor.outlet_1_power",
@@ -216,7 +225,7 @@ describe("entityDisplay", () => {
});
it("returns an empty display for a deleted entity", () => {
expect(entityDisplay(baseHass({}), "light.removed")).toEqual({});
expect(entityDisplay(baseValues({}), "light.removed")).toEqual({});
});
});
@@ -225,9 +234,9 @@ describe("computeLogbookCause", () => {
((key: string) => table[key] ?? "") as HomeAssistant["localize"];
it("uses state kind and entity id as name when source names an entity", () => {
const hass = baseHass({ localize: localizeStub() });
const values = baseValues({ localize: localizeStub() });
const cause = computeLogbookCause(
hass,
values,
entry({
domain: "automation",
source: "state of binary_sensor.porte",
@@ -235,19 +244,19 @@ describe("computeLogbookCause", () => {
{}
);
expect(cause?.type).toBe("state");
// Entity not in hass.states — falls back to entity id
// Entity not in the states — falls back to entity id
expect(cause?.name).toBe("binary_sensor.porte");
expect(cause?.entityId).toBe("binary_sensor.porte");
});
it("labels a service call with the domain name and integration kind", () => {
const hass = baseHass({
const values = baseValues({
localize: localizeStub({
"component.light.title": "Light",
}),
});
const cause = computeLogbookCause(
hass,
values,
entry({
context_event_type: "call_service",
context_domain: "light",
@@ -260,10 +269,10 @@ describe("computeLogbookCause", () => {
expect(cause?.brandDomain).toBe("light");
});
it("uses entity id as name when source entity is not in hass", () => {
const hass = baseHass({ localize: localizeStub() });
it("uses entity id as name when source entity has no state", () => {
const values = baseValues({ localize: localizeStub() });
const cause = computeLogbookCause(
hass,
values,
entry({ domain: "automation", source: "numeric state of sensor.temp" }),
{}
);
@@ -272,9 +281,9 @@ describe("computeLogbookCause", () => {
});
it("uses scheduled kind for time-based triggers", () => {
const hass = baseHass({ localize: localizeStub() });
const values = baseValues({ localize: localizeStub() });
const cause = computeLogbookCause(
hass,
values,
entry({ domain: "automation", source: "time pattern" }),
{}
);
@@ -282,9 +291,9 @@ describe("computeLogbookCause", () => {
});
it("flags a system user when its id is in the system set", () => {
const hass = baseHass({ localize: localizeStub() });
const values = baseValues({ localize: localizeStub() });
const cause = computeLogbookCause(
hass,
values,
entry({ context_user_id: "cloud_user" }),
{ cloud_user: "Home Assistant Cloud" },
new Set(["cloud_user"])
@@ -295,9 +304,9 @@ describe("computeLogbookCause", () => {
});
it("does not flag a regular user as a system user", () => {
const hass = baseHass({ localize: localizeStub() });
const values = baseValues({ localize: localizeStub() });
const cause = computeLogbookCause(
hass,
values,
entry({ context_user_id: "person_1" }),
{ person_1: "Alice" },
new Set(["cloud_user"])
@@ -353,7 +362,7 @@ describe("computeLogbookGlyph", () => {
describe("computeLogbookItem", () => {
it("builds an entity item (name, state as 'value', context, glyph)", () => {
const hass = baseHass({
const values = baseValues({
localize: ((key: string) => key) as HomeAssistant["localize"],
formatEntityState: ((_stateObj: any, state: string) =>
state === "on"
@@ -383,7 +392,7 @@ describe("computeLogbookItem", () => {
areas: { area_1: mockArea({ area_id: "area_1", name: "Salon" }) },
});
const model = computeLogbookItem(
hass,
values,
entry({ entity_id: "light.salon", state: "on", when: 1000 }),
{}
);
@@ -396,7 +405,7 @@ describe("computeLogbookItem", () => {
});
it("builds an automation item ('Triggered' value, automation glyph, trigger cause)", () => {
const hass = baseHass({
const values = baseValues({
localize: ((key: string) =>
({
"ui.components.logbook.automation_triggered": "Triggered",
@@ -404,7 +413,7 @@ describe("computeLogbookItem", () => {
})[key] ?? "") as HomeAssistant["localize"],
});
const model = computeLogbookItem(
hass,
values,
entry({
entity_id: "automation.x",
domain: "automation",
@@ -423,11 +432,11 @@ describe("computeLogbookItem", () => {
});
it("builds an integration item (message as 'phrase', brand glyph)", () => {
const hass = baseHass({
const values = baseValues({
localize: (() => "") as HomeAssistant["localize"],
});
const model = computeLogbookItem(
hass,
values,
entry({ domain: "zha", name: "Remote", message: "button pressed" }),
{}
);
@@ -443,13 +452,13 @@ describe("computeLogbookItem", () => {
});
it("shows 'Ran' for a script started by something else (context, no source)", () => {
const hass = baseHass({
const values = baseValues({
localize: ((key: string) =>
({ "ui.components.logbook.script_ran": "Ran" })[key] ??
"") as HomeAssistant["localize"],
});
const model = computeLogbookItem(
hass,
values,
entry({
entity_id: "script.x",
domain: "script",
@@ -596,12 +605,14 @@ describe("computeRunTraceLink", () => {
});
describe("computeLogbookItem cause", () => {
const hass = baseHass({ localize: (() => "") as HomeAssistant["localize"] });
const values = baseValues({
localize: (() => "") as HomeAssistant["localize"],
});
const users = { user_1: "Alice" };
it("prefers the automation over the user who ran it", () => {
const model = computeLogbookItem(
hass,
values,
entry({
entity_id: "light.ceiling",
state: "on",
@@ -618,7 +629,7 @@ describe("computeLogbookItem cause", () => {
it("keeps the user for a direct action call", () => {
const model = computeLogbookItem(
hass,
values,
entry({
entity_id: "light.ceiling",
state: "on",
@@ -635,7 +646,7 @@ describe("computeLogbookItem cause", () => {
it("falls back to the context cause without a user", () => {
const model = computeLogbookItem(
hass,
values,
entry({
entity_id: "light.ceiling",
state: "on",
@@ -649,7 +660,7 @@ describe("computeLogbookItem cause", () => {
it("leaves the cause empty without any context", () => {
const model = computeLogbookItem(
hass,
values,
entry({ entity_id: "light.ceiling", state: "on" }),
{ userIdToName: users }
);
@@ -659,11 +670,11 @@ describe("computeLogbookItem cause", () => {
describe("computeLogbookItem run rows", () => {
it("uses the run label instead of the raw backend message", () => {
const hass = baseHass({
const values = baseValues({
localize: ((key: string) => key) as HomeAssistant["localize"],
});
const model = computeLogbookItem(
hass,
values,
entry({
entity_id: "automation.wake_up",
domain: "automation",
@@ -679,11 +690,11 @@ describe("computeLogbookItem run rows", () => {
});
it("keeps the custom message of a domain-only entry (logbook.log)", () => {
const hass = baseHass({
const values = baseValues({
localize: ((key: string) => key) as HomeAssistant["localize"],
});
const model = computeLogbookItem(
hass,
values,
entry({ domain: "script", name: "Backup", message: "Backup finished" }),
{}
);
@@ -691,11 +702,11 @@ describe("computeLogbookItem run rows", () => {
});
it("uses the run label for a run with a trigger source", () => {
const hass = baseHass({
const values = baseValues({
localize: ((key: string) => key) as HomeAssistant["localize"],
});
const model = computeLogbookItem(
hass,
values,
entry({
entity_id: "automation.wake_up",
domain: "automation",
@@ -711,11 +722,11 @@ describe("computeLogbookItem run rows", () => {
});
it("uses the run label for a started script", () => {
const hass = baseHass({
const values = baseValues({
localize: ((key: string) => key) as HomeAssistant["localize"],
});
const model = computeLogbookItem(
hass,
values,
entry({
entity_id: "script.backup",
domain: "script",
@@ -732,11 +743,11 @@ describe("computeLogbookItem run rows", () => {
// logbook.log with an automation entity_id used to show "Triggered" (#53746)
it("keeps a custom message logged for an automation", () => {
const hass = baseHass({
const values = baseValues({
localize: ((key: string) => key) as HomeAssistant["localize"],
});
const model = computeLogbookItem(
hass,
values,
entry({
entity_id: "automation.wake_up",
domain: "automation",
@@ -752,11 +763,11 @@ describe("computeLogbookItem run rows", () => {
});
it("only treats the domain's own run message as a run", () => {
const hass = baseHass({
const values = baseValues({
localize: ((key: string) => key) as HomeAssistant["localize"],
});
const automation = computeLogbookItem(
hass,
values,
entry({
entity_id: "automation.wake_up",
domain: "automation",
@@ -766,7 +777,7 @@ describe("computeLogbookItem run rows", () => {
{}
);
const script = computeLogbookItem(
hass,
values,
entry({
entity_id: "script.backup",
domain: "script",