UNPKG

@geogirafe/lib-geoportal

Version:

GeoGirafe is a flexible application to build online geoportals.

657 lines (656 loc) • 41 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { html as uHtml } from 'uhtml'; // SPDX-License-Identifier: Apache-2.0 import Collection from 'ol/Collection.js'; import tippy from 'tippy.js'; import VectorSource from 'ol/source/Vector.js'; import VectorLayer from 'ol/layer/Vector.js'; import { Fill, Icon, Stroke, Style } from 'ol/style.js'; import { containsExtent, getCenter } from 'ol/extent.js'; import GirafeColorPicker from '../../tools/utils/girafecolorpicker.js'; import PinIcon from './images/pin.svg'; import LayerIcon from './images/layer.svg'; import LayerGroupIcon from './images/layergroup.svg'; import SearchIcon from './images/search.svg'; import PaintbrushIcon from './images/paintbrush.svg'; import GirafeHTMLElement from '../../base/GirafeHTMLElement.js'; import { UsedInTemplateOnly } from '../../decorators.js'; import { SEARCH_GROUP_DEFAULT, SEARCH_PROVIDER_DEFAULT } from '../../tools/search/abstractsearchclient.js'; class SearchComponent extends GirafeHTMLElement { templateUrl = null; styleUrls = null; template = () => { return uHtml `<style> .picker_wrapper.no_alpha .picker_alpha{display:none}.picker_wrapper.no_editor .picker_editor{z-index:-1;opacity:0;position:absolute}.picker_wrapper.no_cancel .picker_cancel{display:none}.layout_default.picker_wrapper{flex-flow:wrap;justify-content:space-between;align-items:stretch;width:25em;padding:.5em;font-size:10px;display:flex}.layout_default.picker_wrapper input,.layout_default.picker_wrapper button{font-size:1rem}.layout_default.picker_wrapper>*{margin:.5em}.layout_default.picker_wrapper:before{content:"";order:1;width:100%;height:0;display:block}.layout_default .picker_slider,.layout_default .picker_selector{padding:1em}.layout_default .picker_hue{width:100%}.layout_default .picker_sl{flex:auto}.layout_default .picker_sl:before{content:"";padding-bottom:100%;display:block}.layout_default .picker_editor{order:1;width:6.5rem}.layout_default .picker_editor input{width:100%;height:100%}.layout_default .picker_sample{flex:auto;order:1}.layout_default .picker_done,.layout_default .picker_cancel{order:1}.picker_wrapper{box-sizing:border-box;cursor:default;color:#444;pointer-events:auto;background:#f2f2f2;font-family:sans-serif;box-shadow:0 0 0 1px silver}.picker_wrapper:focus{outline:none}.picker_wrapper button,.picker_wrapper input{box-sizing:border-box;border:none;outline:none;box-shadow:0 0 0 1px silver}.picker_wrapper button:focus,.picker_wrapper button:active,.picker_wrapper input:focus,.picker_wrapper input:active{box-shadow:0 0 2px 1px #1e90ff}.picker_wrapper button{cursor:pointer;background-color:#f5f5f5;background-image:linear-gradient(#0000,#dcdcdc);padding:.4em .6em}.picker_wrapper button:active{background-image:linear-gradient(#dcdcdc,#0000)}.picker_wrapper button:hover{background-color:#fff}.picker_selector{z-index:1;cursor:pointer;background:currentColor;border:2px solid #fff;border-radius:100%;display:block;position:absolute;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);box-shadow:0 0 3px 1px #67b9ff}.picker_slider .picker_selector{border-radius:2px}.picker_hue{background-image:linear-gradient(90deg,red,#ff0,#0f0,#0ff,#00f,#f0f,red);position:relative;box-shadow:0 0 0 1px silver}.picker_sl{background-image:linear-gradient(#fff,#fff0 50%),linear-gradient(#0000 50%,#000),linear-gradient(90deg,gray,#80808000);position:relative;box-shadow:0 0 0 1px silver}.picker_alpha,.picker_sample{background:linear-gradient(45deg,#d3d3d3 25%,#0000 25% 75%,#d3d3d3 75%) 0 0/2em 2em,linear-gradient(45deg,#d3d3d3 25%,#fff 25% 75%,#d3d3d3 75%) 1em 1em/2em 2em;position:relative;box-shadow:0 0 0 1px silver}.picker_alpha .picker_selector,.picker_sample .picker_selector{background:0 0}.picker_editor input{padding:.2em .4em;font-family:monospace}.picker_sample:before{content:"";background:currentColor;width:100%;height:100%;display:block;position:absolute}.picker_arrow{z-index:-1;position:absolute}.picker_wrapper.popup{z-index:2;margin:1.5em;position:absolute}.picker_wrapper.popup,.picker_wrapper.popup .picker_arrow:before,.picker_wrapper.popup .picker_arrow:after{background:#f2f2f2;box-shadow:0 0 10px 1px #0006}.picker_wrapper.popup .picker_arrow{width:3em;height:3em;margin:0}.picker_wrapper.popup .picker_arrow:before,.picker_wrapper.popup .picker_arrow:after{content:"";z-index:-99;display:block;position:absolute;top:0;left:0}.picker_wrapper.popup .picker_arrow:before{-webkit-transform-origin:0 100%;transform-origin:0 100%;width:100%;height:100%;-webkit-transform:skew(45deg);transform:skew(45deg)}.picker_wrapper.popup .picker_arrow:after{width:150%;height:150%;box-shadow:none}.popup.popup_top{bottom:100%;left:0}.popup.popup_top .picker_arrow{bottom:0;left:0;-webkit-transform:rotate(-90deg);transform:rotate(-90deg)}.popup.popup_bottom{top:100%;left:0}.popup.popup_bottom .picker_arrow{top:0;left:0;-webkit-transform:rotate(90deg)scaleY(-1);transform:rotate(90deg)scaleY(-1)}.popup.popup_left{top:0;right:100%}.popup.popup_left .picker_arrow{top:0;right:0;-webkit-transform:scaleX(-1);transform:scaleX(-1)}.popup.popup_right{top:0;left:100%}.popup.popup_right .picker_arrow{top:0;left:0} </style><style> .picker_wrapper,.picker_arrow:after,.picker_arrow:before{background-color:var(--bkg-color)!important}.picker_wrapper,.picker_arrow:before{box-shadow:0 0 10px 1px var(--text-color-grad1)!important}.picker_wrapper.fixedPosition{transform:translate(-260px)}.picker_arrow.fixedPosition{transform:translate(200px)rotate(90deg)scaleX(-1)!important} </style><style> .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}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);cursor:pointer;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)!important;color:var(--text-color)!important}.girafe-onboarding-theme button{background-color:var(--bkg-color)!important;color:var(--text-color)!important;text-shadow:none!important}.girafe-onboarding-theme button.driver-popover-close-btn{z-index:10000}.tippy-box{background-color:var(--bkg-color)!important;border:var(--app-standard-border)!important}.tippy-content{color:var(--text-color)!important}.tippy-arrow{color:var(--bkg-color)!important}.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)!important;& div.tippy-content{background-color:var(--bkg-color)!important;& img{max-width:20rem;max-height:20rem}}& div.tippy-arrow{color:var(--bkg-color)!important}} </style><style> .hidden{display:none}#searchbox{background-color:var(--bkg-color);border:1px solid #cfd6dd;border-radius:4px;flex-direction:row;align-items:center;width:100%;min-width:0;height:2.25rem;display:flex;& slot[name=search-tooltip]{display:none}}#search-filter{flex:none;min-width:0}#search{-webkit-appearance:none;width:auto;height:2.25rem;color:var(--text-color);background:0 0;border:0;outline:none;-webkit-flex:auto;-ms-flex:auto;flex:auto;margin:0 0 0 .25rem;padding-left:.25rem;font-size:1rem}.search-icon,.close-icon,.theme-icon,.select-color-icon{width:14px;color:var(--text-color);padding:0 .75rem}.close-button,.select-color-button{cursor:pointer;background-color:#0000;border:none;padding:0}#results{z-index:1000;background-color:var(--bkg-color);scrollbar-width:thin;border:var(--app-standard-border);border-radius:4px;width:min(36rem,50vw);max-height:31rem;margin-top:.1rem;margin-bottom:.5rem;position:absolute;top:3.5rem;overflow-x:hidden}.entry{width:34rem;color:var(--text-color);padding:.3rem 1rem;line-height:1.3rem;display:inline-block}.entry img{width:.8em;margin-right:1rem}.entry span{text-transform:uppercase}.provider,.group{font-size:1.2rem;font-weight:600;line-height:3rem}.provider{background-color:color-mix(in srgb, var(--bkg-color-grad1) 75%, transparent);margin-top:1rem;font-size:1.5rem}#results>.provider:first-child{margin-top:0}.result{background:0 0;border-top:1px solid #ccc;align-items:stretch;width:100%;padding:0;display:flex}.result button{cursor:pointer;text-align:left;width:100%;color:var(--text-color);background:0 0;border:none;padding:.3rem 1rem}.result.selected,.result button:hover{color:var(--text-color);background-color:var(--bkg-color-grad2)!important}.result .tools{width:1.3rem;margin:0}.result .tools button{height:-webkit-fill-available;margin:0;padding:0 .3rem}.result .tools button img{margin:0;padding:0}#no-result{background:var(--warning-color);opacity:.75;visibility:hidden;pointer-events:none;border-radius:6px;width:fit-content;margin:auto;padding:.5rem 0;font-size:1rem;position:absolute;top:3.5rem;left:0;right:0}#no-result>span{padding:1.3rem}@keyframes fadeOut{0%{opacity:1}80%{opacity:1}to{opacity:0}}.shown-then-fadeout{animation:2s ease-in-out forwards fadeOut;visibility:visible!important} </style> <style>${this.customStyle}</style> <div id="searchbox"><slot name="search-tooltip"></slot><girafe-search-filter id="search-filter"></girafe-search-filter><input id="search" class="gg-input" length="20" maxlength="1000" autocomplete="off" autocorrect="off" i18n="Search..." placeholder="Search..." aria-label="Search" oninput="${(e) => this.doSearchDebounced(e)}" onfocusin="${() => this.onFocusIn()}" onfocusout="${() => this.onFocusOut()}" onkeydown="${(e) => this.onKeyDown(e)}"> <img class="${this.allResults.length > 0 ? 'hidden' : 'search-icon'}" alt="search-icon" src="${this.searchIcon}"> <button class="${this.allResults.length > 0 ? 'close-button' : 'hidden'}" onclick="${() => this.clearSearch(true)}"><img class="close-icon" alt="close-icon" src="icons/close.svg"></button> <button tip="change_search_result_color" id="colorPickerBtn" class="${this.paintSearchResults ? 'select-color-button' : 'hidden'}"><img class="select-color-icon" alt="select-color-icon" src="${this.paintbrushIcon}"></button><div id="results" class="${!this.allResults.length || this.forceHide ? 'hidden' : ''}" onmousemove="${() => this.onMouseMove()}">${(Object.keys(this.groupedResults) ?? []).map(provider => uHtml `<div class="${this.getProviderClass(provider)}"><img alt="provider icon" src="${this.searchIcon}"> <span i18n="${provider}">${provider}</span></div>${(Object.keys(this.groupedResults[provider]) ?? []).map(group => uHtml `<div class="${this.getGroupClass(group)}"><img alt="result icon" src="${this.getGroupIcon(group)}"> <span i18n="${group}">${group}</span></div>${(this.groupedResults[provider][group] ?? []).map(result => uHtml `<div class="${result.get('selected') ? 'result entry selected' : 'result entry'}"><button onmouseover="${() => this.onMouseOver(result)}" onmouseleave="${() => this.onMouseLeave()}" onmousedown="${() => this.onMouseDown()}" onclick="${() => this.onSelect(result)}">${this.getLabel(result)}</button><div class="${this.isFeatureActionThemeRelated(result) ? 'tools' : 'hidden'}"><button class="addFullTree" onclick="${() => this.addFullThemeIfNotPresent(result)}"><img class="theme-icon" alt="theme-icon" src="icons/theme-checked.svg" tip="Complete the theme"></button></div></div>`)} `)} `)}</div><div id="no-result" class="${this.showNoResultWarning ? 'shown-then-fadeout' : ''}"><span i18n="${'No match found'}"></span></div></div> ${this.htmlUnsafe(this.feedbackTemplateHtml ?? '')}`; }; searchIcon = SearchIcon; paintbrushIcon = PaintbrushIcon; get map() { return this.context.mapManager.getMap(); } previewFeaturesCollection = new Collection(); previewLayers; previewGeoLayer = null; ignoreBlur = false; groupedResults = {}; allResults = []; forceHide = true; focusedResultIndex = -1; focusedResult = null; selectedResult = null; searchInput; activeSearchFilter = null; girafeColorPicker; paintSearchResults; defaultSearchStrokeColor; defaultSearchFillColor; searchStrokeColor; searchFillColor; showNoResultWarning = false; tooltipInstance = null; // Keeping track of the last input timeout ongoingSearchTimeoutId = 0; constructor() { super('search'); } async initialSearch() { const searchTerm = this.context.permalinkManager.getSearchTerm(); const results = await this.context.searchManager.doSearch(searchTerm); if (results !== null) { // Apply the first search result in the list const firstResults = this.flattenResultList(results); if (firstResults.length) { this.preview(firstResults[0]); this.onSelect(firstResults[0]); } } } createPreviewLayer() { this.paintSearchResults = this.context.configManager.Config.search?.paintSearchResults; this.previewGeoLayer = new VectorLayer({ properties: { addToPrintedLayers: true }, source: new VectorSource({ features: this.previewFeaturesCollection }) }); this.updatePreviewLayerStyle(this.defaultSearchFillColor, this.defaultSearchStrokeColor); this.map.addLayer(this.previewGeoLayer); this.previewGeoLayer.setZIndex(1010); this.initColorPicker(); } toggleVisibility(visible) { (this.shadowRoot?.host).style.display = visible ? 'flex' : 'none'; } onMouseDown() { this.ignoreBlur = true; } onFocusIn() { this.forceHide = false; super.render(); } onFocusOut() { if (!this.ignoreBlur) { this.forceHide = true; super.render(); } this.ignoreBlur = false; } render() { super.render(); this.searchInput = this.shadowRoot?.getElementById('search'); } registerEvents() { this.subscribe('interface.searchComponentVisible', (_oldValue, newValue) => this.toggleVisibility(newValue)); this.subscribe('interface.searchFilterComponentVisible', (_oldValue, isVisible) => { if (isVisible) { this.forceHide = true; this.refreshRender(); } else { this.searchInput.dispatchEvent(new Event('input')); } }); this.subscribe('search.filter', (_oldValue, newValue) => { this.activeSearchFilter = newValue; // Remove any shortcuts from the search term as soon as the related filter is applied this.sanitizeSearchTerm(this.searchInput?.value ?? ''); this.searchInput.dispatchEvent(new Event('input')); }); this.subscribe('language', () => { this.context.i18nManager.ensureTranslationLoaded().then(() => { this.tooltipInstance?.setContent(this.createToolTipContent()); }); }); } connectedCallback() { super.connectedCallback(); this.defaultSearchStrokeColor = this.context.configManager.Config.search?.defaultStrokeColor; this.defaultSearchFillColor = this.context.configManager.Config.search?.defaultFillColor; this.createPreviewLayer(); this.render(); super.girafeTranslate(); this.registerEvents(); this.context.i18nManager.ensureTranslationLoaded().then((loaded) => { if (loaded) { this.createTooltip(); } else { console.debug('Translations not loaded'); } }); if (this.context.permalinkManager.hasSearch()) { this.subscribe('application.isReady', () => { if (this.state.application.isReady) { void this.initialSearch(); } }); } } flattenResultList(results) { results ??= this.groupedResults; return Object.values(results).flatMap((providerResults) => Object.values(providerResults).flat()); } clearSearch(purge = false) { if (purge) { if (this.searchInput) { this.searchInput.value = ''; } } this.forceHide = this.state.interface.searchFilterComponentVisible; this.groupedResults = {}; this.allResults = []; this.clearPreview(); this.focusedResultIndex = -1; this.focusedResult = null; this.closeToolTip(); super.render(); } async doSearch(e) { this.showNoResultWarning = false; this.context.searchManager.abortSearch(); this.clearSearch(); const target = e.target; const term = this.processSearchFilterShortcut(target.value); if (term.trim().length > 0) { try { const features = await this.context.searchManager.doSearch(term, this.activeSearchFilter); // Check if a search was performed at all (min term length!) if (features !== null) { this.groupedResults = features; this.allResults = this.flattenResultList(); if (!this.allResults.length) { // If the search did not yield any results, a warning // box is displayed for 2 seconds and then fades out (CSS) this.showNoResultWarning = true; } } // And then rerender the results super.render(); super.girafeTranslate(); } catch (error) { if (error instanceof DOMException && error.name === 'AbortError') { // Request was aborted, ignore the error console.debug('Multiple parallel search: previous request was aborted.'); return; } } } } /** * Debounce the fetch call to API to prevent sending request at every stroke. * @param e */ async doSearchDebounced(e) { if (this.ongoingSearchTimeoutId !== 0) { clearTimeout(this.ongoingSearchTimeoutId); } // The original even cannot be passed because event objects are ephemeral and // not designed to be used asynchronously (the target property would be undefined) const syntheticEvent = { target: { value: e.target && 'value' in e.target ? e.target.value : undefined } }; this.ongoingSearchTimeoutId = window.setTimeout(() => { this.ongoingSearchTimeoutId = 0; this.doSearch(syntheticEvent); }, 300); } /** * Detects manually entered filter shortcuts and sanitizes the search term. */ processSearchFilterShortcut(term) { const shortcutDetected = this.context.searchManager.detectSearchFilterShortcut(term); if (shortcutDetected) { // If a complete shortcut was detected and saved to the state, sanitize the search term if (this.state.search.filterShortcut) { return this.sanitizeSearchTerm(term); } else { // No complete shortcut detected yet, wait for next input return ''; } } return term; } sanitizeSearchTerm(term) { const prefix = this.context.stateManager.state.search.filterShortcutPrefix ?? ''; const shortcut = this.context.stateManager.state.search.filterShortcut ?? ''; const sanitizedSearchTerm = term.replace(`${prefix}${shortcut}`, '').trimStart(); this.searchInput.value = sanitizedSearchTerm; this.searchInput.focus(); return sanitizedSearchTerm; } addFullThemeIfNotPresent(feature) { this.clearPreview(); const action = this.getFeatureFirstAction(feature); if (!action) { return; } const layer = this.context.themesHelper.findLayerByName(action.data); if (!layer) { return; } const theme = this.context.themesHelper.getOriginalTheme(layer); if (!theme) { return; } const added = this.context.themesHelper.addThemeIfNotPresent(theme); if (!added) { // If it's not added because it's already in the tree, complete the theme. this.context.themesHelper.completeTheme(theme); } const insertedLayer = this.context.themesHelper.findBaseLayerRecursiveById(this.state.layers.layersList, layer.id); if (insertedLayer) { insertedLayer.activeState = 'on'; } this.closeDropdown(feature); this.onFocusOut(); this.updateSearchboxWithResult(feature); } getGroupIcon(searchGroup) { switch (searchGroup) { case 'Group': return LayerGroupIcon; case 'Layer': return LayerIcon; default: return PinIcon; } } getProviderClass(provider) { if (Object.keys(this.groupedResults).length === 1 || provider === SEARCH_PROVIDER_DEFAULT) { return 'hidden'; } return 'provider entry'; } getGroupClass(group) { if (group === SEARCH_GROUP_DEFAULT) { return 'hidden'; } return 'group entry'; } getLabel(result) { return result.get('label_html') ? this.htmlUnsafe(result.get('label_html')) : result.get('label'); } isFeatureActionThemeRelated(feature) { const action = this.getFeatureFirstAction(feature); const kind = action?.action; const hasThemeRelatedAction = kind?.startsWith('add_layer') || kind?.startsWith('add_group') || kind?.startsWith('add_theme') || false; if (!hasThemeRelatedAction || !action) { return false; } const layer = this.context.themesHelper.findLayerByName(action.data); return !!layer; } onMouseOver(result) { this.focusResult(result); } onMouseLeave() { // Clear preview search result, only if the result was not selected if (this.selectedResult === null) { this.clearPreview(); } } focusResultFromIndex() { const result = this.allResults[this.focusedResultIndex]; this.focusResult(result); } focusResult(result) { // Clear old selection and preview this.clearPreview(); if (this.focusedResult) { this.focusedResult.set('selected', false); } // Set the newly selected object and activate a preview. this.focusedResultIndex = this.allResults.indexOf(result); this.focusedResult = this.allResults[this.focusedResultIndex]; this.focusedResult.set('selected', true); this.render(); this.preview(result); // Scroll to selected div const resultHtmlElement = this.shadow.querySelectorAll('.result')[this.focusedResultIndex]; resultHtmlElement.scrollIntoView({ block: 'nearest' }); } preview(result) { if (result.getGeometry() && this.context.configManager.Config.search?.objectPreview) { // Result with geometry this.addFeatureToPreview(result); this.updatePreviewLayerStyle(); } const firstAction = this.getFeatureFirstAction(result); if (firstAction?.action.startsWith('add_layer') && this.context.configManager.Config.search?.layerPreview) { const layer = this.context.themesHelper.findLayerByName(firstAction.data); if (layer) { const clonedTheme = this.context.themesHelper.getMinimalClonedThemeForLayer(layer); clonedTheme.isExpanded = true; this.previewLayers = this.context.themesHelper.mergeThemeInLayerTree(clonedTheme, true); } else { console.error(`Layer ${firstAction.data} cannot be found`); } } } addFeatureToPreview(feature) { this.previewFeaturesCollection.push(feature); } clearPreview() { // Clear preview search result this.previewFeaturesCollection.clear(); // Clear preview layer if (this.previewLayers) { this.context.themesHelper.removeLayersFromLayerTree(this.previewLayers.insertedLayers); for (const layer of this.previewLayers.activatedLayers) { this.context.layerManager.toggle(layer, 'off'); } this.previewLayers = undefined; } } onSelect(feature) { this.closeDropdown(feature); // If the result has a specific zoom-to extent defined or contains a geometry, zoom to it const zoomBbox = this.context.searchManager.getZoomToBbox(feature); if (zoomBbox) { this.zoomTo(zoomBbox); } else { this.addResultToTreeView(feature); } this.onFocusOut(); this.updateSearchboxWithResult(feature); } closeDropdown(feature) { this.selectedResult = feature; this.ignoreBlur = false; this.forceHide = true; this.previewLayers = undefined; super.render(); } updateSearchboxWithResult(feature) { if (this.searchInput && feature.get('label')) { this.searchInput.value = feature.get('label'); } } getFeatureFirstAction(feature) { const actions = feature.get('actions'); return actions?.length ? actions[0] : undefined; } addResultToTreeView(feature) { const action = this.getFeatureFirstAction(feature); if (!action) { // Nothing to add return; } let clonedTheme; let activate = false; if (action.action.startsWith('add_theme')) { const theme = this.context.themesHelper.findThemeByName(action.data); if (theme) { clonedTheme = theme.clone(); } } else if (action.action.startsWith('add_group')) { const group = this.context.themesHelper.findGroupByName(action.data); if (group) { clonedTheme = this.context.themesHelper.getMinimalClonedThemeForLayer(group); } } else if (action.action.startsWith('add_layer')) { const layer = this.context.themesHelper.findLayerByName(action.data); if (layer) { clonedTheme = this.context.themesHelper.getMinimalClonedThemeForLayer(layer); activate = true; } } else { console.warn('Unsupported result type'); } if (clonedTheme) { this.context.themesHelper.mergeThemeInLayerTree(clonedTheme, activate); } } zoomTo(extent) { const minResolution = this.context.configManager.Config.search?.minResolution; const currentResolution = this.map.getView().getResolution(); const currentExtent = this.map.getView().calculateExtent(); if (minResolution) { if (currentResolution > minResolution) { // If we are in a bigger resolution as the minimal one, // Zoom to object with minResolution this.context.mapManager.zoomToExtent(extent, minResolution); } else if (!containsExtent(currentExtent, extent)) { // Else, if the extent is NOT already within the current extent of the map // We keep the current resolution, and just pan to object this.state.position.center = getCenter(extent); } } // Otherwise, if the searched object is already in the current map extent // We do nothing } onMouseMove() { // if the mouse moves, we activate the hover effect const results = this.shadowRoot?.querySelectorAll('.result'); if (!results) { return; } for (const result of results) { result.classList.remove('active'); const htmlResult = result; htmlResult.style.removeProperty('background-color'); } } onKeyDown(e) { // clear search on escape if (e.key === 'Escape') { this.clearSearch(true); } // automatic re-open search results on enter else if (this.forceHide) { if (e.key === 'Enter') { this.onFocusIn(); } } // navigate through search results else if (!this.forceHide) { this.navigateToResult(e); } } navigateToResult(e) { switch (e.key) { case 'ArrowDown': if (this.focusedResultIndex < this.allResults.length - 1) { this.focusedResultIndex += 1; this.focusResultFromIndex(); } break; case 'ArrowUp': if (this.focusedResultIndex > 0) { this.focusedResultIndex -= 1; this.focusResultFromIndex(); } break; case 'Enter': if (this.focusedResultIndex >= 0) { this.onSelect(this.allResults[this.focusedResultIndex]); } break; } } createToolTipContent() { // Create a temporary div to hold the content const tooltipContent = document.createElement('div'); // Custom tooltip: Check if there's a slot named "search-tooltip" const slot = this.shadow.querySelector('slot[name="search-tooltip"]'); if (slot) { const assignedNodes = slot.assignedNodes({ flatten: true }); if (assignedNodes.length > 0) { assignedNodes.forEach((node) => { tooltipContent.appendChild(node.cloneNode(true)); }); return tooltipContent; } } // Default tooltip const tooltipI18nKey = 'search_tooltip'; tooltipContent.innerHTML = this.context.i18nManager.getTranslation(tooltipI18nKey); // Add an explanation about filter shortcuts if (this.context.searchManager.hasFilterShortcutsEnabled()) { const shortcutPrefix = this.context.configManager.Config.search.filterShortcutPrefix; const prefixList = shortcutPrefix.map((prefix) => `"${prefix}"`).join(', '); const filterShortcutHelp = this.context.i18nManager .getTranslation('Type {prefix} to view available shortcuts to quickly filter search results.') .replace('{prefix}', prefixList); tooltipContent.innerHTML += `<br>${filterShortcutHelp}`; } return tooltipContent; } createTooltip() { const searchBox = this.shadowRoot?.getElementById('searchbox'); if (searchBox) { // Create a tooltip using tippy.js this.tooltipInstance = tippy(searchBox, { content: () => { return this.createToolTipContent(); }, trigger: 'mouseenter', hideOnClick: false, interactive: true, theme: 'light', placement: 'left', arrow: true, appendTo: document.body }); } } closeToolTip() { // Remove the tooltip to not cover any results const res = document.querySelector('[data-tippy-root]'); if (res) { res.remove(); } } initColorPicker() { super.render(); const colorPicker = this.shadowRoot?.getElementById('colorPickerBtn'); if (colorPicker) { this.girafeColorPicker = new GirafeColorPicker({ parent: colorPicker, color: this.context.configManager.Config.search?.defaultStrokeColor, popup: 'right' }); this.girafeColorPicker.onChange = (color) => { // The fill color should be the selected color with a bit more transparency const fillColor = [color.rgba[0], color.rgba[1], color.rgba[2], color.rgba[3] / 2]; this.searchFillColor = fillColor; this.searchStrokeColor = color.hex; this.updatePreviewLayerStyle(fillColor, color.hex); }; this.girafeColorPicker.onOpen = (_) => { if (this.defaultColorHasChanged()) { this.girafeColorPicker?.setColor(this.context.configManager.Config.search?.defaultStrokeColor, true); } }; } } updatePreviewLayerStyle(fillColor, strokeColor) { if (!this.previewGeoLayer) { return; } // Only update style if new colors were provided via color picker or default colors have changed if (this.defaultColorHasChanged()) { const defaultFillColor = this.context.configManager.Config.search?.defaultFillColor; this.defaultSearchFillColor = defaultFillColor; this.searchFillColor = defaultFillColor; const defaultStrokeColor = this.context.configManager.Config.search?.defaultStrokeColor; this.defaultSearchStrokeColor = defaultStrokeColor; this.searchStrokeColor = defaultStrokeColor; } const strokeColorWithFallback = strokeColor ?? this.searchStrokeColor ?? this.defaultSearchStrokeColor; const fillColorWithFallback = fillColor ?? this.searchFillColor ?? this.defaultSearchFillColor; this.previewGeoLayer.setStyle(new Style({ stroke: new Stroke({ color: strokeColorWithFallback, width: this.context.configManager.Config.search?.defaultStrokeWidth }), fill: new Fill({ color: fillColorWithFallback }), image: new Icon({ anchor: [0.5, 1], anchorXUnits: 'fraction', anchorYUnits: 'fraction', src: this.getColoredPinIcon(strokeColorWithFallback), scale: 0.3 }) })); } defaultColorHasChanged() { return (this.defaultSearchFillColor !== this.context.configManager.Config.search?.defaultFillColor || this.defaultSearchStrokeColor !== this.context.configManager.Config.search?.defaultStrokeColor); } getColoredPinIcon(hexColor) { const pin = `<svg xmlns="http://www.w3.org/2000/svg" width="120" height="120" style="fill: ${hexColor};" viewBox="0 0 384 512"> <path d="M215.7 499.2C267 435 384 279.4 384 192C384 86 298 0 192 0S0 86 0 192c0 87.4 117 243 168.3 307.2c12.3 15.3 35.1 15.3 47.4 0zM192 128a64 64 0 1 1 0 128 64 64 0 1 1 0-128z"/> </svg>`; return `data:image/svg+xml;utf8,${encodeURIComponent(pin)}`; } } __decorate([ UsedInTemplateOnly() ], SearchComponent.prototype, "addFullThemeIfNotPresent", null); __decorate([ UsedInTemplateOnly() ], SearchComponent.prototype, "getGroupIcon", null); __decorate([ UsedInTemplateOnly() ], SearchComponent.prototype, "getProviderClass", null); __decorate([ UsedInTemplateOnly() ], SearchComponent.prototype, "getGroupClass", null); __decorate([ UsedInTemplateOnly() ], SearchComponent.prototype, "getLabel", null); __decorate([ UsedInTemplateOnly() ], SearchComponent.prototype, "isFeatureActionThemeRelated", null); export default SearchComponent;