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
Feature/Add global mapsettings override and fine-grain styling support (#1847)
Ekhorndec4c7df55be
diff --git a/manager/src/main/java/org/openremote/manager/map/MapService.java b/manager/src/main/java/org/openremote/manager/map/MapService.javaindex b5b02e272..296d5c61c 100644--- a/manager/src/main/java/org/openremote/manager/map/MapService.java+++ b/manager/src/main/java/org/openremote/manager/map/MapService.java@@ -21,6 +21,7 @@ package org.openremote.manager.map;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.JsonNodeFactory;import com.fasterxml.jackson.databind.node.ObjectNode;import io.undertow.server.HttpHandler;import io.undertow.server.handlers.ResponseCodeHandler;@@ -74,6 +75,8 @@ public class MapService implements ContainerService {public static final String OR_PATH_PREFIX_DEFAULT = "";private static final Logger LOG = Logger.getLogger(MapService.class.getName());private static final String DEFAULT_VECTOR_TILES_URL = "mbtiles://mapdata.mbtiles";+ private static final String DEFAULT_SPRITE_PATH = "map/sprites/bright-v9";+ private static final String DEFAULT_GLYPHS_PATH = "{fontstack}/{range}.pbf";private static ConfigurationService configurationService;// Shared SQL connection is fine concurrently in SQLite@@ -90,25 +93,58 @@ public class MapService implements ContainerService {mapConfig = ValueUtil.JSON.createObjectNode();}- ObjectNode vectorTiles = ValueUtil.JSON.valueToTree(mapConfiguration.sources.get("vector_tiles"));- String tileUrl = Optional.ofNullable(vectorTiles.get("tiles"))- .map(tiles -> tiles.get(0))+ ObjectNode sources = ValueUtil.JSON.valueToTree(mapConfiguration.sources);+ ObjectNode vectorTiles = (ObjectNode)sources.get("vector_tiles");+ String tileJsonUrl = Optional.ofNullable(vectorTiles.get("url")).filter(JsonNode::isTextual).map(JsonNode::textValue).orElse(null);- // Saves custom tile server url if custom is true in the vector_tiles source and the url follows the required xyz scheme.+ ArrayNode tileServerUrls = Optional.ofNullable(vectorTiles.get("tiles"))+ .map(node -> {+ ArrayNode result = JsonNodeFactory.instance.arrayNode();+ StreamSupport.stream(node.spliterator(), false)+ .filter(JsonNode::isTextual)+ .map(JsonNode::textValue)+ .filter(v -> v.contains("/{z}/{x}/{y}"))+ .forEach(result::add);+ return result;+ })+ .orElseGet(JsonNodeFactory.instance::arrayNode);++ // Saves custom tile server url if custom is true in the vector_tiles source and the url follows the required template parameters.// Otherwise, replace it with the default configuration.- if (vectorTiles.get("custom").booleanValue() && tileUrl != null && tileUrl.contains("/{z}/{x}/{y}")) {- vectorTiles.put("url", tileUrl);+ if (vectorTiles.has("custom") && vectorTiles.get("custom").booleanValue()) {+ vectorTiles.put("url", tileJsonUrl);+ vectorTiles.set("tiles", tileServerUrls);} else {vectorTiles = ValueUtil.JSON.createObjectNode().put("type", "vector").put("url", DEFAULT_VECTOR_TILES_URL);+ mapConfig.put("sprite", DEFAULT_SPRITE_PATH);+ mapConfig.put("glyphs", DEFAULT_GLYPHS_PATH);}+ mapConfiguration.sources.clear();mapConfiguration.sources.put("vector_tiles", ValueUtil.JSON.convertValue(vectorTiles, MapSourceConfig.class));+ Iterator<Map.Entry<String, JsonNode>> fields = sources.fields();+ while (fields.hasNext()) {+ Map.Entry<String, JsonNode> field = fields.next();+ if (!Objects.equals(field.getKey(), "vector_tiles")) {+ mapConfiguration.sources.put(field.getKey(), ValueUtil.JSON.convertValue(field.getValue(), MapSourceConfig.class));+ }+ }++ mapConfig.remove("override");+ if (mapConfiguration.override != null) {+ mapConfig.put("override", mapConfiguration.override);+ }mapConfig.putPOJO("options", mapConfiguration.options);mapConfig.putPOJO("sources", mapConfiguration.sources);+ mapConfig.put("sprite", Optional.ofNullable(mapConfiguration.sprite).orElse(DEFAULT_SPRITE_PATH));+ mapConfig.put("glyphs", Optional.ofNullable(mapConfiguration.glyphs).orElse(DEFAULT_GLYPHS_PATH));+ mapConfig.putPOJO("layers", Optional.ofNullable(mapConfiguration.layers).filter(v -> v.length > 0).orElse(+ StreamSupport.stream(configurationService.getMapConfig().get("layers").spliterator(), false).toArray())+ );configurationService.saveMapConfig(mapConfig);mapConfig = configurationService.getMapConfig();@@ -374,6 +410,9 @@ public class MapService implements ContainerService {.filter(JsonNode::isObject).ifPresent(vectorTilesNode -> {ObjectNode vectorTilesObj = (ObjectNode)vectorTilesNode;+ if (vectorTilesObj.has("custom") && vectorTilesObj.get("custom").booleanValue() && vectorTilesObj.hasNonNull("url")) {+ return;+ }vectorTilesObj.remove("url");vectorTilesObj.put("attribution", metadata.attribution);@@ -413,20 +452,20 @@ public class MapService implements ContainerService {// Set sprite URL to shared folderOptional.ofNullable(mapConfig.has("sprite") && mapConfig.get("sprite").isTextual() ? mapConfig.get("sprite").asText() : null).ifPresent(sprite -> {- String spriteUri =+ String spriteUri = sprite.equals(DEFAULT_SPRITE_PATH) ?UriBuilder.fromUri(host).replacePath(pathPrefix + MAP_SHARED_DATA_BASE_URI).path(sprite)- .build().toString();+ .build().toString() : sprite;settings.put("sprite", spriteUri);});// Set glyphs URL to shared folder (tileserver-gl glyphs url cannot contain a path segment so add /fonts hereOptional.ofNullable(mapConfig.has("glyphs") && mapConfig.get("glyphs").isTextual() ? mapConfig.get("glyphs").asText() : null).ifPresent(glyphs -> {- String glyphsUri =+ String glyphsUri = glyphs.equals(DEFAULT_GLYPHS_PATH) ?UriBuilder.fromUri(host).replacePath(pathPrefix + MAP_SHARED_DATA_BASE_URI)- .build().toString() + "/fonts/" + glyphs;+ .build().toString() + "/fonts/" + glyphs : glyphs;settings.put("glyphs", glyphsUri);});@@ -530,7 +569,6 @@ public class MapService implements ContainerService {// Ensure we can access this new file and that it is a valid mbtiles filePath loadedFile = setData(false);- // TODO: Investigate whether this can be combined into setData (see https://github.com/openremote/openremote/issues/1833).// The metadata is set to ensure the bounding box is not outside the visible tile area.saveMapMetadata(metadata);@@ -562,7 +600,6 @@ public class MapService implements ContainerService {if (previousCustomTilesPath.toFile().isFile()) {setData(true);- // TODO: Investigate whether this can be combined into setData (see https://github.com/openremote/openremote/issues/1833).// The metadata is set to ensure the bounding box is not outside the visible tile area.saveMapMetadata(metadata);diff --git a/model/src/main/java/org/openremote/model/manager/MapConfig.java b/model/src/main/java/org/openremote/model/manager/MapConfig.javaindex e791e841c..aea5a0197 100644--- a/model/src/main/java/org/openremote/model/manager/MapConfig.java+++ b/model/src/main/java/org/openremote/model/manager/MapConfig.java@@ -21,7 +21,23 @@ package org.openremote.model.manager;import java.util.Map;+/**+ * Implements MapLibre style spec+ *+ * @see https://maplibre.org/maplibre-style-spec/root/+ */public class MapConfig {+ /**+ * Custom OpenRemote property to override mapconfig with external mapconfig+ * Expects a style.json URL+ */+ public String override;+ /**+ * Custom OpenRemote property to configure mapsettings per realm+ */public Map<String, MapRealmConfig> options;public Map<String, MapSourceConfig> sources;+ public String glyphs;+ public String sprite;+ public Object[] layers;}diff --git a/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy b/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovyindex aa4df5175..8d0c8441a 100644--- a/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy@@ -65,6 +65,50 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {json.options.default.bounds.size() == 4json.sources != nulljson.layers.size() > 0++ when: "custom sprite and glyphs are saved"+ mapSettings = ValueUtil.parse("""{+ "options" : { "default": {} },+ "sources" : {+ "vector_tiles" : {+ "type" : "vector" ,+ "tiles" : [ "https://example.com/tileset/{z}/{x}/{y}.mvt" ],+ "custom" : true+ }+ },+ "sprite": "https://api.example.com/maps/streets/sprite",+ "glyphs": "https://api.example.com/fonts/{fontstack}/{range}.pbf"+ }""", MapConfig.class)+ (ObjectNode)mapResource.saveSettings(null, mapSettings.get())++ and: "retrieve map settings"+ mapSettings = mapResource.getSettings(null)++ then: "JSON content should contain custom sprite and glyphs URLs"+ def json1 = new JsonSlurper().parseText(ValueUtil.asJSON(mapSettings).orElse("null"))+ json1.sprite == "https://api.example.com/maps/streets/sprite"+ json1.glyphs == "https://api.example.com/fonts/{fontstack}/{range}.pbf"++ when: "saving without sprite and glyphs"+ mapSettings = ValueUtil.parse("""{+ "options" : { "default": {} },+ "sources" : {+ "vector_tiles" : {+ "type" : "vector" ,+ "tiles" : [ "https://example.com/tileset/{z}/{x}/{y}.mvt" ],+ "custom" : true+ }+ }+ }""", MapConfig.class)+ (ObjectNode)mapResource.saveSettings(null, mapSettings.get())++ and: "retrieve map settings"+ mapSettings = mapResource.getSettings(null)++ then: "JSON content should contain default sprite and glyphs URLs"+ def json2 = new JsonSlurper().parseText(ValueUtil.asJSON(mapSettings).orElse("null"))+ json2.sprite == "http://127.0.0.1:" + serverPort + MapService.MAP_SHARED_DATA_BASE_URI + "/" + MapService.DEFAULT_SPRITE_PATH+ json2.glyphs == "http://127.0.0.1:" + serverPort + MapService.MAP_SHARED_DATA_BASE_URI + "/fonts/" + MapService.DEFAULT_GLYPHS_PATH}def "Upload custom map tiles"() {@@ -133,15 +177,22 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {"sources" : {"vector_tiles" : {"type" : "vector" ,+ "url" : "https://example.com/tileset/tile.json","tiles" : [ "https://example.com/tileset/{z}/{x}/{y}.mvt" ],"custom" : true}- }+ },+ "sprite": "https://api.example.com/maps/streets/sprite",+ "glyphs": "https://api.example.com/fonts/{fontstack}/{range}.pbf"}""", MapConfig.class)def savedSettings = (ObjectNode)mapResource.saveSettings(null, mapSettings.get())then: "the custom tile server URL should be returned"- savedSettings.get("sources").get("vector_tiles").get("url").textValue() == "https://example.com/tileset/{z}/{x}/{y}.mvt"+ savedSettings.get("sources").get("vector_tiles").get("url").textValue() == "https://example.com/tileset/tile.json"+ savedSettings.get("sources").get("vector_tiles").get("tiles").get(0).textValue() == "https://example.com/tileset/{z}/{x}/{y}.mvt"+ savedSettings.get("sprite").textValue() == "https://api.example.com/maps/streets/sprite"+ savedSettings.get("glyphs").textValue() == "https://api.example.com/fonts/{fontstack}/{range}.pbf"+ savedSettings.get("layers").isArray() && savedSettings.get("layers").size() > 0when: "an invalid tile server URL is configured"mapSettings = ValueUtil.parse("""{@@ -150,13 +201,17 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {"vector_tiles" : {"type" : "vector" ,"tiles" : [ "https://example.com/tileset.mvt" ],- "custom" : true+ "custom" : false}}}""", MapConfig.class)savedSettings = (ObjectNode)mapResource.saveSettings(null, mapSettings.get())then: "the URL should be reset back to normal"+ !savedSettings.get("sources").get("vector_tiles").has("tiles")savedSettings.get("sources").get("vector_tiles").get("url").textValue() == MapService.DEFAULT_VECTOR_TILES_URL+ savedSettings.get("sprite").textValue() == MapService.DEFAULT_SPRITE_PATH+ savedSettings.get("glyphs").textValue() == MapService.DEFAULT_GLYPHS_PATH+ savedSettings.get("layers").isArray() && savedSettings.get("layers").size() > 0}}diff --git a/ui/app/manager/src/components/configuration/or-conf-json.ts b/ui/app/manager/src/components/configuration/or-conf-json.tsindex 9da6a721d..082cf932d 100644--- a/ui/app/manager/src/components/configuration/or-conf-json.ts+++ b/ui/app/manager/src/components/configuration/or-conf-json.ts@@ -24,13 +24,15 @@ import { DialogAction } from "@openremote/or-mwc-components/or-mwc-dialog";import { OrMwcDialog, showDialog } from "@openremote/or-mwc-components/or-mwc-dialog";import { createRef, Ref, ref } from "lit/directives/ref.js";import { OrAceEditor, OrAceEditorChangedEvent } from "@openremote/or-components/or-ace-editor";-import { ManagerAppConfig } from "@openremote/model";+import { ManagerAppConfig, MapConfig } from "@openremote/model";@customElement("or-conf-json")export class OrConfJson extends LitElement {@property({attribute: false})- public managerConfig: ManagerAppConfig = {};+ public config: ManagerAppConfig | MapConfig = {};++ public heading: string;protected _aceEditor: Ref<OrAceEditor> = createRef();@@ -46,15 +48,15 @@ export class OrConfJson extends LitElement {}}- protected _showManagerConfigDialog(){+ protected _showConfigDialog(){let dialog: OrMwcDialog;const _saveConfig = () => {const config = this.beforeSave()if (config) {- this.managerConfig = config as ManagerAppConfig+ this.config = config as ManagerAppConfig | MapConfigthis.dispatchEvent(- new CustomEvent('saveLocalManagerConfig',- {detail: {value: this.managerConfig}}+ new CustomEvent('saveLocalConfig',+ {detail: {value: this.config}}))return true@@ -76,11 +78,11 @@ export class OrConfJson extends LitElement {dialog = new OrMwcDialog().setActions(dialogActions)- .setHeading("manager_config.json")+ .setHeading(this.heading).setContent(html`<or-ace-editor${ref(this._aceEditor)}- .value="${this.managerConfig}"+ .value="${this.config}"@or-ace-editor-changed="${(ev: OrAceEditorChangedEvent) => {const okButton = dialog.actions?.find(action => action.actionName === "ok");if (okButton) {@@ -115,10 +117,7 @@ export class OrConfJson extends LitElement {render() {return html`- <or-mwc-input type="button" label="JSON" outlined icon="pencil" @click="${() => {this._showManagerConfigDialog()}}"></or-mwc-input>+ <or-mwc-input type="button" label="JSON" outlined icon="pencil" @click="${() => {this._showConfigDialog()}}"></or-mwc-input>`}---}diff --git a/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-global.ts b/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-global.tsnew file mode 100644index 000000000..275034042--- /dev/null+++ b/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-global.ts@@ -0,0 +1,264 @@+import { MapConfig } from "@openremote/model";+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";+import { css, html, LitElement } from "lit";+import { customElement, property } from "lit/decorators.js";+import { when } from "lit/directives/when.js"+import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";+import { i18next } from "@openremote/or-translate";+import { StyleSpecification } from "maplibre-gl";++@customElement("or-conf-map-global")+export class OrConfMapGlobal extends LitElement {++ static styles = css`+ .subheader {+ padding: 10px 0 4px;+ font-weight: bolder;+ }++ .map-tile-settings {+ display: flex;+ }++ .map-tile-server-group {+ flex-direction: column;+ width: 50%;+ }++ .map-tile-upload-group {+ flex-direction: column;+ padding-left: 12px;+ width: 50%;+ }++ .map-style-settings {+ display: flex;+ }++ .map-style-server-group {+ flex-direction: column;+ width: 50%;+ }++ .map-style-layers-group {+ flex-direction: column;+ padding-left: 12px;+ width: 50%;+ }++ @media screen and (max-width: 768px) {+ .map-tile-server-group, .map-tile-upload-group,+ .map-style-server-group, .map-style-layers-group {+ width: 100%;+ padding: unset;+ }+ .map-tile-settings, .map-style-settings {+ display: block;+ }+ }++ .input {+ width: 100%;+ max-width: 800px;+ padding: 10px 0;+ }++ .input or-mwc-input:not([icon]) {+ width: 80%;+ }++ .note {+ font-style: italic;+ color: rgba(0, 0, 0, 0.6);+ }++ or-file-uploader {+ width: 108px;+ height: 108px;+ }++ .d-inline-flex {+ display: inline-flex;+ }++ .fit-content {+ width: fit-content;+ }+ `;++ @property()+ public config?: MapConfig = {};++ @property()+ protected filename: string;++ @property()+ protected limit = 30e+6;++ /* -------------- */++ protected render() {+ const isCustom = this.config.sources?.vector_tiles?.custom;+ const hasExternalSource = Object.keys(this.config.sources).length > 1;+ return html`+ <div class="map-tile-settings">+ <div class="map-tile-server-group">+ <div class="subheader"><or-translate value="configuration.global.mapTileServer"></or-translate></div>+ <span>+ <or-translate value="configuration.global.mapTileServerDescription"></or-translate><br>+ <or-translate class="note" value="configuration.global.mapTileServerNote"></or-translate>+ </span>+ <or-mwc-input class="input"+ .value="${isCustom ? this.config.sources?.vector_tiles?.tiles?.[0] : undefined}"+ .type="${InputType.URL}"+ .label="${i18next.t("configuration.global.mapTileServerPlaceholder")}"+ placeholder="https://api.example.com/tileset/{z}/{x}/{y}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {+ this.config.sources.vector_tiles.tiles = e.detail.value ? [e.detail.value] : undefined;+ this.config.sources.vector_tiles.custom = !!e.detail.value;+ this.notifyConfigChange(this.config);+ }}"+ ></or-mwc-input>+ </div>+ <div class="map-tile-upload-group">+ <div class="subheader"><or-translate value="configuration.global.mapTiles"></or-translate></div>+ <span>+ <or-translate value="configuration.global.uploadMapTiles"></or-translate><br>+ <or-translate class="note" value="configuration.global.uploadMapTilesNote"+ .options=${{limit: this.humanReadableBytes(this.limit)}}+ ></or-translate>+ </span>+ <div class="input d-inline-flex" style="height: 56px">+ <div id="fileupload" style="display: flex; align-items: center">+ <or-mwc-input outlined label="selectFile" style="width: fit-content; padding-right: 12px;" .type="${InputType.BUTTON}" @or-mwc-input-changed="${+ () => this.shadowRoot.getElementById('fileupload-elem').click()+ }">+ <input id="fileupload-elem" name="configfile" type="file" accept=".mbtiles" @change="${this.notifyMapFileChange}"/>+ </or-mwc-input>+ <or-mwc-input id="filename-elem" style="width: unset" .value="${this.filename}" .label="${i18next.t("file")}" .type="${InputType.TEXT}" disabled>+ </or-mwc-input>+ ${when(this.filename, () => html`<or-mwc-input type="${InputType.BUTTON}" iconColor="black" icon="delete"+ @or-mwc-input-changed="${this.notifyMapFileChange}"+ ></or-mwc-input>`)}+ </div>+ </div>+ </div>+ </div>+ <div class="map-style-settings">+ <div class="map-style-server-group">+ <span>+ <div class="subheader"><or-translate value="configuration.global.mapStyleJsonUrl"></or-translate></div>+ <or-translate value="configuration.global.mapStyleJsonUrlDescription"></or-translate><br>+ <or-translate class="note" value="configuration.global.mapStyleJsonUrlNote"></or-translate>+ </span>+ <div style="display: flex; height: 56px; align-items: center">+ <or-mwc-input class="input"+ .value="${this.config.override}"+ .type="${InputType.URL}"+ .label="${i18next.t("configuration.global.mapStyleJsonUrlPlaceholder")}"+ placeholder="https://api.example.com/tileset/style.json"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {+ this.config.override = e.detail.value || undefined+ this.notifyConfigChange(this.config)+ this.requestUpdate();+ }}"+ ></or-mwc-input>+ </div>+ </div>+ <div class="map-style-layers-group">+ <span>+ <div class="subheader"><or-translate value="configuration.global.mapLayers"></or-translate></div>+ <or-translate value="configuration.global.mapImportStyle"></or-translate>+ <or-translate class="note" value="configuration.global.mapImportStyleNote"></or-translate>+ </span>+ <div style="display: flex; gap: 12px; align-items: center">+ <or-mwc-input class="input fit-content" type="button" outlined icon="import"+ .label="${i18next.t("configuration.global.import")}"+ .disabled="${!this.config.override}" @or-mwc-input-changed="${this.importMapSettings}"+ ></or-mwc-input>+ <or-conf-json class="input fit-content hide-mobile" .heading="${i18next.t("configuration.global.mapLayers")}"+ .config="${hasExternalSource ? this.config.layers.filter(({ id }) => !id.startsWith("or:")) : this.config.layers}"+ @saveLocalConfig="${(ev: CustomEvent) => {+ if (Array.isArray(ev.detail.value)) {+ if (hasExternalSource) {+ // Set default layers+ this.config.layers = this.config.layers.filter(({ id }) => id.startsWith("or:"))+ // Push changed layers+ this.config.layers.push(...ev.detail.value);+ } else {+ this.config.layers = ev.detail.value;+ }+ this.notifyConfigChange(this.config);+ this.requestUpdate();+ }+ }}"+ ></or-conf-json>+ ${when(hasExternalSource, () => html`+ <or-mwc-input class="input fit-content" outlined type="button" icon="undo"+ .label="${i18next.t("configuration.global.reset")}"+ @or-mwc-input-changed="${this.resetMapSettings}"+ ></or-mwc-input>+ `)}+ </div>+ </div>+ </div>+ `+ }++ protected notifyConfigChange(config: MapConfig) {+ this.dispatchEvent(new CustomEvent("change", { detail: config }));+ }++ protected notifyMapFileChange(e: OrInputChangedEvent) {+ const file = (e.target as HTMLInputElement)?.files?.[0];+ if (file) {+ if (file.size > this.limit) {+ showSnackbar(undefined, "configuration.global.uploadMapTilesError")+ return;+ }+ const filenameEl = this.shadowRoot.getElementById('filename-elem') as HTMLInputElement+ if (filenameEl) {+ filenameEl.value = file.name;+ }+ }+ this.dispatchEvent(new CustomEvent("map-file-changed", { detail: file }));+ }++ protected resetMapSettings() {+ this.config.glyphs = undefined;+ this.config.sprite = undefined;+ this.config.sources = { vector_tiles: this.config.sources.vector_tiles };+ this.config.layers = this.config.layers+ .filter(({ id }) => id.startsWith("or:"))+ .map(({ id, ...layer }) => ({ ...layer, id: id.replace("or:", "") }));+ this.notifyConfigChange(this.config);+ this.requestUpdate();+ }++ protected async importMapSettings() {+ if (this.config.override) {+ const data = await (await fetch(this.config.override)).json() as StyleSpecification+ if (Object.keys(this.config.sources).length > 1) {+ // Set default layers+ this.config.layers = this.config.layers.filter(({ id }) => id.startsWith("or:"))+ // Push new layers+ this.config.layers.push(...data.layers);+ } else {+ this.config.layers = this.config.layers.map(({ id, ...layer }) => ({ ...layer, id: "or:" + id }));+ this.config.layers.push(...data.layers);+ }+ Object.assign(this.config.sources, data.sources)+ this.config.sprite = data.sprite as string;+ this.config.glyphs = data.glyphs;+ delete this.config.override;+ this.notifyConfigChange(this.config);+ this.requestUpdate();+ }+ }++ private humanReadableBytes(bytes: number) {+ const unit = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];+ const exponent = Math.floor(Math.log(bytes) / Math.log(1000));+ return (bytes / Math.pow(1000, exponent)).toFixed(2) + " " + unit[exponent];+ }+}diff --git a/ui/app/manager/src/pages/page-configuration.ts b/ui/app/manager/src/pages/page-configuration.tsindex e23998a32..25e1f6bb5 100644--- a/ui/app/manager/src/pages/page-configuration.ts+++ b/ui/app/manager/src/pages/page-configuration.ts@@ -26,15 +26,14 @@ import {Store} from "@reduxjs/toolkit";import {AppStateKeyed, Page, PageProvider} from "@openremote/or-app";import {when} from "lit/directives/when.js"import "@openremote/or-components/or-collapsible-panel";-import "@openremote/or-mwc-components/or-mwc-input";import "../components/configuration/or-conf-json";import "../components/configuration/or-conf-panel";+import "../components/configuration/or-conf-map/or-conf-map-global";import {ManagerAppConfig, MapConfig, Realm} from "@openremote/model";-import {i18next} from "@openremote/or-translate";import "@openremote/or-components/or-loading-indicator";import {OrConfRealmCard} from "../components/configuration/or-conf-realm/or-conf-realm-card";import {OrConfPanel} from "../components/configuration/or-conf-panel";-import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";+import { InputType } from "@openremote/or-mwc-components/or-mwc-input";import {DefaultHeaderMainMenu, DefaultHeaderSecondaryMenu, DefaultRealmConfig} from "../index";import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";@@ -144,58 +143,10 @@ export class PageConfiguration extends Page<AppStateKeyed> {}}- /* Global map settings */-.subheader {padding: 10px 0 4px;font-weight: bolder;}-- .global-settings-container {- display: flex;- }-- .global-server-group {- width: 50%;- }-- .custom-tile-group {- width: 50%;- padding-left: 12px;- }-- @media screen and (max-width: 768px) {- .custom-tile-group, .global-server-group {- width: 100%;- padding: unset;- }- .global-settings-container {- display: block;- }- }-- .input {- width: 100%;- max-width: 800px;- padding: 10px 0;- }-- .input or-mwc-input:not([icon]) {- width: 80%;- }-- .note {- color: rgba(0, 0, 0, 0.6);- }-- or-file-uploader {- width: 108px;- height: 108px;- }-- .d-inline-flex {- display: inline-flex;- }`;}@@ -213,7 +164,7 @@ export class PageConfiguration extends Page<AppStateKeyed> {protected realms?: Realm[];@state()- protected loading: boolean = false;+ protected loading = false;@state()protected managerConfigurationChanged = false;@@ -225,13 +176,13 @@ export class PageConfiguration extends Page<AppStateKeyed> {protected customMapFilename: string;@state()- protected customMapLimit: number = 1e+9;+ protected customMapLimit: number;@state()protected tilesForUpload: File;@state()- protected tilesForDeletion: boolean = false;+ protected tilesForDeletion = false;@query("#managerConfig-panel")protected realmConfigPanel?: OrConfPanel;@@ -248,12 +199,6 @@ export class PageConfiguration extends Page<AppStateKeyed> {this.customMapFilename = response.data.filename as string | null;}- public humanReadableBytes(bytes: number) {- const unit = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];- const exponent = Math.floor(Math.log(bytes) / Math.log(1000));- return (bytes / Math.pow(1000, exponent)).toFixed(2) + " " + unit[exponent];- }-// On every update..willUpdate(changedProps: PropertyValues<this>) {@@ -308,19 +253,15 @@ export class PageConfiguration extends Page<AppStateKeyed> {const realmHeading = html`<div id="heading" style="justify-content: space-between;"><span style="margin: 0;"><or-translate style="text-transform: uppercase;" value="configuration.realmStyling"></or-translate></span>- <or-conf-json .managerConfig="${this.managerConfiguration}" class="hide-mobile"- @saveLocalManagerConfig="${(ev: CustomEvent) => {- this.managerConfiguration = ev.detail.value as ManagerAppConfig;- this.managerConfigurationChanged = true;- }}"+ <or-conf-json .heading="${'manager_config.json'}" .config="${this.managerConfiguration}" class="hide-mobile" @saveLocalConfig="${(ev: CustomEvent) => {+ this.managerConfiguration = ev.detail.value as ManagerAppConfig;+ this.managerConfigurationChanged = true;+ }}"></or-conf-json>- </div>- `;- const mapHeading = html`- <div id="heading" style="justify-content: space-between;">+ </div>`;+ const mapHeading = html`<div id="heading" style="justify-content: space-between;"><span style="margin: 0;"><or-translate style="text-transform: uppercase;" value="configuration.mapSettings"></or-translate></span>- </div>- `;+ </div>`;const realmOptions = this.realms?.map((r) => ({name: r.name, displayName: r.displayName, canDelete: true}));realmOptions.push({name: 'default', displayName: 'Default', canDelete: false});return html`@@ -332,68 +273,41 @@ export class PageConfiguration extends Page<AppStateKeyed> {</div><div id="header-actions"><or-mwc-input id="save-btn" .disabled="${saveDisabled}" raised type="button" label="save"- @or-mwc-input-changed="${() => this.saveAllConfigs(this.managerConfiguration, this.mapConfig)}"+ @or-mwc-input-changed="${() => this.saveAllConfigs(this.managerConfiguration, this.mapConfig)}"></or-mwc-input></div></div><or-panel .heading="${realmHeading}">${when(this.managerConfiguration, () => html`<or-conf-panel id="managerConfig-panel" .config="${this.managerConfiguration}" .realmOptions="${realmOptions}"- @change="${() => { this.managerConfigurationChanged = true; }}"+ @change="${() => { this.managerConfigurationChanged = true; }}"></or-conf-panel>`, () => html`<div class="notFound-container"><span><or-translate value="configuration.managerConfigNotFound"></or-translate></span><or-mwc-input type="${InputType.BUTTON}" label="configuration.tryAgain"- @or-mwc-input-changed="${() => this.getManagerConfig().then(val => {- this.managerConfiguration = val;- }).catch(e => console.error(e))}"+ @or-mwc-input-changed="${() => this.getManagerConfig().then(val => {+ this.managerConfiguration = val;+ }).catch(e => console.error(e))}"></or-mwc-input></div>`)}</or-panel><or-panel .heading="${mapHeading}">${when(this.mapConfig, () => html`- <div class="global-settings-container">- <div class="global-server-group">- <div class="subheader"><or-translate value="configuration.global.tileServer"></or-translate></div>- <span>- <or-translate value="configuration.global.tileServerDescription"></or-translate><br>- <or-translate style="font-style: italic;" class="note" value="configuration.global.tileServerNote"></or-translate>- </span>- <or-mwc-input class="input"- .value="${this.mapConfig.sources?.vector_tiles?.custom ? this.mapConfig.sources?.vector_tiles?.tiles?.[0] : undefined}"- .type="${InputType.URL}"- .label="${i18next.t("configuration.global.tileServerPlaceholder")}"- placeholder="https://api.example.com/tileset/{z}/{x}/{y}"- @or-mwc-input-changed="${this.setCustomVectorTilesUrl}"- ></or-mwc-input>- </div>-- <div class="custom-tile-group">- <div class="subheader"><or-translate value="configuration.global.mapTiles"></or-translate></div>- <span>- <or-translate value="configuration.global.uploadMapTiles"></or-translate><br>- <or-translate style="font-style: italic;" class="note" value="configuration.global.uploadMapTilesPrecedence"- .options=${{customMapLimit: this.humanReadableBytes(this.customMapLimit)}}- ></or-translate>- </span>- <div class="input d-inline-flex" style="height: 56px">- <div id="fileupload" style="display: flex; align-items: center">- <or-mwc-input outlined label="selectFile" style="width: fit-content; padding-right: 12px;" .type="${InputType.BUTTON}" @or-mwc-input-changed="${- () => this.shadowRoot.getElementById('fileupload-elem').click()- }">- <input id="fileupload-elem" name="configfile" type="file" accept=".mbtiles" @change="${(e) => this.uploadCustomMap(e)}"/>- </or-mwc-input>- <or-mwc-input id="filename-elem" style="width: unset" .value="${this.customMapFilename}" .label="${i18next.t("file")}" .type="${InputType.TEXT}" disabled>- </or-mwc-input>- ${when(this.customMapFilename, () => html`<or-mwc-input type="${InputType.BUTTON}" iconColor="black" icon="delete"- @or-mwc-input-changed="${async () => await this.deleteCustomMap()}"- ></or-mwc-input>`)}- </div>- </div>- </div>- </div>+ <or-conf-map-global .config="${this.mapConfig}" .filename="${this.customMapFilename}" .limit="${this.customMapLimit}"+ @change="${() => { this.mapConfigChanged = true; }}"+ @map-file-changed="${(e: CustomEvent) => {+ // If a map file is provided prepare for upload+ if (e.detail) {+ this.tilesForUpload = e.detail;+ } else {+ this.customMapFilename = undefined;+ }+ // Otherwise assume it is meant for deletion+ this.tilesForDeletion = !e.detail;+ }}"+ ></or-conf-map-global><div class="subheader"><or-translate value="configuration.realmMapSettingsTitle"></or-translate></div><or-conf-panel id="mapConfig-panel" .config="${this.mapConfig}" .realmOptions="${realmOptions}"@change="${() => { this.mapConfigChanged = true; }}"@@ -402,9 +316,9 @@ export class PageConfiguration extends Page<AppStateKeyed> {<div class="notFound-container"><span><or-translate value="configuration.mapSettingsNotFound"></or-translate></span><or-mwc-input type="${InputType.BUTTON}" label="configuration.tryAgain"- @or-mwc-input-changed="${() => this.getMapConfig().then(val => {- this.mapConfig = val;- }).catch(e => console.error(e))}"+ @or-mwc-input-changed="${() => this.getMapConfig().then(val => {+ this.mapConfig = val;+ }).catch(e => console.error(e))}"></or-mwc-input></div>`)}@@ -423,33 +337,6 @@ export class PageConfiguration extends Page<AppStateKeyed> {// FETCH METHODS- protected async setCustomVectorTilesUrl(e: OrInputChangedEvent) {- this.mapConfig.sources.vector_tiles = {- type: "vector",- ...(e.detail.value ? { tiles: [e.detail.value], custom: true } : {}),- }- this.mapConfigChanged = true;- }-- protected async uploadCustomMap(e: CustomEvent) {- const file = (e.target as HTMLInputElement).files[0];- if (file.size > this.customMapLimit) {- showSnackbar(undefined, "configuration.global.uploadMapTilesError")- return;- }- const filenameEl = this.shadowRoot.getElementById('filename-elem') as HTMLInputElement- if (filenameEl) {- filenameEl.value = file.name;- }- this.tilesForUpload = file;- this.tilesForDeletion = false;- }-- protected async deleteCustomMap() {- this.customMapFilename = undefined;- this.tilesForDeletion = true;- }-protected async getManagerConfig(): Promise<ManagerAppConfig | undefined> {const response = await manager.rest.api.ConfigurationResource.getManagerConfig();return response.status === 200 ? response.data as ManagerAppConfig : {@@ -465,8 +352,8 @@ export class PageConfiguration extends Page<AppStateKeyed> {protected async getMapConfig(): Promise<MapConfig> {const response = await manager.rest.api.MapResource.getSettings();if (response.data) {- const { options, sources } = response.data as MapConfig;- return { options, sources };+ const { options, sources, layers, glyphs, override, sprite } = response.data as MapConfig;+ return { options, sources, layers, glyphs, override, sprite };}return null;}diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.jsonindex f6e37cdb6..d96260358 100644--- a/ui/app/shared/locales/en/or.json+++ b/ui/app/shared/locales/en/or.json@@ -828,13 +828,22 @@"deleteMapCustomizationConfirm":"Are you sure you want to delete this Map customization?","addMapCustomization" : "Add map settings","global": {- "tileServer": "Tile Server",- "tileServerDescription": "Configure a tile server.",- "tileServerNote": "The map through a tile server gets priority over custom map tiles.",- "tileServerPlaceholder": "Map Server URL",+ "reset": "Reset",+ "import": "Import",+ "mapLayers": "Map Layers",+ "mapStyleJsonUrl": "Style JSON URL",+ "mapStyleJsonUrlDescription": "Override mapsettings with external JSON map styles.",+ "mapStyleJsonUrlNote": "All other mapsettings will be ignored.",+ "mapStyleJsonUrlPlaceholder": "Style JSON URL",+ "mapImportStyle": "Optionally import the style URL to edit the map layers through the JSON editor.",+ "mapImportStyleNote": "Reset to the default map to edit the default map layers.",+ "mapTileServer": "Tile Server",+ "mapTileServerDescription": "Configure a tile server.",+ "mapTileServerNote": "The map through a tile server gets priority over custom map tiles.",+ "mapTileServerPlaceholder": "Tile Server URL","mapTiles": "Custom Map Tiles","uploadMapTiles": "Upload custom map tiles.",- "uploadMapTilesPrecedence": "The maximum allowed file size is {{customMapLimit}}.",+ "uploadMapTilesNote": "The maximum allowed file size is {{limit}}.","uploadingMapTiles": "Uploading map tiles... This may take a moment.","uploadMapTilesError": "Custom map tiles file exceeds size limit.","uploadingMapTilesError": "Failed to upload map tiles"diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.jsonindex 2a6ead52a..aa654b262 100644--- a/ui/app/shared/locales/nl/or.json+++ b/ui/app/shared/locales/nl/or.json@@ -827,16 +827,25 @@"deleteMapCustomizationConfirm":"Weet je zeker dat je deze kaart wilt verwijderen","addMapCustomization" : "Voeg een Kaartinstelling toe","global": {- "tileServer": "Kaartserver",- "tileServerDescription": "Configureer een kaartserver.",- "tileServerNote": "De kaart van de server URL heeft voorrang op de kaarttegels.",- "tileServerPlaceholder": "Kaartserver URL",- "mapTiles": "Eigen Kaarttegels",- "uploadMapTiles": "Upload aangepaste kaarttegels.",- "uploadMapTilesPrecedence": "De maximaal toegestaande bestandsgrootte is {{customMapLimit}}.",- "uploadingMapTiles": "Kaarttegels uploaden... Dit kan even duren.",+ "reset": "Resetten",+ "import": "Importeren",+ "mapLayers": "Kaartlagen",+ "mapStyleJsonUrl": "Stijl JSON-URL",+ "mapStyleJsonUrlDescription": "Overschrijf kaartinstellingen met externe JSON-kaartstijlen.",+ "mapStyleJsonUrlNote": "Alle andere kaartinstellingen worden genegeerd.",+ "mapStyleJsonUrlPlaceholder": "Stijl JSON-URL",+ "mapImportStyle": "Optioneel kunt u de stijl-URL importeren om de kaart lagen te bewerken via de JSON-editor.",+ "mapImportStyleNote": "Reset naar de standaardkaart om de standaardkaartlagen te bewerken.",+ "mapTileServer": "Kaartserver",+ "mapTileServerDescription": "Configureer een kaartserver.",+ "mapTileServerNote": "De kaart van de server URL heeft voorrang op de kaarttegels.",+ "mapTileServerPlaceholder": "Kaartserver URL",+ "mapTiles": "Kaarttegels",+ "uploadMapTiles": "Upload kaarttegels.",+ "uploadMapTilesNote": "De maximaal toegestaande bestandsgrootte is {{limit}}.",+ "uploadingMapTiles": "Kaarttegels worden geüpload... Dit kan even duren.","uploadMapTilesError": "Kaarttegel bestand overschrijdt de maximale bestandsgrootte.",- "uploadingMapTilesError": "Het uploaden van kaarttegels is mislukt."+ "uploadingMapTilesError": "Uploaden van kaarttegels mislukt"}},"realmRole": {diff --git a/ui/component/or-map/src/mapbox-url-utils.ts b/ui/component/or-map/src/mapbox-url-utils.tsnew file mode 100644index 000000000..7759f9209--- /dev/null+++ b/ui/component/or-map/src/mapbox-url-utils.ts@@ -0,0 +1,71 @@+import { ResourceType } from "maplibre-gl";++export function isMapboxURL(url: string) {+ return url.indexOf("mapbox:") === 0;+}++export function transformMapboxUrl(url: string, accessToken: string, resourceType?: ResourceType) {+ if (url.indexOf("/styles/") > -1 && url.indexOf("/sprite") === -1)+ return { url: normalizeStyleURL(url, accessToken) };+ if (url.indexOf("/sprites/") > -1) return { url: normalizeSpriteURL(url, accessToken) };+ if (url.indexOf("/fonts/") > -1) return { url: normalizeGlyphsURL(url, accessToken) };+ if (url.indexOf("/v4/") > -1) return { url: normalizeSourceURL(url, accessToken) };+ if (resourceType === ResourceType.Source) return { url: normalizeSourceURL(url, accessToken) };+}++function parseUrl(url: string) {+ const urlRe = /^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;+ const parts = url.match(urlRe);+ if (!parts) {+ throw new Error("Unable to parse URL object");+ }+ return {+ protocol: parts[1],+ authority: parts[2],+ path: parts[3] || "/",+ params: parts[4] ? parts[4].split("&") : [],+ };+}++function formatUrl(urlObject: any, accessToken: string) {+ const apiUrlObject = parseUrl("https://api.mapbox.com");+ urlObject.protocol = apiUrlObject.protocol;+ urlObject.authority = apiUrlObject.authority;+ urlObject.params.push(`access_token=${accessToken}`);+ const params = urlObject.params.length ? `?${urlObject.params.join("&")}` : "";+ return `${urlObject.protocol}://${urlObject.authority}${urlObject.path}${params}`;+}++function normalizeStyleURL(url: string, accessToken: string) {+ const urlObject = parseUrl(url);+ urlObject.path = `/styles/v1${urlObject.path}`;+ return formatUrl(urlObject, accessToken);+}++function normalizeGlyphsURL(url: string, accessToken: string) {+ const urlObject = parseUrl(url);+ urlObject.path = `/fonts/v1${urlObject.path}`;+ return formatUrl(urlObject, accessToken);+}++function normalizeSourceURL(url: string, accessToken: string) {+ const urlObject = parseUrl(url);+ urlObject.path = `/v4/${urlObject.authority}.json`;+ urlObject.params.push("secure");+ return formatUrl(urlObject, accessToken);+}++function normalizeSpriteURL(url: string, accessToken: string) {+ const urlObject = parseUrl(url);+ const path = urlObject.path.split(".");+ let properPath = path[0];+ const extension = path[1];+ let format = "";++ if (properPath.indexOf("@2x")) {+ properPath = properPath.split("@2x")[0];+ format = "@2x";+ }+ urlObject.path = `/styles/v1${properPath}/sprite${format}.${extension}`;+ return formatUrl(urlObject, accessToken);+}diff --git a/ui/component/or-map/src/mapwidget.ts b/ui/component/or-map/src/mapwidget.tsindex e3f35d1cb..4b814169b 100644--- a/ui/component/or-map/src/mapwidget.ts+++ b/ui/component/or-map/src/mapwidget.ts@@ -28,6 +28,7 @@ import { OrMapMarker } from "./markers/or-map-marker";import { getLatLngBounds, getLngLat } from "./util";import {GeoJsonConfig, MapType } from "@openremote/model";import { Feature, FeatureCollection } from "geojson";+import { isMapboxURL, transformMapboxUrl } from "./mapbox-url-utils";const mapboxJsStyles = require("mapbox.js/dist/mapbox.css");const maplibreGlStyles = require("maplibre-gl/dist/maplibre-gl.css");@@ -37,6 +38,7 @@ const maplibreGeoCoderStyles = require("@maplibre/maplibre-gl-geocoder/dist/maplconst metersToPixelsAtMaxZoom = (meters: number, latitude: number) =>meters / 0.075 / Math.cos(latitude * Math.PI / 180);+let pkey: string | null;export class MapWidget {protected _mapJs?: L.mapbox.Map;@@ -207,6 +209,10 @@ export class MapWidget {}const settings = settingsResponse.data as any;+ if (settings.override) {+ return settings.override+ }+// Load options for current realm or fallback to default if existconst realmName = manager.displayRealm || "default";this._viewSettings = settings.options ? settings.options[realmName] ? settings.options[realmName] : settings.options.default : null;@@ -313,6 +319,12 @@ export class MapWidget {container: this._mapContainer,style: settings as StyleSpecification,transformRequest: (url, resourceType) => {+ if (!pkey) {+ pkey = new URL(url).searchParams.get("access_token") || ''+ }+ if (isMapboxURL(url)) {+ return transformMapboxUrl(url, pkey, resourceType)+ }// Cross-domain tile servers usually have the following headers specified "access-control-allow-methods GET", "access-control-allow-origin *", "allow GET,HEAD". The "Access-Control-Request-Headers: Authorization" may not be set e.g. with Mapbox tile servers. The CORS preflight request (OPTION) will in this case fail if the "authorization" header is being requested cross-domain. The only headers allowed are so called "simple request" headers, see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests.const headers = new URL(window.origin).hostname === new URL(url).hostname? {Authorization: manager.getAuthorizationHeader()} : {}