100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
UI: upgrade GridStack dependency to latest version 12 (#2438)
Martin Peeters37131b61bcd9
diff --git a/ui/app/manager/test/fixtures/pages/insights.ts b/ui/app/manager/test/fixtures/pages/insights.tsindex 98c6c85cc..b2411ef6e 100644--- a/ui/app/manager/test/fixtures/pages/insights.ts+++ b/ui/app/manager/test/fixtures/pages/insights.ts@@ -21,7 +21,7 @@ export class InsightsPage implements BasePage {}getBrowser(options?: any) {- return this.page.locator("or-dashboard-browser", options);+ return this.page.locator("or-dashboard-browser #sidebar", options);}getWidgetSettings(options?: any) {@@ -62,7 +62,7 @@ export class InsightsPage implements BasePage {// Manual drag and dropconst count = await this.getWidgets().count();- await this.page.locator("#sidebar .ui-draggable", {hasText: type}).first().hover();+ await this.page.locator("#sidebar .grid-stack-item", {hasText: type}).first().hover();await this.page.mouse.down();await this.page.mouse.move(-200, 0, { steps: 5 }); // Move tiny bit left, so the hover event is triggeredawait this.page.locator(".maingrid").hover({ position: { x: coordinates[0], y: coordinates[1] }});diff --git a/ui/app/manager/test/insights.test.ts b/ui/app/manager/test/insights.test.tsindex 7f0a0506f..e79350a95 100644--- a/ui/app/manager/test/insights.test.ts+++ b/ui/app/manager/test/insights.test.ts@@ -26,7 +26,7 @@ test("Create a Line Chart widget", async ({manager, shared, page, insightsPage})// Make widget larger by resizing it using the handleconst chartWidget = insightsPage.getWidgets({ hasText: "Line Chart" }).first();await expect(chartWidget).toBeVisible();- chartWidget.hover();+ await chartWidget.hover();const handle = page.locator(".ui-resizable-handle.ui-resizable-se").first();await expect(handle).toBeVisible();await handle.hover();@@ -35,14 +35,17 @@ test("Create a Line Chart widget", async ({manager, shared, page, insightsPage})const startX = box!.x + box!.width - 4;const startY = box!.y + box!.height - 4;await page.mouse.down();- await page.mouse.move(startX + (box!.width * 3), startY + (box!.height * 3), { steps: 10 });+ await page.mouse.move(startX + (box!.width * 2), startY + (box!.height * 2), { steps: 50 });await page.mouse.up();- await expect.poll(async () => (await chartWidget.boundingBox())!.width).toBeGreaterThan(box!.width * 3.95);- await expect.poll(async () => (await chartWidget.boundingBox())!.height).toBeGreaterThan(box!.height * 3.95);+ await page.waitForTimeout(100);+ await expect(chartWidget).not.toContainClass("ui-resizable-resizing");+ await expect.poll(async () => (await chartWidget.boundingBox())!.width).toBeGreaterThan(box!.width * 3);+ await expect.poll(async () => (await chartWidget.boundingBox())!.height).toBeGreaterThan(box!.height * 3);await expect(insightsPage.getWidgets()).toHaveCount(1);// Select widget, and add attribute of Asset #2 and Asset #1const attrName = "Energy level";+ await expect(chartWidget).toBeVisible();await chartWidget.click();await expect(insightsPage.getBrowser()).toBeHidden();await expect(insightsPage.getWidgetSettings({ hasText: "Line Chart" })).toBeVisible();diff --git a/ui/component/or-dashboard-builder/package.json b/ui/component/or-dashboard-builder/package.jsonindex ffb358e55..fd50f0b4d 100644--- a/ui/component/or-dashboard-builder/package.json+++ b/ui/component/or-dashboard-builder/package.json@@ -38,7 +38,7 @@"@openremote/or-mwc-components": "workspace:*","@openremote/or-translate": "workspace:*","@openremote/rest": "workspace:*",- "gridstack": "^7.2.0",+ "gridstack": "^12.4.2","lit": "^3.3.1","lodash": "^4.17.21","moment": "^2.29.4"diff --git a/ui/component/or-dashboard-builder/src/index.ts b/ui/component/or-dashboard-builder/src/index.tsindex 3bf5a4853..4be89c67e 100644--- a/ui/component/or-dashboard-builder/src/index.ts+++ b/ui/component/or-dashboard-builder/src/index.ts@@ -211,15 +211,15 @@ export function getActivePreset(gridWidth: number, presets: DashboardScreenPreseexport const widgetTypes: Map<string, WidgetManifest> = new Map<string, WidgetManifest>();export function registerWidgetTypes() {- widgetTypes.set("linechart", ChartWidget.getManifest());+ widgetTypes.set("attributeinput", AttributeInputWidget.getManifest());+ widgetTypes.set("barchart", BarChartWidget.getManifest());+ widgetTypes.set("gateway", GatewayWidget.getManifest());widgetTypes.set("gauge", GaugeWidget.getManifest());widgetTypes.set("image", ImageWidget.getManifest());widgetTypes.set("kpi", KpiWidget.getManifest());+ widgetTypes.set("linechart", ChartWidget.getManifest());widgetTypes.set("map", MapWidget.getManifest());- widgetTypes.set("attributeinput", AttributeInputWidget.getManifest());widgetTypes.set("table", TableWidget.getManifest());- widgetTypes.set("gateway", GatewayWidget.getManifest());- widgetTypes.set("barchart", BarChartWidget.getManifest());}@customElement("or-dashboard-builder")diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts b/ui/component/or-dashboard-builder/src/or-dashboard-browser.tsindex 538f9532d..9ffc8f7cd 100644--- a/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts+++ b/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts@@ -1,12 +1,15 @@-import {GridStack, GridStackNode } from "gridstack";-import {css, html, LitElement, unsafeCSS } from "lit";-import { customElement, state} from "lit/decorators.js";+import {GridStack, GridStackNode} from "gridstack";+import {css, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";+import {customElement, property, query, state} from "lit/decorators.js";import {style} from "./style";import {widgetTypes} from "./index";+import {WidgetManifest} from "./util/or-widget";+import {when} from "lit/directives/when.js";+import {repeat} from "lit/directives/repeat.js";+import {DashboardGridNode} from "./or-dashboard-preview";// TODO: Add webpack/rollup to build so consumers aren't forced to use the same tooling-const gridcss = require('gridstack/dist/gridstack.min.css');-const extracss = require('gridstack/dist/gridstack-extra.css');+const gridcss = require("gridstack/dist/gridstack.min.css");//language=cssconst browserStyling = css`@@ -22,7 +25,6 @@ const browserStyling = css`cursor: grab;}.sidebarItem {- height: 100%;background: white;display: flex;align-items: center;@@ -38,145 +40,144 @@ const browserStyling = css`.itemText {margin-top: 10px;}-`+`;@customElement("or-dashboard-browser")export class OrDashboardBrowser extends LitElement {+ @property({type: Number})+ public columns = 4;++ @property({type: Number})+ public size = 2;++ @property({type: Number})+ public itemSize = 134;++ @state()+ protected sidebarGrid?: GridStack;+@state()- private sidebarGrid?: GridStack;+ protected backgroundGrid?: GridStack;@state()- private backgroundGrid?: GridStack;+ protected items: Map<string, WidgetManifest> = new Map(widgetTypes);+ @query("#sidebarElement")+ protected sidebarElem?: HTMLDivElement;++ @query("#sidebarBgElement")+ protected backgroundElem?: HTMLDivElement;++ protected sidebarHeight = this._getSidebarHeight(this.columns);static get styles() {- return [unsafeCSS(gridcss), unsafeCSS(extracss), browserStyling, style];+ return [unsafeCSS(gridcss), browserStyling, style];}- constructor() {- super();- this.updateComplete.then(() => {- this.renderGrid();- })+ updated(changedProps: PropertyValues) {++ // Apply widgetTypeId to identify what 'card' is linked to what widget type+ this.sidebarGrid?.getGridItems()?.forEach(i => {+ if(i.gridstackNode) (i.gridstackNode as DashboardGridNode).widgetTypeId = i.getAttribute("gs-id") ?? i.id;+ });+ return super.updated(changedProps);+ }++ firstUpdated(changedProps: PropertyValues) {+ this.renderGrid();+ return super.firstUpdated(changedProps);}/* --------------------------------- */protected renderGrid() {- const sidebarElement = this.shadowRoot?.getElementById("sidebarElement");- const coords: Array<[number, number]> = this.generateGridCoords(Array.from(widgetTypes).length);- const sidebarItems: any[] = Array.from(widgetTypes)- .sort((a, b) => a[1].displayName.localeCompare(b[1].displayName))- .map((typeArr, index) => {- return {x: coords[index][0], y: coords[index][1], w: 2, h: 2, widgetTypeId: typeArr[0], locked: true, content: `<div class="sidebarItem"><or-icon icon="${typeArr[1].displayIcon}"></or-icon><span class="itemText">${typeArr[1].displayName}</span>`}- });-- // Setting Sidebar height depending on sidebarItems- let sidebarHeight = 0;- sidebarItems.forEach((item) => {- if((item.y + item.h) > sidebarHeight) {- sidebarHeight = (item.y + item.h);- }- });-- let newSidebarHeight = 0;- if (sidebarItems.length % 2 !== 0) {- // If sidebarHeight is based on nr of widgets in array & is not even add 1- newSidebarHeight = sidebarItems.length + 1- } else {- newSidebarHeight = sidebarItems.length- }- // Creation of the sidebarGrid. Only loads items if already existingif(this.sidebarGrid !== undefined) {- this.sidebarGrid.removeAll();- this.sidebarGrid.load(sidebarItems);- } else {- this.sidebarGrid = GridStack.init({- acceptWidgets: false,- column: 4,- cellHeight: 67,- disableOneColumnMode: true,- disableResize: true,- draggable: {- appendTo: 'parent'- },- margin: 8,- row: newSidebarHeight-- // @ts-ignore typechecking, because we can only provide an HTMLElement (which GridHTMLElement inherits)- }, sidebarElement);-- this.sidebarGrid.load(sidebarItems);-- // If an item gets dropped on the main grid, the dragged item needs to be reset to the sidebar.- // This is done by just loading the initial/original widget back in the sidebar.- // @ts-ignore typechecking since we assume they are not undefined- this.sidebarGrid.on('removed', (_event: Event, items: GridStackNode[]) => {- if(items.length === 1) {- const filteredItems = sidebarItems.filter(widget => {- return (widget.content === items[0].content);- });- this.sidebarGrid?.load([filteredItems[0]]);- }- });-- // On any change, recreate the grid to prevent users moving Sidebar items around.- // @ts-ignore typechecking since we assume they are not undefined- this.sidebarGrid.on('change', (_event: Event, _items: GridStackNode[]) => {- this.renderGrid();- });+ this.sidebarGrid.destroy(false);}+ this.sidebarGrid = GridStack.init({+ acceptWidgets: false,+ animate: false,+ column: this.columns,+ cellHeight: this.itemSize / (this.columns / this.size),+ disableResize: true,+ removable: false,+ draggable: {+ appendTo: "parent"+ },+ margin: 8,+ row: this.sidebarHeight+ }, this.sidebarElem);++ // If an item gets dropped on the main grid, the dragged item needs to be reset to the sidebar.+ // This is done by removing the Widget type from the list, waiting for a Lit lifecycle, and adding it back again.+ // Unfortunately, this is required due to HTML elements having to be rendered before it can "initialize the grid")+ // @ts-ignore typechecking since we assume they are not undefined+ this.sidebarGrid.on("removed", (_event: Event, items: GridStackNode[]) => {+ const originalItems = new Map(this.items);+ const removedTypes = items.map(i => (i as DashboardGridNode).widgetTypeId);+ removedTypes.forEach(typeId => this.items.delete(typeId));+ this.items = new Map(this.items);+ this.updateComplete.then(() => {+ this.items = originalItems;+ this.updateComplete.then(() => this.renderGrid());+ });+ });-- // Seperate Static Background grid (to make it look like the items duplicate)- const sidebarBgElement = this.shadowRoot?.getElementById("sidebarBgElement");- if(this.backgroundGrid != undefined) {- this.backgroundGrid.removeAll();- this.backgroundGrid.load(sidebarItems);-- } else {- this.backgroundGrid = GridStack.init({- staticGrid: true,- column: 4,- cellHeight: 67,- disableOneColumnMode: true,- margin: 8-- // @ts-ignore typechecking, because we can only provide an HTMLElement (which GridHTMLElement inherits)- }, sidebarBgElement);- this.backgroundGrid.load(sidebarItems);+ // Separate Static Background grid (to make it look like the items duplicate)+ if(this.backgroundGrid !== undefined) {+ this.backgroundGrid.destroy(false);}+ this.backgroundGrid = GridStack.init({+ acceptWidgets: false,+ animate: false,+ staticGrid: true,+ column: this.columns,+ cellHeight: this.itemSize / (this.columns / this.size),+ margin: 8+ }, this.backgroundElem);}protected render() {return html`<div id="sidebar">- <div id="sidebarElement" class="grid-stack" style="width: 100%; z-index: 3;"></div>- <div id="sidebarBgElement" class="grid-stack" style="width: 100%; z-index: 2"></div>+ <div id="sidebarElement" class="grid-stack" style="width: 100%; z-index: 3;">+ ${repeat(this.items, ([type]) => type, ([type, manifest]) => this._getSidebarItemTemplate(type, type, manifest))}+ ${when(this.items.size % 2 !== 0, () => this._getEmptyItemTemplate())}+ </div>+ <div id="sidebarBgElement" class="grid-stack" style="width: 100%; z-index: 2">+ ${repeat(this.items, ([type]) => type, ([type, manifest]) => this._getSidebarItemTemplate(`bg-${type}`, type, manifest))}+ ${when(this.items.size % 2 !== 0, () => this._getEmptyItemTemplate())}+ </div></div>- `+ `;}- protected generateGridCoords(count: number): [number, number][] {- const result: [number, number][] = [];- const step = 2;-- let x = 0;- let y = 0;+ protected _getSidebarItemTemplate(id: string, type: string, manifest: WidgetManifest): TemplateResult {+ return html`+ <div class="grid-stack-item" id=${id} gs-id=${type} gs-w=${this.size} gs-h=${this.size} gs-locked="true">+ <div class="grid-stack-item-content sidebarItem">+ <or-icon icon="${manifest.displayIcon}"></or-icon>+ <span class="itemText">${manifest.displayName}</span>+ </div>+ </div>+ `;+ }- for (let i = 0; i < count; i++) {- result.push([x, y]);+ protected _getEmptyItemTemplate() {+ return html`+ <div class="grid-stack-item" gs-id="empty" gs-w=${this.size} gs-h=${this.size} gs-locked="true" gs-no-move="true" style="cursor: default;">+ <div class="grid-stack-item-content"></div>+ </div>+ `;+ }- // Alternate between x and y stepping- if (x === 0) {- x = step;- } else {- x = 0;- y += step;- }+ protected _getSidebarHeight(columns = this.columns, size = this.size) {+ let sidebarHeight = Math.ceil(widgetTypes.size / (columns / size) * size);+ if (sidebarHeight % size !== 0) {+ // If sidebarHeight is based on nr of widgets in array & is not even add 1+ sidebarHeight++;}-- return result;+ return sidebarHeight;}}diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts b/ui/component/or-dashboard-builder/src/or-dashboard-preview.tsindex 1e173aa9c..bf6f56ac4 100644--- a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts+++ b/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts@@ -21,7 +21,6 @@ import {OrDashboardWidgetContainer} from "./or-dashboard-widgetcontainer";// TODO: Add webpack/rollup to build so consumers aren't forced to use the same toolingconst gridcss = require('gridstack/dist/gridstack.min.css');-const extracss = require('gridstack/dist/gridstack-extra.css');//language=cssconst editorStyling = css`@@ -95,9 +94,13 @@ const editorStyling = css`border: 2px solid var(--or-app-color4, ${unsafeCSS(DefaultColor4)});margin: -1px !important; /* to compromise with the extra pixel of border. */}+ .grid-stack-item > .ui-resizable-handle {+ opacity: 0.4;+ }/* Grid lines on the background of the grid */.grid-element {+ min-height: 100%;background-image:linear-gradient(90deg, #E0E0E0, transparent 1px),linear-gradient(90deg, transparent calc(100% - 1px), #E0E0E0),@@ -232,7 +235,7 @@ export class OrDashboardPreview extends LitElement {}static get styles() {- return [unsafeCSS(gridcss), unsafeCSS(extracss), editorStyling, style];+ return [unsafeCSS(gridcss), editorStyling, style];}/* ------------------------------ */@@ -370,7 +373,6 @@ export class OrDashboardPreview extends LitElement {}this.activePreset = newPreset;-// If grid got reset, setup the ResizeObserver again.if(this.grid == null) {const gridHTML = this.shadowRoot?.querySelector(".maingrid");@@ -384,8 +386,7 @@ export class OrDashboardPreview extends LitElement {animate: true,cellHeight: (this.activePreset?.scalingPreset === DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN ? (width / (this.template?.columns ? (this.template.columns / 4) : 2)) : 'initial'),column: this.template?.columns,- disableOneColumnMode: (this.activePreset?.scalingPreset !== DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN),- oneColumnModeDomSort: true,+ columnOpts: (this.activePreset?.scalingPreset === DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN) ? { breakpoints: [{w: this.activePreset?.breakpoint ?? 768, c:1}], columnMax: this.template?.columns } : undefined,draggable: {appendTo: 'parent', // Required to work, seems to be Shadow DOM related.},@@ -400,7 +401,6 @@ export class OrDashboardPreview extends LitElement {gridElement!.style.backgroundSize = "" + this.grid.cellWidth() + "px " + this.grid.getCellHeight() + "px";gridElement!.style.height = "100%";- gridElement!.style.minHeight = "100%";// When an item gets dropped ontop of the grid. GridStack docs say:// "called when an item has been dropped and accepted over a grid. If the item came from another grid, the previous widget node info will also be sent (but dom item long gone)."@@ -577,52 +577,9 @@ export class OrDashboardPreview extends LitElement {</div>`}</div>- <style>- ${cache(when(this.isExtraLargeGrid(),- () => this.applyCustomGridstackGridCSS(this.getGridstackColumns(this.grid) ? this.getGridstackColumns(this.grid)! : this.template.columns!)- ))}- </style>`}- protected getGridstackColumns(grid: GridStack | undefined): number | undefined {- try { return grid?.getColumn(); }- catch (e) { return undefined; }- }-- protected isExtraLargeGrid(): boolean {- return !!this.grid && (- (this.getGridstackColumns(this.grid) && this.getGridstackColumns(this.grid)! > 12)- || !!(this.template?.columns && this.template.columns > 12)- );- }---- private cachedGridstackCSS: Map<number, TemplateResult[]> = new Map<number, TemplateResult[]>();-- // Provides support for > 12 columns in GridStack (which requires manual css edits)- //language=html- protected applyCustomGridstackGridCSS(columns: number): TemplateResult {- if(this.cachedGridstackCSS.has(columns)) {- return html`${this.cachedGridstackCSS.get(columns)!.map((x) => x)}`;- } else {- const htmls: TemplateResult[] = [];- for(let i = 0; i < (columns + 1); i++) {- htmls.push(html`- <style>- .grid-stack > .grid-stack-item[gs-w="${i}"]:not(.ui-draggable-dragging):not(.ui-resizable-resizing) { width: ${100 - (columns - i) * (100 / columns)}% !important; }- .grid-stack > .grid-stack-item[gs-x="${i}"]:not(.ui-draggable-dragging):not(.ui-resizable-resizing) { left: ${100 - (columns - i) * (100 / columns)}% !important; }- </style>- `);- }- this.cachedGridstackCSS.set(columns, htmls);- return html`${htmls.map((x) => x)}`;- }- }---/* ---------------------------------------------- */protected resizeObserver?: ResizeObserver;@@ -653,7 +610,7 @@ export class OrDashboardPreview extends LitElement {}this.previousObserverEntry = entries[0];});- }+ };protected _onGridResize() {console.debug("Grid resize detected. Recreating the grid...");diff --git a/ui/component/or-dashboard-builder/src/service/widget-service.ts b/ui/component/or-dashboard-builder/src/service/widget-service.tsindex 75df65385..21e9596af 100644--- a/ui/component/or-dashboard-builder/src/service/widget-service.ts+++ b/ui/component/or-dashboard-builder/src/service/widget-service.ts@@ -9,7 +9,7 @@ export class WidgetService {public static getManifest(widgetTypeId: string) {const manifest = widgetTypes.get(widgetTypeId);if(!manifest) {- throw new Error("Widget manifest could not be found during widget creation.");+ throw new Error(`Widget manifest could not be found during widget creation. [ID=${widgetTypeId}]`);}return manifest;}diff --git a/yarn.lock b/yarn.lockindex 0508f8141..455a2ae7b 100644--- a/yarn.lock+++ b/yarn.lock@@ -1993,7 +1993,7 @@ __metadata:"@openremote/or-mwc-components": "workspace:*""@openremote/or-translate": "workspace:*""@openremote/rest": "workspace:*"- gridstack: "npm:^7.2.0"+ gridstack: "npm:^12.4.2"lit: "npm:^3.3.1"lodash: "npm:^4.17.21"moment: "npm:^2.29.4"@@ -7286,10 +7286,10 @@ __metadata:languageName: nodelinkType: hard-"gridstack@npm:^7.2.0":- version: 7.3.0- resolution: "gridstack@npm:7.3.0"- checksum: 10c0/f6ebaa8edba123f5e4c3d689ff1fc6b7bf6d9b9da9ab722e842237b32890ae3b4d0211173ba48c54b5d511f8c9ff8a00044a5a42135b6ea189acd6004d5bdead+"gridstack@npm:^12.4.2":+ version: 12.4.2+ resolution: "gridstack@npm:12.4.2"+ checksum: 10c0/9b15dabf24947e3f8d529055cbfcd532449b0ea0d4b2ae3b7419eed1742ea394dd19148b023fcbd7d0d69f2b5bc9df33d0f3e01b4153e96f2a7b767e036499bclanguageName: nodelinkType: hard