@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
239 lines (238 loc) • 20.4 kB
JavaScript
import { htmlFor as uHtmlFor } from 'uhtml/keyed';
import { html as uHtml } from 'uhtml';
// SPDX-License-Identifier: Apache-2.0
import GirafeHTMLElement from '../../base/GirafeHTMLElement.js';
import ServerOgc from '../../models/serverogc.js';
import { WmsClientDefault } from '../../tools/wms/wmsclient.js';
import WmtsManager from '../map/tools/wmtsmanager.js';
import LayerWmsExternal from '../../models/layers/layerwmsexternal.js';
import LayerWmtsExternal from '../../models/layers/layerwmtsexternal.js';
import ThemeLayerExternal from '../../models/layers/themelayerexternal.js';
const MaxLayers = 50;
class ExternalLayersComponent 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>
#panel{background:var(--bkg-color);height:100%;color:var(--text-color);flex-direction:column;padding:0 1rem;display:flex}#content{flex-direction:column;flex-grow:1;margin:0;display:flex}header{background-color:var(--bkg-color);margin:0;position:sticky;top:-5px}h4{margin-bottom:.5rem}ul{margin-top:0;margin-left:0;padding-left:2rem;line-height:1.3rem;list-style-type:disc}.clearable-input{background-color:var(--bkg-color);border:1px solid #cfd6dd;border-radius:4px;flex-direction:row;margin-bottom:.1rem;display:flex}.scan-button{float:right}.layers{border-top:1px solid #ccc;flex-direction:column;flex-grow:1;margin-top:1rem;padding-top:.5rem;display:flex;overflow:hidden}ul.results{border:none;margin-bottom:.5rem;padding:0;list-style:none;overflow-y:auto}.result{height:1.6rem;display:flex}.result>button>span{text-align:left;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#panel>div{padding:1rem}#layers li{margin-top:.3rem;margin-bottom:.3rem}#layers li button{text-align:left;overflow-wrap:anywhere;text-wrap-style:balance}#file-selector{display:grid}#file,#file-label{grid-area:1/1}#file{opacity:0;z-index:2;cursor:pointer}#file::file-selector-button{cursor:pointer}#loading-icon{flex-grow:1;align-self:center;width:3rem}.title{margin-top:0}.filter-buttons{flex-direction:row;margin:2px;display:flex}.filter-buttons span{flex-grow:1;align-self:center}.clearable-input-field{width:90%;color:var(--text-color);background:0 0;border:0;outline:none;flex:auto;padding:0;font-size:1rem}.filter-icon,.delete-icon{width:16px;color:var(--text-color);padding:0 .5rem}.delete-button{cursor:pointer;background-color:#0000;border:none;padding:0}
</style>
<style>${this.customStyle}</style>
<div id="panel"><header class="gg-tabs"><button class="${this.selectedTab === 'wms_wmts' ? 'gg-tab active' : 'gg-tab'}" onclick="${() => this.setSelectedTab('wms_wmts')}" i18n="wms_wmts"></button> <button class="${this.selectedTab === 'file' ? 'gg-tab active' : 'gg-tab'}" onclick="${() => this.setSelectedTab('file')}" i18n="local file"></button></header><section class="${(this.selectedTab === 'wms_wmts') ? 'group' : 'hidden'}"><h4 class="title" i18n="Suggestions" ?hidden="${!this.hasPredefinedWmsWmtsSources}">Suggestions</h4><ul class="suggestions" ?hidden="${!this.hasPredefinedWmsWmtsSources}">${this.predefinedWmsWmtsSources.map(source => uHtmlFor(source, source.label) `<li><a href="javascript:void(0)" onclick="${() => this.scanSource(source.url, source.type)}">${source.label}</a></li>`)}</ul><h4 class="title" i18n="Custom service URL">Custom service URL</h4><div class="clearable-input"><input id="url" class="gg-input clearable-input-field" oninput="${() => this.typeUrl()}"><br><button id="clear-url" class="delete-button hidden" onclick="${() => this.clearUrl()}"><img class="delete-icon" alt="delete-button-icon" tip="Reset filter" i18n="Reset filter" src="icons/trash.svg"></button></div><button i18n="Scan Source" class="gg-button scan-button" onclick="${() => this.scanSource()}">Scan Source</button></section><section class="${(this.selectedTab === 'file') ? 'group' : 'hidden'}"><h4 class="title" i18n="Choose local file">Choose local file</h4><div id="file-selector"><label for="file" id="file-label"><button class="gg-button" i18n="Select File"></button> <span>${this.fileDescription}</span></label> <input type="file" accept=".gpx,.kml,.geojson,.json" id="file" onchange="${() => this.render()}"><br></div><button id="load" i18n="Load File" class="gg-button" onclick="${() => this.loadFile()}"></button></section><section class="${(this.selectedTab === 'wms_wmts' && this.externalLayers.length > 0) || this.loading ? 'layers' : 'hidden'}"><h4 class="title" i18n="Layers (from Capabilities)">Layers (from Capabilities)</h4><div class="clearable-input"><img class="filter-icon" alt="filter-button-icon" src="icons/filter.svg"> <input id="layer-search-field" class="gg-input clearable-input-field" placeholder="${this.context.i18nManager.getTranslation('Filter external layers...')}" i18n="Filter external layers..." autocomplete="off" autocorrect="off" oninput="${(e) => this.filterLayers(e.target.value)}"> <button class="${this.isFiltered ? 'delete-button' : 'hidden'}" onclick="${() => this.clearFilter()}"><img class="delete-icon" alt="delete-button-icon" tip="Reset filter" i18n="Reset filter" src="icons/trash.svg"></button></div><div class="filter-buttons"><span>${Object.values(this.externalLayers).filter(layer => layer.isSelected).length.toString()} ${this.context.i18nManager.getTranslation('layers selected')} </span><button class="gg-button" tip="Select all filtered layers" onclick="${() => this.selectVisible()}">+</button> <button class="gg-button" tip="Unselect all filtered layers" onclick="${() => this.deselectVisible()}">-</button> <button class="gg-button" tip="Select none" onclick="${() => this.deselectAll()}">--</button></div><img id="loading-icon" alt="loading-icon" src="icons/loading.svg" class="${this.loading ? 'gg-spin' : 'hidden'}"><ul class="results">${this.filteredLayers.map(layer => uHtmlFor(layer, layer.treeItemId) `<li class="result"><button class="${layer.isSelected ? 'gg-icon-button gg-small gg-selected' : 'gg-icon-button gg-small gg-opacity'}" tip="Activate / Deactivate" onclick="${() => this.selectLayer(layer)}"><img class="${layer.isSelected ? 'gg-checkbox' : 'hidden'}" alt="Expand/Collapse button" src="icons/checked-full.svg"> <img class="${!layer.isSelected ? 'gg-checkbox' : 'hidden'}" alt="Expand/Collapse button" src="icons/checked-no.svg"></button> <button class="${layer.isSelected ? 'gg-icon-button gg-small gg-selected' : 'gg-icon-button gg-small gg-opacity'}" onclick="${() => this.selectLayer(layer)}"><span i18n="${layer.name}" class="gg-tree-label">${layer.name}</span></button></li>`)}</ul><button id="add" tip="Add selected" i18n="Add selected" class="gg-button" onclick="${() => this.addSelectedLayers()}">Add selected</button></section></div>
${this.htmlUnsafe(this.feedbackTemplateHtml ?? '')}`;
};
isPanelVisible = false;
panelTitle = 'ext-layer-panel';
panelTogglePath = 'interface.extLayerPanelVisible';
loading = false;
predefinedSources = [];
get predefinedWmsWmtsSources() {
return this.predefinedSources.filter((source) => source.type === 'WMS' || source.type === 'WMTS');
}
get hasPredefinedWmsWmtsSources() {
return this.predefinedWmsWmtsSources.length > 0;
}
selectedTab = 'wms_wmts';
wmtsManager;
themeName;
externalLayers = [];
filteredLayers = [];
get isFiltered() {
return this.externalLayers.length > this.filteredLayers.length;
}
constructor() {
super('external-layers');
}
render() {
if (this.isPanelVisible) {
super.render();
super.girafeTranslate();
}
else {
this.renderEmpty();
}
}
togglePanel(isVisible) {
this.isPanelVisible = isVisible;
this.render();
}
setSelectedTab(selectedTab) {
this.selectedTab = selectedTab;
this.refreshRender();
}
async scanSource(url, sourceType) {
this.externalLayers = [];
this.filteredLayers = [];
this.loading = true;
this.refreshRender();
if (!url) {
url = this.shadow.getElementById('url').value;
if (url.trim().length === 0) {
return;
}
}
try {
if (sourceType === 'WMS') {
await this.scanLayersWMS(url);
}
else if (sourceType === 'WMTS') {
await this.scanLayersWMTS(url);
}
else {
// Don't know the type, we try both
try {
await this.scanLayersWMS(url);
}
catch {
await this.scanLayersWMTS(url);
}
}
this.clearFilter();
}
finally {
this.loading = false;
this.refreshRender();
}
}
async scanLayersWMS(url) {
const parsedUrl = URL.parse(url);
if (!parsedUrl) {
return;
}
this.themeName = this.parseName(url);
const urlTxt = `${parsedUrl?.origin}${parsedUrl?.pathname}`;
// Try to add a server type from the getCapabilities url params.
const serverTypeKey = Array.from(parsedUrl.searchParams.keys()).find((key) => key.toLowerCase() === 'servertype');
const serverType = (parsedUrl.searchParams.get(serverTypeKey ?? '') ?? 'other');
const server = new ServerOgc(this.themeName, {
url: urlTxt,
type: serverType,
wfsSupport: true,
urlWfs: urlTxt,
imageType: 'image/png'
});
const client = this.context.wmsManager.createClient(WmsClientDefault, server);
const capabilities = await client.getWmsCapabilities(parsedUrl.searchParams);
if (capabilities?.Service?.Title) {
this.themeName = capabilities.Service.Title;
}
this.externalLayers = capabilities.Capability.Layer.Layer.map((l) => new LayerWmsExternal(l.Title, l.Name, server));
}
async scanLayersWMTS(url) {
this.themeName = this.parseName(url);
const capabilities = await this.wmtsManager.getWmtsCapabilities(url);
this.loading = false;
if (capabilities?.ServiceIdentification?.Title) {
this.themeName = capabilities.ServiceIdentification.Title;
}
this.externalLayers = capabilities.Contents.Layer.map((l) => new LayerWmtsExternal(l.Title, url, l.Identifier));
}
selectLayer(layer, forceSelect) {
layer.isSelected = forceSelect ?? !layer.isSelected;
this.refreshRender();
if (this.externalLayers.filter((l) => l.isSelected).length > MaxLayers) {
layer.isSelected = false;
window.gAlert(`For performance reasons, they cannot all be added to the treeview. Please limit the selection to ${MaxLayers} objects.`, 'Too many layers selected!');
return false;
}
return true;
}
parseName(url) {
const { pathname, host } = new URL(url);
const basePath = pathname
.replace(/\/WMTSCapabilities.xml$/, '')
.replace(/\/1.0.0$/, '')
.replace(/\/$/, '');
return `${host}${basePath}`;
}
filterLayers(filter) {
this.filteredLayers = this.externalLayers
.filter((l) => l.name.toLowerCase().includes(filter.toLowerCase()))
.sort((a, b) => a.name.localeCompare(b.name));
this.refreshRender();
}
clearFilter() {
const filterField = this.shadow.getElementById('layer-search-field');
filterField.value = '';
// Order the layers by name
this.filteredLayers = [...this.externalLayers].sort((a, b) => a.name.localeCompare(b.name));
this.refreshRender();
}
typeUrl() {
const urlField = this.shadow.getElementById('url');
const urlReset = this.shadow.getElementById('clear-url');
if (urlField.value === '') {
urlReset.classList.add('hidden');
}
else {
urlReset.classList.remove('hidden');
}
}
clearUrl() {
const urlField = this.shadow.getElementById('url');
urlField.value = '';
const urlReset = this.shadow.getElementById('clear-url');
urlReset.classList.add('hidden');
this.render();
}
selectVisible() {
for (const layer of this.filteredLayers) {
if (!this.selectLayer(layer, true)) {
break;
}
}
this.refreshRender();
}
deselectVisible() {
for (const layer of this.filteredLayers) {
this.selectLayer(layer, false);
}
this.refreshRender();
}
deselectAll() {
for (const layer of this.externalLayers) {
this.selectLayer(layer, false);
}
this.refreshRender();
}
addSelectedLayers() {
const selectedLayers = this.externalLayers.filter((layer) => layer.isSelected).map((l) => l.clone());
if (selectedLayers.length === 0) {
// Nothing to add
return;
}
const theme = new ThemeLayerExternal(this.themeName);
theme.children = selectedLayers;
theme.children.forEach((l) => {
l.parent = theme;
});
this.context.stateManager.batchChanges(() => {
this.state.layers.layersList.push(theme);
});
}
get fileDescription() {
const selectedFiles = this.getById('file')?.files;
if (!selectedFiles || selectedFiles.length == 0) {
return '';
}
return `${selectedFiles[0].name} (${selectedFiles[0].size}b)`;
}
async loadFile() {
const selectedFiles = this.getById('file').files;
if (selectedFiles && selectedFiles.length > 0) {
const selectedFile = selectedFiles[0];
await this.context.localFileManager.loadLocalFile(selectedFile);
}
}
connectedCallback() {
super.connectedCallback();
const olMap = this.context.mapManager.getMap();
// TODO REG : User context singleton for the WMTS-Manager
this.wmtsManager = new WmtsManager(olMap, this.context.stateManager);
const config = this.context.configManager.Config;
this.predefinedSources = config.externalLayers?.predefinedSources || [];
this.render();
}
}
export default ExternalLayersComponent;