@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
427 lines (426 loc) • 22.6 kB
JavaScript
import { html as uHtml } from 'uhtml';
import { getCenter } from 'ol/extent';
import GirafeDraggableElement from '../../base/GirafeDraggableElement';
import { debounce } from '../../tools/utils/debounce';
import FeatureToGridDataById from '../../tools/featuretogriddatabyid';
import { getValidIndex } from '../../tools/utils/utils';
import IconCenter from './images/center.svg';
import ResizeWindow from '../../tools/resizewindow';
import DOMPurify from 'dompurify';
import CsvManager from '../../tools/export/csvmanager';
import { getColumnAlias } from '../../tools/utils/aliases';
import I18nManager from '../../tools/i18n/i18nmanager';
/**
* Represents a draggable and resizable selection window component.
* Display itself when it should be visible and have selected features.
* To be visible, it has to be the defined selectionComponent.
*/
class SelectionWindowComponent extends GirafeDraggableElement {
constructor() {
super('selectionwindow');
Object.defineProperty(this, "template", {
enumerable: true,
configurable: true,
writable: true,
value: () => {
return uHtml `<style>
*{font-family:Arial,sans-serif}.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}.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>
.girafe-resizer{--resize-size:6px;--negative-resize-size:-6px}button.girafe-resizer{background-color:#0000;border:none;position:absolute}.girafe-resizer.corner{width:var(--resize-size);height:var(--resize-size)}.girafe-resizer.top-bottom{width:calc(100% - (2*var(--resize-size)));height:var(--resize-size)}.girafe-resizer.left-right{width:var(--resize-size);height:calc(100% - (2*var(--resize-size)))}.girafe-resizer.tl:hover,.girafe-resizer.br:hover{cursor:nw-resize}.girafe-resizer.tr:hover,.girafe-resizer.bl:hover{cursor:ne-resize}.girafe-resizer.top-bottom:hover{cursor:n-resize}.girafe-resizer.left-right:hover{cursor:e-resize}.girafe-resizer.tl{top:var(--negative-resize-size);left:var(--negative-resize-size)}.girafe-resizer.t{top:var(--negative-resize-size);left:var(--resize-size)}.girafe-resizer.tr{top:var(--negative-resize-size);right:var(--negative-resize-size)}.girafe-resizer.r{top:var(--resize-size);right:var(--negative-resize-size)}.girafe-resizer.br{bottom:var(--negative-resize-size);right:var(--negative-resize-size)}.girafe-resizer.b{bottom:var(--negative-resize-size);left:var(--resize-size)}.girafe-resizer.bl{bottom:var(--negative-resize-size);left:var(--negative-resize-size)}.girafe-resizer.l{top:var(--resize-size);left:var(--negative-resize-size)}.girafe-draggable-window{--window-header-height:2rem;--window-footer-height:2rem;border:solid 1px var(--text-color-grad1);box-shadow:var(--bx-shdw);background:var(--bkg-color);border-radius:3px;width:100%;height:100%}.girafe-draggable-window #header{height:var(--window-header-height);line-height:var(--window-header-height);cursor:move;z-index:10;background-color:var(--bkg-color-grad2);color:var(--text-color);text-align:center;padding:0 .5rem}.girafe-draggable-window #close{color:var(--text-color);cursor:pointer;background-color:#0000;border:none;width:1rem;height:1rem;margin:.5rem;padding:0;line-height:1rem;position:absolute;top:0;right:0}.girafe-draggable-window #close i:before{content:"uf00d"}.girafe-draggable-window #close:hover{color:#000;border-color:#000}.girafe-draggable-window #content{width:100%;height:calc(100% - (var(--window-header-height) + var(--window-footer-height)));color:var(--text-color);overflow-y:auto}.girafe-draggable-window #footer{height:var(--window-footer-height);color:var(--text-color-grad1);border-top:solid 1px var(--text-color-grad1);justify-content:space-around;display:flex}
</style><style>
#content div{padding:1rem 2rem}table{border-collapse:collapse;width:100%}td.label{text-align:right;color:var(--text-color-grad1);vertical-align:top;width:8rem;padding-right:1rem}td.label:after{content:" :"}button{background-color:unset;color:var(--text-color-grad1);cursor:pointer;border:none;flex-grow:1;padding:.5rem}button>img{max-height:calc(var(--window-header-height)/2)}#previous i{float:left}#next i{float:right}#tools{justify-content:space-around;display:flex}#counter{line-height:var(--window-footer-height);height:var(--window-footer-height);text-align:center;margin-top:0}#layers-dropdown{background-color:var(--bkg-color);border:solid 1px var(--bkg-color-grad2);flex-direction:column;align-items:center;padding:.5rem 0;display:flex;position:absolute;bottom:2rem}option.layers-dropdown-item{cursor:pointer;padding:.1rem .5rem}option.layers-dropdown-item:hover{background-color:var(--bkg-color-grad1)}
</style>
<div id="draggable" class="${this.visible ? 'girafe-draggable-window' : 'hidden'}">
<button tabindex="-1" class="girafe-resizer tl corner"></button>
<button tabindex="-1" class="girafe-resizer t top-bottom"></button>
<button tabindex="-1" class="girafe-resizer tr corner"></button>
<button tabindex="-1" class="girafe-resizer r left-right"></button>
<button tabindex="-1" class="girafe-resizer br corner"></button>
<button tabindex="-1" class="girafe-resizer b top-bottom"></button>
<button tabindex="-1" class="girafe-resizer bl corner"></button>
<button tabindex="-1" class="girafe-resizer l left-right"></button>
<div id="header">
<span i18n="${this.getWindowFeature()?.id}"></span>
<img id="close" alt="close-icon" src="icons/close.svg" />
</div>
<div id="content">
<div>
<table>
<tr class="hidden">
<th i18n="Label">Label</th>
<th i18n="Value">Value</th>
</tr>
${this.displayedProperties.map((keyValue) => uHtml `
<tr>
<td class="label" i18n="${keyValue[0]}"></td>
<td class="value">${this.htmlUnsafe(keyValue[1])}</td>
</tr>
`)}
</table>
</div>
</div>
<div id="footer">
<button
id="previous"
class="${this.maxIndex > 0 ? '' : 'hidden'}"
onclick="${() => this.onFocusWindowFeature(this.focusedIndex - 1)}">
<img alt="previous-icon" src="icons/previous.svg" />
</button>
<div id="counter" class="${this.maxIndex > 0 ? '' : 'hidden'}">
<span class="${this.maxIndex > 0 ? '' : 'hidden'}">
<span>${this.focusedIndex + 1}</span>
<span>/</span>
<span>${this.maxIndex + 1}</span>
</span>
</div>
<div class="tools">
<button onclick="${() => this.recenter()}">
<img alt="recenter-icon" src="${this.iconCenter}" />
</button>
<button onclick="${() => this.openDropdown()}"><img alt="csv-icon" src="icons/csv.svg" /></button>
<div ?hidden="${!this.showDropdown}">
<div id="layers-dropdown">
${this.getLayersList().map((layer) => uHtml `
<option
class="layers-dropdown-item"
value="${layer.id}"
onclick="${() => this.generateCSV(layer.id)}"
onkeydown="${() => this.generateCSV(layer.id)}"
tabindex="0"
i18n="${layer.label}"></option>
`)}
</div>
</div>
</div>
<button
id="next"
class="${this.maxIndex > 0 ? '' : 'hidden'}"
onclick="${() => this.onFocusWindowFeature(this.focusedIndex + 1)}">
<img alt="next-icon" src="icons/next.svg" />
</button>
</div>
</div>
`;
}
});
Object.defineProperty(this, "eventsCallbacks", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "isVisibleComponentSetup", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
Object.defineProperty(this, "debounceOnFeaturesSelected", {
enumerable: true,
configurable: true,
writable: true,
value: debounce(this.onFeaturesSelected.bind(this), 200)
});
Object.defineProperty(this, "resizeWindow", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
Object.defineProperty(this, "featureToGridData", {
enumerable: true,
configurable: true,
writable: true,
value: new FeatureToGridDataById({ removeEmptyColumns: false })
});
Object.defineProperty(this, "windowFeatures", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "visible", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
Object.defineProperty(this, "focusedIndex", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "maxIndex", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "iconCenter", {
enumerable: true,
configurable: true,
writable: true,
value: IconCenter
});
Object.defineProperty(this, "csvManager", {
enumerable: true,
configurable: true,
writable: true,
value: CsvManager.getInstance()
});
Object.defineProperty(this, "displayedProperties", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "showDropdown", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
}
connectedCallback() {
this.render();
this.registerVisibilityEvents();
}
/**
* Render the component regarding its visibility.
*/
render() {
if (this.visible) {
this.renderComponent();
}
else {
this.renderEmptyComponent();
}
}
/**
* @returns The WindowFeature at the currently focused index.
*/
getWindowFeature() {
return this.windowFeatures[this.focusedIndex];
}
/**
* Recenter the map view based on the current feature.
*/
recenter() {
const windowFeature = this.getWindowFeature();
const extent = windowFeature?.feature?.getGeometry()?.getExtent();
if (!extent) {
console.error('Invalid feature to recenter on.');
return;
}
this.state.position.center = getCenter(extent);
}
/**
* Toggles the visibility of the layers dropdown.
*/
openDropdown() {
this.showDropdown = !this.showDropdown;
this.render();
}
/**
* Gets the list of layers to export.
* @returns The list of layers to export.
*/
getLayersList() {
const layers = [];
this.windowFeatures.forEach((feature) => {
if (!layers.some((layer) => layer.id === feature.id)) {
const label = `Export ${feature.id}`;
layers.push({ id: feature.id, label });
}
});
return layers;
}
/**
* Generates a CSV file with the properties of the currently focused feature.
* @param layer The layer to export.
*/
generateCSV(layer) {
// Only data from the selected layer
const data = [];
this.windowFeatures.forEach((feature) => {
if (feature.id === layer) {
data.push(feature.notOlProperties);
}
});
// Ignore undefined values
data.forEach((entry) => this.ignoreUndefinedValues(entry));
// Get the columns
const columns = Object.keys(data[0]).map((column) => {
return { name: column };
});
this.csvManager.startDownload(data, columns, 'query-results.csv');
this.showDropdown = false;
this.render();
}
/**
* Ignores undefined values in the data.
*/
ignoreUndefinedValues(data) {
Object.keys(data).forEach((key) => {
if (data[key] === undefined) {
delete data[key];
}
});
}
/**
* Closes the window and deselect the selected features.
*/
closeWindow() {
this.visible = false;
this.state.interface.selectionComponentVisible = false; // Will render it again.
this.state.selection.focusedFeatures = null;
this.state.selection.selectedFeatures = [];
}
/**
* Sets the focus on a specific feature.
*/
onFocusWindowFeature(index) {
const windowFeature = this.selectedWindowFeature(index);
this.state.selection.focusedFeatures = [windowFeature.feature];
// Get content.
this.displayedProperties = Object.entries(windowFeature.notOlProperties).filter((keyValue) => {
return keyValue[1] !== undefined;
});
this.displayedProperties.forEach((keyValue) => {
let config = {};
if (this.configManager.Config.query.legacy) {
config = {
ADD_ATTR: ['onclick'],
ADD_URI_SAFE_ATTR: ['onclick']
};
}
keyValue[0] = I18nManager.getInstance().getTranslation(getColumnAlias(windowFeature.id, keyValue[0]));
keyValue[1] = DOMPurify.sanitize(keyValue[1], config);
});
// Render and translate data.
this.render();
super.girafeTranslate();
}
/**
* Renders the component by calling the necessary methods.
* @private
*/
renderComponent() {
super.render();
if (!this.isVisibleComponentSetup) {
this.setupVisibleComponent();
}
super.girafeTranslate();
}
/**
* Sets up the components state and side-kicks.
* This must be called once at the first (visible) rendering.
* @private
*/
setupVisibleComponent() {
this.isVisibleComponentSetup = true;
this.resizeWindow = new ResizeWindow(this.shadow);
this.makeDraggable();
this.registerEvents();
}
/**
* Render a placeholder, not visible component on hide.
* Removes event registration.
* @private
*/
renderEmptyComponent() {
this.resizeWindow?.destroy();
this.resizeWindow = null;
this.unsubscribe(this.eventsCallbacks);
this.eventsCallbacks.length = 0;
this.isVisibleComponentSetup = false;
this.renderEmpty();
}
/**
* Event about visibility that must be always listened by this component, even hidden.
* @private
*/
registerVisibilityEvents() {
this.subscribe('interface.selectionComponentVisible', (_oldValue, newValue) => this.togglePanel(newValue));
}
/**
* Listen events that must be listened if the component is visible.
* @private
*/
registerEvents() {
this.eventsCallbacks.push(this.subscribe('selection.selectedFeatures', (_oldFeatures, newFeatures) => {
// Use debounce to avoid quicly closing the grid on selection change.
this.debounceOnFeaturesSelected(newFeatures);
}));
}
/**
* Sets the selected features in the window and updates the window state to display the first feature.
* @private
*/
onFeaturesSelected(features) {
if (!features?.length) {
this.closeWindow();
return;
}
this.windowFeatures = SelectionWindowComponent.createWindowFeatures(this.featureToGridData.toGridDataById(features ?? []));
if (!this.windowFeatures.length) {
this.closeWindow();
return;
}
this.maxIndex = this.windowFeatures.length - 1;
this.onFocusWindowFeature(0);
}
/**
* Selects a window feature by its first valid index.
* Out of bound index loops back to the first valid index.
* @returns The selected window feature.
* @private
*/
selectedWindowFeature(index) {
this.focusedIndex = getValidIndex(index, this.maxIndex);
return this.getWindowFeature();
}
/**
* Toggles the panel visibility. If visible, tries to display a grid with selected feature.
* Can only be visible if the component is the wanted selection component.
* @private
*/
togglePanel(visible) {
if (this.state.interface.selectionComponent !== 'window') {
if (!this.visible) {
return;
}
visible = false;
}
this.visible = visible;
if (visible) {
// Will be rendered after computing selected feature.
this.onFeaturesSelected(this.state.selection.selectedFeatures);
}
else {
this.render();
}
}
/**
* Creates an array of WindowFeature objects based on the provided GridDataById object.
* Using gridDataById orders by feature id the WindowFeatures.
* @returns An array of WindowFeature objects.
* @static
*/
static createWindowFeatures(gridDataById) {
const windowFeatures = [];
Object.keys(gridDataById).forEach((id) => {
const gridData = gridDataById[id];
gridData.features.forEach((feature, index) => {
windowFeatures.push({
id,
feature,
notOlProperties: gridData.notOlProperties[index]
});
});
});
return windowFeatures;
}
}
export default SelectionWindowComponent;