@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
532 lines (531 loc) • 31 kB
JavaScript
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>
.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>
.hidden{display:none}#searchbox{background-color:var(--bkg-color);border:1px solid #cfd6dd;border-radius:4px;flex-direction:row;width:100%;height:2.25rem;display:flex;& slot[name=search-tooltip]{display:none}}#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 .5rem;padding-left:.8rem;font-size:1rem}.search-icon,.close-icon,.select-color-icon{width:14px;color:var(--text-color);padding:0 1rem}.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;width:36rem;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}.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{cursor:pointer;text-align:left;background:0 0;border:none;border-top:1px solid #ccc;width:100%}.entry img{width:.8em;margin-right:1rem}.entry span{text-transform:uppercase}.result.selected{color:var(--text-color);background-color:var(--bkg-color-grad2)}#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}
</style>
<style>${this.customStyle}</style>
<link rel="stylesheet" href="lib/vanilla-picker/vanilla-picker.csp.css"><link rel="stylesheet" href="styles/girafecolorpicker.css"><div id="searchbox"><slot name="search-tooltip"></slot><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 ` <button class="${result.get('selected') ? 'result entry selected' : 'result entry'}" onmousedown="${() => this.onMouseDown()}" onclick="${() => this.onSelect(result)}" onmouseover="${() => this.onMouseOver(result)}" onmouseleave="${() => this.onMouseLeave()}">${this.getLabel(result)}</button> `)} `)} `)}</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;
girafeColorPicker;
paintSearchResults;
defaultSearchStrokeColor;
defaultSearchFillColor;
searchStrokeColor;
searchFillColor;
showNoResultWarning = false;
// 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));
}
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 = false;
this.groupedResults = {};
this.allResults = [];
this.clearPreview();
this.focusedResultIndex = -1;
this.focusedResult = null;
super.render();
}
async doSearch(e) {
this.showNoResultWarning = false;
this.context.searchManager.abortSearch();
this.clearSearch();
const target = e.target;
const term = target.value.trim();
if (term.length > 0) {
try {
const features = await this.context.searchManager.doSearch(term);
// 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);
}
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');
}
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 new selected object, and activate 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 = result.get('actions')?.[0];
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.selectedResult = feature;
this.ignoreBlur = false;
this.forceHide = true;
this.previewLayers = undefined;
super.render();
// 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();
// Update searchbox with result
if (this.searchInput && feature.get('label')) {
this.searchInput.value = feature.get('label');
}
}
addResultToTreeView(feature) {
let clonedTheme;
const actions = feature.get('actions');
if (!actions || actions.length === 0) {
// Nothing to add
return;
}
let activate = false;
if (actions[0].action.startsWith('add_theme')) {
const theme = this.context.themesHelper.findThemeByName(actions[0].data);
if (theme) {
clonedTheme = theme.clone();
}
}
else if (actions[0].action.startsWith('add_group')) {
const group = this.context.themesHelper.findGroupByName(actions[0].data);
if (group) {
clonedTheme = this.context.themesHelper.getMinimalClonedThemeForLayer(group);
}
}
else if (actions[0].action.startsWith('add_layer')) {
const layer = this.context.themesHelper.findLayerByName(actions[0].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;
}
}
createTooltip() {
const searchInput = this.shadowRoot?.getElementById('search');
if (searchInput) {
// Create a tooltip using tippy.js
tippy(searchInput, {
content: () => {
// 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) {
// Create a temporary div to hold the content
const tooltipContent = document.createElement('div');
assignedNodes.forEach((node) => {
tooltipContent.appendChild(node.cloneNode(true));
});
return tooltipContent;
}
}
// Fallback to the default tooltip text if no slot content is found
return this.context.i18nManager.getTranslation('search_tooltip') || 'Search...';
},
trigger: 'mouseenter',
hideOnClick: false,
interactive: true,
theme: 'light',
placement: 'left',
arrow: true,
appendTo: document.body
});
}
}
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, "getGroupIcon", null);
__decorate([
UsedInTemplateOnly()
], SearchComponent.prototype, "getProviderClass", null);
__decorate([
UsedInTemplateOnly()
], SearchComponent.prototype, "getGroupClass", null);
__decorate([
UsedInTemplateOnly()
], SearchComponent.prototype, "getLabel", null);
export default SearchComponent;