Compare commits

..
Author SHA1 Message Date
WendelinandClaude Opus 5.5 16681da1e7 Translate validation errors and show them at more fields
Core sends a translation key with the generic validation errors, like
`required` or `value_one_of`, so the frontend translates those and keeps
core's message for the rest. The remaining ha-form editors and the delay
action show their errors at the field instead of in the sidebar alert.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 14:42:19 +01:00
WendelinandClaude Opus 5.5 8598c5a8b0 Track single item blocks through moves and fix review findings
Blocks written as a single item, like `default: { delay: … }`, are now
indexed at the row path the editor uses, so their errors move with them.
Pending validations no longer apply after the editor is left, and the
problem count uses a plural form.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Kv7eJM4cuoppfSaBaZN3x
2026-11-24 14:42:14 +01:00
WendelinandClaude Opus 5.5 c54199ae14 Move errors with their rows and fix review findings
Follow the shown errors through moves and deletes right away instead of
waiting for revalidation, resolve the first row of a single item block
when tracking error items, close the save failed toast also when no
errors are left, and don't expand trigger rows that open in the sidebar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 09:01:11 +01:00
WendelinandClaude Opus 5.5 61fc108ee6 Adapt error rows to core's structured validation errors
Core now reports paths as written in the config, so the mapping of
flattened trigger lists and the parallel shorthand is gone. Only blocks
written as a single item still need the list index the editor shows.

Match the error type to core's contract, show the save failed toast
before revalidating so a later successful save closes it, and render
error alerts with one shared template.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 08:51:58 +01:00
WendelinandClaude Opus 5.5 627c78fcd6 Keep errors on duplicate rows and rows changed while saving
Identical rows keep their own errors after the YAML is parsed again, and
a save whose config changed meanwhile checks the current config in full,
so rows renamed and moved during the save stay marked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 08:42:52 +01:00
WendelinandClaude Opus 5.5 903f5e2624 Follow error rows through moves and saves
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 08:42:52 +01:00
WendelinandClaude Opus 5.5 12b8c005e8 Show automation validation errors on the rows they belong to
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 08:42:52 +01:00
57 changed files with 2397 additions and 196 deletions

No files matched your search

+3 -3
View File
@@ -3,8 +3,8 @@ import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
export const mockConfig = (hass: MockHomeAssistant) => {
hass.mockWS<typeof validateConfig>("validate_config", () => ({
actions: { valid: true, error: null },
conditions: { valid: true, error: null },
triggers: { valid: true, error: null },
actions: { valid: true, error: null, errors: [] },
conditions: { valid: true, error: null, errors: [] },
triggers: { valid: true, error: null, errors: [] },
}));
};
+16
View File
@@ -5,3 +5,19 @@ export const stringifyPath = (path: ConfigPath): string => path.join("/");
export const pathEquals = (a: ConfigPath, b: ConfigPath): boolean =>
a.length === b.length && a.every((segment, index) => segment === b[index]);
export const pathStartsWith = (path: ConfigPath, prefix: ConfigPath): boolean =>
prefix.length <= path.length &&
prefix.every((segment, index) => segment === path[index]);
/** Formats a path the way it reads in YAML, e.g. `actions[1].then[0].delay`. */
export const formatPath = (path: ConfigPath): string =>
path
.map((segment, index) =>
typeof segment === "number"
? `[${segment}]`
: index === 0
? segment
: `.${segment}`
)
.join("");
@@ -39,6 +39,9 @@ export class HaAutomationRow extends LitElement {
/** Makes the row a link, with the icons slot outside of it */
@property() public href?: string;
@property({ type: Boolean, reflect: true })
public error = false;
@query(".row")
private _rowElement?: HTMLDivElement;
@@ -285,6 +288,15 @@ export class HaAutomationRow extends LitElement {
:host([highlight]) .row:hover {
background-color: rgba(var(--rgb-primary-color), 0.16);
}
:host([error]) .row {
background-color: var(--ha-color-fill-danger-quiet-resting);
}
:host([error][selected]) .row,
:host([error][selected]) .row:focus {
outline: 2px solid var(--ha-color-border-danger-loud);
outline-offset: -2px;
background-color: var(--ha-color-fill-danger-normal-resting);
}
.icons,
.leading-icon-wrapper,
@@ -14,6 +14,12 @@ class HaDeviceActionPicker extends HaDeviceAutomationPicker<DeviceAction> {
);
}
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.actions.not_supported"
);
}
protected get UNKNOWN_AUTOMATION_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.actions.unknown_action"
@@ -49,6 +49,10 @@ export abstract class HaDeviceAutomationPicker<
@property({ type: Object }) public value?: T;
@property({ type: Boolean }) public invalid = false;
@property({ attribute: "error-message" }) public errorMessage?: string;
@state() private _automations?: T[];
// Trigger an empty render so we start with a clean DOM.
@@ -106,6 +110,13 @@ export abstract class HaDeviceAutomationPicker<
);
}
/** Error shown when the picked device has nothing to choose from. */
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.actions.not_supported"
);
}
private _localizeDeviceAutomation: (
localize: LocalizeFunc,
states: HassEntities,
@@ -163,6 +174,12 @@ export abstract class HaDeviceAutomationPicker<
.value=${value}
.disabled=${this._automations?.length === 0}
.loading=${this._automations === undefined}
.invalid=${this.invalid}
.errorMessage=${
this._automations?.length === 0
? this.NOT_SUPPORTED_TEXT
: this.errorMessage
}
.getItems=${this._getItems(
value,
this._automations,
@@ -14,6 +14,12 @@ class HaDeviceConditionPicker extends HaDeviceAutomationPicker<DeviceCondition>
);
}
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.conditions.not_supported"
);
}
protected get UNKNOWN_AUTOMATION_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.conditions.unknown_condition"
@@ -107,6 +107,10 @@ export class HaDevicePicker extends LitElement {
@property() public helper?: string;
@property({ type: Boolean }) public invalid = false;
@property({ attribute: "error-message" }) public errorMessage?: string;
@property() public placeholder?: string;
@property({ type: String, attribute: "search-label" })
@@ -521,6 +525,8 @@ export class HaDevicePicker extends LitElement {
.autofocus=${this.autofocus}
.disabled=${this.disabled}
.helper=${this.helper}
.invalid=${this.invalid}
.errorMessage=${this.errorMessage}
.label=${this.label}
.searchLabel=${this.searchLabel}
.notFoundLabel=${this._notFoundLabel}
@@ -14,6 +14,12 @@ class HaDeviceTriggerPicker extends HaDeviceAutomationPicker<DeviceTrigger> {
);
}
protected get NOT_SUPPORTED_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.triggers.not_supported"
);
}
protected get UNKNOWN_AUTOMATION_TEXT() {
return this._i18n.localize(
"ui.panel.config.devices.automation.triggers.unknown_trigger"
+99 -29
View File
@@ -41,6 +41,7 @@ import "./ha-selector/ha-selector";
import type { HaSelector } from "./ha-selector/ha-selector";
import "./ha-service-picker";
import "./ha-service-section-icon";
import "./ha-input-helper-text";
import "./ha-settings-row";
import "./ha-yaml-editor";
import type { HaYamlEditor } from "./ha-yaml-editor";
@@ -119,6 +120,15 @@ export class HaServiceControl extends LitElement {
@property({ attribute: "hide-description", type: Boolean })
public hideDescription = false;
/** Error shown below the target picker. */
@property({ attribute: false }) public targetError?: string;
/** Errors shown below the data fields, keyed by field. */
@property({ attribute: false }) public dataErrors?: Record<string, string>;
/** Error of the data as a whole. */
@property({ attribute: false }) public dataError?: string;
@state() private _value!: this["value"];
@state() private _checkedKeys = new Set();
@@ -558,13 +568,14 @@ export class HaServiceControl extends LitElement {
${
serviceData && "target" in serviceData
? html`<ha-selector
class="target-selector"
.hass=${this.hass}
.selector=${targetSelector}
.disabled=${this.disabled}
@value-changed=${this._targetChanged}
.value=${this._value?.target}
></ha-selector>`
class="target-selector"
.hass=${this.hass}
.selector=${targetSelector}
.disabled=${this.disabled}
@value-changed=${this._targetChanged}
.value=${this._value?.target}
></ha-selector>
${this._renderError(this.targetError)}`
: entityId
? html`<ha-entity-picker
.disabled=${this.disabled}
@@ -610,7 +621,10 @@ export class HaServiceControl extends LitElement {
this._hasFilteredFields(fields, targetEntities)
? html`<ha-expansion-panel
left-chevron
.expanded=${!dataField.collapsed}
.expanded=${
!dataField.collapsed ||
fields.some((field) => this.dataErrors?.[field.key])
}
.header=${
this.hass.localize(
`component.${domain}.services.${serviceName}.sections.${dataField.key}.name`,
@@ -642,7 +656,12 @@ export class HaServiceControl extends LitElement {
</ha-expansion-panel>`
: nothing;
})
} `;
}
${this._unshownErrors(
serviceData,
targetEntities,
Boolean(shouldRenderServiceDataYaml)
).map((error) => this._renderError(error))}`;
}
private _getSectionDescription(
@@ -759,30 +778,70 @@ export class HaServiceControl extends LitElement {
}
></ha-markdown>
</span>
<ha-selector
.context=${this._selectorContext(targetEntities)}
.disabled=${
this.disabled ||
(showOptional &&
!this._checkedKeys.has(dataField.key) &&
(!this._value?.data ||
this._value.data[dataField.key] === undefined))
}
.hass=${this.hass}
.selector=${selector}
.key=${dataField.key}
@value-changed=${this._serviceDataChanged}
.value=${
this._value?.data ? this._value.data[dataField.key] : undefined
}
.placeholder=${dataField.default}
.localizeValue=${this._localizeValueCallback}
.required=${dataField.required}
></ha-selector>
<div class="field">
<ha-selector
.context=${this._selectorContext(targetEntities)}
.disabled=${
this.disabled ||
(showOptional &&
!this._checkedKeys.has(dataField.key) &&
(!this._value?.data ||
this._value.data[dataField.key] === undefined))
}
.hass=${this.hass}
.selector=${selector}
.key=${dataField.key}
@value-changed=${this._serviceDataChanged}
.value=${
this._value?.data ? this._value.data[dataField.key] : undefined
}
.placeholder=${dataField.default}
.localizeValue=${this._localizeValueCallback}
.required=${dataField.required}
></ha-selector>
${this._renderError(this.dataErrors?.[dataField.key])}
</div>
</ha-settings-row>`
: "";
};
// Errors without a field to show them on, e.g. of a field no target
// supports or of a target the action doesn't have a picker for
private _unshownErrors(
serviceData: ExtHassService | undefined,
targetEntities: string[] | null,
dataYaml: boolean
): string[] {
const targetShown = Boolean(serviceData && "target" in serviceData);
const shownFields = new Set(
dataYaml
? []
: (serviceData?.flatFields ?? [])
.filter(
(field) =>
field.selector &&
(!field.filter ||
this._filterField(field.filter, targetEntities))
)
.map((field) => field.key)
);
return [
...(this.targetError && !targetShown ? [this.targetError] : []),
...(this.dataError ? [this.dataError] : []),
...Object.entries(this.dataErrors ?? {})
.filter(([key]) => !shownFields.has(key))
.map(([key, error]) => `${key}: ${error}`),
];
}
private _renderError(error: string | undefined) {
return error
? html`<ha-input-helper-text class="error"
>${error}</ha-input-helper-text
>`
: nothing;
}
private _selectorContext = memoizeOne((targetEntities: string[] | null) => ({
filter_entity: targetEntities || undefined,
}));
@@ -1022,6 +1081,17 @@ export class HaServiceControl extends LitElement {
ha-settings-row {
padding: var(--service-control-padding, 0 var(--ha-space-4));
}
/* Every field has this wrapper, so the selector isn't rebuilt when its
error comes or goes */
.field {
display: flex;
flex-direction: column;
}
ha-input-helper-text.error {
color: var(--ha-color-on-danger-quiet);
padding-top: var(--ha-space-1);
padding-bottom: var(--ha-space-2);
}
ha-settings-row[narrow] {
padding-bottom: var(--ha-space-2);
}
+70
View File
@@ -1,17 +1,33 @@
import type { ConfigPath } from "../common/util/config-path";
import type { HomeAssistant } from "../types";
export interface ConfigValidationError {
message: string;
/** The path in the config as it was sent, `[]` when core does not know. */
path: ConfigPath;
code: string | null;
translation_key: string | null;
translation_domain: string | null;
translation_placeholders: Record<string, unknown>;
}
export interface ValidConfig {
valid: true;
error: null;
errors: [];
}
export interface InvalidConfig {
valid: false;
error: string;
/** Paths are relative to the section. */
errors: ConfigValidationError[];
}
type ValidKeys = "triggers" | "actions" | "conditions";
export type ValidationSectionKeys = Partial<Record<ValidKeys, string>>;
export const validateConfig = <T extends Partial<Record<ValidKeys, unknown>>>(
hass: HomeAssistant,
config: T
@@ -20,3 +36,57 @@ export const validateConfig = <T extends Partial<Record<ValidKeys, unknown>>>(
type: "validate_config",
...config,
});
/**
* Flattens a `validate_config` result into errors with paths from the config
* root. `sectionKeys` names the config key of a section when it differs from
* the key it is validated under, e.g. `{ actions: "sequence" }` for scripts.
*/
export const validationResultErrors = (
result: Partial<Record<ValidKeys, ValidConfig | InvalidConfig>>,
sectionKeys: ValidationSectionKeys = {}
): ConfigValidationError[] =>
(Object.keys(result) as ValidKeys[]).flatMap((key) => {
const sectionKey = sectionKeys[key] ?? key;
return (result[key]?.errors ?? []).map((error) => ({
...error,
path: [sectionKey, ...error.path],
}));
});
export const validateConfigErrors = async (
hass: HomeAssistant,
config: Partial<Record<ValidKeys, unknown>>,
sectionKeys?: ValidationSectionKeys
): Promise<ConfigValidationError[]> =>
validationResultErrors(await validateConfig(hass, config), sectionKeys);
export interface ConfigSaveError {
message: string;
errors: ConfigValidationError[];
}
/**
* Reads the errors of a failed config save. Errors that are not about the
* config, like a network error, only have a message.
*/
export const parseConfigSaveError = (err: unknown): ConfigSaveError => {
const { body, error } = (err ?? {}) as { body?: unknown; error?: unknown };
const bodyObject =
body && typeof body === "object"
? (body as { message?: unknown; errors?: unknown })
: undefined;
const message = String(
bodyObject?.message ||
error ||
(typeof body === "string" && body) ||
(err instanceof Error && err.message) ||
err
);
return {
message,
errors: Array.isArray(bodyObject?.errors)
? (bodyObject.errors as ConfigValidationError[])
: [],
};
};
@@ -129,6 +129,7 @@ import "./types/ha-automation-action-wait_template";
import { renderCtrlOrCmd } from "../../../../common/keyboard/ctrl-or-cmd";
import { scrollRowIntoView } from "../scroll-row-into-view";
import { AutomationPathController } from "../automation-path";
import { renderRowErrorIcon } from "../automation-error-templates";
export interface ActionElement extends LitElement {
action: Action;
@@ -498,6 +499,12 @@ export default class HaAutomationActionRow extends LitElement {
${this._runResult?.title}
</ha-automation-row-event-chip>
${renderRowErrorIcon(
this.hass.localize,
this.pathController.errors,
this.pathController.path,
this.hass.localize("ui.panel.config.automation.editor.errors.label")
)}
<slot name="icons" slot="icons"></slot>
<ha-dropdown
@@ -798,6 +805,7 @@ export default class HaAutomationActionRow extends LitElement {
...ACTION_COMBINED_BLOCKS,
].includes(blockType!)}
.sortSelected=${this.sortSelected}
.error=${this.pathController.errors.length > 0}
.dim=${this._running}
@click=${this._toggleSidebar}
@toggle-collapsed=${this._toggleCollapse}
@@ -1,18 +1,25 @@
import type { PropertyValues } from "lit";
import { html, LitElement } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../../common/dom/fire_event";
import { hasTemplate } from "../../../../../common/string/has-template";
import type { HaDurationData } from "../../../../../components/ha-duration-input";
import "../../../../../components/ha-alert";
import "../../../../../components/ha-duration-input";
import type { DelayAction } from "../../../../../data/script";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { HomeAssistant } from "../../../../../types";
import type { ActionElement } from "../ha-automation-action-row";
import { createDurationData } from "../../../../../common/datetime/create_duration_data";
import { errorMessage } from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-action-delay")
export class HaDelayAction extends LitElement implements ActionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["delay"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean }) public disabled = false;
@@ -52,16 +59,25 @@ export class HaDelayAction extends LitElement implements ActionElement {
}
protected render() {
return html`<ha-duration-input
.label=${this.hass.localize(
`ui.panel.config.automation.editor.actions.type.delay.delay`
)}
.disabled=${this.disabled}
.data=${this._timeData}
enable-millisecond
required
@value-changed=${this._valueChanged}
></ha-duration-input>`;
const label = this.hass.localize(
"ui.panel.config.automation.editor.actions.type.delay.delay"
);
const error = this._fieldErrors.fieldError("delay");
return html`${
error
? html`<ha-alert own-margin alert-type="error">
${errorMessage(this.hass.localize, error, label)}
</ha-alert>`
: nothing
}
<ha-duration-input
.label=${label}
.disabled=${this.disabled}
.data=${this._timeData}
enable-millisecond
required
@value-changed=${this._valueChanged}
></ha-duration-input>`;
}
private _valueChanged(ev: CustomEvent) {
@@ -27,9 +27,18 @@ import {
} from "../../../../../data/device/device_registry";
import type { EntityRegistryEntry } from "../../../../../data/entity/entity_registry";
import type { HomeAssistant } from "../../../../../types";
import {
deviceAutomationErrorText,
deviceErrorText,
} from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-action-device_id")
export class HaDeviceAction extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["device_id", "domain"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean }) public disabled = false;
@@ -131,12 +140,20 @@ export class HaDeviceAction extends LitElement {
}
protected render() {
const deviceError = this._fieldErrors.fieldError("device_id");
const automationError = this._fieldErrors.fieldError("domain");
const deviceId = this._deviceId || this.action.device_id;
return html`
<ha-device-picker
.value=${deviceId}
.replacementDeviceIds=${this._replacementDeviceIds}
.invalid=${!!deviceError}
.errorMessage=${
deviceError
? deviceErrorText(this.hass.localize, deviceError)
: undefined
}
.disabled=${this.disabled}
@value-changed=${this._devicePicked}
label=${this.hass.localize(
@@ -144,6 +161,16 @@ export class HaDeviceAction extends LitElement {
)}
></ha-device-picker>
<ha-device-action-picker
.invalid=${!!automationError}
.errorMessage=${
automationError
? deviceAutomationErrorText(
this.hass.localize,
"actions",
automationError
)
: undefined
}
.value=${this.action}
.deviceId=${deviceId}
.disabled=${this.disabled}
@@ -20,6 +20,7 @@ import type {
import type { HaSelector } from "../../../../../components/ha-selector/ha-selector";
import type { HaActionSelector } from "../../../../../components/ha-selector/ha-selector-action";
import type { HaConditionSelector } from "../../../../../components/ha-selector/ha-selector-condition";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const OPTIONS = ["count", "while", "until", "for_each"] as const;
type RepeatType = (typeof OPTIONS)[number];
@@ -29,6 +30,11 @@ export const getRepeatType = (action: RepeatAction["repeat"]) =>
@customElement("ha-automation-action-repeat")
export class HaRepeatAction extends LitElement implements ActionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
key: "repeat",
inlineFields: ["count", "for_each"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean }) public disabled = false;
@@ -123,6 +129,8 @@ export class HaRepeatAction extends LitElement implements ActionElement {
const data = { ...action, type };
return html`<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${schema}
@@ -12,6 +12,8 @@ import type { ServiceAction } from "../../../../../data/script";
import { serviceActionStruct } from "../../../../../data/script";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { HomeAssistant } from "../../../../../types";
import { errorMessage, targetErrorText } from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import type { ActionElement } from "../ha-automation-action-row";
@customElement("ha-automation-action-service")
@@ -28,6 +30,10 @@ export class HaServiceAction extends LitElement implements ActionElement {
@state() private _responseChecked = false;
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["target", "data"],
});
public static get defaultConfig(): ServiceAction {
return { action: "", data: {} };
}
@@ -80,6 +86,9 @@ export class HaServiceAction extends LitElement implements ActionElement {
? this._action.action.split(".", 2)
: [undefined, undefined];
const targetError = this._fieldErrors.fieldError("target");
const dataError = this._fieldErrors.ownFieldError("data");
const optionalResponse =
domain && service
? !!this.hass.services[domain]?.[service]?.response?.optional
@@ -92,6 +101,15 @@ export class HaServiceAction extends LitElement implements ActionElement {
.value=${this._action}
.disabled=${this.disabled}
.hidePicker=${!!this._action.metadata}
.targetError=${
targetError
? targetErrorText(this.hass.localize, targetError)
: undefined
}
.dataErrors=${this._fieldErrors.nestedFieldErrors("data")}
.dataError=${
dataError ? errorMessage(this.hass.localize, dataError) : undefined
}
@value-changed=${this._actionChanged}
></ha-service-control>
${
@@ -4,6 +4,7 @@ import "../../../../../components/ha-form/ha-form";
import type { SetConversationResponseAction } from "../../../../../data/script";
import type { HomeAssistant } from "../../../../../types";
import type { ActionElement } from "../ha-automation-action-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const SCHEMA = [
{
@@ -19,6 +20,10 @@ export class HaSetConversationResponseAction
extends LitElement
implements ActionElement
{
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["set_conversation_response"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public action!: SetConversationResponseAction;
@@ -32,6 +37,8 @@ export class HaSetConversationResponseAction
protected render() {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${this.action}
.schema=${SCHEMA}
@@ -15,12 +15,17 @@ import "../../trigger/ha-automation-trigger";
import type { TimeoutType } from "../../types";
import type { ActionElement } from "../ha-automation-action-row";
import { handleChangeEvent } from "../ha-automation-action-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-action-wait_for_trigger")
export class HaWaitForTriggerAction
extends LitElement
implements ActionElement
{
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["timeout", "continue_on_timeout"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public action!: WaitForTriggerAction;
@@ -77,6 +82,10 @@ export class HaWaitForTriggerAction
this.inSidebar || (!this.inSidebar && !this.indent)
? html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(
this._computeLabelCallback
)}
.hass=${this.hass}
.data=${this.action}
.schema=${this._schema(timeoutType, timeout !== undefined)}
@@ -7,6 +7,7 @@ import type { WaitAction } from "../../../../../data/script";
import type { HomeAssistant } from "../../../../../types";
import type { ActionElement } from "../ha-automation-action-row";
import "../../../../../components/ha-form/ha-form";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import type {
HaFormSchema,
SchemaUnion,
@@ -15,6 +16,10 @@ import type { TimeoutType } from "../../types";
@customElement("ha-automation-action-wait_template")
export class HaWaitAction extends LitElement implements ActionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["wait_template", "timeout", "continue_on_timeout"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public action!: WaitAction;
@@ -65,6 +70,8 @@ export class HaWaitAction extends LitElement implements ActionElement {
: "duration";
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${this.action}
.schema=${this._schema(timeoutType, timeout !== undefined)}
@@ -0,0 +1,48 @@
import { mdiAlertCircle } from "@mdi/js";
import { html, nothing } from "lit";
import { ifDefined } from "lit/directives/if-defined";
import type { LocalizeFunc } from "../../../common/translations/localize";
import type { ConfigPath } from "../../../common/util/config-path";
import "../../../components/ha-alert";
import "../../../components/ha-svg-icon";
import "../../../components/ha-tooltip";
import type { ConfigValidationError } from "../../../data/config";
import { errorText } from "./automation-errors";
export const renderRowErrorIcon = (
localize: LocalizeFunc,
errors: ConfigValidationError[],
path: ConfigPath,
label: string
) =>
errors.length
? html`<ha-svg-icon
id="error-icon"
slot="icons"
tabindex="0"
class="error-indicator"
.path=${mdiAlertCircle}
role="img"
aria-label=${label}
></ha-svg-icon>
<ha-tooltip for="error-icon" slot="icons">
${errors.map((error) => html`<div>${errorText(localize, error, path)}</div>`)}
</ha-tooltip>`
: nothing;
/** Lists errors with their path relative to `path`. */
export const renderErrorsAlert = (
localize: LocalizeFunc,
errors: ConfigValidationError[],
path: ConfigPath = [],
slot?: string
) =>
errors.length
? html`<ha-alert
alert-type="error"
class="errors-alert"
slot=${ifDefined(slot)}
>
${errors.map((error) => html`<div>${errorText(localize, error, path)}</div>`)}
</ha-alert>`
: nothing;
@@ -0,0 +1,403 @@
import { createContext } from "@lit/context";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../../../common/translations/localize";
import {
formatPath,
pathEquals,
pathStartsWith,
type ConfigPath,
} from "../../../common/util/config-path";
import type { ConfigValidationError } from "../../../data/config";
import type {
AutomationPathRow,
AutomationRowRegistry,
} from "./automation-path";
import { isConfigObject } from "./ui-support";
/** The validation errors of the config being edited, paths from its root. */
export const automationErrorsContext =
createContext<ConfigValidationError[]>("automation-errors");
export const NO_ERRORS: ConfigValidationError[] = [];
/**
* The row an error belongs to: the deepest rendered row on its path. Rows
* above it only contain the error, they are expanded to show it.
*/
export const errorOwner = (
registry: AutomationRowRegistry,
error: ConfigValidationError
): AutomationPathRow | undefined => {
const rows = registry.rowsAlong(error.path);
return rows[rows.length - 1];
};
export const ownedErrors = (
registry: AutomationRowRegistry,
errors: ConfigValidationError[],
row: AutomationPathRow
): ConfigValidationError[] => {
const owned = errors.filter((error) => errorOwner(registry, error) === row);
return owned.length ? owned : NO_ERRORS;
};
/**
* The message of an error, translated when core sent a translation key the
* frontend knows, like `required`.
*/
export const errorMessage = (
localize: LocalizeFunc,
error: ConfigValidationError,
/** The label of the field the error is about, to name it in the message */
field?: string
): string => {
if (!field) {
return translatedMessage(localize, error);
}
return error.translation_key === "required" && !error.translation_domain
? localize(
"ui.panel.config.automation.editor.errors.validation.required_field",
{ field }
)
: localize("ui.panel.config.automation.editor.errors.field_message", {
field,
message: translatedMessage(localize, error),
});
};
const translatedMessage = (
localize: LocalizeFunc,
error: ConfigValidationError
): string => {
if (!error.translation_key || error.translation_domain) {
return error.message;
}
const placeholders = Object.fromEntries(
Object.entries(error.translation_placeholders).map(([key, value]) => [
key,
Array.isArray(value) ? value.join(", ") : String(value),
])
);
return (
localize(
`ui.panel.config.automation.editor.errors.validation.${error.translation_key}` as LocalizeKeys,
placeholders
) || error.message
);
};
export const fieldErrors = (
localize: LocalizeFunc,
errors: ConfigValidationError[],
path: ConfigPath
): Record<string, string> => {
const fields: Record<string, string> = {};
errors.forEach((error) => {
const field = errorField(error, path);
if (field !== undefined && !(field in fields)) {
fields[field] = errorMessage(localize, error);
}
});
return fields;
};
/** The field of the config at `path` an error is about, if any. */
export const errorField = (
error: ConfigValidationError,
path: ConfigPath
): string | undefined =>
error.path.length > path.length && pathStartsWith(error.path, path)
? String(error.path[path.length])
: undefined;
export const errorText = (
localize: LocalizeFunc,
error: ConfigValidationError,
path: ConfigPath = []
): string => {
const relative = pathStartsWith(error.path, path)
? error.path.slice(path.length)
: error.path;
const message = errorMessage(localize, error);
return relative.length ? `${formatPath(relative)}: ${message}` : message;
};
export const errorsEqual = (
a: ConfigValidationError[],
b: ConfigValidationError[]
): boolean =>
a.length === b.length &&
a.every(
(error, index) =>
error.message === b[index].message &&
error.code === b[index].code &&
pathEquals(error.path, b[index].path)
);
const childAt = (value: unknown, segment: string | number): unknown => {
if (typeof value !== "object" || value === null) {
return undefined;
}
// A block written as a single item is its first row, see `configErrorPath`
if (segment === 0 && isConfigObject(value) && !("0" in value)) {
return value;
}
return (value as Record<string | number, unknown>)[segment];
};
const valueAt = (config: unknown, path: ConfigPath): unknown =>
path.reduce<unknown>(childAt, config);
const BLOCK_KEYS = new Set([
"triggers",
"conditions",
"actions",
"sequence",
"if",
"then",
"else",
"choose",
"default",
"parallel",
"while",
"until",
"and",
"or",
"not",
"wait_for_trigger",
]);
/**
* Core reports errors of a block written as a single item, like
* `default: { delay: … }`, without a list index, but the editor shows the
* item as the first row of the block.
*/
export const configErrorPath = (
config: unknown,
path: ConfigPath
): ConfigPath => {
const result: ConfigPath = [];
let value = config;
for (const [index, segment] of path.entries()) {
result.push(segment);
value = childAt(value, segment);
if (typeof segment !== "string") {
continue;
}
if (BLOCK_KEYS.has(segment)) {
if (isConfigObject(value) && typeof path[index + 1] === "string") {
result.push(0);
}
} else if (segment !== "repeat") {
// Keys inside fields like `data` are not blocks
return [...result, ...path.slice(index + 1)];
}
}
return result;
};
export const mapErrorsToConfig = (
config: unknown,
errors: ConfigValidationError[]
): ConfigValidationError[] =>
errors.map((error) => ({
...error,
path: configErrorPath(config, error.path),
}));
// Rows sit at list items that are objects, not at entries of value lists
// like `entity_id`
const errorItemPath = (config: unknown, path: ConfigPath): ConfigPath => {
let value = config;
let end = 0;
path.forEach((segment, index) => {
value = childAt(value, segment);
if (typeof segment === "number" && isConfigObject(value)) {
end = index + 1;
}
});
return path.slice(0, end);
};
/** A config item with an error, to recognize it after edits. */
export interface KnownErrorItem {
path: ConfigPath;
item?: object;
content?: string;
}
const knownItemAt = (config: unknown, path: ConfigPath): KnownErrorItem => {
const item = valueAt(config, path);
return isConfigObject(item)
? { path, item, content: JSON.stringify(item) }
: { path };
};
export const knownErrorItems = (
config: unknown,
errors: ConfigValidationError[]
): KnownErrorItem[] => {
const known: KnownErrorItem[] = [];
errors.forEach((error) => {
const path = errorItemPath(config, error.path);
if (!known.some((entry) => pathEquals(entry.path, path))) {
known.push(knownItemAt(config, path));
}
});
return known;
};
interface ConfigItems {
paths: Map<object, ConfigPath>;
contents: Map<string, ConfigPath[]>;
}
// The list entries that are objects, the items rows show
const configItems = (config: unknown): ConfigItems => {
const items: ConfigItems = { paths: new Map(), contents: new Map() };
const walk = (value: unknown, path: ConfigPath) => {
if (typeof value !== "object" || value === null) {
return;
}
if (typeof path[path.length - 1] === "number" && isConfigObject(value)) {
items.paths.set(value, path);
const content = JSON.stringify(value);
items.contents.set(content, [
...(items.contents.get(content) ?? []),
path,
]);
}
Object.entries(value).forEach(([key, child]) => {
if (Array.isArray(value)) {
walk(child, [...path, Number(key)]);
return;
}
// A block written as a single item is its first row
walk(
child,
BLOCK_KEYS.has(key) && isConfigObject(child)
? [...path, key, 0]
: [...path, key]
);
});
};
walk(config, []);
return items;
};
const followItem = (
entry: KnownErrorItem,
previous: ConfigItems,
current: ConfigItems,
config: unknown
): KnownErrorItem | undefined => {
// Unchanged or moved
const path = entry.item && current.paths.get(entry.item);
if (path) {
return { ...entry, path };
}
// Moved after the YAML was parsed again
const samePaths = entry.content
? current.contents.get(entry.content)
: undefined;
if (samePaths?.length === 1) {
return knownItemAt(config, samePaths[0]);
}
// Identical items, e.g. two copies of a row, keep their place
if (samePaths?.some((other) => pathEquals(other, entry.path))) {
return knownItemAt(config, entry.path);
}
const now = valueAt(config, entry.path);
if (!isConfigObject(now)) {
return undefined;
}
// An item that was already there took the place, e.g. after a delete
const beforePaths = previous.paths.has(now)
? [previous.paths.get(now)!]
: (previous.contents.get(JSON.stringify(now)) ?? []);
if (
beforePaths.length &&
!beforePaths.some((other) => pathEquals(other, entry.path))
) {
return undefined;
}
// Edited in place
return knownItemAt(config, entry.path);
};
/** Follows known items from `previous` to `config` through moves and edits. */
export const followKnownErrorItems = (
known: KnownErrorItem[],
previous: unknown,
config: unknown
): KnownErrorItem[] => {
const previousItems = configItems(previous);
const currentItems = configItems(config);
return known
.map((entry) => followItem(entry, previousItems, currentItems, config))
.filter((entry): entry is KnownErrorItem => entry !== undefined);
};
/**
* Moves errors of `previous` to where their items are in `config`. Errors of
* items that are gone are dropped.
*/
export const followErrors = (
errors: ConfigValidationError[],
previous: unknown,
config: unknown
): ConfigValidationError[] => {
const previousItems = configItems(previous);
const currentItems = configItems(config);
return errors.flatMap((error) => {
const path = errorItemPath(previous, error.path);
const moved = followItem(
knownItemAt(previous, path),
previousItems,
currentItems,
config
);
return moved
? [{ ...error, path: [...moved.path, ...error.path.slice(path.length)] }]
: [];
});
};
export const errorsOnKnownItems = (
known: KnownErrorItem[],
config: unknown,
errors: ConfigValidationError[]
): ConfigValidationError[] =>
errors.filter((error) => {
const path = errorItemPath(config, error.path);
return known.some((entry) => pathEquals(entry.path, path));
});
export const targetErrorText = (
localize: LocalizeFunc,
error: ConfigValidationError
): string =>
localize(
error.code === "required"
? "ui.panel.config.automation.editor.errors.target_required"
: "ui.panel.config.automation.editor.errors.target_invalid"
);
export const deviceErrorText = (
localize: LocalizeFunc,
error: ConfigValidationError
): string =>
error.code === "required"
? localize("ui.panel.config.automation.editor.errors.device_required")
: errorMessage(localize, error);
export const deviceAutomationErrorText = (
localize: LocalizeFunc,
kind: "triggers" | "conditions" | "actions",
error: ConfigValidationError
): string =>
error.code === "required"
? localize(`ui.panel.config.devices.automation.${kind}.required`)
: errorMessage(localize, error);
@@ -0,0 +1,257 @@
import { createContext } from "@lit/context";
import {
consumeContext,
ContextController,
} from "../../../common/decorators/consume";
import {
pathEquals,
pathStartsWith,
type ConfigPath,
} from "../../../common/util/config-path";
import type { ConfigValidationError } from "../../../data/config";
import { internationalizationContext } from "../../../data/context";
import type { HomeAssistantInternationalization } from "../../../types";
import {
automationErrorsContext,
errorField,
errorMessage,
errorsEqual,
fieldErrors,
NO_ERRORS,
ownedErrors,
} from "./automation-errors";
import {
automationPathContext,
automationRowRegistryContext,
type AutomationRowRegistry,
} from "./automation-path";
const fieldsEqual = (a: Record<string, string>, b: Record<string, string>) => {
const keys = Object.keys(a);
return (
keys.length === Object.keys(b).length &&
keys.every((key) => a[key] === b[key])
);
};
/**
* @summary The fields whose errors an editor shows next to the field, so
* the sidebar doesn't list them again.
*/
export class InlineErrorFields {
private _fields = new Map<object, ConfigPath[]>();
constructor(private readonly _onChange: () => void) {}
/** `fields` are paths relative to the row. */
public set(owner: object, fields: ConfigPath[]) {
this._fields.set(owner, fields);
this._onChange();
}
public delete(owner: object) {
if (this._fields.delete(owner)) {
this._onChange();
}
}
/** Whether an error at `path`, relative to the row, is shown inline. */
public has(path: ConfigPath): boolean {
return [...this._fields.values()].some((fields) =>
fields.some((field) => pathStartsWith(path, field))
);
}
}
export const automationInlineErrorFieldsContext =
createContext<InlineErrorFields>("automation-inline-error-fields");
interface AutomationFieldErrorsOptions {
/** Fields the host shows the error of, see `InlineErrorFields`. */
inlineFields?: string[];
/** The key below the path whose fields the host edits, like `repeat`. */
key?: string;
}
/**
* @summary Validation errors of the config at the host's path.
*
* Consumes the errors and the path of the closest ancestor and updates the
* host when the errors it exposes change.
*/
export class AutomationFieldErrorsController extends ContextController {
public fields: Record<string, string> = {};
/** Errors that belong to the row at exactly the path, see `errorOwner`. */
public rowErrors: ConfigValidationError[] = NO_ERRORS;
public path: ConfigPath = [];
@consumeContext({ context: internationalizationContext, subscribe: true })
private _i18n?: HomeAssistantInternationalization;
@consumeContext({ context: automationErrorsContext, subscribe: true })
private _errors: ConfigValidationError[] = NO_ERRORS;
@consumeContext({ context: automationPathContext, subscribe: true })
private _path: ConfigPath = [];
@consumeContext({ context: automationRowRegistryContext })
private _registry?: AutomationRowRegistry;
@consumeContext({ context: automationInlineErrorFieldsContext })
private _inlineErrorFields?: InlineErrorFields;
private _inlineFields?: string[];
private readonly _key: ConfigPath;
private _claimedIn?: InlineErrorFields;
constructor(
host: ConstructorParameters<typeof ContextController>[0],
options: AutomationFieldErrorsOptions = {}
) {
super(host);
this._inlineFields = options.inlineFields;
this._key = options.key ? [options.key] : [];
}
/** Changes the fields the host shows the error of, like when it hides some. */
public set inlineFields(fields: string[]) {
if (
this._inlineFields?.length === fields.length &&
this._inlineFields.every((field, index) => field === fields[index])
) {
return;
}
this._inlineFields = fields;
this._claimedIn?.set(this, this._claims(fields));
}
private _claims(fields: string[]): ConfigPath[] {
return fields.map((field) => [...this._key, field]);
}
private _nestedFieldErrors = new Map<string, Record<string, string>>();
/** First error message of each key inside a field, keyed by the key. */
public nestedFieldErrors(field: string): Record<string, string> {
const errors = this._fieldErrors([...this._path, field]);
const previous = this._nestedFieldErrors.get(field);
// The same object while nothing changed, so the host's child doesn't update
if (previous && fieldsEqual(previous, errors)) {
return previous;
}
this._nestedFieldErrors.set(field, errors);
return errors;
}
/** The error of a field as a whole, not of something inside it. */
public ownFieldError(field: string): ConfigValidationError | undefined {
return this._errors.find((error) =>
pathEquals(error.path, [...this._path, field])
);
}
/** The first error of a field the host edits. */
public fieldError(field: string): ConfigValidationError | undefined {
const path = [...this._path, ...this._key];
return this._errors.find((error) => errorField(error, path) === field);
}
/** The errors at or inside `path`, relative to the host's path. */
public errorsAt(path: ConfigPath): ConfigValidationError[] {
const absolute = [...this._path, ...path];
return this._errors.filter((error) => pathStartsWith(error.path, absolute));
}
private _fieldErrors(path: ConfigPath): Record<string, string> {
return this._errors.length && this._i18n
? fieldErrors(this._i18n.localize, this._errors, path)
: {};
}
private _formErrorLabel?: unknown;
private _formError?: (message: string, schema: { name: string }) => string;
/**
* An ha-form `computeError` that names the field in its error, like
* "Entity is required.", as the error is shown above the field.
*/
public formError<S extends { name: string }>(
computeLabel: (schema: S) => string,
/** The error of a form field, for forms that don't use the config keys */
errorOf: (field: string) => ConfigValidationError | undefined = (field) =>
this.fieldError(field)
): (message: string, schema: S) => string {
if (!this._formError || this._formErrorLabel !== computeLabel) {
this._formErrorLabel = computeLabel;
this._formError = (message, schema) => {
const error = schema.name ? errorOf(schema.name) : undefined;
const label = error && computeLabel(schema as S);
return error && label && this._i18n
? errorMessage(this._i18n.localize, error, label)
: message;
};
}
return this._formError;
}
private _unsubscribeRegistry?: () => void;
public hostConnected() {
this._unsubscribeRegistry ??= this._registry?.subscribe(() => this._sync());
this._claimInlineFields();
this._sync();
}
public hostDisconnected() {
this._unsubscribeRegistry?.();
this._unsubscribeRegistry = undefined;
this._claimedIn?.delete(this);
this._claimedIn = undefined;
}
protected contextUpdated() {
this._claimInlineFields();
this._sync();
}
private _claimInlineFields() {
if (
!this._inlineFields ||
!this._inlineErrorFields ||
this._claimedIn === this._inlineErrorFields
) {
return;
}
this._claimedIn?.delete(this);
this._inlineErrorFields.set(this, this._claims(this._inlineFields));
this._claimedIn = this._inlineErrorFields;
}
private _sync() {
const fields = this._fieldErrors([...this._path, ...this._key]);
const row =
this._errors.length && this._path.length
? this._registry?.rowAt(this._path)
: undefined;
const rowErrors =
row && this._registry
? ownedErrors(this._registry, this._errors, row)
: NO_ERRORS;
if (
this.path === this._path &&
fieldsEqual(fields, this.fields) &&
errorsEqual(rowErrors, this.rowErrors)
) {
return;
}
this.path = this._path;
this.fields = fields;
this.rowErrors = rowErrors;
this.host.requestUpdate();
}
}
@@ -9,6 +9,13 @@ import {
stringifyPath,
type ConfigPath,
} from "../../../common/util/config-path";
import type { ConfigValidationError } from "../../../data/config";
import {
automationErrorsContext,
errorsEqual,
NO_ERRORS,
ownedErrors,
} from "./automation-errors";
export const automationPathContext =
createContext<ConfigPath>("automation-path");
@@ -34,14 +41,19 @@ export class AutomationRowRegistry {
{ path: ConfigPath; rows: AutomationPathRow[] }
>();
private _listeners = new Set<() => void>();
private _notifyScheduled = false;
public register(path: ConfigPath, row: AutomationPathRow) {
const key = stringifyPath(path);
const entry = this._rows.get(key);
if (!entry) {
this._rows.set(key, { path, rows: [row] });
return;
} else {
entry.rows = [...entry.rows.filter((claimed) => claimed !== row), row];
}
entry.rows = [...entry.rows.filter((claimed) => claimed !== row), row];
this._changed();
}
public unregister(path: ConfigPath, row: AutomationPathRow) {
@@ -54,6 +66,33 @@ export class AutomationRowRegistry {
if (!entry.rows.length) {
this._rows.delete(key);
}
this._changed();
}
/**
* Calls `listener` after rows were registered or unregistered, once for all
* changes made in the same task. Returns the function to unsubscribe.
*/
public subscribe(listener: () => void): () => void {
this._listeners.add(listener);
return () => {
this._listeners.delete(listener);
};
}
private _changed() {
if (this._notifyScheduled || !this._listeners.size) {
return;
}
this._notifyScheduled = true;
queueMicrotask(() => {
this._notifyScheduled = false;
this._listeners.forEach((listener) => listener());
});
}
public rowAt(path: ConfigPath): AutomationPathRow | undefined {
return owner(this._rows.get(stringifyPath(path))?.rows);
}
public pathOf(row: AutomationPathRow): ConfigPath | undefined {
@@ -61,6 +100,11 @@ export class AutomationRowRegistry {
?.path;
}
public selectedPath(): ConfigPath | undefined {
return [...this._rows.values()].find((entry) => owner(entry.rows)?.selected)
?.path;
}
/** The rows containing `path`, outermost first. */
public rowsAlong(path: ConfigPath): AutomationPathRow[] {
return path
@@ -83,11 +127,19 @@ interface AutomationPathControllerOptions {
/**
* Consumes the path of the closest ancestor and provides it extended by the
* host's own segment to its descendants.
* host's own segment to its descendants. For a row, also finds the validation
* errors the row owns and updates the host when they change.
*/
export class AutomationPathController extends ContextController {
public path: ConfigPath = [];
public errors: ConfigValidationError[] = NO_ERRORS;
@consumeContext({ context: automationErrorsContext, subscribe: true })
private _configErrors: ConfigValidationError[] = NO_ERRORS;
private _unsubscribeRegistry?: () => void;
@consumeContext({ context: automationPathContext, subscribe: true })
private _parentPath: ConfigPath = [];
@@ -124,6 +176,12 @@ export class AutomationPathController extends ContextController {
public hostConnected() {
// A row moved by a drag reconnects without an update
this._sync();
if (this._options.row && this._registry && !this._unsubscribeRegistry) {
// Another row on the path of an error can take it over or give it back
this._unsubscribeRegistry = this._registry.subscribe(() =>
this._syncErrors()
);
}
}
private _sync() {
@@ -133,12 +191,26 @@ export class AutomationPathController extends ContextController {
this._provider.setValue(path);
}
this._syncRegistration();
this._syncErrors();
}
public hostDisconnected() {
this._unsubscribeRegistry?.();
this._unsubscribeRegistry = undefined;
this._unregister();
}
private _syncErrors() {
const errors =
this._registeredRow && this._registry && this._configErrors.length
? ownedErrors(this._registry, this._configErrors, this._registeredRow)
: NO_ERRORS;
if (!errorsEqual(errors, this.errors)) {
this.errors = errors;
this.host.requestUpdate();
}
}
private _syncRegistration() {
if (!this._registry || !this._options.row) {
return;
@@ -97,6 +97,7 @@ import "./types/ha-automation-condition-zone";
import { renderCtrlOrCmd } from "../../../../common/keyboard/ctrl-or-cmd";
import { scrollRowIntoView } from "../scroll-row-into-view";
import { AutomationPathController } from "../automation-path";
import { renderRowErrorIcon } from "../automation-error-templates";
export interface ConditionElement extends LitElement {
condition: Condition;
@@ -262,6 +263,12 @@ export default class HaAutomationConditionRow extends LitElement {
)}
</ha-automation-row-event-chip>
${renderRowErrorIcon(
this.hass.localize,
this.pathController.errors,
this.pathController.path,
this.hass.localize("ui.panel.config.automation.editor.errors.label")
)}
<slot name="icons" slot="icons"></slot>
<ha-dropdown
@@ -529,6 +536,7 @@ export default class HaAutomationConditionRow extends LitElement {
this.condition.condition
)}
.sortSelected=${this.sortSelected}
.error=${this.pathController.errors.length > 0}
.dim=${this._testing}
@click=${this._toggleSidebar}
@toggle-collapsed=${this._toggleCollapse}
@@ -27,9 +27,18 @@ import {
} from "../../../../../data/device/device_registry";
import type { EntityRegistryEntry } from "../../../../../data/entity/entity_registry";
import type { HomeAssistant } from "../../../../../types";
import {
deviceAutomationErrorText,
deviceErrorText,
} from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-condition-device")
export class HaDeviceCondition extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["device_id", "domain"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Object }) public condition!: DeviceCondition;
@@ -132,12 +141,20 @@ export class HaDeviceCondition extends LitElement {
}
protected render() {
const deviceError = this._fieldErrors.fieldError("device_id");
const automationError = this._fieldErrors.fieldError("domain");
const deviceId = this._deviceId || this.condition.device_id;
return html`
<ha-device-picker
.value=${deviceId}
.replacementDeviceIds=${this._replacementDeviceIds}
.invalid=${!!deviceError}
.errorMessage=${
deviceError
? deviceErrorText(this.hass.localize, deviceError)
: undefined
}
@value-changed=${this._devicePicked}
.disabled=${this.disabled}
.label=${this.hass.localize(
@@ -145,6 +162,16 @@ export class HaDeviceCondition extends LitElement {
)}
></ha-device-picker>
<ha-device-condition-picker
.invalid=${!!automationError}
.errorMessage=${
automationError
? deviceAutomationErrorText(
this.hass.localize,
"conditions",
automationError
)
: undefined
}
.value=${this.condition}
.deviceId=${deviceId}
@value-changed=${this._deviceConditionPicked}
@@ -19,6 +19,7 @@ import type { SchemaUnion } from "../../../../../components/ha-form/types";
import type { NumericStateCondition } from "../../../../../data/automation";
import { NON_NUMERIC_ATTRIBUTES } from "../../../../../data/entity/entity_attributes";
import type { HomeAssistant } from "../../../../../types";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const numericStateConditionStruct = object({
alias: optional(string()),
@@ -34,6 +35,16 @@ const numericStateConditionStruct = object({
@customElement("ha-automation-condition-numeric_state")
export default class HaNumericStateCondition extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: [
"entity_id",
"attribute",
"above",
"below",
"value_template",
],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: NumericStateCondition;
@@ -227,6 +238,8 @@ export default class HaNumericStateCondition extends LitElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${schema}
@@ -34,6 +34,9 @@ import {
} from "../../../../../data/target";
import type { HomeAssistant } from "../../../../../types";
import { documentationUrl } from "../../../../../util/documentation-url";
import "../../../../../components/ha-input-helper-text";
import { targetErrorText } from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import { targetExpandGroupContext } from "../../../../../components/target-picker/target-expand-group-context";
// Mirrors `MAX_HISTORY_PRIMING_LOOKBACK` in homeassistant/helpers/condition.py:
@@ -53,6 +56,10 @@ export class HaPlatformCondition extends LitElement {
@provide({ context: targetExpandGroupContext })
protected _targetExpandGroup = false;
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["target"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: PlatformCondition;
@@ -234,6 +241,7 @@ export class HaPlatformCondition extends LitElement {
></ha-selector>`
: nothing
}
${this._renderTargetError()}
${
shouldRenderDataYaml
? html`<ha-yaml-editor
@@ -258,6 +266,15 @@ export class HaPlatformCondition extends LitElement {
`;
}
private _renderTargetError() {
const error = this._fieldErrors.fieldError("target");
return error
? html`<ha-input-helper-text class="target-error">
${targetErrorText(this.hass.localize, error)}
</ha-input-helper-text>`
: nothing;
}
private _targetSelector = memoizeOne(
(targetSelector: TargetSelector["target"] | null | undefined) =>
targetSelector ? { target: { ...targetSelector } } : { target: {} }
@@ -681,6 +698,10 @@ export class HaPlatformCondition extends LitElement {
1px solid var(--divider-color)
);
}
.target-error {
color: var(--ha-color-on-danger-quiet);
padding-bottom: var(--ha-space-2);
}
ha-yaml-editor {
padding: var(--ha-space-4) 0;
}
@@ -17,6 +17,7 @@ import { ensureArray } from "../../../../../common/array/ensure-array";
import { createDurationData } from "../../../../../common/datetime/create_duration_data";
import { fireEvent } from "../../../../../common/dom/fire_event";
import "../../../../../components/ha-form/ha-form";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import type { StateCondition } from "../../../../../data/automation";
import { STATE_CONDITION_HIDDEN_ATTRIBUTES } from "../../../../../data/entity/entity_attributes";
@@ -71,6 +72,10 @@ const SCHEMA = memoizeOne(
@customElement("ha-automation-condition-state")
export class HaStateCondition extends LitElement implements ConditionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["entity_id", "attribute", "state", "for"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: StateCondition;
@@ -118,6 +123,8 @@ export class HaStateCondition extends LitElement implements ConditionElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${SCHEMA(hasAttribute)}
@@ -8,14 +8,25 @@ import type { HaSelectSelectEvent } from "../../../../../components/ha-select";
import type { SunCondition } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import type { ConditionElement } from "../ha-automation-condition-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
type FormType = "before" | "after" | "between";
const BEFORE_DEFAULT = "sunrise";
const AFTER_DEFAULT = "sunset";
const FORM_FIELDS: Record<FormType, string[]> = {
before: ["before", "before_offset"],
after: ["after", "after_offset"],
between: ["after", "after_offset", "before", "before_offset"],
};
@customElement("ha-automation-condition-sun")
export class HaSunCondition extends LitElement implements ConditionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: FORM_FIELDS.before,
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: SunCondition;
@@ -105,6 +116,10 @@ export class HaSunCondition extends LitElement implements ConditionElement {
] as const
);
protected willUpdate() {
this._fieldErrors.inlineFields = FORM_FIELDS[this._formType];
}
protected render() {
const schema = this._schema(this.hass.localize, this._formType);
return html`
@@ -137,6 +152,8 @@ export class HaSunCondition extends LitElement implements ConditionElement {
>
</ha-select>
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${schema}
.data=${this.condition}
.hass=${this.hass}
@@ -5,6 +5,7 @@ import type { HomeAssistant } from "../../../../../types";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import "../../../../../components/ha-form/ha-form";
import { fireEvent } from "../../../../../common/dom/fire_event";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const SCHEMA = [
{ name: "value_template", required: true, selector: { template: {} } },
@@ -12,6 +13,10 @@ const SCHEMA = [
@customElement("ha-automation-condition-template")
export class HaTemplateCondition extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["value_template"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: TemplateCondition;
@@ -25,6 +30,8 @@ export class HaTemplateCondition extends LitElement {
protected render() {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${this.condition}
.schema=${SCHEMA}
@@ -14,9 +14,14 @@ import type { TimeCondition } from "../../../../../data/automation";
import type { FrontendLocaleData } from "../../../../../data/translation";
import type { HomeAssistant } from "../../../../../types";
import type { ConditionElement } from "../ha-automation-condition-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-condition-time")
export class HaTimeCondition extends LitElement implements ConditionElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["after", "before", "weekday"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: TimeCondition;
@@ -150,6 +155,8 @@ export class HaTimeCondition extends LitElement implements ConditionElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${schema}
@@ -56,7 +56,6 @@ import {
triggerAutomationActions,
} from "../../../data/automation";
import { substituteBlueprint } from "../../../data/blueprint";
import { validateConfig } from "../../../data/config";
import { UNAVAILABLE } from "../../../data/entity/entity";
import {
type EntityRegistryEntry,
@@ -71,7 +70,7 @@ import "../../../layouts/hass-subpage";
import { KeyboardShortcutMixin } from "../../../mixins/keyboard-shortcut-mixin";
import { PreventUnsavedMixin } from "../../../mixins/prevent-unsaved-mixin";
import { haStyle } from "../../../resources/styles";
import type { Entries, ValueChangedEvent } from "../../../types";
import type { ValueChangedEvent } from "../../../types";
import { isMac } from "../../../util/is_mac";
import { showEditorToast } from "./editor-toast";
import { showAssignCategoryDialog } from "../category/show-dialog-assign-category";
@@ -168,7 +167,14 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
const { id, ...rest } = normalizeAutomationConfig(config, report);
return { id, ...rest };
},
checkValidation: () => this._checkValidation(),
validationSections: (config) =>
"use_blueprint" in config
? {}
: {
triggers: config.triggers,
conditions: config.conditions,
actions: config.actions,
},
};
private _undoRedoController = new UndoRedoController<AutomationConfig>(this, {
@@ -510,16 +516,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
@value-changed=${this._valueChanged}
@save-automation=${this._handleSaveAutomation}
>
${
this.errors
? html`<ha-alert
alert-type="error"
slot="alerts"
>
${this.errors}
</ha-alert>`
: nothing
}
${this.renderConfigErrorsAlert("alerts")}
</blueprint-automation-editor>
`
: html`
@@ -531,6 +528,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
.config=${this.config}
.disabled=${this.readOnly}
.saving=${this.saving}
.configErrors=${this.configErrors}
@value-changed=${this._valueChanged}
@save-automation=${this._handleSaveAutomation}
@editor-save=${this._handleSaveAutomation}
@@ -539,26 +537,17 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
<div class="alert-wrapper" slot="alerts">
${this._renderDeprecatedMigratedAlert()}
${
this.errors || stateObj?.state === UNAVAILABLE
stateObj?.state === UNAVAILABLE
? html`<ha-alert
alert-type="error"
.title=${
stateObj?.state === UNAVAILABLE
? this.hass.localize(
"ui.panel.config.automation.editor.unavailable"
)
: undefined
}
.title=${this.hass.localize(
"ui.panel.config.automation.editor.unavailable"
)}
>
${this.errors || this.validationErrors}
${
stateObj?.state === UNAVAILABLE
? html`<ha-svg-icon
slot="icon"
.path=${mdiRobotConfused}
></ha-svg-icon>`
: nothing
}
<ha-svg-icon
slot="icon"
.path=${mdiRobotConfused}
></ha-svg-icon>
</ha-alert>`
: nothing
}
@@ -637,6 +626,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
`
: this.mode === "yaml"
? html`${this._renderDeprecatedMigratedAlert()}
${this.renderConfigErrorsAlert()}
${
stateObj?.state === "off"
? html`
@@ -756,7 +746,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
entityRegistryUpdate: this.entityRegistryUpdate,
}
);
this._checkValidation();
this.checkValidation();
});
this.currentEntityId = this.entityId;
this.readOnly = true;
@@ -784,32 +774,6 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
this.currentEntityId = automation?.entity_id;
}
private async _checkValidation() {
this.validationErrors = undefined;
if (!this.currentEntityId || !this.config) {
return;
}
const stateObj = this.hass.states[this.currentEntityId];
if (stateObj?.state !== UNAVAILABLE) {
return;
}
const validation = await validateConfig(this.hass, {
triggers: this.config.triggers,
conditions: this.config.conditions,
actions: this.config.actions,
});
this.validationErrors = (
Object.entries(validation) as Entries<typeof validation>
).map(([key, value]) =>
value.valid
? ""
: html`${this.hass.localize(
`ui.panel.config.automation.editor.${key}.name`
)}:
${value.error}<br />`
);
}
private _valueChanged(ev: ValueChangedEvent<AutomationConfig>) {
ev.stopPropagation();
const config = ev.detail.value;
@@ -839,7 +803,6 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
config: this.config,
entityRegistryUpdate: this.entityRegistryUpdate,
});
this.errors = undefined;
}
private _showInfo() {
@@ -929,7 +892,6 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
config: this.config!,
entityRegistryUpdate: this.entityRegistryUpdate,
});
this.errors = undefined;
}
protected async confirmUnsavedChanged(addHistory = true): Promise<boolean> {
@@ -1010,9 +972,8 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
this._yamlEditor?.setValue(this.config);
}
this.readOnly = true;
this.errors = undefined;
} catch (err: any) {
this.errors = err.message;
showEditorToast(this, { message: err.message });
}
}
@@ -1125,7 +1086,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
private async _saveAutomation(id): Promise<void> {
this.saving = true;
this.validationErrors = undefined;
const config = this.config!;
let entityRegPromise: Promise<EntityRegistryEntry> | undefined;
if (this.entityRegistryUpdate !== undefined && !this.currentEntityId) {
@@ -1136,7 +1097,7 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
}
try {
await saveAutomationConfig(this.hass, id, this.config!);
await saveAutomationConfig(this.hass, id, config);
if (this.entityRegistryUpdate !== undefined) {
let entityId = this.currentEntityId;
@@ -1183,11 +1144,9 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
this._markDirtyStateClean();
this.deprecatedConfigMigrated = false;
} catch (errors: any) {
this.errors = errors.body?.message || errors.error || errors.body;
showEditorToast(this, {
message: errors.body?.message || errors.error || errors.body,
});
this.clearConfigErrors();
} catch (errors: unknown) {
this.showSaveErrors(errors, config);
throw errors;
} finally {
this.saving = false;
@@ -5,15 +5,23 @@ import type {
TemplateResult,
} from "lit";
import { css, html } from "lit";
import { property, state } from "lit/decorators";
import { property, query, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { transform } from "../../../common/decorators/transform";
import { goBack, navigate } from "../../../common/navigate";
import { debounce } from "../../../common/util/debounce";
import { afterNextRender } from "../../../common/util/render-status";
import "../../../components/animation/ha-fade-in";
import "../../../components/ha-spinner"; // used by renderLoading() provided to both editors
import type { AutomationMigrationReport } from "../../../data/automation";
import {
parseConfigSaveError,
validateConfigErrors,
type ConfigValidationError,
type ValidationSectionKeys,
} from "../../../data/config";
import { fireRelatedContext, fullEntitiesContext } from "../../../data/context";
import { UNAVAILABLE } from "../../../data/entity/entity";
import type { EntityRegistryEntry } from "../../../data/entity/entity_registry";
import {
showAlertDialog,
@@ -22,7 +30,32 @@ import {
import { showMoreInfoDialog } from "../../../dialogs/more-info/show-ha-more-info-dialog";
import { DirtyStateProviderMixin } from "../../../mixins/dirty-state-provider-mixin";
import type { Constructor, HomeAssistant, Route } from "../../../types";
import { showToast } from "../../../util/toast";
import {
errorMessage,
errorsEqual,
errorsOnKnownItems,
followErrors,
followKnownErrorItems,
knownErrorItems,
mapErrorsToConfig,
NO_ERRORS,
type KnownErrorItem,
} from "./automation-errors";
import { renderErrorsAlert } from "./automation-error-templates";
import type { EntityRegistryUpdate } from "./automation-save-dialog/show-dialog-automation-save";
import { showEditorToast } from "./editor-toast";
const CONFIG_ERRORS_TOAST_ID = "config-errors";
const REVALIDATE_DELAY = 500;
// Core reports errors in the config a blueprint generates at `use_blueprint`
const BLUEPRINT_PATH = ["use_blueprint"];
interface ErrorsEditorElement extends HTMLElement {
revealErrors(): Promise<void>;
}
/** Minimum config shape shared by both AutomationConfig and ScriptConfig. */
interface BaseEditorConfig {
@@ -82,7 +115,11 @@ export const automationScriptEditorStyles: CSSResult = css`
export interface EditorDomainHooks<TConfig> {
fetchFileConfig(hass: HomeAssistant, id: string): Promise<TConfig>;
normalizeConfig(raw: TConfig, report?: AutomationMigrationReport): TConfig;
checkValidation(): Promise<void>;
/** The parts of the config `validate_config` checks, none for blueprints. */
validationSections(
config: TConfig
): Partial<Record<"triggers" | "conditions" | "actions", unknown>>;
validationSectionKeys?: ValidationSectionKeys;
domain: "automation" | "script";
}
@@ -111,8 +148,6 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
@consume({ context: fullEntitiesContext, subscribe: true })
entityRegistry?: EntityRegistryEntry[];
@state() protected errors?: string;
@state() protected yamlErrors?: string;
@state() protected currentEntityId?: string;
@@ -125,7 +160,7 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
@state() protected deprecatedConfigMigrated = false;
@state() protected validationErrors?: (string | TemplateResult)[];
@state() protected configErrors: ConfigValidationError[] = NO_ERRORS;
@state() protected config?: TConfig;
@@ -157,6 +192,14 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
private _relatedContextAreaId?: string;
@query("manual-automation-editor, manual-script-editor")
private _errorsEditor?: ErrorsEditorElement;
// Validation responses of an older run are dropped
private _validationRun = 0;
private _knownErrorItems: KnownErrorItem[] = [];
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
if (
@@ -165,6 +208,218 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
) {
this._setRelatedContext();
}
// Errors set in the same update already belong to the current config
if (
changedProps.has("config") &&
!changedProps.has("configErrors") &&
this.configErrors.length
) {
const previous = changedProps.get("config");
const followed = followErrors(this.configErrors, previous, this.config);
if (!followed.length) {
this.clearConfigErrors();
return;
}
if (!errorsEqual(followed, this.configErrors)) {
this.configErrors = followed;
}
this._knownErrorItems = followKnownErrorItems(
this._knownErrorItems,
previous,
this.config
);
this._revalidate();
}
}
public disconnectedCallback() {
super.disconnectedCallback();
// Pending validations must not touch errors or the toast anymore
this._validationRun++;
this._revalidate.cancel();
this._closeErrorsToast();
}
/** Shows the errors of saving `submitted`, the config sent to core. */
protected async showSaveErrors(err: unknown, submitted: TConfig) {
const { message, errors } = parseConfigSaveError(err);
if (!errors.length) {
this._showSaveFailedToast(message);
return;
}
this._validationRun++;
const submittedErrors = mapErrorsToConfig(submitted, errors);
// Edits made while saving moved or removed some of the items
const changed = submitted !== this.config;
this._setConfigErrors(
this.config,
changed
? followErrors(submittedErrors, submitted, this.config)
: submittedErrors
);
// Shown before revalidating, so a later save that succeeds closes it
this._showSaveFailedToast(
errors.length === 1
? errorMessage(this.hass.localize, errors[0])
: this.hass.localize(
"ui.panel.config.automation.editor.errors.problems_found",
{ count: errors.length }
)
);
if (changed) {
// Followed errors miss items that were renamed and moved, so check
// everything again
await this._validateConfig(false);
}
await this._revealErrors();
}
protected async checkValidation() {
if (!this.currentEntityId || !this.config) {
return;
}
if (this.hass.states[this.currentEntityId]?.state !== UNAVAILABLE) {
return;
}
const config = this.config;
const sections = this.domainHooks.validationSections(config);
if (!Object.keys(sections).length) {
return;
}
const run = ++this._validationRun;
let errors: ConfigValidationError[];
try {
errors = await validateConfigErrors(
this.hass,
sections,
this.domainHooks.validationSectionKeys
);
} catch (_err: unknown) {
// The unavailable alert still shows, only the rows stay unmarked
return;
}
if (run !== this._validationRun || config !== this.config) {
return;
}
this._setConfigErrors(config, mapErrorsToConfig(config, errors));
}
private _setConfigErrors(
config: TConfig | undefined,
errors: ConfigValidationError[]
) {
this.configErrors = errors;
this._knownErrorItems = knownErrorItems(config, errors);
}
private async _revealErrors() {
await this.updateComplete;
if (this.mode === "gui") {
await this._errorsEditor?.revealErrors();
}
}
/** All errors, for the editors that have no rows to show them on. */
protected renderConfigErrorsAlert(slot?: string) {
return renderErrorsAlert(
this.hass.localize,
this.configErrors,
BLUEPRINT_PATH,
slot
);
}
private _showSaveFailedToast(problems: string) {
showEditorToast(this, {
id: CONFIG_ERRORS_TOAST_ID,
message: this.hass.localize(
"ui.panel.config.automation.editor.errors.save_failed",
{ problems }
),
});
}
private _closeErrorsToast() {
// A removed editor can't reach the toast manager by bubbling
const host = this.isConnected
? this
: document.querySelector<HTMLElement>("home-assistant");
if (!host) {
return;
}
showToast(host, {
id: CONFIG_ERRORS_TOAST_ID,
message: "",
duration: 0,
});
}
// Updates the errors of the items that had one, so fixed problems clear
// while editing. New problems elsewhere, and errors outside the validated
// sections like an invalid mode, wait for the next save.
private _revalidate = debounce(() => {
this._validateConfig(true);
}, REVALIDATE_DELAY);
/**
* Validates the sections of the current config. With `onlyKnown`, only
* errors on items that already had one are kept.
*/
private async _validateConfig(onlyKnown: boolean) {
this._revalidate.cancel();
const config = this.config;
if (!config || (onlyKnown && !this.configErrors.length)) {
return;
}
const sections = this.domainHooks.validationSections(config);
// Blueprint inputs can't be validated on their own, so their errors
// only last until the next edit
if (!Object.keys(sections).length) {
this.clearConfigErrors();
return;
}
const sectionKeys = this.domainHooks.validationSectionKeys ?? {};
const run = ++this._validationRun;
let sectionErrors: ConfigValidationError[];
try {
sectionErrors = await validateConfigErrors(
this.hass,
sections,
sectionKeys
);
} catch (_err: unknown) {
return;
}
if (run !== this._validationRun || config !== this.config) {
return;
}
const mapped = mapErrorsToConfig(config, sectionErrors);
const validated = Object.keys(sections).map(
(key) => sectionKeys[key] ?? key
);
const errors = [
...this.configErrors.filter(
(error) => !validated.includes(error.path[0] as string)
),
...(onlyKnown
? errorsOnKnownItems(this._knownErrorItems, config, mapped)
: mapped),
];
if (!errors.length) {
this.clearConfigErrors();
return;
}
this._setConfigErrors(
config,
errorsEqual(errors, this.configErrors) ? this.configErrors : errors
);
}
protected clearConfigErrors() {
this._validationRun++;
this._revalidate.cancel();
this.configErrors = NO_ERRORS;
this._closeErrorsToast();
}
private _setRelatedContext(): void {
@@ -277,6 +532,7 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
protected async loadConfig(id: string) {
const hooks = this.domainHooks;
const domain = hooks.domain;
this.clearConfigErrors();
try {
const config = await hooks.fetchFileConfig(this.hass, id);
if (!this.isConnected) {
@@ -296,7 +552,7 @@ export const AutomationScriptEditorMixin = <TConfig extends BaseEditorConfig>(
entityRegistryUpdate: this.entityRegistryUpdate,
}
);
hooks.checkValidation();
this.checkValidation();
} catch (err: any) {
if (!this.isConnected) {
return;
@@ -1,3 +1,4 @@
import { ContextProvider } from "@lit/context";
import { css, html, LitElement, nothing, type PropertyValues } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { tinykeys } from "tinykeys";
@@ -5,6 +6,7 @@ import { consume } from "../../../common/decorators/consume";
import { fireEvent } from "../../../common/dom/fire_event";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { computeRTL } from "../../../common/util/compute_rtl";
import { pathEquals } from "../../../common/util/config-path";
import "../../../components/ha-snap-bottom-sheet";
import type { HaSnapBottomSheet } from "../../../components/ha-snap-bottom-sheet";
import {
@@ -22,6 +24,11 @@ import { manifestsContext } from "../../../data/context";
import type { DomainManifestLookup } from "../../../data/integration";
import { isTriggerList } from "../../../data/trigger";
import type { HomeAssistant } from "../../../types";
import {
automationPathContext,
automationRowRegistryContext,
type AutomationRowRegistry,
} from "./automation-path";
import "./sidebar/ha-automation-sidebar-action";
import type HaAutomationSidebarAction from "./sidebar/ha-automation-sidebar-action";
import "./sidebar/ha-automation-sidebar-condition";
@@ -61,6 +68,17 @@ export default class HaAutomationSidebar extends LitElement {
@consume({ context: manifestsContext, subscribe: true })
private _manifests?: DomainManifestLookup;
@consume({ context: automationRowRegistryContext })
private _registry?: AutomationRowRegistry;
// Editors in the sidebar are not inside their row, so they get its path here
private readonly _pathProvider = new ContextProvider(this, {
context: automationPathContext,
initialValue: [],
});
private _unsubscribeRegistry?: () => void;
@query("ha-snap-bottom-sheet")
private _bottomSheetElement?: HaSnapBottomSheet;
@@ -83,6 +101,28 @@ export default class HaAutomationSidebar extends LitElement {
private _tinykeysUnsub?: () => void;
public connectedCallback() {
super.connectedCallback();
// A row dragged to another place while it is open changes its path
this._unsubscribeRegistry = this._registry?.subscribe(() =>
this._syncPath()
);
}
protected willUpdate(changedProperties: PropertyValues<this>) {
super.willUpdate(changedProperties);
if (changedProperties.has("config")) {
this._syncPath();
}
}
private _syncPath() {
const path = this.config ? (this._registry?.selectedPath() ?? []) : [];
if (!pathEquals(path, this._pathProvider.value)) {
this._pathProvider.setValue(path);
}
}
protected updated(changedProperties: PropertyValues<this>) {
super.updated(changedProperties);
if (
@@ -105,6 +145,8 @@ export default class HaAutomationSidebar extends LitElement {
disconnectedCallback() {
super.disconnectedCallback();
this._unsubscribeRegistry?.();
this._unsubscribeRegistry = undefined;
this._unregisterResizeHandlers();
this._tinykeysUnsub?.();
}
@@ -2,8 +2,8 @@ import { provide } from "@lit/context";
import { mdiContentSave } from "@mdi/js";
import {
html,
nothing,
type LitElement,
type nothing,
type PropertyValues,
type TemplateResult,
} from "lit";
@@ -16,6 +16,7 @@ import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import { replaceCurrentUrl } from "../../../common/navigate";
import { constructUrlCurrentPath } from "../../../common/url/construct-url";
import { nextRender } from "../../../common/util/render-status";
import {
extractSearchParam,
removeSearchParam,
@@ -24,6 +25,7 @@ import "../../../components/ha-button";
import "../../../components/ha-icon-button";
import "../../../components/ha-markdown";
import type { SidebarConfig } from "../../../data/automation";
import type { ConfigValidationError } from "../../../data/config";
import {
dirtyStateContext,
type DirtyStateContext,
@@ -34,10 +36,18 @@ import type {
ValueChangedEvent,
} from "../../../types";
import { showToast } from "../../../util/toast";
import {
automationErrorsContext,
errorOwner,
NO_ERRORS,
} from "./automation-errors";
import { renderErrorsAlert } from "./automation-error-templates";
import {
AutomationRowRegistry,
automationRowRegistryContext,
type AutomationPathRow,
} from "./automation-path";
import { scrollRowIntoView } from "./scroll-row-into-view";
import "./ha-automation-sidebar";
import type HaAutomationSidebar from "./ha-automation-sidebar";
@@ -90,6 +100,10 @@ export const ManualEditorMixin = <TConfig>(
@provide({ context: automationRowRegistryContext })
protected rowRegistry = new AutomationRowRegistry();
@provide({ context: automationErrorsContext })
@property({ attribute: false })
public configErrors: ConfigValidationError[] = NO_ERRORS;
declare protected collapsableElements?: NodeListOf<
Element & {
expandAll(): void;
@@ -103,16 +117,42 @@ export const ManualEditorMixin = <TConfig>(
throw new Error("Not implemented");
};
private _unsubscribeRows?: () => void;
// Rows register while they render, so errors only count as without a
// row once the rows had a frame to render
@state() private _rowsRendered = false;
public connectedCallback() {
super.connectedCallback();
window.addEventListener("paste", this.handlePaste);
// Which errors have a row changes as rows render
this._unsubscribeRows = this.rowRegistry.subscribe(() => {
if (this.configErrors.length) {
this.requestUpdate();
}
});
}
public disconnectedCallback() {
window.removeEventListener("paste", this.handlePaste);
this._unsubscribeRows?.();
this._unsubscribeRows = undefined;
super.disconnectedCallback();
}
private _renderUnownedErrors() {
if (!this._rowsRendered) {
return nothing;
}
return renderErrorsAlert(
this.hass.localize,
this.configErrors.filter(
(error) => !errorOwner(this.rowRegistry, error)
)
);
}
protected renderContent(): TemplateResult | typeof nothing {
throw new Error("Not implemented");
}
@@ -141,7 +181,7 @@ export const ManualEditorMixin = <TConfig>(
>
<div class="content">
<slot name="alerts"></slot>
${this.renderContent()}
${this._renderUnownedErrors()} ${this.renderContent()}
</div>
<div class="fab-positioner">
<ha-button
@@ -179,6 +219,9 @@ export const ManualEditorMixin = <TConfig>(
protected firstUpdated(changedProps: PropertyValues<this>): void {
super.firstUpdated(changedProps);
nextRender().then(() => {
this._rowsRendered = true;
});
this.style.setProperty(
"--sidebar-dynamic-width",
@@ -303,6 +346,54 @@ export const ManualEditorMixin = <TConfig>(
});
}
/**
* Expands the rows along the path of every error, then scrolls to the
* first one and opens it in the sidebar. Does nothing while a row with an
* error is open, so the user stays where they are.
*/
public async revealErrors() {
await this.updateComplete;
const errorRows = () =>
this.configErrors.map((error) =>
this.rowRegistry.rowsAlong(error.path)
);
const owners = (rows: AutomationPathRow[][]) =>
rows
.map((along) => along[along.length - 1])
.filter((owner) => owner !== undefined);
let rows = errorRows();
if (owners(rows).some((owner) => owner.selected)) {
return;
}
const depthOf = (along: AutomationPathRow[][]) =>
along.reduce((sum, path) => sum + path.length, 0);
// Collapsed rows don't render their children, so expand one level at a
// time until no deeper row shows up
let depth = -1;
while (depthOf(rows) > depth) {
depth = depthOf(rows);
rows.flat().forEach((row) => row.expand());
// eslint-disable-next-line no-await-in-loop
await nextRender();
rows = errorRows();
}
// Errors aren't in config order, so take the topmost row
const first = owners(rows).reduce<AutomationPathRow | undefined>(
(top, row) =>
!top ||
row.getBoundingClientRect().top < top.getBoundingClientRect().top
? row
: top,
undefined
);
if (!first) {
return;
}
first.openSidebar();
await nextRender();
scrollRowIntoView(first);
}
public expandAll() {
this.collapsableElements?.forEach((element) => {
element.expandAll();
@@ -65,6 +65,7 @@ import {
import "../trigger/ha-automation-trigger-references";
import { getUiSupportWarnings, isConfigObject } from "../ui-support";
import { AutomationPathController } from "../automation-path";
import { renderRowErrorIcon } from "../automation-error-templates";
@customElement("ha-automation-option-row")
export default class HaAutomationOptionRow extends LitElement {
@@ -272,6 +273,12 @@ export default class HaAutomationOptionRow extends LitElement {
}
</h3>
${renderRowErrorIcon(
this.hass.localize,
this.pathController.errors,
this.pathController.path,
this.hass.localize("ui.panel.config.automation.editor.errors.label")
)}
<slot name="icons" slot="icons"></slot>
${
@@ -502,6 +509,7 @@ export default class HaAutomationOptionRow extends LitElement {
.collapsed=${this._collapsed}
.selected=${this._selected}
.sortSelected=${this.sortSelected}
.error=${this.pathController.errors.length > 0}
@click=${this._toggleSidebar}
@toggle-collapsed=${this._toggleCollapse}
@delete-row=${this._removeOption}
@@ -1,3 +1,4 @@
import { provide } from "@lit/context";
import { mdiClose, mdiDotsVertical } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query } from "lit/decorators";
@@ -12,6 +13,12 @@ import "../../../../components/ha-icon-button";
import { ScrollableFadeMixin } from "../../../../mixins/scrollable-fade-mixin";
import { haStyleScrollbar } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { renderErrorsAlert } from "../automation-error-templates";
import {
automationInlineErrorFieldsContext,
AutomationFieldErrorsController,
InlineErrorFields,
} from "../automation-field-errors";
import "../ha-automation-editor-warning";
export interface SidebarOverflowMenuEntry {
@@ -44,11 +51,22 @@ export default class HaAutomationSidebarCard extends ScrollableFadeMixin(
@query(".card-content") private _contentElement!: HTMLDivElement;
private readonly _errors = new AutomationFieldErrorsController(this);
@provide({ context: automationInlineErrorFieldsContext })
protected inlineErrorFields = new InlineErrorFields(() =>
this.requestUpdate()
);
protected get scrollableElement(): HTMLElement | null {
return this._contentElement;
}
protected render() {
const errors = this._errors.rowErrors.filter((error) => {
const field = error.path.slice(this._errors.path.length);
return !field.length || !this.inlineErrorFields.has(field);
});
return html`
<ha-card
outlined
@@ -90,6 +108,7 @@ export default class HaAutomationSidebarCard extends ScrollableFadeMixin(
</ha-automation-editor-warning>`
: nothing
}
${renderErrorsAlert(this.hass.localize, errors, this._errors.path)}
<div class="card-content ha-scrollbar">
<slot></slot>
${this.renderScrollableFades(this.isWide)}
@@ -148,6 +167,10 @@ export default class HaAutomationSidebarCard extends ScrollableFadeMixin(
padding-bottom: max(var(--safe-area-inset-bottom, 0px), 32px);
}
.errors-alert {
margin: 0 var(--ha-space-4) var(--ha-space-4);
}
.fade-top {
top: var(--ha-space-17);
}
+12 -1
View File
@@ -116,7 +116,8 @@ export const rowStyles = css`
.note-indicator {
color: var(--ha-color-on-neutral-normal);
}
.note-indicator + ha-tooltip::part(body) {
.note-indicator + ha-tooltip::part(body),
.error-indicator + ha-tooltip::part(body) {
cursor: default;
max-width: 300px;
}
@@ -124,6 +125,11 @@ export const rowStyles = css`
white-space: pre-wrap;
margin: 0;
}
.error-indicator {
color: var(--ha-color-on-danger-quiet);
padding: var(--ha-space-3);
}
`;
export const editorStyles = css`
@@ -280,6 +286,11 @@ export const manualEditorStyles = css`
.header a {
color: var(--secondary-text-color);
}
.errors-alert {
display: block;
margin-bottom: var(--ha-space-2);
}
`;
export const automationRowsStyles = css`
@@ -121,6 +121,7 @@ import "./types/ha-automation-trigger-zone";
import { renderCtrlOrCmd } from "../../../../common/keyboard/ctrl-or-cmd";
import { scrollRowIntoView } from "../scroll-row-into-view";
import { AutomationPathController } from "../automation-path";
import { renderRowErrorIcon } from "../automation-error-templates";
import { targetExpandGroupContext } from "../../../../components/target-picker/target-expand-group-context";
export interface TriggerElement extends LitElement {
@@ -400,6 +401,12 @@ export default class HaAutomationTriggerRow extends LitElement {
)}
</ha-automation-row-event-chip>
${renderRowErrorIcon(
this.hass.localize,
this.pathController.errors,
this.pathController.path,
this.hass.localize("ui.panel.config.automation.editor.errors.label")
)}
<slot name="icons" slot="icons"></slot>
<ha-dropdown
@@ -664,6 +671,7 @@ export default class HaAutomationTriggerRow extends LitElement {
.selected=${this._selected}
.highlight=${this.highlight}
.sortSelected=${this.sortSelected}
.error=${this.pathController.errors.length > 0}
.dim=${this._triggered}
@click=${this._toggleSidebar}
>${
@@ -1211,6 +1219,10 @@ export default class HaAutomationTriggerRow extends LitElement {
};
public expand() {
// Rows that open in the sidebar have nothing to expand
if (this.optionsInSidebar) {
return;
}
this.updateComplete.then(() => {
this.shadowRoot!.querySelector("ha-expansion-panel")!.expanded = true;
});
@@ -8,9 +8,14 @@ import type { TriggerElement } from "../ha-automation-trigger-row";
import "../../../../../components/ha-form/ha-form";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-trigger-calendar")
export class HaCalendarTrigger extends LitElement implements TriggerElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["entity_id", "event", "offset"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: CalendarTrigger;
@@ -65,6 +70,8 @@ export class HaCalendarTrigger extends LitElement implements TriggerElement {
const schema = this._schema(this.hass.localize);
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${schema}
.data=${this.trigger}
.hass=${this.hass}
@@ -29,9 +29,18 @@ import {
} from "../../../../../data/device/device_registry";
import type { EntityRegistryEntry } from "../../../../../data/entity/entity_registry";
import type { HomeAssistant } from "../../../../../types";
import {
deviceAutomationErrorText,
deviceErrorText,
} from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-trigger-device")
export class HaDeviceTrigger extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["device_id", "domain"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Object }) public trigger!: DeviceTrigger;
@@ -136,12 +145,20 @@ export class HaDeviceTrigger extends LitElement {
}
protected render() {
const deviceError = this._fieldErrors.fieldError("device_id");
const automationError = this._fieldErrors.fieldError("domain");
const deviceId = this._deviceId || this.trigger.device_id;
return html`
<ha-device-picker
.value=${deviceId}
.replacementDeviceIds=${this._replacementDeviceIds}
.invalid=${!!deviceError}
.errorMessage=${
deviceError
? deviceErrorText(this.hass.localize, deviceError)
: undefined
}
@value-changed=${this._devicePicked}
.disabled=${this.disabled}
.label=${this.hass.localize(
@@ -149,6 +166,16 @@ export class HaDeviceTrigger extends LitElement {
)}
></ha-device-picker>
<ha-device-trigger-picker
.invalid=${!!automationError}
.errorMessage=${
automationError
? deviceAutomationErrorText(
this.hass.localize,
"triggers",
automationError
)
: undefined
}
.value=${this.trigger}
.deviceId=${deviceId}
@value-changed=${this._deviceTriggerPicked}
@@ -7,9 +7,14 @@ import type { GeoLocationTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-trigger-geo_location")
export class HaGeolocationTrigger extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["source", "zone", "event"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: GeoLocationTrigger;
@@ -55,6 +60,8 @@ export class HaGeolocationTrigger extends LitElement {
protected render() {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${this._schema(this.hass.localize)}
.data=${this.trigger}
.hass=${this.hass}
@@ -7,9 +7,14 @@ import type { HassTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-trigger-homeassistant")
export class HaHassTrigger extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["event"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: HassTrigger;
@@ -51,6 +56,8 @@ export class HaHassTrigger extends LitElement {
protected render() {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${this._schema(this.hass.localize)}
.data=${this.trigger}
.hass=${this.hass}
@@ -4,6 +4,7 @@ import memoizeOne from "memoize-one";
import { ensureArray } from "../../../../../common/array/ensure-array";
import { fireEvent } from "../../../../../common/dom/fire_event";
import "../../../../../components/ha-form/ha-form";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import type { NumericStateTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
@@ -183,6 +184,17 @@ const SCHEMA = [
@customElement("ha-automation-trigger-numeric_state")
export class HaNumericStateTrigger extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: [
"entity_id",
"attribute",
"value_template",
"above",
"below",
"for",
],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: NumericStateTrigger;
@@ -230,6 +242,8 @@ export class HaNumericStateTrigger extends LitElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${SCHEMA}
@@ -10,6 +10,7 @@ import "../../../../../components/ha-icon-button";
import type { PersistentNotificationTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import type { TriggerElement } from "../ha-automation-trigger-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const DEFAULT_UPDATE_TYPES = ["added", "removed"];
const DEFAULT_NOTIFICATION_ID = "";
@@ -19,6 +20,10 @@ export class HaPersistentNotificationTrigger
extends LitElement
implements TriggerElement
{
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["notification_id", "update_type"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false })
@@ -80,6 +85,8 @@ export class HaPersistentNotificationTrigger
const schema = this._schema(this.hass.localize);
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${schema}
.data=${this.trigger}
.hass=${this.hass}
@@ -23,6 +23,9 @@ import {
} from "../../../../../data/trigger";
import type { HomeAssistant } from "../../../../../types";
import { documentationUrl } from "../../../../../util/documentation-url";
import "../../../../../components/ha-input-helper-text";
import { targetErrorText } from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import { targetExpandGroupContext } from "../../../../../components/target-picker/target-expand-group-context";
const showOptionalToggle = (field: TriggerDescription["fields"][string]) =>
@@ -43,6 +46,10 @@ export class HaPlatformTrigger extends LitElement {
@provide({ context: targetExpandGroupContext })
protected _targetExpandGroup = false;
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["target"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: PlatformTrigger;
@@ -226,6 +233,7 @@ export class HaPlatformTrigger extends LitElement {
></ha-selector>`
: nothing
}
${this._renderTargetError()}
${
shouldRenderDataYaml
? html`<ha-yaml-editor
@@ -250,6 +258,15 @@ export class HaPlatformTrigger extends LitElement {
`;
}
private _renderTargetError() {
const error = this._fieldErrors.fieldError("target");
return error
? html`<ha-input-helper-text class="target-error">
${targetErrorText(this.hass.localize, error)}
</ha-input-helper-text>`
: nothing;
}
private _targetSelector = memoizeOne(
(targetSelector: TargetSelector["target"] | null | undefined) =>
targetSelector ? { target: { ...targetSelector } } : { target: {} }
@@ -559,6 +576,10 @@ export class HaPlatformTrigger extends LitElement {
1px solid var(--divider-color)
);
}
.target-error {
color: var(--ha-color-on-danger-quiet);
padding-bottom: var(--ha-space-2);
}
ha-yaml-editor {
padding: var(--ha-space-4) 0;
}
@@ -20,6 +20,7 @@ import { hasTemplate } from "../../../../../common/string/has-template";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import { ANY_STATE_VALUE } from "../../../../../components/entity/const";
import "../../../../../components/ha-form/ha-form";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import type {
HaFormSchema,
SchemaUnion,
@@ -57,6 +58,10 @@ const stateTriggerStruct = assign(
@customElement("ha-automation-trigger-state")
export class HaStateTrigger extends LitElement implements TriggerElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["entity_id", "attribute", "from", "to", "for"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: StateTrigger;
@@ -311,6 +316,8 @@ export class HaStateTrigger extends LitElement implements TriggerElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${schema}
@@ -8,9 +8,14 @@ import type { TriggerElement } from "../ha-automation-trigger-row";
import "../../../../../components/ha-form/ha-form";
import type { LocalizeFunc } from "../../../../../common/translations/localize";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
@customElement("ha-automation-trigger-sun")
export class HaSunTrigger extends LitElement implements TriggerElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["event", "offset"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: SunTrigger;
@@ -55,6 +60,8 @@ export class HaSunTrigger extends LitElement implements TriggerElement {
const schema = this._schema(this.hass.localize);
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.schema=${schema}
.data=${this.trigger}
.hass=${this.hass}
@@ -3,6 +3,7 @@ import { customElement, property } from "lit/decorators";
import type { TemplateTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import "../../../../../components/ha-form/ha-form";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
import { fireEvent } from "../../../../../common/dom/fire_event";
import type { SchemaUnion } from "../../../../../components/ha-form/types";
@@ -25,6 +26,10 @@ const SCHEMA = [
@customElement("ha-automation-trigger-template")
export class HaTemplateTrigger extends LitElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["value_template", "for"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: TemplateTrigger;
@@ -54,6 +59,8 @@ export class HaTemplateTrigger extends LitElement {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.data=${data}
.schema=${SCHEMA}
@@ -30,6 +30,9 @@ import type { FrontendLocaleData } from "../../../../../data/translation";
import type { HomeAssistant } from "../../../../../types";
import { baseTriggerStruct } from "../../structs";
import type { TriggerElement } from "../ha-automation-trigger-row";
import type { ConfigValidationError } from "../../../../../data/config";
import { errorMessage } from "../../automation-errors";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const MODE_TIME = "time";
const MODE_ENTITY = "entity";
@@ -53,6 +56,10 @@ const timeTriggerStruct = assign(
@customElement("ha-automation-trigger-time")
export class HaTimeTrigger extends LitElement implements TriggerElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["at", "weekday"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: TimeTrigger;
@@ -189,6 +196,42 @@ export class HaTimeTrigger extends LitElement implements TriggerElement {
}
);
// The form shows `at` as a time, or as an entity and its offset
private _formFieldError = (
field: string
): ConfigValidationError | undefined => {
if (field === "offset") {
return this._fieldErrors.errorsAt(["at", "offset"])[0];
}
if (field === "time" || field === "entity") {
return this._fieldErrors
.errorsAt(["at"])
.find(
(error) => error.path[this._fieldErrors.path.length + 1] !== "offset"
);
}
return this._fieldErrors.fieldError(field);
};
private _formErrors(mode: typeof MODE_TIME | typeof MODE_ENTITY) {
const { at, ...fields } = this._fieldErrors.fields;
if (at === undefined) {
return this._fieldErrors.fields;
}
const atField = mode === MODE_TIME ? "time" : "entity";
const atError = this._formFieldError(atField);
const offsetError = this._formFieldError("offset");
return {
...fields,
...(atError
? { [atField]: errorMessage(this.hass.localize, atError) }
: {}),
...(offsetError
? { offset: errorMessage(this.hass.localize, offsetError) }
: {}),
};
}
protected render() {
const at = this.trigger.at;
@@ -205,6 +248,11 @@ export class HaTimeTrigger extends LitElement implements TriggerElement {
return html`
<ha-form
.error=${this._formErrors(data.mode)}
.computeError=${this._fieldErrors.formError(
this._computeLabelCallback,
this._formFieldError
)}
.hass=${this.hass}
.data=${data}
.schema=${schema}
@@ -6,6 +6,7 @@ import type { SchemaUnion } from "../../../../../components/ha-form/types";
import type { TimePatternTrigger } from "../../../../../data/automation";
import type { HomeAssistant } from "../../../../../types";
import type { TriggerElement } from "../ha-automation-trigger-row";
import { AutomationFieldErrorsController } from "../../automation-field-errors";
const SCHEMA = [
{ name: "hours", selector: { text: {} } },
@@ -15,6 +16,10 @@ const SCHEMA = [
@customElement("ha-automation-trigger-time_pattern")
export class HaTimePatternTrigger extends LitElement implements TriggerElement {
private readonly _fieldErrors = new AutomationFieldErrorsController(this, {
inlineFields: ["hours", "minutes", "seconds"],
});
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: TimePatternTrigger;
@@ -28,6 +33,8 @@ export class HaTimePatternTrigger extends LitElement implements TriggerElement {
protected render() {
return html`
<ha-form
.error=${this._fieldErrors.fields}
.computeError=${this._fieldErrors.formError(this._computeLabelCallback)}
.hass=${this.hass}
.schema=${SCHEMA}
.data=${this.trigger}
+21 -69
View File
@@ -35,7 +35,6 @@ import "../../../components/ha-svg-icon";
import "../../../components/ha-yaml-editor";
import type { HaYamlEditor } from "../../../components/ha-yaml-editor";
import { substituteBlueprint } from "../../../data/blueprint";
import { validateConfig } from "../../../data/config";
import { UNAVAILABLE } from "../../../data/entity/entity";
import {
type EntityRegistryEntry,
@@ -62,7 +61,6 @@ import { KeyboardShortcutMixin } from "../../../mixins/keyboard-shortcut-mixin";
import { PreventUnsavedMixin } from "../../../mixins/prevent-unsaved-mixin";
import { SubscribeMixin } from "../../../mixins/subscribe-mixin";
import { haStyle } from "../../../resources/styles";
import type { Entries } from "../../../types";
import { isMac } from "../../../util/is_mac";
import { showEditorToast } from "../automation/editor-toast";
import { showAutomationModeDialog } from "../automation/automation-mode-dialog/show-dialog-automation-mode";
@@ -99,7 +97,9 @@ export class HaScriptEditor extends SubscribeMixin(
domain: "script",
fetchFileConfig: fetchScriptFileConfig,
normalizeConfig: normalizeScriptConfig,
checkValidation: () => this._checkValidation(),
validationSections: (config) =>
"use_blueprint" in config ? {} : { actions: config.sequence },
validationSectionKeys: { actions: "sequence" },
};
private _undoRedoController = new UndoRedoController<ScriptConfig>(this, {
@@ -429,16 +429,7 @@ export class HaScriptEditor extends SubscribeMixin(
@value-changed=${this._valueChanged}
@save-script=${this._handleSaveScript}
>
${
this.errors
? html`<ha-alert
alert-type="error"
slot="alerts"
>
${this.errors}
</ha-alert>`
: nothing
}
${this.renderConfigErrorsAlert("alerts")}
</blueprint-script-editor>
`
: html`
@@ -449,6 +440,7 @@ export class HaScriptEditor extends SubscribeMixin(
.config=${this.config}
.disabled=${this.readOnly}
.saving=${this.saving}
.configErrors=${this.configErrors}
@value-changed=${this._valueChanged}
@editor-save=${this._handleSaveScript}
@save-script=${this._handleSaveScript}
@@ -456,26 +448,17 @@ export class HaScriptEditor extends SubscribeMixin(
<div class="alert-wrapper" slot="alerts">
${this._renderDeprecatedMigratedAlert()}
${
this.errors || stateObj?.state === UNAVAILABLE
stateObj?.state === UNAVAILABLE
? html`<ha-alert
alert-type="error"
.title=${
stateObj?.state === UNAVAILABLE
? this.hass.localize(
"ui.panel.config.script.editor.unavailable"
)
: undefined
}
.title=${this.hass.localize(
"ui.panel.config.script.editor.unavailable"
)}
>
${this.errors || this.validationErrors}
${
stateObj?.state === UNAVAILABLE
? html`<ha-svg-icon
slot="icon"
.path=${mdiRobotConfused}
></ha-svg-icon>`
: nothing
}
<ha-svg-icon
slot="icon"
.path=${mdiRobotConfused}
></ha-svg-icon>
</ha-alert>`
: nothing
}
@@ -532,6 +515,7 @@ export class HaScriptEditor extends SubscribeMixin(
`
: this.mode === "yaml"
? html`${this._renderDeprecatedMigratedAlert()}
${this.renderConfigErrorsAlert()}
<ha-yaml-editor
.defaultValue=${this._preprocessYaml()}
.readOnly=${this.readOnly}
@@ -628,7 +612,7 @@ export class HaScriptEditor extends SubscribeMixin(
entityRegistryUpdate: this.entityRegistryUpdate,
}
);
this._checkValidation();
this.checkValidation();
});
const regEntry = this.entityRegistry?.find(
(ent) => ent.entity_id === this.entityId
@@ -641,37 +625,12 @@ export class HaScriptEditor extends SubscribeMixin(
}
}
private async _checkValidation() {
this.validationErrors = undefined;
if (!this.currentEntityId || !this.config) {
return;
}
const stateObj = this.hass.states[this.currentEntityId];
if (stateObj?.state !== UNAVAILABLE) {
return;
}
const validation = await validateConfig(this.hass, {
actions: this.config.sequence,
});
this.validationErrors = (
Object.entries(validation) as Entries<typeof validation>
).map(([key, value]) =>
value.valid
? ""
: html`${this.hass.localize(
`ui.panel.config.automation.editor.${key}.name`
)}:
${value.error}<br />`
);
}
private _valueChanged(ev) {
if (this.config) {
this._undoRedoController.commit(this.config);
}
this.config = ev.detail.value;
this.errors = undefined;
this._updateDirtyState({
config: this.config!,
entityRegistryUpdate: this.entityRegistryUpdate,
@@ -784,7 +743,6 @@ export class HaScriptEditor extends SubscribeMixin(
config: this.config!,
entityRegistryUpdate: this.entityRegistryUpdate,
});
this.errors = undefined;
}
protected async confirmUnsavedChanged(addHistory = true): Promise<boolean> {
@@ -864,9 +822,8 @@ export class HaScriptEditor extends SubscribeMixin(
this._yamlEditor?.setValue(this.config);
}
this.readOnly = true;
this.errors = undefined;
} catch (err: any) {
this.errors = err.message;
showEditorToast(this, { message: err.message });
}
}
@@ -982,6 +939,7 @@ export class HaScriptEditor extends SubscribeMixin(
private async _saveScript(id): Promise<void> {
this.saving = true;
const config = this.config!;
let entityRegPromise: Promise<EntityRegistryEntry> | undefined;
if (this.entityRegistryUpdate !== undefined && !this.scriptId) {
@@ -992,11 +950,7 @@ export class HaScriptEditor extends SubscribeMixin(
}
try {
await this.hass!.callApi(
"POST",
"config/script/config/" + id,
this.config
);
await this.hass!.callApi("POST", "config/script/config/" + id, config);
if (this.entityRegistryUpdate !== undefined) {
let entityId = this.currentEntityId;
@@ -1044,11 +998,9 @@ export class HaScriptEditor extends SubscribeMixin(
this._markDirtyStateClean();
this.deprecatedConfigMigrated = false;
} catch (errors: any) {
this.errors = errors.body?.message || errors.error || errors.body;
showEditorToast(this, {
message: errors.body?.message || errors.error || errors.body,
});
this.clearConfigErrors();
} catch (errors: unknown) {
this.showSaveErrors(errors, config);
throw errors;
} finally {
this.saving = false;
+1 -1
View File
@@ -207,7 +207,7 @@ export const colorStyles = css`
--state-climate-fan_only-color: var(--cyan-color);
--state-climate-heat-color: var(--deep-orange-color);
--state-climate-heat-cool-color: var(--amber-color);
--state-cover-active-color: var(--blue-color);
--state-cover-active-color: var(--purple-color);
--state-device_tracker-active-color: var(--blue-color);
--state-device_tracker-home-color: var(--green-color);
--state-fan-active-color: var(--cyan-color);
+39 -3
View File
@@ -5943,6 +5943,36 @@
"disabled": "Automation is disabled",
"read_only": "This automation cannot be edited from the UI, because it is not stored in the automations.yaml file, or doesn't have an ID.",
"unavailable": "Automation is unavailable",
"errors": {
"label": "Problem",
"problems_found": "{count, plural,\n one {# problem found}\n other {# problems found}\n}",
"save_failed": "Saving failed: {problems}",
"target_required": "Choose at least one target.",
"target_invalid": "Some targets aren't valid. Remove or replace them.",
"device_required": "Choose a device.",
"field_message": "{field}: {message}",
"validation": {
"allowed_at_most_one_of": "Use only one of these options: {keys}.",
"allowed_one_of": "Use exactly one of these options: {keys}.",
"expected_boolean": "Choose on or off.",
"expected_duration": "Enter a duration.",
"expected_duration_detailed": "Enter a duration, like 0:05:00.",
"invalid_value": "[%key:ui::panel::config::automation::editor::errors::validation::not_a_valid_value%]",
"key_not_allowed": "[%key:ui::panel::config::automation::editor::errors::validation::not_a_valid_option%]",
"not_a_valid_option": "This option isn't supported here.",
"not_a_valid_value": "This value isn't valid.",
"range_max": "Enter a value of {max} or lower.",
"range_max_exclusive": "Enter a value lower than {max}.",
"range_min": "Enter a value of {min} or higher.",
"range_min_exclusive": "Enter a value higher than {min}.",
"required": "This field is required.",
"required_field": "{field} is required.",
"required_any_of": "Fill in at least one of these options: {keys}.",
"required_one_of": "Fill in exactly one of these options: {keys}.",
"value_not_empty": "This field can't be empty.",
"value_one_of": "Choose one of these values: {values}."
}
},
"deprecated_migrated": {
"title": "Deprecated options updated",
"description": "This automation used deprecated options that have been automatically updated to their new equivalents. Save the automation to apply the changes."
@@ -7734,15 +7764,21 @@
},
"triggers": {
"no_triggers": "No triggers",
"unknown_trigger": "Unknown trigger"
"unknown_trigger": "Unknown trigger",
"required": "Choose a trigger.",
"not_supported": "This device has no triggers. Choose another device."
},
"conditions": {
"no_conditions": "No conditions",
"unknown_condition": "Unknown condition"
"unknown_condition": "Unknown condition",
"required": "Choose a condition.",
"not_supported": "This device has no conditions. Choose another device."
},
"actions": {
"no_actions": "No actions",
"unknown_action": "Unknown action"
"unknown_action": "Unknown action",
"required": "Choose an action.",
"not_supported": "This device has no actions. Choose another device."
}
},
"script": {
+13
View File
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import {
formatPath,
pathEquals,
pathStartsWith,
stringifyPath,
} from "../../../src/common/util/config-path";
@@ -15,5 +17,16 @@ describe("config path", () => {
expect(pathEquals(["actions", 0], ["actions", "0"])).toBe(false);
expect(pathEquals(["actions", 0], ["actions", 0, "then"])).toBe(false);
expect(pathEquals([], [])).toBe(true);
expect(pathStartsWith(["actions", 0, "delay"], ["actions", 0])).toBe(true);
expect(pathStartsWith(["actions", 0], ["actions", 0])).toBe(true);
expect(pathStartsWith(["actions", 0], ["actions", 0, "delay"])).toBe(false);
expect(pathStartsWith(["actions", 0], ["actions", "0"])).toBe(false);
expect(formatPath(["actions", 1, "then", 0, "delay"])).toBe(
"actions[1].then[0].delay"
);
expect(formatPath([0, "for"])).toBe("[0].for");
expect(formatPath([])).toBe("");
});
});
+103
View File
@@ -0,0 +1,103 @@
import { describe, expect, it } from "vitest";
import type { ConfigPath } from "../../src/common/util/config-path";
import {
parseConfigSaveError,
validationResultErrors,
type ConfigValidationError,
} from "../../src/data/config";
const validationError = (
message: string,
path: ConfigPath,
code: string | null = null
): ConfigValidationError => ({
message,
path,
code,
translation_key: null,
translation_domain: null,
translation_placeholders: {},
});
describe("config validation errors", () => {
it("get the section key in front of validate_config paths", () => {
expect(
validationResultErrors({
triggers: { valid: true, error: null, errors: [] },
actions: {
valid: false,
error: "Bad delay at '[1].then[0].delay'",
errors: [
validationError("Bad delay", [1, "then", 0, "delay"]),
validationError("Unknown device", [2]),
],
},
conditions: {
valid: false,
error: "Bad condition",
errors: [validationError("Bad condition", [])],
},
})
).toEqual([
validationError("Bad delay", ["actions", 1, "then", 0, "delay"]),
validationError("Unknown device", ["actions", 2]),
validationError("Bad condition", ["conditions"]),
]);
// Scripts validate their sequence as actions
expect(
validationResultErrors(
{
actions: {
valid: false,
error: "Bad delay at '[0].delay'",
errors: [validationError("Bad delay", [0, "delay"])],
},
},
{ actions: "sequence" }
)
).toEqual([validationError("Bad delay", ["sequence", 0, "delay"])]);
});
it("are read from a failed save", () => {
const errors = [
validationError(
"required key not provided",
["triggers", 1, "entity_id"],
"required"
),
];
expect(
parseConfigSaveError({
error: "Response error: 400",
status_code: 400,
body: {
message:
"Message malformed: required key not provided at 'triggers[1].entity_id'",
errors,
},
})
).toEqual({
message:
"Message malformed: required key not provided at 'triggers[1].entity_id'",
errors,
});
// Errors that are not about the config
expect(
parseConfigSaveError({
error: "Response error: 401",
status_code: 401,
body: { message: "Unauthorized" },
})
).toEqual({ message: "Unauthorized", errors: [] });
expect(
parseConfigSaveError({
error: "Request error",
status_code: undefined,
body: undefined,
})
).toEqual({ message: "Request error", errors: [] });
});
});
@@ -0,0 +1,312 @@
import { describe, expect, it } from "vitest";
import type { LocalizeFunc } from "../../../../src/common/translations/localize";
import type { ConfigPath } from "../../../../src/common/util/config-path";
import type { ConfigValidationError } from "../../../../src/data/config";
import {
configErrorPath,
errorMessage,
errorOwner,
errorsOnKnownItems,
followErrors,
followKnownErrorItems,
knownErrorItems,
errorText,
fieldErrors,
ownedErrors,
} from "../../../../src/panels/config/automation/automation-errors";
import {
AutomationRowRegistry,
type AutomationPathRow,
} from "../../../../src/panels/config/automation/automation-path";
const createRow = () =>
({
selected: false,
openSidebar: () => undefined,
expand: () => undefined,
}) as unknown as AutomationPathRow;
const validationError = (
message: string,
path: ConfigPath
): ConfigValidationError => ({
message,
path,
code: null,
translation_key: null,
translation_domain: null,
translation_placeholders: {},
});
const TRANSLATIONS: Record<string, string> = {
"ui.panel.config.automation.editor.errors.field_message":
"{field}: {message}",
"ui.panel.config.automation.editor.errors.validation.required_field":
"{field} is required.",
"ui.panel.config.automation.editor.errors.validation.value_one_of":
"Choose one of {values}.",
};
const localize = ((key: string, values: Record<string, string> = {}) =>
(TRANSLATIONS[key] ?? "").replace(
/\{(\w+)\}/g,
(_, name: string) => values[name]
)) as LocalizeFunc;
describe("automation errors", () => {
it("belong to the deepest rendered row on their path", () => {
const registry = new AutomationRowRegistry();
const block = createRow();
const nested = createRow();
const other = createRow();
registry.register(["actions", 0], block);
registry.register(["actions", 0, "then", 0], nested);
registry.register(["actions", 1], other);
const inNested = validationError("a", ["actions", 0, "then", 0, "delay"]);
// The nested row of this path is not rendered, so its block owns it
const inCollapsed = validationError("b", ["actions", 0, "else", 0]);
const global = validationError("c", ["mode"]);
const noPath = validationError("d", []);
const errors = [inNested, inCollapsed, global, noPath];
expect(errorOwner(registry, inNested)).toBe(nested);
expect(ownedErrors(registry, errors, block)).toEqual([inCollapsed]);
expect(ownedErrors(registry, errors, nested)).toEqual([inNested]);
expect(ownedErrors(registry, errors, other)).toEqual([]);
expect(errorOwner(registry, global)).toBeUndefined();
expect(errorOwner(registry, noPath)).toBeUndefined();
});
it("map to form fields and read relative to a row", () => {
const errors = [
validationError("bad for", ["triggers", 1, "for", "hours"]),
validationError("second for", ["triggers", 1, "for"]),
validationError("bad entity", ["triggers", 1, "entity_id"]),
validationError("row itself", ["triggers", 1]),
validationError("other row", ["triggers", 2, "for"]),
];
expect(fieldErrors(localize, errors, ["triggers", 1])).toEqual({
for: "bad for",
entity_id: "bad entity",
});
expect(fieldErrors(localize, errors, ["triggers", 3])).toEqual({});
expect(errorText(localize, errors[0], ["triggers", 1])).toBe(
"for.hours: bad for"
);
expect(errorText(localize, errors[3], ["triggers", 1])).toBe("row itself");
expect(errorText(localize, errors[4])).toBe("triggers[2].for: other row");
});
it("are translated when the frontend knows their key", () => {
const oneOf = {
...validationError("value must be one of ['single', 'queued']", ["mode"]),
translation_key: "value_one_of",
translation_placeholders: { values: ["single", "queued"] },
};
expect(errorMessage(localize, oneOf)).toBe("Choose one of single, queued.");
expect(errorText(localize, oneOf)).toBe(
"mode: Choose one of single, queued."
);
// Keys of an integration are not in the frontend translations
expect(
errorMessage(localize, { ...oneOf, translation_domain: "light" })
).toBe(oneOf.message);
expect(
errorMessage(localize, { ...oneOf, translation_key: "expected_type" })
).toBe(oneOf.message);
// Errors shown above a field name it
expect(errorMessage(localize, oneOf, "Mode")).toBe(
"Mode: Choose one of single, queued."
);
expect(
errorMessage(
localize,
{
...validationError("required key not provided", ["entity_id"]),
translation_key: "required",
},
"Entity"
)
).toBe("Entity is required.");
});
it("get the index of a block written as a single item", () => {
const config = {
actions: [
{
choose: {
conditions: { condition: "state" },
sequence: [{ delay: 1 }],
},
default: { delay: "abc" },
},
{ action: "light.turn_on", data: { default: { a: 1 } } },
{ repeat: { while: { condition: "template" }, sequence: [] } },
],
};
expect(
configErrorPath(config, ["actions", 0, "choose", "conditions", "state"])
).toEqual(["actions", 0, "choose", 0, "conditions", 0, "state"]);
expect(
configErrorPath(config, ["actions", 0, "choose", "sequence", 0, "delay"])
).toEqual(["actions", 0, "choose", 0, "sequence", 0, "delay"]);
expect(configErrorPath(config, ["actions", 0, "default", "delay"])).toEqual(
["actions", 0, "default", 0, "delay"]
);
expect(
configErrorPath(config, ["actions", 2, "repeat", "while", "value"])
).toEqual(["actions", 2, "repeat", "while", 0, "value"]);
// Keys inside fields are not blocks
expect(
configErrorPath(config, ["actions", 1, "data", "default", "a"])
).toEqual(["actions", 1, "data", "default", "a"]);
// Errors about the block itself
expect(configErrorPath(config, ["actions", 0, "default"])).toEqual([
"actions",
0,
"default",
]);
expect(configErrorPath(config, ["mode"])).toEqual(["mode"]);
// Editing the single item turns the block into a list, the item keeps
// its error
const delayError = validationError("bad delay", [
"actions",
0,
"default",
0,
"delay",
]);
const known = knownErrorItems(config, [delayError]);
const edited = {
actions: [{ ...config.actions[0], default: [{ delay: "abd" }] }],
};
expect(
errorsOnKnownItems(followKnownErrorItems(known, config, edited), edited, [
delayError,
])
).toEqual([delayError]);
});
it("keep only live errors on items that already had one", () => {
const a = { trigger: "state", entity_id: ["sensor.a"], for: "abc" };
const b = { trigger: "event", event_type: "b" };
const c = { trigger: "state", entity_id: "sensor.c", for: "xyz" };
const forError = (index: number) =>
validationError("bad for", ["triggers", index, "for"]);
const before = { triggers: [a, b, c] };
const known = knownErrorItems(before, [forError(0), forError(2)]);
// Edited in place, the item keeps its errors; a value list entry belongs
// to the trigger, and a new error on another item waits for the save
const edited = { triggers: [{ ...a, for: "abd" }, b, c] };
const valueEntry = validationError("bad entity", [
"triggers",
0,
"entity_id",
0,
]);
const other = validationError("new", ["triggers", 1, "event_type"]);
expect(
errorsOnKnownItems(followKnownErrorItems(known, before, edited), edited, [
forError(0),
valueEntry,
other,
])
).toEqual([forError(0), valueEntry]);
// Deleting a row moves the next error, and the row that takes the old
// index doesn't count as known
const deleted = { triggers: [b, c] };
expect(
errorsOnKnownItems(
followKnownErrorItems(known, before, deleted),
deleted,
[forError(0), forError(1)]
)
).toEqual([forError(1)]);
// Moving a row past another doesn't make the other one known
const swapped = { triggers: [b, a, c] };
expect(
errorsOnKnownItems(
followKnownErrorItems(known, before, swapped),
swapped,
[forError(0), forError(1)]
)
).toEqual([forError(1)]);
// YAML is parsed again on every edit, so items are found by content
const reparsed = structuredClone(deleted);
expect(
errorsOnKnownItems(
followKnownErrorItems(known, before, reparsed),
reparsed,
[forError(0), forError(1)]
)
).toEqual([forError(1)]);
// Identical items both keep their errors after the YAML is parsed again
const twice = { triggers: [a, { ...a }] };
const knownTwice = knownErrorItems(twice, [forError(0), forError(1)]);
const reparsedTwice = structuredClone(twice);
expect(
errorsOnKnownItems(
followKnownErrorItems(knownTwice, twice, reparsedTwice),
reparsedTwice,
[forError(0), forError(1)]
)
).toEqual([forError(0), forError(1)]);
// An item edited and then moved keeps its errors
const knownC = knownErrorItems(before, [forError(2)]);
const editedC = { ...c, for: "xyy" };
const afterEdit = { triggers: [a, b, editedC] };
const afterMove = { triggers: [editedC, a, b] };
const followed = followKnownErrorItems(
followKnownErrorItems(knownC, before, afterEdit),
afterEdit,
afterMove
);
expect(
errorsOnKnownItems(followed, afterMove, [forError(0), forError(2)])
).toEqual([forError(0)]);
});
it("follow save errors to where their items are now", () => {
const a = { delay: "abc" };
const b = { delay: 1 };
const c = { wait_template: "{{ " };
const submitted = { actions: [a, b, c] };
const errors = [
validationError("bad delay", ["actions", 0, "delay"]),
validationError("bad template", ["actions", 2, "wait_template"]),
validationError("bad mode", ["mode"]),
];
// A was deleted and C moved up while saving
expect(followErrors(errors, submitted, { actions: [c, b] })).toEqual([
validationError("bad template", ["actions", 0, "wait_template"]),
validationError("bad mode", ["mode"]),
]);
// A block written as a single item moves with the action around it
const choose = { choose: [], default: { delay: "abc" } };
const delay = { delay: 1 };
const singleton = { actions: [choose, delay] };
const defaultError = validationError("bad delay", [
"actions",
0,
"default",
0,
"delay",
]);
expect(
followErrors([defaultError], singleton, { actions: [delay, choose] })
).toEqual([
validationError("bad delay", ["actions", 1, "default", 0, "delay"]),
]);
});
});
@@ -0,0 +1,21 @@
import { describe, expect, it, vi } from "vitest";
import { InlineErrorFields } from "../../../../src/panels/config/automation/automation-field-errors";
describe("InlineErrorFields", () => {
it("works", () => {
const onChange = vi.fn();
const fields = new InlineErrorFields(onChange);
const editor = {};
fields.set(editor, [["repeat", "count"], ["at"]]);
expect(fields.has(["repeat", "count"])).toBe(true);
expect(fields.has(["at", "offset"])).toBe(true);
// Other keys of a claimed block stay in the sidebar
expect(fields.has(["repeat", "sequence"])).toBe(false);
expect(fields.has(["repeat"])).toBe(false);
fields.delete(editor);
expect(fields.has(["at"])).toBe(false);
expect(onChange).toHaveBeenCalledTimes(2);
});
});