Skip to content

armgit / core

Public Imported from GitHub
0

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

New widgets: added "Attribute Input" and "Table". (#1185)

Martin Peeters1c1868b1c96b
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index f0b051395..aa7625600 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -605,8 +605,6 @@
"dashboard": {
"widget": "Widget",
"widgets": "Widgets",
- "widget-kpi": "KPI",
- "widget-linechart": "Line Chart",
"axisConfig": "Axis Configuration",
"leftAxis": "Left axis",
"rightAxis": "Right axis",
@@ -639,6 +637,7 @@
"whoCanView": "Who can <b>view</b> the dashboard?",
"whoCanEdit": "Who can <b>edit</b> the dashboard?",
"numberOfColumns": "Number of columns",
+ "numberOfRows": "Number of rows",
"maxScreenWidth": "Max screen width",
"onScreenMyBoardShould": "On a {{size}} screen my board should:",
"setToMobilePreset": "Set Mobile Preset",
@@ -654,6 +653,10 @@
"showLegend": "Show legend",
"showGeoJson": "Show GeoJSON overlay",
"showValueAs": "Show value as",
+ "customLabel": "Custom label",
+ "userCanEdit": "Allow user input",
+ "showHelperText": "Show time of last update",
+ "tableSettings": "Table settings",
"deleteWidget": "Delete widget",
"myDashboards": "My dashboards",
"createdByOthers": "Created by others",
diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.json
index 316fed375..79ce0512a 100644
--- a/manager/src/web/shared/locales/nl/or.json
+++ b/manager/src/web/shared/locales/nl/or.json
@@ -605,8 +605,6 @@
"dashboard": {
"widget": "Widget",
"widgets": "Widgets",
- "widget-kpi": "KPI",
- "widget-linechart": "Lijngrafiek",
"axisConfig": "Assen configuratie",
"leftAxis": "Linker as",
"rightAxis": "Rechter as",
@@ -639,6 +637,7 @@
"whoCanView": "Wie kan het dashboard <b>bekijken</b>?",
"whoCanEdit": "Wie kan het dashboard <b>bewerken</b>?",
"numberOfColumns": "Aantal kolommen",
+ "numberOfRows": "Aantal rijen",
"maxScreenWidth": "Max schermbreedte",
"onScreenMyBoardShould": "Op een {{size}} scherm moet het bord:",
"setToMobilePreset": "Stel mobiel preset in",
@@ -654,6 +653,10 @@
"showLegend": "Toon legenda",
"showGeoJson": "Toon GeoJSON overlay",
"showValueAs": "Laat waarde zien als",
+ "customLabel": "Label",
+ "userCanEdit": "Kan waarde aanpassen",
+ "showHelperText": "Toon moment van bijwerken",
+ "tableSettings": "Tabeleigenschappen",
"deleteWidget": "Verwijder widget",
"myDashboards": "Mijn dashboards",
"createdByOthers": "Gemaakt door anderen",
diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardWidget.java b/model/src/main/java/org/openremote/model/dashboard/DashboardWidget.java
index c5b3fb961..050066bb9 100644
--- a/model/src/main/java/org/openremote/model/dashboard/DashboardWidget.java
+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardWidget.java
@@ -10,7 +10,7 @@ public class DashboardWidget {
// Fields
protected String id;
- @NotBlank(message = "{Dashboard.widget.displayName.NotBlank}")
+ @NotNull(message = "{Dashboard.widget.displayName.NotNull}")
protected String displayName;
@NotNull(message = "{Dashboard.widget.gridItem.NotNull}")
@@ -26,7 +26,7 @@ public class DashboardWidget {
/* ------------------------------ */
public void setId(@NotNull @NotEmpty String id) { this.id = id; }
- public void setDisplayName(@NotNull @NotEmpty String displayName) { this.displayName = displayName; }
+ public void setDisplayName(@NotNull String displayName) { this.displayName = displayName; }
public void setGridItem(@NotNull DashboardGridItem gridItem) { this.gridItem = gridItem; }
public void setWidgetTypeId(@NotNull String widgetTypeId) { this.widgetTypeId = widgetTypeId; }
public void setWidgetConfig(Object widgetConfig) { this.widgetConfig = widgetConfig; }
diff --git a/model/src/main/resources/ValidationMessages.properties b/model/src/main/resources/ValidationMessages.properties
index e2d2aedfb..5af4ea4a0 100644
--- a/model/src/main/resources/ValidationMessages.properties
+++ b/model/src/main/resources/ValidationMessages.properties
@@ -40,7 +40,7 @@ Dashboard.template.screenPresets.Null = Template screenPresets cannot be null
Dashboard.screenPreset.displayName.NotBlank = ScreenPreset displayName cannot be empty
Dashboard.screenPreset.breakpoint.Min = ScreenPreset breakpoint cannot be empty nor set to 0
Dashboard.screenPreset.scalingPreset.NotNull = ScreenPreset scalingPreset cannot be null
-Dashboard.widget.displayName.NotBlank = Widget displayName cannot be empty
+Dashboard.widget.displayName.NotNull = Widget displayName cannot be null
Dashboard.widget.gridItem.NotNull = Widget gridItem cannot be null
Dashboard.widget.widgetTypeId.NotNull = Widget widgetTypeId cannot be null
Dashboard.gridItem.w.Min = GridItem w (width) cannot be empty nor set to 0
diff --git a/ui/component/or-asset-tree/src/index.ts b/ui/component/or-asset-tree/src/index.ts
index 2149dddb4..5f9cd4622 100644
--- a/ui/component/or-asset-tree/src/index.ts
+++ b/ui/component/or-asset-tree/src/index.ts
@@ -43,6 +43,7 @@ import {
import {OrAddAssetDialog, OrAddChangedEvent} from "./or-add-asset-dialog";
import "./or-add-asset-dialog";
import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
+import { when } from "lit/directives/when.js";
export interface AssetTreeTypeConfig {
include?: string[];
@@ -274,15 +275,15 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
@property({type: Array})
public _assetIdsOverride?: string[];
- @property({type: Array})
- public _assetTypeOptions?: string[];
-
@property({type: Array})
public rootAssets?: Asset[];
@property({type: Array})
public rootAssetIds?: string[];
+ @property({type: Object})
+ public dataProvider?: () => Promise<Asset[]>;
+
@property({type: Boolean})
public readonly: boolean = false;
@@ -301,6 +302,9 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
@property({type: Boolean})
public showSortBtn?: boolean = true;
+ @property({type: Boolean})
+ public showFilter: boolean = true;
+
@property({type: String})
public sortBy?: string = "name";
@@ -463,105 +467,107 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
</div>
</div>
- <div id="asset-tree-filter">
- <or-mwc-input id="filterInput"
- ?disabled="${this._loading}"
- style="width: 100%;"
- type="${ InputType.TEXT }"
- placeholder="${i18next.t("filter.filter")}..."
- compact="true"
- outlined="true"
- @input="${(e: KeyboardEvent) => {
- // Means some input is occurring so delay filter
- this._onFilterInputEvent(e);
- }}"
- @or-mwc-input-changed="${ (e: OrInputChangedEvent) => {
- // Means field has lost focus so do filter immediately
- this._onFilterInput((e.detail.value as string) || undefined, true);
- }}">
- </or-mwc-input>
- <or-icon id="filterSettingsIcon" icon="${this._filterSettingOpen ? "window-close" : "tune"}" @click="${() => {
- if (this._filterSettingOpen) {
- this._filterSettingOpen = false;
- } else {
- this._filterSettingOpen = true;
- // Avoid to build again the types
- if ( this._assetTypes.length === 0 ) {
- let usedTypes: string[] = [];
- const types = this._getAllowedChildTypes(this._selectedNodes[0]);
- this._assetTypes = types.filter((t) => t.descriptorType === "asset");
- }
-
- if (this._filter.attribute.length > 0) {
- this._attributeNameFilter.value = this._filter.attribute[0];
- }
-
- if (this._filter.attributeValue.length > 0 && this._filter.attribute.length > 0) {
- this._attributeValueFilter.disabled = false;
- this._attributeValueFilter.value = this._filter.attributeValue[0];
- }
-
- if (this._filter.assetType.length > 0) {
- this._assetTypeFilter = this._filter.assetType[0];
- } else {
- this._assetTypeFilter = '';
- }
- }
- }}"></or-icon>
- </div>
- <div id="asset-tree-filter-setting" class="${this._filterSettingOpen ? "visible" : ""}">
- <div class="advanced-filter">
- ${this._assetTypes.length > 0 ? getContentWithMenuTemplate(
- this.assetTypeSelect(),
- this.mapDescriptors(this._assetTypes, { text: i18next.t("filter.assetTypeMenuNone"), value: "", icon: "selection-ellipse" }),
- undefined,
- (v: string[] | string) => {
- this._assetTypeFilter = (v as string);
- },
- undefined,
- false,
- true,
- true) : html ``
- }
- <or-mwc-input id="attributeNameFilter" .label="${i18next.t("filter.attributeLabel")}"
-
- .type="${InputType.TEXT}"
- style="margin-top: 10px;"
+ ${when(this.showFilter, () => html`
+ <div id="asset-tree-filter">
+ <or-mwc-input id="filterInput"
?disabled="${this._loading}"
+ style="width: 100%;"
+ type="${InputType.TEXT}"
+ placeholder="${i18next.t("filter.filter")}..."
+ compact="true"
+ outlined="true"
@input="${(e: KeyboardEvent) => {
- this._shouldEnableAttrTypeEvent(e);
+ // Means some input is occurring so delay filter
+ this._onFilterInputEvent(e);
}}"
- @or-mwc-input-changed="${ (e: OrInputChangedEvent) => {
- this._shouldEnableAttrType((e.detail.value as string) || undefined);
- }}"></or-mwc-input>
- <or-mwc-input id="attributeValueFilter" .label="${i18next.t("filter.attributeValueLabel")}"
-
- .type="${InputType.TEXT}"
- style="margin-top: 10px;"
- disabled></or-mwc-input>
- <div style="margin-top: 10px;">
- <or-mwc-input style="float:left;" type="${ InputType.BUTTON }" .label="${i18next.t("filter.clear")}" @or-mwc-input-changed="${() => {
- // Wipe the current value and hide the clear button
- this._filterInput.value = undefined;
-
- this._attributeValueFilter.value = undefined;
- this._attributeNameFilter.value = undefined;
-
- this._attributeValueFilter.disabled = true;
-
- this._assetTypeFilter = '';
-
- this._filter = new OrAssetTreeFilter();
-
- // Call filtering
- this._doFiltering();
- }}"></or-mwc-input>
- <or-mwc-input style="float: right;" type="${ InputType.BUTTON }" .label="${i18next.t("filter.action")}" raised @or-mwc-input-changed="${() => {
- this._filterFromSettings();
- }}"></or-mwc-input>
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
+ // Means field has lost focus so do filter immediately
+ this._onFilterInput((e.detail.value as string) || undefined, true);
+ }}">
+ </or-mwc-input>
+ <or-icon id="filterSettingsIcon" icon="${this._filterSettingOpen ? "window-close" : "tune"}" @click="${() => {
+ if (this._filterSettingOpen) {
+ this._filterSettingOpen = false;
+ } else {
+ this._filterSettingOpen = true;
+ // Avoid to build again the types
+ if (this._assetTypes.length === 0) {
+ let usedTypes: string[] = [];
+ const types = this._getAllowedChildTypes(this._selectedNodes[0]);
+ this._assetTypes = types.filter((t) => t.descriptorType === "asset");
+ }
+
+ if (this._filter.attribute.length > 0) {
+ this._attributeNameFilter.value = this._filter.attribute[0];
+ }
+
+ if (this._filter.attributeValue.length > 0 && this._filter.attribute.length > 0) {
+ this._attributeValueFilter.disabled = false;
+ this._attributeValueFilter.value = this._filter.attributeValue[0];
+ }
+
+ if (this._filter.assetType.length > 0) {
+ this._assetTypeFilter = this._filter.assetType[0];
+ } else {
+ this._assetTypeFilter = '';
+ }
+ }
+ }}"></or-icon>
+ </div>
+ <div id="asset-tree-filter-setting" class="${this._filterSettingOpen ? "visible" : ""}">
+ <div class="advanced-filter">
+ ${this._assetTypes.length > 0 ? getContentWithMenuTemplate(
+ this.assetTypeSelect(),
+ this.mapDescriptors(this._assetTypes, {text: i18next.t("filter.assetTypeMenuNone"), value: "", icon: "selection-ellipse"}),
+ undefined,
+ (v: string[] | string) => {
+ this._assetTypeFilter = (v as string);
+ },
+ undefined,
+ false,
+ true,
+ true) : html``
+ }
+ <or-mwc-input id="attributeNameFilter" .label="${i18next.t("filter.attributeLabel")}"
+
+ .type="${InputType.TEXT}"
+ style="margin-top: 10px;"
+ ?disabled="${this._loading}"
+ @input="${(e: KeyboardEvent) => {
+ this._shouldEnableAttrTypeEvent(e);
+ }}"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
+ this._shouldEnableAttrType((e.detail.value as string) || undefined);
+ }}"></or-mwc-input>
+ <or-mwc-input id="attributeValueFilter" .label="${i18next.t("filter.attributeValueLabel")}"
+
+ .type="${InputType.TEXT}"
+ style="margin-top: 10px;"
+ disabled></or-mwc-input>
+ <div style="margin-top: 10px;">
+ <or-mwc-input style="float:left;" type="${InputType.BUTTON}" .label="${i18next.t("filter.clear")}" @or-mwc-input-changed="${() => {
+ // Wipe the current value and hide the clear button
+ this._filterInput.value = undefined;
+
+ this._attributeValueFilter.value = undefined;
+ this._attributeNameFilter.value = undefined;
+
+ this._attributeValueFilter.disabled = true;
+
+ this._assetTypeFilter = '';
+
+ this._filter = new OrAssetTreeFilter();
+
+ // Call filtering
+ this._doFiltering();
+ }}"></or-mwc-input>
+ <or-mwc-input style="float: right;" type="${InputType.BUTTON}" .label="${i18next.t("filter.action")}" raised @or-mwc-input-changed="${() => {
+ this._filterFromSettings();
+ }}"></or-mwc-input>
+ </div>
</div>
</div>
- </div>
+ `)}
${!this._nodes
? html`
@@ -798,7 +804,8 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
canSelect = this.config.select.types.indexOf(node.asset!.type!) >= 0;
}
- if (!canSelect) {
+ // If node cannot be selected, and it is not the 'select all of this parent'-checkbox, cancel it.
+ if (!canSelect && !isParentCheckbox) {
return;
}
@@ -824,7 +831,14 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
const childNodes: UiAssetTreeNode[] = [];
OrAssetTree._forEachNodeRecursive(node.children, (childNode) => {
- childNodes.push(childNode);
+ let canSelectChild = true;
+ // If not of required asset type, cancel selection of the child
+ if(childNode && this.config?.select?.types) {
+ canSelectChild = this.config.select.types.indexOf(childNode.asset!.type!) >= 0;
+ }
+ if(canSelectChild) {
+ childNodes.push(childNode);
+ }
});
// based on multiple-box already selected, remove or add to array of selected nodes
@@ -1591,35 +1605,43 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
this._loading = true;
- const query: AssetQuery = {
- realm: {
- name: manager.displayRealm
- },
- select: { // Just need the basic asset info
- attributes: []
- }
- };
+ if(this.dataProvider) {
+ this.dataProvider().then(assets => {
+ this._loading = false;
+ this._buildTreeNodes(assets, sortFunction);
+ })
- if (this.assetIds) {
- query.ids = this.assetIds;
- query.recursive = true;
- } else if (this.rootAssets) {
- query.ids = this.rootAssets.map((asset) => asset.id!);
- query.recursive = true;
- } else if (this.rootAssetIds) {
- query.ids = this.rootAssetIds;
- query.recursive = true;
- }
- this._sendEventWithReply({
- event: {
- eventType: "read-assets",
- assetQuery: query
+ } else {
+
+ const query: AssetQuery = {
+ realm: {
+ name: manager.displayRealm
+ },
+ select: { // Just need the basic asset info
+ attributes: []
+ }
+ };
+
+ if (this.assetIds) {
+ query.ids = this.assetIds;
+ query.recursive = true;
+ } else if (this.rootAssets) {
+ query.ids = this.rootAssets.map((asset) => asset.id!);
+ query.recursive = true;
+ } else if (this.rootAssetIds) {
+ query.ids = this.rootAssetIds;
+ query.recursive = true;
}
- })
- .then((ev) => {
+ this._sendEventWithReply({
+ event: {
+ eventType: "read-assets",
+ assetQuery: query
+ }
+ }).then((ev) => {
this._loading = false;
this._buildTreeNodes((ev as AssetsEvent).assets!, sortFunction)
});
+ }
} else {
this._loading = false;
this._buildTreeNodes(this.assets, sortFunction);
diff --git a/ui/component/or-chart/src/index.ts b/ui/component/or-chart/src/index.ts
index ce787adda..cc00d7c1c 100644
--- a/ui/component/or-chart/src/index.ts
+++ b/ui/component/or-chart/src/index.ts
@@ -38,7 +38,7 @@ import {
Title,
Tooltip
} from "chart.js";
-import {InputType} from "@openremote/or-mwc-components/or-mwc-input";
+import {InputType, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";
import "@openremote/or-components/or-loading-indicator";
import moment from "moment";
import {OrAssetTreeSelectionEvent} from "@openremote/or-asset-tree";
@@ -47,12 +47,13 @@ import ChartAnnotation, {AnnotationOptions} from "chartjs-plugin-annotation";
import "chartjs-adapter-moment";
import {GenericAxiosResponse} from "@openremote/rest";
import {OrAttributePicker, OrAttributePickerPickedEvent} from "@openremote/or-attribute-picker";
-import {showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {OrMwcDialog, showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
import {cache} from "lit/directives/cache.js";
import {throttle} from "lodash";
import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";
import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
import { when } from "lit/directives/when.js";
+import {createRef, Ref, ref } from "lit/directives/ref.js";
Chart.register(LineController, ScatterController, LineElement, PointElement, LinearScale, TimeScale, Title, Filler, Legend, Tooltip, ChartAnnotation);
@@ -398,6 +399,9 @@ export class OrChart extends translate(i18next)(LitElement) {
@property()
public attributeControls: boolean = true;
+ @property()
+ public timeframe?: [Date, Date];
+
@property()
public timestampControls: boolean = true;
@@ -464,8 +468,8 @@ export class OrChart extends translate(i18next)(LitElement) {
}
}
- const reloadData = changedProperties.has("datapointQuery") || changedProperties.has("timePresetKey") || changedProperties.has("rightAxisAttributes") ||
- changedProperties.has("assetAttributes") || changedProperties.has("realm") || changedProperties.has("dataProvider");
+ const reloadData = changedProperties.has("datapointQuery") || changedProperties.has("timePresetKey") || changedProperties.has("timeframe") ||
+ changedProperties.has("rightAxisAttributes") || changedProperties.has("assetAttributes") || changedProperties.has("realm") || changedProperties.has("dataProvider");
if (reloadData) {
this._data = undefined;
@@ -607,7 +611,7 @@ export class OrChart extends translate(i18next)(LitElement) {
container.style.flexDirection = bottomLegend ? 'column' : 'row';
const periodControls = this.shadowRoot.querySelector('.period-controls') as HTMLElement;
if(periodControls) {
- periodControls.style.justifyContent = bottomLegend ? 'center' : 'start';
+ periodControls.style.justifyContent = bottomLegend ? 'center' : 'space-between';
periodControls.style.paddingLeft = bottomLegend ? '' : '18px';
}
const attributeList = this.shadowRoot.getElementById('attribute-list');
@@ -647,20 +651,43 @@ export class OrChart extends translate(i18next)(LitElement) {
${this.timePresetOptions && this.timePresetKey ? html`
${this.timestampControls ? html`
${getContentWithMenuTemplate(
- html`<or-mwc-input .type="${InputType.BUTTON}" .label="${i18next.t(this.timePresetKey)}"></or-mwc-input>`,
+ html`<or-mwc-input .type="${InputType.BUTTON}" .label="${this.timeframe ? i18next.t('Custom') : i18next.t(this.timePresetKey)}"></or-mwc-input>`,
Array.from(this.timePresetOptions!.keys()).map((key) => ({ value: key } as ListItem)),
this.timePresetKey,
- (value: string | string[]) => this.timePresetKey = value.toString(),
+ (value: string | string[]) => {
+ this.timeframe = undefined; // remove any custom start & end times
+ this.timePresetKey = value.toString();
+ },
undefined,
undefined,
undefined,
true
)}
+ <!-- Button that opens custom time selection -->
+ <or-mwc-input .type="${InputType.BUTTON}" icon="calendar-clock" @or-mwc-input-changed="${() => this._openTimeDialog(this._startOfPeriod, this._endOfPeriod)}"></or-mwc-input>
` : html`
<or-mwc-input .type="${InputType.BUTTON}" .label="${i18next.t(this.timePresetKey)}" disabled="true"></or-mwc-input>
`}
` : undefined}
</div>
+ ${this.timeframe ? html`
+ <div style="margin-left: 18px; font-size: 12px;">
+ <table style="width: 100%;">
+ <thead>
+ <tr>
+ <th style="font-weight: normal; text-align: left;">${i18next.t('from')}:</th>
+ <th style="font-weight: normal; text-align: left;">${moment(this.timeframe[0]).format("L HH:mm")}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>${i18next.t('to')}:</td>
+ <td>${moment(this.timeframe[1]).format("L HH:mm")}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ ` : undefined}
${this.attributeControls ? html`
<or-mwc-input class="button" .type="${InputType.BUTTON}" ?disabled="${disabled}" label="${i18next.t("selectAttributes")}" icon="plus" @or-mwc-input-changed="${() => this._openDialog()}"></or-mwc-input>
` : undefined}
@@ -870,7 +897,7 @@ export class OrChart extends translate(i18next)(LitElement) {
manager.console.storeData("OrChartConfig", [...allConfigs.filter(e => e.realm !== this.realm), config]);
}
- _openDialog() {
+ protected _openDialog() {
const dialog = showDialog(new OrAttributePicker()
.setShowOnlyDatapointAttrs(true)
.setMultiSelect(true)
@@ -879,6 +906,32 @@ export class OrChart extends translate(i18next)(LitElement) {
dialog.addEventListener(OrAttributePickerPickedEvent.NAME, (ev: any) => this._addAttribute(ev.detail));
}
+ protected _openTimeDialog(startTimestamp?: number, endTimestamp?: number) {
+ const startRef: Ref<OrMwcInput> = createRef();
+ const endRef: Ref<OrMwcInput> = createRef();
+ const dialog = showDialog(new OrMwcDialog()
+ .setHeading(i18next.t('timeframe'))
+ .setContent(() => html`
+ <div>
+ <or-mwc-input ${ref(startRef)} type="${InputType.DATETIME}" required label="${i18next.t('start')}" .value="${startTimestamp}"></or-mwc-input>
+ <or-mwc-input ${ref(endRef)} type="${InputType.DATETIME}" required label="${i18next.t('ending')}" .value="${endTimestamp}"></or-mwc-input>
+ </div>
+ `)
+ .setActions([{
+ actionName: "cancel",
+ content: i18next.t('cancel')
+ }, {
+ actionName: "ok",
+ content: i18next.t('ok'),
+ action: () => {
+ if(this.timePresetOptions && startRef.value?.value && endRef.value?.value) {
+ this.timeframe = [new Date(startRef.value.value), new Date(endRef.value.value)];
+ }
+ }
+ }])
+ )
+ }
+
protected async _addAttribute(selectedAttrs?: AttributeRef[]) {
if (!selectedAttrs) return;
@@ -1020,8 +1073,8 @@ export class OrChart extends translate(i18next)(LitElement) {
this._loading = true;
const dates: [Date, Date] = this.timePresetOptions!.get(this.timePresetKey!)!(new Date());
- this._startOfPeriod = dates[0].getTime();
- this._endOfPeriod = dates[1].getTime();
+ this._startOfPeriod = this.timeframe ? this.timeframe[0].getTime() : dates[0].getTime();
+ this._endOfPeriod = this.timeframe ? this.timeframe[1].getTime() : dates[1].getTime();
const diffInHours = (this._endOfPeriod - this._startOfPeriod) / 1000 / 60 / 60;
const intervalArr = this._getInterval(diffInHours);
diff --git a/ui/component/or-dashboard-builder/src/index.ts b/ui/component/or-dashboard-builder/src/index.ts
index d286ee024..c5e899453 100644
--- a/ui/component/or-dashboard-builder/src/index.ts
+++ b/ui/component/or-dashboard-builder/src/index.ts
@@ -28,6 +28,8 @@ import {IntervalSelectEvent, intervalToMillis} from "./controls/dashboard-refres
import {ImageWidget} from "./widgets/image-widget";
import {KpiWidget} from "./widgets/kpi-widget";
import {MapWidget} from "./widgets/map-widget";
+import {AttributeInputWidget} from "./widgets/attribute-input-widget";
+import {TableWidget} from "./widgets/table-widget";
// language=CSS
const styling = css`
@@ -212,6 +214,8 @@ export function registerWidgetTypes() {
widgetTypes.set("image", ImageWidget.getManifest());
widgetTypes.set("kpi", KpiWidget.getManifest());
widgetTypes.set("map", MapWidget.getManifest());
+ widgetTypes.set("attributeinput", AttributeInputWidget.getManifest());
+ widgetTypes.set("table", TableWidget.getManifest());
}
@customElement("or-dashboard-builder")
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts b/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts
index d507b7c7c..c5516390d 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts
@@ -66,8 +66,10 @@ export class OrDashboardBrowser extends LitElement {
protected renderGrid() {
const sidebarElement = this.shadowRoot?.getElementById("sidebarElement");
const coords: Array<[number, number]> = new Array<[number, number]>([0,0],[2,0], [0,2], [2,2], [0,4], [2,4], [0,6], [2,6], [0,8], [2,8]) // TODO: make this unlimited possibilities with a formula
- const sidebarItems: any[] = Array.from(widgetTypes).map((typeArr, index) => {
- return {x: coords[index][0], y: coords[index][1], w: 2, h: 2, widgetTypeId: typeArr[0], locked: true, content: `<div class="sidebarItem"><or-icon icon="${typeArr[1].displayIcon}"></or-icon><span class="itemText">${typeArr[1].displayName}</span>`}
+ const sidebarItems: any[] = Array.from(widgetTypes)
+ .sort((a, b) => a[1].displayName.localeCompare(b[1].displayName))
+ .map((typeArr, index) => {
+ return {x: coords[index][0], y: coords[index][1], w: 2, h: 2, widgetTypeId: typeArr[0], locked: true, content: `<div class="sidebarItem"><or-icon icon="${typeArr[1].displayIcon}"></or-icon><span class="itemText">${typeArr[1].displayName}</span>`}
});
// Setting Sidebar height depending on sidebarItems
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts b/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts
index 529fab5d6..98003f2a5 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts
@@ -562,7 +562,7 @@ export class OrDashboardPreview extends LitElement {
this.onGridItemClick(widget.gridItem);
}}">
<div class="grid-stack-item-content" style="display: flex;">
- <or-dashboard-widget-container .widget="${widget}" style="width: 100%; height: auto; border-radius: 4px;"></or-dashboard-widget-container>
+ <or-dashboard-widget-container .widget="${widget}" .editMode="${this.editMode}" style="width: 100%; height: auto; border-radius: 4px;"></or-dashboard-widget-container>
</div>
</div>
`
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-widgetcontainer.ts b/ui/component/or-dashboard-builder/src/or-dashboard-widgetcontainer.ts
index bfffdbea5..aca3266c7 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-widgetcontainer.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-widgetcontainer.ts
@@ -21,6 +21,9 @@ export class OrDashboardWidgetContainer extends LitElement {
@property()
protected readonly widget!: DashboardWidget;
+ @property()
+ protected readonly editMode!: boolean;
+
@property()
protected loading: boolean = false;
@@ -107,11 +110,19 @@ export class OrDashboardWidgetContainer extends LitElement {
}
protected initializeWidgetElem(manifest: WidgetManifest, config: WidgetConfig) {
- console.log(`Initialising ${manifest.displayName} widget..`);
+ console.debug(`Initialising ${manifest.displayName} widget..`);
if (this.orWidget) {
this.orWidget.remove();
}
this.orWidget = manifest.getContentHtml(config);
+ this.orWidget.getDisplayName = () => this.widget.displayName;
+ this.orWidget.getEditMode = () => this.editMode
+ this.orWidget.getWidgetLocation = () => ({
+ x: this.widget.gridItem?.x,
+ y: this.widget.gridItem?.y,
+ w: this.widget.gridItem?.w,
+ h: this.widget.gridItem?.h
+ });
}
protected render() {
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.ts b/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.ts
index 412fbe095..0b523373b 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.ts
@@ -41,9 +41,7 @@ export class OrDashboardWidgetsettings extends LitElement {
<div style="padding: 12px;">
<div>
<or-mwc-input .type="${InputType.TEXT}" style="width: 100%;" .value="${this.selectedWidget?.displayName}" label="${i18next.t('name')}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- this.selectedWidget!.displayName = event.detail.value;
- this.forceParentUpdate(new Map<string, any>([['widget', this.selectedWidget]])); }}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => this.setDisplayName(event.detail.value)}"
></or-mwc-input>
</div>
</div>
@@ -55,6 +53,11 @@ export class OrDashboardWidgetsettings extends LitElement {
`;
}
+ protected setDisplayName(name?: string) {
+ this.selectedWidget!.displayName = name;
+ this.forceParentUpdate(new Map<string, any>([['widget', this.selectedWidget]]));
+ }
+
protected async generateContent(widgetTypeId: string): Promise<TemplateResult> {
if(!this.settingsElem || this.settingsElem.id !== this.selectedWidget.id) {
const manifest = WidgetService.getManifest(widgetTypeId);
@@ -68,6 +71,15 @@ export class OrDashboardWidgetsettings extends LitElement {
protected initSettings(manifest: WidgetManifest): WidgetSettings {
const settingsElem = manifest.getSettingsHtml(this.selectedWidget!.widgetConfig);
settingsElem.id = this.selectedWidget.id!;
+ settingsElem.getDisplayName = () => this.selectedWidget.displayName;
+ settingsElem.setDisplayName = (name?: string) => this.setDisplayName(name);
+ settingsElem.getEditMode = () => true;
+ settingsElem.getWidgetLocation = () => ({
+ x: this.selectedWidget.gridItem?.x,
+ y: this.selectedWidget.gridItem?.y,
+ w: this.selectedWidget.gridItem?.w,
+ h: this.selectedWidget.gridItem?.h
+ });
settingsElem.addEventListener(WidgetSettingsChangedEvent.NAME, (ev: any) => this.onWidgetConfigChange(ev));
return settingsElem;
}
diff --git a/ui/component/or-dashboard-builder/src/panels/assettypes-panel.ts b/ui/component/or-dashboard-builder/src/panels/assettypes-panel.ts
index 9fdb79cac..2814f5938 100644
--- a/ui/component/or-dashboard-builder/src/panels/assettypes-panel.ts
+++ b/ui/component/or-dashboard-builder/src/panels/assettypes-panel.ts
@@ -1,11 +1,15 @@
import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
import {customElement, property, state} from "lit/decorators.js";
-import {AssetDescriptor, AssetModelUtil, AssetTypeInfo} from "@openremote/model";
+import {Asset, AssetDescriptor, AssetModelUtil, AssetQuery, AssetTypeInfo} from "@openremote/model";
import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";
import {i18next} from "@openremote/or-translate";
import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
-import {Util} from "@openremote/core";
+import manager, {Util} from "@openremote/core";
+import {when} from "lit/directives/when.js";
+import {createRef, Ref, ref} from 'lit/directives/ref.js';
+import {AssetTreeConfig, OrAssetTree} from "@openremote/or-asset-tree";
+import {OrMwcDialog, showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
export class AssetTypeSelectEvent extends CustomEvent<string> {
@@ -20,42 +24,41 @@ export class AssetTypeSelectEvent extends CustomEvent<string> {
}
}
-export class AttributeNameSelectEvent extends CustomEvent<string> {
+export class AssetIdsSelectEvent extends CustomEvent<string | string[]> {
- public static readonly NAME = "attributename-select";
+ public static readonly NAME = "assetids-select"
- constructor(attributeName: string) {
- super(AttributeNameSelectEvent.NAME, {
+ constructor(assetIds: string | string[]) {
+ super(AssetIdsSelectEvent.NAME, {
bubbles: true,
composed: true,
- detail: attributeName
+ detail: assetIds
});
}
}
-export class ShowLabelsToggleEvent extends CustomEvent<boolean> {
+export class AttributeNamesSelectEvent extends CustomEvent<string | string[]> {
- public static readonly NAME = "showlabels-toggle";
+ public static readonly NAME = "attributenames-select";
- constructor(state: boolean) {
- super(ShowLabelsToggleEvent.NAME, {
+ constructor(attributeNames: string | string[]) {
+ super(AttributeNamesSelectEvent.NAME, {
bubbles: true,
composed: true,
- detail: state
+ detail: attributeNames
});
}
}
-export class ShowUnitsToggleEvent extends CustomEvent<boolean> {
-
- public static readonly NAME = "showunits-toggle";
-
- constructor(state: boolean) {
- super(ShowUnitsToggleEvent.NAME, {
- bubbles: true,
- composed: true,
- detail: state
- });
+export interface AssetTypesFilterConfig {
+ assets?: {
+ enabled?: boolean,
+ multi?: boolean
+ },
+ attributes?: {
+ enabled?: boolean,
+ multi?: boolean,
+ valueTypes?: string[]
}
}
@@ -70,27 +73,30 @@ const styling = css`
@customElement("assettypes-panel")
export class AssettypesPanel extends LitElement {
- @property()
+ @property() // selected asset type
protected assetType?: string;
@property()
- protected attributeName?: string;
+ protected config: AssetTypesFilterConfig = {
+ attributes: {
+ enabled: true
+ }
+ }
- @property()
- protected attributeList: string[][] = [];
+ @property() // IDs of assets; either undefined, a single entry, or multi select
+ protected assetIds: undefined | string | string[];
- @property()
- protected showLabels!: boolean;
+ @property() // names of selected attributes; either undefined, a single entry, or multi select
+ protected attributeNames: undefined | string | string[];
- @property()
- protected showUnits!: boolean;
+ /* ----------- */
- @property()
- protected valueTypes: string[] = [];
+ @state()
+ protected _attributeSelectList: string[][] = [];
@state()
protected _loadedAssetTypes: AssetDescriptor[] = AssetModelUtil.getAssetDescriptors().filter((t) => t.descriptorType === "asset");
-;
+
static get styles() {
return [styling];
@@ -99,27 +105,22 @@ export class AssettypesPanel extends LitElement {
protected willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
if (changedProps.has("assetType") && this.assetType) {
- this.attributeList = this.getAttributesByType(this.assetType)!;
+ this._attributeSelectList = this.getAttributesByType(this.assetType)!;
this.dispatchEvent(new AssetTypeSelectEvent(this.assetType));
}
- if (changedProps.has("attributeName") && this.attributeName) {
- this.dispatchEvent(new AttributeNameSelectEvent(this.attributeName));
- }
- if (changedProps.has("showLabels")) {
- this.dispatchEvent(new ShowLabelsToggleEvent(this.showLabels));
+ if (changedProps.has("assetIds") && this.assetIds) {
+ this.dispatchEvent(new AssetIdsSelectEvent(this.assetIds));
}
- if (changedProps.has("showUnits")) {
- this.dispatchEvent(new ShowUnitsToggleEvent(this.showUnits));
+ if (changedProps.has("attributeNames") && this.attributeNames) {
+ this.dispatchEvent(new AttributeNamesSelectEvent(this.attributeNames));
}
}
protected render(): TemplateResult {
- const options: [string, string][] = this.attributeList.map(al => [al[0], al[1]]);
- const searchProvider: (search?: string) => Promise<[any, string][]> = async (search) => {
- return search ? options.filter(o => o[1].toLowerCase().includes(search.toLowerCase())) : options;
- };
return html`
<div style="display: flex; flex-direction: column; gap: 8px;">
+
+ <!-- Select asset type -->
<div>
${this._loadedAssetTypes.length > 0 ? getContentWithMenuTemplate(
this.getAssetTypeTemplate(),
@@ -139,39 +140,44 @@ export class AssettypesPanel extends LitElement {
true) : html``
}
</div>
- <div>
- <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t("filter.attributeLabel")}" .disabled="${!this.assetType}" style="width: 100%;"
- .options="${options}" .searchProvider="${searchProvider}" .value="${this.attributeName}"
- @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
- this.attributeName = ev.detail.value;
- }}"
- ></or-mwc-input>
- </div>
- <div>
- <div class="switchMwcInputContainer">
- <span>${i18next.t("dashboard.showLabels")}</span>
- <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
- .value="${this.showLabels}" .disabled="${!this.assetType}"
- @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
- this.showLabels = ev.detail.value;
- }}"
- ></or-mwc-input>
- </div>
- <div class="switchMwcInputContainer">
- <span>${i18next.t("dashboard.showUnits")}</span>
- <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
- .value="${this.showUnits}" .disabled="${!this.showLabels || !this.assetType}"
- @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
- this.showUnits = ev.detail.value;
- }}"
- ></or-mwc-input>
- </div>
- </div>
+ <!-- Select one or more assets -->
+ ${when(this.config.assets?.enabled, () => {
+ const assetIds = (typeof this.assetIds === 'string') ? [this.assetIds] : this.assetIds;
+ return html`
+ <div>
+ <or-mwc-input .type="${InputType.BUTTON}" .label="${(this.assetIds?.length || 0) + ' ' + i18next.t('assets')}" .disabled="${!this.assetType}" fullWidth outlined comfortable style="width: 100%;"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this._openAssetSelector(this.assetType!, assetIds, this.config.assets?.multi)}"
+ ></or-mwc-input>
+ </div>
+ `;
+ })}
+
+ <!-- Select one or more attributes -->
+ ${when(this.config.attributes?.enabled, () => {
+ const options: [string, string][] = this._attributeSelectList.map(al => [al[0], al[1]]);
+ const searchProvider: (search?: string) => Promise<[any, string][]> = async (search) => {
+ return search ? options.filter(o => o[1].toLowerCase().includes(search.toLowerCase())) : options;
+ };
+ return html`
+ <div>
+ <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t("filter.attributeLabel")}" .disabled="${!this.assetType}" style="width: 100%;"
+ .options="${options}" .searchProvider="${searchProvider}" .multiple="${this.config.attributes?.multi}" .value="${this.attributeNames as string}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ this.attributeNames = ev.detail.value;
+ }}"
+ ></or-mwc-input>
+ </div>
+ `
+
+ })}
</div>
`;
}
+
+ /* ----------- */
+
protected getAssetTypeTemplate(): TemplateResult {
if (this.assetType) {
const descriptor: AssetDescriptor | undefined = this._loadedAssetTypes.find((at: AssetDescriptor) => at.name === this.assetType);
@@ -227,8 +233,9 @@ export class AssettypesPanel extends LitElement {
if (descriptor) {
const typeInfo: AssetTypeInfo = (AssetModelUtil.getAssetTypeInfo(descriptor) as AssetTypeInfo);
if (typeInfo?.attributeDescriptors) {
- return typeInfo.attributeDescriptors
- .filter((ad) => this.valueTypes.indexOf(ad.type!) > -1)
+ const valueTypes = this.config.attributes?.valueTypes;
+ const filtered = valueTypes ? typeInfo.attributeDescriptors.filter(ad => valueTypes.indexOf(ad.type!) > -1) : typeInfo.attributeDescriptors;
+ return filtered
.map((ad) => {
const label = Util.getAttributeLabel(ad, undefined, type, false);
return [ad.name!, label];
@@ -238,4 +245,67 @@ export class AssettypesPanel extends LitElement {
}
}
+ protected _openAssetSelector(assetType: string, assetIds?: string[], multi = false) {
+ const assetTreeRef: Ref<OrAssetTree> = createRef();
+ const config = {
+ select: {
+ types: [assetType],
+ multiSelect: multi
+ }
+ } as AssetTreeConfig
+ const dialog = showDialog(new OrMwcDialog()
+ .setHeading(i18next.t("linkedAssets"))
+ .setContent(html`
+ <div style="width: 400px;">
+ <or-asset-tree ${ref(assetTreeRef)} .dataProvider="${this.assetTreeDataProvider}" expandAllNodes
+ id="chart-asset-tree" readonly .config="${config}" .selectedIds="${assetIds}"
+ .showSortBtn="${false}" .showFilter="${false}" .checkboxes="${multi}"
+ ></or-asset-tree>
+ </div>
+ `)
+ .setActions([
+ {
+ default: true,
+ actionName: "cancel",
+ content: i18next.t("cancel"),
+ },
+ {
+ actionName: "ok",
+ content: i18next.t("ok"),
+ action: () => {
+ const tree = assetTreeRef.value;
+ if(tree?.selectedIds) {
+ if(multi) {
+ this.assetIds = tree.selectedIds;
+ } else {
+ this.assetIds = tree.selectedIds[0];
+ }
+ }
+ }
+ }
+ ])
+ .setDismissAction({
+ actionName: "cancel",
+ }));
+ }
+
+ protected assetTreeDataProvider = async (): Promise<Asset[]> => {
+ const assetQuery: AssetQuery = {
+ realm: {
+ name: manager.displayRealm
+ },
+ select: { // Just need the basic asset info
+ attributes: []
+ }
+ };
+ // At first, just fetch all accessible assets without attribute info...
+ const assets = (await manager.rest.api.AssetResource.queryAssets(assetQuery)).data;
+
+ // After fetching, narrow down the list to assets with the same assetType.
+ // Since it is a tree, we also include the parents of those assets, based on the 'asset.path' variable.
+ const pathsOfAssetType = assets.filter(a => a.type === this.assetType).map(a => a.path!);
+ const filteredAssetIds = [...new Set([].concat(...pathsOfAssetType as any[]))] as string[];
+ return assets.filter(a => filteredAssetIds.includes(a.id!));
+ }
+
}
diff --git a/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts b/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts
index 94dcd9c97..971031576 100644
--- a/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts
+++ b/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts
@@ -19,15 +19,16 @@ export interface AttributeAction {
disabled: boolean
}
-export class AttributeActionEvent extends CustomEvent<{ attributeRef: AttributeRef, action: AttributeAction }> {
+export class AttributeActionEvent extends CustomEvent<{ asset: Asset, attributeRef: AttributeRef, action: AttributeAction }> {
public static readonly NAME = "attribute-action"
- constructor(attributeRef: AttributeRef, action: AttributeAction) {
+ constructor(asset: Asset, attributeRef: AttributeRef, action: AttributeAction) {
super(AttributeActionEvent.NAME, {
bubbles: true,
composed: true,
detail: {
+ asset: asset,
attributeRef: attributeRef,
action: action
}
@@ -35,15 +36,18 @@ export class AttributeActionEvent extends CustomEvent<{ attributeRef: AttributeR
}
}
-export class AttributesSelectEvent extends CustomEvent<AttributeRef[]> {
+export class AttributesSelectEvent extends CustomEvent<{ assets: Asset[], attributeRefs: AttributeRef[] }> {
public static readonly NAME = "attribute-select";
- constructor(attributeRefs: AttributeRef[]) {
+ constructor(assets: Asset[], attributeRefs: AttributeRef[]) {
super(AttributesSelectEvent.NAME, {
bubbles: true,
composed: true,
- detail: attributeRefs
+ detail: {
+ assets: assets,
+ attributeRefs: attributeRefs
+ }
});
}
}
@@ -166,13 +170,14 @@ export class AttributesPanel extends LitElement {
this.attributeRefs = [];
}
if (changedProps.has("attributeRefs") && this.attributeRefs) {
- if(this.attributeRefs.filter(ar => !this.getLoadedAsset(ar)).length > 0) {
- this.loadAssets(this.attributeRefs);
- }
- // Only dispatch event when it CHANGED, so not from 'undefined' to [];
- if(changedProps.get("attributeRefs")) {
- this.dispatchEvent(new AttributesSelectEvent(this.attributeRefs))
- }
+ this.loadAssets().then((assets) => {
+
+ // Only dispatch event when it CHANGED, so not from 'undefined' to [];
+ if(changedProps.get("attributeRefs")) {
+ this.dispatchEvent(new AttributesSelectEvent(assets, this.attributeRefs))
+ }
+
+ })
}
}
@@ -186,10 +191,14 @@ export class AttributesPanel extends LitElement {
}
}
- protected loadAssets(attributeRefs: AttributeRef[]) {
- this.fetchAssets(attributeRefs).then(assets => {
+ protected async loadAssets(): Promise<Asset[]> {
+ if(this.attributeRefs.filter(ar => !this.getLoadedAsset(ar)).length > 0) {
+ const assets = await this.fetchAssets(this.attributeRefs);
this.loadedAssets = assets;
- })
+ return assets;
+ } else {
+ return this.loadedAssets;
+ }
}
// Fetching the assets according to the AttributeRef[] input in DashboardWidget if required.
@@ -211,8 +220,8 @@ export class AttributesPanel extends LitElement {
return assets;
}
- protected onAttributeActionClick(attributeRef: AttributeRef, action: AttributeAction) {
- this.dispatchEvent(new AttributeActionEvent(attributeRef, action));
+ protected onAttributeActionClick(asset: Asset, attributeRef: AttributeRef, action: AttributeAction) {
+ this.dispatchEvent(new AttributeActionEvent(asset, attributeRef, action));
}
protected openAttributeSelector(attributeRefs: AttributeRef[], multi: boolean, onlyDataAttrs = true, attributeFilter?: (attribute: Attribute<any>) => boolean) {
@@ -259,7 +268,7 @@ export class AttributesPanel extends LitElement {
<!-- Custom actions defined by callback -->
${when(!!this.attributeActionCallback, () => {
return this.attributeActionCallback!(attributeRef).map((action) => html`
- <button class="button-action" .disabled="${action.disabled}" title="${action.tooltip}" @click="${() => this.onAttributeActionClick(attributeRef, action)}">
+ <button class="button-action" .disabled="${action.disabled}" title="${action.tooltip}" @click="${() => this.onAttributeActionClick(asset, attributeRef, action)}">
<or-icon icon="${action.icon}"></or-icon>
</button>
`);
diff --git a/ui/component/or-dashboard-builder/src/settings/attribute-input-settings.ts b/ui/component/or-dashboard-builder/src/settings/attribute-input-settings.ts
new file mode 100644
index 000000000..2a705071f
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/settings/attribute-input-settings.ts
@@ -0,0 +1,80 @@
+import {css, html, TemplateResult } from "lit";
+import { customElement } from "lit/decorators.js";
+import {AttributeInputWidgetConfig} from "../widgets/attribute-input-widget";
+import {i18next} from "@openremote/or-translate";
+import {AttributesSelectEvent} from "../panels/attributes-panel";
+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
+import {AssetWidgetSettings} from "../util/or-asset-widget";
+
+const styling = css`
+ .switch-container {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+`;
+
+@customElement("attribute-input-settings")
+export class AttributeInputSettings extends AssetWidgetSettings {
+
+ protected readonly widgetConfig!: AttributeInputWidgetConfig;
+
+ static get styles() {
+ return [...super.styles, styling];
+ }
+
+ protected render(): TemplateResult {
+ return html`
+ <div>
+ <!-- Attribute selection -->
+ <settings-panel displayName="${i18next.t('attributes')}" expanded="${true}">
+ <attributes-panel .attributeRefs="${this.widgetConfig.attributeRefs}" style="padding-bottom: 12px;"
+ @attribute-select="${(ev: AttributesSelectEvent) => this.onAttributesSelect(ev)}"
+ ></attributes-panel>
+ </settings-panel>
+
+ <!-- Other settings -->
+ <settings-panel displayName="${i18next.t('settings')}" expanded="${true}">
+ <div>
+ <!-- Toggle readonly -->
+ <div class="switch-container">
+ <span>${i18next.t('dashboard.userCanEdit')}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${!this.widgetConfig.readonly}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onReadonlyToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ <!-- Toggle helper text -->
+ <div class="switch-container">
+ <span>${i18next.t('dashboard.showHelperText')}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.showHelperText}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onHelperTextToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ </settings-panel>
+ </div>
+ `;
+ }
+
+ protected onAttributesSelect(ev: AttributesSelectEvent) {
+ this.widgetConfig.attributeRefs = ev.detail.attributeRefs;
+ if(ev.detail.attributeRefs.length === 1) {
+ const asset = ev.detail.assets.find((asset) => asset.id === ev.detail.attributeRefs[0].id);
+ if(asset) {
+ this.setDisplayName!(asset.name);
+ }
+ }
+ this.notifyConfigUpdate();
+ }
+
+ protected onReadonlyToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.readonly = !ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onHelperTextToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.showHelperText = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+}
diff --git a/ui/component/or-dashboard-builder/src/settings/chart-settings.ts b/ui/component/or-dashboard-builder/src/settings/chart-settings.ts
index 2e624b821..35e96e17c 100644
--- a/ui/component/or-dashboard-builder/src/settings/chart-settings.ts
+++ b/ui/component/or-dashboard-builder/src/settings/chart-settings.ts
@@ -235,9 +235,9 @@ export class ChartSettings extends WidgetSettings {
// we should remove the "right axis" references for the attributes that got removed.
// Also update the WidgetConfig attributeRefs field as usual
protected onAttributesSelect(ev: AttributesSelectEvent) {
- const removedAttributeRefs = this.widgetConfig.attributeRefs.filter(ar => !ev.detail.includes(ar));
+ const removedAttributeRefs = this.widgetConfig.attributeRefs.filter(ar => !ev.detail.attributeRefs.includes(ar));
removedAttributeRefs.forEach(raf => this.removeFromRightAxis(raf));
- this.widgetConfig.attributeRefs = ev.detail as AttributeRef[];
+ this.widgetConfig.attributeRefs = ev.detail.attributeRefs;
this.notifyConfigUpdate();
}
diff --git a/ui/component/or-dashboard-builder/src/settings/gauge-settings.ts b/ui/component/or-dashboard-builder/src/settings/gauge-settings.ts
index e8f1cd09a..4a29787b0 100644
--- a/ui/component/or-dashboard-builder/src/settings/gauge-settings.ts
+++ b/ui/component/or-dashboard-builder/src/settings/gauge-settings.ts
@@ -58,8 +58,15 @@ export class GaugeSettings extends WidgetSettings {
`;
}
+ // When new attributes get selected
+ // Update the displayName to the new asset and attribute name.
protected onAttributesSelect(ev: AttributesSelectEvent) {
- this.widgetConfig.attributeRefs = ev.detail as AttributeRef[];
+ this.widgetConfig.attributeRefs = ev.detail.attributeRefs;
+ if(ev.detail.attributeRefs.length === 1) {
+ const attributeRef = ev.detail.attributeRefs[0];
+ const asset = ev.detail.assets.find((asset) => asset.id === attributeRef.id);
+ this.setDisplayName!(asset ? `${asset.name} - ${attributeRef.name}` : `${attributeRef.name}`);
+ }
this.notifyConfigUpdate();
}
diff --git a/ui/component/or-dashboard-builder/src/settings/image-settings.ts b/ui/component/or-dashboard-builder/src/settings/image-settings.ts
index fd21f684f..ed5728825 100644
--- a/ui/component/or-dashboard-builder/src/settings/image-settings.ts
+++ b/ui/component/or-dashboard-builder/src/settings/image-settings.ts
@@ -79,7 +79,7 @@ export class ImageSettings extends AssetWidgetSettings {
}
protected onAttributesSelect(ev: AttributesSelectEvent) {
- this.widgetConfig.attributeRefs = ev.detail as AttributeRef[];
+ this.widgetConfig.attributeRefs = ev.detail.attributeRefs;
this.notifyConfigUpdate();
}
diff --git a/ui/component/or-dashboard-builder/src/settings/kpi-settings.ts b/ui/component/or-dashboard-builder/src/settings/kpi-settings.ts
index 6eca69b8f..f08990df0 100644
--- a/ui/component/or-dashboard-builder/src/settings/kpi-settings.ts
+++ b/ui/component/or-dashboard-builder/src/settings/kpi-settings.ts
@@ -71,8 +71,15 @@ export class KpiSettings extends AssetWidgetSettings {
`;
}
+ // When new attributes get selected
+ // Update the displayName to the new asset and attribute name.
protected onAttributesSelect(ev: AttributesSelectEvent) {
- this.widgetConfig.attributeRefs = ev.detail as AttributeRef[];
+ this.widgetConfig.attributeRefs = ev.detail.attributeRefs;
+ if(ev.detail.attributeRefs.length === 1) {
+ const attributeRef = ev.detail.attributeRefs[0];
+ const asset = ev.detail.assets.find((asset) => asset.id === attributeRef.id);
+ this.setDisplayName!(asset ? `${asset.name} - ${attributeRef.name}` : `${attributeRef.name}`);
+ }
this.notifyConfigUpdate();
}
diff --git a/ui/component/or-dashboard-builder/src/settings/map-settings.ts b/ui/component/or-dashboard-builder/src/settings/map-settings.ts
index d72050789..bfef1c23e 100644
--- a/ui/component/or-dashboard-builder/src/settings/map-settings.ts
+++ b/ui/component/or-dashboard-builder/src/settings/map-settings.ts
@@ -1,29 +1,47 @@
-import {html, TemplateResult } from "lit";
-import { customElement } from "lit/decorators.js";
+import {css, html, TemplateResult} from "lit";
+import {customElement} from "lit/decorators.js";
import {AssetWidgetSettings} from "../util/or-asset-widget";
import {i18next} from "@openremote/or-translate";
-import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
import {MapWidgetConfig} from "../widgets/map-widget";
-import { LngLatLike } from "@openremote/or-map";
+import {LngLatLike} from "@openremote/or-map";
import "../panels/assettypes-panel";
import "../panels/thresholds-panel";
import {LngLat} from "maplibre-gl"; // TODO: Replace this import
-import { when } from "lit/directives/when.js";
-import {AssetTypeSelectEvent, AttributeNameSelectEvent, ShowLabelsToggleEvent, ShowUnitsToggleEvent} from "../panels/assettypes-panel";
+import {when} from "lit/directives/when.js";
+import {AssetTypeSelectEvent, AssetTypesFilterConfig, AttributeNamesSelectEvent} from "../panels/assettypes-panel";
import manager from "@openremote/core";
-import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
import {ThresholdChangeEvent} from "../panels/thresholds-panel";
+const styling = css`
+ .switchMwcInputContainer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+`;
+
@customElement("map-settings")
export class MapSettings extends AssetWidgetSettings {
protected widgetConfig!: MapWidgetConfig;
+ static get styles() {
+ return [...super.styles, styling];
+ }
+
protected render(): TemplateResult {
const allowedValueTypes = ["boolean", "number", "positiveInteger", "positiveNumber", "negativeInteger", "negativeNumber", "text"];
+ const config = {
+ attributes: {
+ enabled: true,
+ valueTypes: allowedValueTypes
+ }
+ } as AssetTypesFilterConfig;
return html`
<div>
-
+
<!-- Map settings -->
<settings-panel displayName="${i18next.t('configuration.mapSettings')}" expanded="${true}">
<div style="display: flex; flex-direction: column; gap: 8px;">
@@ -49,19 +67,33 @@ export class MapSettings extends AssetWidgetSettings {
</div>
</div>
</settings-panel>
-
+
<!-- Panel where Asset type and the selected attribute can be customized -->
<settings-panel displayName="${i18next.t('attributes')}" expanded="${true}">
- <assettypes-panel .assetType="${this.widgetConfig.assetType}" .attributeName="${this.widgetConfig.attributeName}"
- .showLabels="${this.widgetConfig.showLabels}" .showUnits="${this.widgetConfig.showUnits}"
- .valueTypes="${allowedValueTypes}"
+ <assettypes-panel .assetType="${this.widgetConfig.assetType}" .attributeNames="${this.widgetConfig.attributeName}" .config="${config}"
@assettype-select="${(ev: AssetTypeSelectEvent) => this.onAssetTypeSelect(ev)}"
- @attributename-select="${(ev: AttributeNameSelectEvent) => this.onAttributeNameSelect(ev)}"
- @showlabels-toggle="${(ev: ShowLabelsToggleEvent) => this.onShowLabelsToggle(ev)}"
- @showunits-toggle="${(ev: ShowUnitsToggleEvent) => this.onShowUnitsToggle(ev)}"
+ @attributenames-select="${(ev: AttributeNamesSelectEvent) => this.onAttributeNameSelect(ev)}"
></assettypes-panel>
+
+ <!-- Other settings like labels and units-->
+ <div>
+ <div class="switchMwcInputContainer">
+ <span>${i18next.t("dashboard.showLabels")}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
+ .value="${this.widgetConfig.showLabels}" .disabled="${!this.widgetConfig.assetType}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onShowLabelsToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ <div class="switchMwcInputContainer">
+ <span>${i18next.t("dashboard.showUnits")}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
+ .value="${this.widgetConfig.showUnits}" .disabled="${!this.widgetConfig.showLabels || !this.widgetConfig.assetType}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onShowUnitsToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
</settings-panel>
-
+
<!-- List of customizable thresholds -->
${when(this.widgetConfig.assetIds.length > 0, () => html`
<settings-panel displayName="${i18next.t('thresholds')}" expanded="${true}">
@@ -113,19 +145,20 @@ export class MapSettings extends AssetWidgetSettings {
}
}
- protected async onAttributeNameSelect(ev: AttributeNameSelectEvent) {
- this.widgetConfig.attributeName = ev.detail;
+ protected async onAttributeNameSelect(ev: AttributeNamesSelectEvent) {
+ const attrName = ev.detail as string;
+ this.widgetConfig.attributeName = attrName;
await manager.rest.api.AssetResource.queryAssets({
realm: {
name: manager.displayRealm
},
select: {
- attributes: [ev.detail, 'location']
+ attributes: [attrName, 'location']
},
types: [this.widgetConfig.assetType!],
}).then(response => {
this.widgetConfig.assetIds = response.data.map((a) => a.id!);
- this.widgetConfig.valueType = (response.data.length > 0) ? response.data[0].attributes![ev.detail].type : "text"; // sometimes no asset exists of that assetType, so using 'text' as fallback.
+ this.widgetConfig.valueType = (response.data.length > 0) ? response.data[0].attributes![attrName].type : "text"; // sometimes no asset exists of that assetType, so using 'text' as fallback.
}).catch((reason) => {
console.error(reason);
showSnackbar(undefined, i18next.t('errorOccurred'));
@@ -134,13 +167,13 @@ export class MapSettings extends AssetWidgetSettings {
this.notifyConfigUpdate()
}
- protected onShowLabelsToggle(ev: ShowLabelsToggleEvent) {
- this.widgetConfig.showLabels = ev.detail;
+ protected onShowLabelsToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.showLabels = ev.detail.value;
this.notifyConfigUpdate();
}
- protected onShowUnitsToggle(ev: ShowUnitsToggleEvent) {
- this.widgetConfig.showUnits = ev.detail;
+ protected onShowUnitsToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.showUnits = ev.detail.value;
this.notifyConfigUpdate();
}
diff --git a/ui/component/or-dashboard-builder/src/settings/table-settings.ts b/ui/component/or-dashboard-builder/src/settings/table-settings.ts
new file mode 100644
index 000000000..a3a9e445f
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/settings/table-settings.ts
@@ -0,0 +1,93 @@
+import {css, html, TemplateResult } from "lit";
+import { customElement } from "lit/decorators.js";
+import {AssetWidgetSettings} from "../util/or-asset-widget";
+import {TableWidgetConfig} from "../widgets/table-widget";
+import {i18next} from "@openremote/or-translate";
+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
+import {AssetIdsSelectEvent, AssetTypeSelectEvent, AssetTypesFilterConfig, AttributeNamesSelectEvent} from "../panels/assettypes-panel";
+
+const styling = css`
+ .customMwcInputContainer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+`;
+
+@customElement("table-settings")
+export class TableSettings extends AssetWidgetSettings {
+
+ protected widgetConfig!: TableWidgetConfig;
+
+ static get styles() {
+ return [...super.styles, styling];
+ }
+
+ protected render(): TemplateResult {
+ const config = {
+ assets: {
+ enabled: true,
+ multi: true
+ },
+ attributes: {
+ enabled: true,
+ multi: true
+ }
+ } as AssetTypesFilterConfig
+ return html`
+ <div>
+ <!-- Asset type, assets, and attribute picker -->
+ <settings-panel displayName="${i18next.t('attributes')}" expanded="${true}">
+ <div style="padding-bottom: 12px;">
+ <assettypes-panel .assetType="${this.widgetConfig.assetType}" .config="${config}"
+ .assetIds="${this.widgetConfig.assetIds}" .attributeNames="${this.widgetConfig.attributeNames}"
+ @assettype-select="${(ev: AssetTypeSelectEvent) => this.onAssetTypeSelect(ev)}"
+ @assetids-select="${(ev: AssetIdsSelectEvent) => this.onAssetIdsSelect(ev)}"
+ @attributenames-select="${(ev: AttributeNamesSelectEvent) => this.onAttributesSelect(ev)}"
+ ></assettypes-panel>
+ </div>
+ </settings-panel>
+
+ <!-- Table settings like amount of rows -->
+ <settings-panel displayName="${i18next.t('dashboard.tableSettings')}" expanded="${true}">
+ <div style="padding-bottom: 12px;">
+ <div class="customMwcInputContainer">
+ <span style="min-width: 180px">${i18next.t('dashboard.numberOfRows')}</span>
+ <or-mwc-input type="${InputType.SELECT}" .options="${[10, 25, 100]}" .value="${this.widgetConfig.tableSize}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTableSizeSelect(ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ </settings-panel>
+ </div>
+ `
+ }
+
+ protected onAssetTypeSelect(ev: AssetTypeSelectEvent) {
+ this.widgetConfig.assetType = ev.detail;
+ this.widgetConfig.assetIds = [];
+ this.widgetConfig.attributeNames = [];
+ this.notifyConfigUpdate();
+ }
+
+ protected onAssetIdsSelect(ev: AssetIdsSelectEvent) {
+ this.widgetConfig.assetIds = ev.detail as string[];
+ this.notifyConfigUpdate();
+ }
+
+ protected onAttributesSelect(ev: AttributeNamesSelectEvent) {
+ this.widgetConfig.attributeNames = ev.detail as string[];
+ this.notifyConfigUpdate();
+ }
+
+ protected onTableSizeSelect(ev: OrInputChangedEvent) {
+ const value = ev.detail.value || 10;
+ this.widgetConfig.tableSize = value;
+ if(value !== 10) {
+ this.widgetConfig.tableOptions = [value];
+ } else {
+ this.widgetConfig.tableOptions = [10, 25, 100]
+ }
+ this.notifyConfigUpdate();
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/util/or-asset-widget.ts b/ui/component/or-dashboard-builder/src/util/or-asset-widget.ts
index ec9da8300..4c81c8458 100644
--- a/ui/component/or-dashboard-builder/src/util/or-asset-widget.ts
+++ b/ui/component/or-dashboard-builder/src/util/or-asset-widget.ts
@@ -1,5 +1,5 @@
import {OrWidget} from "./or-widget";
-import {Asset, Attribute, AttributeRef} from "@openremote/model";
+import {Asset, AssetQuery, Attribute, AttributeRef} from "@openremote/model";
import { state } from "lit/decorators.js";
import manager from "@openremote/core";
import {i18next} from "@openremote/or-translate";
@@ -29,11 +29,19 @@ export abstract class OrAssetWidget extends OrWidget {
// Fetching the assets according to the AttributeRef[] input in DashboardWidget if required.
protected async fetchAssets(attributeRefs: AttributeRef[] = []) {
- return fetchAssets(attributeRefs);
+ return fetchAssetsByAttributeRef(attributeRefs);
+ }
+
+ protected async queryAssets(assetQuery: AssetQuery) {
+ return fetchAssets(assetQuery);
+ }
+
+ protected isAssetLoaded(assetId: string) {
+ return isAssetIdLoaded(this.loadedAssets, assetId);
}
protected isAttributeRefLoaded(attributeRef: AttributeRef) {
- return isAttributeRefLoaded(this.loadedAssets, attributeRef);
+ return isAssetIdLoaded(this.loadedAssets, attributeRef.id!);
}
}
@@ -51,11 +59,19 @@ export abstract class AssetWidgetSettings extends WidgetSettings {
protected loadedAssets: Asset[] = [];
protected async fetchAssets(attributeRefs: AttributeRef[] = []) {
- return fetchAssets(attributeRefs);
+ return fetchAssetsByAttributeRef(attributeRefs);
+ }
+
+ protected async queryAssets(assetQuery: AssetQuery) {
+ return fetchAssets(assetQuery);
+ }
+
+ protected isAssetLoaded(assetId: string) {
+ return isAssetIdLoaded(this.loadedAssets, assetId)
}
protected isAttributeRefLoaded(attributeRef: AttributeRef) {
- return isAttributeRefLoaded(this.loadedAssets, attributeRef);
+ return isAssetIdLoaded(this.loadedAssets, attributeRef.id!);
}
}
@@ -67,15 +83,21 @@ export abstract class AssetWidgetSettings extends WidgetSettings {
// GENERIC FUNCTIONS
// Simple async function for fetching assets by attributeRefs
-async function fetchAssets(attributeRefs: AttributeRef[] = []) {
- let assets: Asset[] = [];
- await manager.rest.api.AssetResource.queryAssets({
+async function fetchAssetsByAttributeRef(attributeRefs: AttributeRef[] = []) {
+ const assetIds = attributeRefs.map(ar => ar.id!);
+ const attributeNames = attributeRefs.map(ar => ar.name!);
+ return fetchAssets({
ids: attributeRefs?.map((x: AttributeRef) => x.id) as string[],
- realm: { name: manager.displayRealm },
select: {
attributes: attributeRefs?.map((x: AttributeRef) => x.name) as string[]
}
- }).then(response => {
+ });
+}
+
+async function fetchAssets(assetQuery: AssetQuery) {
+ let assets: Asset[] = [];
+ assetQuery.realm = { name: manager.displayRealm };
+ await manager.rest.api.AssetResource.queryAssets(assetQuery).then(response => {
assets = response.data;
}).catch((reason) => {
console.error(reason);
@@ -84,6 +106,6 @@ async function fetchAssets(attributeRefs: AttributeRef[] = []) {
return assets;
}
-function isAttributeRefLoaded(loadedAssets: Asset[] | undefined, attrRef: AttributeRef) {
- return loadedAssets?.find((asset) => asset.id === attrRef.id) !== undefined;
+function isAssetIdLoaded(loadedAssets: Asset[] | undefined, assetId: string) {
+ return loadedAssets?.find(asset => asset.id === assetId) !== undefined;
}
diff --git a/ui/component/or-dashboard-builder/src/util/or-widget.ts b/ui/component/or-dashboard-builder/src/util/or-widget.ts
index a837ecfa9..2bd0f7f18 100644
--- a/ui/component/or-dashboard-builder/src/util/or-widget.ts
+++ b/ui/component/or-dashboard-builder/src/util/or-widget.ts
@@ -52,4 +52,9 @@ export abstract class OrWidget extends LitElement {
/* ------------------------------------- */
+ public getDisplayName?: () => string | undefined;
+
+ public getEditMode?: () => boolean;
+
+ public getWidgetLocation?: () => { x?: number, y?: number, h?: number, w?: number }
}
diff --git a/ui/component/or-dashboard-builder/src/util/widget-settings.ts b/ui/component/or-dashboard-builder/src/util/widget-settings.ts
index c7fd85f22..fdaa2ca42 100644
--- a/ui/component/or-dashboard-builder/src/util/widget-settings.ts
+++ b/ui/component/or-dashboard-builder/src/util/widget-settings.ts
@@ -44,4 +44,15 @@ export abstract class WidgetSettings extends LitElement {
protected notifyConfigUpdate() {
this.requestUpdate('widgetConfig');
}
+
+
+ /* ----------------------------- */
+
+ public getDisplayName?: () => string | undefined;
+
+ public setDisplayName?: (name?: string) => void;
+
+ public getEditMode?: () => boolean;
+
+ public getWidgetLocation?: () => { x?: number, y?: number, h?: number, w?: number }
}
diff --git a/ui/component/or-dashboard-builder/src/widgets/attribute-input-widget.ts b/ui/component/or-dashboard-builder/src/widgets/attribute-input-widget.ts
new file mode 100644
index 000000000..cb24665ca
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/widgets/attribute-input-widget.ts
@@ -0,0 +1,144 @@
+import {css, html, PropertyValues, TemplateResult } from "lit";
+import {OrAssetWidget} from "../util/or-asset-widget";
+import {WidgetConfig} from "../util/widget-config";
+import {Attribute, AttributeRef, WellknownMetaItems} from "@openremote/model";
+import {WidgetManifest} from "../util/or-widget";
+import {WidgetSettings} from "../util/widget-settings";
+import { customElement, query, queryAll } from "lit/decorators.js";
+import {AttributeInputSettings} from "../settings/attribute-input-settings";
+import { when } from "lit/directives/when.js";
+import {i18next} from "@openremote/or-translate";
+import {OrAttributeInput, OrAttributeInputChangedEvent} from "@openremote/or-attribute-input";
+import {throttle} from "lodash";
+import {Util} from "@openremote/core";
+
+export interface AttributeInputWidgetConfig extends WidgetConfig {
+ attributeRefs: AttributeRef[];
+ readonly: boolean,
+ showHelperText: boolean
+}
+
+function getDefaultWidgetConfig() {
+ return {
+ attributeRefs: [],
+ readonly: false,
+ showHelperText: true
+ } as AttributeInputWidgetConfig
+}
+
+const styling = css`
+ #widget-wrapper {
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ overflow: hidden;
+ }
+
+ .attr-input {
+ width: 100%;
+ box-sizing: border-box;
+ }
+`
+
+@customElement("attribute-input-widget")
+export class AttributeInputWidget extends OrAssetWidget {
+
+ protected widgetConfig!: AttributeInputWidgetConfig;
+
+ @query("#widget-wrapper")
+ protected widgetWrapperElem?: HTMLElement;
+
+ @queryAll(".attr-input")
+ protected attributeInputElems?: NodeList;
+
+ protected resizeObserver?: ResizeObserver;
+
+ static getManifest(): WidgetManifest {
+ return {
+ displayName: "Attribute",
+ displayIcon: "form-textbox",
+ getContentHtml(config: WidgetConfig): OrAssetWidget {
+ return new AttributeInputWidget(config);
+ },
+ getDefaultConfig(): WidgetConfig {
+ return getDefaultWidgetConfig();
+ },
+ getSettingsHtml(config: WidgetConfig): WidgetSettings {
+ return new AttributeInputSettings(config);
+ }
+
+ }
+ }
+
+ // TODO: Improve this to be more efficient
+ refreshContent(force: boolean): void {
+ this.widgetConfig = JSON.parse(JSON.stringify(this.widgetConfig)) as AttributeInputWidgetConfig;
+ }
+
+ static get styles() {
+ return [...super.styles, styling];
+ }
+
+ disconnectedCallback() {
+ super.disconnectedCallback();
+ this.resizeObserver?.disconnect();
+ delete this.resizeObserver;
+ }
+
+ protected updated(changedProps: PropertyValues) {
+
+ // If widgetConfig, and the attributeRefs of them have changed...
+ if(changedProps.has("widgetConfig") && this.widgetConfig) {
+ const attributeRefs = this.widgetConfig.attributeRefs;
+ if(attributeRefs.length > 0 && !this.isAttributeRefLoaded(attributeRefs[0])) {
+ this.loadAssets(attributeRefs);
+ }
+ }
+
+ // Workaround for an issue with scalability of or-attribute-input when using 'display: flex'.
+ // The percentage slider doesn't scale properly, causing the dragging knob to glitch.
+ // Why? Because the Material Design element listens to a window resize, not a container resize.
+ // So we manually trigger this event when the attribute-input-widget changes in size.
+ if(!this.resizeObserver && this.widgetWrapperElem) {
+ this.resizeObserver = new ResizeObserver(throttle(() => {
+ window.dispatchEvent(new Event('resize'));
+ }, 200));
+ this.resizeObserver.observe(this.widgetWrapperElem);
+ }
+
+ return super.updated(changedProps);
+ }
+
+ protected loadAssets(attributeRefs: AttributeRef[]) {
+ this.fetchAssets(attributeRefs).then((assets) => {
+ this.loadedAssets = assets;
+ });
+ }
+
+ protected render(): TemplateResult {
+ const config = this.widgetConfig;
+ const attribute = (config.attributeRefs.length > 0 && this.loadedAssets[0]?.attributes) ? this.loadedAssets[0].attributes[config.attributeRefs[0].name!] : undefined;
+ const readOnlyMetaItem = Util.getMetaValue(WellknownMetaItems.READONLY, attribute);
+ return html`
+ ${when(config.attributeRefs.length > 0 && attribute && this.loadedAssets && this.loadedAssets.length > 0, () => {
+ return html`
+ <div id="widget-wrapper">
+ <or-attribute-input class="attr-input" fullWidth
+ .assetType="${this.loadedAssets[0]?.type}"
+ .attribute="${attribute}"
+ .assetId="${this.loadedAssets[0]?.id}"
+ .disabled="${!this.loadedAssets}"
+ .readonly="${config.readonly || readOnlyMetaItem || this.getEditMode!()}"
+ .hasHelperText="${config.showHelperText}"
+ ></or-attribute-input>
+ </div>
+ `
+ }, () => html`
+ <div style="height: 100%; display: flex; justify-content: center; align-items: center;">
+ <span>${i18next.t('noAttributesConnected')}</span>
+ </div>
+ `)}
+ `;
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/widgets/kpi-widget.ts b/ui/component/or-dashboard-builder/src/widgets/kpi-widget.ts
index fc8e90ae9..3907017ce 100644
--- a/ui/component/or-dashboard-builder/src/widgets/kpi-widget.ts
+++ b/ui/component/or-dashboard-builder/src/widgets/kpi-widget.ts
@@ -84,10 +84,12 @@ export class KpiWidget extends OrAssetWidget {
protected render(): TemplateResult {
return html`
- <or-attribute-card .assets="${this.loadedAssets}" .assetAttributes="${this.assetAttributes}" .period="${this.widgetConfig.period}"
- .deltaFormat="${this.widgetConfig.deltaFormat}" .mainValueDecimals="${this.widgetConfig.decimals}"
- showControls="${this.widgetConfig?.showTimestampControls}" showTitle="${false}" style="height: 100%;">
- </or-attribute-card>
+ <div style="height: 100%; overflow: hidden;">
+ <or-attribute-card .assets="${this.loadedAssets}" .assetAttributes="${this.assetAttributes}" .period="${this.widgetConfig.period}"
+ .deltaFormat="${this.widgetConfig.deltaFormat}" .mainValueDecimals="${this.widgetConfig.decimals}"
+ showControls="${this.widgetConfig?.showTimestampControls}" showTitle="${false}" style="height: 100%;">
+ </or-attribute-card>
+ </div>
`;
}
diff --git a/ui/component/or-dashboard-builder/src/widgets/table-widget.ts b/ui/component/or-dashboard-builder/src/widgets/table-widget.ts
new file mode 100644
index 000000000..5aaa11e74
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/widgets/table-widget.ts
@@ -0,0 +1,156 @@
+import {css, html, PropertyValues, TemplateResult } from "lit";
+import { customElement } from "lit/decorators.js";
+import {OrAssetWidget} from "../util/or-asset-widget";
+import {WidgetManifest} from "../util/or-widget";
+import {WidgetConfig} from "../util/widget-config";
+import {WidgetSettings} from "../util/widget-settings";
+import {TableSettings} from "../settings/table-settings";
+import {OrMwcTableRowClickEvent, TableColumn, TableRow, TableConfig} from "@openremote/or-mwc-components/or-mwc-table";
+import {i18next} from "@openremote/or-translate";
+import {Util} from "@openremote/core";
+import {Asset, AssetModelUtil} from "@openremote/model";
+
+export interface TableWidgetConfig extends WidgetConfig {
+ assetType?: string
+ assetIds: string[]
+ attributeNames: string[],
+ tableSize: number,
+ tableOptions: number[]
+}
+
+function getDefaultConfig(): TableWidgetConfig {
+ return {
+ assetType: undefined,
+ assetIds: [],
+ attributeNames: [],
+ tableSize: 10,
+ tableOptions: [10, 25, 100]
+ }
+}
+
+const styling = css`
+ #widget-wrapper {
+ height: 100%;
+ overflow: hidden;
+ }
+`
+
+@customElement("table-widget")
+export class TableWidget extends OrAssetWidget {
+
+ protected widgetConfig!: TableWidgetConfig;
+
+ static getManifest(): WidgetManifest {
+ return {
+ displayName: "Table",
+ displayIcon: "table",
+ getContentHtml(config: WidgetConfig): OrAssetWidget {
+ return new TableWidget(config);
+ },
+ getDefaultConfig(): WidgetConfig {
+ return getDefaultConfig();
+ },
+ getSettingsHtml(config: WidgetConfig): WidgetSettings {
+ return new TableSettings(config);
+ }
+
+ }
+ }
+
+ static get styles() {
+ return [...super.styles, styling];
+ }
+
+ // TODO: Improve this to be more efficient
+ refreshContent(force: boolean): void {
+ this.widgetConfig = JSON.parse(JSON.stringify(this.widgetConfig)) as TableWidgetConfig;
+ }
+
+ // Lit Lifecycle
+ protected willUpdate(changedProps: PropertyValues) {
+ if(changedProps.has('widgetConfig') && this.widgetConfig) {
+ this.loadAssets();
+ }
+
+ return super.willUpdate(changedProps);
+ }
+
+
+ /* --------------------------------------- */
+
+ protected loadAssets() {
+ if(this.widgetConfig.assetIds.find(id => !this.isAssetLoaded(id))) {
+ this.queryAssets({
+ ids: this.widgetConfig.assetIds,
+ select: {
+ attributes: this.widgetConfig.attributeNames
+ }
+ }).then((assets) => {
+ this.loadedAssets = assets;
+ })
+ }
+ }
+
+ protected getColumns(attributeNames: string[]): TableColumn[] {
+ const referenceAsset: Asset | undefined = this.loadedAssets[0];
+ const attrColumns = attributeNames.map(attrName => {
+ let text = attrName;
+ let numeric = false;
+ if(this.widgetConfig.assetType && referenceAsset && referenceAsset.attributes && referenceAsset.attributes[attrName]) {
+ const attributeDescriptor = AssetModelUtil.getAttributeDescriptor(attrName, this.widgetConfig.assetType);
+ text = Util.getAttributeLabel(referenceAsset.attributes[attrName], attributeDescriptor, this.widgetConfig.assetType, true);
+ numeric = attributeDescriptor?.format?.asNumber || attributeDescriptor?.format?.asSlider || false;
+ }
+ return {
+ title: text,
+ isSortable: true,
+ isNumeric: numeric
+ } as TableColumn;
+ });
+ return Array.of({ title: i18next.t('assetName'), isSortable: true }, ...attrColumns);
+ }
+
+ protected getRows(attributeNames: string[]): TableRow[] {
+ return this.loadedAssets.map(asset => {
+ const attrEntries = attributeNames.map(attrName => {
+ if(asset.attributes && asset.attributes[attrName]) {
+ const attributeDescriptor = AssetModelUtil.getAttributeDescriptor(attrName, asset.type!);
+ const strValue = Util.getAttributeValueAsString(asset.attributes[attrName], attributeDescriptor, asset.type, false);
+ const numValue = parseFloat(strValue);
+ return isNaN(numValue) ? strValue : numValue;
+ } else {
+ return 'N.A.'
+ }
+ })
+ const content: any[] = Array.of(asset.name!, ...attrEntries);
+ return {
+ content: content
+ };
+ })
+ }
+
+ protected render(): TemplateResult {
+ const tableConfig: any = {
+ fullHeight: true,
+ pagination: {
+ enable: true,
+ options: this.widgetConfig.tableOptions,
+ }
+ } as TableConfig
+ const columns: TableColumn[] = this.getColumns(this.widgetConfig.attributeNames);
+ const rows: TableRow[] = this.getRows(this.widgetConfig.attributeNames);
+ return html`
+ <div id="widget-wrapper">
+ <or-mwc-table .columns="${columns}" .rows="${rows}" .config="${tableConfig}" .paginationSize="${this.widgetConfig.tableSize}"
+ @or-mwc-table-row-click="${(ev: OrMwcTableRowClickEvent) => this.onTableRowClick(ev)}"
+ ></or-mwc-table>
+ </div>
+ `;
+ }
+
+ protected onTableRowClick(ev: OrMwcTableRowClickEvent) {
+
+ }
+
+
+}
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 f3fa4a62f..388318679 100644
--- a/ui/component/or-mwc-components/src/or-mwc-input.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-input.ts
@@ -49,6 +49,7 @@ import {
} from "@openremote/model";
import {getItemTemplate, getListTemplate, ListItem, ListType} from "./or-mwc-list";
import { i18next } from "@openremote/or-translate";
+import { styleMap } from "lit/directives/style-map.js";
// TODO: Add webpack/rollup to build so consumers aren't forced to use the same tooling
const buttonStyle = require("@material/button/dist/mdc.button.css");
@@ -192,6 +193,7 @@ export const getValueHolderInputTemplateProvider: ValueInputProviderGenerator =
let required: boolean | undefined;
let selectOptions: [string, string][] | undefined;
let valueConverter: (v: any) => any | undefined;
+ const styles = {} as any;
const assetType = typeof assetDescriptor === "string" ? assetDescriptor : assetDescriptor.name;
const constraints: ValueConstraint[] = (valueHolder && ((valueHolder as MetaHolder).meta) || (valueDescriptor && (valueDescriptor as MetaHolder).meta) ? Util.getAttributeValueConstraints(valueHolder as Attribute<any>, valueHolderDescriptor as AttributeDescriptor, assetType) : Util.getMetaValueConstraints(valueHolder as NameValueHolder<any>, valueHolderDescriptor as AttributeDescriptor, assetType)) || [];
@@ -387,6 +389,10 @@ export const getValueHolderInputTemplateProvider: ValueInputProviderGenerator =
step = format.resolution;
}
+ if (inputType === InputType.COLOUR) {
+ styles.marginLeft = "24px"
+ }
+
const supportsHelperText = inputTypeSupportsHelperText(inputType);
const supportsLabel = inputTypeSupportsLabel(inputType);
const supportsSendButton = inputTypeSupportsButton(inputType);
@@ -401,7 +407,7 @@ export const getValueHolderInputTemplateProvider: ValueInputProviderGenerator =
const disabled = options.disabled || loading || sending;
const label = supportsLabel ? options.label : undefined;
- return html`<or-mwc-input ${ref(inputRef)} id="input" .type="${inputType}" .label="${label}" .value="${value}" .pattern="${pattern}"
+ return html`<or-mwc-input ${ref(inputRef)} id="input" style="${styleMap(styles)}" .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}"
@@ -1271,7 +1277,7 @@ export class OrMwcInput extends LitElement {
`;
case InputType.COLOUR:
return html`
- <div id="component" style="width: 100%; height: 100%; display: inline-flex; align-items: center; padding: 8px 0;">
+ <div id="component" style="width: 100%; display: inline-flex; align-items: center; padding: 8px 0;">
<input type="color" id="elem" style="border: none; height: 31px; width: 31px; padding: 1px 3px; min-height: 22px; min-width: 30px;cursor: pointer" value="${this.value}"
?disabled="${this.disabled || this.readonly}"
?required="${this.required}"
@@ -1549,7 +1555,8 @@ export class OrMwcInput extends LitElement {
}
// This overrides the standard mdc menu body click capture handler as it doesn't work with webcomponents
- const searchable: boolean = (this.searchProvider != undefined);
+ const searchable: boolean = (this.searchProvider !== undefined);
+ const multi: boolean = this.multiple;
(mdcSelect as any).menu.menuSurface_.foundation.handleBodyClick = function (evt: MouseEvent) {
const el = evt.composedPath()[0]; // Use composed path not evt target to work with webcomponents
if (this.adapter.isElementInContainer(el)) {
@@ -1561,6 +1568,9 @@ export class OrMwcInput extends LitElement {
else if (el instanceof Element && !el.className.includes('mdc-list-item')) {
return;
}
+ else if (multi) {
+ return;
+ }
}
(mdcSelect as any).menu.menuSurface_.close();
};
diff --git a/ui/component/or-mwc-components/src/or-mwc-table.ts b/ui/component/or-mwc-components/src/or-mwc-table.ts
index 26bb539d4..f2674fc6d 100644
--- a/ui/component/or-mwc-components/src/or-mwc-table.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-table.ts
@@ -8,6 +8,7 @@ import {when} from 'lit/directives/when.js';
import {DefaultColor3, DefaultColor2, DefaultColor1, manager} from "@openremote/core";
import {i18next} from "@openremote/or-translate";
import {InputType, OrInputChangedEvent} from "./or-mwc-input";
+import { styleMap } from "lit/directives/style-map.js";
const dataTableStyle = require("@material/data-table/dist/mdc.data-table.css");
@@ -34,6 +35,11 @@ const style = css`
max-height: 700px;
justify-content: space-between;
}
+
+ .mdc-data-table__fullheight {
+ height: 100%;
+ max-height: none !important;
+ }
/* first column should be sticky*/
.mdc-data-table.has-sticky-first-column tr th:first-of-type,
@@ -89,6 +95,15 @@ const style = css`
}
.sort-button {
+ padding-right: 0;
+ border: none;
+ background-color: ${unsafeCSS(DefaultColor1)};
+ color: ${unsafeCSS(DefaultColor3)};
+ cursor: pointer;
+ }
+
+ .sort-button-reverse {
+ padding-left: 0;
border: none;
background-color: ${unsafeCSS(DefaultColor1)};
color: ${unsafeCSS(DefaultColor3)};
@@ -96,6 +111,12 @@ const style = css`
}
.sortable {
+ flex-direction: row;
+ cursor: pointer;
+ }
+
+ .sortable-reverse {
+ flex-direction: row-reverse;
cursor: pointer;
}
@@ -141,11 +162,13 @@ const style = css`
}
`;
-interface TableConfig {
+export interface TableConfig {
columnFilter?: string[];
stickyFirstColumn?: boolean;
+ fullHeight?: boolean;
pagination?: {
- enable?: boolean
+ enable?: boolean;
+ options?: number[];
}
multiSelect?: boolean;
}
@@ -203,21 +226,22 @@ export class OrMwcTable extends LitElement {
@property({type: Object}) // to manually control HTML (requires td and tr elements)
protected rowsTemplate?: TemplateResult;
- @property({type: Number})
- protected paginationIndex: number = 0;
-
- @property({type: Number})
- protected paginationSize: number = 10;
-
@property({type: Array})
protected config: TableConfig = {
columnFilter: [],
stickyFirstColumn: true,
+ fullHeight: false,
pagination: {
enable: false
}
};
+ @property({type: Number})
+ protected paginationIndex: number = 0;
+
+ @property({type: Number})
+ protected paginationSize: number = 10;
+
@state()
protected _dataTable?: MDCDataTable;
@@ -265,11 +289,15 @@ export class OrMwcTable extends LitElement {
const tableClasses = {
"mdc-data-table": true,
"mdc-data-table__paginated": !!this.config.pagination,
+ "mdc-data-table__fullheight": !!this.config.fullHeight,
"has-sticky-first-column": !!this.config.stickyFirstColumn
}
+ // Only show pagination if enabled in config, and when "the amount of rows doesn't fit on the page".
+ const showPagination = this.config.pagination && (!!this.rowsTemplate || (this.rows && (this.rows.length > this.paginationSize)));
+ const tableWidth = this.shadowRoot?.firstElementChild?.clientWidth;
return html`
<div class="${classMap(tableClasses)}">
- <div class="mdc-data-table__table-container">
+ <div class="mdc-data-table__table-container" style="flex: 1;">
<table class="mdc-data-table__table">
<!-- Header row that normally includes entries like 'id' and 'name'. You can use either a template or a list of columns -->
${when(this.columnsTemplate, () => this.columnsTemplate, () => {
@@ -277,6 +305,9 @@ export class OrMwcTable extends LitElement {
<thead>
<tr class="mdc-data-table__header-row">
${this.columns.map((column: TableColumn | string, index: number) => {
+ const styles = {
+ maxWidth: tableWidth ? `${tableWidth / (this.columns!.length / 2)}px` : undefined
+ } as any;
if(index == 0 && this.config.multiSelect){
return html`
<th class="mdc-data-table__header-cell mdc-data-table__header-cell--checkbox"
@@ -302,9 +333,10 @@ export class OrMwcTable extends LitElement {
'hide-mobile': !!column.hideMobile,
'mdc-data-table__header-cell--with-sort': !!column.isSortable,
})}"
+ style="${styleMap(styles)}"
role="columnheader" scope="col" title="${column.title}" data-column-id="${column.title}"
@click="${(ev: MouseEvent) => !!column.isSortable ? this.sortRows(ev, index, this.sortDirection!) : ''}">
- ${(!column.isSortable ? column.title : until(this.getSortHeader(index, column.title!, this.sortDirection!), html`${i18next.t('loading')}`))}
+ ${(!column.isSortable ? column.title : until(this.getSortHeader(index, column.title!, this.sortDirection!, !!column.isNumeric), html`${i18next.t('loading')}`))}
</th>
`
})}
@@ -331,6 +363,9 @@ export class OrMwcTable extends LitElement {
.filter((row, index) => (index >= (this.paginationIndex * this.paginationSize)) && (index < (this.paginationIndex * this.paginationSize + this.paginationSize)))
.map((item: TableRow | string[]) => {
const content: (string | number | TemplateResult)[] | undefined = (Array.isArray(item) ? item : (item as TableRow).content);
+ const styles = {
+ maxWidth: tableWidth ? `${tableWidth / (this.columns!.length / 2)}px` : undefined
+ } as any;
return html`
<tr class="mdc-data-table__row" @click="${(ev: MouseEvent) => this.onRowClick(ev, item)}">
${content?.map((cell: string | number | TemplateResult, index: number) => {
@@ -352,7 +387,7 @@ export class OrMwcTable extends LitElement {
</td> `
}
return html`
- <td class="${classMap(classes)}" title="${cell}">
+ <td class="${classMap(classes)}" title="${cell}" style="${styleMap(styles)}">
<span>${cell}</span>
</td>
`
@@ -366,7 +401,8 @@ export class OrMwcTable extends LitElement {
</table>
</div>
<!-- Pagination HTML, shown on the bottom right. Same as Material Design spec -->
- ${when(this.config.pagination, () => {
+ ${when(showPagination, () => {
+ const options = this.config.pagination?.options || [10, 25, 100];
return html`
<div class="mdc-data-table__pagination">
<div class="mdc-data-table__pagination-trailing">
@@ -375,8 +411,8 @@ export class OrMwcTable extends LitElement {
${i18next.t('rowsPerPage')}
</div>
<or-mwc-input class="mdc-data-table__pagination-rows-per-page-select"
- .type="${InputType.SELECT}" compact comfortable outlined
- .value="${this.paginationSize}" .options="${[10, 25, 100]}"
+ .type="${InputType.SELECT}" compact comfortable outlined .readonly="${options.length === 1}"
+ .value="${this.paginationSize}" .options="${options}"
@or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
this.paginationSize = ev.detail.value;
this.paginationIndex = 0;
@@ -403,14 +439,14 @@ export class OrMwcTable extends LitElement {
}
- async getSortHeader(index: number, title: string, sortDirection: 'ASC' | 'DESC'): Promise<TemplateResult> {
- this.sortIndex == -1 ? this.sortIndex = index : '';
+ async getSortHeader(index: number, title: string, sortDirection: 'ASC' | 'DESC', arrowOnLeft = false): Promise<TemplateResult> {
+ this.sortIndex === -1 ? this.sortIndex = index : '';
return html`
- <div class="mdc-data-table__header-cell-wrapper sortable" >
+ <div class="mdc-data-table__header-cell-wrapper ${arrowOnLeft ? 'sortable-reverse' : 'sortable'}">
<div class="mdc-data-table__header-cell-label">
${title}
</div>
- <button class="mdc-icon-button material-icons sort-button ${this.sortIndex === index ? '' : 'hidden'}"
+ <button class="mdc-icon-button material-icons ${arrowOnLeft ? 'sort-button-reverse' : 'sort-button'} ${this.sortIndex === index ? '' : 'hidden'}"
aria-label="Sort by ${title}" aria-describedby="${title}-status-label" aria-hidden="${!(this.sortIndex === index)}">
<or-icon icon="${ sortDirection == 'ASC' ? "arrow-up" : "arrow-down"}"></or-icon>
</button>