@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
417 lines (416 loc) • 22.8 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 { Draw, Modify, Select } from 'ol/interaction.js';
import Feature from 'ol/Feature.js';
import VectorSource from 'ol/source/Vector.js';
import VectorLayer from 'ol/layer/Vector.js';
import { Circle, Fill, Stroke, Style } from 'ol/style.js';
import { bbox } from 'ol/loadingstrategy.js';
import { DEMO_LAYERS } from '../../tools/ogcapi/demolayers.js';
import { getSelectionBoxFromMapClick } from '../../tools/utils/olutils.js';
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 {
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>
#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>
<style>${this.customStyle}</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)}">${this.editableLayersList.length === 0 && this.state.oauth.status !== 'loggedIn' ? uHtml `<option i18n="Please log in to edit layers..." ?selected="true" value="">Please log in to edit layers...</option>` : uHtml `<option i18n="Choose a layer..." ?selected="true" value="">Choose a layer...</option>`} ${this.editableLayersList.map(layer => uHtmlFor(layer, layer.collectionId) `<option value="${layer.collectionId}">${layer.displayName}</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>
${this.htmlUnsafe(this.feedbackTemplateHtml ?? '')}`;
};
isPanelVisible = false;
panelTitle = 'edit-panel';
panelTogglePath = 'interface.editPanelVisible';
editableLayersList = [];
get map() {
return this.context.mapManager.getMap();
}
draw;
modify;
select;
drawingLayer;
drawingSource;
feature;
form;
featureSchema;
// POC: Demo layers
layer; // Layer definition / config
demoMapLayer; // Layer in the map
constructor() {
super('edit');
}
render() {
super.render();
if (this.isPanelVisible) {
this.renderComponent();
this.state.layers.isSnappingActive = true;
}
else {
this.renderEmptyComponent();
this.state.layers.isSnappingActive = false;
}
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() {
// Editable demo layers should only be available if the user is currently on the matching demo instance and is logged in
this.editableLayersList = Object.values(DEMO_LAYERS).filter((layer) => {
try {
const oapifUrl = new URL(layer.url);
const themesUrl = new URL(this.context.configManager.Config.themes.url);
return oapifUrl.hostname === themesUrl.hostname && this.state.oauth.status === 'loggedIn';
}
catch {
// Cannot parse this.configManager.Config.themes.url as URL.
// TODO : This should be changed when editing is not just a demo any more
return false;
}
});
void this.loadDemoServerConfig();
this.render();
}
async onSelectLayer(evt) {
const layerId = evt.target?.value;
this.layer = this.editableLayersList.find((layer) => layer.collectionId === layerId);
this.removeMapInteractions();
this.unsetEditFeature();
if (this.layer) {
this.featureSchema = await this.context.ogcApiFeaturesManager.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.context.ogcApiFeaturesManager.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.context.ogcApiFeaturesManager.createItem(this.layer, featureToSave);
}
else {
featureToSave.setId(id);
await this.context.ogcApiFeaturesManager.updateItem(this.layer, id, featureToSave);
}
this.unsetEditFeature();
this.refreshDemoMapLayer();
this.startSelectionMode();
}
async deleteFeature(featureId) {
await this.context.ogcApiFeaturesManager.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.context.ogcApiFeaturesManager.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.isPanelVisible = 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.
*/
async loadDemoServerConfig() {
for (const layer of this.editableLayersList) {
if (!this.state.ogcServers[layer.server.name]) {
this.state.ogcServers[layer.server.name] = layer.server;
await this.context.ogcApiFeaturesManager.getServer(layer.server);
// A demo layer is defined either by its collection id or title. In the case of the title,
// the id is requested from the server and stored in the layer definition.
if (!layer.collectionId) {
const collection = await this.context.ogcApiFeaturesManager.getCollectionByTitle(layer.collectionTitle, layer.server);
if (collection?.title) {
layer.collectionId = collection.id;
}
}
}
}
}
connectedCallback() {
super.connectedCallback();
this.subscribe('oauth.status', () => this.loginStateChanged());
// Add ogc servers to state
this.subscribe('application.isReady', () => {
if (this.state.application.isReady) {
this.loginStateChanged();
}
});
this.render();
}
}