UNPKG

@geogirafe/lib-geoportal

Version:

GeoGirafe is a flexible application to build online geoportals.

544 lines (533 loc) 23.6 kB
import { htmlFor as uHtmlFor } from 'uhtml/keyed'; import { html as uHtml } from 'uhtml'; import GirafeHTMLElement from '../../base/GirafeHTMLElement'; import StateManager from '../../tools/state/statemanager'; import OgcApiFeaturesManager from '../../tools/ogcapi/ogcapifeaturesmanager'; import MapManager from '../../tools/state/mapManager'; import { Draw, Modify, Select } from 'ol/interaction'; import Feature from 'ol/Feature'; import VectorSource from 'ol/source/Vector'; import VectorLayer from 'ol/layer/Vector'; import { Circle, Fill, Stroke, Style } from 'ol/style'; import { bbox } from 'ol/loadingstrategy'; import { DEMO_LAYERS } from '../../tools/ogcapi/demolayers'; import { getSelectionBoxFromMapClick } from '../../tools/utils/olutils'; const getStyle = (col = 'rgb(255,89,0)', width = 4) => { return new Style({ stroke: new Stroke({ color: col, width: width }), fill: new Fill({ color: col }), image: new Circle({ radius: width, fill: new Fill({ color: col }) }) }); }; const baseStyle = getStyle(); const editStyle = getStyle('rgb(0,81,255)', 6); const newId = '-'; export default class EditComponent extends GirafeHTMLElement { constructor() { super('edit'); Object.defineProperty(this, "template", { enumerable: true, configurable: true, writable: true, value: () => { return uHtml `<style> *{font-family:Arial,sans-serif}.hidden{display:none!important}.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}.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-grad2);background-color:var(--text-color-grad2);color:var(--bkg-color)}.gg-button:disabled{color:gray;cursor:not-allowed;background-color:#d3d3d3;border:none}.gg-input:disabled,.gg-select:disabled,.gg-textarea:disabled{color:gray;cursor:not-allowed;background-color:#d3d3d3}.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-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,.gg-select:hover,.gg-input:hover,.gg-textarea:hover,.gg-icon-button:hover{background-color:var(--bkg-color-grad1)}.gg-opacity{opacity:.5}.gg-opacity:hover{opacity:1;background-color:#0000}.gg-tabs{cursor:pointer;border-bottom:1px solid gray;justify-content:left;align-items:end;gap:1rem;height:2rem;margin:.5rem auto 1rem;display:flex}.gg-tab{cursor:pointer;color:var(--text-color);background:0 0;border:none;padding:.5rem}.gg-tab.active{border-bottom:solid 2px var(--text-color-grad2);font-weight:600}.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} </style><style> #content{background:var(--bkg-color);color:var(--text-color);flex-direction:column;gap:1rem;margin:0;padding:1rem;display:flex}.girafe-prototype{color:#fff;text-align:center;background:#ec5555;font-size:1rem;font-weight:700;line-height:40px}.editing{flex-direction:column;gap:1rem;display:flex}#layer-selector{width:100%}.draw-btn{text-align:right}.current-feature{border-top:var(--app-standard-border);margin-top:2rem}.current-feature-row{align-items:center;gap:.5em;display:flex}.current-feature-row>button{margin-left:auto}.current-feature-row>div:first-child{font-weight:700}.attribute-form-btns{justify-content:flex-end;gap:.5rem;margin-top:1rem;display:flex}.btn-active{background-color:var(--bkg-color-grad2)} </style> <div id="content"> <div class="girafe-prototype" i18n="PROTOTYPE - Work in progress">PROTOTYPE - Work in progress</div> <div class="editing"> <select id="layer-selector" class="gg-select" disabled="${this.feature}" onchange="${(evt) => this.onSelectLayer(evt)}"> <option i18n="Choose a layer..." ?selected="true" value="">Choose a layer...</option> ${this.editableLayersList.map(layer => uHtmlFor(layer, layer.id) ` <option value="${layer.id}">${layer.name}</option> `)} </select> ${this.layer ? uHtml ` <div class="draw-btn"> ${this.displayDrawingCancelButton() ? uHtml ` <button class="gg-button gg-medium-withtext btn-active" onclick="${() => this.onCancelDrawing()}"> <img alt="cancel-drawing-icon" src="icons/close.svg" /> <span i18n="Cancel editing">Cancel editing</span> </button> ` : uHtml ` <button class="gg-button gg-medium-withtext" onclick="${() => this.onStartDrawing()}"> <img alt="start-drawing-icon" src="${this.getButtonIcon()}" /> <span i18n="${this.getButtonText()}">${this.getButtonText()}</span> </button> `} </div> ` : uHtml ``} ${this.feature ? uHtml ` <div class="current-feature"> <h3 i18n="Current Feature">Current Feature</h3> <div class="current-feature-row"> <div i18n="Feature ID">Feature ID</div> <div>${this.getFeatureId()}</div> <button class="${this.canDelete() ? 'gg-button gg-medium-withtext delete-btn' : 'hidden'}" onclick="${() => this.onDelete()}"> <img alt="delete-icon" src="icons/trash.svg" /> <span i18n="delete">Delete</span> </button> </div> </div> ` : uHtml ``} <girafe-edit-form id="edit-form"></girafe-edit-form> ${this.feature ? uHtml ` <div class="attribute-form-btns"> <button class="gg-button" disabled="${!this.isValidForm()}" onclick="${() => this.onSave()}"> <span i18n="Save">Save</span> </button> <button class="gg-button" onclick="${() => this.onDiscard()}"> <span i18n="Discard">Discard</span> </button> </div> ` : uHtml ``} </div> </div> `; } }); Object.defineProperty(this, "stateManager", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "oapifManager", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "visible", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "editableLayersList", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "map", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "draw", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "modify", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "select", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "drawingLayer", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "drawingSource", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "feature", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "form", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "featureSchema", { enumerable: true, configurable: true, writable: true, value: void 0 }); // POC: Demo layers Object.defineProperty(this, "layer", { enumerable: true, configurable: true, writable: true, value: void 0 }); // Layer definition / config Object.defineProperty(this, "demoMapLayer", { enumerable: true, configurable: true, writable: true, value: void 0 }); // Layer in the map this.stateManager = StateManager.getInstance(); this.oapifManager = OgcApiFeaturesManager.getInstance(); this.map = MapManager.getInstance().getMap(); this.subscribe('oauth.status', () => this.loginStateChanged()); } render() { super.render(); if (this.visible) { this.renderComponent(); } else { this.renderEmptyComponent(); } super.girafeTranslate(); } renderComponent() { this.registerInteractionListener('map.select', true); this.registerInteractionListener('map.draw', true); this.registerInteractionListener('map.modify', true); this.collectEditableLayers(); this.refreshRender(); if (!this.form) { // The attribute form is managed in a subcomponent this.form = this.getById('edit-form'); } } renderEmptyComponent() { this.resetComponent(); this.renderEmpty(); } loginStateChanged() { // List of POC demo layers // The GMF demo layer is only selectable when in the experimental demo and logged in const isOnGMF29DemoAndLoggedIn = this.configManager.Config.themes.url.includes('geomapfish-demo-2-9.camptocamp') && this.state.oauth.status === 'loggedIn'; this.editableLayersList = Object.keys(DEMO_LAYERS) .filter((layerID) => layerID !== 'GMF' || isOnGMF29DemoAndLoggedIn) .map((layerID) => { return { id: layerID, name: DEMO_LAYERS[layerID].name }; }); this.loadDemoServerConfig(); this.render(); } async onSelectLayer(evt) { const layerId = evt.target?.value; this.layer = DEMO_LAYERS[layerId]; this.removeMapInteractions(); this.unsetEditFeature(); if (this.layer) { this.featureSchema = await this.oapifManager.getSchema(this.layer); this.form.setSchema(this.featureSchema); this.createDemoMapLayer(); // POC this.createMapInteractions(); } else { this.removeDemoMapLayer(); // POC } this.refreshRender(); } onStartDrawing() { this.unsetEditFeature(); this.startDrawingMode(); this.refreshRender(); } onCancelDrawing() { this.onDiscard(); } onDiscard() { this.unsetEditFeature(); this.startSelectionMode(); this.refreshRender(); } startDrawingMode() { // Stop selection mode this.select?.getFeatures().clear(); this.select?.setActive(false); // Start drawing mode this.drawingSource?.clear(); this.draw?.setActive(true); } startSelectionMode() { this.draw?.setActive(false); this.select?.getFeatures().clear(); this.select?.setActive(true); } onSave() { if (!this.feature) return; void this.saveFeature(); } async onDelete() { if (!this.feature || !this.canDelete()) return; const confirm = await window.gConfirm('Do you want to delete this feature?', 'Delete feature'); if (confirm) { void this.deleteFeature(this.getFeatureId()); } } canDelete() { return this.getFeatureId() !== newId; } resetComponent() { this.removeMapInteractions(); this.unselectLayer(); this.removeDemoMapLayer(); // POC this.refreshRender(); } unselectLayer() { this.layer = undefined; this.unsetEditFeature(); this.getById('layer-selector').value = ''; } collectEditableLayers() { // POC return; } createMapInteractions() { if (!this.drawingLayer) { // Create drawing layer and source this.drawingSource = new VectorSource({}); this.drawingLayer = new VectorLayer({ source: this.drawingSource, style: editStyle, zIndex: 2001 }); this.map.addLayer(this.drawingLayer); } // Interactions if (this.select) { this.map.removeInteraction(this.select); } if (this.demoMapLayer) { this.select = new Select({ layers: [this.demoMapLayer], hitTolerance: 10, style: editStyle }); this.select.on('select', (evt) => { if (!this.canExecute('map.select')) return; void this.onSelectFeature(evt); }); this.map.addInteraction(this.select); } if (this.draw) { this.map.removeInteraction(this.draw); } this.draw = new Draw({ source: this.drawingSource, condition: () => this.canExecute('map.draw'), type: this.layer.geometryType, stopClick: true, style: editStyle }); this.draw.on('drawstart', () => { }); this.draw.on('drawend', (evt) => { if (!this.canExecute('map.draw')) return; this.setEditFeature(evt.feature); this.draw?.setActive(false); }); this.draw.setActive(false); this.map.addInteraction(this.draw); if (this.modify) { this.map.removeInteraction(this.modify); } this.modify = new Modify({ source: this.drawingSource, condition: () => this.canExecute('map.modify') }); this.map.addInteraction(this.modify); this.modify.setActive(false); } removeMapInteractions() { this.drawingSource?.clear(); if (this.select) this.map.removeInteraction(this.select); if (this.draw) this.map.removeInteraction(this.draw); if (this.modify) this.map.removeInteraction(this.modify); if (this.drawingLayer) { this.map.removeLayer(this.drawingLayer); this.drawingLayer = undefined; } } async onSelectFeature(evt) { this.drawingSource?.clear(); const bbox = getSelectionBoxFromMapClick(evt.mapBrowserEvent.pixel, this.map, 10); const selectedFeature = await this.oapifManager.getItems(this.layer, this.map.getView().getProjection().getCode(), bbox, 1); if (selectedFeature.length > 0) { this.setEditFeature(selectedFeature[0]); if (this.feature) this.drawingSource?.addFeature(this.feature); } else { this.unsetEditFeature(); } this.select?.getFeatures().clear(); } setEditFeature(feature) { if (!feature) { this.unsetEditFeature(); return; } this.feature = feature; this.form.setFeature(this.feature); this.modify?.setActive(true); this.refreshRender(); } unsetEditFeature() { this.feature = undefined; this.drawingSource?.clear(); this.form?.setFeature(this.feature); this.modify?.setActive(false); this.refreshRender(); } isValidForm() { return this.form.valid(); } async saveFeature() { if (!this.layer || !this.feature) { return; } const formValues = this.form.getFormValues(); const featureToSave = new Feature(); const id = this.getFeatureId(); featureToSave.setGeometry(this.feature.getGeometry()); featureToSave.setProperties(formValues); if (id === newId) { await this.oapifManager.createItem(this.layer, featureToSave); } else { featureToSave.setId(id); await this.oapifManager.updateItem(this.layer, id, featureToSave); } this.unsetEditFeature(); this.refreshDemoMapLayer(); this.startSelectionMode(); } async deleteFeature(featureId) { await this.oapifManager.deleteItem(this.layer, featureId); this.unsetEditFeature(); this.refreshDemoMapLayer(); this.startSelectionMode(); } createDemoMapLayer() { if (!this.layer) return; if (this.demoMapLayer) { this.removeDemoMapLayer(); } const vectorSource = new VectorSource({ loader: async (extent, _resolution, projection) => { const features = await this.oapifManager.getItems(this.layer, projection.getCode(), extent); if (features) { vectorSource.addFeatures(features); } }, strategy: bbox }); this.demoMapLayer = new VectorLayer({ source: vectorSource, style: baseStyle }); this.map.addLayer(this.demoMapLayer); } refreshDemoMapLayer() { if (!this.layer) return; if (!this.demoMapLayer) { this.createDemoMapLayer(); } this.demoMapLayer.getSource().refresh(); } removeDemoMapLayer() { if (this.demoMapLayer) { this.map.removeLayer(this.demoMapLayer); this.demoMapLayer = undefined; } } togglePanel(visible) { this.visible = visible; this.render(); } getButtonIcon() { let icon = 'draw'; const geometryType = this.layer?.geometryType ?? ''; if (geometryType.includes('Point')) { icon = 'point'; } else if (geometryType.includes('Line')) { icon = 'polyline'; } else if (geometryType.includes('Polygon')) { icon = 'polygon'; } return `icons/${icon}.svg`; } getButtonText() { let text = 'Draw geometry'; const geometryType = this.layer?.geometryType ?? ''; if (geometryType.includes('Point')) { text = geometryType.startsWith('Multi') ? 'Draw points' : 'Draw point'; } else if (geometryType.includes('Line')) { text = geometryType.startsWith('Multi') ? 'Draw lines' : 'Draw line'; } else if (geometryType.includes('Polygon')) { text = geometryType.startsWith('Multi') ? 'Draw polygons' : 'Draw polygon'; } return text; } displayDrawingCancelButton() { return this.draw?.getActive() ?? false; } getFeatureId() { if (this.feature && this.featureSchema) { return this.feature.getId()?.toString() ?? newId; } return ''; } getFeatureProperties() { return this.featureSchema?.formAttributes ?? []; } /** * POC: Add ogc servers to the state and preload them. */ loadDemoServerConfig() { this.editableLayersList.forEach((layer) => { if (!this.state.ogcServers[DEMO_LAYERS[layer.id].server.name]) { this.state.ogcServers[DEMO_LAYERS[layer.id].server.name] = DEMO_LAYERS[layer.id].server; void OgcApiFeaturesManager.getInstance().getServer(DEMO_LAYERS[layer.id].server); } }); } connectedCallback() { this.loadConfig().then(() => { // Add ogc servers to state this.subscribe('interface.editPanelVisible', (_, newValue) => this.togglePanel(newValue)); this.render(); }); } }