@senx/discovery-widgets
Version:
Discovery Widgets Elements
734 lines (733 loc) • 31.2 kB
JavaScript
/*
* Copyright 2022-2024 SenX S.A.S.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { h } from "@stencil/core";
import { DataModel } from "../../model/types";
import { Param } from "../../model/param";
import { Logger } from "../../utils/logger";
import { GTSLib } from "../../utils/gts.lib";
import { ColorLib } from "../../utils/color-lib";
import { Utils } from "../../utils/utils";
import domtoimage from "dom-to-image";
export class DiscoveryLinearGauge {
constructor() {
this.options = new Param();
this.debug = false;
this.vars = '{}';
this.parsing = false;
this.rendering = false;
this.innerVars = {};
this.defOptions = new Param();
this.divider = 1000;
this.isVertical = true;
}
updateRes() {
var _a;
this.convert(GTSLib.getData(this.result) || new DataModel());
this.innerOptions.gauge = Object.assign({ horizontal: true }, this.innerOptions.gauge);
this.isVertical = !((_a = this.innerOptions.gauge) === null || _a === void 0 ? void 0 : _a.horizontal);
}
optionsUpdate(newValue, oldValue) {
var _a, _b, _c, _d;
(_a = this.LOG) === null || _a === void 0 ? void 0 : _a.debug(['optionsUpdate'], newValue, oldValue);
let opts = newValue;
if (!!newValue && typeof newValue === 'string') {
opts = JSON.parse(newValue);
}
if (!Utils.deepEqual(opts, this.innerOptions)) {
opts.gauge = Object.assign({ horizontal: true }, opts.gauge);
this.innerOptions = Object.assign({}, opts);
this.isVertical = !((_b = this.innerOptions.gauge) === null || _b === void 0 ? void 0 : _b.horizontal);
this.convert((_c = this.result) !== null && _c !== void 0 ? _c : new DataModel());
(_d = this.LOG) === null || _d === void 0 ? void 0 : _d.debug(['optionsUpdate 2'], { options: this.innerOptions, newValue, oldValue }, this.chartOpts);
}
}
varsUpdate(newValue, oldValue) {
var _a;
if (!!this.vars && typeof this.vars === 'string') {
this.innerVars = JSON.parse(this.vars);
}
if (this.LOG) {
(_a = this.LOG) === null || _a === void 0 ? void 0 : _a.debug(['varsUpdate'], {
vars: this.vars,
newValue, oldValue,
});
}
}
discoveryEventHandler(event) {
const res = Utils.parseEventData(event.detail, this.options.eventHandler, this.el.id);
if (res.style) {
this.innerStyle = Utils.clone(Object.assign(Object.assign({}, this.innerStyle), res.style));
}
if (res.vars) {
this.innerVars = Utils.clone(Object.assign(Object.assign({}, this.innerVars), res.vars));
}
}
async resize() {
const width = Utils.getContentBounds(this.el.parentElement).w - 4;
if (this.myChart && this.innerWidth !== width) {
this.innerWidth = width;
this.myChart.resize({ width, silent: true });
}
return Promise.resolve();
}
async show(regexp) {
this.myChart.dispatchAction({
type: 'legendSelect',
batch: this.myChart.getOption().series.map(s => ({ name: s.name })).filter(s => new RegExp(regexp).test(s.name)),
});
return Promise.resolve();
}
async hide(regexp) {
this.myChart.dispatchAction({
type: 'legendUnSelect',
batch: this.myChart.getOption().series.map(s => ({ name: s.name })).filter(s => new RegExp(regexp).test(s.name)),
});
return Promise.resolve();
}
async hideById(id) {
if (this.myChart) {
this.myChart.dispatchAction({
type: 'legendUnSelect',
batch: this.myChart.getOption().series
.filter((s, i) => new RegExp(id.toString()).test((s.id || i).toString())),
});
}
return Promise.resolve();
}
async showById(id) {
if (this.myChart) {
this.myChart.dispatchAction({
type: 'legendSelect',
batch: this.myChart.getOption().series
.filter((s, i) => new RegExp(id.toString()).test((s.id || i).toString())),
});
}
return Promise.resolve();
}
// noinspection JSUnusedGlobalSymbols
componentWillLoad() {
var _a;
this.parsing = true;
this.LOG = new Logger(DiscoveryLinearGauge, this.debug);
this.innerVars = JSON.parse(this.vars);
if (typeof this.options === 'string') {
this.innerOptions = JSON.parse(this.options);
}
else {
this.innerOptions = this.options;
}
this.convert(GTSLib.getData(this.result) || new DataModel());
(_a = this.LOG) === null || _a === void 0 ? void 0 : _a.debug(['componentWillLoad'], {
type: this.type,
options: this.innerOptions,
chartOpts: this.chartOpts,
});
}
convert(data) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
let options = Utils.mergeDeep(this.defOptions, this.innerOptions || {});
options = Utils.mergeDeep(options || {}, data.globalParams);
this.innerOptions = Object.assign({}, options);
this.divider = GTSLib.getDivider(this.innerOptions.timeUnit || 'us');
this.isVertical = !((_a = this.innerOptions.gauge) === null || _a === void 0 ? void 0 : _a.horizontal);
if (this.innerOptions.customStyles) {
this.innerStyle = Utils.clone(Object.assign(Object.assign({}, this.innerStyle), (_b = this.innerOptions.customStyles) !== null && _b !== void 0 ? _b : {}));
}
// noinspection JSUnusedAssignment
let gtsList = [];
if (GTSLib.isArray(data.data)) {
data.data = GTSLib.flatDeep(data.data);
(_c = this.LOG) === null || _c === void 0 ? void 0 : _c.debug(['convert', 'isArray']);
if (data.data.length > 0 && GTSLib.isGts(data.data[0])) {
(_d = this.LOG) === null || _d === void 0 ? void 0 : _d.debug(['convert', 'isArray 2']);
gtsList = GTSLib.flattenGtsIdArray(data.data, 0).res;
}
else {
(_e = this.LOG) === null || _e === void 0 ? void 0 : _e.debug(['convert', 'isArray 3']);
gtsList = data.data;
}
}
else {
(_f = this.LOG) === null || _f === void 0 ? void 0 : _f.debug(['convert', 'not array']);
gtsList = [data.data];
}
gtsList = gtsList.filter(d => d !== '');
(_g = this.LOG) === null || _g === void 0 ? void 0 : _g.debug(['convert'], { options: this.innerOptions, gtsList });
const gtsCount = gtsList.length;
let overallMax = (_h = this.innerOptions.maxValue) !== null && _h !== void 0 ? _h : 0;
let overallMin = (_j = this.innerOptions.minValue) !== null && _j !== void 0 ? _j : 0;
const dataStruct = [];
const decimals = (_l = (_k = this.innerOptions.gauge) === null || _k === void 0 ? void 0 : _k.decimals) !== null && _l !== void 0 ? _l : this.innerOptions.decimals;
for (let i = 0; i < gtsCount; i++) {
const c = ColorLib.getColor(i, this.innerOptions.scheme);
const color = ((data.params || [])[i] || { datasetColor: c }).datasetColor || c;
const unit = ((data.params || [])[i] || {}).unit || this.innerOptions.unit || this.unit || '';
const gts = gtsList[i];
if (GTSLib.isGts(gts)) {
let max = Number.MIN_VALUE;
const values = (_m = gts.v) !== null && _m !== void 0 ? _m : [];
const val = (_o = values[values.length - 1]) !== null && _o !== void 0 ? _o : [];
let ts = 0;
let value = 0;
if (val.length > 0) {
value = val[val.length - 1];
ts = val[0];
}
if (!!data.params && !!data.params[i] && !!data.params[i].maxValue) {
max = data.params[i].maxValue;
}
else {
if (overallMax < value) {
overallMax = value;
}
}
let min = Number.MAX_VALUE;
if (!!data.params && !!data.params[i] && !!data.params[i].minValue) {
min = data.params[i].minValue;
}
else {
if (overallMin > value) {
overallMin = value;
}
}
if (decimals) {
value = GTSLib.roundValue(value, decimals);
max = GTSLib.roundValue(max, decimals);
min = GTSLib.roundValue(min, decimals);
}
dataStruct.push({
key: ((data.params || [])[i] || { key: undefined }).key || GTSLib.serializeGtsMetadata(gts),
value, max, min, color, ts, unit,
});
}
else {
// custom data format
let max = Number.MIN_VALUE;
if (!!data.params && !!data.params[i] && !!data.params[i].maxValue) {
max = data.params[i].maxValue;
}
else {
if (overallMax < gts.value || Number.MIN_VALUE) {
overallMax = gts.value || Number.MIN_VALUE;
}
}
let min = Number.MAX_VALUE;
if (!!data.params && !!data.params[i] && !!data.params[i].minValue) {
min = data.params[i].minValue;
}
else {
if (overallMin > gts.value || Number.MAX_VALUE) {
overallMin = gts.value || Number.MAX_VALUE;
}
}
let value = 0;
if (gts.hasOwnProperty('value')) {
value = (_p = gts.value) !== null && _p !== void 0 ? _p : 0;
}
else {
value = gts !== null && gts !== void 0 ? gts : 0;
}
if (decimals) {
value = GTSLib.roundValue(value, decimals);
max = GTSLib.roundValue(max, decimals);
min = GTSLib.roundValue(min, decimals);
}
dataStruct.push({ key: (_q = gts.key) !== null && _q !== void 0 ? _q : '', value, max, min, color, unit });
}
}
(_r = this.LOG) === null || _r === void 0 ? void 0 : _r.debug(['convert', 'dataStruct'], dataStruct);
if (decimals) {
overallMax = GTSLib.roundValue(overallMax, decimals);
overallMin = GTSLib.roundValue(overallMin, decimals);
}
dataStruct.forEach(d => {
d.max = Math.max(overallMax, d.max);
d.min = Math.min(overallMin, d.min);
if (d.max === Number.MIN_VALUE) {
d.max = d.value > 0 ? 100 : 0;
}
if (d.min === Number.MAX_VALUE) {
d.min = d.value < 0 ? -100 : 0;
}
if (d.value > 0) {
d.progress = d.value / d.max * 100.0;
}
else {
d.progress = d.value / d.min * -100.0;
}
});
this.dataStruct = dataStruct;
}
// noinspection JSUnusedGlobalSymbols
componentDidLoad() {
this.parsing = false;
this.rendering = true;
this.rendering = false;
setTimeout(() => this.draw.emit());
}
// noinspection JSUnusedLocalSymbols
async export(_type = 'png') {
var _a, _b, _c;
let bgColor = Utils.getCSSColor(this.el, '--warp-view-bg-color', 'transparent');
bgColor = (_b = ((_a = this.options) !== null && _a !== void 0 ? _a : { bgColor }).bgColor) !== null && _b !== void 0 ? _b : bgColor;
const res = this.result;
const dm = ((_c = (res !== null && res !== void 0 ? res : {
globalParams: Object.assign(Object.assign({}, new Param()), { bgColor }),
}).globalParams) !== null && _c !== void 0 ? _c : Object.assign(Object.assign({}, new Param()), { bgColor }));
bgColor = dm.bgColor || bgColor;
return await domtoimage.toPng(this.root, { height: this.height, width: this.width, bgcolor: bgColor });
}
setMousePosition(e) {
const r = this.el.getBoundingClientRect();
this.tooltip.style.top = `${e.clientY - r.y}px`;
this.tooltip.style.left = `${e.clientX - r.x}px`;
}
showTooltip(data) {
var _a;
this.tooltip.style.display = 'block';
this.tooltip.innerHTML = `<div style="font-size:14px;color:#666;font-weight:400;line-height:1;">${data.ts ? (this.innerOptions.timeMode || 'date') === 'date'
? GTSLib.toISOString(GTSLib.toTimestamp(data.ts, 1, this.innerOptions.timeZone), this.divider, this.innerOptions.timeZone, this.innerOptions.fullDateDisplay ? this.innerOptions.timeFormat : undefined).replace('T', ' ').replace('Z', '')
: data.ts
: ''}</div>
<span class="label">${GTSLib.formatLabel(data.key)}</span>
<span class="value" style="margin-left: ${data.key || '' !== '' ? '20px' : '0'} ">${data.value}${(_a = data.unit) !== null && _a !== void 0 ? _a : ''}</span>`;
}
hideTooltip() {
this.tooltip.style.display = 'none';
}
generateStyle(innerStyle) {
return Object.keys(innerStyle || {}).map(k => k + ' { ' + innerStyle[k] + ' }').join('\n');
}
render() {
var _a, _b;
return [h("style", { key: '21693734b8c09ee2b8a7e3996dedd6f322633894' }, this.generateStyle(this.innerStyle)), h("div", { key: '9d8a62c803a88cac7f315e869298547a6a8886f2', ref: el => this.root = el, onMouseMove: e => this.setMousePosition(e), class: { 'vertical-wrapper': !((_a = this.innerOptions.gauge) === null || _a === void 0 ? void 0 : _a.horizontal) } }, h("div", { key: 'ac8b3e2aa8a9a7c93cdb9c1d9ce49f1e245e10db', class: "wv-tooltip", style: { display: 'none' }, ref: el => this.tooltip = el }), ((_b = this.dataStruct) !== null && _b !== void 0 ? _b : []).map(d => {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
return h("div", { class: {
'discovery-progress-group': true,
'discovery-progress-group-vertical': this.isVertical,
} }, this.innerOptions.showLegend && !((_a = this.innerOptions.gauge) === null || _a === void 0 ? void 0 : _a.horizontal) ?
h("p", { class: "small", innerHTML: GTSLib.formatLabel(d.key) }) : '', h("h3", { class: "discovery-legend" }, (_b = d.value) !== null && _b !== void 0 ? _b : '0', d.unit, " ", !((_c = this.innerOptions.gauge) === null || _c === void 0 ? void 0 : _c.horizontal) ?
h("br", null) : '', h("span", { class: "small" }, "of ", d.value > 0 ? d.max : d.min, d.unit)), h("div", { class: {
'discovery-progress-container-horizontal': (_d = this.innerOptions.gauge) === null || _d === void 0 ? void 0 : _d.horizontal,
'discovery-progress-container-vertical': !((_e = this.innerOptions.gauge) === null || _e === void 0 ? void 0 : _e.horizontal),
} }, d.min < 0 ?
h("div", { class: "discovery-progress negative", onMouseOver: () => this.showTooltip(d), onMouseLeave: () => this.hideTooltip() }, h("div", { class: "ticks" }, Array((((_f = this.innerOptions.gauge) === null || _f === void 0 ? void 0 : _f.showTicks) ? 10 : 0)).fill(0).map(() => h("i", { class: "tick" }))), h("div", { class: "discovery-progress-bar", style: {
width: ((_g = this.innerOptions.gauge) === null || _g === void 0 ? void 0 : _g.horizontal) ? `${Math.abs(d.progress)}%` : 'var(--warp-view-progress-size, 1rem)',
height: !((_h = this.innerOptions.gauge) === null || _h === void 0 ? void 0 : _h.horizontal) ? `${Math.abs(d.progress)}%` : 'var(--warp-view-progress-size, 1rem)',
display: d.progress > 0 ? 'none' : 'block',
backgroundColor: d.color,
} }))
: '', d.max > 0 ?
h("div", { class: "discovery-progress positive", onMouseOver: () => this.showTooltip(d), onMouseLeave: () => this.hideTooltip() }, h("div", { class: "ticks" }, Array((((_j = this.innerOptions.gauge) === null || _j === void 0 ? void 0 : _j.showTicks) ? 10 : 0)).fill(0).map(() => h("i", { class: "tick" }))), h("div", { class: "discovery-progress-bar", style: {
width: ((_k = this.innerOptions.gauge) === null || _k === void 0 ? void 0 : _k.horizontal) ? `${Math.abs(d.progress)}%` : 'var(--warp-view-progress-size, 1rem)',
height: !((_l = this.innerOptions.gauge) === null || _l === void 0 ? void 0 : _l.horizontal) ? `${Math.abs(d.progress)}%` : 'var(--warp-view-progress-size, 1rem)',
backgroundColor: d.color,
display: d.progress < 0 ? 'none' : 'block',
} }))
: ''), this.innerOptions.showLegend && ((_m = this.innerOptions.gauge) === null || _m === void 0 ? void 0 : _m.horizontal) ?
h("p", { class: "small", innerHTML: GTSLib.formatLabel(d.key) }) : '');
}), this.parsing ? h("div", { class: "discovery-chart-spinner" }, h("discovery-spinner", null, "Parsing data...")) : '', this.rendering ? h("div", { class: "discovery-chart-spinner" }, h("discovery-spinner", null, "Rendering data...")) : '')];
}
static get is() { return "discovery-linear-gauge"; }
static get encapsulation() { return "shadow"; }
static get originalStyleUrls() {
return {
"$": ["discovery-linear-gauge.scss"]
};
}
static get styleUrls() {
return {
"$": ["discovery-linear-gauge.css"]
};
}
static get properties() {
return {
"result": {
"type": "string",
"mutable": true,
"complexType": {
"original": "DataModel | string",
"resolved": "DataModel | string",
"references": {
"DataModel": {
"location": "import",
"path": "../../model/types",
"id": "src/model/types.ts::DataModel"
}
}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"getter": false,
"setter": false,
"attribute": "result",
"reflect": false
},
"type": {
"type": "string",
"mutable": false,
"complexType": {
"original": "ChartType",
"resolved": "string",
"references": {
"ChartType": {
"location": "import",
"path": "../../model/types",
"id": "src/model/types.ts::ChartType"
}
}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"getter": false,
"setter": false,
"attribute": "type",
"reflect": false
},
"options": {
"type": "string",
"mutable": false,
"complexType": {
"original": "Param | string",
"resolved": "Param | string",
"references": {
"Param": {
"location": "import",
"path": "../../model/param",
"id": "src/model/param.ts::Param"
}
}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"getter": false,
"setter": false,
"attribute": "options",
"reflect": false,
"defaultValue": "new Param()"
},
"width": {
"type": "number",
"mutable": false,
"complexType": {
"original": "number",
"resolved": "number",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"getter": false,
"setter": false,
"attribute": "width",
"reflect": false
},
"height": {
"type": "number",
"mutable": false,
"complexType": {
"original": "number",
"resolved": "number",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"getter": false,
"setter": false,
"attribute": "height",
"reflect": false
},
"debug": {
"type": "boolean",
"mutable": false,
"complexType": {
"original": "boolean",
"resolved": "boolean",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"getter": false,
"setter": false,
"attribute": "debug",
"reflect": false,
"defaultValue": "false"
},
"unit": {
"type": "string",
"mutable": false,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"getter": false,
"setter": false,
"attribute": "unit",
"reflect": false
},
"vars": {
"type": "string",
"mutable": false,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"getter": false,
"setter": false,
"attribute": "vars",
"reflect": false,
"defaultValue": "'{}'"
}
};
}
static get states() {
return {
"parsing": {},
"rendering": {},
"innerOptions": {},
"innerStyle": {}
};
}
static get events() {
return [{
"method": "draw",
"name": "draw",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": ""
},
"complexType": {
"original": "void",
"resolved": "void",
"references": {}
}
}, {
"method": "dataPointOver",
"name": "dataPointOver",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": ""
},
"complexType": {
"original": "any",
"resolved": "any",
"references": {}
}
}];
}
static get methods() {
return {
"resize": {
"complexType": {
"signature": "() => Promise<void>",
"parameters": [],
"references": {
"Promise": {
"location": "global",
"id": "global::Promise"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "",
"tags": []
}
},
"show": {
"complexType": {
"signature": "(regexp: string) => Promise<void>",
"parameters": [{
"name": "regexp",
"type": "string",
"docs": ""
}],
"references": {
"Promise": {
"location": "global",
"id": "global::Promise"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "",
"tags": []
}
},
"hide": {
"complexType": {
"signature": "(regexp: string) => Promise<void>",
"parameters": [{
"name": "regexp",
"type": "string",
"docs": ""
}],
"references": {
"Promise": {
"location": "global",
"id": "global::Promise"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "",
"tags": []
}
},
"hideById": {
"complexType": {
"signature": "(id: number | string) => Promise<void>",
"parameters": [{
"name": "id",
"type": "string | number",
"docs": ""
}],
"references": {
"Promise": {
"location": "global",
"id": "global::Promise"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "",
"tags": []
}
},
"showById": {
"complexType": {
"signature": "(id: number | string) => Promise<void>",
"parameters": [{
"name": "id",
"type": "string | number",
"docs": ""
}],
"references": {
"Promise": {
"location": "global",
"id": "global::Promise"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "",
"tags": []
}
},
"export": {
"complexType": {
"signature": "(_type?: \"png\" | \"svg\") => Promise<string>",
"parameters": [{
"name": "_type",
"type": "\"svg\" | \"png\"",
"docs": ""
}],
"references": {
"Promise": {
"location": "global",
"id": "global::Promise"
},
"Param": {
"location": "import",
"path": "../../model/param",
"id": "src/model/param.ts::Param"
},
"DataModel": {
"location": "import",
"path": "../../model/types",
"id": "src/model/types.ts::DataModel"
}
},
"return": "Promise<string>"
},
"docs": {
"text": "",
"tags": []
}
}
};
}
static get elementRef() { return "el"; }
static get watchers() {
return [{
"propName": "result",
"methodName": "updateRes"
}, {
"propName": "options",
"methodName": "optionsUpdate"
}, {
"propName": "vars",
"methodName": "varsUpdate"
}];
}
static get listeners() {
return [{
"name": "discoveryEvent",
"method": "discoveryEventHandler",
"target": "window",
"capture": false,
"passive": false
}];
}
}
//# sourceMappingURL=discovery-linear-gauge.js.map