@senx/discovery-widgets
Version:
Discovery Widgets Elements
410 lines (406 loc) • 19.4 kB
JavaScript
import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { b as DataModel } from './types.js';
import { P as Param, U as Utils, G as GTSLib, L as Logger, v as v4 } from './utils.js';
import { i as init } from './index2.js';
import { C as ColorLib } from './color-lib.js';
import { d as defineCustomElement$1 } from './discovery-spinner2.js';
const discoveryCalendarCss = "/*!\n * Copyright 2022 SenX S.A.S.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */:host>div{width:100%;height:100%}:host>div>div{width:100%;height:100%}:host .calendar-wrapper{width:100%;height:100%;overflow-y:auto;overflow-x:hidden;position:absolute;margin-right:5px}:host .calendar-wrapper>div{width:calc(100% - 20px)}:host .wv-tooltip{max-width:300px}:host .wv-tooltip div{word-wrap:anywhere}";
const DiscoveryCalendarStyle0 = discoveryCalendarCss;
const DiscoveryCalendar = /*@__PURE__*/ proxyCustomElement(class DiscoveryCalendar extends HTMLElement {
constructor() {
super();
this.__registerHost();
this.__attachShadow();
this.draw = createEvent(this, "draw", 7);
this.dataPointOver = createEvent(this, "dataPointOver", 7);
this.dataPointSelected = createEvent(this, "dataPointSelected", 7);
this.discoveryEvent = createEvent(this, "discoveryEvent", 7);
this.execError = createEvent(this, "execError", 7);
this.options = new Param();
this.debug = false;
this.language = 'warpscript';
this.vars = '{}';
this.parsing = false;
this.rendering = false;
this.defOptions = new Param();
this.divider = 1000;
this.CAL_SIZE = 150;
this.innerWidth = 0;
this.innerHeight = 0;
this.innerVars = {};
}
varsUpdate(newValue, oldValue) {
var _a;
let vars = this.vars;
if (!!this.vars && typeof this.vars === 'string') {
vars = JSON.parse(this.vars);
}
if (!Utils.deepEqual(vars, this.innerVars)) {
this.innerVars = Utils.clone(vars);
}
(_a = this.LOG) === null || _a === void 0 ? void 0 : _a.debug(['varsUpdate'], { vars: this.vars, newValue, oldValue });
}
updateType(newValue, oldValue) {
if (newValue !== oldValue) {
this.chartOpts = this.convert(GTSLib.getData(this.result));
setTimeout(() => {
this.myChart.setOption(this.chartOpts || {}, true, false);
this.myChart.resize({ height: this.height });
this.setOpts(true);
});
}
}
updateRes() {
this.chartOpts = this.convert(GTSLib.getData(this.result));
setTimeout(() => {
this.myChart.setOption(this.chartOpts || {}, true, false);
this.myChart.resize({ height: this.height });
this.setOpts(true);
});
}
optionsUpdate(newValue, oldValue) {
var _a, _b;
(_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)) {
this.innerOptions = Utils.clone(opts);
if (this.myChart) {
this.chartOpts = this.convert(this.result || new DataModel());
setTimeout(() => {
this.myChart.setOption(this.chartOpts || {}, true, false);
this.myChart.resize({ height: this.height });
this.setOpts(true);
});
}
(_b = this.LOG) === null || _b === void 0 ? void 0 : _b.debug(['optionsUpdate 2'], { options: this.innerOptions, newValue, oldValue }, this.chartOpts);
}
}
async resize() {
const dims = Utils.getContentBounds(this.el.parentElement);
const width = dims.w - 4;
const height = dims.h;
if (this.myChart && (this.innerWidth !== width || this.innerHeight !== dims.h)) {
this.innerWidth = width;
this.innerHeight = this.innerHeight !== dims.h ? height - this.el.parentElement.offsetTop : this.innerHeight;
this.myChart.resize({ width: this.innerWidth, height: this.innerHeight, silent: true });
}
return Promise.resolve();
}
async show(regexp) {
this.myChart.dispatchAction({
type: 'legendSelect',
batch: this.myChart.getOption().series.filter(s => new RegExp(regexp).test(s.name)),
});
return Promise.resolve();
}
async hide(regexp) {
this.myChart.dispatchAction({
type: 'legendUnSelect',
batch: this.myChart.getOption().series.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) => { var _a; return new RegExp(id.toString()).test(((_a = s.id) !== null && _a !== void 0 ? _a : i).toString()); }),
});
}
return Promise.resolve();
}
async showById(id) {
if (this.myChart) {
this.myChart.dispatchAction({
type: 'legendSelect',
batch: this.myChart.getOption().series
.filter((s, i) => { var _a; return new RegExp(id.toString()).test(((_a = s.id) !== null && _a !== void 0 ? _a : i).toString()); }),
});
}
return Promise.resolve();
}
// noinspection JSUnusedGlobalSymbols
componentWillLoad() {
var _a, _b, _c;
this.parsing = true;
this.LOG = new Logger(DiscoveryCalendar, this.debug);
if (typeof this.options === 'string') {
this.innerOptions = JSON.parse(this.options);
}
else {
this.innerOptions = this.options;
}
this.result = GTSLib.getData(this.result);
this.divider = GTSLib.getDivider((_a = this.innerOptions.timeUnit) !== null && _a !== void 0 ? _a : 'us');
this.chartOpts = this.convert((_b = this.result) !== null && _b !== void 0 ? _b : new DataModel());
this.setOpts();
(_c = this.LOG) === null || _c === void 0 ? void 0 : _c.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;
let options = Utils.mergeDeep(this.defOptions, this.innerOptions || {});
options = Utils.mergeDeep(options || {}, data.globalParams);
this.innerOptions = Object.assign({}, options);
const series = [];
const calendar = [];
const titles = [];
const visualMap = [];
let gtsList;
if (GTSLib.isArray(data.data)) {
data.data = GTSLib.flatDeep(data.data);
(_a = this.LOG) === null || _a === void 0 ? void 0 : _a.debug(['convert', 'isArray']);
if (data.data.length > 0 && GTSLib.isGts(data.data[0])) {
(_b = this.LOG) === null || _b === void 0 ? void 0 : _b.debug(['convert', 'isArray 2']);
gtsList = GTSLib.flattenGtsIdArray(data.data, 0).res;
}
else {
(_c = this.LOG) === null || _c === void 0 ? void 0 : _c.debug(['convert', 'isArray 3']);
gtsList = data.data;
}
}
else {
(_d = this.LOG) === null || _d === void 0 ? void 0 : _d.debug(['convert', 'not array']);
gtsList = [data.data];
}
(_e = this.LOG) === null || _e === void 0 ? void 0 : _e.debug(['convert'], { options: this.innerOptions, gtsList });
const gtsCount = gtsList.length;
let cal = 0;
let seriesIndex = 0;
for (let i = 0; i < gtsCount; i++) {
const datasetNoAlpha = (_h = (_g = ((_f = data.params) !== null && _f !== void 0 ? _f : [])[i]) === null || _g === void 0 ? void 0 : _g.datasetNoAlpha) !== null && _h !== void 0 ? _h : this.innerOptions.datasetNoAlpha;
const gts = gtsList[i];
let min = Number.MAX_SAFE_INTEGER;
let max = Number.MIN_SAFE_INTEGER;
const dataStruct = {};
if (GTSLib.isGtsToPlot(gts) && !!gts.v) {
// add title
titles.push({
text: ((data.params || [])[i] || { key: undefined }).key || GTSLib.serializeGtsMetadata(gts),
left: 'center',
textStyle: {
height: 20, fontSize: 12,
color: Utils.getLabelColor(this.el),
},
top: this.CAL_SIZE * cal + seriesIndex * 20,
});
// Find min/max
(gts.v || []).forEach((v) => {
const value = v[v.length - 1];
const d = GTSLib.toISOString(v[0], this.divider, this.innerOptions.timeZone, undefined);
const y = d.split('-')[0];
dataStruct[y] = dataStruct[y] || {};
// Aggregation
dataStruct[y][d] = dataStruct[y][d] + value || value;
min = Math.min(min, dataStruct[y][d]);
max = Math.max(max, dataStruct[y][d]);
});
Object.keys(dataStruct).forEach(currentRange => {
var _a, _b, _c;
// Add VisualMap and Calendar
visualMap.push({
min, max, show: false,
seriesIndex: cal,
color: ColorLib.getHeatMap(((data.params || [])[i] || {}).scheme || this.innerOptions.scheme),
});
calendar.push({
top: this.CAL_SIZE * cal + (seriesIndex + 1) * 20 + 20,
range: currentRange,
cellSize: ['auto', 15],
itemStyle: {
color: 'transparent',
borderWidth: 1,
borderColor: ColorLib.transparentize(Utils.getGridColor(this.el), datasetNoAlpha ? 1 : 0.5),
},
splitLine: { lineStyle: { width: 2, color: Utils.getGridColor(this.el) } },
dayLabel: {
firstDay: ((_a = this.innerOptions.calendar) === null || _a === void 0 ? void 0 : _a.firstDay) || 0,
nameMap: (_b = this.innerOptions.calendar) === null || _b === void 0 ? void 0 : _b.dayLabel,
color: Utils.getLabelColor(this.el),
},
monthLabel: {
nameMap: (_c = this.innerOptions.calendar) === null || _c === void 0 ? void 0 : _c.monthLabel,
color: Utils.getLabelColor(this.el),
},
yearLabel: { color: Utils.getLabelColor(this.el) },
});
series.push({
type: 'heatmap',
coordinateSystem: 'calendar',
name: ((data.params || [])[i] || { key: undefined }).key || GTSLib.serializeGtsMetadata(gts),
calendarIndex: cal,
data: Object.keys(dataStruct[currentRange]).map(d => [d, dataStruct[currentRange][d]]),
});
cal++;
});
seriesIndex++;
}
}
this.height = this.CAL_SIZE * cal + titles.length * 20 + 40;
(_j = this.LOG) === null || _j === void 0 ? void 0 : _j.debug(['convert', 'series'], { series, calendar, visualMap, titles });
const opts = Object.assign({ title: titles, grid: {
left: 10, top: 10, bottom: 10, right: 10,
containLabel: true,
}, tooltip: {
trigger: 'item',
axisPointer: {
type: 'shadow',
},
backgroundColor: Utils.getCSSColor(this.el, '--warp-view-tooltip-bg-color', 'white'),
hideDelay: this.innerOptions.tooltipDelay || 100,
formatter: (params) => {
return `<div style="font-size:14px;color:#666;font-weight:400;line-height:1;">${GTSLib.toISOString(GTSLib.toTimestamp(params.value[0], this.divider, this.innerOptions.timeZone), this.divider, this.innerOptions.timeZone, this.innerOptions.fullDateDisplay ? this.innerOptions.timeFormat : undefined).replace('T', ' ').replace('Z', '')}</div>
${params.marker}
<span style="font-size:14px;color:#666;font-weight:400;margin-left:2px">${params.seriesName}</span>
<span style="float:right;margin-left:20px;font-size:14px;color:#666;font-weight:900">
${params.value[1]}</span>`;
},
}, toolbox: {
show: this.innerOptions.showControls,
feature: {
saveAsImage: { type: 'png', excludeComponents: ['toolbox'] },
},
}, legend: { bottom: 10, left: 'center', show: false }, visualMap,
series,
calendar }, ((_l = (_k = this.innerOptions) === null || _k === void 0 ? void 0 : _k.extra) === null || _l === void 0 ? void 0 : _l.chartOpts) || {});
((_m = this.innerOptions.actions) !== null && _m !== void 0 ? _m : []).forEach((action) => {
var _a, _b;
if (action.macro) {
opts.toolbox.feature['my' + v4().replaceAll('-', '')] = {
title: (_a = action.title) !== null && _a !== void 0 ? _a : '',
show: true,
icon: (_b = action.icon) !== null && _b !== void 0 ? _b : Utils.DEFICON,
onclick: () => Utils.execAction(action.macro, this),
};
}
});
return opts;
}
async export(type = 'png') {
return Promise.resolve(this.myChart ? this.myChart.getDataURL({
type,
excludeComponents: ['toolbox'],
}) : undefined);
}
setOpts(notMerge = false) {
var _a, _b;
if (!!this.vars && typeof this.vars === 'string') {
this.innerVars = JSON.parse(this.vars);
}
else if (this.vars) {
this.innerVars = this.vars;
}
if ((((_a = this.chartOpts) === null || _a === void 0 ? void 0 : _a.series) || []).length === 0) {
this.chartOpts.title = {
show: true,
textStyle: { color: Utils.getLabelColor(this.el), fontSize: 20 },
text: this.innerOptions.noDataLabel || '',
left: 'center',
top: 'center',
};
this.chartOpts.xAxis = { show: false };
this.chartOpts.yAxis = { show: false };
this.chartOpts.tooltip = { show: false };
}
else {
this.chartOpts.title = Object.assign(Object.assign({}, (_b = this.chartOpts.title) !== null && _b !== void 0 ? _b : {}), { show: false });
}
setTimeout(() => {
var _a;
if (this.myChart) {
this.myChart.setOption((_a = this.chartOpts) !== null && _a !== void 0 ? _a : {}, notMerge, true);
}
});
}
// noinspection JSUnusedGlobalSymbols
componentDidLoad() {
setTimeout(() => {
this.parsing = false;
this.rendering = true;
let initial = false;
this.myChart = init(this.graph, null, {
width: this.width,
height: this.height ? this.height - 10 : undefined,
});
this.myChart.on('rendered', () => {
this.rendering = false;
if (initial) {
setTimeout(() => this.draw.emit());
initial = false;
}
});
this.myChart.on('mouseover', (event) => {
this.dataPointOver.emit({ date: event.value[0], name: event.seriesName, value: event.value[1], meta: {} });
});
this.el.addEventListener('mouseout', () => this.dataPointOver.emit({}));
this.myChart.on('click', (event) => {
this.dataPointSelected.emit({ date: event.value[0], name: event.seriesName, value: event.value[1], meta: {} });
});
this.myChart.setOption(this.chartOpts || {}, true, false);
initial = true;
});
}
render() {
return h("div", { key: 'b90a2cf2b554c13a78792bb16e793962001680e2', class: "calendar-wrapper" }, this.parsing ? h("discovery-spinner", null, "Parsing data...") : '', this.rendering ? h("discovery-spinner", null, "Rendering data...") : '', h("div", { key: '9fc2b3df00965347138194b440fc3021cd268d2b', ref: (el) => this.graph = el }));
}
get el() { return this; }
static get watchers() { return {
"vars": ["varsUpdate"],
"type": ["updateType"],
"result": ["updateRes"],
"options": ["optionsUpdate"]
}; }
static get style() { return DiscoveryCalendarStyle0; }
}, [1, "discovery-calendar", {
"result": [1],
"type": [1],
"options": [1],
"width": [2],
"height": [2],
"debug": [4],
"unit": [1],
"url": [1],
"language": [1],
"vars": [1],
"parsing": [32],
"rendering": [32],
"innerOptions": [32],
"resize": [64],
"show": [64],
"hide": [64],
"hideById": [64],
"showById": [64],
"export": [64]
}, undefined, {
"vars": ["varsUpdate"],
"type": ["updateType"],
"result": ["updateRes"],
"options": ["optionsUpdate"]
}]);
function defineCustomElement() {
if (typeof customElements === "undefined") {
return;
}
const components = ["discovery-calendar", "discovery-spinner"];
components.forEach(tagName => { switch (tagName) {
case "discovery-calendar":
if (!customElements.get(tagName)) {
customElements.define(tagName, DiscoveryCalendar);
}
break;
case "discovery-spinner":
if (!customElements.get(tagName)) {
defineCustomElement$1();
}
break;
} });
}
export { DiscoveryCalendar as D, defineCustomElement as d };
//# sourceMappingURL=discovery-calendar2.js.map