/** * Copyright Sourcepole AG * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {connect} from 'react-redux'; import Sortable from 'react-sortablejs'; import classnames from 'classnames'; import FileSaver from 'file-saver'; import isEmpty from 'lodash.isempty'; import PropTypes from 'prop-types'; import {setActiveLayerInfo} from '../actions/layerinfo'; import {LayerRole, changeLayerProperty, removeLayer, reorderLayer, setSwipe, addLayerSeparator, setThemeLayersVisibilityPreset} from '../actions/layers'; import {toggleMapTips, zoomToExtent, zoomToPoint} from '../actions/map'; import {setCurrentTask} from '../actions/task'; import Icon from '../components/Icon'; import ImportLayer from '../components/ImportLayer'; import LayerInfoWindow from '../components/LayerInfoWindow'; import LegendPrintWindow from '../components/LegendPrintWindow'; import ServiceInfoWindow from '../components/ServiceInfoWindow'; import SideBar from '../components/SideBar'; import PopupMenu from '../components/widgets/PopupMenu'; import {Image} from '../components/widgets/Primitives'; import Spinner from '../components/widgets/Spinner'; import ConfigUtils from '../utils/ConfigUtils'; import CoordinatesUtils from '../utils/CoordinatesUtils'; import LayerUtils from '../utils/LayerUtils'; import LocaleUtils from '../utils/LocaleUtils'; import MapUtils from '../utils/MapUtils'; import MiscUtils from '../utils/MiscUtils'; import withTooltip from '../utils/Tooltip'; import VectorLayerUtils from '../utils/VectorLayerUtils'; import '../actions/bookmark'; import './style/LayerTree.css'; /** * Displays the map layer tree in a sidebar. * * The print legend functionality requires a template located by default at assets/templates/legendprint.html * with containing a container element with id=legendcontainer. */ class LayerTree extends React.Component { static propTypes = { /** Whether to add imported layers behind the existing tree layers. */ addImportedLayersBehind: PropTypes.func, addLayerSeparator: PropTypes.func, /** Whether to enable the compare function. Requires the `MapCompare` plugin. */ allowCompare: PropTypes.bool, /** Whether to allow importing external layers. */ allowImport: PropTypes.bool, /** Whether to allow adding separator entries in the layer tree, useful for organizing the tree. */ allowLayerTreeSeparators: PropTypes.bool, /** Whether to allow enabling map tips. */ allowMapTips: PropTypes.bool, /** Whether to allow removing theme layers. */ allowRemovingThemeLayers: PropTypes.bool, /** Whether to allow selection of identifyable layers. The `showQueryableIcon` property should be `true` to be able to select identifyable layers. */ allowSelectIdentifyableLayers: PropTypes.bool, /** Whether to display a BBOX dependent legend. Can be `true|false|"theme"`, latter means only for theme layers. */ bboxDependentLegend: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]), changeLayerProperty: PropTypes.func, /** The DnD delay when dragging a layer tree entry, in milliseconds. */ dndDelay: PropTypes.number, editConfigs: PropTypes.object, /** Whether to enable the legend print functionality. */ enableLegendPrint: PropTypes.bool, /** Whether to display a service info button to display the WMS service metadata. */ enableServiceInfo: PropTypes.bool, /** Whether to display a button to filter invisible layers from the layertree. */ enableVisibleFilter: PropTypes.bool, /** List of layernames for which no legend is displayed, neither as icon nor in the legend print. */ excludeLegendLayers: PropTypes.array, /** Additional parameters to pass to the GetLegendGraphics request. */ extraLegendParameters: PropTypes.string, /** Whether to use the fallback logic for drag-and-drop. */ fallbackDrag: PropTypes.bool, filter: PropTypes.object, /** Whether to display a flat layer tree, omitting any groups. */ flattenGroups: PropTypes.bool, /** Whether to display unchecked layers gray in the layertree. */ grayUnchecked: PropTypes.bool, /** Whether toggling a group also toggles all sublayers. */ groupTogglesSublayers: PropTypes.bool, /** Whether to display the layer info button inside the layer settings menu rather than next to the layer title. */ infoInSettings: PropTypes.bool, /** Default layer info window geometry with size, position and docking status. */ layerInfoGeometry: PropTypes.shape({ initialWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), initialHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), initialX: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), initialY: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), initiallyDocked: PropTypes.bool }), layers: PropTypes.array, loadingLayers: PropTypes.array, map: PropTypes.object, mapTipsEnabled: PropTypes.bool, mobile: PropTypes.bool, /** Whether to only display layer groups but not individual layers in layertree. */ onlyGroups: PropTypes.bool, removeLayer: PropTypes.func, reorderLayer: PropTypes.func, /** Whether to display a scale dependent legend. Can be `true|false|"theme"`, latter means only for theme layers. */ scaleDependentLegend: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]), setActiveLayerInfo: PropTypes.func, setCurrentTask: PropTypes.func, setSwipe: PropTypes.func, setThemeLayersVisibilityPreset: PropTypes.func, /** Whether to display an icon linking to the layer attribute table in the layer options menu. */ showAttributeTableLink: PropTypes.bool, /** Whether to show style selection menu for groups (if `showStyleSelector` is `true`). */ showGroupStyleSelector: PropTypes.bool, /** Whether to display legend icons. */ showLegendIcons: PropTypes.bool, /** Whether to display the queryable icon to indicate that a layer is identifyable. */ showQueryableIcon: PropTypes.bool, /** Whether to display the root entry of the layertree. */ showRootEntry: PropTypes.bool, /** Whether to show the style selection menu for layers with multiple styles. */ showStyleSelector: PropTypes.bool, /** Whether to show a settings menu in the titlebar which groups all titlebar buttons. */ showTitlebarSettingsMenu: PropTypes.bool, /** Whether to display a checkbox to toggle all layers. */ showToggleAllLayersCheckbox: PropTypes.bool, /** The side of the application on which to display the sidebar. */ side: PropTypes.string, swipe: PropTypes.number, /** Template location for the legend print functionality */ templatePath: PropTypes.string, theme: PropTypes.object, toggleMapTips: PropTypes.func, transparencyIcon: PropTypes.bool, visibilityPresets: PropTypes.func, /** The initial width of the layertree, as a CSS width string. */ width: PropTypes.string, zoomToExtent: PropTypes.func, zoomToPoint: PropTypes.func }; static defaultProps = { layers: [], showLegendIcons: true, showRootEntry: true, showQueryableIcon: true, allowMapTips: true, allowCompare: true, allowImport: true, allowSelectIdentifyableLayers: false, dndDelay: 200, groupTogglesSublayers: false, grayUnchecked: true, layerInfoGeometry: { initialWidth: 480, initialHeight: 480, initialX: null, initialY: null, initiallyDocked: false }, bboxDependentLegend: false, flattenGroups: false, onlyGroups: false, width: "25em", enableLegendPrint: true, enableVisibleFilter: true, enableServiceInfo: true, excludeLegendLayers: [], infoInSettings: true, showGroupStyleSelector: true, showStyleSelector: true, showToggleAllLayersCheckbox: true, transparencyIcon: true, side: 'right', templatePath: ":/templates/legendprint.html" }; state = { activemenu: null, activestylemenu: null, legendTooltip: null, sidebarwidth: null, importvisible: false, filterinvisiblelayers: false, legendPrintVisible: false, visibilityMenu: false, activePreset: null, serviceInfoVisible: false }; constructor(props) { super(props); this.visibilityButton = null; } componentDidUpdate(prevProps) { if (this.props.allowMapTips && !ConfigUtils.isMobile() && this.props.theme.mapTips !== prevProps.theme.mapTips) { this.props.toggleMapTips(this.props.theme.mapTips === true); } if (this.props.layers !== prevProps.layers) { this.setState(state => ({activePreset: LayerUtils.getActiveVisibilityPreset(this.props.layers, state.visibilityPresets)})); } if (this.props.theme && ( this.props.theme !== prevProps.theme || this.props.visibilityPresets !== prevProps.visibilityPresets )) { const visibilityPresets = { ...this.props.theme.visibilityPresets, ...this.props.visibilityPresets.reduce((res, entry) => { if (entry.data && entry.theme_id === this.props.theme.id) { return {...res, [entry.key]: entry.data}; } else { return res; } }, {}) }; this.setState({visibilityPresets, activePreset: LayerUtils.getActiveVisibilityPreset(this.props.layers, visibilityPresets)}); } } renderSubLayers = (layer, group, path, enabled, inMutuallyExclusiveGroup, usedGroupIds) => { return (group.sublayers || []).map((sublayer, idx) => { const subpath = [...path, idx]; if (sublayer.sublayers) { return this.renderLayerGroup(layer, sublayer, subpath, enabled, inMutuallyExclusiveGroup, usedGroupIds); } else { return this.renderLayer(layer, sublayer, subpath, enabled, inMutuallyExclusiveGroup); } }); }; renderLayerGroup = (layer, group, path, enabled, inMutuallyExclusiveGroup, usedGroupIds) => { const flattenGroups = ConfigUtils.getConfigProp("flattenLayerTreeGroups", this.props.theme) || this.props.flattenGroups; if (flattenGroups) { return this.renderSubLayers(layer, group, path, enabled, false, usedGroupIds); } if (Array.isArray(layer.layerTreeHiddenSublayers) && layer.layerTreeHiddenSublayers.includes(group.name)) { return null; } const subtreevisibility = LayerUtils.computeLayerVisibility(group); if (subtreevisibility === 0 && this.state.filterinvisiblelayers) { return null; } let groupId = layer.id + ":" + group.name; for (let i = 0; usedGroupIds.has(groupId); ++i) { groupId = layer.id + ":" + group.name + ":" + i; } usedGroupIds.add(groupId); let visibility = true; let checkboxstate = ""; if (this.props.groupTogglesSublayers && !inMutuallyExclusiveGroup) { visibility = subtreevisibility > 0; if (subtreevisibility === 1) { checkboxstate = "checked"; } else if (subtreevisibility === 0) { checkboxstate = "unchecked"; } else { checkboxstate = "tristate"; } } else { visibility = group.visibility === undefined ? subtreevisibility > 0 : group.visibility; if (visibility) { checkboxstate = subtreevisibility === 1 ? 'checked' : 'tristate'; } else { checkboxstate = 'unchecked'; } } let omitqueryable; let identifyableClassName = ""; const subtreequeryable = LayerUtils.computeLayerQueryable(group); if (subtreequeryable === 1) { identifyableClassName = "layertree-item-identifyable-checked"; omitqueryable = false; } else if (subtreequeryable === 0) { identifyableClassName = "layertree-item-identifyable-unchecked"; omitqueryable = true; } else { identifyableClassName = "layertree-item-identifyable-tristate"; omitqueryable = true; } if (inMutuallyExclusiveGroup) { checkboxstate = 'radio_' + checkboxstate; } const expanderstate = group.expanded ? 'tree_minus' : 'tree_plus'; const showExpander = (!this.props.onlyGroups || (group.sublayers || []).some(sublayer => sublayer.sublayers)) && group.sublayers.some(sublayer => !(layer.layerTreeHiddenSublayers ?? []).includes(sublayer.name)); const itemclasses = { "layertree-item": true, "layertree-item-disabled": (!this.props.groupTogglesSublayers && !enabled) || (this.props.grayUnchecked && !visibility) }; let sublayersContent = null; if (group.expanded) { sublayersContent = this.renderSubLayers(layer, group, path, enabled && visibility, group.mutuallyExclusive === true, usedGroupIds); } const optMenuClasses = classnames({ "layertree-item-menubutton": true, "layertree-item-menubutton-active": this.state.activemenu === groupId }); const styleMenuClasses = classnames({ "layertree-item-menubutton": true, "layertree-item-menubutton-active": this.state.activestylemenu === groupId }); const allowRemove = this.props.allowRemovingThemeLayers || ConfigUtils.getConfigProp("allowRemovingThemeLayers", this.props.theme) === true || layer.role !== LayerRole.THEME; const allowReordering = ConfigUtils.getConfigProp("allowReorderingLayers", this.props.theme) === true && !this.state.filterinvisiblelayers; const sortable = allowReordering && ConfigUtils.getConfigProp("preventSplittingGroupsWhenReordering", this.props.theme) === true; const styles = this.props.showStyleSelector && this.props.showGroupStyleSelector && layer.type === "wms" && path.length === 0 ? this.getLayerStyles(layer) : null; return (
{showExpander ? ( this.groupExpandedToggled(layer, path, group.expanded)} />) : ()} this.itemVisibilityToggled(layer, path, visibility)} /> this.itemVisibilityToggled(layer, path, visibility)} {...withTooltip(group.title, {}, 'pointer')}>{group.title} {LayerUtils.hasQueryableSublayers(group) && this.props.allowSelectIdentifyableLayers ? ( this.itemOmitQueryableToggled(layer, path, omitqueryable)} />) : null} {Object.keys(styles || {}).length > 1 ? ( this.layerStyleMenuToggled(groupId)}/>) : null} this.layerMenuToggled(groupId)}/> {allowRemove ? ( this.props.removeLayer(layer.id, path)}/>) : null}
{this.state.activemenu === groupId ? this.renderOptionsMenu(layer, group, path, allowRemove, subtreevisibility) : null} {this.state.activestylemenu === groupId ? this.renderStyleMenu(styles, this.getSelectedStyles(layer), (style) => this.applyLayerStyle(style, layer)) : null} {sublayersContent}
); }; renderLayer = (layer, sublayer, path, enabled = true, inMutuallyExclusiveGroup = false, skipExpanderPlaceholder = false) => { if (this.props.onlyGroups) { return null; } if (this.state.filterinvisiblelayers && !sublayer.visibility) { return null; } if ((layer.layerTreeHiddenSublayers ?? []).includes(sublayer.name)) { return null; } const sublayerId = layer.id + ":" + sublayer.name; const allowRemove = this.props.allowRemovingThemeLayers || ConfigUtils.getConfigProp("allowRemovingThemeLayers", this.props.theme) === true || layer.role !== LayerRole.THEME; const allowReordering = ConfigUtils.getConfigProp("allowReorderingLayers", this.props.theme) === true; let checkboxstate = sublayer.visibility === true ? 'checked' : 'unchecked'; if (inMutuallyExclusiveGroup) { checkboxstate = 'radio_' + checkboxstate; } const optMenuClasses = classnames({ "layertree-item-menubutton": true, "layertree-item-menubutton-active": this.state.activemenu === sublayerId }); const styleMenuClasses = classnames({ "layertree-item-menubutton": true, "layertree-item-menubutton-active": this.state.activestylemenu === sublayerId }); const itemclasses = { "layertree-item": true, "layertree-item-disabled": layer.type !== "separator" && ((!this.props.groupTogglesSublayers && !enabled) || (this.props.grayUnchecked && !sublayer.visibility)), "layertree-item-separator": layer.type === "separator", "layertree-item-outsidescalerange": (sublayer.minScale !== undefined && this.props.map.scale < sublayer.minScale) || (sublayer.maxScale !== undefined && this.props.map.scale > sublayer.maxScale) }; let infoButton = null; if (layer.type === "wms" || layer.type === "wfs" || layer.type === "wmts") { infoButton = ( this.props.setActiveLayerInfo(layer, sublayer)}/>); } let legendicon = null; if (this.props.showLegendIcons && !this.props.excludeLegendLayers.includes(sublayer.name)) { const legendUrl = LayerUtils.getLegendUrl(layer, sublayer, this.props.map, this.props.bboxDependentLegend, this.props.scaleDependentLegend, this.props.extraLegendParameters); if (legendUrl) { legendicon = ( this.showLegendTooltip(ev, legendUrl)} onTouchStart={ev => this.showLegendTooltip(ev, legendUrl)} src={legendUrl + "&TYPE=thumbnail"} />); } else if (layer.color) { legendicon = (); } } let checkbox = null; if (layer.type === "placeholder") { checkbox = (); } else if (layer.type === "separator") { checkbox = null; } else { checkbox = ( this.itemVisibilityToggled(layer, path, sublayer.visibility)} />); } let title = null; if (layer.type === "separator") { title = ( this.props.changeLayerProperty(layer.id, "title", ev.target.value)} value={sublayer.title}/>); } else { title = ( this.itemVisibilityToggled(layer, path, sublayer.visibility)} {...withTooltip(sublayer.title, {}, 'pointer')}>{sublayer.title}); } let queryableicon = null; if (this.props.allowSelectIdentifyableLayers) { const identifyableClassName = !sublayer.omitFromQueryLayers ? "layertree-item-identifyable-checked" : "layertree-item-identifyable-unchecked"; queryableicon = this.itemOmitQueryableToggled(layer, path, sublayer.omitFromQueryLayers)}/>; } else { queryableicon = ; } let timeIcon = null; if (ConfigUtils.havePlugin("TimeManager") && (sublayer.dimensions ?? []).find(dim => dim.units === "ISO8601")) { timeIcon = ( this.openTimenManager(layer, path, sublayer)} />); } const allowOptions = layer.type !== "placeholder" && layer.type !== "separator"; const flattenGroups = ConfigUtils.getConfigProp("flattenLayerTreeGroups", this.props.theme) || this.props.flattenGroups; const allowSeparators = allowReordering && (this.props.allowLayerTreeSeparators || ConfigUtils.getConfigProp("allowLayerTreeSeparators", this.props.theme)); const separatorTooltip = LocaleUtils.tr("layertree.separatortooltip"); return (
{allowSeparators ? (
this.addLayerSeparator(layer.id, path)} {...withTooltip(separatorTooltip, {}, 'pointer')} />) : null}
{(flattenGroups || skipExpanderPlaceholder) ? null : ()} {checkbox} {legendicon} {title} {sublayer.queryable && this.props.showQueryableIcon ? (queryableicon) : null} {timeIcon} {sublayer.name in (this.props.filter.filterParams || {}) || this.props.filter.filterGeom ? () : null} {this.props.loadingLayers.includes(layer.id) ? () : null} {allowOptions && !this.props.infoInSettings ? infoButton : null} {this.props.showStyleSelector && Object.keys(sublayer.styles || {}).length > 1 ? ( this.layerStyleMenuToggled(sublayerId)}/>) : null} {allowOptions ? ( this.layerMenuToggled(sublayerId)}/>) : null} {allowRemove ? ( this.props.removeLayer(layer.id, path)}/>) : null}
{this.state.activemenu === sublayerId ? this.renderOptionsMenu(layer, sublayer, path, allowRemove) : null} {this.state.activestylemenu === sublayerId ? this.renderStyleMenu(sublayer.styles, [sublayer.style], (style) => this.layerStyleChanged(layer, path, style)) : null}
); }; renderOptionsMenu = (layer, sublayer, path, marginRight, subtreevisibility = 0) => { const allowReordering = ConfigUtils.getConfigProp("allowReorderingLayers", this.props.theme) === true; let zoomToLayerButton = null; if (sublayer.bbox?.bounds) { const zoomToLayerTooltip = LocaleUtils.tr("layertree.zoomtolayer"); const crs = sublayer.bbox.crs || this.props.map.projection; zoomToLayerButton = ( this.props.zoomToExtent(sublayer.bbox.bounds, crs)} title={zoomToLayerTooltip} /> ); } let zoomToScaleButton = null; if (sublayer.minScale !== undefined || sublayer.maxScale !== undefined) { // Zoom to closest scale at which layer is visible const zoomToScale = (scale, roundFunc) => { let zoom = MapUtils.computeFractionalZoom(this.props.map.scales, scale); if (!ConfigUtils.getConfigProp("allowFractionalZoom")) { zoom = roundFunc(zoom); } let center = this.props.map.center; if (sublayer.bbox?.bounds) { const bounds = CoordinatesUtils.reprojectBbox(sublayer.bbox.bounds, sublayer.bbox.crs, this.props.map.projection); if (!MiscUtils.extentContainsPoint(bounds, center)) { center = [0.5 * (bounds[0] + bounds[2]), 0.5 * (bounds[1] + bounds[3])]; } } this.props.zoomToPoint(center, zoom, this.props.map.projection); }; if (sublayer.maxScale !== undefined && this.props.map.scale >= sublayer.maxScale) { zoomToScaleButton = ( zoomToScale(sublayer.maxScale - 1, Math.ceil)} title={LocaleUtils.tr("layertree.zoomoscale")} /> ); } else if (sublayer.minScale !== undefined && this.props.map.scale <= sublayer.minScale) { zoomToScaleButton = ( zoomToScale(sublayer.minScale + 1, Math.floor)} title={LocaleUtils.tr("layertree.zoomoscale")} /> ); } } let reorderButtons = null; if (allowReordering && !this.state.filterinvisiblelayers) { reorderButtons = [ ( this.props.reorderLayer(layer.id, path, +1)} />), ( this.props.reorderLayer(layer.id, path, -1)} />) ]; } let toggleGroupButton = null; if (sublayer.sublayers && !this.props.groupTogglesSublayers) { toggleGroupButton = ( this.props.changeLayerProperty(layer.id, "visibility", subtreevisibility !== 1, path, "children")} title={LocaleUtils.tr("layertree.togglegroup")} />); } let infoButton = null; if (this.props.infoInSettings && (layer.type === "wms" || layer.type === "wfs" || layer.type === "wmts")) { infoButton = ( this.props.setActiveLayerInfo(layer, sublayer)}/>); } let attrTableButton = null; if ( this.props.showAttributeTableLink && ConfigUtils.havePlugin("AttributeTable") && this.props.editConfigs[layer.wms_name]?.[sublayer.name] ) { attrTableButton = ( this.props.setCurrentTask("AttributeTable", null, null, {layer: layer.wms_name + "#" + sublayer.name})} title={LocaleUtils.tr("common.openinattributetable")} />); } return (
{zoomToLayerButton} {zoomToScaleButton} {this.props.transparencyIcon ? () : LocaleUtils.tr("layertree.transparency")} this.layerTransparencyChanged(layer, path, ev.target.value, !isEmpty(sublayer.sublayers) ? 'children' : null)} onMouseDown={ev => ev.stopPropagation()} onMouseMove={ev => ev.stopPropagation()} onPointerDown={ev => ev.stopPropagation()} onPointerMove={ev => ev.stopPropagation()} onTouchMove={ev => ev.stopPropagation()} onTouchStart={ev => ev.stopPropagation()} step="1" type="range" value={255 - LayerUtils.computeLayerOpacity(sublayer)} /> {reorderButtons} {toggleGroupButton} {infoButton} {attrTableButton} {layer.type === 'vector' ? ( this.exportRedliningLayer(layer)} />) : null}
); }; renderStyleMenu = (styles, selectedStyles, onStyleChange, marginRight = 0) => { const checkedIcon = selectedStyles.length === 1 ? "radio_checked" : "radio_tristate"; return (
{Object.entries(styles).map(([name, title]) => (
onStyleChange(name)} onKeyDown={MiscUtils.checkKeyActivate} tabIndex={0}>
{title}
))}
); }; preventLayerTreeItemDrag = (ev) => { const draggableEl = ev.currentTarget.parentNode; if (draggableEl.draggable) { draggableEl.draggable = false; document.addEventListener('pointerup', () => { draggableEl.draggable = true; }, {once: true}); } }; renderLayerTree = (layers) => { const flattenGroups = ConfigUtils.getConfigProp("flattenLayerTreeGroups", this.props.theme) || this.props.flattenGroups; const haveGroups = !flattenGroups && layers.find(layer => { if (layer.role === LayerRole.THEME && !this.props.showRootEntry) { return (layer.sublayers || []).find(sublayer => !isEmpty(sublayer.sublayers)); } else { return !isEmpty(layer.sublayers); } }); return layers.map(layer => { const usedGroupIds = new Set(); if (isEmpty(layer.sublayers) && layer.role !== LayerRole.THEME) { return this.renderLayer(layer, layer, [], layer.visibility, false, !haveGroups); } else if (this.props.showRootEntry && layer.role === LayerRole.THEME && isEmpty(layer.sublayers)) { return null; } else if (this.props.showRootEntry || layer.role !== LayerRole.THEME) { return this.renderLayerGroup(layer, layer, [], layer.visibility, false, usedGroupIds); } else { return layer.sublayers.map((sublayer, idx) => { const subpath = [idx]; if (!isEmpty(sublayer.sublayers)) { return this.renderLayerGroup(layer, sublayer, subpath, true, false, usedGroupIds); } else { return this.renderLayer(layer, sublayer, subpath, true, false, !haveGroups); } }); } }); }; renderBody = () => { let maptipCheckbox = null; if (this.props.allowMapTips && !ConfigUtils.isMobile() && this.props.theme.mapTips !== null) { const maptipcheckboxstate = this.props.mapTipsEnabled === true ? 'checked' : 'unchecked'; maptipCheckbox = (
{LocaleUtils.tr("layertree.maptip")}
); } const allowReordering = ConfigUtils.getConfigProp("allowReorderingLayers", this.props.theme) === true && !this.state.filterinvisiblelayers; const haveMapCompare = ConfigUtils.havePlugin("MapCompare"); let compareCheckbox = null; if (haveMapCompare && this.props.allowCompare && allowReordering) { const swipecheckboxstate = this.props.swipe || this.props.swipe === 0 ? 'checked' : 'unchecked'; compareCheckbox = (
{LocaleUtils.tr("layertree.compare")}
); } let layerImportExpander = null; if (this.props.allowImport) { layerImportExpander = (
{LocaleUtils.tr("layertree.importlayer")}
); } const flattenGroups = ConfigUtils.getConfigProp("flattenLayerTreeGroups", this.props.theme) || this.props.flattenGroups; const sortable = allowReordering && (ConfigUtils.getConfigProp("preventSplittingGroupsWhenReordering", this.props.theme) === true || flattenGroups === true); const treelayers = this.props.layers.filter(layer => layer.role !== LayerRole.BACKGROUND && !layer.layertreehidden); return (
{ // Prevent context menu on drag-sort ev.stopPropagation(); ev.preventDefault(); return false; }} onTouchEnd={ev => { const target = ev.currentTarget; clearTimeout(target.preventScrollTimeout); target.preventScrollTimeout = null; target.removeEventListener("touchmove", MiscUtils.killEvent); }} onTouchStart={ev => { // Prevent touch-scroll after sortable trigger delay const target = ev.currentTarget; target.preventScrollTimeout = setTimeout(() => { target.addEventListener("touchmove", MiscUtils.killEvent, {passive: false}); }, 200); }} ref={MiscUtils.setupKillTouchEvents} > {this.renderLayerTree(treelayers)}
{maptipCheckbox} {compareCheckbox} {layerImportExpander} {this.state.importvisible ? () : null}
); }; render() { let legendTooltip = null; if (this.state.legendTooltip) { const style = { left: this.state.legendTooltip.x, top: this.state.legendTooltip.y, maxWidth: (window.innerWidth - this.state.legendTooltip.x - 2), maxHeight: (window.innerHeight - this.state.legendTooltip.y - 2), visibility: 'hidden' }; legendTooltip = ( ); } let legendPrintIcon = null; if (this.props.enableLegendPrint) { legendPrintIcon = ( this.setState({legendPrintVisible: true})} title={LocaleUtils.tr("layertree.printlegend")} /> ); } let deleteAllLayersIcon = null; if (this.props.allowRemovingThemeLayers || ConfigUtils.getConfigProp("allowRemovingThemeLayers") === true) { deleteAllLayersIcon = (); } let serviceInfoIcon = null; if (this.props.enableServiceInfo) { serviceInfoIcon = ( this.setState((state) => ({serviceInfoVisible: true}))} title={LocaleUtils.tr("serviceinfo.title")} />); } const extraBeforeContent = this.props.showTitlebarSettingsMenu ? this.renderVisibilityButton() : null; const extraTitlebarContent = this.props.showTitlebarSettingsMenu ? null : ( {this.renderVisibilityButton()} {legendPrintIcon} {deleteAllLayersIcon} {serviceInfoIcon} ); return (
{() => ({ body: this.renderBody() })} {legendTooltip} {this.state.legendPrintVisible ? ( this.setState({legendPrintVisible: false})} scaleDependentLegend={this.props.scaleDependentLegend} visibleOnly /> ) : null} {this.state.serviceInfoVisible && this.setState((state) => ({serviceInfoVisible: false}))} service={this.props.theme} /> }
); } renderVisibilityButton = () => { const menuEntries = []; let vis = 0; if (this.state.visibilityMenu) { let count = 0; for (const layer of this.props.layers) { if (layer.role === LayerRole.THEME || layer.role === LayerRole.USERLAYER) { count += 1; vis += layer.visibility; } } vis /= Math.min(1, count); } if (this.props.showToggleAllLayersCheckbox) { menuEntries.push(
this.toggleLayerTreeVisibility(vis === 0)}> {LocaleUtils.tr("layertree.showallayers")}
); } if (this.props.enableVisibleFilter) { menuEntries.push(
this.setState((state) => ({filterinvisiblelayers: !state.filterinvisiblelayers}))}> {LocaleUtils.tr("layertree.visiblefilter")}
); } menuEntries.push(
this.expandCollapseTree(false)}> {LocaleUtils.tr("common.collapseall")}
); menuEntries.push(
this.expandCollapseTree(true)}> {LocaleUtils.tr("common.expandall")}
); let needsep = menuEntries.length > 0; Object.entries(this.props.theme.visibilityPresets || {}).forEach(([name, preset], idx) => { menuEntries.push(
this.props.setThemeLayersVisibilityPreset(preset)}> {name}
); needsep = true; }); this.props.visibilityPresets.filter(entry => entry.theme_id === this.props.theme.id && entry.data).map((entry, idx) => { menuEntries.push(
this.props.setThemeLayersVisibilityPreset(entry.data)}> {entry.description}
); needsep = true; }); if (this.props.showTitlebarSettingsMenu) { if (this.props.enableLegendPrint) { menuEntries.push(
this.setState({legendPrintVisible: true})}> {LocaleUtils.tr("layertree.printlegend")}
); needsep = false; } if (this.props.allowRemovingThemeLayers || ConfigUtils.getConfigProp("allowRemovingThemeLayers") === true) { menuEntries.push(
{LocaleUtils.tr("layertree.deletealllayers")}
); needsep = false; } if (this.props.enableServiceInfo) { menuEntries.push(
this.setState((state) => ({serviceInfoVisible: true}))}> {LocaleUtils.tr("serviceinfo.title")}
); needsep = false; } } if (menuEntries.length === 0) { return null; } const buttonClasses = classnames({ "layertree-visibility-button": true, "layertree-visibility-button-active": this.state.visibilityMenu }); return ( this.setState(state => ({visibilityMenu: !state.visibilityMenu}))} onKeyDown={MiscUtils.checkKeyActivate} ref={el => {this.visibilityButton = el;}} tabIndex={0}> {this.state.visibilityMenu ? ( this.setState({visibilityMenu: false})}> {menuEntries} ) : null} ); }; legendTooltipLoaded = (ev) => { if (ev.target.naturalWidth > 1) { ev.target.style.visibility = 'visible'; } }; onSortChange = (order, sortable, ev) => { const moved = JSON.parse(order[ev.newIndex]); this.props.reorderLayer(moved.layer, moved.path, ev.newIndex - ev.oldIndex); }; toggleImportLayers = () => { this.setState((state) => { const visible = !state.importvisible; return {importvisible: visible, sidebarwidth: visible ? '40em' : null}; }); }; propagateOptions = (layer, options, path = null) => { if (layer.sublayers) { layer.sublayers = layer.sublayers.map((sublayer, idx) => { if (path === null || (!isEmpty(path) && path[0] === idx)) { const newsublayer = {...sublayer, ...options}; this.propagateOptions(newsublayer, options, path ? path.slice(1) : null); return newsublayer; } else { return sublayer; } }); } }; groupExpandedToggled = (layer, grouppath, oldexpanded) => { this.props.changeLayerProperty(layer.id, "expanded", !oldexpanded, grouppath); }; itemVisibilityToggled = (layer, grouppath, oldvisibility) => { let recurseDirection = null; // If item becomes visible, also make parents visible if (this.props.groupTogglesSublayers) { recurseDirection = !oldvisibility ? "both" : "children"; } else { recurseDirection = !oldvisibility ? "parents" : null; } this.props.changeLayerProperty(layer.id, "visibility", !oldvisibility, grouppath, recurseDirection); }; openTimenManager = (layer, path, sublayer) => { if (!sublayer.visibility) { this.props.changeLayerProperty(layer.id, "visibility", true, path); } this.props.setCurrentTask("TimeManager"); }; itemOmitQueryableToggled = (layer, grouppath, oldomitqueryable) => { this.props.changeLayerProperty(layer.id, "omitFromQueryLayers", !oldomitqueryable, grouppath, "children"); }; layerTransparencyChanged = (layer, sublayerpath, value, recurse = null) => { this.props.changeLayerProperty(layer.id, "opacity", Math.max(1, 255 - value), sublayerpath, recurse); }; layerStyleChanged = (layer, sublayerpath, value, recurseDirection = null) => { this.props.changeLayerProperty(layer.id, "style", value, sublayerpath, recurseDirection); }; layerMenuToggled = (sublayerid) => { this.setState((state) => ({activemenu: state.activemenu === sublayerid ? null : sublayerid, activestylemenu: null})); }; layerStyleMenuToggled = (sublayerid) => { this.setState((state) => ({activestylemenu: state.activestylemenu === sublayerid ? null : sublayerid, activemenu: null})); }; showLegendTooltip = (ev, request) => { this.setState({ legendTooltip: { x: ev.target.getBoundingClientRect().right, y: ev.target.getBoundingClientRect().top, img: request + "&TYPE=tooltip" } }); }; onHide = () => { this.setState({legendTooltip: undefined, visibilityMenu: false}); }; hideLegendTooltip = () => { this.setState({legendTooltip: undefined}); }; toggleMapTips = () => { this.props.toggleMapTips(!this.props.mapTipsEnabled); }; toggleSwipe = () => { this.props.setSwipe(this.props.swipe !== null ? null : 50); }; deleteAllLayers = () => { for (const layer of this.props.layers) { if (layer.role === LayerRole.THEME) { const sublayers = layer.sublayers || []; for (let i = sublayers.length - 1; i >= 0; --i) { this.props.removeLayer(layer.id, [i]); } } else if (layer.role === LayerRole.USERLAYER) { this.props.removeLayer(layer.id); } } }; toggleLayerTreeVisibility = (visible) => { for (const layer of this.props.layers) { if (layer.role === LayerRole.THEME || layer.role === LayerRole.USERLAYER) { this.props.changeLayerProperty(layer.id, "visibility", visible, [], this.props.groupTogglesSublayers ? "children" : null); } } }; expandCollapseTree = (expanded) => { for (const layer of this.props.layers) { if (layer.role === LayerRole.THEME || layer.role === LayerRole.USERLAYER) { this.props.changeLayerProperty(layer.id, "expanded", expanded, [], "children"); } } }; exportRedliningLayer = (layer) => { const data = JSON.stringify({ type: "FeatureCollection", features: layer.features.map(feature => { const newFeature = {...feature, geometry: VectorLayerUtils.reprojectGeometry(feature.geometry, feature.crs || this.props.map.projection, 'EPSG:4326')}; delete newFeature.crs; return newFeature; }) }, null, ' '); FileSaver.saveAs(new Blob([data], {type: "text/plain;charset=utf-8"}), layer.title + ".json"); }; getSelectedStyles = (layer) => { return [...new Set((layer.params?.STYLES || "").split(",").filter(Boolean))]; }; getLayerStyles = (layer) => { return layer?.sublayers?.reduce((styleList, sublayer) => { Object.assign(styleList, this.getLayerStyles(sublayer)); return Object.assign(styleList, sublayer.styles); }, {}); }; applyLayerStyle = (style, layer, path = [], layerId = null) => { layerId = layerId ?? layer.id; (layer.sublayers || []).forEach((sublayer, idx) => { this.applyLayerStyle(style, sublayer, [...path, idx], layerId); if (style in (sublayer.styles || {})) { this.props.changeLayerProperty(layerId, "style", style, [...path, idx]); } }); }; addLayerSeparator = (layerid, path) => { // eslint-disable-next-line no-alert const separatorTitle = prompt( LocaleUtils.tr("layertree.separatortooltip"), LocaleUtils.tr("layertree.separator") ); if (separatorTitle !== null) { this.props.addLayerSeparator(separatorTitle, layerid, path); } }; } const selector = (state) => ({ editConfigs: state.layers.editConfigs, layers: state.layers.flat, filter: state.layers.filter, loadingLayers: state.layers.loading, map: state.map, swipe: state.layers.swipe, theme: state.theme.current || {}, mapTipsEnabled: state.map.maptips, visibilityPresets: state.bookmark.visibilityPresets }); export default connect(selector, { addLayerSeparator: addLayerSeparator, changeLayerProperty: changeLayerProperty, removeLayer: removeLayer, reorderLayer: reorderLayer, toggleMapTips: toggleMapTips, setSwipe: setSwipe, setActiveLayerInfo: setActiveLayerInfo, setCurrentTask: setCurrentTask, setThemeLayersVisibilityPreset: setThemeLayersVisibilityPreset, zoomToExtent: zoomToExtent, zoomToPoint: zoomToPoint })(LayerTree);