From cd6fd6a46cda0f2c80a35eb09a7b205ffbffcb14 Mon Sep 17 00:00:00 2001 From: Bram Kragten Date: Wed, 2 Oct 2019 21:21:13 +0200 Subject: [PATCH] Allow yaml in script and automation (#3862) * Allow yaml in script and automation * Restore defaults * Rename class * Catch errors in constructor * Update yaml_textarea.tsx --- src/panels/config/js/script/call_service.tsx | 4 +- src/panels/config/js/script/event.tsx | 4 +- src/panels/config/js/trigger/event.tsx | 4 +- src/panels/config/js/yaml_textarea.tsx | 80 ++++++++++++++++++++ 4 files changed, 86 insertions(+), 6 deletions(-) create mode 100644 src/panels/config/js/yaml_textarea.tsx diff --git a/src/panels/config/js/script/call_service.tsx b/src/panels/config/js/script/call_service.tsx index 5182248c26..754171ab6e 100644 --- a/src/panels/config/js/script/call_service.tsx +++ b/src/panels/config/js/script/call_service.tsx @@ -1,7 +1,7 @@ import { h, Component } from "preact"; import "../../../../components/ha-service-picker"; -import JSONTextArea from "../json_textarea"; +import YAMLTextArea from "../yaml_textarea"; export default class CallServiceAction extends Component { constructor() { @@ -32,7 +32,7 @@ export default class CallServiceAction extends Component { value={service} onChange={this.serviceChanged} /> - { value={event} onvalue-changed={this.onChange} /> - { @@ -34,7 +34,7 @@ export default class EventTrigger extends Component { value={event_type} onvalue-changed={this.onChange} /> - { + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + return false; + } + } + return true; +}; + +export default class YAMLTextArea extends Component { + constructor(props) { + super(props); + + let value: string | undefined; + try { + value = + props.value && !isEmpty(props.value) + ? yaml.safeDump(props.value) + : undefined; + } catch (err) { + alert(`There was an error converting to YAML: ${err}`); + } + + this.state = { + isvalid: true, + value, + }; + + this.onChange = this.onChange.bind(this); + } + + public onChange(ev) { + const value = ev.target.value; + let parsed; + let isValid = true; + + if (value) { + try { + parsed = yaml.safeLoad(value); + isValid = true; + } catch (err) { + // Invalid YAML + isValid = false; + } + } else { + parsed = {}; + } + + this.setState({ + value, + isValid, + }); + if (isValid) { + this.props.onChange(parsed); + } + } + + public render({ label }, { value, isValid }) { + const style: any = { + minWidth: 300, + width: "100%", + }; + if (!isValid) { + style.border = "1px solid red"; + } + return ( + + ); + } +}