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: New chart widget features using Apache ECharts (#1997)

Martin Peeters7daf161ccce1
diff --git a/setup/src/demo/resources/demo/dashboards/manufacturer/harvesting.json b/setup/src/demo/resources/demo/dashboards/manufacturer/harvesting.json
index efa675897..5751732c2 100644
--- a/setup/src/demo/resources/demo/dashboards/manufacturer/harvesting.json
+++ b/setup/src/demo/resources/demo/dashboards/manufacturer/harvesting.json
@@ -66,7 +66,6 @@
"fromTimestamp": 1710943555635,
"amountOfPoints": 100
},
- "rightAxisAttributes": [],
"defaultTimePresetKey": "last24Hours",
"showTimestampControls": false
}
diff --git a/setup/src/demo/resources/demo/dashboards/smartcity/parking.json b/setup/src/demo/resources/demo/dashboards/smartcity/parking.json
index a817a5820..6b8412364 100644
--- a/setup/src/demo/resources/demo/dashboards/smartcity/parking.json
+++ b/setup/src/demo/resources/demo/dashboards/smartcity/parking.json
@@ -66,7 +66,6 @@
"fromTimestamp": 1710942863421,
"amountOfPoints": 100
},
- "rightAxisAttributes": [],
"defaultTimePresetKey": "last24Hours",
"showTimestampControls": false
}
diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json
index 6abf68f5d..98d715768 100644
--- a/ui/app/shared/locales/en/or.json
+++ b/ui/app/shared/locales/en/or.json
@@ -141,30 +141,25 @@
"filterInvite": "Filter with at least 3 characters",
"location": "Location",
"longPressSetLoc": "Long press to set location",
+ "this": "Current",
+ "last": "Last",
+ "60minutes": "60 minutes",
"hour": "Hour",
- "lastHour": "Last hour",
- "last24Hours": "Last 24 hours",
- "thisHour": "This hour",
+ "6hours": "6 hours",
+ "24hours": "24 hours",
+ "7days": "7 days",
+ "30days": "30 days",
+ "90days": "90 days",
+ "6months": "6 months",
+ "365days": "365 days",
"day": "Day",
- "thisDay": "This day",
- "thisDayLastWeek": "This day last week",
- "yesterday": "Yesterday",
- "last7Days": "Last 7 days",
- "last30Days": "Last 30 days",
- "last90Days": "Last 90 days",
"week": "Week",
- "thisWeek": "This week",
- "previousWeek": "Previous week",
"month": "Month",
- "thisMonth": "This month",
- "previousMonth": "Previous month",
- "last6Months": "Last 6 months",
"year": "Year",
- "lastYear": "Last year",
- "thisYear": "This year",
- "previousYear": "Previous year",
"period": "Period",
"ending": "Ending",
+ "prefix": "Prefix",
+ "prefixDefault": "Default prefix",
"timeframe": "Timeframe",
"timeframeDefault": "Default timeframe",
"dataSampling": "Data sampling",
@@ -762,11 +757,13 @@
"deletePermanentWarning": "This will delete {{dashboard}} permanently.",
"deleteWidgetWarning": "This will remove the widget from your board, and be permanently deleted after saving.",
"widgetTooSmall": "Widget is too small.",
+ "toggleStackView": "Use stacked chart",
"allowTimerangeSelect": "Allow time range selection",
"toggleAxis": "Toggle axis",
"showLegend": "Show legend",
"showGeoJson": "Show GeoJSON overlay",
"showValueAs": "Show value as",
+ "showZoomBar": "Show zoom bar",
"customLabel": "Custom label",
"customTimeSpan": "Custom",
"userCanEdit": "Allow user input",
@@ -778,7 +775,13 @@
"zoom": "Zoom",
"center": "Center",
"imageUrl": "Image URL",
- "noImageSelected": "No image selected"
+ "noImageSelected": "No image selected",
+ "faint": "Faint",
+ "smooth": "Smooth",
+ "stepped": "Stepped",
+ "fill": "Fill",
+ "extendData": "Extend latest datapoint",
+ "lineColor": "Line color"
},
"south": "South",
"east": "East",
diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json
index be64bd3df..9121b5f5c 100644
--- a/ui/app/shared/locales/nl/or.json
+++ b/ui/app/shared/locales/nl/or.json
@@ -141,30 +141,25 @@
"filterInvite": "Filter met minsters 3 karakters",
"location": "Locatie",
"longPressSetLoc": "Druk lang op de kaart om locatie in te stellen",
+ "this": "Huidige",
+ "last": "Afgelopen",
+ "60minutes": "60 minuten",
"hour": "Uur",
- "lastHour": "Afgelopen uur",
- "last24Hours": "Afgelopen 24 uur",
- "thisHour": "Dit uur",
+ "6hours": "6 uur",
+ "24hours": "24 uur",
+ "7days": "7 dagen",
+ "30days": "30 dagen",
+ "90days": "90 dagen",
+ "6months": "6 maanden",
+ "365days": "365 dagen",
"day": "Dag",
- "thisDay": "Vandaag",
- "thisDayLastWeek": "Vandaag een week geleden",
- "yesterday": "Gisteren",
- "last7Days": "Afgelopen 7 dagen",
- "last30Days": "Afgelopen 30 dagen",
- "last90Days": "Afgelopen 90 dagen",
"week": "Week",
- "thisWeek": "Deze week",
- "previousWeek": "Vorige week",
"month": "Maand",
- "thisMonth": "Deze maand",
- "previousMonth": "Vorige maand",
- "last6Months": "Afgelopen 6 maanden",
"year": "Jaar",
- "lastYear": "Afgelopen jaar",
- "thisYear": "Dit jaar",
- "previousYear": "Vorig jaar",
"period": "Periode",
"ending": "Einde",
+ "prefix": "Prefix",
+ "prefixDefault": "Standaard prefix",
"timeframe": "Tijdvak",
"timeframeDefault": "Standaard tijdvak",
"dataSampling": "Data weergave",
@@ -761,11 +756,13 @@
"deletePermanentWarning": "Dit zal {{dashboard}} permanent verwijderen.",
"deleteWidgetWarning": "De widget zal worden weggehaald van het bord, en zal permanent worden verwijderd als u opslaat.",
"widgetTooSmall": "Widget is te klein.",
+ "toggleStackView": "Gestapelde grafiek",
"allowTimerangeSelect": "Sta tijdselectie toe",
"toggleAxis": "As wisselen",
"showLegend": "Toon legenda",
"showGeoJson": "Toon GeoJSON overlay",
"showValueAs": "Laat waarde zien als",
+ "showZoomBar": "Toon zoom balk",
"customLabel": "Label",
"customTimeSpan": "Aangepast",
"userCanEdit": "Kan waarde aanpassen",
@@ -777,7 +774,13 @@
"zoom": "Zoom",
"center": "Middelpunt",
"imageUrl": "Afbeelding URL",
- "noImageSelected": "Geen afbeelding geselecteerd"
+ "noImageSelected": "Geen afbeelding geselecteerd",
+ "faint": "Vervagen",
+ "smooth": "Gladstrijken",
+ "stepped": "Treden",
+ "fill": "Vullen",
+ "extendData": "Verleng laatste datapunt",
+ "lineColor": "Lijnkleur"
},
"south": "Zuid",
"east": "Oost",
diff --git a/ui/app/shared/locales/ro/or.json b/ui/app/shared/locales/ro/or.json
index 4bda1fe42..4e693d00b 100644
--- a/ui/app/shared/locales/ro/or.json
+++ b/ui/app/shared/locales/ro/or.json
@@ -129,27 +129,10 @@
"location": "Locație",
"longPressSetLoc": "Apasă lung pentru a seta locația",
"hour": "Oră",
- "lastHour": "În ultima oră",
- "last24Hours": "În ultimele 24 de ore",
- "thisHour": "În aceasta oră",
"day": "Zi",
- "thisDay": "Astăzi",
- "thisDayLastWeek": "Acum o săptămână",
- "yesterday": "Ieri",
- "last7Days": "Ultimele 7 zile",
- "last30Days": "Ultimele 30 de zile",
- "last90Days": "Ultimele 90 de zile",
"week": "Saptamană",
- "thisWeek": "Această săptămână",
- "previousWeek": "Săptămâna trecută",
"month": "Lună",
- "thisMonth": "Această Lună",
- "previousMonth": "Luna trecută",
- "last6Months": "Ultimele 6 luni",
"year": "An",
- "lastYear": "Anul trecut",
- "thisYear": "Anul acesta",
- "previousYear": "Anul trecut",
"period": "Perioadă",
"ending": "Se termina în",
"timeframe": "Interval de timp",
diff --git a/ui/app/shared/locales/uk/or.json b/ui/app/shared/locales/uk/or.json
index 04348c670..8f4cc317c 100644
--- a/ui/app/shared/locales/uk/or.json
+++ b/ui/app/shared/locales/uk/or.json
@@ -131,27 +131,10 @@
"location": "Місце розташування",
"longPressSetLoc": "Довге натискання, щоб встановити місце",
"hour": "Година",
- "lastHour": "Остання година",
- "last24Hours": "Останні 24 години",
- "thisHour": "Ця година",
"day": "День",
- "thisDay": "Сьогодні",
- "thisDayLastWeek": "Цей день минулого тижня",
- "yesterday": "Вчора",
- "last7Days": "Останні 7 днів",
- "last30Days": "Останні 30 днів",
- "last90Days": "Останні 90 днів",
"week": "Тиждень",
- "thisWeek": "Цей тиждень",
- "previousWeek": "Попередній тиждень",
"month": "Місяць",
- "thisMonth": "Цей місяць",
- "previousMonth": "Попередній місяць",
- "last6Months": "Останні 6 місяців",
"year": "Рік",
- "lastYear": "Минулий рік",
- "thisYear": "Цей рік",
- "previousYear": "Попередній рік",
"period": "Період",
"ending": "Закінчення",
"timeframe": "Вімір часу",
diff --git a/ui/component/or-attribute-card/package.json b/ui/component/or-attribute-card/package.json
index 1d615440b..0e0b08cd5 100644
--- a/ui/component/or-attribute-card/package.json
+++ b/ui/component/or-attribute-card/package.json
@@ -23,6 +23,8 @@
"@openremote/or-attribute-picker": "workspace:*",
"@openremote/or-chart": "workspace:*",
"@openremote/or-mwc-components": "workspace:*",
+ "chart.js": "^3.6.0",
+ "chartjs-adapter-moment": "^1.0.0",
"lit": "^2.0.2",
"moment": "^2.29.4"
},
diff --git a/ui/component/or-attribute-history/src/index.ts b/ui/component/or-attribute-history/src/index.ts
index 3e79b0044..99f9756aa 100644
--- a/ui/component/or-attribute-history/src/index.ts
+++ b/ui/component/or-attribute-history/src/index.ts
@@ -23,7 +23,6 @@ import "@openremote/or-mwc-components/or-mwc-input";
import "@openremote/or-components/or-panel";
import "@openremote/or-translate";
import "@openremote/or-chart";
-import "chartjs-adapter-moment";
import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
import {MDCDataTable} from "@material/data-table";
import {JSONPath} from "jsonpath-plus";
diff --git a/ui/component/or-chart/package.json b/ui/component/or-chart/package.json
index 5625eb938..07ef7cccb 100644
--- a/ui/component/or-chart/package.json
+++ b/ui/component/or-chart/package.json
@@ -27,10 +27,7 @@
"@openremote/or-icon": "workspace:*",
"@openremote/or-mwc-components": "workspace:*",
"@openremote/or-translate": "workspace:*",
- "chart.js": "^3.6.0",
- "chartjs-adapter-moment": "^1.0.0",
- "chartjs-plugin-annotation": "^1.1.0",
- "jsonpath-plus": "^6.0.1",
+ "echarts": "~5.6.0",
"lit": "^2.0.2",
"moment": "^2.29.4"
},
diff --git a/ui/component/or-chart/src/index.ts b/ui/component/or-chart/src/index.ts
index 5021011e4..d1b376ac0 100644
--- a/ui/component/or-chart/src/index.ts
+++ b/ui/component/or-chart/src/index.ts
@@ -1,5 +1,5 @@
import {css, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
-import {customElement, property, query} from "lit/decorators.js";
+import {customElement, property, state, query} from "lit/decorators.js";
import i18next from "i18next";
import {translate} from "@openremote/or-translate";
import {
@@ -9,53 +9,44 @@ import {
AssetModelUtil,
AssetQuery,
Attribute,
- AttributeRef,
- DatapointInterval,
+ AttributeRef, DatapointInterval,
ReadAssetEvent,
- ValueDatapoint,
- WellknownMetaItems
+ ValueDatapoint
} from "@openremote/model";
import manager, {DefaultColor2, DefaultColor3, DefaultColor4, DefaultColor5, Util} from "@openremote/core";
import "@openremote/or-asset-tree";
import "@openremote/or-mwc-components/or-mwc-input";
import "@openremote/or-components/or-panel";
import "@openremote/or-translate";
-import {
- Chart,
- ChartConfiguration,
- ChartDataset,
- Filler,
- Legend,
- LinearScale,
- LineController,
- LineElement,
- PointElement,
- ScatterController,
- ScatterDataPoint,
- TimeScale,
- TimeScaleOptions,
- TimeUnit,
- Title,
- Tooltip
-} from "chart.js";
+import * as echarts from "echarts/core";
+import {DatasetComponentOption, DataZoomComponent, DataZoomComponentOption, GridComponent, GridComponentOption, TooltipComponent, TooltipComponentOption} from "echarts/components";
+import {LineChart, LineSeriesOption} from "echarts/charts";
+import {CanvasRenderer} from "echarts/renderers";
+import {UniversalTransition} from "echarts/features";
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";
import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";
-import ChartAnnotation, {AnnotationOptions} from "chartjs-plugin-annotation";
-import "chartjs-adapter-moment";
import {GenericAxiosResponse, isAxiosError} from "@openremote/rest";
import {OrAssetAttributePicker, OrAssetAttributePickerPickedEvent} from "@openremote/or-attribute-picker";
import {OrMwcDialog, showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
import {cache} from "lit/directives/cache.js";
-import {throttle} from "lodash";
+import {debounce} 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);
+echarts.use([GridComponent, TooltipComponent, DataZoomComponent, LineChart, CanvasRenderer, UniversalTransition]);
+
+export type ECChartOption = echarts.ComposeOption<
+ | LineSeriesOption
+ | TooltipComponentOption
+ | GridComponentOption
+ | DatasetComponentOption
+ | DataZoomComponentOption
+>;
export class OrChartEvent extends CustomEvent<OrChartEventDetail> {
@@ -73,8 +64,6 @@ export class OrChartEvent extends CustomEvent<OrChartEventDetail> {
}
}
-export type TimePresetCallback = (date: Date) => [Date, Date];
-
export interface ChartViewConfig {
attributeRefs?: AttributeRef[];
fromTimestamp?: number;
@@ -85,6 +74,15 @@ export interface ChartViewConfig {
decimals?: number;
}
+export interface ChartAttributeConfig {
+ rightAxisAttributes?: AttributeRef[],
+ smoothAttributes?: AttributeRef[],
+ steppedAttributes?: AttributeRef[],
+ areaAttributes?: AttributeRef[],
+ faintAttributes?: AttributeRef[],
+ extendedAttributes?: AttributeRef[]
+}
+
export interface OrChartEventDetail {
value?: any;
previousValue?: any;
@@ -109,6 +107,18 @@ export interface OrChartConfig {
}};
}
+/**
+ * ECharts dataset object with additional optional fields for visualization purposes.
+ * For example, {@link assetId} and {@link attrName} can be specified, so their information can be shown alongside the data itself.
+ */
+export interface LineChartData extends LineSeriesOption {
+ assetId?: string;
+ attrName?: string;
+ unit?: string;
+ extended?: boolean;
+ predicted?: boolean;
+}
+
// Declare require method which we'll use for importing webpack resources (using ES6 imports will confuse typescript parser)
declare function require(name: string): any;
@@ -121,11 +131,12 @@ const style = css`
:host {
--internal-or-chart-background-color: var(--or-chart-background-color, var(--or-app-color2, ${unsafeCSS(DefaultColor2)}));
+ --internal-or-chart-border-color: var(--or-chart-border-color, rgba(76, 76, 76, 0.6));
--internal-or-chart-text-color: var(--or-chart-text-color, var(--or-app-color3, ${unsafeCSS(DefaultColor3)}));
--internal-or-chart-controls-margin: var(--or-chart-controls-margin, 0 0 20px 0);
--internal-or-chart-controls-margin-children: var(--or-chart-controls-margin-children, 0 auto 20px auto);
--internal-or-chart-graph-fill-color: var(--or-chart-graph-fill-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));
- --internal-or-chart-graph-fill-opacity: var(--or-chart-graph-fill-opacity, 1);
+ --internal-or-chart-graph-fill-opacity: var(--or-chart-graph-fill-opacity, 0.25);
--internal-or-chart-graph-line-color: var(--or-chart-graph-line-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));
--internal-or-chart-graph-point-color: var(--or-chart-graph-point-color, var(--or-app-color3, ${unsafeCSS(DefaultColor3)}));
--internal-or-chart-graph-point-border-color: var(--or-chart-graph-point-border-color, var(--or-app-color5, ${unsafeCSS(DefaultColor5)}));
@@ -161,7 +172,7 @@ const style = css`
.button-icon {
align-self: center;
- padding: 10px;
+ padding: 11px 6px;
cursor: pointer;
}
@@ -188,6 +199,7 @@ const style = css`
min-width: 0;
flex-direction: row;
height: 100%;
+ gap: 8px;
}
#msg {
@@ -201,25 +213,24 @@ const style = css`
#msg:not([hidden]) {
display: flex;
}
- .period-controls {
+ #period-controls {
display: flex;
- min-width: 180px;
+ flex-direction: column;
align-items: center;
}
+
#controls {
display: flex;
flex-wrap: wrap;
- margin: var(--internal-or-chart-controls-margin);
width: 100%;
flex-direction: column;
- margin: 0;
+ justify-content: center;
}
#attribute-list {
overflow: hidden auto;
- min-height: 50px;
- flex: 1 1 0;
+ flex: 1 1 50px;
width: 100%;
display: flex;
flex-direction: column;
@@ -280,12 +291,7 @@ const style = css`
.attribute-list-item:hover .button.delete {
display: block;
}
-
- #controls > * {
- margin-top: 5px;
- margin-bottom: 5px;
- }
-
+
.dialog-container {
display: flex;
flex-direction: row;
@@ -305,25 +311,20 @@ const style = css`
flex: 1 1 0;
position: relative;
overflow: hidden;
+ gap: 4px;
/*min-height: 400px;
max-height: 550px;*/
}
#chart-controls {
+ padding: 0 8px;
display: flex;
flex-direction: column;
- align-items: center;
}
- canvas {
+ #chart {
width: 100% !important;
height: 100%; !important;
}
- @media screen and (max-width: 1280px) {
- #chart-container {
- max-height: 330px;
- }
- }
-
@media screen and (max-width: 769px) {
.mdc-dialog .mdc-dialog__surface {
min-width: auto;
@@ -340,8 +341,7 @@ const style = css`
min-width: 100%;
padding-left: 0;
}
- .interval-controls,
- .period-controls {
+ #period-controls {
flex-direction: row;
justify-content: left;
align-items: center;
@@ -353,7 +353,7 @@ const style = css`
@customElement("or-chart")
export class OrChart extends translate(i18next)(LitElement) {
- public static DEFAULT_TIMESTAMP_FORMAT = "L HH:mm:ss";
+ public static readonly DEFAULT_COLORS = ["#3869B1", "#DA7E30", "#3F9852", "#CC2428", "#6B4C9A", "#922427", "#958C3D", "#535055"];
static get styles() {
return [
@@ -372,14 +372,28 @@ export class OrChart extends translate(i18next)(LitElement) {
@property({type: Object})
public assetAttributes: [number, Attribute<any>][] = [];
- @property({type: Array}) // List of AttributeRef that are shown on the right axis instead.
- public rightAxisAttributes: AttributeRef[] = [];
+ /**
+ * The list of HEX colors representing the line color for each {@link AttributeRef}.
+ * Acts as an override, and will fall back to the {@link colors} attribute if not specified.
+ * The {@link AttributeRef} object with Asset ID and Attribute name need to be present in the Chart to work.
+ * The HEX color should be put in without '#' prefix. For example, you'd use '4d9d2a' instead of '#4d9d2a'.
+ */
+ @property({type: Array})
+ public attributeColors: [AttributeRef, string][] = [];
+
+ /**
+ * Chart attribute configuration object, specifying characteristics for each Chart line.
+ * For example, what {@link AttributeRef} is aligned to the right side, or what {@link AttributeRef} is using a fill.
+ * Check for {@link ChartAttributeConfig} for specification. This HTML attribute expects JSON string input.
+ */
+ @property({type: Object})
+ public attributeConfig: ChartAttributeConfig = this._getDefaultAttributeConfig();
@property()
- public dataProvider?: (startOfPeriod: number, endOfPeriod: number, timeUnits: TimeUnit, stepSize: number) => Promise<ChartDataset<"line", ScatterDataPoint[]>[]>
+ public dataProvider?: (startOfPeriod: number, endOfPeriod: number) => Promise<LineChartData[]>;
@property({type: Array})
- public colors: string[] = ["#3869B1", "#DA7E30", "#3F9852", "#CC2428", "#6B4C9A", "#922427", "#958C3D", "#535055"];
+ public colors: string[] = OrChart.DEFAULT_COLORS;
@property({type: Object})
public readonly datapointQuery!: AssetDatapointQueryUnion;
@@ -387,8 +401,8 @@ export class OrChart extends translate(i18next)(LitElement) {
@property({type: Object})
public config?: OrChartConfig;
- @property({type: Object}) // options that will get merged with our default chartjs configuration.
- public chartOptions?: any
+ @property({type: Object})
+ public chartOptions?: ECChartOption;
@property({type: String})
public realm?: string;
@@ -396,47 +410,93 @@ export class OrChart extends translate(i18next)(LitElement) {
@property()
public panelName?: string;
- @property()
- public attributeControls: boolean = true;
+ @property({type: Boolean})
+ public attributeControls = true;
@property()
public timeframe?: [Date, Date];
- @property()
- public timestampControls: boolean = true;
+ @property({type: Boolean})
+ public timestampControls = true;
- @property()
- public timePresetOptions?: Map<string, TimePresetCallback>;
+ /**
+ * List of 'time prefix' options like 'this' or 'last', for the user to select from.
+ * In combination with the {@link timeWindowOptions} attribute, it becomes a string like 'last 6 hours'.
+ * @protected
+ */
+ @property({type: Array})
+ public timePrefixOptions?: string[];
- @property()
- public timePresetKey?: string;
+ /**
+ * Selected 'time prefix' of the available {@link timePrefixOptions}.
+ * This string attribute will only accept keys of the {@link timeWindowOptions} Array.
+ */
+ @property({type: String})
+ public timePrefixKey?: string;
+
+ /**
+ * List of timeframe options like '6 hours' for the user to select from.
+ * In combination with the {@link timePrefixKey} attribute, it becomes a string like 'last 6 hours'.
+ * Expects a JSON string input, that is formatted as an JavaScript {@link Map} object.
+ * The map is identified with a unique key, and a combination of `[duration, length]`.
+ * For example `['6hours', ['hours', 6]]`.
+ */
+ @property({type: Object})
+ public timeWindowOptions?: Map<string, [moment.unitOfTime.DurationConstructor, number]>;
- @property()
- public showLegend: boolean = true;
+ /**
+ * Selected 'time window' of the available {@link timeWindowOptions}.
+ * This string attribute will only accept keys of the {@link timeWindowOptions} Map.
+ */
+ @property({type: String})
+ public timeWindowKey?: string;
- @property()
- public denseLegend: boolean = false;
+ /**
+ * Boolean attribute to enable/disable stacking the data vertically. (compound line chart)
+ * On the same axis, it will display a cumulative effect of all data series on top of each other.
+ */
+ @property({type: Boolean})
+ public stacked = false;
- @property()
- protected _loading: boolean = false;
+ @property({type: Boolean})
+ public showLegend = true;
- @property()
- protected _data?: ChartDataset<"line", ScatterDataPoint[]>[] = undefined;
+ @property({type: Boolean})
+ public denseLegend = false;
+
+ @property({type: Boolean})
+ public showZoomBar = true;
+
+ @state()
+ protected _loading = false;
+
+ @state()
+ protected _data?: LineChartData[];
@property()
protected _tableTemplate?: TemplateResult;
+ @state()
+ protected _zoomChanged = false;
+
+ @state()
+ protected _isCustomWindow = false;
+
@query("#chart")
- protected _chartElem!: HTMLCanvasElement;
+ protected _chartElem!: HTMLDivElement;
- protected _chart?: Chart;
+ protected _chart?: echarts.ECharts;
protected _style!: CSSStyleDeclaration;
protected _startOfPeriod?: number;
protected _endOfPeriod?: number;
- protected _timeUnits?: TimeUnit;
- protected _stepSize?: number;
+ protected _zoomStartOfPeriod?: number;
+ protected _zoomEndOfPeriod?: number;
protected _latestError?: string;
protected _dataAbortController?: AbortController;
+ protected _zoomHandler?: any;
+ protected _containerResizeObserver?: ResizeObserver;
+ protected _tooltipCache: [xTime: number, content: string] = [0, ""];
+
constructor() {
super();
@@ -467,13 +527,15 @@ export class OrChart extends translate(i18next)(LitElement) {
}
}
- const reloadData = changedProperties.has("datapointQuery") || changedProperties.has("timePresetKey") || changedProperties.has("timeframe") ||
- changedProperties.has("rightAxisAttributes") || changedProperties.has("assetAttributes") || changedProperties.has("realm") || changedProperties.has("dataProvider");
+ const reloadData = changedProperties.has('attributeColors') || changedProperties.has("datapointQuery") || changedProperties.has("timeframe") || changedProperties.has("timePrefixKey") || changedProperties.has("timeWindowKey")||
+ changedProperties.has("attributeConfig") || changedProperties.has("assetAttributes") || changedProperties.has("realm") || changedProperties.has("dataProvider");
if (reloadData) {
this._data = undefined;
if (this._chart) {
- this._chart.destroy();
+ // Remove event listeners
+ this._toggleChartEventListeners(false);
+ this._chart.dispose();
this._chart = undefined;
}
this._loadData();
@@ -483,119 +545,152 @@ export class OrChart extends translate(i18next)(LitElement) {
return;
}
- const now = moment().toDate().getTime();
-
if (!this._chart) {
- const options = {
- type: "line",
- data: {
- datasets: this._data
+
+ // Parse the background color from CSS variables
+ let bgColor = this._style.getPropertyValue("--internal-or-chart-graph-fill-color").trim();
+ const opacity = Number(this._style.getPropertyValue("--internal-or-chart-graph-fill-opacity").trim());
+ if (!isNaN(opacity)) {
+ if (bgColor.startsWith("#") && (bgColor.length === 4 || bgColor.length === 7)) {
+ bgColor += (bgColor.length === 4 ? Math.round(opacity * 255).toString(16).substr(0, 1) : Math.round(opacity * 255).toString(16));
+ } else if (bgColor.startsWith("rgb(")) {
+ bgColor = bgColor.substring(0, bgColor.length - 1) + opacity;
+ }
+ }
+ // Define default EChart configration / options
+ this.chartOptions = {
+ animation: false,
+ grid: {
+ show: true,
+ backgroundColor: this._style.getPropertyValue("--internal-or-asset-tree-background-color"),
+ borderColor: this._style.getPropertyValue("--internal-or-chart-border-color"),
+ left: 10,
+ right: 10,
+ top: 10,
+ bottom: this.showZoomBar ? 68 : 10,
+ containLabel: true
},
- options: {
- responsive: true,
- maintainAspectRatio: false,
- onResize: throttle(() => { this.dispatchEvent(new OrChartEvent("resize")); this.applyChartResponsiveness(); }, 200),
- showLines: true,
- plugins: {
- legend: {
- display: false
- },
- tooltip: {
- mode: "x",
- intersect: false,
- xPadding: 10,
- yPadding: 10,
- titleMarginBottom: 10,
- callbacks: {
- label: (tooltipItem: any) => tooltipItem.dataset.label + ': ' + tooltipItem.formattedValue + tooltipItem.dataset.unit,
- }
- },
- annotation: {
- annotations: [
- {
- type: "line",
- xMin: now,
- xMax: now,
- borderColor: "#275582",
- borderWidth: 2
- }
- ]
- },
+ backgroundColor: this._style.getPropertyValue("--internal-or-asset-tree-background-color"),
+ tooltip: {
+ trigger: "axis",
+ confine: true,
+ axisPointer: {
+ type: "cross",
+ },
+ formatter: (params: any) => {
+ const xTime = params[0].axisValue as number;
+ if (xTime !== this._tooltipCache[0]) {
+ // use global var to store current time selection, avoiding replicate calculation loops
+ this._tooltipCache[0] = xTime;
+ this._tooltipCache[1] = this._getTooltipData(xTime);
+ }
+ return this._tooltipCache[1];
+ }
+ },
+ toolbox: {},
+ xAxis: {
+ type: "time",
+ axisLine: {
+ onZero: false,
+ lineStyle: {color: this._style.getPropertyValue("--internal-or-chart-text-color")}
},
- hover: {
- mode: 'x',
- intersect: false
+ splitLine: {show: true},
+ min: this._startOfPeriod,
+ max: this._endOfPeriod,
+ axisLabel: {
+ hideOverlap: true,
+ fontSize: 10,
+ formatter: {
+ year: "{yyyy}-{MMM}",
+ month: "{yy}-{MMM}",
+ day: "{d}-{MMM}",
+ hour: "{HH}:{mm}",
+ minute: "{HH}:{mm}",
+ second: "{HH}:{mm}:{ss}",
+ millisecond: "{d}-{MMM} {HH}:{mm}",
+ none: "{MMM}-{dd} {HH}:{mm}"
+ }
+ }
+ },
+ yAxis: [
+ {
+ type: "value",
+ axisLine: { lineStyle: {color: this._style.getPropertyValue("--internal-or-chart-text-color")}},
+ boundaryGap: ["10%", "10%"],
+ scale: true,
+ min: (this.chartOptions?.options as any)?.scales?.y?.min,
+ max: (this.chartOptions?.options as any)?.scales?.y?.max,
+ axisLabel: { hideOverlap: true }
},
- scales: {
- y: {
- ticks: {
- beginAtZero: true
- },
- grid: {
- color: "#cccccc"
- }
- },
- y1: {
- display: this.rightAxisAttributes.length > 0,
- position: 'right',
- ticks: {
- beginAtZero: true
- },
- grid: {
- drawOnChartArea: false
- }
+ {
+ type: "value",
+ show: (this.attributeConfig?.rightAxisAttributes?.length ?? 0) > 0,
+ axisLine: { lineStyle: {color: this._style.getPropertyValue("--internal-or-chart-text-color")}},
+ boundaryGap: ["10%", "10%"],
+ scale: true,
+ min: (this.chartOptions?.options as any)?.scales?.y1?.min,
+ max: (this.chartOptions?.options as any)?.scales?.y1?.max,
+ axisLabel: { hideOverlap: true }
+ }
+ ],
+ dataZoom: [
+ {
+ type: "inside",
+ start: 0,
+ end: 100
+ }
+ ],
+ series: []
+ } as ECChartOption;
+
+ // Add dataZoom bar if enabled
+ if(this.showZoomBar) {
+ (this.chartOptions.dataZoom as DataZoomComponentOption[]).push({
+ start: 0,
+ end: 100,
+ backgroundColor: bgColor,
+ fillerColor: bgColor,
+ dataBackground: {
+ areaStyle: {
+ color: this._style.getPropertyValue("--internal-or-chart-graph-fill-color")
+ }
+ },
+ selectedDataBackground: {
+ areaStyle: {
+ color: this._style.getPropertyValue("--internal-or-chart-graph-fill-color")
+ }
+ },
+ moveHandleStyle: {
+ color: this._style.getPropertyValue("--internal-or-chart-graph-fill-color")
+ },
+ emphasis: {
+ moveHandleStyle: {
+ color: this._style.getPropertyValue("--internal-or-chart-graph-fill-color")
},
- x: {
- type: "time",
- min: this._startOfPeriod,
- max: this._endOfPeriod,
- time: {
- tooltipFormat: 'MMM D, YYYY, HH:mm:ss',
- displayFormats: {
- millisecond: 'HH:mm:ss.SSS',
- second: 'HH:mm:ss',
- minute: "HH:mm",
- hour: (this._endOfPeriod && this._startOfPeriod && this._endOfPeriod - this._startOfPeriod > 86400000) ? "MMM DD, HH:mm" : "HH:mm",
- day: "MMM DD",
- week: "w"
- },
- unit: this._timeUnits,
- stepSize: this._stepSize
- },
- ticks: {
- autoSkip: true,
- color: "#000",
- font: {
- family: "'Open Sans', Helvetica, Arial, Lucida, sans-serif",
- size: 9,
- style: "normal"
- }
- },
- gridLines: {
- color: "#cccccc"
- }
+ handleLabel: {
+ show: false
}
+ },
+ handleLabel: {
+ show: false
}
- }
- } as ChartConfiguration<"line", ScatterDataPoint[]>;
+ });
+ }
- const mergedOptions = Util.mergeObjects(options, this.chartOptions, false);
+ // Initialize echarts instance
+ this._chart = echarts.init(this._chartElem);
+ // Set chart options to default
+ this._chart.setOption(this.chartOptions);
+ this._toggleChartEventListeners(true);
+ }
- this._chart = new Chart<"line", ScatterDataPoint[]>(this._chartElem.getContext("2d")!, mergedOptions as ChartConfiguration<"line", ScatterDataPoint[]>);
- } else {
- if (changedProperties.has("_data")) {
- this._chart.options.scales!.x!.min = this._startOfPeriod;
- this._chart.options!.scales!.x!.max = this._endOfPeriod;
- (this._chart.options!.scales!.x! as TimeScaleOptions).time!.unit = this._timeUnits!;
- (this._chart.options!.scales!.x! as TimeScaleOptions).time!.stepSize = this._stepSize!;
- (this._chart.options!.plugins!.annotation!.annotations! as AnnotationOptions<"line">[])[0].xMin = now;
- (this._chart.options!.plugins!.annotation!.annotations! as AnnotationOptions<"line">[])[0].xMax = now;
- this._chart.data.datasets = this._data;
- this._chart.update();
- }
+ if (changedProperties.has("_data")) {
+ //Update chart to data from set period
+ this._updateChartData();
}
- this.onCompleted().then(() => {
- this.dispatchEvent(new OrChartEvent('rendered'));
+
+ this.getUpdateComplete().then(() => {
+ this.dispatchEvent(new OrChartEvent("rendered"));
});
}
@@ -604,38 +699,41 @@ export class OrChart extends translate(i18next)(LitElement) {
// Also sorts the attribute lists horizontally when it is below the chart
applyChartResponsiveness(): void {
if(this.shadowRoot) {
- const container = this.shadowRoot.getElementById('container');
+ const container = this.shadowRoot.getElementById("container");
if(container) {
const bottomLegend: boolean = (container.clientWidth < 600);
- container.style.flexDirection = bottomLegend ? 'column' : 'row';
- const periodControls = this.shadowRoot.querySelector('.period-controls') as HTMLElement;
+ container.style.flexDirection = bottomLegend ? "column" : "row";
+ const controls = this.shadowRoot.getElementById("controls");
+ if(controls) {
+ controls.style.flexDirection = bottomLegend ? "row" : "column";
+ }
+ const periodControls = this.shadowRoot.getElementById("period-controls");
if(periodControls) {
- periodControls.style.justifyContent = bottomLegend ? 'center' : 'space-between';
- periodControls.style.paddingLeft = bottomLegend ? '' : '18px';
+ periodControls.style.flexDirection = bottomLegend ? "row" : "column";
}
- const attributeList = this.shadowRoot.getElementById('attribute-list');
+ const attributeList = this.shadowRoot.getElementById("attribute-list");
if(attributeList) {
- attributeList.style.gap = bottomLegend ? '4px 12px' : '';
- attributeList.style.maxHeight = bottomLegend ? '90px' : '';
- attributeList.style.flexFlow = bottomLegend ? 'row wrap' : 'column nowrap';
- attributeList.style.padding = bottomLegend ? '0' : '12px 0';
+ attributeList.style.gap = bottomLegend ? "4px 12px" : "";
+ attributeList.style.maxHeight = bottomLegend ? "90px" : "";
+ attributeList.style.flexFlow = bottomLegend ? "row wrap" : "column nowrap";
+ attributeList.style.padding = bottomLegend ? "0" : "5px 0";
}
- this.shadowRoot.querySelectorAll('.attribute-list-item').forEach((item: Element) => {
- (item as HTMLElement).style.minHeight = bottomLegend ? '0px' : '44px';
- (item as HTMLElement).style.paddingLeft = bottomLegend ? '' : '16px';
- (item.children[1] as HTMLElement).style.flexDirection = bottomLegend ? 'row' : 'column';
- (item.children[1] as HTMLElement).style.gap = bottomLegend ? '4px' : '';
+ this.shadowRoot.querySelectorAll(".attribute-list-item").forEach((item: Element) => {
+ (item as HTMLElement).style.minHeight = bottomLegend ? "0px" : "44px";
+ (item as HTMLElement).style.paddingLeft = bottomLegend ? "" : "0";
+ (item.children[1] as HTMLElement).style.flexDirection = bottomLegend ? "row" : "column";
+ (item.children[1] as HTMLElement).style.gap = bottomLegend ? "4px" : "";
});
}
}
}
render() {
- const disabled = this._loading || this._latestError;
+ const disabled = this._latestError;
return html`
<div id="container">
- <div id="chart-container">
- ${when(this._loading, () => html`
+ <div id="chart-container" style="opacity: ${this._loading ? '0.7' : '1'};">
+ ${when(this._loading && !this._data, () => html`
<div style="position: absolute; height: 100%; width: 100%;">
<or-loading-indicator ?overlay="false"></or-loading-indicator>
</div>
@@ -645,48 +743,79 @@ export class OrChart extends translate(i18next)(LitElement) {
<or-translate .value="${this._latestError || 'errorOccurred'}"></or-translate>
</div>
`)}
- <canvas id="chart" style="visibility: ${disabled ? 'hidden' : 'visible'}"></canvas>
+ <div id="chart" style="visibility: ${disabled ? 'hidden' : 'visible'};"></div>
</div>
${(this.timestampControls || this.attributeControls || this.showLegend) ? html`
<div id="chart-controls">
<div id="controls">
- <div class="period-controls">
- ${this.timePresetOptions && this.timePresetKey ? html`
+ ${this.timePrefixKey && this.timePrefixOptions && this.timeWindowKey && this.timeWindowOptions ? html`
${this.timestampControls ? html`
- ${getContentWithMenuTemplate(
- html`<or-mwc-input .type="${InputType.BUTTON}" label="${this.timeframe ? "dashboard.customTimeSpan" : this.timePresetKey}"></or-mwc-input>`,
- Array.from(this.timePresetOptions!.keys()).map((key) => ({ value: key } as ListItem)),
- this.timePresetKey,
- (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>
+ <div id="period-controls">
+ <!-- Time prefix selection -->
+ ${getContentWithMenuTemplate(
+ html`<or-mwc-input .type="${InputType.BUTTON}" label="${this.timeframe ? "dashboard.customTimeSpan" : this.timePrefixKey.toLowerCase()}"></or-mwc-input>`,
+ this.timePrefixOptions.map(option => ({value: option, text: option.toLowerCase() } as ListItem)),
+ this.timePrefixKey,
+ (value: string | string[]) => {
+ this.timeframe = undefined; // remove any custom start & end times
+ this.timePrefixKey = value.toString();
+ },
+ undefined,
+ undefined,
+ undefined,
+ true
+ )}
+ <!-- Time window selection -->
+ ${getContentWithMenuTemplate(
+ html`<or-mwc-input .type="${InputType.BUTTON}" label="${this._isCustomWindow ? "timeframe" : this.timeWindowKey.toLowerCase()}"></or-mwc-input>`,
+ Array.from(this.timeWindowOptions!.keys()).map(key => ({ value: key, text: key.toLowerCase() } as ListItem)),
+ this.timeWindowKey,
+ (value: string | string[]) => {
+ this.timeframe = undefined; // remove any custom start & end times
+ this.timeWindowKey = value.toString();
+ },
+ undefined,
+ undefined,
+ undefined,
+ true
+ )}
+ </div>
+ <div style="text-align: center">
+ <!-- Scroll left button -->
+ <or-icon class="button button-icon" ?disabled="${disabled}" icon="chevron-left"
+ @click="${() => this._shiftTimeframe(this.timeframe?.[0] ?? new Date(this._startOfPeriod!), this.timeframe?.[1] ?? new Date(this._endOfPeriod!), this.timeWindowKey!, "previous")}"
+ ></or-icon>
+ <!-- Scroll right button -->
+ <or-icon class="button button-icon" ?disabled="${disabled}" icon="chevron-right"
+ @click="${() => this._shiftTimeframe(this.timeframe?.[0] ?? new Date(this._startOfPeriod!), this.timeframe?.[1] ?? new Date(this._endOfPeriod!), this.timeWindowKey!, "next")}"
+ ></or-icon>
+ <!-- Button that opens custom time selection or restores to widget setting-->
+ <or-icon class="button button-icon" ?disabled="${disabled}" icon="${this.timeframe ? 'restore' : 'calendar-clock'}"
+ @click="${() => this.timeframe ? (this._isCustomWindow = false, this.timeframe = undefined) : this._openTimeDialog(this._startOfPeriod, this._endOfPeriod)}"
+ ></or-icon>
+ </div>
` : html`
- <or-mwc-input .type="${InputType.BUTTON}" label="${this.timePresetKey}" disabled="true"></or-mwc-input>
+ <div style = "display: flex; flex-direction: column; align-items: center">
+ <or-mwc-input .type="${InputType.BUTTON}" label="${this.timePrefixKey}" disabled></or-mwc-input>
+ <or-mwc-input .type="${InputType.BUTTON}" label="${this.timeWindowKey}" disabled></or-mwc-input>
+ </div>
`}
` : undefined}
- </div>
+
${this.timeframe ? html`
- <div style="margin-left: 18px; font-size: 12px;">
- <table style="width: 100%;">
+ <div style="font-size: 12px; display: flex; justify-content: flex-end;">
+ <table style="text-align: right;">
<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>
+ <th style="font-weight: normal;">${i18next.t('from')}:</th>
+ <th style="font-weight: normal;">${moment(this.timeframe[0]).format("lll")}</th>
</tr>
</thead>
<tbody>
<tr>
<td>${i18next.t('to')}:</td>
- <td>${moment(this.timeframe[1]).format("L HH:mm")}</td>
+ <td>${moment(this.timeframe[1]).format("lll")}</td>
</tr>
</tbody>
</table>
@@ -706,15 +835,18 @@ export class OrChart extends translate(i18next)(LitElement) {
${this.assetAttributes && this.assetAttributes.map(([assetIndex, attr], index) => {
const asset: Asset | undefined = this.assets[assetIndex];
const colourIndex = index % this.colors.length;
+ const color = this.attributeColors.find(x => x[0].id === asset.id && x[0].name === attr.name)?.[1];
const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset!.type, attr.name, attr);
const label = Util.getAttributeLabel(attr, descriptors[0], asset!.type, true);
- const axisNote = (this.rightAxisAttributes.find(ar => asset!.id === ar.id && attr.name === ar.name)) ? i18next.t('right') : undefined;
- const bgColor = this.colors[colourIndex] || "";
+ const axisNote = (this.attributeConfig.rightAxisAttributes?.find(ar => asset!.id === ar.id && attr.name === ar.name)) ? i18next.t('right') : undefined;
+ const bgColor = (color ?? this.colors[colourIndex]) || "";
return html`
- <div class="attribute-list-item ${this.denseLegend ? 'attribute-list-item-dense' : undefined}" @mouseover="${()=> this.addDatasetHighlight(this.assets[assetIndex]!.id, attr.name)}" @mouseout="${()=> this.removeDatasetHighlight(bgColor)}">
+ <div class="attribute-list-item ${this.denseLegend ? 'attribute-list-item-dense' : undefined}"
+ @mouseenter="${() => this._addDatasetHighlight({id: this.assets[assetIndex]!.id, name: attr.name})}"
+ @mouseleave="${()=> this._removeDatasetHighlights()}">
<span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.assets[assetIndex]!.type!), undefined, undefined, bgColor.split('#')[1])}</span>
<div class="attribute-list-item-label ${this.denseLegend ? 'attribute-list-item-label-dense' : undefined}">
- <div style="display: flex; justify-content: space-between;">
+ <div style="display: flex; gap: 4px;">
<span style="font-size:12px; ${this.denseLegend ? 'margin-right: 8px' : undefined}">${this.assets[assetIndex].name}</span>
${when(axisNote, () => html`<span style="font-size:12px; color:grey">(${axisNote})</span>`)}
</div>
@@ -751,49 +883,67 @@ export class OrChart extends translate(i18next)(LitElement) {
}
}
- removeDatasetHighlight(bgColor:string) {
- if(this._chart && this._chart.data && this._chart.data.datasets){
- this._chart.data.datasets.map((dataset, idx) => {
- if (dataset.borderColor && typeof dataset.borderColor === "string" && dataset.borderColor.length === 9) {
- dataset.borderColor = dataset.borderColor.slice(0, -2);
- dataset.backgroundColor = dataset.borderColor;
- }
- });
- this._chart.update();
+ /**
+ * Removes all active Chart line color highlights, by reducing/increasing opacity.
+ * @protected
+ */
+ protected _removeDatasetHighlights(chart = this._chart) {
+ if(chart){
+ const options = chart.getOption();
+ if (options.series && Array.isArray(options.series)) {
+ options.series.forEach(function (series) {
+ if (series.lineStyle.opacity === 0.2 || series.lineStyle.opacity === 0.99) {
+ series.lineStyle.opacity = 0.31;
+ series.showSymbol = false;
+ } else {
+ series.lineStyle.opacity = 1;
+ series.showSymbol = true;
+ }
+ });
+ }
+ chart.setOption(options);
}
}
- addDatasetHighlight(assetId?:string, attrName?:string) {
- if (!assetId || !attrName) return;
-
- if(this._chart && this._chart.data && this._chart.data.datasets){
- this._chart.data.datasets.map((dataset, idx) => {
- if ((dataset as any).assetId === assetId && (dataset as any).attrName === attrName) {
- return
- }
- dataset.borderColor = dataset.borderColor + "36";
- dataset.backgroundColor = dataset.borderColor;
- });
- this._chart.update();
+ /**
+ * Adds a Chart line color highlight, by reducing/increasing opacity.
+ * So the given line (represented by {@link assetId} and {@link attrName} will be emphasized, while others are less visible.
+ * @param attrRef - Asset ID and attribute name to be highlighted
+ * @param chart - ECharts instance to add the highlight to.
+ */
+ _addDatasetHighlight(attrRef: AttributeRef, chart = this._chart) {
+ if (chart) {
+ const options = chart.getOption();
+ if (options.series && Array.isArray(options.series)) {
+ options.series.forEach(series => {
+ if (series.assetId !== attrRef.id || series.attrName !== attrRef.name) {
+ if (series.lineStyle.opacity === 0.31) { // 0.31 is faint setting, 1 is normal
+ series.lineStyle.opacity = 0.2;
+ } else {
+ series.lineStyle.opacity = 0.3;
+ series.showSymbol = false;
+ }
+ } else if (series.lineStyle.opacity === 0.31) { // extra highlight if selected is faint
+ series.lineStyle.opacity = 0.99;
+ series.showSymbol = true;
+ }
+ });
+ }
+ chart.setOption(options);
}
}
async loadSettings(reset: boolean) {
- if(this.assetAttributes == undefined || reset) {
+ if(this.assetAttributes === undefined || reset) {
this.assetAttributes = [];
}
- if (!this.realm) {
- this.realm = manager.getRealm();
- }
-
- if (!this.timePresetOptions) {
- this.timePresetOptions = this._getDefaultTimestampOptions();
- }
- if (!this.timePresetKey) {
- this.timePresetKey = this.timePresetOptions.keys().next().value?.toString();
- }
+ this.realm ??= manager.getRealm();
+ this.timePrefixOptions ??= this._getDefaultTimePrefixOptions();
+ this.timeWindowOptions ??= this._getDefaultTimeWindowOptions();
+ this.timeWindowKey ??= this.timeWindowOptions.keys().next().value!.toString();
+ this.timePrefixKey ??= this.timePrefixOptions[1];
if (!this.panelName) {
return;
@@ -806,7 +956,7 @@ export class OrChart extends translate(i18next)(LitElement) {
manager.console.storeData("OrChartConfig", [allConfigs]);
}
- let config: OrChartConfig | undefined = allConfigs.find(e => e.realm === this.realm);
+ const config: OrChartConfig | undefined = allConfigs.find(e => e.realm === this.realm);
if (!config) {
return;
@@ -842,10 +992,11 @@ export class OrChart extends translate(i18next)(LitElement) {
try {
const response = await manager.rest.api.AssetResource.queryAssets(query);
const assets = response.data || [];
- view.attributeRefs = view.attributeRefs.filter((attrRef) => !!assets.find((asset) => asset.id === attrRef.id && asset.attributes && asset.attributes.hasOwnProperty(attrRef.name!)));
+ view.attributeRefs = view.attributeRefs.filter(attrRef =>
+ !!assets.find(asset => asset.id === attrRef.id && asset.attributes && asset.attributes.hasOwnProperty(attrRef.name!)));
manager.console.storeData("OrChartConfig", [...allConfigs.filter(e => e.realm !== this.realm), config]);
- this.assets = assets.filter((asset) => view.attributeRefs!.find((attrRef) => attrRef.id === asset.id));
+ this.assets = assets.filter(asset => view.attributeRefs!.find(attrRef => attrRef.id === asset.id));
} catch (e) {
console.error("Failed to get assets requested in settings", e);
}
@@ -853,17 +1004,16 @@ export class OrChart extends translate(i18next)(LitElement) {
this._loading = false;
if (this.assets && this.assets.length > 0) {
- this.assetAttributes = view.attributeRefs.map((attrRef) => {
- const assetIndex = this.assets.findIndex((asset) => asset.id === attrRef.id);
+ this.assetAttributes = view.attributeRefs.map(attrRef => {
+ const assetIndex = this.assets.findIndex(asset => asset.id === attrRef.id);
const asset = assetIndex >= 0 ? this.assets[assetIndex] : undefined;
return asset && asset.attributes ? [assetIndex!, asset.attributes[attrRef.name!]] : undefined;
- }).filter((indexAndAttr) => !!indexAndAttr) as [number, Attribute<any>][];
+ }).filter(indexAndAttr => !!indexAndAttr) as [number, Attribute<any>][];
}
}
}
async saveSettings() {
-
if (!this.panelName) {
return;
}
@@ -871,14 +1021,7 @@ export class OrChart extends translate(i18next)(LitElement) {
const viewSelector = window.location.hash;
const allConfigs: OrChartConfig[] = await manager.console.retrieveData("OrChartConfig") || [];
let config: OrChartConfig | undefined = allConfigs.find(e => e.realm === this.realm);
-
- if (!config) {
- config = {
- realm: this.realm,
- views: {
- }
- }
- }
+ config ??= {realm: this.realm, views: {}};
if (!config.views[viewSelector]) {
config.views[viewSelector] = {};
@@ -911,7 +1054,7 @@ export class OrChart extends translate(i18next)(LitElement) {
protected _openTimeDialog(startTimestamp?: number, endTimestamp?: number) {
const startRef: Ref<OrMwcInput> = createRef();
const endRef: Ref<OrMwcInput> = createRef();
- const dialog = showDialog(new OrMwcDialog()
+ showDialog(new OrMwcDialog()
.setHeading(i18next.t('timeframe'))
.setContent(() => html`
<div>
@@ -926,14 +1069,16 @@ export class OrChart extends translate(i18next)(LitElement) {
actionName: "ok",
content: "ok",
action: () => {
- if(this.timePresetOptions && startRef.value?.value && endRef.value?.value) {
+ if(startRef.value?.value && endRef.value?.value) {
+ this._isCustomWindow = true;
this.timeframe = [new Date(startRef.value.value), new Date(endRef.value.value)];
}
}
}])
- )
+ );
}
+
protected async _addAttribute(selectedAttrs?: AttributeRef[]) {
if (!selectedAttrs) return;
@@ -960,107 +1105,111 @@ export class OrChart extends translate(i18next)(LitElement) {
});
}
- async onCompleted() {
- await this.updateComplete;
- }
-
protected _cleanup() {
if (this._chart) {
- this._chart.destroy();
+ this._toggleChartEventListeners(false);
+ this._chart.dispose();
this._chart = undefined;
this.requestUpdate();
}
}
- protected _deleteAttribute (index: number) {
- const removed = this.assetAttributes.splice(index, 1)[0];
- const assetIndex = removed[0];
- this.assetAttributes = [...this.assetAttributes];
- if (!this.assetAttributes.some(([index, attrRef]) => index === assetIndex)) {
- // Asset no longer referenced
- this.assets.splice(index, 1);
- this.assetAttributes.forEach((indexRef) => {
- if (indexRef[0] >= assetIndex) {
- indexRef[0] -= 1;
- }
- });
- }
- this.saveSettings();
+ protected _getDefaultTimePrefixOptions(): string[] {
+ return ["this", "last"];
}
- protected _getAttributeOptionsOld(): [string, string][] | undefined {
- if(!this.activeAsset || !this.activeAsset.attributes) {
- return;
- }
-
- if(this.shadowRoot && this.shadowRoot.getElementById('chart-attribute-picker')) {
- const elm = this.shadowRoot.getElementById('chart-attribute-picker') as HTMLInputElement;
- elm.value = '';
+ protected _getDefaultTimeWindowOptions(): Map<string, [moment.unitOfTime.DurationConstructor, number]> {
+ return new Map<string, [moment.unitOfTime.DurationConstructor, number]>([
+ ["Hour", ["hours", 1]],
+ ["6Hours", ["hours", 6]],
+ ["24Hours", ["hours", 24]],
+ ["Day", ["days", 1]],
+ ["7Days", ["days", 7]],
+ ["Week", ["weeks", 1]],
+ ["30Days", ["days", 30]],
+ ["Month", ["months", 1]],
+ ["365Days", ["days", 365]],
+ ["Year", ["years", 1]]
+ ]);
+ };
+
+ /**
+ * Internal function for retrieving a start/end date, based on the selected time frame.
+ * Given the {@link selectedTimePrefix} (say 'last') and the {@link selectedTimeWindow} (say '6 hours'),
+ * it will return the respected JavaScript {@link Date} objects.
+ * @param selectedTimePrefix - Time prefix string, for example 'last'.
+ * @param selectedTimeWindow - Time window string, for example '6 hours'.
+ * @protected
+ */
+ protected _getTimeSelectionDates(selectedTimePrefix: string, selectedTimeWindow: string): [Date, Date] {
+ let startDate = moment();
+ let endDate = moment();
+ const timeWindow: [moment.unitOfTime.DurationConstructor, number] | undefined = this.timeWindowOptions!.get(selectedTimeWindow);
+ if (!timeWindow) {
+ throw new Error(`Unsupported time window selected: ${selectedTimeWindow}`);
}
-
- const attributes = Object.values(this.activeAsset.attributes);
- if (attributes && attributes.length > 0) {
- return attributes
- .filter((attribute) => attribute.meta && (attribute.meta.hasOwnProperty(WellknownMetaItems.STOREDATAPOINTS) ? attribute.meta[WellknownMetaItems.STOREDATAPOINTS] : attribute.meta.hasOwnProperty(WellknownMetaItems.AGENTLINK)))
- .filter((attr) => (this.assetAttributes && !this.assetAttributes.some(([index, assetAttr]) => (assetAttr.name === attr.name) && this.assets[index].id === this.activeAsset!.id)))
- .map((attr) => {
- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(this.activeAsset!.type, attr.name, attr);
- const label = Util.getAttributeLabel(attr, descriptors[0], this.activeAsset!.type, false);
- return [attr.name!, label];
- });
+ const [unit , value]: [moment.unitOfTime.DurationConstructor, number] = timeWindow;
+ switch (selectedTimePrefix) {
+ case "this":
+ if (value === 1) { // For singulars like this hour
+ startDate = moment().startOf(unit);
+ endDate = moment().endOf(unit);
+ } else { // For multiples like this 5 min, put now in the middle
+ startDate = moment().subtract(value*0.5, unit);
+ endDate = moment().add(value*0.5, unit);
+ }
+ break;
+ case "last":
+ startDate = moment().subtract(value, unit).startOf(unit);
+ if (value === 1) { // For singulars like last hour
+ endDate = moment().startOf(unit);
+ } else { //For multiples like last 5 min
+ endDate = moment();
+ }
+ break;
}
+ return [startDate.toDate(), endDate.toDate()];
}
- protected _getAttributeOptions(): [string, string][] | undefined {
- if(!this.activeAsset || !this.activeAsset.attributes) {
- return;
- }
-
- if(this.shadowRoot && this.shadowRoot.getElementById('chart-attribute-picker')) {
- const elm = this.shadowRoot.getElementById('chart-attribute-picker') as HTMLInputElement;
- elm.value = '';
- }
-
- const attributes = Object.values(this.activeAsset.attributes);
- if (attributes && attributes.length > 0) {
- return attributes
- .filter((attribute) => attribute.meta && (attribute.meta.hasOwnProperty(WellknownMetaItems.STOREDATAPOINTS) ? attribute.meta[WellknownMetaItems.STOREDATAPOINTS] : attribute.meta.hasOwnProperty(WellknownMetaItems.AGENTLINK)))
- .filter((attr) => (this.assetAttributes && !this.assetAttributes.some(([index, assetAttr]) => (assetAttr.name === attr.name) && this.assets[index].id === this.activeAsset!.id)))
- .map((attr) => {
- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(this.activeAsset!.type, attr.name, attr);
- const label = Util.getAttributeLabel(attr, descriptors[0], this.activeAsset!.type, false);
- return [attr.name!, label];
- });
+ /**
+ * Internal function for shifting a timeframe in a specific {@link direction}.
+ * Based on the given {@link currentStart} and {@link currentEnd} dates, it will move forward/backwards for the {@link selectedTimeWindow}.
+ * For example, when viewing '1 week' of data, and calling this function with the 'previous' direction, it will update {@link timeframe} with dates one week in advance.
+ *
+ * @param currentStart - Start date of the current viewport
+ * @param currentEnd - End date of the current viewport
+ * @param selectedTimeWindow - Time window to subtract/add from the viewport
+ * @param direction - Whether to advance or reverse the viewport (whether to add or remove time)
+ * @protected
+ */
+ protected _shiftTimeframe(currentStart: Date, currentEnd: Date, selectedTimeWindow: string, direction: "previous" | "next") {
+ const timeWindow = this.timeWindowOptions!.get(selectedTimeWindow);
+ if (!timeWindow) {
+ throw new Error(`Unsupported time window selected: ${selectedTimeWindow}`);
}
- }
-
- protected _getDefaultTimestampOptions(): Map<string, TimePresetCallback> {
- return new Map<string, TimePresetCallback>([
- ["lastHour", (date) => [moment(date).subtract(1, 'hour').toDate(), date]],
- ["last24Hours", (date) => [moment(date).subtract(24, 'hours').toDate(), date]],
- ["last7Days", (date) => [moment(date).subtract(7, 'days').toDate(), date]],
- ["last30Days", (date) => [moment(date).subtract(30, 'days').toDate(), date]],
- ["last90Days", (date) => [moment(date).subtract(90, 'days').toDate(), date]],
- ["last6Months", (date) => [moment(date).subtract(6, 'months').toDate(), date]],
- ["lastYear", (date) => [moment(date).subtract(1, 'year').toDate(), date]]
- ]);
+ const [unit, value] = timeWindow;
+ let newStart = moment(currentStart);
+ direction === "previous" ? newStart.subtract(value, unit as moment.unitOfTime.DurationConstructor) : newStart.add(value, unit as moment.unitOfTime.DurationConstructor);
+ let newEnd = moment(currentEnd)
+ direction === "previous" ? newEnd.subtract(value, unit as moment.unitOfTime.DurationConstructor) : newEnd.add(value, unit as moment.unitOfTime.DurationConstructor);
+ this.timeframe = [newStart.toDate(), newEnd.toDate()];
}
protected _getInterval(diffInHours: number): [number, DatapointInterval] {
- if(diffInHours <= 1) {
+ if (diffInHours <= 1) {
return [5, DatapointInterval.MINUTE];
- } else if(diffInHours <= 3) {
+ } else if (diffInHours <= 3) {
return [10, DatapointInterval.MINUTE];
- } else if(diffInHours <= 6) {
+ } else if (diffInHours <= 6) {
return [30, DatapointInterval.MINUTE];
- } else if(diffInHours <= 24) { // one day
+ } else if (diffInHours <= 24) { // one day
return [1, DatapointInterval.HOUR];
- } else if(diffInHours <= 48) { // two days
+ } else if (diffInHours <= 48) { // two days
return [3, DatapointInterval.HOUR];
- } else if(diffInHours <= 96) {
+ } else if (diffInHours <= 96) {
return [12, DatapointInterval.HOUR];
- } else if(diffInHours <= 744) { // one month
+ } else if (diffInHours <= 744) { // one month
return [1, DatapointInterval.DAY];
} else {
return [1, DatapointInterval.MONTH];
@@ -1068,7 +1217,7 @@ export class OrChart extends translate(i18next)(LitElement) {
}
protected async _loadData() {
- if (this._data || !this.assetAttributes || !this.assets || (this.assets.length === 0 && !this.dataProvider) || (this.assetAttributes.length === 0 && !this.dataProvider) || !this.datapointQuery) {
+ if ((this._data && !this._zoomChanged) || !this.assetAttributes || !this.assets || (this.assets.length === 0 && !this.dataProvider) || (this.assetAttributes.length === 0 && !this.dataProvider) || !this.datapointQuery) {
return;
}
@@ -1082,52 +1231,59 @@ export class OrChart extends translate(i18next)(LitElement) {
}
this._loading = true;
-
- const dates: [Date, Date] = this.timePresetOptions!.get(this.timePresetKey!)!(new Date());
- 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);
-
- const stepSize: number = intervalArr[0];
- const interval: DatapointInterval = intervalArr[1];
-
- const lowerCaseInterval = interval.toLowerCase();
- this._timeUnits = lowerCaseInterval as TimeUnit;
- this._stepSize = stepSize;
- const now = moment().toDate().getTime();
- let predictedFromTimestamp = now < this._startOfPeriod ? this._startOfPeriod : now;
-
- const data: ChartDataset<"line", ScatterDataPoint[]>[] = [];
+ const dates: [Date, Date] = this._getTimeSelectionDates(this.timePrefixKey!, this.timeWindowKey!);
+ const data: LineChartData[] = [];
let promises;
+ if(!this._zoomChanged || !this._startOfPeriod || !this._endOfPeriod) {
+ // If zoom has changed, we want to keep the previous start and end of period
+ this._startOfPeriod = this.timeframe ? this.timeframe[0].getTime() : dates[0].getTime();
+ this._endOfPeriod = this.timeframe ? this.timeframe[1].getTime() : dates[1].getTime();
+ }
+
try {
- if(this.dataProvider) {
- await this.dataProvider(this._startOfPeriod, this._endOfPeriod, (interval.toString() as TimeUnit), stepSize).then((dataset) => {
- dataset.forEach((set) => { data.push(set); });
+ if(this.dataProvider && !this._zoomChanged) {
+ await this.dataProvider(this._startOfPeriod, this._endOfPeriod).then(dataset => {
+ dataset.forEach(set => data.push(set));
});
} else {
this._dataAbortController = new AbortController();
promises = this.assetAttributes.map(async ([assetIndex, attribute], index) => {
const asset = this.assets[assetIndex];
- const shownOnRightAxis = !!this.rightAxisAttributes.find(ar => ar.id === asset.id && ar.name === attribute.name);
+ const shownOnRightAxis = !!this.attributeConfig?.rightAxisAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);
+ const smooth = !!this.attributeConfig?.smoothAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);
+ const stacked = this.stacked;
+ const stepped = !!this.attributeConfig?.steppedAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);
+ const area = !!this.attributeConfig?.areaAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);
+ const faint = !!this.attributeConfig?.faintAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);
+ const extended = !!this.attributeConfig?.extendedAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);
+ const color = this.attributeColors.find(x => x[0].id === asset.id && x[0].name === attribute.name)?.[1];
const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attribute.name, attribute);
const label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, false);
const unit = Util.resolveUnits(Util.getAttributeUnits(attribute, descriptors[0], asset.type));
const colourIndex = index % this.colors.length;
const options = { signal: this._dataAbortController?.signal };
- let dataset = await this._loadAttributeData(asset, attribute, this.colors[colourIndex], this._startOfPeriod!, this._endOfPeriod!, false, asset.name + " " + label, options);
- (dataset as any).assetId = asset.id;
- (dataset as any).attrName = attribute.name;
- (dataset as any).unit = unit;
- (dataset as any).yAxisID = shownOnRightAxis ? 'y1' : 'y';
+
+ // Load Historic Data
+ let dataset = await this._loadAttributeData(asset, attribute, color ?? this.colors[colourIndex], false, smooth, stacked, stepped, area, faint, false, `${asset.name} ${label}`, options, unit);
+ dataset.assetId = asset.id;
+ dataset.attrName = attribute.name;
+ dataset.unit = unit;
+ dataset.yAxisIndex = shownOnRightAxis ? 1 : 0;
data.push(dataset);
- dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, this.colors[colourIndex], predictedFromTimestamp, this._endOfPeriod!, true, asset.name + " " + label + " " + i18next.t("predicted"), options);
- (dataset as any).unit = unit;
+ // Load Predicted Data
+ dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, color ?? this.colors[colourIndex], true, smooth, stacked, stepped, area, faint, false , `${asset.name} ${label} ${i18next.t("predicted")}`, options, unit);
data.push(dataset);
+
+ // If necessary, load Extended Data
+ if (extended) {
+ dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, color ?? this.colors[colourIndex], false, false, stacked, false, area, faint, extended, `${asset.name} ${label} lastKnown`, options, unit);
+ dataset.yAxisIndex = shownOnRightAxis ? 1 : 0;
+ data.push(dataset);
+ }
+
});
}
@@ -1137,6 +1293,7 @@ export class OrChart extends translate(i18next)(LitElement) {
this._data = data;
this._loading = false;
+ this._zoomChanged = false;
} catch (ex) {
console.error(ex);
@@ -1144,6 +1301,7 @@ export class OrChart extends translate(i18next)(LitElement) {
return; // If request has been canceled (using AbortController); return, and prevent _loading is set to false.
}
this._loading = false;
+ this._zoomChanged = false;
if(isAxiosError(ex)) {
if(ex.message.includes("timeout")) {
@@ -1158,60 +1316,295 @@ export class OrChart extends translate(i18next)(LitElement) {
}
}
+ protected async _loadAttributeData(asset: Asset, attribute: Attribute<any>, color: string, predicted: boolean, smooth: boolean, stacked: boolean, stepped: boolean, area: boolean, faint: boolean, extended: boolean, label?: string, options?: any, unit?: any): Promise<LineChartData> {
- protected async _loadAttributeData(asset: Asset, attribute: Attribute<any>, color: string | undefined, from: number, to: number, predicted: boolean, label?: string, options?: any): Promise<ChartDataset<"line", ScatterDataPoint[]>> {
+ function rgba (color: string, alpha: number) {
+ return `rgba(${parseInt(color.slice(-6,-4), 16)}, ${parseInt(color.slice(-4,-2), 16)}, ${parseInt(color.slice(-2), 16)}, ${alpha})`;
+ }
- const dataset: ChartDataset<"line", ScatterDataPoint[]> = {
- borderColor: color,
- backgroundColor: color,
- label: label,
- pointRadius: 2,
- fill: false,
+ const dataset = {
+ name: label,
+ type: "line",
data: [],
- borderDash: predicted ? [2, 4] : undefined
- };
+ sampling: "lttb",
+ lineStyle: {
+ color: color,
+ type: predicted ? [2, 4] : extended ? [10, 2] : undefined,
+ opacity: faint ? 0.31 : 1,
+ },
+ symbol: "circle",
+ showSymbol: !faint,
+ itemStyle: {
+ color: color
+ },
+ stack: stacked ? (extended ? "extended" : "total") : undefined,
+ smooth: smooth,
+ step: stepped ? "end" : undefined,
+ extended: extended,
+ predicted: predicted,
+ areaStyle: area ? {color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
+ {
+ offset: 0,
+ color: rgba(color, faint ? 0.1 : 0.5)
+ },
+ {
+ offset: 1,
+ color: rgba(color, 0)
+ }
+ ])} : undefined,
+ } as LineChartData;
if (asset.id && attribute.name && this.datapointQuery) {
let response: GenericAxiosResponse<ValueDatapoint<any>[]>;
const query = JSON.parse(JSON.stringify(this.datapointQuery)); // recreating object, since the changes shouldn't apply to parent components; only or-chart itself.
- query.fromTimestamp = this._startOfPeriod;
- query.toTimestamp = this._endOfPeriod;
-
- if(query.type == 'lttb') {
- // If amount of data points is set, only allow a maximum of 1 points per pixel in width
- // Otherwise, dynamically set amount of data points based on chart width (1000px = 200 data points)
+ if(query.type === "lttb") {
+ // If number of data points is set, only allow a maximum of 1 point per pixel in width
+ // Otherwise, dynamically set number of data points based on chart width (1000px = 100 data points)
if(query.amountOfPoints) {
if(this._chartElem?.clientWidth > 0) {
- query.amountOfPoints = Math.min(query.amountOfPoints, this._chartElem?.clientWidth)
+ query.amountOfPoints = Math.min(query.amountOfPoints, this._chartElem?.clientWidth);
}
} else {
if(this._chartElem?.clientWidth > 0) {
- query.amountOfPoints = Math.round(this._chartElem.clientWidth / 5)
+ query.amountOfPoints = Math.round(this._chartElem.clientWidth / 10);
} else {
- console.warn("Could not grab width of the Chart for estimating amount of data points. Using 100 points instead.")
+ console.warn("Could not grab width of the Chart for estimating amount of data points. Using 100 points instead.");
query.amountOfPoints = 100;
}
}
-
- } else if(query.type === 'interval' && !query.interval) {
+ } else if(query.type === "interval" && !query.interval) {
const diffInHours = (this.datapointQuery.toTimestamp! - this.datapointQuery.fromTimestamp!) / 1000 / 60 / 60;
const intervalArr = this._getInterval(diffInHours);
query.interval = (intervalArr[0].toString() + " " + intervalArr[1].toString()); // for example: "5 minute"
}
- if(!predicted) {
- response = await manager.rest.api.AssetDatapointResource.getDatapoints(asset.id, attribute.name, query, options)
+ // Update start/end dates in DatapointQuery object
+ if (!this._zoomChanged) {
+ query.fromTimestamp = this._startOfPeriod;
+ query.toTimestamp = this._endOfPeriod;
+ } else {
+ query.fromTimestamp = this._zoomStartOfPeriod;
+ query.toTimestamp = this._zoomEndOfPeriod;
+ }
+
+ // Request data using HTTP
+ if (predicted) {
+ response = await manager.rest.api.AssetPredictedDatapointResource.getPredictedDatapoints(asset.id, attribute.name, query, options);
} else {
- response = await manager.rest.api.AssetPredictedDatapointResource.getPredictedDatapoints(asset.id, attribute.name, query, options)
+ if (extended) {
+ // if request is for extended dataset, we want to get the last known value only
+ query.type = "nearest";
+ query.timestamp = new Date().toISOString();
+ }
+ response = await manager.rest.api.AssetDatapointResource.getDatapoints(asset.id, attribute.name, query, options);
}
+ let data: ValueDatapoint<any>[] = [];
+
if (response.status === 200) {
- dataset.data = response.data.filter(value => value.y !== null && value.y !== undefined) as ScatterDataPoint[];
+ data = response.data
+ .filter(value => value.y !== null && value.y !== undefined)
+ .map(point => ({ x: point.x, y: point.y } as ValueDatapoint<any>));
+
+ dataset.data = data.map(point => [point.x, point.y]);
}
- }
+ if (extended) {
+ const firstPoint = dataset.data?.[0] as any[] | undefined;
+ if (firstPoint !== undefined) {
+ // Get the first datapoint's timestamp
+ const firstPointTime = new Date(firstPoint[0]).getTime();
+
+ // If the first point is earlier than startOfPeriod, use startOfPeriod as the starting timestamp
+ const startTimestamp = firstPointTime < query.fromTimestamp!
+ ? new Date(query.fromTimestamp!).toISOString()
+ : firstPoint[0];
+
+ // Use endOfPeriod if it's earlier than now, otherwise use the current time
+ const now = new Date().getTime();
+ const endTimestamp = query.toTimestamp! < now
+ ? new Date(query.toTimestamp!).toISOString()
+ : new Date().toISOString();
+
+ // Create a clean extended line by removing any existing points and adding just two points:
+ // One at the appropriate start time and one at the current time
+ dataset.data = [
+ [startTimestamp, firstPoint[1]],
+ [endTimestamp, firstPoint[1]]
+ ];
+ }
+ }
+ }
return dataset;
}
+ /**
+ * Callback event for the 'datazoom' event of ECharts.
+ * Whenever a user zooms in the chart, we update the start/end time, and refetch chart data.
+ * So, if user is zooming in from a year of data, to only view data of September, we refetch the data of September.
+ * This is also to improve data accuracy, since we're using the LTTB algorithm by default.
+ *
+ * @param event - Payload of the 'datazoom' event
+ * @protected
+ */
+ protected _onZoomChange(event: any) {
+ this._zoomChanged = true;
+ const { start: zoomStartPercentage, end: zoomEndPercentage } = event.batch?.[0] ?? event; // Events triggered by scroll and zoombar return different structures
+
+ //Define the start and end of the period based on the zoomed area
+ this._zoomStartOfPeriod = this._startOfPeriod! + ((this._endOfPeriod! - this._startOfPeriod!) * zoomStartPercentage / 100);
+ this._zoomEndOfPeriod = this._startOfPeriod! + ((this._endOfPeriod! - this._startOfPeriod!) * zoomEndPercentage / 100);
+ this._loadData().then(() => {
+ this._updateChartData();
+ });
+
+ }
+
+ /**
+ * Updates the data in the chart. It will replace existing data.
+ * @param data - Time series data to insert
+ * @param start - Start timestamp
+ * @param end - End timestamp
+ * @protected
+ */
+ protected _updateChartData(data = this._data, start = this._startOfPeriod, end = this._endOfPeriod){
+ if(!this._chart) {
+ console.error("Could not update chart data; the chart is not initialized yet.");
+ return;
+ }
+ this._chart.setOption({
+ xAxis: {
+ min: start,
+ max: end
+ },
+ series: data?.map(series => ({
+ ...series,
+ markLine: {
+ symbol: "none",
+ silent: true,
+ data: [{ name: "", xAxis: new Date().toISOString(), label: { formatter: "{b}" } }],
+ lineStyle: {
+ color: this._style.getPropertyValue("--internal-or-chart-text-color"),
+ type: "solid",
+ width: 1,
+ opacity: 1
+ }
+ }
+ }))
+ });
+ }
+
+ /**
+ * Adds/removes the event listeners for the Chart element.
+ * For example, subscribing / unsubscribing from the element resize or zoom event.
+ *
+ * @param connect - Whether to connect or disconnect event listeners.
+ * @protected
+ */
+ protected _toggleChartEventListeners(connect: boolean){
+ if (connect) {
+ // Add resize eventlisteners to make chart size responsive
+ window.addEventListener("resize", () => this._chart!.resize());
+ this._containerResizeObserver = new ResizeObserver(() => { this._chart!.resize(); this.applyChartResponsiveness();});
+ if (this.shadowRoot) {
+ this._containerResizeObserver.observe(this.shadowRoot!.getElementById('container') as HTMLElement);
+ }
+ // Add event listener for zooming
+ this._zoomHandler = this._chart!.on('datazoom', debounce((params: any) => { this._onZoomChange(params); }, 750));
+ }
+ else if (!connect) {
+ //Disconnect event listeners
+ this._chart!.off('datazoom', this._zoomHandler);
+ this._containerResizeObserver?.disconnect();
+ this._containerResizeObserver = undefined;
+ }
+ }
+
+ /**
+ * Internal function to retrieve a string for the time series data tooltip.
+ * Based on {@link xTime}, it will retrieve data from the dataset, and display the correct value in a tooltip.
+ * It uses the format `{asset + attribute name}: {value} {unit}`. For example, "Light 1 brightness: 30 %"
+ *
+ * @param xTime - Timestamp to use for generating the tooltip
+ * @protected
+ */
+ protected _getTooltipData(xTime: number) {
+ type DataPoint = { timestamp: number; value: number };
+ type tooltipRow = {value: number; text: string};
+ const tooltipArray: tooltipRow[] = [];
+ this._data?.forEach(dataset => {
+ const xTimeIsFuture: boolean = xTime > moment().toDate().getTime();
+ // Load datasets to be shown. Show historic or predicted based on cursor location, dont show extended datasets.
+ if (dataset.data && dataset.data.length > 0 && !dataset.extended && (dataset.predicted === xTimeIsFuture)) {
+ const name = dataset.name;
+ let left = 0;
+ let right = dataset.data.length - 1;
+ let pastDatapoint: DataPoint | null = null;
+ let futureDatapoint: DataPoint | null = null;
+ let displayValue: number | null = null;
+ let exactMatch: boolean = false;
+
+ // Find closest past and future timestamps to given time
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+ const [timestamp, value] = dataset.data[mid] as [number, number];
+ if (timestamp === xTime) {
+ displayValue = value;
+ exactMatch = true;
+ break;
+ } else if (timestamp < xTime) {
+ pastDatapoint = {timestamp, value};
+ left = mid + 1;
+ } else {
+ futureDatapoint = {timestamp, value};
+ right = mid - 1;
+ }
+ }
+
+ // Clear past/future if they are at dataset boundaries (ensuring they remain null if no valid data exists)
+ if (pastDatapoint && pastDatapoint.timestamp > xTime) pastDatapoint = null;
+ if (futureDatapoint && futureDatapoint.timestamp < xTime) futureDatapoint = null;
+
+ // Interpolate or show one of the closest datapoints.
+ if (!exactMatch) {
+ if (pastDatapoint && futureDatapoint && !dataset.step) {
+ // Interpolate between past and future datapoint if they exist, keep up to 2 decimals
+ displayValue = parseFloat((pastDatapoint.value + ((xTime - pastDatapoint.timestamp) / (futureDatapoint.timestamp - pastDatapoint.timestamp)) * (futureDatapoint.value - pastDatapoint.value)).toFixed(2));
+ } else if (!pastDatapoint && futureDatapoint) {
+ //Show nearest future value if at start of dataset
+ displayValue = futureDatapoint.value;
+ } else if (pastDatapoint && (!futureDatapoint || dataset.step == "end")) {
+ //Show nearest past value if: at end of dataset or the stepped setting is active
+ displayValue = pastDatapoint.value;
+ }
+ }
+ if (displayValue) {
+ tooltipArray.push({
+ value: displayValue,
+ text: `<div><span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color: ${dataset.lineStyle?.color}"></span> ${name}: <b>${displayValue} ${dataset.unit}</b></div>`
+ });
+ }
+ }
+ });
+ // Sort by value for better readability
+ tooltipArray.sort((a, b) => b.value - a.value);
+ return tooltipArray.map(t => t.text).join('');
+ }
+
+ /**
+ * Internal function to get the default Chart attribute config.
+ * @protected
+ */
+ protected _getDefaultAttributeConfig(): ChartAttributeConfig {
+ return {
+ rightAxisAttributes: [],
+ smoothAttributes: [],
+ steppedAttributes: [],
+ areaAttributes: [],
+ faintAttributes: [],
+ extendedAttributes: []
+ };
+ }
+
}
diff --git a/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.ts b/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.ts
new file mode 100644
index 000000000..2782785cb
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.ts
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import { TemplateResult, css, html } from "lit";
+import {AttributeAction, AttributesPanel} from "./attributes-panel";
+import {Asset, AttributeRef} from "@openremote/model";
+import { customElement } from "lit/decorators.js";
+import {i18next} from "@openremote/or-translate";
+import { when } from "lit/directives/when.js";
+
+@customElement("attributes-chart-panel")
+export class AttributesChartPanel extends AttributesPanel {
+
+ static get styles() {
+ return [...super.styles, css`
+ .attribute-list-item:hover {
+ padding-bottom: 8px;
+ }
+ `];
+ }
+
+ protected _getAttributeActionsTemplate(asset: Asset, attributeRef: AttributeRef): TemplateResult {
+ return html`
+ <div class="attribute-list-item-actions">
+ <!-- Remove attribute button -->
+ <button class="button-action" title="${i18next.t('delete')}" @click="${() => this.removeWidgetAttribute(attributeRef)}">
+ <or-icon icon="close-circle"></or-icon>
+ </button>
+ </div>
+ ${when(!!this.attributeIconCallback, () => html`
+ <div class="attribute-list-item-actions" style="margin-left: 18px; justify-content: start;">
+ <!-- Custom actions defined by callback -->
+ ${this.attributeActionCallback!(attributeRef).map(action => this._getAttributeActionTemplate(action, asset, attributeRef))}
+ </div>
+ `)}
+ `;
+ }
+
+ protected _getAttributeActionTemplate(action: AttributeAction, asset: Asset, attributeRef: AttributeRef): TemplateResult {
+ // If 'palette', aka 'color palette', show color picker instead.
+ if(action.icon === "palette") {
+ return html`
+ <div style="position: relative;">
+ <input id="chart-color-${attributeRef.id}-${attributeRef.name}" type="color" style="position: absolute; visibility: hidden; height: 24px; width: 24px; padding: 0;" />
+ ${super._getAttributeActionTemplate(action, asset, attributeRef)}
+ </div>
+ `;
+ } else {
+ return super._getAttributeActionTemplate(action, asset, attributeRef);
+ }
+ }
+}
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 fc3f19829..79421a8ad 100644
--- a/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts
+++ b/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts
@@ -1,10 +1,11 @@
import {css, CSSResult, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
import {customElement, property, state} from "lit/decorators.js";
-import {Asset, AssetModelUtil, Attribute, AttributeRef} from "@openremote/model";
+import {Asset, AssetDescriptor, AssetModelUtil, Attribute, AttributeRef} from "@openremote/model";
import {style} from "../style";
import {when} from "lit/directives/when.js";
import {map} from "lit/directives/map.js";
import {guard} from "lit/directives/guard.js";
+import {styleMap} from "lit/directives/style-map.js";
import {i18next} from "@openremote/or-translate";
import "@openremote/or-translate";
import {InputType} from "@openremote/or-mwc-components/or-mwc-input";
@@ -17,7 +18,9 @@ import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
export interface AttributeAction {
icon: string,
tooltip: string,
- disabled: boolean
+ active: boolean,
+ disabled: boolean,
+ color?: string
}
export class AttributeActionEvent extends CustomEvent<{ asset: Asset, attributeRef: AttributeRef, action: AttributeAction }> {
@@ -54,102 +57,117 @@ export class AttributesSelectEvent extends CustomEvent<{ assets: Asset[], attrib
}
const styling = css`
- #attribute-list {
- overflow: auto;
- flex: 1 1 0;
- width: 100%;
- display: flex;
- flex-direction: column;
- }
-
- .attribute-list-item {
- position: relative;
- cursor: pointer;
- display: flex;
- flex-direction: row;
- align-items: stretch;
- gap: 10px;
- padding: 0;
- min-height: 50px;
- }
-
- .attribute-list-item-icon {
- display: flex;
- align-items: center;
- --or-icon-width: 20px;
- }
-
- .attribute-list-item-label {
- display: flex;
- justify-content: center;
- flex: 1 1 0;
- line-height: 16px;
- flex-direction: column;
- }
-
- .attribute-list-item-actions {
- flex: 1;
- justify-content: end;
- align-items: center;
- display: flex;
- gap: 8px;
- }
-
- .attribute-list-item-bullet {
- width: 14px;
- height: 14px;
- border-radius: 7px;
- margin-right: 10px;
- }
-
- .attribute-list-item .button.delete {
- display: none;
- }
-
- .attribute-list-item:hover .button.delete {
- display: block;
- }
-
- .button-action {
- background: none;
- visibility: hidden;
- color: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
- --or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
- display: inline-block;
- border: none;
- padding: 0;
- cursor: pointer;
- }
-
- .attribute-list-item:hover .attribute-list-item-actions {
- background: white;
- z-index: 1;
- }
-
- .attribute-list-item:hover .button-action {
- visibility: visible;
- }
-
- .button-action:hover {
- --or-icon-fill: var(--or-app-color4);
- }
+ #attribute-list {
+ overflow: auto;
+ flex: 1 1 0;
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ }
+
+ .attribute-list-item {
+ position: relative;
+ cursor: pointer;
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
+ align-items: stretch;
+ gap: 0 10px;
+ padding: 0;
+ min-height: 50px;
+ }
+
+ .attribute-list-item-icon {
+ display: flex;
+ align-items: center;
+ --or-icon-width: 20px;
+ min-height: 50px;
+ }
+
+ .attribute-list-item-label {
+ display: flex;
+ justify-content: center;
+ flex: 1 1 0;
+ line-height: 16px;
+ flex-direction: column;
+ overflow: hidden;
+ white-space: nowrap;
+ }
+
+ .attribute-list-item-label > * {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ .attribute-list-item-actions {
+ justify-content: end;
+ align-items: center;
+ display: flex;
+ position: absolute;
+ visibility: hidden;
+ gap: 8px;
+ }
+
+ .attribute-list-item-bullet {
+ width: 14px;
+ height: 14px;
+ border-radius: 7px;
+ margin-right: 10px;
+ }
+
+ .attribute-list-item .button.delete {
+ display: none;
+ }
+
+ .attribute-list-item:hover .button.delete {
+ display: block;
+ }
+
+ .button-action {
+ background: none;
+ visibility: hidden;
+ color: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
+ --or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
+ display: inline-block;
+ border: none;
+ padding: 0;
+ cursor: pointer;
+ }
+
+ .attribute-list-item:hover .attribute-list-item-actions {
+ visibility: visible;
+ position: unset;
+ background: white;
+ z-index: 1;
+ }
+
+ .attribute-list-item:hover .button-action {
+ visibility: visible;
+ }
+
+ .button-action:hover {
+ --or-icon-fill: var(--or-icon-fill--hover, var(--or-app-color4));
+ }
`
@customElement('attributes-panel')
export class AttributesPanel extends LitElement {
- @property()
- protected attributeRefs: AttributeRef[] = [];
+ @property({type: Array})
+ public attributeRefs: AttributeRef[] = [];
- @property()
- protected multi: boolean = false;
+ @property({type: Boolean})
+ public multi = false;
- @property()
- protected onlyDataAttrs: boolean = false;
+ @property({type: Boolean})
+ public onlyDataAttrs = false;
@property()
protected attributeFilter?: (attribute: Attribute<any>) => boolean;
+ @property()
+ protected attributeIconCallback?: (asset: Asset, attribute: Attribute<any>, descriptor?: AssetDescriptor) => TemplateResult;
+
@property()
protected attributeLabelCallback?: (asset: Asset, attribute: Attribute<any>, attributeLabel: string) => TemplateResult;
@@ -253,32 +271,21 @@ export class AttributesPanel extends LitElement {
return html`
<div class="attribute-list-item">
<div class="attribute-list-item-icon">
- <span>${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(asset.type))}</span>
+ ${when(!!this.attributeIconCallback,
+ () => this.attributeIconCallback!(asset, attribute, AssetModelUtil.getAssetDescriptor(asset.type)),
+ () => html`<span>${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(asset.type))}</span>`
+ )}
</div>
<div class="attribute-list-item-label">
${when(!!this.attributeLabelCallback,
- () => this.attributeLabelCallback!(asset, attribute, label),
+ () => this.attributeLabelCallback!(asset, attribute, label),
() => html`
<span>${asset.name}</span>
- <span style="font-size:14px; color:grey;">${label}</span>
+ <span style="color:grey;">${label}</span>
`
)}
</div>
- <div class="attribute-list-item-actions">
-
- <!-- 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(asset, attributeRef, action)}">
- <or-icon icon="${action.icon}"></or-icon>
- </button>
- `);
- })}
- <!-- Remove attribute button -->
- <button class="button-action" title="${i18next.t('delete')}" @click="${() => this.removeWidgetAttribute(attributeRef)}">
- <or-icon icon="close-circle"></or-icon>
- </button>
- </div>
+ ${this._getAttributeActionsTemplate(asset, attributeRef)}
</div>
`;
} else {
@@ -301,4 +308,32 @@ export class AttributesPanel extends LitElement {
`;
}
+ protected _getAttributeActionsTemplate(asset: Asset, attributeRef: AttributeRef): TemplateResult {
+ return html`
+ <div class="attribute-list-item-actions">
+ <!-- Custom actions defined by callback -->
+ ${when(!!this.attributeActionCallback, () => this.attributeActionCallback!(attributeRef).map(
+ action => this._getAttributeActionTemplate(action, asset, attributeRef)
+ ))}
+ <!-- Remove attribute button -->
+ <button class="button-action" title="${i18next.t('delete')}" @click="${() => this.removeWidgetAttribute(attributeRef)}">
+ <or-icon icon="close-circle"></or-icon>
+ </button>
+ </div>
+ `;
+ }
+
+ protected _getAttributeActionTemplate(action: AttributeAction, asset: Asset, attributeRef: AttributeRef): TemplateResult {
+ const styles = styleMap({
+ "--or-icon-fill": action.active ? action?.color || "inherit" : "inherit",
+ "--or-icon-fill--hover": action?.color ?? "unset"
+ });
+ return html`
+ <button class="button-action" .disabled="${action.disabled}" title="${action.tooltip}" style=${styles}
+ @click="${() => this.onAttributeActionClick(asset, attributeRef, action)}">
+ <or-icon icon="${action.icon}"></or-icon>
+ </button>
+ `;
+ }
+
}
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 8da97fe58..2f7153858 100644
--- a/ui/component/or-dashboard-builder/src/settings/chart-settings.ts
+++ b/ui/component/or-dashboard-builder/src/settings/chart-settings.ts
@@ -1,15 +1,19 @@
import {css, html, TemplateResult } from "lit";
-import { customElement } from "lit/decorators.js";
+import { customElement, query } from "lit/decorators.js";
import {WidgetSettings} from "../util/widget-settings";
-import "../panels/attributes-panel";
+import "../panels/attributes-chart-panel";
import "../util/settings-panel";
import {i18next} from "@openremote/or-translate";
+import {debounce} from "lodash";
+import {AttributesChartPanel} from "../panels/attributes-chart-panel";
import {AttributeAction, AttributeActionEvent, AttributesSelectEvent} from "../panels/attributes-panel";
-import {Asset, AssetDatapointIntervalQuery, AssetDatapointIntervalQueryFormula, Attribute, AttributeRef} from "@openremote/model";
+import {Asset, AssetDatapointIntervalQuery, AssetDatapointIntervalQueryFormula, AssetDescriptor, Attribute, AttributeRef} from "@openremote/model";
import {ChartWidgetConfig} from "../widgets/chart-widget";
import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
-import {TimePresetCallback} from "@openremote/or-chart";
import {when} from "lit/directives/when.js";
+import moment from "moment/moment";
+import {ChartAttributeConfig, OrChart} from "@openremote/or-chart";
+import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";
const styling = css`
.switch-container {
@@ -17,19 +21,26 @@ const styling = css`
align-items: center;
justify-content: space-between;
}
-`
+`;
@customElement("chart-settings")
export class ChartSettings extends WidgetSettings {
- protected readonly widgetConfig!: ChartWidgetConfig
+ @query("attributes-chart-panel")
+ protected _attributesPanelElem?: AttributesChartPanel;
- protected timePresetOptions: Map<string, TimePresetCallback> = new Map<string, TimePresetCallback>();
+ protected readonly widgetConfig!: ChartWidgetConfig;
+ protected timeWindowOptions: Map<string, [moment.unitOfTime.DurationConstructor, number]> = new Map<string, [moment.unitOfTime.DurationConstructor, number]>;
+ protected timePrefixOptions: string[] = [];
protected samplingOptions: Map<string, string> = new Map<string, string>();
- public setTimePresetOptions(options: Map<string, TimePresetCallback>) {
- this.timePresetOptions = options;
+ public setTimeWindowOptions(options: Map<string, [moment.unitOfTime.DurationConstructor, number]>) {
+ this.timeWindowOptions = options;
+ }
+
+ public setTimePrefixOptions(options: string[]) {
+ this.timePrefixOptions = options;
}
public setSamplingOptions(options: Map<string, string>) {
@@ -44,68 +55,153 @@ export class ChartSettings extends WidgetSettings {
const attributeFilter: (attr: Attribute<any>) => boolean = (attr): boolean => {
return ["boolean", "positiveInteger", "positiveNumber", "number", "long", "integer", "bigInteger", "negativeInteger", "negativeNumber", "bigNumber", "integerByte", "direction"].includes(attr.type!)
};
+ const attrConfig = this.widgetConfig.attributeConfig;
const min = this.widgetConfig.chartOptions.options?.scales?.y?.min;
const max = this.widgetConfig.chartOptions.options?.scales?.y?.max;
- const isMultiAxis = this.widgetConfig.rightAxisAttributes.length > 0;
- const samplingValue = Array.from(this.samplingOptions.entries()).find((entry => entry[1] === this.widgetConfig.datapointQuery.type))![0]
- const attributeLabelCallback = (asset: Asset, attribute: Attribute<any>, attributeLabel: string) => {
- const isOnRightAxis = isMultiAxis && this.widgetConfig.rightAxisAttributes.find(ar => ar.id === asset.id && ar.name === attribute.name) !== undefined;
- return html`
- <span>${asset.name}</span>
- <span style="font-size:14px; color:grey;">${attributeLabel}</span>
- ${when(isOnRightAxis, () => html`
- <span style="position: absolute; right: 0; margin-bottom: 16px; font-size:14px; color:grey;"><or-translate value="right"></or-translate></span>
- `)}
- `
- }
+ const isMultiAxis = (attrConfig?.rightAxisAttributes?.length || 0) > 0;
+
+ const attributeIconCallback = (asset: Asset, attribute: Attribute<any>, descriptor?: AssetDescriptor) => {
+ let color = this.widgetConfig.attributeColors?.find(a => a[0].id === asset.id && a[0].name === attribute.name)?.[1]?.replace('#', '');
+ if(!color) {
+ const index = this.widgetConfig.attributeRefs?.findIndex(ref => ref.id === asset.id && ref.name === attribute.name);
+ if(index >= 0) color = OrChart.DEFAULT_COLORS?.[index]?.replace('#', '');
+ }
+ return html`<span>${getAssetDescriptorIconTemplate(descriptor, undefined, undefined, color)}</span>`;
+ };
const attributeActionCallback = (attributeRef: AttributeRef): AttributeAction[] => {
- return [{
- icon: this.widgetConfig.rightAxisAttributes.includes(attributeRef) ? "arrow-right-bold" : "arrow-left-bold",
- tooltip: i18next.t('dashboard.toggleAxis'),
- disabled: false
- }]
- }
+ const isOnRightAxis = this.widgetConfig?.attributeConfig?.rightAxisAttributes?.find(a => a.id === attributeRef.id && a.name === attributeRef.name) !== undefined;
+ const isFaint = attrConfig?.faintAttributes?.find(ar => ar.id === attributeRef.id && ar.name === attributeRef.name) !== undefined;
+ const isSmooth = attrConfig?.smoothAttributes?.find(ar => ar.id === attributeRef.id && ar.name === attributeRef.name) !== undefined;
+ const isStepped = attrConfig?.steppedAttributes?.find(ar => ar.id === attributeRef.id && ar.name === attributeRef.name) !== undefined;
+ const isArea = attrConfig?.areaAttributes?.find(ar => ar.id === attributeRef.id && ar.name === attributeRef.name) !== undefined;
+ const isExtended = attrConfig?.extendedAttributes?.find(ar => ar.id === attributeRef.id && ar.name === attributeRef.name) !== undefined;
+ let color = this.widgetConfig?.attributeColors?.find(a => a[0].id === attributeRef.id && a[0].name === attributeRef.name)?.[1];
+ let customColor = false;
+ if (!color) {
+ const index = this.widgetConfig?.attributeRefs?.findIndex(ref => ref.id === attributeRef.id && ref.name === attributeRef.name);
+ if (index >= 0) color = OrChart.DEFAULT_COLORS?.[index];
+ } else {
+ customColor = true;
+ }
+ return [
+ {
+ icon: "palette",
+ tooltip: i18next.t("dashboard.lineColor"),
+ active: customColor,
+ color: color,
+ disabled: false
+ },
+ {
+ icon: "chart-bell-curve-cumulative",
+ tooltip: i18next.t("dashboard.smooth"),
+ active: isSmooth,
+ color: color,
+ disabled: false
+ },
+ {
+ icon: "square-wave",
+ tooltip: i18next.t("dashboard.stepped"),
+ active: isStepped,
+ color: color,
+ disabled: false
+ },
+ {
+ icon: "chart-areaspline-variant",
+ tooltip: i18next.t("dashboard.fill"),
+ active: isArea,
+ color: color,
+ disabled: false
+ },
+ {
+ icon: "arrange-send-backward",
+ tooltip: i18next.t("dashboard.faint"),
+ active: isFaint,
+ color: color,
+ disabled: false
+ },
+ {
+ icon: 'arrow-expand-right',
+ tooltip: i18next.t("dashboard.extendData"),
+ active: isExtended,
+ color: color,
+ disabled: false
+ },
+ {
+ icon: isOnRightAxis ? "arrow-right-bold" : "arrow-left-bold",
+ tooltip: i18next.t("dashboard.toggleAxis"),
+ active: isOnRightAxis,
+ color: color,
+ disabled: false
+ }
+ ];
+ };
+ // Determine the selected timeframe
+ const timePrefix = this.timePrefixOptions.find(prefix => this.widgetConfig?.defaultTimePresetKey?.startsWith(prefix)) ?? this.timePrefixOptions[0];
+ let [_, timeWindow] = this.widgetConfig?.defaultTimePresetKey?.split(timePrefix);
+ if(!timeWindow || !this.timeWindowOptions.has(timeWindow)) timeWindow = Array.from(this.timeWindowOptions.keys())[0];
+
+ // List the available timeframes to select from
+ const prefixOptions = this.timePrefixOptions.map(s => s.toLowerCase());
+ const windowOptions = Array.from(this.timeWindowOptions.keys()).map(s => [s, i18next.t(s.toLowerCase())]);
return html`
<div>
<!-- Attribute selection -->
- <settings-panel displayName="attributes" expanded="${true}">
- <attributes-panel .attributeRefs="${this.widgetConfig.attributeRefs}" multi="${true}" onlyDataAttrs="${true}" .attributeFilter="${attributeFilter}" style="padding-bottom: 12px;"
- .attributeLabelCallback="${attributeLabelCallback}" .attributeActionCallback="${attributeActionCallback}"
+ <settings-panel displayName="attributes" expanded>
+ <attributes-chart-panel .attributeRefs="${this.widgetConfig.attributeRefs}" multi onlyDataAttrs .attributeFilter="${attributeFilter}" style="padding-bottom: 12px;"
+ .attributeIconCallback="${attributeIconCallback}" .attributeActionCallback="${attributeActionCallback}"
@attribute-action="${(ev: AttributeActionEvent) => this.onAttributeAction(ev)}"
@attribute-select="${(ev: AttributesSelectEvent) => this.onAttributesSelect(ev)}"
- ></attributes-panel>
+ ></attributes-chart-panel>
</settings-panel>
- <!-- Display options -->
- <settings-panel displayName="display" expanded="${true}">
+ <!-- Time options -->
+ <settings-panel displayName="time" expanded>
<div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 6px;">
- <!-- Timeframe -->
- <div>
- <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t('timeframeDefault')}" style="width: 100%;"
- .options="${Array.from(this.timePresetOptions.keys())}" value="${this.widgetConfig.defaultTimePresetKey}"
- @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimePresetSelect(ev)}"
+ <!-- This/last selection of timeframe -->
+ <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t('prefixDefault')}" style="width: 100%;"
+ .options="${prefixOptions}" value="${timePrefix.toLowerCase()}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimePrefixSelect(ev)}"
+ ></or-mwc-input>
+ <!-- Select time frame -->
+ <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t('timeframeDefault')}" style="width: 100%;"
+ .options="${windowOptions}" value="${timeWindow}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimeWindowSelect(ev)}"
+ ></or-mwc-input>
+ </div>
+ </settings-panel>
+ <!-- Display options -->
+ <settings-panel displayName="display" expanded>
+ <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 6px;">
+ <div class="switch-container">
+ <span><or-translate value="dashboard.toggleStackView"></or-translate></span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.stacked}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onStackViewToggle(ev)}"
></or-mwc-input>
</div>
- <!-- Y Min/max options -->
- <div>
- <div class="switch-container">
- <span><or-translate value="dashboard.allowTimerangeSelect"></or-translate></span>
- <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${!this.widgetConfig.showTimestampControls}"
- @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimestampControlsToggle(ev)}"
- ></or-mwc-input>
- </div>
- <div class="switch-container">
- <span><or-translate value="dashboard.showLegend"></or-translate></span>
- <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.showLegend}"
- @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onShowLegendToggle(ev)}"
- ></or-mwc-input>
- </div>
+ <div class="switch-container">
+ <span><or-translate value="dashboard.allowTimerangeSelect"></or-translate></span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${!this.widgetConfig.showTimestampControls}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimestampControlsToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ <div class="switch-container">
+ <span><or-translate value="dashboard.showLegend"></or-translate></span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.showLegend}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onShowLegendToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ <!-- Datazoombar -->
+ <div class="switch-container">
+ <span><or-translate value="dashboard.showZoomBar"></or-translate></span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.showZoomBar}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onShowZoomBarToggle(ev)}"
+ ></or-mwc-input>
</div>
</div>
</settings-panel>
<!-- Axis configuration -->
- <settings-panel displayName="dashboard.axisConfig" expanded="${true}">
+ <settings-panel displayName="dashboard.axisConfig" expanded>
<div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 16px;">
<!-- Left axis configuration -->
@@ -177,39 +273,45 @@ export class ChartSettings extends WidgetSettings {
></or-mwc-input>
</div>
</div>
- `
+ `;
})}
</div>
</settings-panel>
<!-- Data sampling options -->
- <settings-panel displayName="dataSampling" expanded="${true}">
- <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 12px;">
- <div>
- <or-mwc-input .type="${InputType.SELECT}" style="width: 100%" .options="${Array.from(this.samplingOptions.keys())}" .value="${samplingValue}"
- label="${i18next.t('algorithm')}" @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onSamplingQueryChange(ev)}"
- ></or-mwc-input>
- </div>
- <div>
- ${this.getSamplingOptionsTemplate(this.widgetConfig.datapointQuery.type)}
- </div>
- </div>
- </settings-panel>
+ ${when(Array.from(this.samplingOptions?.keys()).length > 1, () => {
+ const samplingOptions = Array.from(this.samplingOptions.entries());
+ const samplingValue = samplingOptions?.find((entry => entry[1] === this.widgetConfig.datapointQuery.type))?.[0] ?? samplingOptions[0];
+ return html`
+ <settings-panel displayName="dataSampling" expanded="${false}">
+ <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 12px;">
+ <div>
+ <or-mwc-input .type="${InputType.SELECT}" style="width: 100%" .options="${Array.from(this.samplingOptions.keys())}" .value="${samplingValue}"
+ label="${i18next.t('algorithm')}" @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onSamplingQueryChange(ev)}"
+ ></or-mwc-input>
+ </div>
+ <div>
+ ${this.getSamplingOptionsTemplate(this.widgetConfig.datapointQuery.type)}
+ </div>
+ </div>
+ </settings-panel>
+ `;
+ })}
</div>
`;
}
- protected getSamplingOptionsTemplate(type: any): TemplateResult {
+ protected getSamplingOptionsTemplate(type: string): TemplateResult {
switch (type) {
- case 'interval': {
+ case "interval": {
const intervalQuery = this.widgetConfig.datapointQuery as AssetDatapointIntervalQuery;
const formulaOptions = [AssetDatapointIntervalQueryFormula.AVG, AssetDatapointIntervalQueryFormula.MIN, AssetDatapointIntervalQueryFormula.MAX];
return html`
<or-mwc-input .type="${InputType.SELECT}" style="width: 100%;" .options="${formulaOptions}"
- .value="${intervalQuery.formula}" label="${i18next.t('algorithmMethod')}" @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- intervalQuery.formula = event.detail.value;
- this.notifyConfigUpdate();
- }}"
+ .value="${intervalQuery.formula}" label="${i18next.t("algorithmMethod")}" @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ intervalQuery.formula = event.detail.value;
+ this.notifyConfigUpdate();
+ }}"
></or-mwc-input>
`;
}
@@ -218,49 +320,156 @@ export class ChartSettings extends WidgetSettings {
}
}
- // When a user clicks on ANY action in the attribute list, we want to switch between LEFT and RIGHT axis.
- // Since that is the only action, there is no need to check the ev.action variable.
+ // Check which icon was pressed and act accordingly.
protected onAttributeAction(ev: AttributeActionEvent) {
- if(this.widgetConfig.attributeRefs.indexOf(ev.detail.attributeRef) >= 0) {
- if(this.widgetConfig.rightAxisAttributes.includes(ev.detail.attributeRef)) {
- this.removeFromRightAxis(ev.detail.attributeRef);
- } else {
- this.addToRightAxis(ev.detail.attributeRef);
- }
- this.notifyConfigUpdate();
+ const {attributeRef, action } = ev.detail;
+ switch (action.icon) {
+ case "palette":
+ this.openColorPickDialog(attributeRef);
+ break;
+ case "arrow-right-bold":
+ case "arrow-left-bold":
+ this._toggleAttributeSetting("rightAxisAttributes", attributeRef);
+ break;
+ case "chart-bell-curve-cumulative":
+ this._toggleAttributeSetting("smoothAttributes", attributeRef);
+ break;
+ case "square-wave":
+ this._toggleAttributeSetting("steppedAttributes", attributeRef);
+ break;
+ case "chart-areaspline-variant":
+ this._toggleAttributeSetting("areaAttributes", attributeRef);
+ break;
+ case "arrange-send-backward":
+ this._toggleAttributeSetting("faintAttributes", attributeRef);
+ break;
+ case "arrow-expand-right":
+ this._toggleAttributeSetting("extendedAttributes", attributeRef);
+ break;
+ default:
+ console.warn("Unknown attribute panel action:", action);
}
}
// When the list of attributeRefs is changed by the asset selector,
- // we should remove the "right axis" references for the attributes that got removed.
+ // we should remove the settings 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.attributeRefs.includes(ar));
- removedAttributeRefs.forEach(raf => this.removeFromRightAxis(raf));
+
+ removedAttributeRefs.forEach(raf => {
+ this.removeFromAttributeConfig(raf);
+ this.removeFromAttributeColors(raf);
+ });
+
this.widgetConfig.attributeRefs = ev.detail.attributeRefs;
this.notifyConfigUpdate();
}
- protected addToRightAxis(attributeRef: AttributeRef, notify = false) {
- if(!this.widgetConfig.rightAxisAttributes.includes(attributeRef)) {
- this.widgetConfig.rightAxisAttributes.push(attributeRef);
- if(notify) {
- this.notifyConfigUpdate();
+ protected removeFromAttributeConfig(attributeRef: AttributeRef) {
+ const config = this.widgetConfig.attributeConfig;
+ if(config) {
+ (Object.keys(config) as (keyof typeof config)[]).forEach(key => {
+ config[key] = config[key]?.filter((ar: AttributeRef) => ar.id !== attributeRef.id || ar.name !== attributeRef.name);
+ });
+ }
+ }
+
+ /**
+ * Internal function that removes/adds an {@link AttributeRef} to a category of the {@link AttributeConfig}.
+ * For example, you can add an attribute to the array of 'rightAxisAttributes'.
+ * If the attribute is already present, it will be removed automatically.
+ *
+ * @param setting The key / category to add the attribute to. (for example, 'rightAxisAttributes')
+ * @param attributeRef The asset-attribute combination to add/remove.
+ * @protected
+ */
+ protected _toggleAttributeSetting(setting: keyof ChartAttributeConfig, attributeRef: AttributeRef) {
+ this.widgetConfig.attributeConfig ??= {};
+ this.widgetConfig.attributeConfig[setting] ??= [];
+ const attributes = this.widgetConfig.attributeConfig[setting]!;
+ const index = attributes.findIndex(
+ (item: AttributeRef) => item.id === attributeRef.id && item.name === attributeRef.name
+ );
+ if (index < 0) {
+ // Adding the attribute setting
+ attributes.push(attributeRef);
+ } else {
+ // Removing the attribute setting
+ if (attributes.length === 1) {
+ delete this.widgetConfig.attributeConfig[setting];
+ } else {
+ attributes.splice(index, 1);
}
}
+ this.notifyConfigUpdate();
}
- protected removeFromRightAxis(attributeRef: AttributeRef, notify = false) {
- if(this.widgetConfig.rightAxisAttributes.includes(attributeRef)) {
- this.widgetConfig.rightAxisAttributes.splice(this.widgetConfig.rightAxisAttributes.indexOf(attributeRef), 1);
- if(notify) {
- this.notifyConfigUpdate();
+ protected removeFromAttributeColors(attributeRef: AttributeRef) {
+ this.widgetConfig.attributeColors = this.widgetConfig.attributeColors.filter(x => x[0] !== attributeRef);
+ }
+
+ protected openColorPickDialog(attributeRef: AttributeRef) {
+ const inputElem = this._attributesPanelElem?.shadowRoot?.querySelector(`#chart-color-${attributeRef.id}-${attributeRef.name}`) as HTMLInputElement | undefined;
+ if(inputElem) {
+ let oldColor = this.widgetConfig.attributeColors?.find(x => x[0] === attributeRef)?.[1];
+ if(!oldColor) {
+ const index = this.widgetConfig.attributeRefs?.indexOf(attributeRef);
+ if(index >= 0) {
+ oldColor = OrChart.DEFAULT_COLORS?.[index];
+ }
}
+ // Update value
+ inputElem.value = oldColor ?? "";
+
+ // Listen for changes
+ inputElem.addEventListener("input", debounce(() => {
+ const color = inputElem.value;
+ this.widgetConfig.attributeColors ??= [];
+ const existingColor = this.widgetConfig.attributeColors.find(x => x[0] === attributeRef);
+ if(existingColor) {
+ existingColor[1] = color;
+ } else {
+ this.widgetConfig.attributeColors.push([attributeRef, color]);
+ }
+ this.notifyConfigUpdate();
+ }, 200));
+
+ // Open color picker
+ inputElem.click();
}
}
- protected onTimePresetSelect(ev: OrInputChangedEvent) {
- this.widgetConfig.defaultTimePresetKey = ev.detail.value.toString();
+ protected onTimePrefixSelect(ev: OrInputChangedEvent) {
+ let oldValue = this.widgetConfig.defaultTimePresetKey;
+ const newPrefix = ev.detail.value.toString();
+ const prefixOptions = this.timePrefixOptions;
+ if(!prefixOptions.find(o => oldValue.includes(o))) {
+ oldValue = Array.from(this.timeWindowOptions.keys())[0]; // Old value was invalid, so we replace it in full
+ } else {
+ prefixOptions.forEach(option => oldValue = oldValue.replace(option, ""));
+ }
+ this.widgetConfig.defaultTimePresetKey = newPrefix + oldValue;
+ console.debug(`Updated default time preset to ${this.widgetConfig.defaultTimePresetKey}`);
+ this.notifyConfigUpdate();
+ }
+
+ protected onTimeWindowSelect(ev: OrInputChangedEvent) {
+ let oldValue = this.widgetConfig.defaultTimePresetKey;
+ const newWindow = ev.detail.value.toString();
+ const windowOptions = Array.from(this.timeWindowOptions.keys()).sort((a, b) => b.length - a.length);
+ if(!windowOptions.find(o => oldValue.includes(o))) {
+ oldValue = this.timePrefixOptions[0]; // Old value was invalid, so we replace it in full
+ } else {
+ windowOptions.forEach(window => oldValue = oldValue.replace(window, ""));
+ }
+ this.widgetConfig.defaultTimePresetKey = oldValue + newWindow;
+ console.debug(`Updated default time preset to ${this.widgetConfig.defaultTimePresetKey}`);
+ this.notifyConfigUpdate();
+ }
+
+ protected onStackViewToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.stacked = ev.detail.value;
this.notifyConfigUpdate();
}
@@ -274,6 +483,11 @@ export class ChartSettings extends WidgetSettings {
this.notifyConfigUpdate();
}
+ protected onShowZoomBarToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.showZoomBar = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
protected setAxisMinMaxValue(axis: 'left' | 'right', type: 'min' | 'max', value?: number) {
if(axis === 'left') {
if(type === 'min') {
diff --git a/ui/component/or-dashboard-builder/src/util/settings-panel.ts b/ui/component/or-dashboard-builder/src/util/settings-panel.ts
index f21a8a7c5..ed7ed6644 100644
--- a/ui/component/or-dashboard-builder/src/util/settings-panel.ts
+++ b/ui/component/or-dashboard-builder/src/util/settings-panel.ts
@@ -44,8 +44,8 @@ const styling = css`
@customElement("settings-panel")
export class SettingsPanel extends LitElement {
- @property()
- protected expanded: boolean = false;
+ @property({type: Boolean})
+ public expanded = false;
@property()
protected displayName?: string;
diff --git a/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts b/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts
index 8e656ff4f..923f7d5bb 100644
--- a/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts
+++ b/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts
@@ -1,8 +1,8 @@
import {AssetDatapointLTTBQuery, AssetDatapointQueryUnion, Attribute, AttributeRef} from "@openremote/model";
import {html, PropertyValues, TemplateResult } from "lit";
import { when } from "lit/directives/when.js";
-import {TimePresetCallback} from "@openremote/or-chart";
import moment from "moment";
+import {ChartAttributeConfig} from "@openremote/or-chart";
import {OrAssetWidget} from "../util/or-asset-widget";
import { customElement, state } from "lit/decorators.js";
import {AssetWidgetConfig} from "../util/widget-config";
@@ -12,51 +12,55 @@ import {WidgetSettings} from "../util/widget-settings";
import "@openremote/or-chart";
export interface ChartWidgetConfig extends AssetWidgetConfig {
- rightAxisAttributes: AttributeRef[];
+ attributeColors: [AttributeRef, string][];
datapointQuery: AssetDatapointQueryUnion;
- chartOptions?: any; // ChartConfiguration<"line", ScatterDataPoint[]>
+ attributeConfig?: ChartAttributeConfig,
+ chartOptions?: any;
showTimestampControls: boolean;
defaultTimePresetKey: string;
showLegend: boolean;
+ showZoomBar: boolean;
+ stacked: boolean;
}
-function getDefaultTimePresetOptions(): Map<string, TimePresetCallback> {
- return new Map<string, TimePresetCallback>([
- ["lastHour", (date: Date) => [moment(date).subtract(1, 'hour').toDate(), date]],
- ["last24Hours", (date: Date) => [moment(date).subtract(24, 'hours').toDate(), date]],
- ["last7Days", (date: Date) => [moment(date).subtract(7, 'days').toDate(), date]],
- ["last30Days", (date: Date) => [moment(date).subtract(30, 'days').toDate(), date]],
- ["last90Days", (date: Date) => [moment(date).subtract(90, 'days').toDate(), date]],
- ["last6Months", (date: Date) => [moment(date).subtract(6, 'months').toDate(), date]],
- ["lastYear", (date: Date) => [moment(date).subtract(1, 'year').toDate(), date]],
- ["thisHour", (date: Date) => [moment(date).startOf('hour').toDate(), moment(date).endOf('hour').toDate()]],
- ["thisDay", (date: Date) => [moment(date).startOf('day').toDate(), moment(date).endOf('day').toDate()]],
- ["thisWeek", (date: Date) => [moment(date).startOf('isoWeek').toDate(), moment(date).endOf('isoWeek').toDate()]],
- ["thisMonth", (date: Date) => [moment(date).startOf('month').toDate(), moment(date).endOf('month').toDate()]],
- ["thisYear", (date: Date) => [moment(date).startOf('year').toDate(), moment(date).endOf('year').toDate()]],
- ["yesterday", (date: Date) => [moment(date).subtract(24, 'hours').startOf('day').toDate(), moment(date).subtract(24, 'hours').endOf('day').toDate()]],
- ["thisDayLastWeek", (date: Date) => [moment(date).subtract(1, 'week').startOf('day').toDate(), moment(date).subtract(1, 'week').endOf('day').toDate()]],
- ["previousWeek", (date: Date) => [moment(date).subtract(1, 'week').startOf('isoWeek').toDate(), moment(date).subtract(1, 'week').endOf('isoWeek').toDate()]],
- ["previousMonth", (date: Date) => [moment(date).subtract(1, 'month').startOf('month').toDate(), moment(date).subtract(1, 'month').endOf('month').toDate()]],
- ["previousYear", (date: Date) => [moment(date).subtract(1, 'year').startOf('year').toDate(), moment(date).subtract(1, 'year').endOf('year').toDate()]]
+function getDefaultTimeWindowOptions(): Map<string, [moment.unitOfTime.DurationConstructor, number]> {
+ return new Map<string, [moment.unitOfTime.DurationConstructor, number]>([
+ ["60Minutes", ['minutes', 60]],
+ ["Hour", ['hours', 1]],
+ ["6Hours", ['hours', 6]],
+ ["24Hours", ['hours', 24]],
+ ["Day", ['days', 1]],
+ ["7Days", ['days', 7]],
+ ["Week", ['weeks', 1]],
+ ["30Days", ['days', 30]],
+ ["Month", ['months', 1]],
+ ["90Days", ['days', 90]],
+ ["6Months", ['months', 6]],
+ ["365Days", ['days', 365]],
+ ["Year", ['years', 1]]
]);
}
+function getDefaultTimePrefixOptions(): string[] {
+ return ["this", "last"];
+}
+
function getDefaultSamplingOptions(): Map<string, string> {
- return new Map<string, string>([["lttb", 'lttb'], ["withInterval", 'interval']]);
+ return new Map<string, string>([["lttb", 'lttb']]);
}
function getDefaultWidgetConfig(): ChartWidgetConfig {
- const preset = "last24Hours"
- const dateFunc = getDefaultTimePresetOptions().get(preset) as TimePresetCallback;
- const dates = dateFunc(new Date());
+ const defaultPrefix = getDefaultTimePrefixOptions()[0];
+ const [defaultWindowKey, defaultWindow] = Array.from(getDefaultTimeWindowOptions().entries())[0];
+ const startDate = moment().subtract(defaultWindow[1], defaultWindow[0]).startOf(defaultWindow[0]);
+ const endDate = defaultWindow[1] === 1 ? moment().endOf(defaultWindow[0]) : moment();
return {
attributeRefs: [],
- rightAxisAttributes: [],
+ attributeColors: [],
datapointQuery: {
type: "lttb",
- fromTimestamp: dates[0].getTime(),
- toTimestamp: dates[1].getTime()
+ fromTimestamp: startDate.toDate().getTime(),
+ toTimestamp: endDate.toDate().getTime()
},
chartOptions: {
options: {
@@ -70,17 +74,19 @@ function getDefaultWidgetConfig(): ChartWidgetConfig {
max: undefined
}
}
- },
+ }
},
showTimestampControls: false,
- defaultTimePresetKey: preset,
- showLegend: true
+ defaultTimePresetKey: defaultPrefix + defaultWindowKey,
+ showLegend: true,
+ showZoomBar: false,
+ stacked: false
};
}
/* --------------------------------------------------- */
-@customElement('chart-widget')
+@customElement("chart-widget")
export class ChartWidget extends OrAssetWidget {
@state()
@@ -103,14 +109,15 @@ export class ChartWidget extends OrAssetWidget {
},
getSettingsHtml(config: ChartWidgetConfig): WidgetSettings {
const settings = new ChartSettings(config);
- settings.setTimePresetOptions(getDefaultTimePresetOptions());
+ settings.setTimeWindowOptions(getDefaultTimeWindowOptions());
+ settings.setTimePrefixOptions(getDefaultTimePrefixOptions());
settings.setSamplingOptions(getDefaultSamplingOptions());
return settings;
},
getDefaultConfig(): ChartWidgetConfig {
return getDefaultWidgetConfig();
}
- }
+ };
}
// Method called on every refresh/reload of the widget
@@ -190,11 +197,20 @@ export class ChartWidget extends OrAssetWidget {
</div>
`, () => {
+ const timePrefixList = getDefaultTimePrefixOptions();
+ const timePrefix = timePrefixList.find(prefix => this.widgetConfig?.defaultTimePresetKey?.startsWith(prefix)) ?? timePrefixList[0];
+ const timeWindowList = getDefaultTimeWindowOptions();
+ let [_, timeWindow] = this.widgetConfig?.defaultTimePresetKey?.split(timePrefix);
+ if(!timeWindow || !timeWindowList.has(timeWindow)) timeWindow = Array.from(timeWindowList.keys())[0];
return html`
- <or-chart .assets="${this.loadedAssets}" .assetAttributes="${this.assetAttributes}" .rightAxisAttributes="${this.widgetConfig.rightAxisAttributes}"
+ <or-chart .assets="${this.loadedAssets}" .assetAttributes="${this.assetAttributes}"
+ .attributeColors="${this.widgetConfig?.attributeColors}" ?stacked="${this.widgetConfig?.stacked}"
+ .attributeConfig="${this.widgetConfig?.attributeConfig != null ? this.widgetConfig.attributeConfig : {}}"
.showLegend="${(this.widgetConfig?.showLegend != null) ? this.widgetConfig?.showLegend : true}"
+ .showZoomBar="${(this.widgetConfig?.showZoomBar != null) ? this.widgetConfig?.showZoomBar : true}"
.attributeControls="${false}" .timestampControls="${!this.widgetConfig?.showTimestampControls}"
- .timePresetOptions="${getDefaultTimePresetOptions()}" .timePresetKey="${this.widgetConfig?.defaultTimePresetKey}"
+ .timePrefixOptions="${timePrefixList}" .timeWindowOptions="${timeWindowList}"
+ .timePrefixKey="${timePrefix}" .timeWindowKey="${timeWindow}"
.datapointQuery="${this.datapointQuery}" .chartOptions="${this.widgetConfig?.chartOptions}"
style="height: 100%"
></or-chart>
@@ -208,6 +224,6 @@ export class ChartWidget extends OrAssetWidget {
type: "lttb",
fromTimestamp: moment().set('minute', -60).toDate().getTime(),
toTimestamp: moment().set('minute', 60).toDate().getTime()
- }
+ };
}
}
diff --git a/yarn.lock b/yarn.lock
index 8e93d0a0f..2102347d9 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1386,6 +1386,8 @@ __metadata:
"@openremote/or-chart": "workspace:*"
"@openremote/or-mwc-components": "workspace:*"
"@openremote/util": "workspace:*"
+ chart.js: "npm:^3.6.0"
+ chartjs-adapter-moment: "npm:^1.0.0"
lit: "npm:^2.0.2"
moment: "npm:^2.29.4"
languageName: unknown
@@ -1461,10 +1463,7 @@ __metadata:
"@openremote/util": "workspace:*"
"@types/chart.js": "npm:^2.9.34"
"@types/offscreencanvas": "npm:^2019.6.4"
- chart.js: "npm:^3.6.0"
- chartjs-adapter-moment: "npm:^1.0.0"
- chartjs-plugin-annotation: "npm:^1.1.0"
- jsonpath-plus: "npm:^6.0.1"
+ echarts: "npm:~5.6.0"
lit: "npm:^2.0.2"
moment: "npm:^2.29.4"
languageName: unknown
@@ -3505,15 +3504,6 @@ __metadata:
languageName: node
linkType: hard
-"chartjs-plugin-annotation@npm:^1.1.0":
- version: 1.4.0
- resolution: "chartjs-plugin-annotation@npm:1.4.0"
- peerDependencies:
- chart.js: ^3.1.0
- checksum: 10c0/dfbdcdec2f12dc893e21c9b0a868032e4cd8b8527604e2754d4afc4cdcba8f71c7b7888b35e32ef3751ceb4b0a18aa136987bc1c4e9686f8f248f33d8ecd703b
- languageName: node
- linkType: hard
-
"chokidar@npm:3.5.2":
version: 3.5.2
resolution: "chokidar@npm:3.5.2"