@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
454 lines (453 loc) • 25.1 kB
JavaScript
import { html as uHtml } from 'uhtml';
// SPDX-License-Identifier: Apache-2.0
import proj4 from 'proj4';
import GirafeHTMLElement from '../base/GirafeHTMLElement.js';
import MapComponent from '../components/map/component.js';
import { register } from 'ol/proj/proj4.js';
import GirafeApiContext from './apicontext.js';
import BasemapComponent from '../components/basemap/component.js';
import MenuButtonComponent from '../components/menubutton/component.js';
import MapCustomContextMenuComponent from '../components/context-menu/custom-context-menu/component.js';
import SearchComponent from '../components/search/component.js';
import SelectionWindowComponent from '../components/selectionwindow/component.js';
import { splitTrimAndConvertToNumber } from '../tools/utils/utils.js';
import DOMPurify from 'dompurify';
const getImageSize = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve({
width: img.naturalWidth,
height: img.naturalHeight
});
};
img.onerror = () => {
reject(new Error(`Failed to load image: ${url}`));
};
img.src = url;
});
};
export default class GeoGirafeApi extends GirafeHTMLElement {
templateUrl = null;
styleUrls = null;
template = () => {
return uHtml `<style>
.hidden{display:none}.gg-rotate90{transform:rotate(90deg)}.gg-rotate180{transform:rotate(180deg)}.gg-rotate270{transform:rotate(270deg)}img{filter:var(--svg-filter)}img.legend-image{filter:var(--svg-map-filter);background:var(--svg-legend-bkg)}div{scrollbar-width:thin}a,a:visited{color:var(--link-color)}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@keyframes spin-wait{0%{transform:rotate(0)}7%{transform:rotate(360deg)}to{transform:rotate(360deg)}}.gg-spin{animation-name:spin;animation-duration:2s;animation-timing-function:linear;animation-iteration-count:infinite}.gg-spin-wait{animation-name:spin-wait;animation-duration:10s;animation-timing-function:linear;animation-iteration-count:infinite}::-webkit-scrollbar{width:5px}::-webkit-scrollbar-thumb{background:#999}button,input,select,textarea{font:inherit}.gg-button,.gg-select,.gg-input,.gg-textarea{background-color:var(--bkg-color);color:var(--text-color);border:var(--app-standard-border);box-sizing:border-box;cursor:pointer;border-radius:3px;outline:0;margin:0;padding:0 0 0 .5rem;display:inline-block}.gg-label{background-color:var(--bkg-color);color:var(--text-color);border:none;align-items:center;margin:0;padding:0;display:flex}.gg-button,.gg-select,.gg-input,.gg-label{min-height:calc(var(--app-standard-height) / 1.5)}.gg-textarea{max-height:initial;resize:vertical;height:6rem;padding:.5rem;line-height:1.3rem}.gg-input{cursor:text}.gg-checkbox{accent-color:var(--text-color);width:1.2rem}.gg-range{accent-color:var(--text-color)}.gg-button{padding:0 .5rem}.gg-button.active{border:solid 1px var(--text-color-grad1);background-color:var(--bkg-color-grad2)}.gg-button:disabled{background-color:var(--bkg-color-grad1);color:var(--text-color-grad2);cursor:not-allowed;border:none}.gg-button:disabled img{filter:opacity(.6)}.gg-input:disabled,.gg-select:disabled,.gg-textarea:disabled{background-color:var(--bkg-color-grad1);color:var(--text-color-grad2);cursor:not-allowed}.gg-button>img{vertical-align:middle}.gg-icon-button{color:var(--text-color);cursor:pointer;background-color:#0000;border:none;flex-direction:column;justify-content:center;align-items:center;padding:0;display:flex}.gg-icon{justify-content:center;align-items:center;display:flex}.gg-big,.gg-big-withtext{min-width:var(--app-standard-height);min-height:var(--app-standard-height);max-height:var(--app-standard-height)}.gg-big img,.gg-big-withtext img{width:calc(var(--app-standard-height) - 1.5rem);margin:0}.gg-big-withtext span{font-variant:small-caps;padding:0 1rem;font-size:.9rem}.gg-medium,.gg-medium-withtext{min-width:calc(var(--app-standard-height) / 1.2);min-height:calc(var(--app-standard-height) / 1.2);max-height:calc(var(--app-standard-height) / 1.2);flex-direction:row}.gg-medium img{width:calc(var(--app-standard-height) / 2.4);margin:0}.gg-medium-withtext img{width:calc(var(--app-standard-height) / 2.4);margin-left:.5rem}.gg-medium-withtext span{padding:0 1rem 0 .5rem;font-size:.9rem}.gg-small,.gg-small-withtext{min-width:calc(var(--app-standard-height) / 2);min-height:calc(var(--app-standard-height) / 2);max-height:calc(var(--app-standard-height) / 2);flex-direction:row}.gg-small img{width:calc(var(--app-standard-height) / 3);margin:0}.gg-small-withtext img{width:calc(var(--app-standard-height) / 3);margin-left:.5rem}.gg-small-withtext span{padding:0 .5rem 0 .3rem;font-size:.9rem}.gg-button:hover:not(:disabled),.gg-select:hover:not(:disabled),.gg-input:hover:not(:disabled),.gg-textarea:hover:not(:disabled),.gg-icon-button:hover:not(:disabled){background-color:var(--bkg-color-grad1)}.gg-opacity{opacity:.5}.gg-opacity:hover{opacity:1;background-color:#0000}.gg-tabs{cursor:pointer;grid-auto-flow:column;padding-bottom:1rem;font-size:1rem;display:grid}.gg-tab{border:none;border-bottom:var(--app-standard-border);cursor:pointer;color:var(--text-color);background:0 0;padding:.5rem}.gg-tab.active{border-bottom:solid 1px var(--text-color)}.girafe-button-big,.girafe-button-large,.girafe-button-small,.girafe-button-tiny{color:var(--text-color);background-color:#0000;border:none;flex-direction:column;display:flex}.girafe-button-big:hover,.girafe-button-large:hover,.girafe-button-small:hover,.girafe-button-tiny:hover{background-color:var(--bkg-color-grad1);cursor:pointer}.girafe-button-big.dark,.girafe-button-large.dark,.girafe-button-small.dark,.girafe-button-tiny.dark{background-color:var(--bkg-color);filter:invert()}.girafe-button-big{width:var(--app-standard-height);height:var(--app-standard-height);align-items:center;padding:1rem}.girafe-button-big img{overflow:hidden}.girafe-button-large{flex-direction:row}.girafe-button-large img{height:2rem;margin:.3rem}.girafe-button-large span{height:2rem;margin:.3rem;line-height:2rem}.girafe-button-small{min-width:calc(var(--app-standard-height) / 2);height:calc(var(--app-standard-height) / 2);align-items:center;padding:.5rem}.girafe-button-small img{overflow:hidden}.girafe-button-small span{text-align:left;text-overflow:ellipsis;width:100%;overflow:hidden}.girafe-button-tiny{align-items:center;width:1rem;height:1rem;padding:0}.girafe-button-tiny img{overflow:hidden}.girafe-onboarding-theme{background-color:var(--bkg-color);color:var(--text-color)}.girafe-onboarding-theme button{background-color:var(--bkg-color);color:var(--text-color);text-shadow:none}.girafe-onboarding-theme button.driver-popover-close-btn{z-index:10000}.tippy-box{background-color:var(--bkg-color);border:var(--app-standard-border)}.tippy-content{color:var(--text-color)}.tippy-arrow{color:var(--bkg-color)}.tippy-box[data-theme~=error]{background-color:var(--error-color);white-space:pre-line}div.tippy-box[data-theme=image-popup]{border:var(--app-standard-border);& div.tippy-content{background-color:var(--bkg-color);& img{max-width:20rem;max-height:20rem}}& div.tippy-arrow{color:var(--bkg-color)}}
</style><style>
:host{position:relative}girafe-map{width:100%;height:100%;position:relative}girafe-basemap{display:block;position:absolute;bottom:.5rem;left:.5rem}girafe-search{width:50%;height:2.25rem;display:block;position:absolute;top:.5rem;left:.5rem;box-shadow:0 1px 4px #0000004d}girafe-selection-window{z-index:100;width:400px;height:240px;position:absolute;bottom:1rem;right:1rem}
</style>
<style>${this.customStyle}</style>
<girafe-map></girafe-map>
${this.htmlUnsafe(this.feedbackTemplateHtml ?? '')}`;
};
isInitialized = false;
constructor() {
super('geogirafe-api');
this.injectConfigMetaTags();
}
get config() {
return this.context.configManager.Config.api.demo;
}
connectedCallback() {
super.connectedCallback();
this.initialize().then(() => {
console.log('GeoGirafe API is ready!');
this.defineApiComponents();
this.subscribe('application.isReady', (_, isLoaded) => {
if (isLoaded) {
this.manageAttributes();
this.isInitialized = true;
this.dispatchEvent(new CustomEvent('geogirafe-api-ready'));
}
});
this.render();
});
}
static get observedAttributes() {
return ['center', 'zoom', 'basemap', 'basemapselector', 'crosshair', 'tooltip', 'markers', 'markersfile', 'layers'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (this.isInitialized) {
// We listen to attribute changes only if the API is already initialized
console.log(`Attribute ${name} changed : ${oldValue} → ${newValue}`);
if (name === 'center') {
this.manageCenterAttribute();
}
else if (name === 'zoom') {
this.manageZoomAttribute();
}
else if (name === 'basemap') {
this.manageBasemapAttribute();
}
else if (name === 'basemapselector') {
this.manageBasemapSelectorAttribute();
}
else if (name === 'crosshair') {
this.manageCrosshairAttribute();
}
else if (name === 'tooltip') {
this.manageTooltipAttribute();
}
else if (name === 'markers') {
this.manageMarkersAttribute();
}
else if (name === 'markersfile') {
this.manageMarkersFileAttribute();
}
else if (name === 'layers') {
this.manageLayersAttribute();
}
}
}
getInheritedContext() {
return new GirafeApiContext();
}
defineApiComponents() {
if (!customElements.get('girafe-map')) {
customElements.define('girafe-map', MapComponent);
}
}
manageAttributes() {
this.manageCenterAttribute();
this.manageZoomAttribute();
this.manageBasemapAttribute();
this.manageBasemapSelectorAttribute();
this.manageSearchbarAttribute();
this.manageCrosshairAttribute();
this.manageTooltipAttribute();
this.manageMarkersAttribute();
this.manageMarkersFileAttribute();
this.manageLayersAttribute();
this.manageSelectionboxAttribute();
this.manageUserInteraction();
}
manageUserInteraction() {
// Deactivate the preview of search results
if (this.context.configManager.Config.search) {
this.context.configManager.Config.search.objectPreview = false;
this.context.configManager.Config.search.layerPreview = false;
}
// Force window as selection component
this.state.interface.selectionComponent = 'window';
// Deactivate selection if the selectionbox is not active
const selectionbox = this.getAttribute('selectionbox');
if (selectionbox === null) {
this.context.userInteractionManager.registerListener('map.select', true, 'api');
}
}
getAttributeFromConfig(attributeName) {
let attributeValue = this.getAttribute(attributeName);
if (!attributeValue) {
return null;
}
if (attributeValue.startsWith('api.demo.')) {
const configName = attributeValue.replace('api.demo.', '');
attributeValue = this.config[configName];
this.setAttribute(attributeName, attributeValue);
}
return attributeValue;
}
defineAndAddComponent(customElementName, customElementType) {
if (!customElements.get(customElementName)) {
console.log(`Defining custom element: ${customElementName}`);
customElements.define(customElementName, customElementType);
}
const existingElement = this.shadowRoot?.querySelector(customElementName);
console.log('existingElement', existingElement);
if (!existingElement) {
const component = new customElementType();
this.shadow.appendChild(component);
}
}
manageCenterAttribute() {
const center = this.getAttributeFromConfig('center');
if (center) {
const coords = center.split(',');
const x = Number(coords[0].trim());
const y = Number(coords[1].trim());
if (!Number.isNaN(x) && !Number.isNaN(y)) {
this.context.stateManager.state.position.center = [x, y];
}
else {
console.warn('Invalid center coordinates');
}
}
}
manageZoomAttribute() {
const zoom = this.getAttributeFromConfig('zoom');
if (zoom) {
const zoomLevel = Number(zoom.trim());
if (Number.isNaN(zoomLevel)) {
console.warn('Invalid zoom level');
}
else {
this.context.stateManager.state.position.zoom = zoomLevel;
}
}
}
manageBasemapAttribute() {
const basemap = this.getAttributeFromConfig('basemap');
if (basemap) {
const basemapName = basemap.trim();
if (basemapName) {
// Find the basemap in the available basemaps
const availableBasemap = Object.values(this.context.stateManager.state.basemaps).find((b) => b.name === basemapName);
if (availableBasemap) {
// Force opacity to 1 for the API
availableBasemap.opacity = 1;
this.context.stateManager.state.activeBasemaps = [availableBasemap];
}
else {
console.warn(`Basemap '${basemapName}' not found in configuration`);
}
}
}
}
manageLayersAttribute() {
const layers = this.getAttributeFromConfig('layers');
if (layers) {
const layerNames = layers.split(',');
for (const layerName of layerNames) {
if (!this.context.themesHelper.addLayerFromName(layerName.trim())) {
console.warn(`Cannot add layer ${layerName.trim()}`);
}
}
}
}
manageBasemapSelectorAttribute() {
const basemapselector = this.getAttribute('basemapselector');
if (basemapselector != null) {
this.defineAndAddComponent('girafe-menu-button', MenuButtonComponent);
this.defineAndAddComponent('girafe-basemap', BasemapComponent);
}
}
manageSearchbarAttribute() {
const searchbar = this.getAttribute('searchbar');
if (searchbar != null) {
this.defineAndAddComponent('girafe-search', SearchComponent);
}
}
manageSelectionboxAttribute() {
const selectionbox = this.getAttribute('selectionbox');
if (selectionbox != null) {
this.defineAndAddComponent('girafe-selection-window', SelectionWindowComponent);
}
}
manageCrosshairAttribute() {
const crosshair = this.getAttributeFromConfig('crosshair');
if (crosshair) {
const coords = crosshair.split(',');
const x = Number(coords[0].trim());
const y = Number(coords[1].trim());
if (!Number.isNaN(x) && !Number.isNaN(y)) {
this.context.stateManager.state.position.crosshair = [x, y];
}
else {
console.warn('Invalid crosshair coordinates');
}
}
}
manageTooltipAttribute() {
const tooltip = this.getAttributeFromConfig('tooltip');
if (tooltip) {
this.defineAndAddComponent('girafe-custom-context-menu', MapCustomContextMenuComponent);
const content = tooltip.split('|');
const hasTitle = content.length > 2;
const coords = content[0].split(',');
const x = Number(coords[0].trim());
const y = Number(coords[1].trim());
if (!Number.isNaN(x) && !Number.isNaN(y)) {
const title = hasTitle ? content[1] : undefined;
const text = content[hasTitle ? 2 : 1];
this.context.stateManager.state.position.tooltip = {
position: [x, y],
title,
content: text
};
}
else {
console.warn('Invalid tooltip coordinates');
}
}
}
manageMarkersAttribute() {
const markers = this.getAttributeFromConfig('markers');
if (markers) {
const markerValues = markers.split(';');
for (const markerValue of markerValues) {
const marker = this.markerStringToMapMarker(markerValue);
if (marker) {
this.context.stateManager.state.position.markers.push(marker);
}
else {
console.warn('Invalid marker coordinates');
}
}
}
}
markerStringToMapMarker(markerValue) {
console.log('markerStringToMapMarker', markerValue);
const contentParts = markerValue.split('|');
const needToGuessThirdParameter = contentParts.length == 3;
if (needToGuessThirdParameter) {
console.warn(`Marker has only 3 Parameters! Guessing if third Parameter '${contentParts[2]}' is Size or Offset`);
}
const coords = contentParts[0].split(',');
const x = Number(coords[0].trim());
const y = Number(coords[1].trim());
if (!Number.isNaN(x) && !Number.isNaN(y)) {
const imageUrl = contentParts[1].trim();
let size;
let offset;
if (needToGuessThirdParameter) {
if (contentParts[2].match(/[+-]+/gm)) {
offset = splitTrimAndConvertToNumber(contentParts[2]);
}
else {
size = splitTrimAndConvertToNumber(contentParts[2]);
}
}
else if (contentParts.length > 2) {
size = splitTrimAndConvertToNumber(contentParts[2]);
offset = splitTrimAndConvertToNumber(contentParts[3]);
}
return {
position: [x, y],
imageUrl: imageUrl,
size: size,
offset: offset
};
}
else {
return undefined;
}
}
manageMarkersFileAttribute() {
const markersFile = this.getAttributeFromConfig('markersfile');
if (markersFile) {
this.defineAndAddComponent('girafe-custom-context-menu', MapCustomContextMenuComponent);
void this.readMarkersFromFile(markersFile).then((markers) => {
this.context.stateManager.state.position.markers.push(...markers);
});
}
}
async readMarkersFromFile(fileUrl) {
const response = await fetch(fileUrl);
if (!response.ok) {
console.warn(`Cannot read markers file '${fileUrl}': ${response.status} ${response.statusText}`);
return [];
}
const fileContent = await response.text();
const lines = fileContent
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.length > 0);
if (lines.length < 2) {
return [];
}
const headers = lines[0].split('\t').map((header) => header.trim());
const columnIndexes = {
pointIndex: headers.indexOf('point'),
titleIndex: headers.indexOf('title'),
descriptionIndex: headers.indexOf('description'),
iconIndex: headers.indexOf('icon'),
iconSizeIndex: headers.indexOf('iconSize'),
iconOffsetIndex: headers.indexOf('iconOffset')
};
if (columnIndexes.pointIndex === -1 || columnIndexes.iconIndex === -1) {
console.warn(`Invalid markers file '${fileUrl}': missing required 'point' or 'icon' column`);
return [];
}
const markers = [];
const legacy = fileUrl.includes('legacy');
for (const line of lines.slice(1)) {
await this.lineToMarker(line, columnIndexes, legacy).then((marker) => {
if (marker) {
markers.push(marker);
}
});
}
return markers;
}
async lineToMarker(line, columnIndexes, legacy) {
const columns = line.split('\t');
const getColumOrUndefined = (index) => (index ? columns[index]?.trim() : undefined);
const coords = splitTrimAndConvertToNumber(columns[columnIndexes.pointIndex]);
const imageUrl = columnIndexes.iconIndex ? columns[columnIndexes.iconIndex]?.trim() : undefined;
if (!coords || coords.length < 2 || !imageUrl || Number.isNaN(coords[0]) || Number.isNaN(coords[1])) {
console.warn(`Invalid marker line ': ${line}`);
return undefined;
}
// In the old WebGIS the coordinates are in the wrong order. This is to ensure compatibility with older data.
if (coords[0] < coords[1] && this.context.stateManager.state.projection === 'EPSG:2056') {
coords.reverse();
}
const size = splitTrimAndConvertToNumber(getColumOrUndefined(columnIndexes.iconSizeIndex));
let offset = splitTrimAndConvertToNumber(getColumOrUndefined(columnIndexes.iconOffsetIndex));
// In the old WebGIS the Offset referred to the Size of the original Image, while now it refers to the Size of the
// resized Image. This is to ensure compatibility with older data.
if (offset && size && legacy) {
await getImageSize(imageUrl).then((imageSize) => {
const scaleX = size[0] / imageSize.width;
const scaleY = size[1] / imageSize.height;
offset = [offset[0] * scaleX, offset[1] * scaleY];
});
}
const tooltipTitle = getColumOrUndefined(columnIndexes.titleIndex);
const tooltipContent = getColumOrUndefined(columnIndexes.descriptionIndex);
const tooltip = tooltipTitle && tooltipContent ? { title: tooltipTitle, content: DOMPurify.sanitize(tooltipContent) } : undefined;
return {
position: [coords[0], coords[1]],
imageUrl,
size,
offset,
tooltip
};
}
async initialize() {
await this.context.initialize();
// Register Coordinate Reference Systems (CRS) definitions in PROJ4
for (const crs of this.context.configManager.Config.crs) {
proj4.defs(crs.code, crs.definition);
}
register(proj4);
// No custom serializer for the API
this.context.stateManager.state.application.isCustomSerializerInitialized = true;
// No auth for the api
this.context.stateManager.state.application.isAuthInitialized = true;
// Automatically toggle dark/light mode when changed in the system
globalThis.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
const state = this.context.stateManager.state;
if (e.matches) {
state.interface.darkFrontendMode = true;
}
else {
state.interface.darkFrontendMode = false;
}
});
}
injectConfigMetaTags() {
const location = new URL(import.meta.url);
// The 2 following lines are a small hack to make the api interface work in both context
// (debugging in vite + production app)
location.pathname = location.pathname.replace('/src/api', '');
location.pathname = location.pathname.replace('/node_modules/.vite/deps', '');
const origin = `${location.origin}${location.pathname.substring(0, location.pathname.lastIndexOf('/'))}`;
const baseConfigUrl = `${origin}/config.json`;
const apiConfigUrl = `${origin}/config.api.json`;
if (!document.querySelector('meta[name="configs"]')) {
const metaTag = document.createElement('meta');
metaTag.name = 'configs';
metaTag.content = 'main,api';
document.head.appendChild(metaTag);
const linkMain = document.createElement('link');
linkMain.rel = 'config-main-url';
linkMain.href = baseConfigUrl;
document.head.appendChild(linkMain);
const linkApi = document.createElement('link');
linkApi.rel = 'config-api-url';
linkApi.href = apiConfigUrl;
document.head.appendChild(linkApi);
}
}
}