@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
507 lines (493 loc) • 22.8 kB
JavaScript
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 VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import { Circle, Fill, Stroke, Style } from 'ol/style';
import ServerOgcApi from '../../models/serverogcapi';
import { DEMO_INSTANCES } from '../../tools/ogcapi/ogcapifeaturesclient';
import { bbox } from 'ol/loadingstrategy';
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);
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{color:var(--link-color)}a:visited{color:var(--link-color)} spin{from{transform:rotate(0)}to{transform:rotate(360deg)}} spin-wait{0%{transform:rotate(0)}7%{transform:rotate(360deg)}100%{transform:rotate(360deg)}}.gg-spin{animation-name:spin;animation-duration:2s;animation-iteration-count:infinite;animation-timing-function:linear}.gg-spin-wait{animation-name:spin-wait;animation-duration:10s;animation-iteration-count:infinite;animation-timing-function:linear}::-webkit-scrollbar{width:5px}::-webkit-scrollbar-thumb{background:#999}.gg-button,.gg-input,.gg-select,.gg-textarea{background-color:var(--bkg-color);color:var(--text-color);outline:0;border-radius:3px;border:var(--app-standard-border);display:inline-block;box-sizing:border-box;padding:0 0 0 .5rem;margin:0;cursor:pointer}.gg-label{background-color:var(--bkg-color);color:var(--text-color);border:none;display:inline-block;padding:0;margin:0}.gg-button,.gg-input,.gg-label,.gg-select{min-height:calc(var(--app-standard-height)/ 1.5);max-height:calc(var(--app-standard-height)/ 1.5);line-height:calc(var(--app-standard-height) / 1.5)}.gg-textarea{padding:.5rem;height:6rem}.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{background-color:#d3d3d3;color:grey;border:none;cursor:not-allowed}.gg-button>img{vertical-align:middle}.gg-icon-button{border:none;background-color:transparent;display:flex;flex-direction:column;color:var(--text-color);padding:0;align-items:center;justify-content:center;cursor:pointer}.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{margin:0;width:calc(var(--app-standard-height) - 1.5rem)}.gg-big-withtext span{font-size:.9rem;font-variant:small-caps;padding:0 1rem}.gg-medium,.gg-medium-withtext{flex-direction:row;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)}.gg-medium img{margin:0;width:calc(var(--app-standard-height)/ 2.4)}.gg-medium-withtext img{margin-left:.5rem;width:calc(var(--app-standard-height)/ 2.4)}.gg-medium-withtext span{font-size:.9rem;padding:0 1rem;padding-left:.5rem}.gg-small,.gg-small-withtext{flex-direction:row;min-width:calc(var(--app-standard-height)/ 2);min-height:calc(var(--app-standard-height)/ 2);max-height:calc(var(--app-standard-height)/ 2)}.gg-small img{margin:0;width:calc(var(--app-standard-height)/ 3)}.gg-small-withtext img{margin-left:.5rem;width:calc(var(--app-standard-height)/ 3)}.gg-small-withtext span{font-size:.9rem;padding:0 .5rem;padding-left:.3rem}.gg-button:hover,.gg-icon-button:hover,.gg-input:hover,.gg-select:hover,.gg-textarea:hover{background-color:var(--bkg-color-grad1)}.gg-opacity{opacity:.5}.gg-opacity:hover{background-color:transparent;opacity:1}.gg-tabs{display:flex;justify-content:left;margin:.5rem auto 0;border-bottom:1px solid grey;cursor:pointer;height:2rem;align-items:end;gap:1rem;margin-bottom:1rem}.gg-tab{border:none;background:0 0;cursor:pointer;padding:.5rem;color:var(--text-color)}.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{border:none;background-color:transparent;display:flex;flex-direction:column;color:var(--text-color)}.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(1)}.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{margin:.3rem;height:2rem}.girafe-button-large span{line-height:2rem;height:2rem;margin:.3rem}.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{width:100%;text-align:left;overflow:hidden;text-overflow:ellipsis}.girafe-button-tiny{width:1rem;height:1rem;align-items:center;padding:0}.girafe-button-tiny img{overflow:hidden}
</style><style>
#content{background:var(--bkg-color);color:var(--text-color);padding:1rem;margin:0;display:flex;flex-direction:column;gap:1rem}.girafe-prototype{line-height:40px;color:#fff;background:#ec5555;text-align:center;font-weight:700;font-size:1rem}.editing{display:flex;flex-direction:column;gap:1rem}#layer-selector{width:100%}.draw-btn{text-align:right}.current-feature{border-top:var(--app-standard-border);margin-top:3rem}.current-feature-row{display:flex;gap:.5em;align-items:center}.current-feature-row>button{margin-left:auto}.attribute-form{display:flex;flex-direction:column;gap:.5rem;margin-top:3rem}.attribute-form-row{display:flex;flex-direction:column;gap:.5rem}.attribute-form-btns{margin-top:1rem;display:flex;gap:.5rem;justify-content:flex-end}.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.hasFeature()}"
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.displayDrawingStartButton() ? 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>
` : uHtml `
<button class="gg-button gg-medium-withtext btn-active" onclick="${() => this.onCancelEditing()}">
<img alt="cancel-drawing-icon" src="icons/close.svg" />
<span i18n="Cancel editing">Cancel editing</span>
</button>
`}
</div>
${this.hasFeature() ? 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="gg-button gg-medium-withtext delete-btn" disabled onclick="${() => this.onDelete()}">
<img alt="delete-icon" src="icons/trash.svg" />
<span i18n="delete">Delete</span>
</button>
</div>
</div>
<div class="attribute-form">
<div class="attribute-form-row">
<label for="attribute-test">${this.layer.attributeName}</label>
<input id="attribute-test" type="${this.layer.attributeType}" class="gg-input" />
</div>
<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>
</div>
</div>
` : uHtml ``} ` : uHtml ``}
</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, "isDrawing", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
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, "propertiesTemplate", {
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();
// 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_INSTANCES)
.filter((layerID) => layerID !== 'GMF' || isOnGMF29DemoAndLoggedIn)
.map((layerID) => {
return { id: layerID, name: DEMO_INSTANCES[layerID].name };
});
}
render() {
super.render();
this.visible ? this.renderComponent() : this.renderEmptyComponent();
super.girafeTranslate();
}
renderComponent() {
this.registerInteractionListener('map.select', true);
this.registerInteractionListener('map.draw', true);
this.registerInteractionListener('map.modify', true);
this.collectEditableLayers();
this.refreshRender();
}
renderEmptyComponent() {
this.resetComponent();
this.renderEmpty();
}
onSelectLayer(evt) {
const layerId = evt.target?.value;
this.layer = DEMO_INSTANCES[layerId];
this.removeMapInteractions();
this.clearForm();
if (this.layer) {
this.layer.server = new ServerOgcApi(layerId, this.layer.url, this.layer.serverType);
this.oapifManager.getItemTemplate(this.layer).then((response) => (this.propertiesTemplate = response));
this.createDemoMapLayer(); // POC
this.createMapInteractions();
}
else {
this.removeDemoMapLayer(); // POC
}
this.refreshRender();
}
onStartDrawing() {
this.drawingSource?.clear();
this.select?.getFeatures().clear();
this.select?.setActive(false);
this.draw?.setActive(true);
this.isDrawing = true;
this.refreshRender();
}
onCancelEditing() {
this.resetComponent();
}
onDiscard() {
this.select?.getFeatures().clear();
this.drawingSource?.clear();
this.refreshDemoMapLayer();
this.clearForm();
this.select?.setActive(true);
this.refreshRender();
}
onSave() {
this.feature = this.drawingSource?.getFeatures()[0] ?? undefined;
this.readoutAttributes();
void this.saveFeature();
}
onDelete() {
throw new Error('Method not implemented.');
}
hasFeature() {
return this.drawingSource && this.drawingSource.getFeatures().length > 0;
}
resetComponent() {
this.removeMapInteractions();
this.unselectLayer();
this.removeDemoMapLayer(); // POC
this.clearForm();
this.refreshRender();
}
unselectLayer() {
this.layer = undefined;
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;
this.drawingSource?.clear();
if (evt.selected.length > 0) {
this.drawingSource?.addFeature(evt.selected[0].clone());
this.select?.getFeatures().clear();
}
this.refreshRender();
});
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', (_e) => {
this.isDrawing = false;
this.draw?.setActive(false);
this.refreshRender();
});
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);
}
removeMapInteractions() {
this.clearDrawing();
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;
}
}
clearDrawing() {
this.drawingSource?.clear();
this.feature = undefined;
this.draw?.setActive(false);
}
clearForm() {
const nameInput = this.getById('attribute-name');
if (nameInput instanceof HTMLInputElement) {
nameInput.value = '';
}
}
isValidForm() {
// POC: Only allow saving for newly created features without an ID
return this.getFeatureId() === '';
}
readoutAttributes() {
if (!this.feature || !this.layer) {
return;
}
const nameInput = this.getById('attribute-test');
const properties = this.getPropertiesTemplate();
// Set attribute values
if (Object.keys(properties).includes(this.layer.attributeName)) {
let attrValue = nameInput.value;
if (this.layer.attributeType === 'number') {
attrValue = Number(attrValue);
}
properties[this.layer.attributeName] = attrValue;
}
this.feature.setProperties(properties);
}
getPropertiesTemplate() {
let properties = { ...this.propertiesTemplate };
// POC: If the OAPIF service did not provide a schema, use the first feature in the source as a template
if (Object.keys(properties).length === 0) {
const randomFeature = this.demoMapLayer.getSource().getFeatures()[0];
properties = { ...(randomFeature?.getProperties() ?? {}) };
properties.fid = null;
delete properties.geometry;
Object.keys(properties).forEach(function (index) {
properties[index] = null;
});
}
return properties;
}
async saveFeature() {
if (!this.layer || !this.feature) {
return;
}
// Create the feature on the server
const success = await this.oapifManager.createItem(this.layer, this.feature);
if (success) {
this.clearDrawing();
this.clearForm();
this.refreshDemoMapLayer();
this.select?.setActive(true);
this.refreshRender();
}
else {
void window.gAlert('Error when saving feature', 'Error');
}
}
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, extent, this.layer.crs);
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;
}
displayDrawingStartButton() {
return !this.hasFeature() && !this.isDrawing;
}
getFeatureId() {
return this.drawingSource?.getFeatures()[0]?.getId() ?? '';
}
connectedCallback() {
this.loadConfig().then(() => {
this.subscribe('interface.editPanelVisible', (_, newValue) => this.togglePanel(newValue));
this.render();
});
}
}