Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/components/ha-code-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
mdiArrowCollapse,
mdiArrowExpand,
mdiContentCopy,
mdiFlask,
mdiRedo,
mdiUndo,
} from "@mdi/js";
Expand All @@ -36,6 +37,7 @@ import type { HaIconButtonToolbar } from "./ha-icon-button-toolbar";
declare global {
interface HASSDomEvents {
"editor-save": undefined;
"test-toggle": undefined;
}
}

Expand Down Expand Up @@ -82,6 +84,9 @@ export class HaCodeEditor extends ReactiveElement {
@property({ type: Boolean, attribute: "has-toolbar" })
public hasToolbar = true;

@property({ type: Boolean, attribute: "has-test" })
public hasTest = false;

@property({ type: String }) public placeholder?: string;

@state() private _value = "";
Expand Down Expand Up @@ -359,6 +364,16 @@ export class HaCodeEditor extends ReactiveElement {
}

this._editorToolbar.items = [
...(this.hasTest && !this._isFullscreen
? [
{
id: "test",
label: this.hass?.localize("ui.common.test") || "Test",
path: mdiFlask,
action: (e: Event) => this._handleTestClick(e),
},
]
: []),
{
id: "undo",
disabled: !this._canUndo,
Expand Down Expand Up @@ -416,6 +431,15 @@ export class HaCodeEditor extends ReactiveElement {
}
};

private _handleTestClick = (e: Event) => {
e.preventDefault();
e.stopPropagation();
if (!this.codemirror) {
return;
}
fireEvent(this, "test-toggle");
};

private _handleUndoClick = (e: Event) => {
e.preventDefault();
e.stopPropagation();
Expand Down
119 changes: 119 additions & 0 deletions src/components/ha-selector/ha-selector-template.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
import type { PropertyValues } from "lit";
import { css, html, nothing, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import { fireEvent } from "../../common/dom/fire_event";
import type { HomeAssistant } from "../../types";
import { documentationUrl } from "../../util/documentation-url";
import "../ha-code-editor";
import "../ha-input-helper-text";
import "../ha-alert";
import type { RenderTemplateResult } from "../../data/ws-templates";
import { subscribeRenderTemplate } from "../../data/ws-templates";
import { debounce } from "../../common/util/debounce";
import type { TemplateSelector } from "../../data/selector";

const WARNING_STRINGS = ["template:", "sensor:", "state:", "trigger: template"];

@customElement("ha-selector-template")
export class HaTemplateSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;

@property({ attribute: false }) public selector!: TemplateSelector;

@property() public value?: string;

@property() public label?: string;
Expand All @@ -27,6 +35,37 @@ export class HaTemplateSelector extends LitElement {

@state() private warn: string | undefined = undefined;

@state() private _test = false;

@state() private _error?: string;

@state() private _errorLevel?: "ERROR" | "WARNING";

@state() private _templateResult?: RenderTemplateResult;

@state() private _unsubRenderTemplate?: Promise<UnsubscribeFunc>;

private _debounceError = debounce(
(error, level) => {
this._error = error;
this._errorLevel = level;
this._templateResult = undefined;
},
500,
false
);

public disconnectedCallback() {
super.disconnectedCallback();
this._debounceError.cancel();
}

protected updated(changedProps: PropertyValues) {
if (changedProps.has("value") && this._test) {
this._subscribeTemplate();
}
}

protected render() {
return html`
${this.warn
Expand Down Expand Up @@ -61,10 +100,23 @@ export class HaTemplateSelector extends LitElement {
autofocus
autocomplete-entities
autocomplete-icons
.hasTest=${this.selector.template?.preview !== false}
@value-changed=${this._handleChange}
@test-toggle=${this._testToggle}
dir="ltr"
linewrap
></ha-code-editor>
${this._test && this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: this._test && this._templateResult
? html`<ha-alert alert-type="info">
<pre>
${typeof this._templateResult.result === "object"
? JSON.stringify(this._templateResult.result, null, 2)
: this._templateResult.result}</pre
>
</ha-alert>`
: nothing}
${this.helper
? html`<ha-input-helper-text .disabled=${this.disabled}
>${this.helper}</ha-input-helper-text
Expand All @@ -73,6 +125,73 @@ export class HaTemplateSelector extends LitElement {
`;
}

private _testToggle() {
this._test = !this._test;
if (this._test) {
this._subscribeTemplate();
} else {
this._unsubscribeTemplate();
}
}

private async _subscribeTemplate() {
await this._unsubscribeTemplate();

const template = this.value || "";

try {
this._unsubRenderTemplate = subscribeRenderTemplate(
this.hass.connection,
(result) => {
if ("error" in result) {
// We show the latest error, or a warning if there are no errors
if (result.level === "ERROR" || this._errorLevel !== "ERROR") {
this._debounceError(result.error, result.level);
}
} else {
this._debounceError.cancel();
this._error = undefined;
this._errorLevel = undefined;
this._templateResult = result;
}
},
{
template,
timeout: 3,
report_errors: true,
}
);
await this._unsubRenderTemplate;
} catch (err: any) {
this._error = "Unknown error";
this._errorLevel = undefined;
if (err.message) {
this._error = err.message;
this._errorLevel = undefined;
this._templateResult = undefined;
}
this._unsubRenderTemplate = undefined;
}
}

private async _unsubscribeTemplate(): Promise<void> {
if (!this._unsubRenderTemplate) {
return;
}

try {
const unsub = await this._unsubRenderTemplate;
unsub();
this._unsubRenderTemplate = undefined;
} catch (err: any) {
if (err.code === "not_found") {
// If we get here, the connection was probably already closed. Ignore.
} else {
throw err;
}
}
}

private _handleChange(ev) {
ev.stopPropagation();
let value = ev.target.value;
Expand Down
4 changes: 3 additions & 1 deletion src/data/selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,9 @@ export interface TargetSelector {
}

export interface TemplateSelector {
template: {} | null;
template: {
preview?: boolean;
} | null;
}

export interface ThemeSelector {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,11 @@ export class HuiMarkdownCardEditor
...(!text_only
? ([{ name: "title", selector: { text: {} } }] as const)
: []),
{ name: "content", required: true, selector: { template: {} } },
{
name: "content",
required: true,
selector: { template: { preview: false } },
},
] as const satisfies HaFormSchema[]
);

Expand Down
Loading