Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

UI updates: or-asset-editor validation and reporting

Rich Turnere8036511a8b9
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index 2ecb40326..dd0caced1 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -415,6 +415,9 @@
"key": "Key",
"anyOfPickerLabel": "{{label}} type",
"validation": {
+ "invalidAsset": "Asset is not valid",
+ "invalidAttributeValue": "Invalid attribute value for attribute '{{attrName}}'",
+ "invalidMetaItemValue": "Invalid configuration item value for `{{metaName}}` on attribute '{{attrName}}'",
"invalidNumber": "Invalid number",
"invalidJSON": "Invalid JSON",
"invalidDate": "Invalid date",
diff --git a/ui/component/or-asset-viewer/src/index.ts b/ui/component/or-asset-viewer/src/index.ts
index 297e0686a..cf69cce7c 100644
--- a/ui/component/or-asset-viewer/src/index.ts
+++ b/ui/component/or-asset-viewer/src/index.ts
@@ -2,7 +2,7 @@
declare function require(name: string): any;
import {html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
-import {customElement, property, query} from "lit/decorators.js";
+import {customElement, property, query, state} from "lit/decorators.js";
import "@openremote/or-icon";
import "@openremote/or-mwc-components/or-mwc-input";
import "@openremote/or-attribute-input";
@@ -41,7 +41,7 @@ import {classMap} from "lit/directives/class-map";
import { GenericAxiosResponse } from "axios";
import {OrIcon} from "@openremote/or-icon";
import "./or-edit-asset-panel";
-import {OrEditAssetModifiedEvent} from "./or-edit-asset-panel";
+import {OrEditAssetModifiedEvent, OrEditAssetPanel, ValidatorResult} from "./or-edit-asset-panel";
import "@openremote/or-mwc-components/or-mwc-snackbar";
import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
@@ -815,10 +815,7 @@ export function getPropertyTemplate(asset: Asset, property: string, hostElement:
switch (property) {
case "parentId":
// Display the path instead
- value = (asset as { [index: string]: any })["path"];
- if (!value || !(Array.isArray(value))) {
- return;
- }
+ value = asset.path || ["", asset.parentId];
// Populate value when we get the response
const ancestors = [...value];
@@ -1027,6 +1024,8 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem
@property()
protected _loading: boolean = false;
+ @state()
+ protected _validationResults: ValidatorResult[] = [];
protected _assetModified = false;
protected _viewerConfig?: AssetViewerConfig;
protected _attributes?: { [index: string]: Attribute<any> };
@@ -1041,12 +1040,15 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem
@query("#edit-btn")
protected editBtnElem!: OrMwcInput;
+ @query("#editor")
+ protected editor!: OrEditAssetPanel;
+
constructor() {
super();
this.addEventListener(OrAssetViewerComputeGridEvent.NAME, () => OrAssetViewer.generateGrid(this.shadowRoot));
this.addEventListener(OrChartEvent.NAME, () => OrAssetViewer.generateGrid(this.shadowRoot));
this.addEventListener(OrAttributeHistoryEvent.NAME, () => OrAssetViewer.generateGrid(this.shadowRoot));
- this.addEventListener(OrEditAssetModifiedEvent.NAME, () => this._onAssetModified());
+ this.addEventListener(OrEditAssetModifiedEvent.NAME, (ev: OrEditAssetModifiedEvent) => this._onAssetModified(ev.detail));
}
public isModified() {
@@ -1105,6 +1107,18 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem
return super.shouldUpdate(changedProperties);
}
+ updated(_changedProperties: PropertyValues) {
+ if (_changedProperties.has("asset")) {
+ this._doValidation();
+ }
+ }
+
+ protected _doValidation() {
+ if (this.editMode && this.editor) {
+ this._validationResults = this.editor.validate();
+ }
+ }
+
protected render(): TemplateResult | void {
if (this._loading) {
@@ -1137,7 +1151,7 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem
if (editMode) {
content = html`
<div id="edit-container">
- <or-edit-asset-panel .asset="${this.asset}"></or-edit-asset-panel>
+ <or-edit-asset-panel id="editor" .asset="${this.asset}"></or-edit-asset-panel>
</div>
`;
} else {
@@ -1156,6 +1170,23 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem
}
}
+ const validationErrors: string[] = this.editMode
+ ? this._validationResults
+ .filter((validationResult) => !validationResult.valid || validationResult.metaResults && validationResult.metaResults.some((r) => !r.valid))
+ .flatMap((validationResult) => {
+ const errors: string[] = [];
+ if (!validationResult.valid) {
+ errors.push(i18next.t("validation.invalidAttributeValue", {attrName: validationResult.name}));
+ }
+ if (validationResult.metaResults) {
+ validationResult.metaResults.filter((result) => !result.valid).forEach((metaResult) => {
+ errors.push(i18next.t("validation.invalidMetaItemValue", {attrName: validationResult.name, metaName: metaResult.name}));
+ });
+ }
+ return errors;
+ })
+ : [];
+
return html`
<div id="wrapper">
<div id="asset-header" class=${editMode ? "editmode" : ""}>
@@ -1164,11 +1195,16 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem
</a>
<div id="title">
<or-icon title="${descriptor && descriptor.name ? descriptor.name : "unset"}" style="--or-icon-fill: ${descriptor && descriptor.colour ? "#" + descriptor.colour : "unset"}" icon="${descriptor && descriptor.icon ? descriptor.icon : AssetModelUtil.getAssetDescriptorIcon(WellknownAssets.THINGASSET)}"></or-icon>
- ${editMode ? html`<or-mwc-input id="name-input" .type="${InputType.TEXT}" min="1" max="1023" comfortable required outlined .label="${i18next.t("name")}" .value="${this.asset.name}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => {this.asset!.name = e.detail.value; this._onAssetModified();}}"></or-mwc-input>` : html`<span>${this.asset.name}</span>`}
+ ${editMode
+ ? html`
+ <or-mwc-input id="name-input" .type="${InputType.TEXT}" min="1" max="1023" comfortable required outlined .label="${i18next.t("name")}" .value="${this.asset.name}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => {this.asset!.name = e.detail.value; this._assetModified = true; this._doValidation();}}"></or-mwc-input>
+ `
+ : html`<span>${this.asset.name}</span>`}
</div>
+ <div id="error-wrapper">${validationErrors.length === 0 ? `` : html`<span .title="${validationErrors.join("\n")}"><or-icon icon="alert"></or-icon><or-translate value="validation.invalidAsset"></or-translate></span>`}</div>
<div id="right-wrapper" class="mobileHidden">
${this.asset!.createdOn ? html`<or-translate id="created-time" value="createdOnWithDate" .options="${{ date: new Date(this.asset!.createdOn!) } as TOptions<InitOptions>}"></or-translate>` : ``}
- ${editMode ? html`<or-mwc-input id="save-btn" .disabled="${!this.isModified()}" raised .type="${InputType.BUTTON}" .label="${i18next.t("save")}" @or-mwc-input-changed="${() => this._onSaveClicked()}"></or-mwc-input>` : ``}
+ ${editMode ? html`<or-mwc-input id="save-btn" .disabled="${!this.isModified() || validationErrors.length > 0}" raised .type="${InputType.BUTTON}" .label="${i18next.t("save")}" @or-mwc-input-changed="${() => this._onSaveClicked()}"></or-mwc-input>` : ``}
${!this._isReadonly() ? html`<or-mwc-input id="edit-btn" class="mobileHidden" outlined .type="${InputType.BUTTON}" .value="${this.editMode}" .label="${this.editMode ? i18next.t("view") : i18next.t("modify")}" icon="${this.editMode ? "eye" : "pencil"}" @or-mwc-input-changed="${() => this._onEditToggleClicked(!this.editMode!)}"></or-mwc-input>
`: ``}
</div>
@@ -1227,7 +1263,7 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem
}
protected async _doSave() {
- let asset = this.asset;
+ const asset = this.asset;
if (!asset) {
return;
@@ -1250,9 +1286,9 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem
this.dispatchEvent(new OrAssetViewerSaveEvent(result));
}
- protected _onAssetModified() {
+ protected _onAssetModified(validationResults: ValidatorResult[]) {
this._assetModified = true;
- this.requestUpdate();
+ this._validationResults = validationResults;
}
public static generateGrid(shadowRoot: ShadowRoot | null) {
diff --git a/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts b/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts
index e79a758bd..5a3848cb4 100644
--- a/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts
+++ b/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts
@@ -1,7 +1,7 @@
-import {css, html, LitElement, TemplateResult, unsafeCSS} from "lit";
+import {css, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
import {until} from "lit/directives/until";
-import {customElement, property} from "lit/decorators.js";
-import {InputType, OrMwcInput, OrInputChangedEvent, getValueHolderInputTemplateProvider, ValueInputProviderOptions, OrInputChangedEventDetail} from "@openremote/or-mwc-components/or-mwc-input";
+import {customElement, property, state} from "lit/decorators.js";
+import {InputType, OrMwcInput, OrInputChangedEvent, getValueHolderInputTemplateProvider, ValueInputProviderOptions, OrInputChangedEventDetail, ValueInputProvider} from "@openremote/or-mwc-components/or-mwc-input";
import i18next from "i18next";
import {Asset, Attribute, NameValueHolder} from "@openremote/model";
import {AssetModelUtil, DefaultColor5, DefaultColor3, Util} from "@openremote/core";
@@ -16,7 +16,8 @@ import {
} from "./or-add-attribute-panel";
import {panelStyles} from "./style";
import { OrAssetTree, UiAssetTreeNode } from "@openremote/or-asset-tree";
-import {jsonFormsInputTemplateProvider, OrAttributeInputChangedEvent } from "@openremote/or-attribute-input";
+import {jsonFormsInputTemplateProvider, OrAttributeInput, OrAttributeInputChangedEvent } from "@openremote/or-attribute-input";
+import {createRef, ref, Ref } from "lit/directives/ref.js";
// TODO: Add webpack/rollup to build so consumers aren't forced to use the same tooling
const tableStyle = require("@material/data-table/dist/mdc.data-table.css");
@@ -134,14 +135,15 @@ const style = css`
}
`;
-export class OrEditAssetModifiedEvent extends CustomEvent<void> {
+export class OrEditAssetModifiedEvent extends CustomEvent<ValidatorResult[]> {
public static readonly NAME = "or-edit-asset-modified";
- constructor() {
+ constructor(validatorResults: ValidatorResult[]) {
super(OrEditAssetModifiedEvent.NAME, {
bubbles: true,
- composed: true
+ composed: true,
+ detail: validatorResults
});
}
}
@@ -154,12 +156,25 @@ declare global {
const AssetNameRegex = /^\w+$/;
+export interface ValidatorResult {
+ name: string;
+ valid: boolean;
+ metaResults?: ValidatorResult[]; // For meta items
+}
+
+interface TemplateAndValidator {
+ template: TemplateResult;
+ validator: () => ValidatorResult;
+}
+
@customElement("or-edit-asset-panel")
export class OrEditAssetPanel extends LitElement {
@property({attribute: false})
protected asset!: Asset;
+ protected attributeTemplatesAndValidators: TemplateAndValidator[] = [];
+
public static get styles() {
return [
unsafeCSS(tableStyle),
@@ -217,6 +232,8 @@ export class OrEditAssetPanel extends LitElement {
}
};
+ this.attributeTemplatesAndValidators = !this.asset.attributes ? [] : Object.entries(this.asset.attributes!).sort(Util.sortByString(([name, attribute]) => name.toUpperCase())).map(([name, attribute]) => {attribute.name = name; return this._getAttributeTemplate(this.asset.type!, attribute as Attribute<any>);})
+
const attributes = html`
<div id="attribute-table" class="mdc-data-table">
<table class="mdc-data-table__table" aria-label="attribute list" @click="${expanderToggle}">
@@ -229,7 +246,7 @@ export class OrEditAssetPanel extends LitElement {
</tr>
</thead>
<tbody class="mdc-data-table__content">
- ${!this.asset.attributes ? `` : Object.entries(this.asset.attributes!).sort(Util.sortByString(([name, attribute]) => name.toUpperCase())).map(([name, attribute]) => {attribute.name = name; return this._getEditAttributeTemplate(this.asset.type!, attribute as Attribute<any>);})}
+ ${this.attributeTemplatesAndValidators.map((attrTemplateAndValidator) => attrTemplateAndValidator.template)}
<tr class="mdc-data-table__row">
<td colspan="4">
<div class="item-add-attribute">
@@ -250,7 +267,7 @@ export class OrEditAssetPanel extends LitElement {
`;
}
- protected _getEditAttributeTemplate(assetType: string, attribute: Attribute<any>): TemplateResult {
+ protected _getAttributeTemplate(assetType: string, attribute: Attribute<any>): TemplateAndValidator {
const deleteAttribute = () => {
delete this.asset.attributes![attribute.name!];
@@ -259,13 +276,29 @@ export class OrEditAssetPanel extends LitElement {
const descriptor = AssetModelUtil.getAttributeDescriptor(attribute.name!, assetType);
const canDelete = !descriptor || descriptor.optional;
+ const attributeInputRef: Ref<OrAttributeInput> = createRef();
+ const metaTemplatesAndValidators = !attribute.meta ? [] : Object.entries(attribute.meta).sort(Util.sortByString(([name, value]) => name!)).map(([name, value]) => this._getMetaItemTemplate(attribute, Util.getMetaItemNameValueHolder(name, value)));
- return html`
+ const validator = (): ValidatorResult => {
+ let valid = false;
+
+ if (attributeInputRef.value) {
+ valid = attributeInputRef.value.checkValidity();
+ }
+
+ return {
+ name: attribute.name!,
+ valid: valid,
+ metaResults: metaTemplatesAndValidators.map((metaTemplateAndValidator) => metaTemplateAndValidator.validator())
+ };
+ };
+
+ const template = html`
<tr class="mdc-data-table__row">
<td class="padded-cell mdc-data-table__cell expander-cell"><or-icon icon="chevron-right"></or-icon><span>${attribute.name}</span></td>
<td class="padded-cell mdc-data-table__cell">${Util.getValueDescriptorLabel(attribute.type!)}</td>
<td class="padded-cell overflow-visible mdc-data-table__cell">
- <or-attribute-input compact .comfortable="${true}" .assetType="${assetType}" .label=${null} .readonly="${false}" .attribute="${attribute}" .assetId="${this.asset.id!}" disableWrite disableSubscribe disableButton @or-attribute-input-changed="${(e: OrAttributeInputChangedEvent) => this._onAttributeModified(attribute, e.detail.value)}"></or-attribute-input>
+ <or-attribute-input ${ref(attributeInputRef)} compact .comfortable="${true}" .assetType="${assetType}" .label=${null} .readonly="${false}" .attribute="${attribute}" .assetId="${this.asset.id!}" disableWrite disableSubscribe disableButton @or-attribute-input-changed="${(e: OrAttributeInputChangedEvent) => this._onAttributeModified(attribute, e.detail.value)}"></or-attribute-input>
</td>
<td class="padded-cell mdc-data-table__cell actions-cell">${canDelete ? html`<or-mwc-input type="${InputType.BUTTON}" icon="delete" @click="${deleteAttribute}">` : ``}</td>
</tr>
@@ -274,7 +307,7 @@ export class OrEditAssetPanel extends LitElement {
<div class="meta-item-container">
<div>
<div>
- ${!attribute.meta ? `` : Object.entries(attribute.meta).sort(Util.sortByString(([name, value]) => name!)).map(([name, value]) => this._getMetaItemTemplate(attribute, Util.getMetaItemNameValueHolder(name, value)))}
+ ${metaTemplatesAndValidators.map((metaTemplateAndValidator) => metaTemplateAndValidator.template)}
</div>
<div class="item-add">
<or-mwc-input .type="${InputType.BUTTON}" .label="${i18next.t("addMetaItems")}" icon="plus" @click="${() => this._addMetaItems(attribute)}"></or-mwc-input>
@@ -284,13 +317,22 @@ export class OrEditAssetPanel extends LitElement {
</td>
</tr>
`;
+
+ return {
+ template: template,
+ validator: validator
+ };
};
protected _onModified() {
- this.dispatchEvent(new OrEditAssetModifiedEvent());
+ this.dispatchEvent(new OrEditAssetModifiedEvent(this.validate()));
this.requestUpdate();
}
+ public validate(): ValidatorResult[] {
+ return this.attributeTemplatesAndValidators.map((attrTemplateAndValidator) => attrTemplateAndValidator.validator());
+ }
+
protected _onAttributeModified(attribute: Attribute<any>, newValue: any) {
attribute.value = newValue;
attribute.timestamp = undefined; // Clear timestamp so server will set this
@@ -303,25 +345,25 @@ export class OrEditAssetPanel extends LitElement {
this._onModified();
}
- protected _getMetaItemTemplate(attribute: Attribute<any>, metaItem: NameValueHolder<any>): TemplateResult {
-
- const removeMetaItem = () => {
- delete attribute.meta![metaItem.name!];
- this._onModified();
- };
-
+ protected _getMetaItemTemplate(attribute: Attribute<any>, metaItem: NameValueHolder<any>): TemplateAndValidator {
const descriptor = AssetModelUtil.getMetaItemDescriptor(metaItem.name);
const valueDescriptor = descriptor ? AssetModelUtil.getValueDescriptor(descriptor.type) : undefined;
let content: TemplateResult = html``;
+ let validator: () => ValidatorResult = () => {
+ return {
+ name: metaItem.name!,
+ valid: true
+ };
+ };
if (!valueDescriptor) {
- content = html`<p>NOT SUPPORTED</p>`;
+ console.log("Couldn't find value descriptor for meta item so falling back to simple JSON input: " + metaItem.name);
+ content = html`<or-mwc-input @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this._onMetaItemModified(attribute, metaItem, ev.detail)}" .type="${InputType.JSON}" .value="${metaItem.value}"></or-mwc-input>`;
} else {
const options: ValueInputProviderOptions = {
label: Util.getMetaLabel(metaItem, descriptor!, this.asset.type!, true),
resizeVertical: true
};
-
const standardInputProvider = getValueHolderInputTemplateProvider(this.asset.type!, metaItem, descriptor, valueDescriptor, (detail) => this._onMetaItemModified(attribute, metaItem, detail), options);
let provider = jsonFormsInputTemplateProvider(standardInputProvider)(this.asset.type!, metaItem, descriptor, valueDescriptor, (detail) => this._onMetaItemModified(attribute, metaItem, detail), options);
@@ -329,17 +371,37 @@ export class OrEditAssetPanel extends LitElement {
provider = standardInputProvider;
}
- if (provider.templateFunction) {
+ if (provider && provider.templateFunction) {
content = html`${until(provider.templateFunction(metaItem.value, false, false, false, false, undefined), ``)}`;
}
+ if (provider.validator) {
+ validator = () => {
+ return {
+ name: metaItem.name!,
+ valid: provider.validator!()
+ };
+ };
+ }
}
- return html`
- <div class="meta-item-wrapper">
- ${content}
- <button class="button-clear" @click="${removeMetaItem}"><or-icon icon="close-circle"></or-icon></input>
- </div>
- `;
+ const removeMetaItem = () => {
+ delete attribute.meta![metaItem.name!];
+ this._onModified();
+ };
+
+ const template = html`
+ <div class="meta-item-wrapper">
+ ${content}
+ <button class="button-clear" @click="${removeMetaItem}">
+ <or-icon icon="close-circle"></or-icon>
+ </input>
+ </div>
+ `;
+
+ return {
+ template: template,
+ validator: validator
+ };
}
protected _addAttribute() {
diff --git a/ui/component/or-asset-viewer/src/style.ts b/ui/component/or-asset-viewer/src/style.ts
index bfb4b4bd5..96a809e6f 100644
--- a/ui/component/or-asset-viewer/src/style.ts
+++ b/ui/component/or-asset-viewer/src/style.ts
@@ -167,11 +167,29 @@ export const style = css`
flex: 1 1 0%;
font-size: 18px;
font-weight: bold;
+ display: flex;
+ flex-direction: row;
+ align-items: center;
}
#title > or-icon {
margin-right: 10px;
}
+
+ #error-wrapper {
+ color: red;
+ flex: 1;
+ display: flex;
+ align-items: center;
+ }
+
+ #error-wrapper > span {
+ margin: auto;
+ }
+
+ #error-wrapper or-icon {
+ margin-right: 5px;
+ }
#created-time {
font-size: 12px;
@@ -218,7 +236,7 @@ export const style = css`
display: none;
cursor: pointer;
}
-
+
@media screen and (max-width: 769px) {
#wrapper {
position: absolute;
diff --git a/ui/component/or-attribute-input/src/index.ts b/ui/component/or-attribute-input/src/index.ts
index 9b09d7c90..e969fb70c 100644
--- a/ui/component/or-attribute-input/src/index.ts
+++ b/ui/component/or-attribute-input/src/index.ts
@@ -20,7 +20,7 @@ import {
import manager, {AssetModelUtil, DefaultColor4, subscribe, Util} from "@openremote/core";
import "@openremote/or-mwc-components/or-mwc-input";
import "@openremote/or-components/or-loading-wrapper";
-import {OrLoadingWrapper} from "@openremote/or-components/src/or-loading-wrapper";
+import {OrLoadingWrapper} from "@openremote/or-components/or-loading-wrapper";
import {
getValueHolderInputTemplateProvider,
InputType,
@@ -251,7 +251,13 @@ export const jsonFormsInputTemplateProvider: (fallback: ValueInputProvider) => V
templateFunction: templateFunction,
supportsHelperText: false,
supportsLabel: false,
- supportsSendButton: false
+ supportsSendButton: false,
+ validator: () => {
+ if (!jsonForms.value) {
+ return false;
+ }
+ return jsonForms.value.checkValidity();
+ }
};
}
@@ -777,6 +783,16 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE
this._onAttributeValueChanged(oldValue, this._attributeEvent.attributeState!.value, event.timestamp);
}
+ public checkValidity(): boolean {
+ if (!this._templateProvider) {
+ return false;
+ }
+ if (!this._templateProvider.validator) {
+ return true;
+ }
+ return this._templateProvider.validator();
+ }
+
protected _onAttributeValueChanged(oldValue: any, newValue: any, timestamp?: number) {
if (this.attribute) {
this.attribute.value = newValue;
diff --git a/ui/component/or-components/package.json b/ui/component/or-components/package.json
index b8c3f8a3f..3cfbdf9e6 100644
--- a/ui/component/or-components/package.json
+++ b/ui/component/or-components/package.json
@@ -12,6 +12,9 @@
"exports": {
"./*": "./dist/*.js"
},
+ "typesVersions": {
+ "*": { "*": ["dist/*"] }
+ },
"author": "OpenRemote",
"license": "AGPL-3.0-or-later",
"dependencies": {
diff --git a/ui/component/or-components/src/or-ace-editor.ts b/ui/component/or-components/src/or-ace-editor.ts
new file mode 100644
index 000000000..ddab993c9
--- /dev/null
+++ b/ui/component/or-components/src/or-ace-editor.ts
@@ -0,0 +1,186 @@
+import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
+import {customElement, property, query} from "lit/decorators.js";
+import ace, {Ace} from "ace-builds";
+import "ace-builds/src-noconflict/mode-javascript";
+import "ace-builds/src-noconflict/mode-json";
+import "ace-builds/src-noconflict/mode-groovy";
+import "ace-builds/webpack-resolver";
+
+export class OrAceEditorChangedEvent extends CustomEvent<{ value: string, valid: boolean }> {
+
+ public static readonly NAME = "or-ace-editor-changed";
+
+ constructor(value: string, valid: boolean) {
+ super(OrAceEditorChangedEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: {
+ value: value,
+ valid: valid
+ }
+ });
+ }
+}
+
+export class OrAceEditorEditEvent extends CustomEvent<void> {
+
+ public static readonly NAME = "or-ace-editor-edit";
+
+ constructor() {
+ super(OrAceEditorEditEvent.NAME, {
+ bubbles: true,
+ composed: true
+ });
+ }
+}
+
+declare global {
+ export interface HTMLElementEventMap {
+ [OrAceEditorChangedEvent.NAME]: OrAceEditorChangedEvent;
+ [OrAceEditorEditEvent.NAME]: OrAceEditorEditEvent;
+ }
+}
+
+@customElement("or-ace-editor")
+export class OrAceEditor extends LitElement {
+
+ // language=CSS
+ static get styles() {
+ return css`
+ :host {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+
+ #ace-editor {
+ position: relative;
+ height: 100%;
+ width: 100%;
+ }
+
+ @media screen and (max-width: 1400px) {
+ :host > * {
+ flex-grow: 0;
+ }
+
+ :host {
+ flex-direction: column;
+ }
+ }
+ `;
+ }
+
+ @property({type: Boolean, attribute: false})
+ public readonly?: boolean;
+
+ @property({attribute: false})
+ public value?: any;
+
+ @property({type: String, attribute: false})
+ public mode: string = "ace/mode/json";
+
+ @query("#ace-editor")
+ protected _aceElem?: HTMLElement;
+ protected _aceEditor?: Ace.Editor;
+ protected _lastValue: string = "";
+ protected _editing: boolean = false;
+ protected _changeTimer?: number;
+
+ disconnectedCallback(): void {
+ this.destroyEditor();
+ super.disconnectedCallback();
+ }
+
+ updated(_changedProperties: PropertyValues) {
+ super.updated(_changedProperties);
+
+ if (_changedProperties.has("mode")) {
+ this.destroyEditor();
+ this.initEditor();
+ }
+
+ if (_changedProperties.has("value")) {
+ if (this._aceEditor) {
+ this._lastValue = this.value !== undefined ? typeof this.value === "string" ? this.value : JSON.stringify(this.value, null, 2) : "";
+ this._aceEditor.setValue(this._lastValue);
+ }
+ }
+ }
+
+ render(): TemplateResult | void {
+ return html`
+ <div id="ace-editor"></div>
+ `;
+ }
+
+ protected destroyEditor() {
+ if (this._aceEditor) {
+ this._aceEditor.destroy();
+ this._aceEditor = undefined;
+ }
+ }
+
+ protected initEditor() {
+ if (this._aceElem) {
+ this._aceEditor = ace.edit(this._aceElem, {
+ mode: this.mode,
+ value: this._lastValue,
+ useSoftTabs: true,
+ tabSize: 2,
+ readOnly: this.readonly,
+ showPrintMargin: false
+ });
+ this._aceEditor.renderer.attachToShadowRoot();
+ // Use the changeAnnotation event instead of change event so we have up to date validation info
+ // @ts-ignore
+ this._aceEditor.getSession().on("changeAnnotation", () => this._onEditorChange());
+ this._aceEditor.on("change", () => this._onEditorEdit());
+ }
+ }
+
+ protected _onEditorEdit() {
+ if (!this._editing) {
+ this.dispatchEvent(new OrAceEditorEditEvent());
+ this._editing = true;
+ }
+ if (this._changeTimer) {
+ window.clearTimeout(this._changeTimer);
+ }
+ // Set change timer to expire after annotation web worker
+ this._changeTimer = window.setTimeout(() => {
+ this._changeTimer = undefined;
+ if (this._editing) {
+ this._onEditorChange();
+ }
+ }, 600);
+ }
+
+ protected _onEditorChange() {
+ this._editing = false;
+ const newValue = this.getValue() || "";
+ if (this._lastValue !== newValue) {
+ this._lastValue = newValue;
+ const valid = this.validate();
+ this.dispatchEvent(new OrAceEditorChangedEvent(newValue, valid));
+ }
+ }
+
+ public getValue(): string | undefined {
+ if (!this._aceEditor) {
+ return undefined;
+ }
+
+ return this._aceEditor.getValue();
+ }
+
+ public validate(): boolean {
+
+ if (!this._aceEditor) {
+ return false;
+ }
+
+ const annotations = this._aceEditor.getSession().getAnnotations();
+ return !annotations || annotations.length === 0;
+ }
+}
diff --git a/ui/component/or-json-forms/src/controls/control-array-element.ts b/ui/component/or-json-forms/src/controls/control-array-element.ts
index 46d1ea2d9..2d3b12dcc 100644
--- a/ui/component/or-json-forms/src/controls/control-array-element.ts
+++ b/ui/component/or-json-forms/src/controls/control-array-element.ts
@@ -5,13 +5,12 @@ import {
mapDispatchToArrayControlProps,
OwnPropsOfRenderer,
Paths,
- RendererProps,
Resolve,
update
} from "@jsonforms/core";
import {css, html, PropertyValues, TemplateResult, unsafeCSS} from "lit";
import {customElement, property} from "lit/decorators.js";
-import {CombinatorInfo, controlWithoutLabel, getCombinatorInfos, getTemplateFromProps} from "../util";
+import {CombinatorInfo, controlWithoutLabel, getCombinatorInfos, getTemplateFromProps, showJsonEditor} from "../util";
import {InputType, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";
import {i18next} from "@openremote/or-translate";
import {showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
@@ -19,8 +18,6 @@ import "@openremote/or-mwc-components/or-mwc-list";
import {addItemOrParameterDialogStyle, baseStyle, panelStyle} from "../styles";
import {ListItem, OrMwcListChangedEvent} from "@openremote/or-mwc-components/or-mwc-list";
import {DefaultColor4, DefaultColor5} from "@openremote/core";
-import "../json-editor";
-import {JsonEditor} from "../json-editor";
import {ControlBaseElement} from "./control-base-element";
import {getTemplateWrapper} from "../index";
import {AdditionalProps} from "../base-element";
@@ -262,56 +259,9 @@ export class ControlArrayElement extends ControlBaseElement {
protected _showJson(ev: MouseEvent) {
ev.stopPropagation();
- const dialog = showDialog(
- {
- content: html`
- <or-json-forms-json-editor id="json-editor" .json="${this.data === undefined ? "" : JSON.stringify(this.data, null, 2)}"></or-json-forms-json-editor>
- `,
- actions: [
- {
- actionName: "cancel",
- content: i18next.t("cancel")
- },
- {
- default: true,
- actionName: "update",
- action: () => {
- const editor = dialog.shadowRoot!.getElementById("json-editor") as JsonEditor;
- if (editor.validate()) {
- const data = !!editor.getValue() ? JSON.parse(editor.getValue()!) : undefined;
- this.state.dispatch(
- update(this.path || "", (d) => {
- return data;
- })
- )
- }
- },
- content: html`<or-mwc-input id="add-btn" .type="${InputType.BUTTON}" .label="${i18next.t("update")}"></or-mwc-input>`
- }
- ],
- title: this.title || this.schema.title,
- dismissAction: null,
- styles: html`
- <style>
- .mdc-dialog__surface {
- width: 1024px;
- overflow-x: visible !important;
- overflow-y: visible !important;
- }
- #dialog-content {
- border-color: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
- border-top-width: 1px;
- border-top-style: solid;
- border-bottom-width: 1px;
- border-bottom-style: solid;
- padding: 0;
- overflow: visible;
- height: 60vh;
- }
- </style>
- `
- }
- )
+ showJsonEditor(this.title || this.schema.title || "", this.data, ((newValue) => {
+ this.handleChange(this.path || "", newValue);
+ }));
}
protected doAddItem() {
diff --git a/ui/component/or-json-forms/src/index.ts b/ui/component/or-json-forms/src/index.ts
index 8809b1ba4..a98337afa 100644
--- a/ui/component/or-json-forms/src/index.ts
+++ b/ui/component/or-json-forms/src/index.ts
@@ -107,6 +107,10 @@ export class OrJSONForms extends LitElement implements OwnPropsOfJsonFormsRender
protected previousData: any;
protected previousErrors: ErrorObject[] = [];
+ public checkValidity() {
+ return this.previousErrors.length === 0;
+ }
+
shouldUpdate(_changedProperties: PropertyValues) {
super.shouldUpdate(_changedProperties);
diff --git a/ui/component/or-json-forms/src/json-editor.ts b/ui/component/or-json-forms/src/json-editor.ts
deleted file mode 100644
index b92c725c5..000000000
--- a/ui/component/or-json-forms/src/json-editor.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-import {css, html, LitElement, PropertyValues, TemplateResult } from "lit";
-import { customElement, property, query } from "lit/decorators.js";
-import ace, {Ace} from "ace-builds";
-import "ace-builds/src-noconflict/mode-javascript";
-import "ace-builds/src-noconflict/mode-json";
-import "ace-builds/src-noconflict/mode-groovy";
-import "ace-builds/webpack-resolver";
-
-// language=CSS
-const style = css`
- :host {
- display: flex;
- width: 100%;
- height: 100%;
- }
-
- #ace-editor {
- position: relative;
- height: 100%;
- width: 100%;
- }
-
- @media screen and (max-width: 1400px) {
- :host > * {
- flex-grow: 0;
- }
-
- :host {
- flex-direction: column;
- }
- }
-`;
-
-@customElement("or-json-forms-json-editor")
-export class JsonEditor extends LitElement {
-
- static get styles() {
- return style;
- }
-
- @property({attribute: false})
- public readonly?: boolean;
-
- @property({type: String, attribute: false})
- public json?: string;
-
- @query("#ace-editor")
- protected _aceElem?: HTMLElement;
- protected _aceEditor?: Ace.Editor;
- protected _changeTimer?: number;
-
- disconnectedCallback(): void {
- this.destroyEditor();
- super.disconnectedCallback();
- }
-
- firstUpdated(_changedProperties: PropertyValues) {
- super.firstUpdated(_changedProperties);
- this.initEditor();
- }
-
- render(): TemplateResult | void {
- return html`
- <div id="ace-editor"></div>
- `;
- }
-
- protected _onEditorChanged() {
- if (this._changeTimer) {
- window.clearTimeout(this._changeTimer);
- }
- this._changeTimer = window.setTimeout(() => this._onEdit(), 1000);
- }
-
- protected _onEdit() {
- //this.dispatchEvent(new OrRulesRuleChangedEvent(this.validate()));
- this._changeTimer = undefined;
- }
-
- public getValue(): string | undefined {
- if (!this._aceEditor) {
- return undefined;
- }
-
- return this._aceEditor.getValue();
- }
-
- public validate(): boolean {
-
- if (!this._aceEditor) {
- return false;
- }
-
- const annotations = this._aceEditor.getSession().getAnnotations();
- return !annotations || annotations.length === 0;
- }
-
-
- protected destroyEditor() {
- if (this._aceEditor) {
- this._aceEditor.destroy();
- this._aceEditor = undefined;
- }
- }
-
- protected initEditor() {
- if (this._aceElem) {
- this._aceEditor = ace.edit(this._aceElem, {
- mode: "ace/mode/json",
- value: this.json,
- useSoftTabs: true,
- tabSize: 2,
- readOnly: this.readonly,
- showPrintMargin: false
- });
- this._aceEditor.on("change", () => this._onEditorChanged());
- this._aceEditor.renderer.attachToShadowRoot();
- }
- }
-}
diff --git a/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts b/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts
index 51f4ba43b..11e23a04a 100644
--- a/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts
+++ b/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts
@@ -19,7 +19,7 @@ import {
import {css, html, TemplateResult, unsafeCSS} from "lit";
import {customElement, property} from "lit/decorators.js";
import {LayoutBaseElement} from "./layout-base-element";
-import {controlWithoutLabel, getLabel, getTemplateFromProps} from "../util";
+import {controlWithoutLabel, getLabel, getTemplateFromProps, showJsonEditor} from "../util";
import {InputType, OrInputChangedEvent, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";
import {i18next} from "@openremote/or-translate";
import {showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
@@ -28,8 +28,6 @@ import "@openremote/or-components/or-collapsible-panel";
import {addItemOrParameterDialogStyle, baseStyle, panelStyle} from "../styles";
import {ListItem, OrMwcListChangedEvent} from "@openremote/or-mwc-components/or-mwc-list";
import {DefaultColor5} from "@openremote/core";
-import "../json-editor";
-import {JsonEditor} from "../json-editor";
import {AdditionalProps} from "../base-element";
// language=CSS
@@ -238,52 +236,9 @@ export class LayoutVerticalElement extends LayoutBaseElement<VerticalLayout | Gr
protected _showJson(ev: MouseEvent) {
ev.stopPropagation();
- const dialog = showDialog(
- {
- content: html`
- <or-json-forms-json-editor id="json-editor" .json="${this.data === undefined ? "" : JSON.stringify(this.data, null, 2)}"></or-json-forms-json-editor>
- `,
- actions: [
- {
- actionName: "cancel",
- content: i18next.t("cancel")
- },
- {
- default: true,
- actionName: "update",
- action: () => {
- const editor = dialog.shadowRoot!.getElementById("json-editor") as JsonEditor;
- if (editor.validate()) {
- const data = !!editor.getValue() ? JSON.parse(editor.getValue()!) : undefined;
- this.handleChange(this.path || "", data);
- }
- },
- content: html`<or-mwc-input id="add-btn" .type="${InputType.BUTTON}" .label="${i18next.t("update")}"></or-mwc-input>`
- }
- ],
- title: this.title || this.schema.title,
- dismissAction: null,
- styles: html`
- <style>
- .mdc-dialog__surface {
- width: 1024px;
- overflow-x: visible !important;
- overflow-y: visible !important;
- }
- #dialog-content {
- border-color: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
- border-top-width: 1px;
- border-top-style: solid;
- border-bottom-width: 1px;
- border-bottom-style: solid;
- padding: 0;
- overflow: visible;
- height: 60vh;
- }
- </style>
- `
- }
- )
+ showJsonEditor(this.title || this.schema.title || "", this.data, (newValue) => {
+ this.handleChange(this.path || "", newValue);
+ });
}
protected _addParameter(optionalProps: StatePropsOfControl[], dynamicPropertyRegex?: string, dynamicValueSchema?: JsonSchema) {
diff --git a/ui/component/or-json-forms/src/util.ts b/ui/component/or-json-forms/src/util.ts
index 1a1679838..f3469fc14 100644
--- a/ui/component/or-json-forms/src/util.ts
+++ b/ui/component/or-json-forms/src/util.ts
@@ -22,10 +22,16 @@ import {
resolveSubSchemas,
StatePropsOfCombinator,
} from "@jsonforms/core";
-import {Util} from "@openremote/core";
-import {html, TemplateResult} from "lit";
+import {DefaultColor5, Util} from "@openremote/core";
+import { InputType, OrMwcInput } from "@openremote/or-mwc-components/or-mwc-input";
+import { i18next } from "@openremote/or-translate";
+import "@openremote/or-components/or-ace-editor";
+import {OrAceEditor, OrAceEditorChangedEvent} from "@openremote/or-components/or-ace-editor";
+import {html, TemplateResult, unsafeCSS} from "lit";
+import {createRef, Ref, ref} from 'lit/directives/ref.js';
import {ErrorObject} from "./index";
import {unknownTemplate} from "./standard-renderers";
+import { showDialog } from "@openremote/or-mwc-components/or-mwc-dialog";
export function getTemplateFromProps<T extends OwnPropsOfRenderer>(state: JsonFormsSubStates | undefined, props: T | undefined): TemplateResult {
if (!state || !props) {
@@ -305,3 +311,64 @@ export const controlWithoutLabel = (scope: string): ControlElement => ({
scope: scope,
label: false
});
+
+export const showJsonEditor = (title: string, value: any, updateCallback: (newValue: string) => void): void => {
+
+ const editorRef: Ref<OrAceEditor> = createRef();
+ const updateBtnRef: Ref<OrMwcInput> = createRef();
+ const onEditorEdit = () => {
+ // Disable update button whilst edit in progress
+ updateBtnRef.value!.disabled = true;
+ };
+ const onEditorChanged = (ev: OrAceEditorChangedEvent) => {
+ const valid = ev.detail.valid;
+ updateBtnRef.value!.disabled = !valid;
+ };
+
+ const dialog = showDialog(
+ {
+ content: html`
+ <or-ace-editor ${ref(editorRef)} @or-ace-editor-edit="${() => onEditorEdit()}" @or-ace-editor-changed="${(ev: OrAceEditorChangedEvent) => onEditorChanged(ev)}" .value="${value}"></or-ace-editor>
+ `,
+ actions: [
+ {
+ actionName: "cancel",
+ content: i18next.t("cancel")
+ },
+ {
+ default: true,
+ actionName: "update",
+ action: () => {
+ const editor = editorRef.value!;
+ if (editor.validate()) {
+ const data = !!editor.getValue() ? JSON.parse(editor.getValue()!) : undefined;
+ updateCallback(data);
+ }
+ },
+ content: html`<or-mwc-input ${ref(updateBtnRef)} disabled .type="${InputType.BUTTON}" .label="${i18next.t("update")}"></or-mwc-input>`
+ }
+ ],
+ title: title,
+ dismissAction: null,
+ styles: html`
+ <style>
+ .mdc-dialog__surface {
+ width: 1024px;
+ overflow-x: visible !important;
+ overflow-y: visible !important;
+ }
+ #dialog-content {
+ border-color: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
+ border-top-width: 1px;
+ border-top-style: solid;
+ border-bottom-width: 1px;
+ border-bottom-style: solid;
+ padding: 0;
+ overflow: visible;
+ height: 60vh;
+ }
+ </style>
+ `
+ }
+ )
+};
diff --git a/ui/component/or-map/src/index.ts b/ui/component/or-map/src/index.ts
index ff9e1ed53..2850f94fa 100644
--- a/ui/component/or-map/src/index.ts
+++ b/ui/component/or-map/src/index.ts
@@ -106,7 +106,7 @@ function getCoordinatesInputKeyHandler(valueChangedHandler: (value: LngLat | und
return (e: KeyboardEvent) => {
if (e.code === "Enter" || e.code === "NumpadEnter") {
const valStr = (e.target as OrMwcInput).value as string;
- let value: LngLat | undefined;
+ let value: LngLat | undefined = !valStr ? undefined : {} as LngLat;
if (valStr) {
const lngLatArr = valStr.split(/[ ,]/).filter(v => !!v);
@@ -200,9 +200,9 @@ export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (a
};
const coordinatesControl = new CoordinatesControl(disabled, valueChangeHandler);
+ let pos: { lng: number, lat: number } | undefined;
const templateFunction: ValueInputTemplateFunction = (value, focused, loading, sending, error, helperText) => {
- let pos: { lng: number, lat: number } | undefined;
let center: number[] | undefined;
if (value) {
@@ -314,7 +314,8 @@ export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (a
templateFunction: templateFunction,
supportsHelperText: false,
supportsLabel: false,
- supportsSendButton: false
+ supportsSendButton: false,
+ validator: () => !pos || (pos.lat !== undefined && pos.lat !== null && pos.lng !== undefined && pos.lng !== null)
};
}
diff --git a/ui/component/or-mwc-components/src/or-mwc-input.ts b/ui/component/or-mwc-components/src/or-mwc-input.ts
index bd0e59773..b8b289508 100644
--- a/ui/component/or-mwc-components/src/or-mwc-input.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-input.ts
@@ -1,5 +1,6 @@
import {css, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
import {customElement, property, state} from "lit/decorators.js";
+import {Ref, ref, createRef} from "lit/directives/ref.js";
import {classMap} from "lit/directives/class-map";
import {ifDefined} from "lit/directives/if-defined";
import {MDCTextField} from "@material/textfield";
@@ -141,6 +142,7 @@ export interface ValueInputProvider {
supportsHelperText: boolean;
supportsLabel: boolean;
supportsSendButton: boolean;
+ validator?: () => boolean;
}
export type ValueInputTemplateFunction = ((value: any, focused: boolean, loading: boolean, sending: boolean, error: boolean, helperText: string | undefined) => TemplateResult | PromiseLike<TemplateResult>) | undefined;
@@ -380,13 +382,14 @@ export const getValueHolderInputTemplateProvider: ValueInputProviderGenerator =
const readonly = options.readonly;
const comfortable = options.comfortable;
const resizeVertical = options.resizeVertical;
+ const inputRef: Ref<OrMwcInput> = createRef();
const templateFunction: ValueInputTemplateFunction = (value, focused, loading, sending, error, helperText) => {
const disabled = options.disabled || loading || sending;
const label = supportsLabel ? options.label : undefined;
- return html`<or-mwc-input id="input" .type="${inputType}" .label="${label}" .value="${value}" .pattern="${pattern}"
+ return html`<or-mwc-input ${ref(inputRef)} id="input" .type="${inputType}" .label="${label}" .value="${value}" .pattern="${pattern}"
.min="${min}" .max="${max}" .format="${format}" .focused="${focused}" .required="${required}" .multiple="${multiple}"
.options="${selectOptions}" .comfortable="${comfortable}" .readonly="${readonly}" .disabled="${disabled}" .step="${step}"
.helperText="${helperText}" .helperPersistent="${true}" .resizeVertical="${resizeVertical}"
@@ -401,7 +404,13 @@ export const getValueHolderInputTemplateProvider: ValueInputProviderGenerator =
templateFunction: templateFunction,
supportsHelperText: supportsHelperText,
supportsSendButton: supportsSendButton,
- supportsLabel: supportsLabel
+ supportsLabel: supportsLabel,
+ validator: () => {
+ if (!inputRef.value) {
+ return false;
+ }
+ return inputRef.value.checkValidity();
+ }
};
}
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
index 27bf79489..f35abece6 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
@@ -153,7 +153,7 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
} else {
this._rule = {
recurrence: {
- mins: 0 //always
+ mins: 0 // always
}
};
}
@@ -262,7 +262,7 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
}
protected _onJsonRuleChanged() {
- let valid = this.validate();
+ const valid = this.validate();
this.dispatchEvent(new OrRulesRuleChangedEvent(valid));
}
diff --git a/ui/component/or-rules/src/or-rule-text-viewer.ts b/ui/component/or-rules/src/or-rule-text-viewer.ts
index c83371dbc..ff7a4052f 100644
--- a/ui/component/or-rules/src/or-rule-text-viewer.ts
+++ b/ui/component/or-rules/src/or-rule-text-viewer.ts
@@ -1,12 +1,14 @@
import {OrRulesRuleChangedEvent, RulesConfig, RuleView} from "./index";
-import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
-import {customElement, property, query} from "lit/decorators.js";
+import {css, html, LitElement, TemplateResult} from "lit";
+import {customElement, property} from "lit/decorators.js";
import {RulesetLang, RulesetUnion} from "@openremote/model";
-import ace, {Ace} from "ace-builds";
import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/mode-json";
import "ace-builds/src-noconflict/mode-groovy";
import "ace-builds/webpack-resolver";
+import "@openremote/or-components/or-ace-editor";
+import {OrAceEditor, OrAceEditorChangedEvent} from "@openremote/or-components/or-ace-editor";
+import {createRef, ref, Ref} from "lit/directives/ref.js";
// language=CSS
const style = css`
@@ -49,19 +51,8 @@ export class OrRuleTextViewer extends LitElement implements RuleView {
@property({attribute: false})
protected _ruleset!: RulesetUnion;
- @query("#ace-editor")
- protected _aceElem?: HTMLElement;
protected _rules?: string;
- protected _aceEditor?: Ace.Editor;
- protected _changeTimer?: number;
-
- disconnectedCallback(): void {
- if (this._aceEditor) {
- this._aceEditor.destroy();
- this._aceEditor = undefined;
- }
- super.disconnectedCallback();
- }
+ protected _aceEditor: Ref<OrAceEditor> = createRef();
public set ruleset(ruleset: RulesetUnion) {
if (this._ruleset === ruleset) {
@@ -84,51 +75,10 @@ export class OrRuleTextViewer extends LitElement implements RuleView {
protected render(): TemplateResult | void {
return html`
- <div id="ace-editor"></div>
+ <or-ace-editor ${ref(this._aceEditor)} @or-ace-editor-changed="${(ev: OrAceEditorChangedEvent) => this._onEditorChanged(ev)}" .mode="${this._getMode()}" .value="${this._getRulesString()}"></or-ace-editor>
`;
}
- protected refresh() {
- this.destroyEditor()
- this.initEditor();
- }
-
- protected destroyEditor() {
- if (this._aceEditor) {
- this._aceEditor.destroy();
- this._aceEditor = undefined;
- }
- }
-
- protected initEditor() {
- if (this._aceElem) {
- this._aceEditor = ace.edit(this._aceElem, {
- mode: this._getMode(),
- value: this._getRulesString(),
- useSoftTabs: true,
- tabSize: 2,
- readOnly: this.readonly,
- showPrintMargin: false
- });
- this._aceEditor.on("change", () => this._onEditorChanged());
- this._aceEditor.renderer.attachToShadowRoot();
- }
- }
-
- protected updated(_changedProperties: PropertyValues): void {
- if(_changedProperties.has('_ruleset')){
- this.refresh();
- }
-
- if (!this._aceElem) {
- this.destroyEditor();
- } else {
- if (!this._aceEditor) {
- this.initEditor();
- }
- }
- }
-
protected _getMode() {
switch (this._ruleset.lang) {
case RulesetLang.JAVASCRIPT:
@@ -154,33 +104,20 @@ export class OrRuleTextViewer extends LitElement implements RuleView {
}
}
- protected _onEditorChanged() {
- if (this._changeTimer) {
- window.clearTimeout(this._changeTimer);
- }
- this._changeTimer = window.setTimeout(() => this._onEdit(), 1000);
- }
-
- protected _onEdit() {
- this.dispatchEvent(new OrRulesRuleChangedEvent(this.validate()));
- this._changeTimer = undefined;
+ protected _onEditorChanged(ev: OrAceEditorChangedEvent) {
+ const valid = ev.detail.valid;
+ this.dispatchEvent(new OrRulesRuleChangedEvent(valid));
}
public beforeSave() {
- if (!this._aceEditor) {
+ if (!this._aceEditor.value) {
return;
}
- this._ruleset.rules = this._aceEditor.getValue();
+ this._ruleset.rules = this._aceEditor.value.getValue();
}
public validate(): boolean {
-
- if (!this._aceEditor) {
- return false;
- }
-
- const annotations = this._aceEditor.getSession().getAnnotations();
- return !annotations || annotations.length === 0;
+ return this._aceEditor.value ? this._aceEditor.value.validate() : false;
}
}