qwc2 2025.7.13 → 2025.7.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof
4
4
  *
5
5
  * This source code is licensed under the BSD-style license found in the
6
6
  * LICENSE file in the root directory of this source tree.
7
- */import React from"react";import{connect}from"react-redux";import isEmpty from"lodash.isempty";import PropTypes from"prop-types";import{setEditContext,clearEditContext}from"../actions/editing";import{LayerRole}from"../actions/layers";import{setCurrentTask}from"../actions/task";import AttributeForm from"../components/AttributeForm";import ResizeableWindow from"../components/ResizeableWindow";import TaskBar from"../components/TaskBar";import ConfigUtils from"../utils/ConfigUtils";import EditingInterface from"../utils/EditingInterface";import LayerUtils from"../utils/LayerUtils";import LocaleUtils from"../utils/LocaleUtils";import MapUtils from"../utils/MapUtils";import"./style/FeatureForm.css";/**
7
+ */import React from"react";import{connect}from"react-redux";import isEmpty from"lodash.isempty";import PropTypes from"prop-types";import{setEditContext,clearEditContext}from"../actions/editing";import{LayerRole}from"../actions/layers";import{setCurrentTask}from"../actions/task";import AttributeForm from"../components/AttributeForm";import ResizeableWindow from"../components/ResizeableWindow";import TaskBar from"../components/TaskBar";import ConfigUtils from"../utils/ConfigUtils";import CoordinatesUtils from"../utils/CoordinatesUtils";import EditingInterface from"../utils/EditingInterface";import LayerUtils from"../utils/LayerUtils";import LocaleUtils from"../utils/LocaleUtils";import MapUtils from"../utils/MapUtils";import"./style/FeatureForm.css";/**
8
8
  * Displays queried feature attributes in a form.
9
9
  *
10
10
  * The attribute form is generated from the QGIS attribute form configuration.
@@ -18,4 +18,4 @@ function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof
18
18
  *
19
19
  * Can be used as default identify tool by setting `"identifyTool": "FeatureForm"` in `config.json`.
20
20
  */var FeatureForm=/*#__PURE__*/function(_React$Component){function FeatureForm(props){var _this;_classCallCheck(this,FeatureForm);_this=_callSuper(this,FeatureForm,[props]);_defineProperty(_this,"queryPoint",function(prevProps){if(_this.props.click.button!==0||_this.props.click===prevProps.click||(_this.props.click.features||[]).find(function(feature){return feature.id==="startupposmarker"})){return null}var searchMarker=(_this.props.click.features||[]).find(function(feature){return feature.id==="searchmarker"});if(searchMarker&&searchMarker.geometry.type==="Point"){return searchMarker.geometry.coordinates}return _this.props.click.coordinate});_defineProperty(_this,"queryFeatures",function(pos){var pendingRequests=0;Object.entries(_this.props.theme.editConfig||{}).forEach(function(_ref){var _this$props$filter$fi;var _ref2=_slicedToArray(_ref,2),layerId=_ref2[0],editConfig=_ref2[1];if(!editConfig.geomType){// Skip geometryless datasets
21
- return}var path=[];var sublayer=null;var mapScale=MapUtils.computeForZoom(_this.props.map.scales,_this.props.map.zoom);var layer=_this.props.layers.find(function(l){return l.role===LayerRole.THEME&&(sublayer=LayerUtils.searchSubLayer(l,"name",layerId,path))});if(!layer||!sublayer||!LayerUtils.sublayerVisible(layer,path)||!LayerUtils.layerScaleInRange(sublayer,mapScale)){return}var layerOrder=layer.params.LAYERS.split(",");++pendingRequests;var editDataset=editConfig.editDataset||layerId;var scale=Math.round(MapUtils.computeForZoom(_this.props.map.scales,_this.props.map.zoom));_this.props.iface.getFeature(editDataset,pos,_this.props.map.projection,scale,96,function(featureCollection){if(featureCollection&&!isEmpty(featureCollection.features)){_this.setState(function(state){var newPickedFeatures=Object.fromEntries(Object.entries(_objectSpread(_objectSpread({},state.pickedFeatures),featureCollection.features.reduce(function(res,feature){return _objectSpread(_objectSpread({},res),{},_defineProperty({},layerId+"::"+feature.id,feature))},{}))).sort(function(a,b){var partsA=a[0].split("::");var partsB=b[0].split("::");var diff=layerOrder.indexOf(partsB[0])-layerOrder.indexOf(partsA[0]);return diff===0?partsA[1].localeCompare(partsB[1]):diff}));var selectedFeature=state.pendingRequests<=1&&!state.selectedFeature?Object.keys(newPickedFeatures)[0]:"";return{pickedFeatures:newPickedFeatures,pendingRequests:state.pendingRequests-1,selectedFeature:selectedFeature}})}else{_this.setState(function(state){var _Object$keys$;var selectedFeature=state.pendingRequests<=1&&!state.selectedFeature?(_Object$keys$=Object.keys(state.pickedFeatures)[0])!==null&&_Object$keys$!==void 0?_Object$keys$:"":"";return{pendingRequests:state.pendingRequests-1,selectedFeature:selectedFeature}})}},(_this$props$filter$fi=_this.props.filter.filterParams)===null||_this$props$filter$fi===void 0?void 0:_this$props$filter$fi[sublayer.name],_this.props.filter.filterGeom)});_this.setState({pendingRequests:pendingRequests,pickedFeatures:{},selectedFeature:""})});_defineProperty(_this,"setSelectedFeature",function(ev){_this.setState({selectedFeature:ev.target.value})});_defineProperty(_this,"onWindowClose",function(){_this.clearResults();if(_this.props.exitTaskOnResultsClose){_this.props.setCurrentTask(null)}});_defineProperty(_this,"clearResults",function(){if(!_this.props.editContext.changed){_this.setState(FeatureForm.defaultState)}});_defineProperty(_this,"updatePickedFeatures",function(newfeature){_this.setState(function(state){return{pickedFeatures:Object.entries(state.pickedFeatures).reduce(function(res,_ref3){var _ref4=_slicedToArray(_ref3,2),key=_ref4[0],feature=_ref4[1];res[key]=feature.id===newfeature.id?newfeature:feature;return res},{})}})});_this.state=FeatureForm.defaultState;return _this}_inherits(FeatureForm,_React$Component);return _createClass(FeatureForm,[{key:"componentDidMount",value:function componentDidMount(){if(this.props.enabled){this.props.setEditContext("FeatureForm",{action:"Pick"})}}},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps,prevState){if(this.props.enabled&&!prevProps.enabled){this.props.setEditContext("FeatureForm",{action:"Pick"})}var isCurrentContext=this.props.editContext.id===this.props.currentEditContext;if(this.props.enabled&&isCurrentContext&&!this.props.editContext.changed&&this.state.pendingRequests===0){var clickPoint=this.queryPoint(prevProps);if(clickPoint){this.queryFeatures(clickPoint)}}if(this.props.enabled&&this.state.selectedFeature!==prevState.selectedFeature){var feature=this.state.pickedFeatures?this.state.pickedFeatures[this.state.selectedFeature]:null;var curLayerId=this.state.selectedFeature.split("::")[0];var curConfig=this.props.theme.editConfig[curLayerId]||{};var canEditGeometry=["Point","LineString","Polygon"].includes((curConfig.geomType||"").replace(/^Multi/,"").replace(/Z$/,""));var editPermissions=curConfig.permissions||{};this.props.setEditContext("FeatureForm",{action:"Pick",feature:feature,changed:false,geomType:curConfig.geomType||null,geomReadOnly:editPermissions.updatable===false||!canEditGeometry})}if(!this.props.enabled&&prevProps.enabled){this.props.clearEditContext("FeatureForm");this.setState(FeatureForm.defaultState)}}},{key:"render",value:function render(){var _this2=this;var resultWindow=null;if(this.state.pickedFeatures!==null){var body=null;if(this.state.pendingRequests>0){body=/*#__PURE__*/React.createElement("div",{className:"feature-query-body",role:"body"},/*#__PURE__*/React.createElement("span",{className:"identify-body-message"},LocaleUtils.tr("featureform.querying")))}else if(isEmpty(this.state.pickedFeatures)){body=/*#__PURE__*/React.createElement("div",{className:"feature-query-body",role:"body"},/*#__PURE__*/React.createElement("span",{className:"identify-body-message"},LocaleUtils.tr("featureform.noresults")))}else{var featureText=LocaleUtils.tr("featureform.feature");var curLayerId=this.state.selectedFeature.split("::")[0];var curConfig=this.props.theme.editConfig[curLayerId];body=/*#__PURE__*/React.createElement("div",{className:"feature-query-body",role:"body"},Object.keys(this.state.pickedFeatures).length>1?/*#__PURE__*/React.createElement("div",{className:"feature-query-selection"},/*#__PURE__*/React.createElement("select",{onChange:this.setSelectedFeature,value:this.state.selectedFeature},Object.entries(this.state.pickedFeatures).map(function(_ref5){var _match$sublayer$title,_match$sublayer;var _ref6=_slicedToArray(_ref5,2),id=_ref6[0],feature=_ref6[1];var _id$split=id.split("::"),_id$split2=_slicedToArray(_id$split,2),layerId=_id$split2[0],featureId=_id$split2[1];var editConfig=_this2.props.theme.editConfig[layerId];var match=LayerUtils.searchLayer(_this2.props.layers,_this2.props.theme.url,editConfig.layerName);var layerName=(_match$sublayer$title=match===null||match===void 0||(_match$sublayer=match.sublayer)===null||_match$sublayer===void 0?void 0:_match$sublayer.title)!==null&&_match$sublayer$title!==void 0?_match$sublayer$title:editConfig.layerName;var featureName=editConfig.displayField?feature.properties[editConfig.displayField]:featureText+" "+featureId;return/*#__PURE__*/React.createElement("option",{key:id,value:id},layerName+": "+featureName)}))):null,this.props.editContext.feature?/*#__PURE__*/React.createElement(AttributeForm,{editConfig:curConfig,editContext:this.props.editContext,iface:this.props.iface,onCommit:this.updatePickedFeatures}):null)}resultWindow=/*#__PURE__*/React.createElement(ResizeableWindow,{dockable:this.props.geometry.side,icon:"featureform",initialHeight:this.props.geometry.initialHeight,initialWidth:this.props.geometry.initialWidth,initialX:this.props.geometry.initialX,initialY:this.props.geometry.initialY,initiallyDocked:this.props.geometry.initiallyDocked,key:"FeatureForm",onClose:this.onWindowClose,title:LocaleUtils.tr("featureform.title")},body)}return[resultWindow,/*#__PURE__*/React.createElement(TaskBar,{key:"FeatureFormTaskBar",task:"FeatureForm"},function(){return{body:LocaleUtils.tr("infotool.clickhelpPoint")}})]}}])}(React.Component);_defineProperty(FeatureForm,"propTypes",{clearEditContext:PropTypes.func,click:PropTypes.object,currentEditContext:PropTypes.string,editContext:PropTypes.object,enabled:PropTypes.bool,/** Whether to clear the task when the results window is closed. */exitTaskOnResultsClose:PropTypes.bool,filter:PropTypes.object,/** Default window geometry with size, position and docking status. Positive position values (including '0') are related to top (InitialY) and left (InitialX), negative values (including '-0') to bottom (InitialY) and right (InitialX). */geometry:PropTypes.shape({initialWidth:PropTypes.number,initialHeight:PropTypes.number,initialX:PropTypes.number,initialY:PropTypes.number,initiallyDocked:PropTypes.bool,side:PropTypes.string}),iface:PropTypes.object,layers:PropTypes.array,map:PropTypes.object,setCurrentTask:PropTypes.func,setEditContext:PropTypes.func,theme:PropTypes.object});_defineProperty(FeatureForm,"defaultProps",{geometry:{initialWidth:320,initialHeight:480,initialX:0,initialY:0,initiallyDocked:false,side:"left"}});_defineProperty(FeatureForm,"defaultState",{pendingRequests:0,pickedFeatures:null,selectedFeature:""});export default(function(){var iface=arguments.length>0&&arguments[0]!==undefined?arguments[0]:EditingInterface;return connect(function(state){var enabled=state.task.id==="FeatureForm"||state.task.identifyEnabled&&ConfigUtils.getConfigProp("identifyTool",state.theme.current,"Identify")==="FeatureForm";return{click:state.map.click||{modifiers:{}},enabled:enabled,editContext:state.editing.contexts.FeatureForm||{},currentEditContext:state.editing.currentContext,iface:iface,layers:state.layers.flat,filter:state.layers.filter,map:state.map,theme:state.theme.current}},{setCurrentTask:setCurrentTask,clearEditContext:clearEditContext,setEditContext:setEditContext})(FeatureForm)});
21
+ return}var path=[];var sublayer=null;var mapScale=MapUtils.computeForZoom(_this.props.map.scales,_this.props.map.zoom);var layer=_this.props.layers.find(function(l){return l.role===LayerRole.THEME&&(sublayer=LayerUtils.searchSubLayer(l,"name",layerId,path))});if(!layer||!sublayer||!LayerUtils.sublayerVisible(layer,path)||!LayerUtils.layerScaleInRange(sublayer,mapScale)){return}var layerOrder=layer.params.LAYERS.split(",");++pendingRequests;var editDataset=editConfig.editDataset||layerId;var scale=Math.round(MapUtils.computeForZoom(_this.props.map.scales,_this.props.map.zoom));_this.props.iface.getFeature(editDataset,pos,_this.props.map.projection,scale,96,function(featureCollection){if(featureCollection&&!isEmpty(featureCollection.features)){_this.setState(function(state){var newPickedFeatures=Object.fromEntries(Object.entries(_objectSpread(_objectSpread({},state.pickedFeatures),featureCollection.features.reduce(function(res,feature){return _objectSpread(_objectSpread({},res),{},_defineProperty({},layerId+"::"+feature.id,feature))},{}))).sort(function(a,b){var partsA=a[0].split("::");var partsB=b[0].split("::");var diff=layerOrder.indexOf(partsB[0])-layerOrder.indexOf(partsA[0]);return diff===0?partsA[1].localeCompare(partsB[1]):diff}));var selectedFeature=state.pendingRequests<=1&&!state.selectedFeature?Object.keys(newPickedFeatures)[0]:"";return{pickedFeatures:newPickedFeatures,pendingRequests:state.pendingRequests-1,selectedFeature:selectedFeature}})}else{_this.setState(function(state){var _Object$keys$;var selectedFeature=state.pendingRequests<=1&&!state.selectedFeature?(_Object$keys$=Object.keys(state.pickedFeatures)[0])!==null&&_Object$keys$!==void 0?_Object$keys$:"":"";return{pendingRequests:state.pendingRequests-1,selectedFeature:selectedFeature}})}},(_this$props$filter$fi=_this.props.filter.filterParams)===null||_this$props$filter$fi===void 0?void 0:_this$props$filter$fi[sublayer.name],_this.props.filter.filterGeom)});_this.setState({pendingRequests:pendingRequests,pickedFeatures:{},selectedFeature:""})});_defineProperty(_this,"setSelectedFeature",function(ev){_this.setState({selectedFeature:ev.target.value})});_defineProperty(_this,"onWindowClose",function(){_this.clearResults();if(_this.props.exitTaskOnResultsClose){_this.props.setCurrentTask(null)}});_defineProperty(_this,"clearResults",function(){if(!_this.props.editContext.changed){_this.setState(FeatureForm.defaultState)}});_defineProperty(_this,"updatePickedFeatures",function(newfeature){_this.setState(function(state){return{pickedFeatures:Object.entries(state.pickedFeatures).reduce(function(res,_ref3){var _ref4=_slicedToArray(_ref3,2),key=_ref4[0],feature=_ref4[1];res[key]=feature.id===newfeature.id?newfeature:feature;return res},{})}})});_this.state=FeatureForm.defaultState;return _this}_inherits(FeatureForm,_React$Component);return _createClass(FeatureForm,[{key:"componentDidMount",value:function componentDidMount(){if(this.props.enabled){this.props.setEditContext("FeatureForm",{action:"Pick"})}}},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps,prevState){if(this.props.enabled&&this.props.theme&&!prevProps.theme){var startupParams=this.props.startupParams;var haveIc=["1","true"].includes((startupParams.ic||"").toLowerCase());var c=(startupParams.c||"").split(/[;,]/g).map(function(x){return parseFloat(x)||0});if(haveIc&&c.length===2){var mapCrs=this.props.theme.mapCrs;this.queryFeatures(CoordinatesUtils.reproject(c,startupParams.crs||mapCrs,mapCrs))}}else if(this.props.theme!==prevProps.theme){this.clearResults()}else if(!this.props.enabled&&prevProps.enabled){if(this.props.clearResultsOnClose){this.clearResults()}}if(this.props.enabled&&!prevProps.enabled){this.props.setEditContext("FeatureForm",{action:"Pick"})}var isCurrentContext=this.props.editContext.id===this.props.currentEditContext;if(this.props.enabled&&isCurrentContext&&!this.props.editContext.changed&&this.state.pendingRequests===0){var clickPoint=this.queryPoint(prevProps);if(clickPoint){this.queryFeatures(clickPoint)}}if(this.props.enabled&&this.state.selectedFeature!==prevState.selectedFeature){var feature=this.state.pickedFeatures?this.state.pickedFeatures[this.state.selectedFeature]:null;var curLayerId=this.state.selectedFeature.split("::")[0];var curConfig=this.props.theme.editConfig[curLayerId]||{};var canEditGeometry=["Point","LineString","Polygon"].includes((curConfig.geomType||"").replace(/^Multi/,"").replace(/Z$/,""));var editPermissions=curConfig.permissions||{};this.props.setEditContext("FeatureForm",{action:"Pick",feature:feature,changed:false,geomType:curConfig.geomType||null,geomReadOnly:editPermissions.updatable===false||!canEditGeometry})}if(!this.props.enabled&&prevProps.enabled){this.props.clearEditContext("FeatureForm");this.setState(FeatureForm.defaultState)}}},{key:"render",value:function render(){var _this2=this;var resultWindow=null;if(this.state.pickedFeatures!==null){var body=null;if(this.state.pendingRequests>0){body=/*#__PURE__*/React.createElement("div",{className:"feature-query-body",role:"body"},/*#__PURE__*/React.createElement("span",{className:"identify-body-message"},LocaleUtils.tr("featureform.querying")))}else if(isEmpty(this.state.pickedFeatures)){body=/*#__PURE__*/React.createElement("div",{className:"feature-query-body",role:"body"},/*#__PURE__*/React.createElement("span",{className:"identify-body-message"},LocaleUtils.tr("featureform.noresults")))}else{var featureText=LocaleUtils.tr("featureform.feature");var curLayerId=this.state.selectedFeature.split("::")[0];var curConfig=this.props.theme.editConfig[curLayerId];body=/*#__PURE__*/React.createElement("div",{className:"feature-query-body",role:"body"},Object.keys(this.state.pickedFeatures).length>1?/*#__PURE__*/React.createElement("div",{className:"feature-query-selection"},/*#__PURE__*/React.createElement("select",{onChange:this.setSelectedFeature,value:this.state.selectedFeature},Object.entries(this.state.pickedFeatures).map(function(_ref5){var _match$sublayer$title,_match$sublayer;var _ref6=_slicedToArray(_ref5,2),id=_ref6[0],feature=_ref6[1];var _id$split=id.split("::"),_id$split2=_slicedToArray(_id$split,2),layerId=_id$split2[0],featureId=_id$split2[1];var editConfig=_this2.props.theme.editConfig[layerId];var match=LayerUtils.searchLayer(_this2.props.layers,_this2.props.theme.url,editConfig.layerName);var layerName=(_match$sublayer$title=match===null||match===void 0||(_match$sublayer=match.sublayer)===null||_match$sublayer===void 0?void 0:_match$sublayer.title)!==null&&_match$sublayer$title!==void 0?_match$sublayer$title:editConfig.layerName;var featureName=editConfig.displayField?feature.properties[editConfig.displayField]:featureText+" "+featureId;return/*#__PURE__*/React.createElement("option",{key:id,value:id},layerName+": "+featureName)}))):null,this.props.editContext.feature?/*#__PURE__*/React.createElement(AttributeForm,{editConfig:curConfig,editContext:this.props.editContext,iface:this.props.iface,onCommit:this.updatePickedFeatures}):null)}resultWindow=/*#__PURE__*/React.createElement(ResizeableWindow,{dockable:this.props.geometry.side,icon:"featureform",initialHeight:this.props.geometry.initialHeight,initialWidth:this.props.geometry.initialWidth,initialX:this.props.geometry.initialX,initialY:this.props.geometry.initialY,initiallyDocked:this.props.geometry.initiallyDocked,key:"FeatureForm",onClose:this.onWindowClose,title:LocaleUtils.tr("featureform.title")},body)}return[resultWindow,/*#__PURE__*/React.createElement(TaskBar,{key:"FeatureFormTaskBar",task:"FeatureForm"},function(){return{body:LocaleUtils.tr("infotool.clickhelpPoint")}})]}}])}(React.Component);_defineProperty(FeatureForm,"propTypes",{clearEditContext:PropTypes.func,/** Whether to clear the identify results when exiting the identify tool. */clearResultsOnClose:PropTypes.bool,click:PropTypes.object,currentEditContext:PropTypes.string,editContext:PropTypes.object,enabled:PropTypes.bool,/** Whether to clear the task when the results window is closed. */exitTaskOnResultsClose:PropTypes.bool,filter:PropTypes.object,/** Default window geometry with size, position and docking status. Positive position values (including '0') are related to top (InitialY) and left (InitialX), negative values (including '-0') to bottom (InitialY) and right (InitialX). */geometry:PropTypes.shape({initialWidth:PropTypes.number,initialHeight:PropTypes.number,initialX:PropTypes.number,initialY:PropTypes.number,initiallyDocked:PropTypes.bool,side:PropTypes.string}),iface:PropTypes.object,layers:PropTypes.array,map:PropTypes.object,setCurrentTask:PropTypes.func,setEditContext:PropTypes.func,startupParams:PropTypes.object,theme:PropTypes.object});_defineProperty(FeatureForm,"defaultProps",{clearResultsOnClose:true,geometry:{initialWidth:320,initialHeight:480,initialX:0,initialY:0,initiallyDocked:false,side:"left"}});_defineProperty(FeatureForm,"defaultState",{pendingRequests:0,pickedFeatures:null,selectedFeature:""});export default(function(){var iface=arguments.length>0&&arguments[0]!==undefined?arguments[0]:EditingInterface;return connect(function(state){var enabled=state.task.id==="FeatureForm"||state.task.identifyEnabled&&ConfigUtils.getConfigProp("identifyTool",state.theme.current,"Identify")==="FeatureForm";return{click:state.map.click||{modifiers:{}},enabled:enabled,editContext:state.editing.contexts.FeatureForm||{},currentEditContext:state.editing.currentContext,iface:iface,layers:state.layers.flat,filter:state.layers.filter,map:state.map,theme:state.theme.current,startupParams:state.localConfig.startupParams}},{setCurrentTask:setCurrentTask,clearEditContext:clearEditContext,setEditContext:setEditContext})(FeatureForm)});
@@ -16,12 +16,12 @@ _this.imageEl.innerHTML="<img src=\"".concat(src,"\" style=\"width: 100%\" />")}
16
16
  *
17
17
  * The print height profile functionality requires a template located by default at `assets/templates/heightprofileprint.html`
18
18
  * with containing a container element with `id=heightprofilecontainer`.
19
- */var HeightProfile=/*#__PURE__*/function(_React$Component){function HeightProfile(props){var _this3;_classCallCheck(this,HeightProfile);_this3=_callSuper(this,HeightProfile,[props]);_defineProperty(_this3,"state",{data:{},reqId:null,drawnodes:true,printdialog:false});_defineProperty(_this3,"onClose",function(){_this3.setState({data:{},isloading:false});_this3.props.changeMeasurementState(_objectSpread(_objectSpread({},_this3.props.measurement),{},{pickPositionCallback:null}))});_defineProperty(_this3,"renderHeightProfile",function(saveRef,interactive){if(_this3.props.measurement.drawing){return null}if(_this3.state.data.error){return/*#__PURE__*/React.createElement("div",{className:"height-profile-error",role:"body"},LocaleUtils.tr("heightprofile.error")+": "+_this3.state.data.error)}var distanceStr=LocaleUtils.tr("heightprofile.distance");var heightStr=LocaleUtils.tr("heightprofile.height");var aslStr=LocaleUtils.tr("heightprofile.asl");var data={labels:_this3.state.data.x,datasets:[{data:_this3.state.data.y,fill:true,backgroundColor:"rgba(255,0,0,0.5)",borderColor:"rgb(255,0,0)",borderWidth:2,pointRadius:0,order:1},{type:"bubble",data:_this3.state.data.nodes,backgroundColor:"rgb(255, 255, 255)",borderColor:"rgb(255, 0, 0)",borderWidth:2,radius:5,hoverRadius:0,hoverBorderWidth:2,order:0,hidden:!_this3.state.drawnodes}]};// Approx 10 ticks
20
- var stepSizeFact=Math.pow(10,Math.ceil(Math.log10(_this3.state.data.totLength/10)));var stepSize=Math.round(_this3.state.data.totLength/stepSizeFact)*stepSizeFact/10;var prec=_this3.props.heightProfilePrecision;var options={responsive:true,maintainAspectRatio:false,animation:{duration:0},plugins:{legend:{display:false},tooltip:{enabled:interactive,intersect:false,displayColors:false,bodyFont:{weight:"bold"},callbacks:{title:function title(ctx){return distanceStr+": "+MeasureUtils.formatMeasurement(ctx[0].parsed.x,false,"metric")},label:function label(ctx){return heightStr+": "+ctx.parsed.y.toFixed(prec)+" m "+aslStr}}}},scales:{x:{type:"linear",ticks:{stepSize:stepSize,font:{size:10},callback:function callback(value){return value}},title:{display:true,text:distanceStr+" [m]",padding:0},max:Math.ceil(_this3.state.data.totLength)},y:{ticks:{font:{size:10},callback:function callback(value){return value.toFixed(prec)}},title:{display:true,text:heightStr+" [m "+aslStr+"]"},max:Math.ceil(_this3.state.data.maxY)}},onHover:interactive?function(evt,activeEls,chart){var chartArea=chart.chartArea;var chartX=Math.min(Math.max(evt.x-chartArea.left),chartArea.width);_this3.updateMarker(chartX/chartArea.width*_this3.state.data.totLength)}:undefined};return/*#__PURE__*/React.createElement("div",{className:"height-profile-chart-container",role:"body",style:{position:"relative"}},/*#__PURE__*/React.createElement(Line,{data:data,options:options,ref:saveRef}))});_defineProperty(_this3,"resizeChart",function(){if(_this3.chart){_this3.chart.resize()}});_defineProperty(_this3,"updateMarker",function(x){var segmentLengths=_this3.props.measurement.segment_lengths;var coo=_this3.props.measurement.coordinates;if(isEmpty(segmentLengths)||isEmpty(coo)){return}var i=0;var runl=0;while(i<segmentLengths.length-1&&x>runl+segmentLengths[i]){runl+=segmentLengths[i++]}var lambda=(x-runl)/segmentLengths[i];var p=[coo[i][0]+lambda*(coo[i+1][0]-coo[i][0]),coo[i][1]+lambda*(coo[i+1][1]-coo[i][1])];_this3.props.addMarker("heightprofile",p,"",_this3.props.projection,1000001);// 1000001: one higher than the zIndex in MeasurementSupport...
21
- });_defineProperty(_this3,"showTooltip",function(idx){if(!_this3.chart){return}var chartArea=_this3.chart.chartArea;_this3.chart.tooltip.setActiveElements([{datasetIndex:0,index:idx}],{x:(chartArea.left+chartArea.right)/2,y:(chartArea.top+chartArea.bottom)/2});_this3.chart.update()});_defineProperty(_this3,"clearMarkerAndTooltip",function(){_this3.props.removeMarker("heightprofile");if(_this3.chart){_this3.chart.tooltip.setActiveElements([],{x:0,y:0})}});_defineProperty(_this3,"pickPositionCallback",function(pos){if(!pos||!_this3.state.data){_this3.clearMarkerAndTooltip();return}// Find sample index
22
- var segmentLengths=_this3.props.measurement.segment_lengths;var coo=_this3.props.measurement.coordinates;var x=0;for(var iSegment=0;iSegment<coo.length-1;++iSegment){if(_this3.pointOnSegment(pos,coo[iSegment],coo[iSegment+1])){var len=MeasureUtils.computeSegmentLengths([pos,coo[iSegment]],_this3.props.projection,_this3.props.measurement.geodesic)[0];x+=len;break}else{x+=segmentLengths[iSegment]}}var k=Math.min(1,x/_this3.state.data.totLength);var idx=Math.min(_this3.state.data.y.length-1,Math.floor(k*_this3.props.samples));_this3.showTooltip(idx)});_defineProperty(_this3,"pointOnSegment",function(q,p1,p2){var tol=1E-3;// Determine whether points lie on same line: cross-product (P2-P1) x (Q - P1) zero?
19
+ */var HeightProfile=/*#__PURE__*/function(_React$Component){function HeightProfile(props){var _this3;_classCallCheck(this,HeightProfile);_this3=_callSuper(this,HeightProfile,[props]);_defineProperty(_this3,"state",{data:{},selectedDatasetIndex:0,reqId:null,drawnodes:true,printdialog:false});_defineProperty(_this3,"onClose",function(){_this3.setState({data:{},isloading:false});_this3.props.changeMeasurementState(_objectSpread(_objectSpread({},_this3.props.measurement),{},{pickPositionCallback:null}))});_defineProperty(_this3,"renderHeightProfile",function(saveRef,interactive){if(_this3.props.measurement.drawing){return null}if(_this3.state.data.error){return/*#__PURE__*/React.createElement("div",{className:"height-profile-error",role:"body"},LocaleUtils.tr("heightprofile.error")+": "+_this3.state.data.error)}var distanceStr=LocaleUtils.tr("heightprofile.distance");var heightStr=LocaleUtils.tr("heightprofile.height");var aslStr=LocaleUtils.tr("heightprofile.asl");var selectedDataset=_this3.state.data[_this3.state.selectedDatasetIndex];var data={labels:selectedDataset.x,datasets:[{data:selectedDataset.y,fill:true,backgroundColor:"rgba(255,0,0,0.5)",borderColor:"rgb(255,0,0)",borderWidth:2,pointRadius:0,order:1},{type:"bubble",data:selectedDataset.nodes,backgroundColor:"rgb(255, 255, 255)",borderColor:"rgb(255, 0, 0)",borderWidth:2,radius:5,hoverRadius:0,hoverBorderWidth:2,order:0,hidden:!_this3.state.drawnodes}]};// Approx 10 ticks
20
+ var stepSizeFact=Math.pow(10,Math.ceil(Math.log10(selectedDataset.totLength/10)));var stepSize=Math.round(selectedDataset.totLength/stepSizeFact)*stepSizeFact/10;var prec=_this3.props.heightProfilePrecision;var options={responsive:true,maintainAspectRatio:false,animation:{duration:0},plugins:{legend:{display:false},tooltip:{enabled:interactive,intersect:false,displayColors:false,bodyFont:{weight:"bold"},callbacks:{title:function title(ctx){return distanceStr+": "+MeasureUtils.formatMeasurement(ctx[0].parsed.x,false,"metric")},label:function label(ctx){return heightStr+": "+ctx.parsed.y.toFixed(prec)+" m "+aslStr}}}},scales:{x:{type:"linear",ticks:{stepSize:stepSize,font:{size:10},callback:function callback(value){return value}},title:{display:true,text:distanceStr+" [m]",padding:0},max:Math.ceil(selectedDataset.totLength)},y:{ticks:{font:{size:10},callback:function callback(value){return value.toFixed(prec)}},title:{display:true,text:heightStr+" [m "+aslStr+"]"},max:Math.ceil(selectedDataset.maxY)}},onHover:interactive?function(evt,activeEls,chart){var chartArea=chart.chartArea;var chartX=Math.min(Math.max(evt.x-chartArea.left),chartArea.width);_this3.updateMarker(chartX/chartArea.width*selectedDataset.totLength)}:undefined};var datasetSelector=null;if(_this3.state.data.length>1){datasetSelector=/*#__PURE__*/React.createElement("select",{className:"height-profile-dataset-select",onChange:function onChange(e){return _this3.setState({selectedDatasetIndex:parseInt(e.target.value,10)})},value:_this3.state.selectedDatasetIndex},_this3.state.data.map(function(dataset,idx){return/*#__PURE__*/React.createElement("option",{key:idx,value:idx},dataset.dataset?dataset.dataset:"<unnamed>")}))}return/*#__PURE__*/React.createElement("div",{className:"height-profile-chart-container",role:"body",style:{position:"relative"}},datasetSelector,/*#__PURE__*/React.createElement(Line,{data:data,options:options,ref:saveRef}))});_defineProperty(_this3,"resizeChart",function(){if(_this3.chart){_this3.chart.resize()}});_defineProperty(_this3,"updateMarker",function(x){var segmentLengths=_this3.props.measurement.segment_lengths;var coo=_this3.props.measurement.coordinates;if(isEmpty(segmentLengths)||isEmpty(coo)){return}var i=0;var runl=0;while(i<segmentLengths.length-1&&x>runl+segmentLengths[i]){runl+=segmentLengths[i++]}var lambda=(x-runl)/segmentLengths[i];var p=[coo[i][0]+lambda*(coo[i+1][0]-coo[i][0]),coo[i][1]+lambda*(coo[i+1][1]-coo[i][1])];_this3.props.addMarker("heightprofile",p,"",_this3.props.projection,1000001);// 1000001: one higher than the zIndex in MeasurementSupport...
21
+ });_defineProperty(_this3,"showTooltip",function(idx){if(!_this3.chart){return}var chartArea=_this3.chart.chartArea;_this3.chart.tooltip.setActiveElements([{datasetIndex:0,index:idx}],{x:(chartArea.left+chartArea.right)/2,y:(chartArea.top+chartArea.bottom)/2});_this3.chart.update()});_defineProperty(_this3,"clearMarkerAndTooltip",function(){_this3.props.removeMarker("heightprofile");if(_this3.chart){_this3.chart.tooltip.setActiveElements([],{x:0,y:0})}});_defineProperty(_this3,"pickPositionCallback",function(pos){if(!pos||isEmpty(_this3.state.data)){_this3.clearMarkerAndTooltip();return}var data=_this3.state.data[_this3.state.selectedDatasetIndex];// Find sample index
22
+ var segmentLengths=_this3.props.measurement.segment_lengths;var coo=_this3.props.measurement.coordinates;var x=0;for(var iSegment=0;iSegment<coo.length-1;++iSegment){if(_this3.pointOnSegment(pos,coo[iSegment],coo[iSegment+1])){var len=MeasureUtils.computeSegmentLengths([pos,coo[iSegment]],_this3.props.projection,_this3.props.measurement.geodesic)[0];x+=len;break}else{x+=segmentLengths[iSegment]}}var k=Math.min(1,x/data.totLength);var idx=Math.min(data.y.length-1,Math.floor(k*_this3.props.samples));_this3.showTooltip(idx)});_defineProperty(_this3,"pointOnSegment",function(q,p1,p2){var tol=1E-3;// Determine whether points lie on same line: cross-product (P2-P1) x (Q - P1) zero?
23
23
  var cross=(p2[0]-p1[0])*(q[1]-p1[1])-(q[0]-p1[0])*(p2[1]-p1[1]);if(Math.abs(cross)>tol){return false}// Determine if coordinates lie within segment coordinates
24
- if(Math.abs(p1[0]-p2[0])>tol){return p1[0]<=q[0]&&q[0]<=p2[0]||p2[0]<=q[0]&&q[0]<=p1[0]}else{return p1[1]<=q[1]&&q[1]<=p2[1]||p2[1]<=q[1]&&q[1]<=p1[1]}});_defineProperty(_this3,"exportProfile",function(){if(!_this3.state.data.x){return}var csv="";csv+="index"+"\t"+"distance"+"\t"+"elevation"+"\n";_this3.state.data.x.forEach(function(x,idx){var sample={x:x,y:_this3.state.data.y[idx]};var prec=_this3.props.heightProfilePrecision;var distance=Math.round(sample.x*Math.pow(10,prec))/Math.pow(10,prec);var height=Math.round(sample.y*Math.pow(10,prec))/Math.pow(10,prec);csv+=String(idx).replace("\"","\"\"")+"\t"+String(distance)+"\t"+String(height)+"\n"});FileSaver.saveAs(new Blob([csv],{type:"text/plain;charset=utf-8"}),"heightprofile.csv")});_this3.chart=null;_this3.profilePrintWindow=null;return _this3}_inherits(HeightProfile,_React$Component);return _createClass(HeightProfile,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){if(this.props.measurement.coordinates!==prevProps.measurement.coordinates){if(this.props.measurement.drawing===false&&this.props.measurement.geomType==="LineString"&&!isEmpty(this.props.measurement.coordinates)){this.queryElevations(this.props.measurement.coordinates,this.props.measurement.segment_lengths,this.props.projection)}else if(!isEmpty(this.state.data)){this.setState({data:{}});this.props.changeMeasurementState(_objectSpread(_objectSpread({},this.props.measurement),{},{pickPositionCallback:null}))}}}},{key:"queryElevations",value:function queryElevations(coordinates,distances,projection){var _this4=this;var reqId=uuidv1();this.setState({reqId:reqId});var totLength=this.props.measurement.length;getElevationInterface().getProfile(coordinates,distances,projection,this.props.samples).then(function(elevations){// Request changed
25
- if(_this4.state.reqId!==reqId){return}// Compute x-axis distances and get node points
26
- var nodes=[];var cumDist=distances[0];var distIdx=0;var y=elevations;var x=y.map(function(entry,idx,a){var dist=(idx/(a.length-1)*totLength).toFixed(0);if(dist>=cumDist){nodes.push({x:dist,y:y[idx]});cumDist+=distances[++distIdx]}return dist});// First and last node
27
- nodes.unshift({x:x[0],y:y[0]});nodes.push({x:x[x.length-1],y:y[y.length-1]});var data={x:x,y:elevations,maxY:Math.max.apply(Math,_toConsumableArray(elevations)),totLength:totLength,nodes:nodes};_this4.setState({reqId:null,data:data});_this4.props.changeMeasurementState(_objectSpread(_objectSpread({},_this4.props.measurement),{},{pickPositionCallback:_this4.pickPositionCallback}))})["catch"](function(error){_this4.setState({reqId:null,data:error?{error:error}:{}})})}},{key:"render",value:function render(){var _this5=this;if(isEmpty(this.state.data)&&!this.state.isloading){return null}var extraControls=[{icon:"circle",active:this.state.drawnodes,callback:function callback(){return _this5.setState(function(state){return{drawnodes:!state.drawnodes}})},title:LocaleUtils.tr("heightprofile.drawnodes")},{icon:"export",callback:this.exportProfile,title:LocaleUtils.tr("heightprofile.export")},{icon:"print",active:this.state.printdialog,callback:function callback(){return _this5.setState(function(state){return{printdialog:!state.printdialog}})},title:LocaleUtils.tr("heightprofile.print")}];return[/*#__PURE__*/React.createElement(ResizeableWindow,{dockable:"bottom",extraControls:extraControls,icon:"line",initialHeight:this.props.height,initialWidth:600,initiallyDocked:true,key:"ProfileDialog",onClose:this.onClose,onExternalWindowResized:this.resizeChart,splitScreenWhenDocked:true,title:LocaleUtils.tr("heightprofile.title"),usePortal:false},this.state.isloading?/*#__PURE__*/React.createElement("div",{className:"height-profile-loading-indicator",role:"body"},/*#__PURE__*/React.createElement(Spinner,{className:"spinner"})," ",LocaleUtils.tr("heightprofile.loading")):this.renderHeightProfile(function(el){_this5.chart=el},true)),this.state.printdialog?/*#__PURE__*/React.createElement(HeightProfilePrintDialog,{key:"ProfilePrintDialog",measurement:this.props.measurement,onClose:function onClose(){return _this5.setState({printdialog:false})},templatePath:this.props.templatePath},this.renderHeightProfile):null]}}])}(React.Component);_defineProperty(HeightProfile,"propTypes",{addMarker:PropTypes.func,changeMeasurementState:PropTypes.func,/** The height of the height profile widget in pixels. */height:PropTypes.number,/** The precision of displayed and exported values (0: no decimals, 1: 1 decimal position, etc). */heightProfilePrecision:PropTypes.number,measurement:PropTypes.object,projection:PropTypes.string,removeMarker:PropTypes.func,/** The number of elevation samples to query. */samples:PropTypes.number,/** Template location for the height profile print functionality */templatePath:PropTypes.string});_defineProperty(HeightProfile,"defaultProps",{samples:500,heightProfilePrecision:0,height:150,templatePath:":/templates/heightprofileprint.html"});export default connect(function(state){return{measurement:state.measurement,projection:state.map.projection}},{addMarker:addMarker,changeMeasurementState:changeMeasurementState,removeMarker:removeMarker})(HeightProfile);
24
+ if(Math.abs(p1[0]-p2[0])>tol){return p1[0]<=q[0]&&q[0]<=p2[0]||p2[0]<=q[0]&&q[0]<=p1[0]}else{return p1[1]<=q[1]&&q[1]<=p2[1]||p2[1]<=q[1]&&q[1]<=p1[1]}});_defineProperty(_this3,"exportProfile",function(){var data=_this3.state.data[_this3.state.selectedDatasetIndex];if(!data.x){return}var csv="";csv+="index"+"\t"+"distance"+"\t"+"elevation"+"\n";data.x.forEach(function(x,idx){var sample={x:x,y:data.y[idx]};var prec=_this3.props.heightProfilePrecision;var distance=Math.round(sample.x*Math.pow(10,prec))/Math.pow(10,prec);var height=Math.round(sample.y*Math.pow(10,prec))/Math.pow(10,prec);csv+=String(idx).replace("\"","\"\"")+"\t"+String(distance)+"\t"+String(height)+"\n"});FileSaver.saveAs(new Blob([csv],{type:"text/plain;charset=utf-8"}),"heightprofile.csv")});_this3.chart=null;_this3.profilePrintWindow=null;return _this3}_inherits(HeightProfile,_React$Component);return _createClass(HeightProfile,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){if(this.props.measurement.coordinates!==prevProps.measurement.coordinates){if(this.props.measurement.drawing===false&&this.props.measurement.geomType==="LineString"&&!isEmpty(this.props.measurement.coordinates)){this.queryElevations(this.props.measurement.coordinates,this.props.measurement.segment_lengths,this.props.projection)}else if(!isEmpty(this.state.data)){this.setState({data:{}});this.props.changeMeasurementState(_objectSpread(_objectSpread({},this.props.measurement),{},{pickPositionCallback:null}))}}}},{key:"queryElevations",value:function queryElevations(coordinates,distances,projection){var _this4=this;var reqId=uuidv1();this.setState({reqId:reqId});var totLength=this.props.measurement.length;getElevationInterface().getProfile(coordinates,distances,projection,this.props.samples).then(function(response){// Request changed
25
+ if(_this4.state.reqId!==reqId){return}var elevationsList=response.list;if(!elevationsList){elevationsList=[{elevations:response,dataset:null}]}var data=elevationsList.map(function(entry,index){var elevations=entry.elevations;// Compute x-axis distances and get node points
26
+ var nodes=[];var cumDist=distances[0];var distIdx=0;var y=elevations;var x=y.map(function(value,idx,a){var dist=(idx/(a.length-1)*totLength).toFixed(0);if(dist>=cumDist){nodes.push({x:dist,y:y[idx]});cumDist+=distances[++distIdx]}return dist});// First and last node
27
+ nodes.unshift({x:x[0],y:y[0]});nodes.push({x:x[x.length-1],y:y[y.length-1]});return{dataset:entry.dataset,x:x,y:elevations,maxY:Math.max.apply(Math,_toConsumableArray(elevations)),totLength:totLength,nodes:nodes}});_this4.setState(function(prevState){return{reqId:null,data:data,selectedDatasetIndex:prevState.selectedDatasetIndex<=data.length?prevState.selectedDatasetIndex:0}});_this4.props.changeMeasurementState(_objectSpread(_objectSpread({},_this4.props.measurement),{},{pickPositionCallback:_this4.pickPositionCallback}))})["catch"](function(error){_this4.setState({reqId:null,data:error?{error:error}:{}})})}},{key:"render",value:function render(){var _this5=this;if(isEmpty(this.state.data)&&!this.state.isloading){return null}var extraControls=[{icon:"circle",active:this.state.drawnodes,callback:function callback(){return _this5.setState(function(state){return{drawnodes:!state.drawnodes}})},title:LocaleUtils.tr("heightprofile.drawnodes")},{icon:"export",callback:this.exportProfile,title:LocaleUtils.tr("heightprofile.export")},{icon:"print",active:this.state.printdialog,callback:function callback(){return _this5.setState(function(state){return{printdialog:!state.printdialog}})},title:LocaleUtils.tr("heightprofile.print")}];return[/*#__PURE__*/React.createElement(ResizeableWindow,{dockable:"bottom",extraControls:extraControls,icon:"line",initialHeight:this.props.height,initialWidth:600,initiallyDocked:true,key:"ProfileDialog",onClose:this.onClose,onExternalWindowResized:this.resizeChart,splitScreenWhenDocked:true,title:LocaleUtils.tr("heightprofile.title"),usePortal:false},this.state.isloading?/*#__PURE__*/React.createElement("div",{className:"height-profile-loading-indicator",role:"body"},/*#__PURE__*/React.createElement(Spinner,{className:"spinner"})," ",LocaleUtils.tr("heightprofile.loading")):this.renderHeightProfile(function(el){_this5.chart=el},true)),this.state.printdialog?/*#__PURE__*/React.createElement(HeightProfilePrintDialog,{key:"ProfilePrintDialog",measurement:this.props.measurement,onClose:function onClose(){return _this5.setState({printdialog:false})},templatePath:this.props.templatePath},this.renderHeightProfile):null]}}])}(React.Component);_defineProperty(HeightProfile,"propTypes",{addMarker:PropTypes.func,changeMeasurementState:PropTypes.func,/** The height of the height profile widget in pixels. */height:PropTypes.number,/** The precision of displayed and exported values (0: no decimals, 1: 1 decimal position, etc). */heightProfilePrecision:PropTypes.number,measurement:PropTypes.object,projection:PropTypes.string,removeMarker:PropTypes.func,/** The number of elevation samples to query. */samples:PropTypes.number,/** Template location for the height profile print functionality */templatePath:PropTypes.string});_defineProperty(HeightProfile,"defaultProps",{samples:500,heightProfilePrecision:0,height:150,templatePath:":/templates/heightprofileprint.html"});export default connect(function(state){return{measurement:state.measurement,projection:state.map.projection}},{addMarker:addMarker,changeMeasurementState:changeMeasurementState,removeMarker:removeMarker})(HeightProfile);
@@ -4,7 +4,7 @@ function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof
4
4
  *
5
5
  * This source code is licensed under the BSD-style license found in the
6
6
  * LICENSE file in the root directory of this source tree.
7
- */import React from"react";import{connect}from"react-redux";import isEmpty from"lodash.isempty";import PropTypes from"prop-types";import{LayerRole,addLayerFeatures,addMarker,removeMarker,removeLayer}from"../actions/layers";import{setCurrentTask}from"../actions/task";import IdentifyViewer from"../components/IdentifyViewer";import MapSelection from"../components/MapSelection";import ResizeableWindow from"../components/ResizeableWindow";import TaskBar from"../components/TaskBar";import NumberInput from"../components/widgets/NumberInput";import ConfigUtils from"../utils/ConfigUtils";import IdentifyUtils from"../utils/IdentifyUtils";import LocaleUtils from"../utils/LocaleUtils";import MeasureUtils from"../utils/MeasureUtils";import VectorLayerUtils from"../utils/VectorLayerUtils";import"./style/Identify.css";/**
7
+ */import React from"react";import{connect}from"react-redux";import isEmpty from"lodash.isempty";import PropTypes from"prop-types";import{LayerRole,addLayerFeatures,addMarker,removeMarker,removeLayer}from"../actions/layers";import{setCurrentTask}from"../actions/task";import IdentifyViewer from"../components/IdentifyViewer";import MapSelection from"../components/MapSelection";import ResizeableWindow from"../components/ResizeableWindow";import TaskBar from"../components/TaskBar";import NumberInput from"../components/widgets/NumberInput";import ConfigUtils from"../utils/ConfigUtils";import CoordinatesUtils from"../utils/CoordinatesUtils";import IdentifyUtils from"../utils/IdentifyUtils";import LocaleUtils from"../utils/LocaleUtils";import MeasureUtils from"../utils/MeasureUtils";import VectorLayerUtils from"../utils/VectorLayerUtils";import"./style/Identify.css";/**
8
8
  * Displays queried feature attributes.
9
9
  *
10
10
  * Uses WMS GetFeatureInfo to query features and displays the result in
@@ -15,4 +15,4 @@ function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof
15
15
  * for customized queries and templates for the result presentation.
16
16
  */var Identify=/*#__PURE__*/function(_React$Component){function Identify(){var _this;_classCallCheck(this,Identify);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this=_callSuper(this,Identify,[].concat(args));_defineProperty(_this,"state",{mode:"Point",identifyResults:null,pendingRequests:0,radius:0,radiusUnits:_this.props.initialRadiusUnits,exitTaskOnResultsClose:null,filterGeom:null,filterGeomModifiers:{}});_defineProperty(_this,"identifyPoint",function(clickPoint){if(clickPoint){_this.setState(function(state){// Remove any search selection layer to avoid confusion
17
17
  _this.props.removeLayer("searchselection");var pendingRequests=0;var identifyResults=_this.props.click.modifiers.ctrl!==true?{}:state.identifyResults;var queryableLayers=[];queryableLayers=IdentifyUtils.getQueryLayers(_this.props.layers,_this.props.map);queryableLayers.forEach(function(l){var request=IdentifyUtils.buildRequest(l,l.queryLayers.join(","),clickPoint,_this.props.map,_this.props.params);++pendingRequests;IdentifyUtils.sendRequest(request,function(response){_this.setState(function(state2){return{pendingRequests:state2.pendingRequests-1}});if(response){_this.parseResult(response,l,request.params.info_format,clickPoint)}})});if(!isEmpty(_this.props.click.features)){_this.props.click.features.forEach(function(feature){var layer=_this.props.layers.find(function(l){return l.id===feature.layerId});if((layer===null||layer===void 0?void 0:layer.role)===LayerRole.USERLAYER){var _layer$features$find,_layer$features,_layer$features$find2,_layer$projection;var queryFeature=_objectSpread({},(_layer$features$find=(_layer$features=layer.features)===null||_layer$features===void 0||(_layer$features$find2=_layer$features.find)===null||_layer$features$find2===void 0?void 0:_layer$features$find2.call(_layer$features,function(f){return f.id===feature.id}))!==null&&_layer$features$find!==void 0?_layer$features$find:feature);if(!(queryFeature!==null&&queryFeature!==void 0&&queryFeature.properties)){return}if(!identifyResults[layer.name]){identifyResults[layer.name]=[]}queryFeature.crs=(_layer$projection=layer.projection)!==null&&_layer$projection!==void 0?_layer$projection:_this.props.map.projection;queryFeature.displayname=queryFeature.properties.name||queryFeature.properties.Name||queryFeature.properties.NAME||queryFeature.properties.label||queryFeature.properties.id||queryFeature.id;queryFeature.layertitle=layer.title||layer.name||layer.id;queryFeature.properties=Object.entries(queryFeature.properties).reduce(function(res,_ref){var _ref2=_slicedToArray(_ref,2),key=_ref2[0],val=_ref2[1];return _objectSpread(_objectSpread({},res),{},_defineProperty({},key,_typeof(val)==="object"?JSON.stringify(val):val))},{});identifyResults[layer.name].push(queryFeature)}})}_this.props.addMarker("identify",clickPoint,"",_this.props.map.projection);return{identifyResults:identifyResults,pendingRequests:pendingRequests}})}});_defineProperty(_this,"queryPoint",function(prevProps){if(_this.props.click.button!==0||_this.props.click===prevProps.click||(_this.props.click.features||[]).find(function(feature){return feature.id==="startupposmarker"})){return null}var searchMarker=(_this.props.click.features||[]).find(function(feature){return feature.id==="searchmarker"});if(searchMarker&&searchMarker.geometry.type==="Point"){return searchMarker.geometry.coordinates}return _this.props.click.coordinate});_defineProperty(_this,"identifyRegion",function(){var queryableLayers=IdentifyUtils.getQueryLayers(_this.props.layers,_this.props.map);var poly=_this.state.filterGeom.coordinates[0];if(poly.length<3||isEmpty(queryableLayers)){return}var identifyResults=_this.state.filterGeomModifiers.ctrl!==true?{}:_this.state.identifyResults;var center=[0,0];poly.forEach(function(point){center[0]+=point[0];center[1]+=point[1]});center[0]/=poly.length;center[1]/=poly.length;var filter=VectorLayerUtils.geoJSONGeomToWkt(_this.state.filterGeom);var pendingRequests=0;var params=_objectSpread({},_this.props.params);if(_this.props.params.region_feature_count){params.feature_count=_this.props.params.region_feature_count;delete params.region_feature_count}queryableLayers.forEach(function(layer){var request=IdentifyUtils.buildFilterRequest(layer,layer.queryLayers.join(","),filter,_this.props.map,params);++pendingRequests;IdentifyUtils.sendRequest(request,function(response){_this.setState(function(state){return{pendingRequests:state.pendingRequests-1}});if(response){_this.parseResult(response,layer,request.params.info_format,center)}});_this.setState({identifyResults:identifyResults,pendingRequests:pendingRequests})})});_defineProperty(_this,"identifyRadius",function(){var clickPoint=_this.state.filterGeom.center;var queryableLayers=IdentifyUtils.getQueryLayers(_this.props.layers,_this.props.map);if(isEmpty(queryableLayers)){return}var identifyResults=_this.state.filterGeomModifiers.ctrl!==true?{}:_this.state.identifyResults;var filter=VectorLayerUtils.geoJSONGeomToWkt(_this.state.filterGeom);var pendingRequests=0;var params=_objectSpread({},_this.props.params);if(_this.props.params.radius_feature_count){params.feature_count=_this.props.params.radius_feature_count;delete params.radius_feature_count}queryableLayers.forEach(function(layer){var request=IdentifyUtils.buildFilterRequest(layer,layer.queryLayers.join(","),filter,_this.props.map,params);++pendingRequests;IdentifyUtils.sendRequest(request,function(response){_this.setState(function(state){return{pendingRequests:state.pendingRequests-1}});if(response){_this.parseResult(response,layer,request.params.info_format,clickPoint)}});_this.setState({identifyResults:identifyResults,pendingRequests:pendingRequests})});_this.props.addMarker("identify",clickPoint,"",_this.props.map.projection)});_defineProperty(_this,"changeBufferUnit",function(ev){_this.setState({radiusUnits:ev.target.value})});_defineProperty(_this,"parseResult",function(response,layer,format,clickPoint){var newResults=IdentifyUtils.parseResponse(response,layer,format,clickPoint,_this.props.map.projection,_this.props.featureInfoReturnsLayerName);// Merge with previous
18
- _this.setState(function(state){var identifyResults=_objectSpread({},state.identifyResults);Object.entries(newResults).forEach(function(_ref3){var _ref4=_slicedToArray(_ref3,2),layername=_ref4[0],features=_ref4[1];var key=layer.url+"#"+layername;identifyResults[key]=features.reduce(function(result,feature){if(result.find(function(f){return f.id===feature.id})===undefined){result.push(feature)}return result},identifyResults[key]||[])});return{identifyResults:identifyResults}})});_defineProperty(_this,"onShow",function(mode,data){_this.setState({mode:mode||"Point",exitTaskOnResultsClose:data===null||data===void 0?void 0:data.exitTaskOnResultsClose});if(mode==="Point"&&data!==null&&data!==void 0&&data.pos){_this.identifyPoint(data.pos)}});_defineProperty(_this,"onToolClose",function(){_this.setState({mode:"Point",exitTaskOnResultsClose:null,filterGeom:null});if(_this.props.clearResultsOnClose){_this.clearResults()}});_defineProperty(_this,"onWindowClose",function(){_this.clearResults();if(_this.state.exitTaskOnResultsClose||_this.props.exitTaskOnResultsClose){_this.props.setCurrentTask(null)}});_defineProperty(_this,"clearResults",function(){_this.props.removeMarker("identify");_this.props.removeLayer("identifyslection");_this.props.removeLayer("identifyradiusbuffer");_this.setState({identifyResults:null,pendingRequests:0})});_defineProperty(_this,"updateRadius",function(radius,units){_this.setState(function(state){return{radius:radius,radiusUnits:units,filterGeom:_objectSpread(_objectSpread({},state.filterGeom),{},{radius:MeasureUtils.convertLength(radius,units,"m")})}})});_defineProperty(_this,"renderBody",function(){if(_this.state.mode==="Point"){return LocaleUtils.tr("infotool.clickhelpPoint")}else if(_this.state.mode==="Region"){return LocaleUtils.tr("infotool.clickhelpPolygon")}else if(_this.state.mode==="Radius"){var text=LocaleUtils.tr("infotool.clickhelpRadius");return/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("div",null,text),/*#__PURE__*/React.createElement("div",{className:"identify-radius-controls controlgroup"},/*#__PURE__*/React.createElement("span",null,LocaleUtils.tr("infotool.radius"),":\xA0"),/*#__PURE__*/React.createElement(NumberInput,{disabled:!_this.state.filterGeom,max:1000000,min:1,mobile:true,onChange:function onChange(rad){return _this.updateRadius(rad,_this.state.radiusUnits)},value:_this.state.radius}),/*#__PURE__*/React.createElement("select",{onChange:function onChange(ev){return _this.updateRadius(_this.state.radius,ev.target.value)},value:_this.state.radiusUnits},/*#__PURE__*/React.createElement("option",{value:"m"},"m"),/*#__PURE__*/React.createElement("option",{value:"ft"},"ft"),/*#__PURE__*/React.createElement("option",{value:"km"},"km"),/*#__PURE__*/React.createElement("option",{value:"mi"},"mi"))))}return null});return _this}_inherits(Identify,_React$Component);return _createClass(Identify,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps,prevState){if(this.props.theme!==prevProps.theme){this.clearResults()}else if(!this.props.enabled&&prevProps.enabled){if(this.props.clearResultsOnClose){this.clearResults()}}if(this.props.enabled){if(this.state.mode==="Point"){var clickPoint=this.queryPoint(prevProps);this.identifyPoint(clickPoint)}else if(this.state.mode==="Region"){if(this.state.filterGeom&&this.state.filterGeom!==prevState.filterGeom){this.identifyRegion()}}else if(this.state.mode==="Radius"){if(this.state.filterGeom&&this.state.filterGeom!==prevState.filterGeom){this.setState(function(state){return{radius:MeasureUtils.convertLength(state.filterGeom.radius,"m",state.radiusUnits)}});this.identifyRadius()}}}}},{key:"render",value:function render(){var _this2=this;var resultWindow=null;if(this.state.pendingRequests>0||this.state.identifyResults!==null){var body=null;if(isEmpty(this.state.identifyResults)){if(this.state.pendingRequests>0){body=/*#__PURE__*/React.createElement("div",{className:"identify-body",role:"body"},/*#__PURE__*/React.createElement("span",{className:"identify-body-message"},LocaleUtils.tr("identify.querying")))}else{body=/*#__PURE__*/React.createElement("div",{className:"identify-body",role:"body"},/*#__PURE__*/React.createElement("span",{className:"identify-body-message"},LocaleUtils.tr("identify.noresults")))}}else{body=/*#__PURE__*/React.createElement(IdentifyViewer,{attributeCalculator:this.props.attributeCalculator,attributeTransform:this.props.attributeTransform,customExporters:this.props.customExporters,displayResultTree:this.props.displayResultTree,enableAggregatedReports:this.props.enableAggregatedReports,enableExport:this.props.enableExport,exportGeometry:this.props.exportGeometry,highlightAllResults:this.props.highlightAllResults,identifyResults:this.state.identifyResults,iframeDialogsInitiallyDocked:this.props.iframeDialogsInitiallyDocked,longAttributesDisplay:this.props.longAttributesDisplay,replaceImageUrls:this.props.replaceImageUrls,role:"body",showLayerSelector:this.props.showLayerSelector})}resultWindow=/*#__PURE__*/React.createElement(ResizeableWindow,{busyIcon:this.state.pendingRequests>0,dockable:this.props.geometry.side,icon:"info-sign",initialHeight:this.props.geometry.initialHeight,initialWidth:this.props.geometry.initialWidth,initialX:this.props.geometry.initialX,initialY:this.props.geometry.initialY,initiallyDocked:this.props.geometry.initiallyDocked,key:"IdentifyWindow",onClose:this.onWindowClose,title:LocaleUtils.tr("identify.title")},body)}return[resultWindow,/*#__PURE__*/React.createElement(TaskBar,{key:"IdentifyTaskBar",onHide:this.onToolClose,onShow:this.onShow,task:"Identify"},function(){return{body:_this2.renderBody()}}),this.state.mode==="Region"||this.state.mode==="Radius"?/*#__PURE__*/React.createElement(MapSelection,{active:true,geomType:this.state.mode==="Radius"?"Circle":"Polygon",geometry:this.state.filterGeom,geometryChanged:function geometryChanged(geom,mod){return _this2.setState({filterGeom:geom,filterGeomModifiers:mod})},key:"MapSelection",measure:this.state.mode==="Radius"}):null]}}])}(React.Component);_defineProperty(Identify,"propTypes",{addLayerFeatures:PropTypes.func,addMarker:PropTypes.func,/** Optional function for computing derived attributes. See js/IdentifyExtensions.js for details. This prop can be specified in the appConfig.js cfg section. */attributeCalculator:PropTypes.func,/** Optional function for transforming attribute values. See js/IdentifyExtensions.js for details. This prop can be specified in the appConfig.js cfg section. */attributeTransform:PropTypes.func,/** Whether to clear the identify results when exiting the identify tool. */clearResultsOnClose:PropTypes.bool,click:PropTypes.object,currentIdentifyTool:PropTypes.string,currentTask:PropTypes.string,/** Optional list of custom exporters to offer along with the built-in exporters. See js/IdentifyExtensions.js for details. This prop can be specified in the appConfig.js cfg section. */customExporters:PropTypes.array,/** Whether to display a tree overview of results (as opposed to a flat list of results). */displayResultTree:PropTypes.bool,/** Whether to enable the aggregated report download button. */enableAggregatedReports:PropTypes.bool,/** Whether to enable the export functionality. Either `true|false` or a list of single allowed formats (builtin formats: `json`, `geojson`, `csv`, `csvzip`) */enableExport:PropTypes.oneOfType([PropTypes.bool,PropTypes.array]),enabled:PropTypes.bool,/** Whether to clear the task when the results window is closed. */exitTaskOnResultsClose:PropTypes.bool,/** Whether to include the geometry in exported features. Default: `true`. */exportGeometry:PropTypes.bool,/** Whether to assume that XML GetFeatureInfo responses specify the technical layer name in the `name` attribute, rather than the layer title. */featureInfoReturnsLayerName:PropTypes.bool,/** Default window geometry with size, position and docking status. Positive position values (including '0') are related to top (InitialY) and left (InitialX), negative values (including '-0') to bottom (InitialY) and right (InitialX). */geometry:PropTypes.shape({initialWidth:PropTypes.number,initialHeight:PropTypes.number,initialX:PropTypes.number,initialY:PropTypes.number,initiallyDocked:PropTypes.bool,side:PropTypes.string}),/** Whether to highlight all results if no result is hovered */highlightAllResults:PropTypes.bool,iframeDialogsInitiallyDocked:PropTypes.bool,/** The initial radius units of the identify dialog in radius mode. One of 'm', 'ft', 'km', 'mi'. */initialRadiusUnits:PropTypes.string,layers:PropTypes.array,longAttributesDisplay:PropTypes.string,map:PropTypes.object,/** Extra params to append to the GetFeatureInfo request (i.e. `FI_POINT_TOLERANCE`, `FI_LINE_TOLERANCE`, `feature_count`, ...). Additionally, `region_feature_count` and `radius_feature_count` are supported. */params:PropTypes.object,removeLayer:PropTypes.func,removeMarker:PropTypes.func,/** Whether to replace an attribute value containing an URL to an image with an inline image. */replaceImageUrls:PropTypes.bool,selection:PropTypes.object,setCurrentTask:PropTypes.func,/** Whether to show a layer selector to filter the identify results by layer. */showLayerSelector:PropTypes.bool,theme:PropTypes.object});_defineProperty(Identify,"defaultProps",{enableAggregatedReports:true,enableExport:true,exportGeometry:true,clearResultsOnClose:true,customExporters:[],longAttributesDisplay:"ellipsis",displayResultTree:true,replaceImageUrls:true,featureInfoReturnsLayerName:true,geometry:{initialWidth:240,initialHeight:320,initialX:0,initialY:0,initiallyDocked:false,side:"left"},initialRadiusUnits:"m",highlightAllResults:true,showLayerSelector:true});export default connect(function(state){var enabled=state.task.id==="Identify"||state.task.identifyEnabled&&ConfigUtils.getConfigProp("identifyTool",state.theme.current,"Identify")==="Identify";return{click:state.map.click||{modifiers:{}},enabled:enabled,layers:state.layers.flat,map:state.map,selection:state.selection,theme:state.theme.current}},{addLayerFeatures:addLayerFeatures,addMarker:addMarker,removeMarker:removeMarker,removeLayer:removeLayer,setCurrentTask:setCurrentTask})(Identify);
18
+ _this.setState(function(state){var identifyResults=_objectSpread({},state.identifyResults);Object.entries(newResults).forEach(function(_ref3){var _ref4=_slicedToArray(_ref3,2),layername=_ref4[0],features=_ref4[1];var key=layer.url+"#"+layername;identifyResults[key]=features.reduce(function(result,feature){if(result.find(function(f){return f.id===feature.id})===undefined){result.push(feature)}return result},identifyResults[key]||[])});return{identifyResults:identifyResults}})});_defineProperty(_this,"onShow",function(mode,data){_this.setState({mode:mode||"Point",exitTaskOnResultsClose:data===null||data===void 0?void 0:data.exitTaskOnResultsClose});if(mode==="Point"&&data!==null&&data!==void 0&&data.pos){_this.identifyPoint(data.pos)}});_defineProperty(_this,"onToolClose",function(){_this.setState({mode:"Point",exitTaskOnResultsClose:null,filterGeom:null});if(_this.props.clearResultsOnClose){_this.clearResults()}});_defineProperty(_this,"onWindowClose",function(){_this.clearResults();if(_this.state.exitTaskOnResultsClose||_this.props.exitTaskOnResultsClose){_this.props.setCurrentTask(null)}});_defineProperty(_this,"clearResults",function(){_this.props.removeMarker("identify");_this.props.removeLayer("identifyslection");_this.props.removeLayer("identifyradiusbuffer");_this.setState({identifyResults:null,pendingRequests:0})});_defineProperty(_this,"updateRadius",function(radius,units){_this.setState(function(state){return{radius:radius,radiusUnits:units,filterGeom:_objectSpread(_objectSpread({},state.filterGeom),{},{radius:MeasureUtils.convertLength(radius,units,"m")})}})});_defineProperty(_this,"renderBody",function(){if(_this.state.mode==="Point"){return LocaleUtils.tr("infotool.clickhelpPoint")}else if(_this.state.mode==="Region"){return LocaleUtils.tr("infotool.clickhelpPolygon")}else if(_this.state.mode==="Radius"){var text=LocaleUtils.tr("infotool.clickhelpRadius");return/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("div",null,text),/*#__PURE__*/React.createElement("div",{className:"identify-radius-controls controlgroup"},/*#__PURE__*/React.createElement("span",null,LocaleUtils.tr("infotool.radius"),":\xA0"),/*#__PURE__*/React.createElement(NumberInput,{disabled:!_this.state.filterGeom,max:1000000,min:1,mobile:true,onChange:function onChange(rad){return _this.updateRadius(rad,_this.state.radiusUnits)},value:_this.state.radius}),/*#__PURE__*/React.createElement("select",{onChange:function onChange(ev){return _this.updateRadius(_this.state.radius,ev.target.value)},value:_this.state.radiusUnits},/*#__PURE__*/React.createElement("option",{value:"m"},"m"),/*#__PURE__*/React.createElement("option",{value:"ft"},"ft"),/*#__PURE__*/React.createElement("option",{value:"km"},"km"),/*#__PURE__*/React.createElement("option",{value:"mi"},"mi"))))}return null});return _this}_inherits(Identify,_React$Component);return _createClass(Identify,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps,prevState){if(this.props.enabled&&this.props.theme&&!prevProps.theme){var startupParams=this.props.startupParams;var haveIc=["1","true"].includes((startupParams.ic||"").toLowerCase());var c=(startupParams.c||"").split(/[;,]/g).map(function(x){return parseFloat(x)||0});if(haveIc&&c.length===2){var mapCrs=this.props.theme.mapCrs;this.identifyPoint(CoordinatesUtils.reproject(c,startupParams.crs||mapCrs,mapCrs))}}else if(this.props.theme!==prevProps.theme){this.clearResults()}else if(!this.props.enabled&&prevProps.enabled){if(this.props.clearResultsOnClose){this.clearResults()}}if(this.props.enabled){if(this.state.mode==="Point"){var clickPoint=this.queryPoint(prevProps);this.identifyPoint(clickPoint)}else if(this.state.mode==="Region"){if(this.state.filterGeom&&this.state.filterGeom!==prevState.filterGeom){this.identifyRegion()}}else if(this.state.mode==="Radius"){if(this.state.filterGeom&&this.state.filterGeom!==prevState.filterGeom){this.setState(function(state){return{radius:MeasureUtils.convertLength(state.filterGeom.radius,"m",state.radiusUnits)}});this.identifyRadius()}}}}},{key:"render",value:function render(){var _this2=this;var resultWindow=null;if(this.state.pendingRequests>0||this.state.identifyResults!==null){var body=null;if(isEmpty(this.state.identifyResults)){if(this.state.pendingRequests>0){body=/*#__PURE__*/React.createElement("div",{className:"identify-body",role:"body"},/*#__PURE__*/React.createElement("span",{className:"identify-body-message"},LocaleUtils.tr("identify.querying")))}else{body=/*#__PURE__*/React.createElement("div",{className:"identify-body",role:"body"},/*#__PURE__*/React.createElement("span",{className:"identify-body-message"},LocaleUtils.tr("identify.noresults")))}}else{body=/*#__PURE__*/React.createElement(IdentifyViewer,{attributeCalculator:this.props.attributeCalculator,attributeTransform:this.props.attributeTransform,customExporters:this.props.customExporters,displayResultTree:this.props.displayResultTree,enableAggregatedReports:this.props.enableAggregatedReports,enableExport:this.props.enableExport,exportGeometry:this.props.exportGeometry,highlightAllResults:this.props.highlightAllResults,identifyResults:this.state.identifyResults,iframeDialogsInitiallyDocked:this.props.iframeDialogsInitiallyDocked,longAttributesDisplay:this.props.longAttributesDisplay,replaceImageUrls:this.props.replaceImageUrls,role:"body",showLayerSelector:this.props.showLayerSelector})}resultWindow=/*#__PURE__*/React.createElement(ResizeableWindow,{busyIcon:this.state.pendingRequests>0,dockable:this.props.geometry.side,icon:"info-sign",initialHeight:this.props.geometry.initialHeight,initialWidth:this.props.geometry.initialWidth,initialX:this.props.geometry.initialX,initialY:this.props.geometry.initialY,initiallyDocked:this.props.geometry.initiallyDocked,key:"IdentifyWindow",onClose:this.onWindowClose,title:LocaleUtils.tr("identify.title")},body)}return[resultWindow,/*#__PURE__*/React.createElement(TaskBar,{key:"IdentifyTaskBar",onHide:this.onToolClose,onShow:this.onShow,task:"Identify"},function(){return{body:_this2.renderBody()}}),this.state.mode==="Region"||this.state.mode==="Radius"?/*#__PURE__*/React.createElement(MapSelection,{active:true,geomType:this.state.mode==="Radius"?"Circle":"Polygon",geometry:this.state.filterGeom,geometryChanged:function geometryChanged(geom,mod){return _this2.setState({filterGeom:geom,filterGeomModifiers:mod})},key:"MapSelection",measure:this.state.mode==="Radius"}):null]}}])}(React.Component);_defineProperty(Identify,"propTypes",{addLayerFeatures:PropTypes.func,addMarker:PropTypes.func,/** Optional function for computing derived attributes. See js/IdentifyExtensions.js for details. This prop can be specified in the appConfig.js cfg section. */attributeCalculator:PropTypes.func,/** Optional function for transforming attribute values. See js/IdentifyExtensions.js for details. This prop can be specified in the appConfig.js cfg section. */attributeTransform:PropTypes.func,/** Whether to clear the identify results when exiting the identify tool. */clearResultsOnClose:PropTypes.bool,click:PropTypes.object,currentIdentifyTool:PropTypes.string,currentTask:PropTypes.string,/** Optional list of custom exporters to offer along with the built-in exporters. See js/IdentifyExtensions.js for details. This prop can be specified in the appConfig.js cfg section. */customExporters:PropTypes.array,/** Whether to display a tree overview of results (as opposed to a flat list of results). */displayResultTree:PropTypes.bool,/** Whether to enable the aggregated report download button. */enableAggregatedReports:PropTypes.bool,/** Whether to enable the export functionality. Either `true|false` or a list of single allowed formats (builtin formats: `json`, `geojson`, `csv`, `csvzip`) */enableExport:PropTypes.oneOfType([PropTypes.bool,PropTypes.array]),enabled:PropTypes.bool,/** Whether to clear the task when the results window is closed. */exitTaskOnResultsClose:PropTypes.bool,/** Whether to include the geometry in exported features. Default: `true`. */exportGeometry:PropTypes.bool,/** Whether to assume that XML GetFeatureInfo responses specify the technical layer name in the `name` attribute, rather than the layer title. */featureInfoReturnsLayerName:PropTypes.bool,/** Default window geometry with size, position and docking status. Positive position values (including '0') are related to top (InitialY) and left (InitialX), negative values (including '-0') to bottom (InitialY) and right (InitialX). */geometry:PropTypes.shape({initialWidth:PropTypes.number,initialHeight:PropTypes.number,initialX:PropTypes.number,initialY:PropTypes.number,initiallyDocked:PropTypes.bool,side:PropTypes.string}),/** Whether to highlight all results if no result is hovered */highlightAllResults:PropTypes.bool,iframeDialogsInitiallyDocked:PropTypes.bool,/** The initial radius units of the identify dialog in radius mode. One of 'm', 'ft', 'km', 'mi'. */initialRadiusUnits:PropTypes.string,layers:PropTypes.array,longAttributesDisplay:PropTypes.string,map:PropTypes.object,/** Extra params to append to the GetFeatureInfo request (i.e. `FI_POINT_TOLERANCE`, `FI_LINE_TOLERANCE`, `feature_count`, ...). Additionally, `region_feature_count` and `radius_feature_count` are supported. */params:PropTypes.object,removeLayer:PropTypes.func,removeMarker:PropTypes.func,/** Whether to replace an attribute value containing an URL to an image with an inline image. */replaceImageUrls:PropTypes.bool,selection:PropTypes.object,setCurrentTask:PropTypes.func,/** Whether to show a layer selector to filter the identify results by layer. */showLayerSelector:PropTypes.bool,startupParams:PropTypes.object,theme:PropTypes.object});_defineProperty(Identify,"defaultProps",{enableAggregatedReports:true,enableExport:true,exportGeometry:true,clearResultsOnClose:true,customExporters:[],longAttributesDisplay:"ellipsis",displayResultTree:true,replaceImageUrls:true,featureInfoReturnsLayerName:true,geometry:{initialWidth:240,initialHeight:320,initialX:0,initialY:0,initiallyDocked:false,side:"left"},initialRadiusUnits:"m",highlightAllResults:true,showLayerSelector:true});export default connect(function(state){var enabled=state.task.id==="Identify"||state.task.identifyEnabled&&ConfigUtils.getConfigProp("identifyTool",state.theme.current,"Identify")==="Identify";return{click:state.map.click||{modifiers:{}},enabled:enabled,layers:state.layers.flat,map:state.map,selection:state.selection,theme:state.theme.current,startupParams:state.localConfig.startupParams}},{addLayerFeatures:addLayerFeatures,addMarker:addMarker,removeMarker:removeMarker,removeLayer:removeLayer,setCurrentTask:setCurrentTask})(Identify);
@@ -6,7 +6,7 @@ function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */import React from"react";import{connect}from"react-redux";import{TextEncoder,TextDecoder}from"@kayahr/text-encoding";import axios from"axios";import dayjs from"dayjs";import FileSaver from"file-saver";import isEmpty from"lodash.isempty";import PropTypes from"prop-types";import{LayerRole}from"../actions/layers";import{setSnappingConfig}from"../actions/map";import Icon from"../components/Icon";import PrintSelection from"../components/PrintSelection";import SideBar from"../components/SideBar";import NumberInput from"../components/widgets/NumberInput";import Spinner from"../components/widgets/Spinner";import ConfigUtils from"../utils/ConfigUtils";import CoordinatesUtils from"../utils/CoordinatesUtils";import{explodeDxf,implodeDxf,mergeDxf}from"../utils/DxfUtils";import LayerUtils from"../utils/LayerUtils";import LocaleUtils from"../utils/LocaleUtils";import MapUtils from"../utils/MapUtils";import VectorLayerUtils from"../utils/VectorLayerUtils";import"./style/MapExport.css";import"@kayahr/text-encoding/encodings/windows-1252";/**
8
8
  * Allows exporting a selected portion of the map to a variety of formats.
9
- */var MapExport=/*#__PURE__*/function(_React$Component){function MapExport(props){var _this;_classCallCheck(this,MapExport);_this=_callSuper(this,MapExport,[props]);_defineProperty(_this,"state",{extents:[],exporting:false,availableFormats:[],selectedFormat:null,selectedFormatConfiguration:"",exportProjection:null,scale:null,pageSize:null,dpi:96});_defineProperty(_this,"changeFormat",function(ev){var _this$props$formatCon,_formatConfigurations,_formatConfigurations2;var selectedFormat=ev.target.value;var formatConfigurations=((_this$props$formatCon=_this.props.formatConfiguration)===null||_this$props$formatCon===void 0?void 0:_this$props$formatCon[selectedFormat.split(";")[0]])||[];_this.setState({selectedFormat:selectedFormat,selectedFormatConfiguration:(_formatConfigurations=formatConfigurations[0])===null||_formatConfigurations===void 0?void 0:_formatConfigurations.name,exportProjection:_this.getExportProjection((_formatConfigurations2=formatConfigurations[0])===null||_formatConfigurations2===void 0?void 0:_formatConfigurations2.projections)})});_defineProperty(_this,"setSelectedFormatConfiguration",function(ev){var _this$props$formatCon2;var selectedFormatConfiguration=ev.target.value;var formatConfigurations=((_this$props$formatCon2=_this.props.formatConfiguration)===null||_this$props$formatCon2===void 0?void 0:_this$props$formatCon2[_this.state.selectedFormat.split(";")[0]])||[];var formatConfiguration=formatConfigurations.find(function(entry){return entry.name===selectedFormatConfiguration});_this.setState({selectedFormatConfiguration:selectedFormatConfiguration,exportProjection:_this.getExportProjection(formatConfiguration.projections)})});_defineProperty(_this,"getExportProjection",function(projections){if(isEmpty(projections)){return _this.props.map.projection}else{return projections.indexOf(_this.props.map.projection)!==-1?_this.props.map.projection:projections[0]}});_defineProperty(_this,"changeScale",function(value){_this.setState({scale:Math.max(1,parseInt(value,10)||0)})});_defineProperty(_this,"changeResolution",function(ev){_this.setState({dpi:parseInt(ev.target.value,10)||0})});_defineProperty(_this,"renderBody",function(){var _this$props$formatCon3;if(!_this.props.theme||!_this.state.selectedFormat){return null}var formatMap={"image/jpeg":"JPEG","image/png":"PNG","image/png; mode=16bit":"PNG 16bit","image/png; mode=8bit":"PNG 8bit","image/png; mode=1bit":"PNG 1bit","image/geotiff":"GeoTIFF","image/tiff":"GeoTIFF","application/dxf":"DXF","application/pdf":"GeoPDF"};var formatConfigurations=((_this$props$formatCon3=_this.props.formatConfiguration)===null||_this$props$formatCon3===void 0?void 0:_this$props$formatCon3[_this.state.selectedFormat.split(";")[0]])||[];var formatConfiguration=formatConfigurations.find(function(entry){return entry.name===_this.state.selectedFormatConfiguration});var scaleChooser=null;if(!isEmpty(_this.props.allowedScales)){scaleChooser=/*#__PURE__*/React.createElement("select",{onChange:_this.changeScale,value:_this.state.scale||""},/*#__PURE__*/React.createElement("option",{hidden:true,value:_this.state.scale||""},_this.state.scale||""),_this.props.allowedScales.map(function(scale){return/*#__PURE__*/React.createElement("option",{key:scale,value:scale},"1 : ",scale)}))}else if(_this.props.allowedScales!==false){scaleChooser=/*#__PURE__*/React.createElement(NumberInput,{min:1,mobile:true,onChange:_this.changeScale,prefix:"1 : ",value:_this.state.scale||null})}return/*#__PURE__*/React.createElement("div",{className:"mapexport-body"},/*#__PURE__*/React.createElement("form",{action:"#",method:"POST",onSubmit:_this["export"],ref:function ref(el){_this.form=el}},/*#__PURE__*/React.createElement("table",{className:"options-table"},/*#__PURE__*/React.createElement("tbody",null,/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.format")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("select",{onChange:_this.changeFormat,value:_this.state.selectedFormat},_this.state.availableFormats.map(function(format){return/*#__PURE__*/React.createElement("option",{key:format,value:format},formatMap[format]||format)})))),formatConfigurations.length>1?/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.configuration")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("select",{onChange:_this.setSelectedFormatConfiguration,value:_this.state.selectedFormatConfiguration},formatConfigurations.map(function(config){return/*#__PURE__*/React.createElement("option",{key:config.name,value:config.name},config.labelMsgId?LocaleUtils.tr(config.labelMsgId):config.name)})))):null,!isEmpty(_this.props.pageSizes)?/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.size")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("select",{onChange:function onChange(ev){return _this.setState({pageSize:ev.target.value||null})},value:_this.state.pageSize||""},/*#__PURE__*/React.createElement("option",{value:""},LocaleUtils.tr("mapexport.usersize")),_this.props.pageSizes.map(function(entry,idx){return/*#__PURE__*/React.createElement("option",{key:"size_"+idx,value:idx},entry.name)})))):null,scaleChooser&&_this.state.pageSize!==null?/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.scale")),/*#__PURE__*/React.createElement("td",null,scaleChooser)):null,_this.props.dpis?/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.resolution")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("select",{onChange:_this.changeResolution,value:_this.state.dpi},_this.props.dpis.map(function(dpi){return/*#__PURE__*/React.createElement("option",{key:dpi+"dpi",value:dpi},dpi+" dpi")})))):null,((formatConfiguration===null||formatConfiguration===void 0?void 0:formatConfiguration.projections)||[]).length>1?/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.projection")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("select",{onChange:function onChange(ev){return _this.setState({exportProjection:ev.target.value})},value:_this.state.exportProjection},formatConfiguration.projections.map(function(proj){return/*#__PURE__*/React.createElement("option",{key:proj,value:proj},proj)})))):null)),/*#__PURE__*/React.createElement("div",{className:"button-bar"},/*#__PURE__*/React.createElement("button",{className:"button",disabled:_this.state.exporting||isEmpty(_this.state.extents),type:"submit"},_this.state.exporting?/*#__PURE__*/React.createElement("span",{className:"mapexport-wait"},/*#__PURE__*/React.createElement(Spinner,null)," ",LocaleUtils.tr("mapexport.wait")):LocaleUtils.tr("mapexport.submit")))))});_defineProperty(_this,"renderPrintSelection",function(){if(_this.state.pageSize!==null){var pageSize=_this.props.pageSizes[_this.state.pageSize];var frame={width:pageSize.width,height:pageSize.height};return/*#__PURE__*/React.createElement(PrintSelection,{allowRotation:false,allowScaling:_this.props.allowedScales!==false,center:_this.props.map.center,fixedFrame:frame,geometryChanged:_this.geometryChanged,key:"PrintSelection",scale:_this.state.scale})}else{return/*#__PURE__*/React.createElement(PrintSelection,{allowRotation:false,geometryChanged:_this.geometryChanged,key:"PrintSelection"})}});_defineProperty(_this,"onShow",function(){var _this$props$formatCon4,_formatConfigurations3,_formatConfigurations4;var scale=Math.round(MapUtils.computeForZoom(_this.props.map.scales,_this.props.map.zoom)*_this.props.defaultScaleFactor);if(!isEmpty(_this.props.allowedScales)){var closestVal=Math.abs(scale-_this.props.allowedScales[0]);var closestIdx=0;for(var i=1;i<_this.props.allowedScales.length;++i){var currVal=Math.abs(scale-_this.props.allowedScales[i]);if(currVal<closestVal){closestVal=currVal;closestIdx=i}}scale=_this.props.allowedScales[closestIdx]}var availableFormats=_this.props.theme.availableFormats;if(!isEmpty(_this.props.allowedFormats)){availableFormats=availableFormats.filter(function(fmt){return _this.props.allowedFormats.includes(fmt)})}var selectedFormat=_this.props.defaultFormat&&availableFormats.includes(_this.props.defaultFormat)?_this.props.defaultFormat:availableFormats[0];var formatConfigurations=((_this$props$formatCon4=_this.props.formatConfiguration)===null||_this$props$formatCon4===void 0?void 0:_this$props$formatCon4[selectedFormat.split(";")[0]])||[];_this.setState({scale:scale,availableFormats:availableFormats,selectedFormat:selectedFormat,selectedFormatConfiguration:(_formatConfigurations3=formatConfigurations[0])===null||_formatConfigurations3===void 0?void 0:_formatConfigurations3.name,exportProjection:_this.getExportProjection((_formatConfigurations4=formatConfigurations[0])===null||_formatConfigurations4===void 0?void 0:_formatConfigurations4.projections)});_this.props.setSnappingConfig(false,false)});_defineProperty(_this,"onHide",function(){_this.setState({extents:[],width:0,height:0,scale:null,pageSize:null})});_defineProperty(_this,"geometryChanged",function(center,extents,rotation,scale){_this.setState(function(state){return{extents:extents,scale:scale!==null&&scale!==void 0?scale:state.scale}})});_defineProperty(_this,"export",function(ev){var _this$props$formatCon5,_this$state$extents$a;ev.preventDefault();_this.setState({exporting:true});var format=_this.state.selectedFormat.split(";")[0];var formatConfiguration=(((_this$props$formatCon5=_this.props.formatConfiguration)===null||_this$props$formatCon5===void 0?void 0:_this$props$formatCon5[format])||[]).find(function(entry){return entry.name===_this.state.selectedFormatConfiguration});var version=_this.props.theme.version;var crs=_this.state.exportProjection;var extent=CoordinatesUtils.reprojectBbox((_this$state$extents$a=_this.state.extents.at(0))!==null&&_this$state$extents$a!==void 0?_this$state$extents$a:[0,0,0,0],_this.props.map.projection,crs);var formattedExtent=CoordinatesUtils.getAxisOrder(crs).substring(0,2)==="ne"&&version==="1.3.0"?extent[1]+","+extent[0]+","+extent[3]+","+extent[2]:extent.join(",");var getPixelFromCoordinate=MapUtils.getHook(MapUtils.GET_PIXEL_FROM_COORDINATES_HOOK);var p1=getPixelFromCoordinate(extent.slice(0,2));var p2=getPixelFromCoordinate(extent.slice(2,4));var width=Math.round(Math.abs(p1[0]-p2[0])*_this.state.dpi/96);var height=Math.round(Math.abs(p1[1]-p2[1])*_this.state.dpi/96);var ext=format.split("/").pop();var timestamp=dayjs(new Date).format("YYYYMMDD_HHmmss");var fileName=_this.props.fileNameTemplate.replace("{username}",ConfigUtils.getConfigProp("username",null,"")).replace("{tenant}",ConfigUtils.getConfigProp("tenant",null,"")).replace("{theme}",_this.props.theme.id).replace("{timestamp}",timestamp)+"."+ext;var params={};// Base request params
9
+ */var MapExport=/*#__PURE__*/function(_React$Component){function MapExport(props){var _this;_classCallCheck(this,MapExport);_this=_callSuper(this,MapExport,[props]);_defineProperty(_this,"state",{extents:[],exporting:false,availableFormats:[],selectedFormat:null,selectedFormatConfiguration:"",exportProjection:null,scale:null,pageSize:null,dpi:96});_defineProperty(_this,"changeFormat",function(ev){var _this$props$formatCon,_formatConfigurations,_formatConfigurations2;var selectedFormat=ev.target.value;var formatConfigurations=((_this$props$formatCon=_this.props.formatConfiguration)===null||_this$props$formatCon===void 0?void 0:_this$props$formatCon[selectedFormat.split(";")[0]])||[];_this.setState({selectedFormat:selectedFormat,selectedFormatConfiguration:(_formatConfigurations=formatConfigurations[0])===null||_formatConfigurations===void 0?void 0:_formatConfigurations.name,exportProjection:_this.getExportProjection((_formatConfigurations2=formatConfigurations[0])===null||_formatConfigurations2===void 0?void 0:_formatConfigurations2.projections)})});_defineProperty(_this,"setSelectedFormatConfiguration",function(ev){var _this$props$formatCon2;var selectedFormatConfiguration=ev.target.value;var formatConfigurations=((_this$props$formatCon2=_this.props.formatConfiguration)===null||_this$props$formatCon2===void 0?void 0:_this$props$formatCon2[_this.state.selectedFormat.split(";")[0]])||[];var formatConfiguration=formatConfigurations.find(function(entry){return entry.name===selectedFormatConfiguration});_this.setState({selectedFormatConfiguration:selectedFormatConfiguration,exportProjection:_this.getExportProjection(formatConfiguration.projections)})});_defineProperty(_this,"getExportProjection",function(projections){if(isEmpty(projections)){return _this.props.map.projection}else{return projections.indexOf(_this.props.map.projection)!==-1?_this.props.map.projection:projections[0]}});_defineProperty(_this,"changeScale",function(value){_this.setState({scale:Math.max(1,parseInt(value,10)||0)})});_defineProperty(_this,"changeResolution",function(ev){_this.setState({dpi:parseInt(ev.target.value,10)||0})});_defineProperty(_this,"renderBody",function(){var _this$props$formatCon3;if(!_this.props.theme||!_this.state.selectedFormat){return null}var formatMap={"image/jpeg":"JPEG","image/png":"PNG","image/png; mode=16bit":"PNG 16bit","image/png; mode=8bit":"PNG 8bit","image/png; mode=1bit":"PNG 1bit","image/geotiff":"GeoTIFF","image/tiff":"GeoTIFF","application/dxf":"DXF","application/pdf":"GeoPDF"};var formatConfigurations=((_this$props$formatCon3=_this.props.formatConfiguration)===null||_this$props$formatCon3===void 0?void 0:_this$props$formatCon3[_this.state.selectedFormat.split(";")[0]])||[];var formatConfiguration=formatConfigurations.find(function(entry){return entry.name===_this.state.selectedFormatConfiguration});var scaleChooser=null;if(!isEmpty(_this.props.allowedScales)){scaleChooser=/*#__PURE__*/React.createElement("select",{onChange:_this.changeScale,value:_this.state.scale||""},/*#__PURE__*/React.createElement("option",{hidden:true,value:_this.state.scale||""},_this.state.scale||""),_this.props.allowedScales.map(function(scale){return/*#__PURE__*/React.createElement("option",{key:scale,value:scale},"1 : ",scale)}))}else if(_this.props.allowedScales!==false){scaleChooser=/*#__PURE__*/React.createElement(NumberInput,{min:1,mobile:true,onChange:_this.changeScale,prefix:"1 : ",value:_this.state.scale||null})}return/*#__PURE__*/React.createElement("div",{className:"mapexport-body"},/*#__PURE__*/React.createElement("form",{action:"#",method:"POST",onSubmit:_this["export"],ref:function ref(el){_this.form=el}},/*#__PURE__*/React.createElement("table",{className:"options-table"},/*#__PURE__*/React.createElement("tbody",null,/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.format")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("select",{onChange:_this.changeFormat,value:_this.state.selectedFormat},_this.state.availableFormats.map(function(format){return/*#__PURE__*/React.createElement("option",{key:format,value:format},formatMap[format]||format)})))),formatConfigurations.length>1?/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.configuration")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("select",{onChange:_this.setSelectedFormatConfiguration,value:_this.state.selectedFormatConfiguration},formatConfigurations.map(function(config){return/*#__PURE__*/React.createElement("option",{key:config.name,value:config.name},config.labelMsgId?LocaleUtils.tr(config.labelMsgId):config.name)})))):null,!isEmpty(_this.props.pageSizes)?/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.size")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("select",{onChange:function onChange(ev){return _this.setState({pageSize:ev.target.value||null})},value:_this.state.pageSize||""},/*#__PURE__*/React.createElement("option",{value:""},LocaleUtils.tr("mapexport.usersize")),_this.props.pageSizes.map(function(entry,idx){return/*#__PURE__*/React.createElement("option",{key:"size_"+idx,value:idx},entry.name)})))):null,scaleChooser&&_this.state.pageSize!==null?/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.scale")),/*#__PURE__*/React.createElement("td",null,scaleChooser)):null,_this.props.dpis?/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.resolution")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("select",{onChange:_this.changeResolution,value:_this.state.dpi},_this.props.dpis.map(function(dpi){return/*#__PURE__*/React.createElement("option",{key:dpi+"dpi",value:dpi},dpi+" dpi")})))):null,((formatConfiguration===null||formatConfiguration===void 0?void 0:formatConfiguration.projections)||[]).length>1?/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,LocaleUtils.tr("mapexport.projection")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("select",{onChange:function onChange(ev){return _this.setState({exportProjection:ev.target.value})},value:_this.state.exportProjection},formatConfiguration.projections.map(function(proj){return/*#__PURE__*/React.createElement("option",{key:proj,value:proj},proj)})))):null)),/*#__PURE__*/React.createElement("div",{className:"button-bar"},/*#__PURE__*/React.createElement("button",{className:"button",disabled:_this.state.exporting||isEmpty(_this.state.extents),type:"submit"},_this.state.exporting?/*#__PURE__*/React.createElement("span",{className:"mapexport-wait"},/*#__PURE__*/React.createElement(Spinner,null)," ",LocaleUtils.tr("mapexport.wait")):LocaleUtils.tr("mapexport.submit")))))});_defineProperty(_this,"renderPrintSelection",function(){if(_this.state.pageSize!==null){var pageSize=_this.props.pageSizes[_this.state.pageSize];var frame={width:pageSize.width,height:pageSize.height};return/*#__PURE__*/React.createElement(PrintSelection,{allowRotation:false,allowScaling:_this.props.allowedScales!==false,center:_this.props.map.center,fixedFrame:frame,geometryChanged:_this.geometryChanged,key:"PrintSelection",scale:_this.state.scale})}else{return/*#__PURE__*/React.createElement(PrintSelection,{allowRotation:false,geometryChanged:_this.geometryChanged,key:"PrintSelection"})}});_defineProperty(_this,"onShow",function(){var _this$props$formatCon4,_formatConfigurations3,_formatConfigurations4;var scale=Math.round(MapUtils.computeForZoom(_this.props.map.scales,_this.props.map.zoom)*_this.props.defaultScaleFactor);if(!isEmpty(_this.props.allowedScales)){var closestVal=Math.abs(scale-_this.props.allowedScales[0]);var closestIdx=0;for(var i=1;i<_this.props.allowedScales.length;++i){var currVal=Math.abs(scale-_this.props.allowedScales[i]);if(currVal<closestVal){closestVal=currVal;closestIdx=i}}scale=_this.props.allowedScales[closestIdx]}var availableFormats=_this.props.theme.availableFormats;if(!isEmpty(_this.props.allowedFormats)){availableFormats=_this.props.allowedFormats.filter(function(fmt){return availableFormats.includes(fmt)})}var selectedFormat=_this.props.defaultFormat&&availableFormats.includes(_this.props.defaultFormat)?_this.props.defaultFormat:availableFormats[0];var formatConfigurations=((_this$props$formatCon4=_this.props.formatConfiguration)===null||_this$props$formatCon4===void 0?void 0:_this$props$formatCon4[selectedFormat.split(";")[0]])||[];_this.setState({scale:scale,availableFormats:availableFormats,selectedFormat:selectedFormat,selectedFormatConfiguration:(_formatConfigurations3=formatConfigurations[0])===null||_formatConfigurations3===void 0?void 0:_formatConfigurations3.name,exportProjection:_this.getExportProjection((_formatConfigurations4=formatConfigurations[0])===null||_formatConfigurations4===void 0?void 0:_formatConfigurations4.projections)});_this.props.setSnappingConfig(false,false)});_defineProperty(_this,"onHide",function(){_this.setState({extents:[],width:0,height:0,scale:null,pageSize:null})});_defineProperty(_this,"geometryChanged",function(center,extents,rotation,scale){_this.setState(function(state){return{extents:extents,scale:scale!==null&&scale!==void 0?scale:state.scale}})});_defineProperty(_this,"export",function(ev){var _this$props$formatCon5,_this$state$extents$a;ev.preventDefault();_this.setState({exporting:true});var format=_this.state.selectedFormat.split(";")[0];var formatConfiguration=(((_this$props$formatCon5=_this.props.formatConfiguration)===null||_this$props$formatCon5===void 0?void 0:_this$props$formatCon5[format])||[]).find(function(entry){return entry.name===_this.state.selectedFormatConfiguration});var version=_this.props.theme.version;var crs=_this.state.exportProjection;var extent=CoordinatesUtils.reprojectBbox((_this$state$extents$a=_this.state.extents.at(0))!==null&&_this$state$extents$a!==void 0?_this$state$extents$a:[0,0,0,0],_this.props.map.projection,crs);var formattedExtent=CoordinatesUtils.getAxisOrder(crs).substring(0,2)==="ne"&&version==="1.3.0"?extent[1]+","+extent[0]+","+extent[3]+","+extent[2]:extent.join(",");var getPixelFromCoordinate=MapUtils.getHook(MapUtils.GET_PIXEL_FROM_COORDINATES_HOOK);var p1=getPixelFromCoordinate(extent.slice(0,2));var p2=getPixelFromCoordinate(extent.slice(2,4));var width=Math.round(Math.abs(p1[0]-p2[0])*_this.state.dpi/96);var height=Math.round(Math.abs(p1[1]-p2[1])*_this.state.dpi/96);var ext=format.split("/").pop();var timestamp=dayjs(new Date).format("YYYYMMDD_HHmmss");var fileName=_this.props.fileNameTemplate.replace("{username}",ConfigUtils.getConfigProp("username",null,"")).replace("{tenant}",ConfigUtils.getConfigProp("tenant",null,"")).replace("{theme}",_this.props.theme.id).replace("{themeTitle}",_this.props.theme.title||"").replace("{timestamp}",timestamp)+"."+ext;var params={};// Base request params
10
10
  params.SERVICE="WMS";params.VERSION=version;params.REQUEST="GetMap";params.FORMAT=_this.state.selectedFormat;params.DPI=_this.state.dpi;params.TRANSPARENT=true;params.TILED=false;params.CRS=crs;params.BBOX=formattedExtent;params.WIDTH=width;params.HEIGHT=height;params.filename=fileName;// Dimension values
11
11
  _this.props.layers.forEach(function(layer){if(layer.role===LayerRole.THEME){Object.entries(layer.dimensionValues||{}).forEach(function(_ref){var _ref2=_slicedToArray(_ref,2),key=_ref2[0],value=_ref2[1];if(value!==undefined){params[key]=value}})}});// Add parameters from custom format configuration
12
12
  if(formatConfiguration){var _formatConfiguration$;var keyCaseMap=Object.keys(params).reduce(function(res,key){return _objectSpread(_objectSpread({},res),{},_defineProperty({},key.toLowerCase(),key))},{});(formatConfiguration.extraQuery||"").split(/[?&]/).filter(Boolean).forEach(function(entry){var _entry$split=entry.split("="),_entry$split2=_slicedToArray(_entry$split,2),key=_entry$split2[0],value=_entry$split2[1];var caseKey=keyCaseMap[key.toLowerCase()]||key;params[caseKey]=value!==null&&value!==void 0?value:""});params.FORMAT_OPTIONS=(_formatConfiguration$=formatConfiguration.formatOptions)!==null&&_formatConfiguration$!==void 0?_formatConfiguration$:"";if(formatConfiguration.baseLayer){var layers=params[keyCaseMap.layers].split(",");if(!layers.includes(formatConfiguration.baseLayer)){params[keyCaseMap.layers]=[formatConfiguration.baseLayer].concat(_toConsumableArray(layers))}}}if(_this.state.selectedFormat==="application/dxf"){_this.dxfExport(params,fileName)}else{_this.genericExport(params,fileName,formatConfiguration)}});_defineProperty(_this,"genericExport",function(params,fileName,formatConfiguration){// Layer params
@@ -16,7 +16,7 @@ Object.keys(_this.props.theme.watermark||{}).forEach(function(key){params["WATER
16
16
  responses.forEach((response, idx) => {
17
17
  FileSaver.saveAs(new Blob([response.data], {type: "application/dxf"}), "orig_" + idx + "_" + fileName);
18
18
  });
19
- */_this.setState({exporting:false})})});_this.form=null;_this.state.dpi=(props.dpis||[])[0]||96;return _this}_inherits(MapExport,_React$Component);return _createClass(MapExport,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps,prevState){if(this.state.pageSize===null&&prevState.pageSize!==null){this.setState({extents:[]})}}},{key:"render",value:function render(){var _this2=this;var minMaxTooltip=this.state.minimized?LocaleUtils.tr("print.maximize"):LocaleUtils.tr("print.minimize");var extraTitlebarContent=/*#__PURE__*/React.createElement(Icon,{className:"mapexport-minimize-maximize",icon:this.state.minimized?"chevron-down":"chevron-up",onClick:function onClick(){return _this2.setState(function(state){return{minimized:!state.minimized}})},title:minMaxTooltip});return/*#__PURE__*/React.createElement(SideBar,{extraClasses:"MapExport",extraTitlebarContent:extraTitlebarContent,icon:"rasterexport",id:"MapExport",key:"MapExport",onHide:this.onHide,onShow:this.onShow,side:this.props.side,title:LocaleUtils.tr("appmenu.items.MapExport"),width:"20em"},function(){return{body:_this2.state.minimized?null:_this2.renderBody(),extra:[_this2.renderPrintSelection()]}})}}])}(React.Component);_defineProperty(MapExport,"propTypes",{/** Whitelist of allowed export format mimetypes. If empty, supported formats are listed. */allowedFormats:PropTypes.arrayOf(PropTypes.string),/** List of scales at which to export the map. If empty, scale can be freely specified. If `false`, the map can only be exported at the current scale. */allowedScales:PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number),PropTypes.bool]),/** Default export format mimetype. If empty, first available format is used. */defaultFormat:PropTypes.string,/** The factor to apply to the map scale to determine the initial export map scale (if `allowedScales` is not `false`). */defaultScaleFactor:PropTypes.number,/** List of dpis at which to export the map. If empty, the default server dpi is used. */dpis:PropTypes.arrayOf(PropTypes.number),/** Whether to include external layers in the image. Requires QGIS Server 3.x! */exportExternalLayers:PropTypes.bool,/** Template for the name of the generated files when downloading. Can contain the placeholders `{username}`, `{tenant}`, `{theme}`, `{timestamp}`. */fileNameTemplate:PropTypes.string,/** Custom export configuration per format.
19
+ */_this.setState({exporting:false})})});_this.form=null;_this.state.dpi=(props.dpis||[])[0]||96;return _this}_inherits(MapExport,_React$Component);return _createClass(MapExport,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps,prevState){if(this.state.pageSize===null&&prevState.pageSize!==null){this.setState({extents:[]})}}},{key:"render",value:function render(){var _this2=this;var minMaxTooltip=this.state.minimized?LocaleUtils.tr("print.maximize"):LocaleUtils.tr("print.minimize");var extraTitlebarContent=/*#__PURE__*/React.createElement(Icon,{className:"mapexport-minimize-maximize",icon:this.state.minimized?"chevron-down":"chevron-up",onClick:function onClick(){return _this2.setState(function(state){return{minimized:!state.minimized}})},title:minMaxTooltip});return/*#__PURE__*/React.createElement(SideBar,{extraClasses:"MapExport",extraTitlebarContent:extraTitlebarContent,icon:"rasterexport",id:"MapExport",key:"MapExport",onHide:this.onHide,onShow:this.onShow,side:this.props.side,title:LocaleUtils.tr("appmenu.items.MapExport"),width:"20em"},function(){return{body:_this2.state.minimized?null:_this2.renderBody(),extra:[_this2.renderPrintSelection()]}})}}])}(React.Component);_defineProperty(MapExport,"propTypes",{/** Whitelist of allowed export format mimetypes. If empty, supported formats are listed. */allowedFormats:PropTypes.arrayOf(PropTypes.string),/** List of scales at which to export the map. If empty, scale can be freely specified. If `false`, the map can only be exported at the current scale. */allowedScales:PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number),PropTypes.bool]),/** Default export format mimetype. If empty, first available format is used. */defaultFormat:PropTypes.string,/** The factor to apply to the map scale to determine the initial export map scale (if `allowedScales` is not `false`). */defaultScaleFactor:PropTypes.number,/** List of dpis at which to export the map. If empty, the default server dpi is used. */dpis:PropTypes.arrayOf(PropTypes.number),/** Whether to include external layers in the image. Requires QGIS Server 3.x! */exportExternalLayers:PropTypes.bool,/** Template for the name of the generated files when downloading. Can contain the placeholders `{username}`, `{tenant}`, `{theme}`, `{themeTitle}`, `{timestamp}`. */fileNameTemplate:PropTypes.string,/** Custom export configuration per format.
20
20
  * If more than one configuration per format is provided, a selection combo will be displayed.
21
21
  * `labelMsgId` is a translation string message id for the combo label. If not defined, `name` will be displayed.
22
22
  * `extraQuery` will be appended to the query string (replacing any existing parameters).
@@ -1,4 +1,4 @@
1
- function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _toConsumableArray(r){return _arrayWithoutHoles(r)||_iterableToArray(r)||_unsupportedIterableToArray(r)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _iterableToArray(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}function _arrayWithoutHoles(r){if(Array.isArray(r))return _arrayLikeToArray(r)}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _callSuper(t,o,e){return o=_getPrototypeOf(o),_possibleConstructorReturn(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _possibleConstructorReturn(t,e){if(e&&("object"==_typeof(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(t)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t})()}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}/**
1
+ function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _toConsumableArray(r){return _arrayWithoutHoles(r)||_iterableToArray(r)||_unsupportedIterableToArray(r)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}function _arrayWithoutHoles(r){if(Array.isArray(r))return _arrayLikeToArray(r)}function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function e(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function s(){t=t.call(r)},n:function n(){var r=t.next();return a=r.done,r},e:function e(r){u=!0,o=r},f:function f(){try{a||null==t["return"]||t["return"]()}finally{if(u)throw o}}}}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _callSuper(t,o,e){return o=_getPrototypeOf(o),_possibleConstructorReturn(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _possibleConstructorReturn(t,e){if(e&&("object"==_typeof(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(t)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t})()}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}/**
2
2
  * Copyright 2018-2024 Sourcepole AG
3
3
  * All rights reserved.
4
4
  *
@@ -31,4 +31,4 @@ function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof
31
31
  * render() { return ...; }
32
32
  * };
33
33
  * ```
34
- */var MapInfoTooltip=/*#__PURE__*/function(_React$Component){function MapInfoTooltip(){var _this;_classCallCheck(this,MapInfoTooltip);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this=_callSuper(this,MapInfoTooltip,[].concat(args));_defineProperty(_this,"state",{point:null,elevation:null,extraInfo:null});_defineProperty(_this,"clear",function(){_this.setState({point:null,height:null,extraInfo:null})});return _this}_inherits(MapInfoTooltip,_React$Component);return _createClass(MapInfoTooltip,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var _this2=this;if(!this.props.enabled&&this.state.point){this.clear();return}var newPoint=this.props.map.click;if(!newPoint||newPoint.button!==2){if(this.state.point){this.clear()}}else{var oldPoint=prevProps.map.click;if(!oldPoint||oldPoint.pixel[0]!==newPoint.pixel[0]||oldPoint.pixel[1]!==newPoint.pixel[1]){this.setState({point:newPoint,elevation:null,extraInfo:null});var pos=newPoint.coordinate;var crs=this.props.map.projection;getElevationInterface().getElevation(pos,crs).then(function(elevation){var elevationPrecision=_this2.props.elevationPrecision;_this2.setState({elevation:Math.round(elevation*Math.pow(10,elevationPrecision))/Math.pow(10,elevationPrecision)})})["catch"](function(){});var mapInfoService=ConfigUtils.getConfigProp("mapInfoService");if(mapInfoService){axios.get(mapInfoService,{params:{pos:pos.join(","),crs:crs}}).then(function(response){_this2.setState({extraInfo:response.data.results})})["catch"](function(){})}}}}},{key:"render",value:function render(){var _this3=this;if(!this.state.point){return null}var info=[];var projections=[this.props.map.displayCrs];if(!projections.includes(this.props.map.projection)){projections.push(this.props.map.projection)}if(this.props.includeWGS84&&!projections.includes("EPSG:4326")){projections.push("EPSG:4326")}projections.map(function(crs){var coo=CoordinatesUtils.reproject(_this3.state.point.coordinate,_this3.props.map.projection,crs);var decimals=CoordinatesUtils.getPrecision(crs);info.push([(CoordinatesUtils.getAvailableCRS()[crs]||{label:crs}).label,coo.map(function(x){return LocaleUtils.toLocaleFixed(x,decimals)}).join(", ")])});if(this.state.elevation){info.push([LocaleUtils.tr("mapinfotooltip.elevation"),this.state.elevation+" m"])}if(this.state.extraInfo){info.push.apply(info,_toConsumableArray(this.state.extraInfo))}var title=LocaleUtils.tr("mapinfotooltip.title");var pixel=MapUtils.getHook(MapUtils.GET_PIXEL_FROM_COORDINATES_HOOK)(this.state.point.coordinate);var style={left:pixel[0]+"px",top:pixel[1]+"px"};var text=info.map(function(entry){return entry.join(": ")}).join("\n");var routingButtons=null;if(ConfigUtils.havePlugin("Routing")){var prec=CoordinatesUtils.getPrecision(this.props.map.displayCrs);var pos=CoordinatesUtils.reproject(this.state.point.coordinate,this.props.map.projection,this.props.map.displayCrs);var point={text:pos.map(function(x){return x.toFixed(prec)}).join(", ")+" ("+this.props.map.displayCrs+")",pos:_toConsumableArray(pos),crs:this.props.map.displayCrs};routingButtons=/*#__PURE__*/React.createElement("table",{className:"mapinfotooltip-body-routing"},/*#__PURE__*/React.createElement("tbody",null,/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("b",null,LocaleUtils.tr("routing.route"),":")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("div",{className:"controlgroup"},/*#__PURE__*/React.createElement("button",{className:"button",onClick:function onClick(){return _this3.props.setCurrentTask("Routing",null,null,{from:point})}},LocaleUtils.tr("routing.fromhere")),/*#__PURE__*/React.createElement("button",{className:"button",onClick:function onClick(){return _this3.props.setCurrentTask("Routing",null,null,{to:point})}},LocaleUtils.tr("routing.tohere")),/*#__PURE__*/React.createElement("button",{className:"button",onClick:function onClick(){return _this3.props.setCurrentTask("Routing",null,null,{via:point})}},LocaleUtils.tr("routing.addviapoint"))))),/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("b",null,LocaleUtils.tr("routing.reachability"),":")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("div",{className:"controlgroup"},/*#__PURE__*/React.createElement("button",{className:"button",onClick:function onClick(){return _this3.props.setCurrentTask("Routing",null,null,{isocenter:point})}},LocaleUtils.tr("routing.isocenter")),/*#__PURE__*/React.createElement("button",{className:"button",onClick:function onClick(){return _this3.props.setCurrentTask("Routing",null,null,{isoextracenter:point})}},LocaleUtils.tr("routing.isoextracenter")))))))}return/*#__PURE__*/ReactDOM.createPortal(/*#__PURE__*/React.createElement("div",{className:"mapinfotooltip",style:style},/*#__PURE__*/React.createElement("div",{className:"mapinfotooltip-window"},/*#__PURE__*/React.createElement("div",{className:"mapinfotooltip-titlebar"},/*#__PURE__*/React.createElement("span",{className:"mapinfotooltip-title"},title),/*#__PURE__*/React.createElement(CopyButton,{buttonClass:"mapinfotooltip-button",text:text}),/*#__PURE__*/React.createElement(Icon,{className:"mapinfotooltip-button",icon:"remove",onClick:this.clear})),/*#__PURE__*/React.createElement("div",{className:"mapinfotooltip-body"},/*#__PURE__*/React.createElement("table",null,/*#__PURE__*/React.createElement("tbody",null,info.map(function(entry,index){return/*#__PURE__*/React.createElement("tr",{key:"row"+index},/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("b",null,entry[0],":")),/*#__PURE__*/React.createElement("td",null,entry[1]))}))),routingButtons,this.props.plugins.map(function(Plugin,idx){return/*#__PURE__*/React.createElement(Plugin,{closePopup:_this3.clear,key:idx,point:_this3.state.point,projection:_this3.props.map.projection})})))),this.context)}}])}(React.Component);_defineProperty(MapInfoTooltip,"contextType",MapContainerPortalContext);_defineProperty(MapInfoTooltip,"propTypes",{/** The number of decimal places to display for elevation values. */elevationPrecision:PropTypes.number,enabled:PropTypes.bool,includeWGS84:PropTypes.bool,map:PropTypes.object,/** Additional plugin components for the map info tooltip. */plugins:PropTypes.array,setCurrentTask:PropTypes.func});_defineProperty(MapInfoTooltip,"defaultProps",{elevationPrecision:0,includeWGS84:true,plugins:[]});export default(function(plugins){return connect(function(state){return{enabled:state.task.identifyEnabled,map:state.map,plugins:plugins}},{setCurrentTask:setCurrentTask})(MapInfoTooltip)});
34
+ */var MapInfoTooltip=/*#__PURE__*/function(_React$Component){function MapInfoTooltip(){var _this;_classCallCheck(this,MapInfoTooltip);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this=_callSuper(this,MapInfoTooltip,[].concat(args));_defineProperty(_this,"state",{point:null,elevation:null,extraInfo:null});_defineProperty(_this,"clear",function(){_this.setState({point:null,elevation:null,extraInfo:null})});return _this}_inherits(MapInfoTooltip,_React$Component);return _createClass(MapInfoTooltip,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var _this2=this;if(!this.props.enabled&&this.state.point){this.clear();return}var newPoint=this.props.map.click;if(!newPoint||newPoint.button!==2){if(this.state.point){this.clear()}}else{var oldPoint=prevProps.map.click;if(!oldPoint||oldPoint.pixel[0]!==newPoint.pixel[0]||oldPoint.pixel[1]!==newPoint.pixel[1]){this.setState({point:newPoint,elevation:null,extraInfo:null});var pos=newPoint.coordinate;var crs=this.props.map.projection;getElevationInterface().getElevation(pos,crs).then(function(elevation){_this2.setState({elevation:elevation})})["catch"](function(){});var mapInfoService=ConfigUtils.getConfigProp("mapInfoService");if(mapInfoService){axios.get(mapInfoService,{params:{pos:pos.join(","),crs:crs}}).then(function(response){_this2.setState({extraInfo:response.data.results})})["catch"](function(){})}}}}},{key:"render",value:function render(){var _this3=this;if(!this.state.point){return null}var info=[];var projections=[this.props.map.displayCrs];if(!projections.includes(this.props.map.projection)){projections.push(this.props.map.projection)}if(this.props.includeWGS84&&!projections.includes("EPSG:4326")){projections.push("EPSG:4326")}projections.map(function(crs){var coo=CoordinatesUtils.reproject(_this3.state.point.coordinate,_this3.props.map.projection,crs);var decimals=CoordinatesUtils.getPrecision(crs);info.push([(CoordinatesUtils.getAvailableCRS()[crs]||{label:crs}).label,coo.map(function(x){return LocaleUtils.toLocaleFixed(x,decimals)}).join(", ")])});if(this.state.elevation){var elevs=this.state.elevation.list;if(!elevs){elevs=[{elevation:this.state.elevation,dataset:null}]}var _iterator=_createForOfIteratorHelper(elevs),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var data=_step.value;info.push([LocaleUtils.tr("mapinfotooltip.elevation")+(data.dataset?" ("+data.dataset+")":""),data.elevation.toFixed(this.props.elevationPrecision)+" m"])}}catch(err){_iterator.e(err)}finally{_iterator.f()}}if(this.state.extraInfo){info.push.apply(info,_toConsumableArray(this.state.extraInfo))}var title=LocaleUtils.tr("mapinfotooltip.title");var pixel=MapUtils.getHook(MapUtils.GET_PIXEL_FROM_COORDINATES_HOOK)(this.state.point.coordinate);var style={left:pixel[0]+"px",top:pixel[1]+"px"};var text=info.map(function(entry){return entry.join(": ")}).join("\n");var routingButtons=null;if(ConfigUtils.havePlugin("Routing")){var prec=CoordinatesUtils.getPrecision(this.props.map.displayCrs);var pos=CoordinatesUtils.reproject(this.state.point.coordinate,this.props.map.projection,this.props.map.displayCrs);var point={text:pos.map(function(x){return x.toFixed(prec)}).join(", ")+" ("+this.props.map.displayCrs+")",pos:_toConsumableArray(pos),crs:this.props.map.displayCrs};routingButtons=/*#__PURE__*/React.createElement("table",{className:"mapinfotooltip-body-routing"},/*#__PURE__*/React.createElement("tbody",null,/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("b",null,LocaleUtils.tr("routing.route"),":")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("div",{className:"controlgroup"},/*#__PURE__*/React.createElement("button",{className:"button",onClick:function onClick(){return _this3.props.setCurrentTask("Routing",null,null,{from:point})}},LocaleUtils.tr("routing.fromhere")),/*#__PURE__*/React.createElement("button",{className:"button",onClick:function onClick(){return _this3.props.setCurrentTask("Routing",null,null,{to:point})}},LocaleUtils.tr("routing.tohere")),/*#__PURE__*/React.createElement("button",{className:"button",onClick:function onClick(){return _this3.props.setCurrentTask("Routing",null,null,{via:point})}},LocaleUtils.tr("routing.addviapoint"))))),/*#__PURE__*/React.createElement("tr",null,/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("b",null,LocaleUtils.tr("routing.reachability"),":")),/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("div",{className:"controlgroup"},/*#__PURE__*/React.createElement("button",{className:"button",onClick:function onClick(){return _this3.props.setCurrentTask("Routing",null,null,{isocenter:point})}},LocaleUtils.tr("routing.isocenter")),/*#__PURE__*/React.createElement("button",{className:"button",onClick:function onClick(){return _this3.props.setCurrentTask("Routing",null,null,{isoextracenter:point})}},LocaleUtils.tr("routing.isoextracenter")))))))}return/*#__PURE__*/ReactDOM.createPortal(/*#__PURE__*/React.createElement("div",{className:"mapinfotooltip",style:style},/*#__PURE__*/React.createElement("div",{className:"mapinfotooltip-window"},/*#__PURE__*/React.createElement("div",{className:"mapinfotooltip-titlebar"},/*#__PURE__*/React.createElement("span",{className:"mapinfotooltip-title"},title),/*#__PURE__*/React.createElement(CopyButton,{buttonClass:"mapinfotooltip-button",text:text}),/*#__PURE__*/React.createElement(Icon,{className:"mapinfotooltip-button",icon:"remove",onClick:this.clear})),/*#__PURE__*/React.createElement("div",{className:"mapinfotooltip-body"},/*#__PURE__*/React.createElement("table",null,/*#__PURE__*/React.createElement("tbody",null,info.map(function(entry,index){return/*#__PURE__*/React.createElement("tr",{key:"row"+index},/*#__PURE__*/React.createElement("td",null,/*#__PURE__*/React.createElement("b",null,entry[0],":")),/*#__PURE__*/React.createElement("td",null,entry[1]))}))),routingButtons,this.props.plugins.map(function(Plugin,idx){return/*#__PURE__*/React.createElement(Plugin,{closePopup:_this3.clear,key:idx,point:_this3.state.point,projection:_this3.props.map.projection})})))),this.context)}}])}(React.Component);_defineProperty(MapInfoTooltip,"contextType",MapContainerPortalContext);_defineProperty(MapInfoTooltip,"propTypes",{/** The number of decimal places to display for elevation values. */elevationPrecision:PropTypes.number,enabled:PropTypes.bool,includeWGS84:PropTypes.bool,map:PropTypes.object,/** Additional plugin components for the map info tooltip. */plugins:PropTypes.array,setCurrentTask:PropTypes.func});_defineProperty(MapInfoTooltip,"defaultProps",{elevationPrecision:0,includeWGS84:true,plugins:[]});export default(function(plugins){return connect(function(state){return{enabled:state.task.identifyEnabled,map:state.map,plugins:plugins}},{setCurrentTask:setCurrentTask})(MapInfoTooltip)});
package/plugins/MapTip.js CHANGED
@@ -10,6 +10,6 @@ function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof
10
10
  * Queries the map tips configured in the QGIS layer properites over GetFeatureInfo.
11
11
  *
12
12
  * The map tip needs to be configured in QGIS Layer Properties &rarr; Display.
13
- */var MapTip=/*#__PURE__*/function(_React$Component){function MapTip(){var _this;_classCallCheck(this,MapTip);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this=_callSuper(this,MapTip,[].concat(args));_defineProperty(_this,"state",{maptips:{},maptipsLayerOrder:[],mousePos:null,pos:null});_defineProperty(_this,"getMapMousePos",function(ev){_this.clearMaptip();clearTimeout(_this.mouseStateTimeout);_this.mouseStateTimeout=setTimeout(function(){_this.setState({mousePos:{coordinate:ev.coordinate,pixel:ev.pixel}})},100)});_defineProperty(_this,"clearMaptip",function(){clearTimeout(_this.timeoutId);_this.timeoutId=null;if(_this.state.pos){_this.props.removeLayer("maptipselection");_this.setState({maptips:{},maptipsOrder:[],pos:null})}});_defineProperty(_this,"queryMapTip",function(pos){_this.timeoutId=null;var options={info_format:"text/xml",feature_count:_this.props.layerFeatureCount,FI_POINT_TOLERANCE:16,FI_LINE_TOLERANCE:8,FI_POLYGON_TOLERANCE:4,with_maptip:true,with_htmlcontent:false};var reqId=uuidv1();_this.reqId=reqId;var layerOrder=[];_this.props.layers.forEach(function(layer){if(!(layer.role===LayerRole.THEME||layer.role===LayerRole.USERLAYER)||!(layer.infoFormats||[]).includes("text/xml")||isEmpty(layer.queryLayers)){return}var queryLayers=layer.queryLayers;if(!isEmpty(layer.drawingOrder)){queryLayers=layer.drawingOrder.slice(0).reverse().filter(function(entry){return layer.queryLayers.includes(entry)})}layerOrder.push(layer.id);var request=IdentifyUtils.buildRequest(layer,queryLayers.join(","),_this.state.mousePos.coordinate,_this.props.map,options);IdentifyUtils.sendRequest(request,function(response){if(_this.reqId===reqId){var result=IdentifyUtils.parseXmlResponse(response||"",_this.props.map.projection);var mapTips=[];var features=[];var _iterator=_createForOfIteratorHelper(request.params.layers.split(",")),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var sublayer=_step.value;var sublayerFeatures=(result[sublayer]||[]).filter(function(feature){return feature.properties.maptip});features.push.apply(features,_toConsumableArray(sublayerFeatures));mapTips.push.apply(mapTips,_toConsumableArray(sublayerFeatures.map(function(feature){return feature.properties.maptip})))}}catch(err){_iterator.e(err)}finally{_iterator.f()}if(_this.props.showFeatureSelection&&!isEmpty(features)){var sellayer={id:"maptipselection",role:LayerRole.SELECTION};_this.props.addLayerFeatures(sellayer,features,true)}_this.setState(function(state){return{pos:pos,maptips:_objectSpread(_objectSpread({},state.maptips),{},_defineProperty({},layer.id,mapTips))}})}})});_this.setState({maptipsLayerOrder:layerOrder})});_defineProperty(_this,"parsedContent",function(text){var options={replace:function replace(node){if(node.name==="a"){return/*#__PURE__*/React.createElement("a",{href:node.attribs.href,onClick:node.attribs.onclick?function(ev){return _this.evalOnClick(ev,node.attribs.onclick)}:_this.attributeLinkClicked,target:node.attribs.target||"_blank"},domToReact(node.children,options))}return undefined}};return htmlReactParser(text,options)});_defineProperty(_this,"evalOnClick",function(ev,onclick){// eslint-disable-next-line
13
+ */var MapTip=/*#__PURE__*/function(_React$Component){function MapTip(){var _this;_classCallCheck(this,MapTip);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this=_callSuper(this,MapTip,[].concat(args));_defineProperty(_this,"state",{maptips:{},maptipsLayerOrder:[],mousePos:null,pos:null});_defineProperty(_this,"getMapMousePos",function(ev){_this.clearMaptip();clearTimeout(_this.mouseStateTimeout);_this.mouseStateTimeout=setTimeout(function(){_this.setState({mousePos:{coordinate:ev.coordinate,pixel:ev.pixel}})},100)});_defineProperty(_this,"clearMaptip",function(){clearTimeout(_this.timeoutId);_this.timeoutId=null;if(_this.state.pos){_this.props.removeLayer("maptipselection");_this.setState({maptips:{},maptipsOrder:[],pos:null})}});_defineProperty(_this,"queryMapTip",function(pos){_this.timeoutId=null;var options={info_format:"text/xml",feature_count:_this.props.layerFeatureCount,FI_POINT_TOLERANCE:16,FI_LINE_TOLERANCE:8,FI_POLYGON_TOLERANCE:4,with_maptip:true,with_htmlcontent:false};var reqId=uuidv1();_this.reqId=reqId;var layerOrder=[];_this.props.layers.forEach(function(layer){if(!(layer.role===LayerRole.THEME||layer.role===LayerRole.USERLAYER)||!(layer.infoFormats||[]).includes("text/xml")||isEmpty(layer.queryLayers)){return}var queryLayers=layer.queryLayers;if(!isEmpty(layer.drawingOrder)){queryLayers=layer.drawingOrder.slice(0).reverse().filter(function(entry){return layer.queryLayers.includes(entry)})}layerOrder.push(layer.id);var request=IdentifyUtils.buildRequest(layer,queryLayers.join(","),_this.state.mousePos.coordinate,_this.props.map,options);IdentifyUtils.sendRequest(request,function(response){if(_this.reqId===reqId){var result=IdentifyUtils.parseXmlResponse(response||"",_this.props.map.projection,layer);var mapTips=[];var features=[];var _iterator=_createForOfIteratorHelper(request.params.layers.split(",")),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var sublayer=_step.value;var sublayerFeatures=(result[sublayer]||[]).filter(function(feature){return feature.properties.maptip});features.push.apply(features,_toConsumableArray(sublayerFeatures));mapTips.push.apply(mapTips,_toConsumableArray(sublayerFeatures.map(function(feature){return feature.properties.maptip})))}}catch(err){_iterator.e(err)}finally{_iterator.f()}if(_this.props.showFeatureSelection&&!isEmpty(features)){var sellayer={id:"maptipselection",role:LayerRole.SELECTION};_this.props.addLayerFeatures(sellayer,features,true)}_this.setState(function(state){return{pos:pos,maptips:_objectSpread(_objectSpread({},state.maptips),{},_defineProperty({},layer.id,mapTips))}})}})});_this.setState({maptipsLayerOrder:layerOrder})});_defineProperty(_this,"parsedContent",function(text){var options={replace:function replace(node){if(node.name==="a"){return/*#__PURE__*/React.createElement("a",{href:node.attribs.href,onClick:node.attribs.onclick?function(ev){return _this.evalOnClick(ev,node.attribs.onclick)}:_this.attributeLinkClicked,target:node.attribs.target||"_blank"},domToReact(node.children,options))}return undefined}};return htmlReactParser(text,options)});_defineProperty(_this,"evalOnClick",function(ev,onclick){// eslint-disable-next-line
14
14
  eval(onclick);ev.preventDefault()});_defineProperty(_this,"attributeLinkClicked",function(ev){_this.props.openExternalUrl(ev.target.href,ev.target.target,{docked:_this.props.iframeDialogsInitiallyDocked});ev.preventDefault()});_defineProperty(_this,"positionMapTip",function(el){if(el){var x=_this.state.pos[0];var y=_this.state.pos[1];var parentBBox=el.parentElement.getBoundingClientRect();var bbox=el.getBoundingClientRect();if(x+bbox.width>parentBBox.width){x-=bbox.width}if(y+bbox.height>parentBBox.height){y-=bbox.height}el.style.left=x+"px";el.style.top=y+"px"}});return _this}_inherits(MapTip,_React$Component);return _createClass(MapTip,[{key:"componentDidMount",value:function componentDidMount(){MapUtils.getHook(MapUtils.ADD_POINTER_MOVE_LISTENER)(this.getMapMousePos)}},{key:"componentWillUnmount",value:function componentWillUnmount(){MapUtils.getHook(MapUtils.REMOVE_POINTER_MOVE_LISTENER)(this.getMapMousePos)}},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps,prevState){var _this2=this;if(this.props.map!==prevProps.map){this.clearMaptip()}if(this.props.mapTipsEnabled&&this.state.mousePos&&this.state.mousePos!==prevState.mousePos&&(isEmpty(this.state.pos)||Math.abs(this.state.mousePos.pixel[0]-this.state.pos[0])>5||Math.abs(this.state.mousePos.pixel[1]-this.state.pos[1])>5)){this.timeoutId=setTimeout(function(){return _this2.queryMapTip(_this2.state.mousePos.pixel)},500)}else if(!this.props.mapTipsEnabled&&prevProps.mapTipsEnabled){this.clearMaptip()}}},{key:"render",value:function render(){var _this3=this;if(!isEmpty(this.state.maptips)&&this.state.pos){// Render off-screen first to measure dimensions, then place as necessary
15
15
  var style={left:10000+"px",top:10000+"px",maxHeight:this.props.maxHeight,maxWidth:this.props.maxWidth};var bufferPos={left:this.state.pos[0]-8+"px",top:this.state.pos[1]-8+"px"};return/*#__PURE__*/ReactDOM.createPortal([/*#__PURE__*/React.createElement("div",{id:"MapTipPointerBuffer",key:"MapTipPointerBuffer",style:bufferPos}),/*#__PURE__*/React.createElement("div",{id:"MapTip",key:"MapTip",ref:this.positionMapTip,style:style},this.state.maptipsLayerOrder.map(function(key){return _this3.state.maptips[key]||[]}).flat().map(function(maptip,idx){return/*#__PURE__*/React.createElement("div",{key:idx},_this3.parsedContent(maptip))}))],this.context)}return null}}])}(React.Component);_defineProperty(MapTip,"contextType",MapContainerPortalContext);_defineProperty(MapTip,"propTypes",{addLayerFeatures:PropTypes.func,iframeDialogsInitiallyDocked:PropTypes.bool,/** The maximum number of feature maptips to display for a single layer. */layerFeatureCount:PropTypes.number,layers:PropTypes.array,map:PropTypes.object,mapTipsEnabled:PropTypes.bool,/** The maximum height of the maptip popop bubble, as a CSS string. */maxHeight:PropTypes.string,/** The maximum height of the maptip popop bubble, as a CSS string. */maxWidth:PropTypes.string,openExternalUrl:PropTypes.func,removeLayer:PropTypes.func,/** Whether to show the maptip feature selection on the map or not */showFeatureSelection:PropTypes.bool});_defineProperty(MapTip,"defaultProps",{layerFeatureCount:5,maxHeight:"15em",maxWidth:"20em",showFeatureSelection:true});export default connect(function(state){return{mapTipsEnabled:state.map.maptips&&state.task.identifyEnabled,layers:state.layers.flat,map:state.map}},{addLayerFeatures:addLayerFeatures,removeLayer:removeLayer,openExternalUrl:openExternalUrl})(MapTip);
package/plugins/Portal.js CHANGED
@@ -7,4 +7,4 @@ function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof
7
7
  */import React from"react";import{connect}from"react-redux";import PropTypes from"prop-types";import{setCurrentTask}from"../actions/task";import{openExternalUrl}from"../actions/windows";import AppMenu from"../components/AppMenu";import Icon from"../components/Icon";import ThemeList from"../components/ThemeList";import ConfigUtils from"../utils/ConfigUtils";import LocaleUtils from"../utils/LocaleUtils";import{UrlParams}from"../utils/PermaLinkUtils";import ThemeUtils from"../utils/ThemeUtils";import"./style/Portal.css";/**
8
8
  * Displays a landing lage, consisting of a full-screen theme switcher and a configurable menu.
9
9
  */var Portal=/*#__PURE__*/function(_React$Component){function Portal(){var _this;_classCallCheck(this,Portal);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this=_callSuper(this,Portal,[].concat(args));_defineProperty(_this,"state",{filter:"",popupClosed:false,menuVisible:false});_defineProperty(_this,"openUrl",function(url,target,title){if(target==="iframe"){target=":iframedialog:externallinkiframe"}_this.props.openExternalUrl(url,target,{title:title,zIndex:250})});_defineProperty(_this,"menuToggled",function(visible){_this.setState({menuVisible:visible})});return _this}_inherits(Portal,_React$Component);return _createClass(Portal,[{key:"componentDidMount",value:function componentDidMount(){if(!this.props.startupParams.t&&!this.props.startupParams.k&&!this.props.startupParams.bk){this.props.setCurrentTask("Portal")}}},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){if(this.props.currentTask==="Portal"&&(this.props.currentTask!==prevProps.currentTask||this.props.currentTheme!==prevProps.currentTheme||this.props.map!==prevProps.map)){UrlParams.clear()}else if(!prevProps.themes&&this.props.themes&&this.props.currentTask!=="Portal"){// Show portal if no theme is to be loaded
10
- var theme=ThemeUtils.getThemeById(this.props.themes,this.props.startupParams.t);if((!theme||theme.restricted)&&(ConfigUtils.getConfigProp("dontLoadDefaultTheme")||!this.props.themes.defaultTheme)){this.props.setCurrentTask("Portal")}}}},{key:"render",value:function render(){var _this2=this;if(this.props.currentTask!=="Portal"){return null}var assetsPath=ConfigUtils.getAssetsPath();var preserveSettings=ConfigUtils.getConfigProp("preserveSettingsOnPortalThemeSwitch");return/*#__PURE__*/React.createElement("div",{className:"Portal"},/*#__PURE__*/React.createElement("div",{className:"portal-topbar"},/*#__PURE__*/React.createElement("img",{className:"portal-logo",src:assetsPath+"/img/"+this.props.logo}),/*#__PURE__*/React.createElement("span",{className:"portal-topbar-text",dangerouslySetInnerHTML:{__html:this.props.topBarText}}),/*#__PURE__*/React.createElement("input",{className:"portal-search-field",onChange:function onChange(ev){return _this2.setState({filter:ev.target.value})},placeholder:LocaleUtils.tr("portal.filter"),type:"text",value:this.state.filter}),/*#__PURE__*/React.createElement("span",{className:"portal-topbar-spacer"}),/*#__PURE__*/React.createElement(AppMenu,{appMenuClearsTask:false,buttonLabel:LocaleUtils.tr("portal.menulabel"),keepMenuOpen:this.props.keepMenuOpen,menuItems:this.props.menuItems,onMenuToggled:this.menuToggled,openExternalUrl:this.openUrl,showOnStartup:this.props.showMenuOnStartup})),/*#__PURE__*/React.createElement("div",{className:"portal-body "+(this.state.menuVisible?"portal-body-menuvisible":"")},/*#__PURE__*/React.createElement(ThemeList,{collapsibleGroups:this.props.collapsibleGroups,dontPreserveSettingsOnSwitch:!preserveSettings,filter:this.state.filter})),/*#__PURE__*/React.createElement("div",{className:"portal-bottombar"},this.props.userName?/*#__PURE__*/React.createElement("div",{className:"portal-bottombar-user"},/*#__PURE__*/React.createElement(Icon,{icon:"logout"}),/*#__PURE__*/React.createElement("span",null,this.props.userName)):null,/*#__PURE__*/React.createElement("div",{className:"portal-bottombar-links"},(this.props.bottomBarLinks||[]).map(function(link,idx){var _link$label;var label=(_link$label=link.label)!==null&&_link$label!==void 0?_link$label:LocaleUtils.tr(link.labelmsgid);return/*#__PURE__*/React.createElement("a",{href:"#",key:"l"+idx,onClick:function onClick(ev){ev.preventDefault();_this2.openUrl(link.href,link.target,label)}},label)}))))}}])}(React.Component);_defineProperty(Portal,"propTypes",{/** Links to show in the portal bottom bar */bottomBarLinks:PropTypes.arrayOf(PropTypes.shape({href:PropTypes.string,label:PropTypes.string,labelmsgid:PropTypes.string,target:PropTypes.string})),/** Whether to allow collapsing groups in the theme switcher. */collapsibleGroups:PropTypes.bool,currentTask:PropTypes.string,currentTheme:PropTypes.object,keepMenuOpen:PropTypes.bool,/** Name of a logo image below assets/img. */logo:PropTypes.string,map:PropTypes.object,/** Portal menu items, in the same format as the TopBar menu items. */menuItems:PropTypes.array,openExternalUrl:PropTypes.func,setCurrentTask:PropTypes.func,/** Whether the menu should be visible on startup. */showMenuOnStartup:PropTypes.bool,startupParams:PropTypes.object,themes:PropTypes.object,/** Portal title text to show in the top bar. */topBarText:PropTypes.string,userName:PropTypes.string});_defineProperty(Portal,"defaultProps",{collapsibleGroups:true,menuItems:[]});var selector=function selector(state){return{currentTask:state.task.id,currentTheme:state.theme.current,map:state.map,themes:state.theme.themes,startupParams:state.localConfig.startupParams,userName:state.localConfig.username||""}};export default connect(selector,{setCurrentTask:setCurrentTask,openExternalUrl:openExternalUrl})(Portal);
10
+ var theme=ThemeUtils.getThemeById(this.props.themes,this.props.startupParams.t);if((!theme||theme.restricted)&&(ConfigUtils.getConfigProp("dontLoadDefaultTheme")||!this.props.themes.defaultTheme)){this.props.setCurrentTask("Portal")}}}},{key:"render",value:function render(){var _this2=this;if(this.props.currentTask!=="Portal"){return null}var assetsPath=ConfigUtils.getAssetsPath();var preserveSettings=ConfigUtils.getConfigProp("preserveSettingsOnPortalThemeSwitch");return/*#__PURE__*/React.createElement("div",{className:"Portal"},/*#__PURE__*/React.createElement("div",{className:"portal-topbar"},/*#__PURE__*/React.createElement("img",{className:"portal-logo",src:assetsPath+"/img/"+this.props.logo}),/*#__PURE__*/React.createElement("span",{className:"portal-topbar-text",dangerouslySetInnerHTML:{__html:this.props.topBarText}}),/*#__PURE__*/React.createElement("input",{className:"portal-search-field",onChange:function onChange(ev){return _this2.setState({filter:ev.target.value})},placeholder:LocaleUtils.tr("portal.filter"),type:"text",value:this.state.filter}),/*#__PURE__*/React.createElement("span",{className:"portal-topbar-spacer"}),this.props.menuItems.length>0?/*#__PURE__*/React.createElement(AppMenu,{appMenuClearsTask:false,buttonLabel:LocaleUtils.tr("portal.menulabel"),keepMenuOpen:this.props.keepMenuOpen,menuItems:this.props.menuItems,onMenuToggled:this.menuToggled,openExternalUrl:this.openUrl,showOnStartup:this.props.showMenuOnStartup}):null),/*#__PURE__*/React.createElement("div",{className:"portal-body "+(this.state.menuVisible?"portal-body-menuvisible":"")},/*#__PURE__*/React.createElement(ThemeList,{collapsibleGroups:this.props.collapsibleGroups,dontPreserveSettingsOnSwitch:!preserveSettings,filter:this.state.filter})),/*#__PURE__*/React.createElement("div",{className:"portal-bottombar"},this.props.userName?/*#__PURE__*/React.createElement("div",{className:"portal-bottombar-user"},/*#__PURE__*/React.createElement(Icon,{icon:"logout"}),/*#__PURE__*/React.createElement("span",null,this.props.userName)):null,/*#__PURE__*/React.createElement("div",{className:"portal-bottombar-links"},(this.props.bottomBarLinks||[]).map(function(link,idx){var _link$label;var label=(_link$label=link.label)!==null&&_link$label!==void 0?_link$label:LocaleUtils.tr(link.labelmsgid);return/*#__PURE__*/React.createElement("a",{href:"#",key:"l"+idx,onClick:function onClick(ev){ev.preventDefault();_this2.openUrl(link.href,link.target,label)}},label)}))))}}])}(React.Component);_defineProperty(Portal,"propTypes",{/** Links to show in the portal bottom bar */bottomBarLinks:PropTypes.arrayOf(PropTypes.shape({href:PropTypes.string,label:PropTypes.string,labelmsgid:PropTypes.string,target:PropTypes.string})),/** Whether to allow collapsing groups in the theme switcher. */collapsibleGroups:PropTypes.bool,currentTask:PropTypes.string,currentTheme:PropTypes.object,keepMenuOpen:PropTypes.bool,/** Name of a logo image below assets/img. */logo:PropTypes.string,map:PropTypes.object,/** Portal menu items, in the same format as the TopBar menu items. */menuItems:PropTypes.array,openExternalUrl:PropTypes.func,setCurrentTask:PropTypes.func,/** Whether the menu should be visible on startup. */showMenuOnStartup:PropTypes.bool,startupParams:PropTypes.object,themes:PropTypes.object,/** Portal title text to show in the top bar. */topBarText:PropTypes.string,userName:PropTypes.string});_defineProperty(Portal,"defaultProps",{collapsibleGroups:true,menuItems:[]});var selector=function selector(state){return{currentTask:state.task.id,currentTheme:state.theme.current,map:state.map,themes:state.theme.themes,startupParams:state.localConfig.startupParams,userName:state.localConfig.username||""}};export default connect(selector,{setCurrentTask:setCurrentTask,openExternalUrl:openExternalUrl})(Portal);
package/plugins/Print.js CHANGED
@@ -15,9 +15,9 @@ var printParams=LayerUtils.collectPrintParams(_this.props.layers,_this.props.the
15
15
  var printDpi=parseInt(_this.state.dpi,10)||0;if(_this.props.printMapHighlights){var highlightParams=VectorLayerUtils.createPrintHighlighParams(_this.props.layers,mapCrs,_this.state.scale,printDpi,_this.props.scaleFactor);formData[mapName+":HIGHLIGHT_GEOM"]=highlightParams.geoms.join(";");formData[mapName+":HIGHLIGHT_SYMBOL"]=highlightParams.styles.join(";");formData[mapName+":HIGHLIGHT_LABELSTRING"]=highlightParams.labels.join(";");formData[mapName+":HIGHLIGHT_LABELCOLOR"]=highlightParams.labelFillColors.join(";");formData[mapName+":HIGHLIGHT_LABELBUFFERCOLOR"]=highlightParams.labelOutlineColors.join(";");formData[mapName+":HIGHLIGHT_LABELBUFFERSIZE"]=highlightParams.labelOutlineSizes.join(";");formData[mapName+":HIGHLIGHT_LABELSIZE"]=highlightParams.labelSizes.join(";");formData[mapName+":HIGHLIGHT_LABEL_DISTANCE"]=highlightParams.labelDist.join(";");formData[mapName+":HIGHLIGHT_LABEL_ROTATION"]=highlightParams.labelRotations.join(";")}// Add grid params
16
16
  var printGrid=_this.props.theme.printGrid;if(!isEmpty(printGrid)){if(_this.state.grid){var cur=0;while(cur<printGrid.length-1&&_this.state.scale<printGrid[cur].s){cur+=1}formData[mapName+":GRID_INTERVAL_X"]=printGrid[cur].x;formData[mapName+":GRID_INTERVAL_Y"]=printGrid[cur].y}else{formData[mapName+":GRID_INTERVAL_X"]=0;formData[mapName+":GRID_INTERVAL_Y"]=0}}// Add dimension values
17
17
  _this.props.layers.forEach(function(layer){if(layer.role===LayerRole.THEME){Object.entries(layer.dimensionValues||{}).forEach(function(_ref5){var _ref6=_slicedToArray(_ref5,2),key=_ref6[0],value=_ref6[1];if(value!==undefined){formData[key]=value}})}});// Add extra print parameters
18
- var extraOptions=Object.fromEntries((_this.props.theme.extraPrintParameters||"").split("&").filter(Boolean).map(function(entry){return entry.split("=")}));Object.entries(extraOptions).forEach(function(_ref7){var _ref8=_slicedToArray(_ref7,2),key=_ref8[0],value=_ref8[1];formData[key]=value});var pages=[formData];if(_this.state.printSeriesEnabled){pages=_this.state.extents.map(function(extent,index){var fd=structuredClone(formData);fd.name=(index+1).toString().padStart(2,"0");fd[_this.state.layout.map.name+":extent"]=_this.formatExtent(extent);return fd})}var timestamp=dayjs(new Date).format("YYYYMMDD_HHmmss");var fileName=_this.props.fileNameTemplate.replace("{username}",ConfigUtils.getConfigProp("username",null,"")).replace("{tenant}",ConfigUtils.getConfigProp("tenant",null,"")).replace("{theme}",_this.props.theme.id).replace("{timestamp}",timestamp);// batch print all pages
19
- _this.batchPrint(pages,fileName)["catch"](function(e){_this.setState({outputLoaded:true,printOutputVisible:false});if(e.response){/* eslint-disable-next-line */console.warn(new TextDecoder().decode(e.response.data))}/* eslint-disable-next-line */alert("Print failed")})["finally"](function(){_this.setState({printing:false})})});_this.printForm=null;_this.state.grid=props.gridInitiallyEnabled;_this.state.dpi=props.defaultDpi;_this.state.selectedFormat=props.formats[0];return _this}_inherits(Print,_React$Component);return _createClass(Print,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps,prevState){if(prevProps.theme!==this.props.theme){if(this.props.theme&&!isEmpty(this.props.theme.print)){var layouts=this.props.theme.print.filter(function(l){return l.map}).sort(function(a,b){return a.name.split("/").pop().localeCompare(b.name.split("/").pop(),undefined,{numeric:true})});var layout=layouts.find(function(l){return l["default"]})||layouts[0];this.setState({layouts:layouts,layout:layout,atlasFeatures:[]})}else{this.setState({layouts:[],layout:null,atlasFeatures:[]})}}if(this.state.atlasFeatures!==prevState.atlasFeatures){if(!isEmpty(this.state.atlasFeatures)){var layer={id:"print-pick-selection",role:LayerRole.SELECTION,skipPrint:true};this.props.addLayerFeatures(layer,this.state.atlasFeatures,true)}else if(!isEmpty(prevState.atlasFeatures)){this.props.clearLayer("print-pick-selection")}}if(this.state.printSeriesEnabled&&this.state.selectedFormat!=="application/pdf"){this.setState({selectedFormat:"application/pdf"})}}},{key:"render",value:function render(){var _this2=this;var minMaxTooltip=this.state.minimized?LocaleUtils.tr("print.maximize"):LocaleUtils.tr("print.minimize");var extraTitlebarContent=/*#__PURE__*/React.createElement(Icon,{className:"print-minimize-maximize",icon:this.state.minimized?"chevron-down":"chevron-up",onClick:function onClick(){return _this2.setState(function(state){return{minimized:!state.minimized}})},title:minMaxTooltip});return[/*#__PURE__*/React.createElement(SideBar,{extraTitlebarContent:extraTitlebarContent,icon:"print",id:"Print",key:"Print",onHide:this.onHide,onShow:this.onShow,side:this.props.side,title:LocaleUtils.tr("appmenu.items.Print"),width:"20em"},function(){return{body:_this2.state.minimized?null:_this2.renderBody(),extra:[_this2.renderPrintSelection()]}}),this.renderPrintOutputWindow(),this.props.active&&this.state.layout&&this.state.layout.atlasCoverageLayer&&!this.state.printSeriesEnabled?/*#__PURE__*/React.createElement(PickFeature,{featurePicked:this.selectAtlasFeature,key:"FeaturePicker",layerFilter:{url:this.props.theme.url,name:this.state.layout.atlasCoverageLayer}}):null]}},{key:"batchPrint",value:function(){var _batchPrint=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(pages,fileName){var _this3=this;var promises,docs,files,file,fileURL,_iterator,_step,_file;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:// Print pages on server
20
- promises=pages.map(function(formData){return _this3.printRequest(formData)});// Collect printing results
18
+ var extraOptions=Object.fromEntries((_this.props.theme.extraPrintParameters||"").split("&").filter(Boolean).map(function(entry){return entry.split("=")}));Object.entries(extraOptions).forEach(function(_ref7){var _ref8=_slicedToArray(_ref7,2),key=_ref8[0],value=_ref8[1];formData[key]=value});var pages=[formData];if(_this.state.printSeriesEnabled){pages=_this.state.extents.map(function(extent,index){var fd=structuredClone(formData);fd.name=(index+1).toString().padStart(2,"0");fd[_this.state.layout.map.name+":extent"]=_this.formatExtent(extent);return fd})}var timestamp=dayjs(new Date).format("YYYYMMDD_HHmmss");var fileName=_this.props.fileNameTemplate.replace("{layout}",_this.state.layout.name).replace("{username}",ConfigUtils.getConfigProp("username",null,"")).replace("{tenant}",ConfigUtils.getConfigProp("tenant",null,"")).replace("{theme}",_this.props.theme.id).replace("{themeTitle}",_this.props.theme.title||"").replace("{timestamp}",timestamp);// batch print all pages
19
+ _this.batchPrint(pages,fileName)["catch"](function(e){_this.setState({outputLoaded:true,printOutputVisible:false});if(e.response){/* eslint-disable-next-line */console.warn(new TextDecoder().decode(e.response.data))}/* eslint-disable-next-line */alert("Print failed")})["finally"](function(){_this.setState({printing:false})})});_this.printForm=null;_this.state.grid=props.gridInitiallyEnabled;_this.state.dpi=props.defaultDpi;_this.state.selectedFormat=props.formats[0];return _this}_inherits(Print,_React$Component);return _createClass(Print,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps,prevState){var _this2=this;if(prevProps.theme!==this.props.theme){if(this.props.theme&&!isEmpty(this.props.theme.print)){var sortDir=this.props.layoutSortOrder==="desc"?-1:1;var layouts=this.props.theme.print.filter(function(l){return l.map&&!l.name.split("/").pop().startsWith(_this2.props.layoutHidePrefix)}).sort(function(a,b){return sortDir*a.name.split("/").pop().localeCompare(b.name.split("/").pop(),undefined,{numeric:true})});var layout=layouts.find(function(l){return l["default"]})||layouts[0];this.setState({layouts:layouts,layout:layout,atlasFeatures:[]})}else{this.setState({layouts:[],layout:null,atlasFeatures:[]})}}if(this.state.atlasFeatures!==prevState.atlasFeatures){if(!isEmpty(this.state.atlasFeatures)){var layer={id:"print-pick-selection",role:LayerRole.SELECTION,skipPrint:true};this.props.addLayerFeatures(layer,this.state.atlasFeatures,true)}else if(!isEmpty(prevState.atlasFeatures)){this.props.clearLayer("print-pick-selection")}}if(this.state.printSeriesEnabled&&this.state.selectedFormat!=="application/pdf"){this.setState({selectedFormat:"application/pdf"})}}},{key:"render",value:function render(){var _this3=this;var minMaxTooltip=this.state.minimized?LocaleUtils.tr("print.maximize"):LocaleUtils.tr("print.minimize");var extraTitlebarContent=/*#__PURE__*/React.createElement(Icon,{className:"print-minimize-maximize",icon:this.state.minimized?"chevron-down":"chevron-up",onClick:function onClick(){return _this3.setState(function(state){return{minimized:!state.minimized}})},title:minMaxTooltip});return[/*#__PURE__*/React.createElement(SideBar,{extraTitlebarContent:extraTitlebarContent,icon:"print",id:"Print",key:"Print",onHide:this.onHide,onShow:this.onShow,side:this.props.side,title:LocaleUtils.tr("appmenu.items.Print"),width:"20em"},function(){return{body:_this3.state.minimized?null:_this3.renderBody(),extra:[_this3.renderPrintSelection()]}}),this.renderPrintOutputWindow(),this.props.active&&this.state.layout&&this.state.layout.atlasCoverageLayer&&!this.state.printSeriesEnabled?/*#__PURE__*/React.createElement(PickFeature,{featurePicked:this.selectAtlasFeature,key:"FeaturePicker",layerFilter:{url:this.props.theme.url,name:this.state.layout.atlasCoverageLayer}}):null]}},{key:"batchPrint",value:function(){var _batchPrint=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(pages,fileName){var _this4=this;var promises,docs,files,file,fileURL,_iterator,_step,_file;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:// Print pages on server
20
+ promises=pages.map(function(formData){return _this4.printRequest(formData)});// Collect printing results
21
21
  _context.next=3;return Promise.all(promises);case 3:docs=_context.sent;_context.next=6;return this.collectFiles(docs,fileName);case 6:files=_context.sent;// Download or display files
22
- if(this.props.inlinePrintOutput&&files.length===1){file=files.pop();fileURL=URL.createObjectURL(file.content);this.setState({pdfData:file,pdfDataUrl:fileURL,outputLoaded:true})}else{_iterator=_createForOfIteratorHelper(files);try{for(_iterator.s();!(_step=_iterator.n()).done;){_file=_step.value;FileSaver.saveAs(_file.content,_file.fileName)}}catch(err){_iterator.e(err)}finally{_iterator.f()}}case 8:case"end":return _context.stop()}},_callee,this)}));function batchPrint(_x,_x2){return _batchPrint.apply(this,arguments)}return batchPrint}()},{key:"printRequest",value:function(){var _printRequest=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(formData){var data,config,response,contentType;return _regeneratorRuntime().wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:data=Object.entries(formData).map(function(pair){return pair.map(function(entry){return encodeURIComponent(entry).replace(/%20/g,"+")}).join("=")}).join("&");config={headers:{"Content-Type":"application/x-www-form-urlencoded"},responseType:"arraybuffer"};_context2.next=4;return axios.post(this.props.theme.printUrl,data,config);case 4:response=_context2.sent;contentType=response.headers["content-type"];return _context2.abrupt("return",{name:formData.name,data:response.data,contentType:contentType});case 7:case"end":return _context2.stop()}},_callee2,this)}));function printRequest(_x3){return _printRequest.apply(this,arguments)}return printRequest}()},{key:"collectFiles",value:function(){var _collectFiles=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(docs,fileName){var _this4=this;var data,content,_data,_content;return _regeneratorRuntime().wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:if(!(docs.length>1&&this.state.downloadMode==="onepdf")){_context3.next=6;break}_context3.next=3;return this.collectOnePdf(docs);case 3:data=_context3.sent;content=new Blob([data],{type:"application/pdf"});return _context3.abrupt("return",[{content:content,fileName:fileName+".pdf"}]);case 6:if(!(docs.length>1&&this.state.downloadMode==="onezip")){_context3.next=12;break}_context3.next=9;return this.collectOneZip(docs,fileName);case 9:_data=_context3.sent;_content=new Blob([_data],{type:"application/zip"});return _context3.abrupt("return",[{content:_content,fileName:fileName+".zip"}]);case 12:return _context3.abrupt("return",docs.map(function(doc){var content=new Blob([doc.data],{type:doc.contentType});var ext=_this4.state.selectedFormat.split(";")[0].split("/").pop();var appendix=doc.name?"_"+doc.name:"";return{content:content,fileName:fileName+appendix+"."+ext}}));case 13:case"end":return _context3.stop()}},_callee3,this)}));function collectFiles(_x4,_x5){return _collectFiles.apply(this,arguments)}return collectFiles}()},{key:"collectOnePdf",value:function(){var _collectOnePdf=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(docs){var _yield$import,PDFDocument,mergedDoc,_iterator2,_step2,doc,pdfBytes,copiedPages,_iterator3,_step3,page;return _regeneratorRuntime().wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=2;return import("pdf-lib");case 2:_yield$import=_context4.sent;PDFDocument=_yield$import.PDFDocument;_context4.next=6;return PDFDocument.create();case 6:mergedDoc=_context4.sent;_iterator2=_createForOfIteratorHelper(docs);_context4.prev=8;_iterator2.s();case 10:if((_step2=_iterator2.n()).done){_context4.next=22;break}doc=_step2.value;_context4.next=14;return PDFDocument.load(doc.data);case 14:pdfBytes=_context4.sent;_context4.next=17;return mergedDoc.copyPages(pdfBytes,pdfBytes.getPageIndices());case 17:copiedPages=_context4.sent;_iterator3=_createForOfIteratorHelper(copiedPages);try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){page=_step3.value;mergedDoc.addPage(page)}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}case 20:_context4.next=10;break;case 22:_context4.next=27;break;case 24:_context4.prev=24;_context4.t0=_context4["catch"](8);_iterator2.e(_context4.t0);case 27:_context4.prev=27;_iterator2.f();return _context4.finish(27);case 30:_context4.next=32;return mergedDoc.save();case 32:return _context4.abrupt("return",_context4.sent);case 33:case"end":return _context4.stop()}},_callee4,null,[[8,24,27,30]])}));function collectOnePdf(_x6){return _collectOnePdf.apply(this,arguments)}return collectOnePdf}()},{key:"collectOneZip",value:function(){var _collectOneZip=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(docs,fileName){var mergedDoc,_iterator4,_step4,doc,file,ext,appendix;return _regeneratorRuntime().wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:mergedDoc=new JSZip;_iterator4=_createForOfIteratorHelper(docs);try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){doc=_step4.value;file=new Blob([doc.data],{type:doc.contentType});ext=this.state.selectedFormat.split(";")[0].split("/").pop();appendix=doc.name?"_"+doc.name:"";mergedDoc.file(fileName+appendix+"."+ext,file)}}catch(err){_iterator4.e(err)}finally{_iterator4.f()}_context5.next=5;return mergedDoc.generateAsync({type:"arraybuffer"});case 5:return _context5.abrupt("return",_context5.sent);case 6:case"end":return _context5.stop()}},_callee5,this)}));function collectOneZip(_x7,_x8){return _collectOneZip.apply(this,arguments)}return collectOneZip}()}])}(React.Component);_defineProperty(Print,"propTypes",{active:PropTypes.bool,addLayerFeatures:PropTypes.func,/** Whether to allow GeoPDF export. Requires QGIS Server 3.32 or newer. */allowGeoPdfExport:PropTypes.bool,clearLayer:PropTypes.func,/** The default print dpi. */defaultDpi:PropTypes.number,/** The factor to apply to the map scale to determine the initial print map scale. */defaultScaleFactor:PropTypes.number,/** Show an option to print a series of extents. */displayPrintSeries:PropTypes.bool,/** Whether to display the printing rotation control. */displayRotation:PropTypes.bool,/** Template for the name of the generated files when downloading. Can contain the placeholders `{username}`, `{tenant}`, `{theme}`, `{timestamp}`. */fileNameTemplate:PropTypes.string,/** Export layout format mimetypes. If format is not supported by QGIS Server, print will fail. */formats:PropTypes.arrayOf(PropTypes.string),/** Whether the grid is enabled by default. */gridInitiallyEnabled:PropTypes.bool,/** Whether to hide form fields which contain autopopulated values (i.e. search result label). */hideAutopopulatedFields:PropTypes.bool,/** Whether to display the print output in an inline dialog instead triggering a download. */inlinePrintOutput:PropTypes.bool,layers:PropTypes.array,map:PropTypes.object,/** Whether to print external layers. Requires QGIS Server 3.x! */printExternalLayers:PropTypes.bool,/** Whether to print highlights on the map, e.g. selected features or redlining. */printMapHighlights:PropTypes.bool,/** Scale factor to apply to line widths, font sizes, ... of redlining drawings passed to GetPrint. */scaleFactor:PropTypes.number,setIdentifyEnabled:PropTypes.func,setSnappingConfig:PropTypes.func,/** The side of the application on which to display the sidebar. */side:PropTypes.string,theme:PropTypes.object});_defineProperty(Print,"defaultProps",{defaultDpi:300,defaultScaleFactor:0.5,displayPrintSeries:false,displayRotation:true,fileNameTemplate:"{theme}_{timestamp}",gridInitiallyEnabled:false,formats:["application/pdf","image/jpeg","image/png","image/svg"],inlinePrintOutput:false,printExternalLayers:true,printMapHighlights:true,scaleFactor:1.9,// Experimentally determined...
22
+ if(this.props.inlinePrintOutput&&files.length===1){file=files.pop();fileURL=URL.createObjectURL(file.content);this.setState({pdfData:file,pdfDataUrl:fileURL,outputLoaded:true})}else{_iterator=_createForOfIteratorHelper(files);try{for(_iterator.s();!(_step=_iterator.n()).done;){_file=_step.value;FileSaver.saveAs(_file.content,_file.fileName)}}catch(err){_iterator.e(err)}finally{_iterator.f()}}case 8:case"end":return _context.stop()}},_callee,this)}));function batchPrint(_x,_x2){return _batchPrint.apply(this,arguments)}return batchPrint}()},{key:"printRequest",value:function(){var _printRequest=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(formData){var data,config,response,contentType;return _regeneratorRuntime().wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:data=Object.entries(formData).map(function(pair){return pair.map(function(entry){return encodeURIComponent(entry).replace(/%20/g,"+")}).join("=")}).join("&");config={headers:{"Content-Type":"application/x-www-form-urlencoded"},responseType:"arraybuffer"};_context2.next=4;return axios.post(this.props.theme.printUrl,data,config);case 4:response=_context2.sent;contentType=response.headers["content-type"];return _context2.abrupt("return",{name:formData.name,data:response.data,contentType:contentType});case 7:case"end":return _context2.stop()}},_callee2,this)}));function printRequest(_x3){return _printRequest.apply(this,arguments)}return printRequest}()},{key:"collectFiles",value:function(){var _collectFiles=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(docs,fileName){var _this5=this;var data,content,_data,_content;return _regeneratorRuntime().wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:if(!(docs.length>1&&this.state.downloadMode==="onepdf")){_context3.next=6;break}_context3.next=3;return this.collectOnePdf(docs);case 3:data=_context3.sent;content=new Blob([data],{type:"application/pdf"});return _context3.abrupt("return",[{content:content,fileName:fileName+".pdf"}]);case 6:if(!(docs.length>1&&this.state.downloadMode==="onezip")){_context3.next=12;break}_context3.next=9;return this.collectOneZip(docs,fileName);case 9:_data=_context3.sent;_content=new Blob([_data],{type:"application/zip"});return _context3.abrupt("return",[{content:_content,fileName:fileName+".zip"}]);case 12:return _context3.abrupt("return",docs.map(function(doc){var content=new Blob([doc.data],{type:doc.contentType});var ext=_this5.state.selectedFormat.split(";")[0].split("/").pop();var appendix=doc.name?"_"+doc.name:"";return{content:content,fileName:fileName+appendix+"."+ext}}));case 13:case"end":return _context3.stop()}},_callee3,this)}));function collectFiles(_x4,_x5){return _collectFiles.apply(this,arguments)}return collectFiles}()},{key:"collectOnePdf",value:function(){var _collectOnePdf=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(docs){var _yield$import,PDFDocument,mergedDoc,_iterator2,_step2,doc,pdfBytes,copiedPages,_iterator3,_step3,page;return _regeneratorRuntime().wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=2;return import("pdf-lib");case 2:_yield$import=_context4.sent;PDFDocument=_yield$import.PDFDocument;_context4.next=6;return PDFDocument.create();case 6:mergedDoc=_context4.sent;_iterator2=_createForOfIteratorHelper(docs);_context4.prev=8;_iterator2.s();case 10:if((_step2=_iterator2.n()).done){_context4.next=22;break}doc=_step2.value;_context4.next=14;return PDFDocument.load(doc.data);case 14:pdfBytes=_context4.sent;_context4.next=17;return mergedDoc.copyPages(pdfBytes,pdfBytes.getPageIndices());case 17:copiedPages=_context4.sent;_iterator3=_createForOfIteratorHelper(copiedPages);try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){page=_step3.value;mergedDoc.addPage(page)}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}case 20:_context4.next=10;break;case 22:_context4.next=27;break;case 24:_context4.prev=24;_context4.t0=_context4["catch"](8);_iterator2.e(_context4.t0);case 27:_context4.prev=27;_iterator2.f();return _context4.finish(27);case 30:_context4.next=32;return mergedDoc.save();case 32:return _context4.abrupt("return",_context4.sent);case 33:case"end":return _context4.stop()}},_callee4,null,[[8,24,27,30]])}));function collectOnePdf(_x6){return _collectOnePdf.apply(this,arguments)}return collectOnePdf}()},{key:"collectOneZip",value:function(){var _collectOneZip=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(docs,fileName){var mergedDoc,_iterator4,_step4,doc,file,ext,appendix;return _regeneratorRuntime().wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:mergedDoc=new JSZip;_iterator4=_createForOfIteratorHelper(docs);try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){doc=_step4.value;file=new Blob([doc.data],{type:doc.contentType});ext=this.state.selectedFormat.split(";")[0].split("/").pop();appendix=doc.name?"_"+doc.name:"";mergedDoc.file(fileName+appendix+"."+ext,file)}}catch(err){_iterator4.e(err)}finally{_iterator4.f()}_context5.next=5;return mergedDoc.generateAsync({type:"arraybuffer"});case 5:return _context5.abrupt("return",_context5.sent);case 6:case"end":return _context5.stop()}},_callee5,this)}));function collectOneZip(_x7,_x8){return _collectOneZip.apply(this,arguments)}return collectOneZip}()}])}(React.Component);_defineProperty(Print,"propTypes",{active:PropTypes.bool,addLayerFeatures:PropTypes.func,/** Whether to allow GeoPDF export. Requires QGIS Server 3.32 or newer. */allowGeoPdfExport:PropTypes.bool,clearLayer:PropTypes.func,/** The default print dpi. */defaultDpi:PropTypes.number,/** The factor to apply to the map scale to determine the initial print map scale. */defaultScaleFactor:PropTypes.number,/** Show an option to print a series of extents. */displayPrintSeries:PropTypes.bool,/** Whether to display the printing rotation control. */displayRotation:PropTypes.bool,/** Template for the name of the generated files when downloading. Can contain the placeholders `{layout}`, `{username}`, `{tenant}`, `{theme}`, `{themeTitle}`, `{timestamp}`. */fileNameTemplate:PropTypes.string,/** Export layout format mimetypes. If format is not supported by QGIS Server, print will fail. */formats:PropTypes.arrayOf(PropTypes.string),/** Whether the grid is enabled by default. */gridInitiallyEnabled:PropTypes.bool,/** Whether to hide form fields which contain autopopulated values (i.e. search result label). */hideAutopopulatedFields:PropTypes.bool,/** Whether to display the print output in an inline dialog instead triggering a download. */inlinePrintOutput:PropTypes.bool,layers:PropTypes.array,/** Hide layouts which begin with this prefix. */layoutHidePrefix:PropTypes.string,/** Layout sort order, asc or desc. */layoutSortOrder:PropTypes.string,map:PropTypes.object,/** Whether to print external layers. Requires QGIS Server 3.x! */printExternalLayers:PropTypes.bool,/** Whether to print highlights on the map, e.g. selected features or redlining. */printMapHighlights:PropTypes.bool,/** Scale factor to apply to line widths, font sizes, ... of redlining drawings passed to GetPrint. */scaleFactor:PropTypes.number,setIdentifyEnabled:PropTypes.func,setSnappingConfig:PropTypes.func,/** The side of the application on which to display the sidebar. */side:PropTypes.string,theme:PropTypes.object});_defineProperty(Print,"defaultProps",{defaultDpi:300,defaultScaleFactor:0.5,displayPrintSeries:false,displayRotation:true,fileNameTemplate:"{theme}_{timestamp}",gridInitiallyEnabled:false,layoutSortOrder:"asc",formats:["application/pdf","image/jpeg","image/png","image/svg"],inlinePrintOutput:false,printExternalLayers:true,printMapHighlights:true,scaleFactor:1.9,// Experimentally determined...
23
23
  side:"right"});var selector=function selector(state){return{active:state.task.id==="Print",theme:state.theme.current,map:state.map,layers:state.layers.flat}};export default connect(selector,{addLayerFeatures:addLayerFeatures,clearLayer:clearLayer,setSnappingConfig:setSnappingConfig})(Print);
@@ -4,9 +4,9 @@ function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof
4
4
  *
5
5
  * This source code is licensed under the BSD-style license found in the
6
6
  * LICENSE file in the root directory of this source tree.
7
- */import React from"react";import{connect}from"react-redux";import PropTypes from"prop-types";import{addMarker,removeMarker}from"../actions/layers";import{UrlParams}from"../utils/PermaLinkUtils";/**
7
+ */import React from"react";import{connect}from"react-redux";import PropTypes from"prop-types";import{addMarker,removeMarker}from"../actions/layers";/**
8
8
  * Displays a marker when starting up the viewer.
9
9
  *
10
10
  * The marked is displayed in the center of the map if `c=<x>,<y>&hc=1` is set in the URL.
11
- */var StartupMarker=/*#__PURE__*/function(_React$Component){function StartupMarker(props){var _this;_classCallCheck(this,StartupMarker);_this=_callSuper(this,StartupMarker,[props]);_this.markerSet=false;return _this}_inherits(StartupMarker,_React$Component);return _createClass(StartupMarker,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var highlight=["true","1"].includes(""+(this.props.startupParams&&this.props.startupParams.hc||"").toLowerCase());if(highlight&&this.props.theme&&!prevProps.theme&&this.props.startupParams.c){UrlParams.updateParams({hc:undefined});var point=this.props.startupParams.c.split(/[;,]/g).map(function(x){return parseFloat(x)});prevProps.addMarker("startupposmarker",point,"",this.props.startupParams.crs||this.props.map.projection);this.markerSet=true}else if(this.markerSet){if(this.props.removeMode==="onpan"&&this.props.map.center!==prevProps.map.center&&this.props.map.zoom===prevProps.map.zoom||this.props.removeMode==="onzoom"&&this.props.map.zoom!==prevProps.map.zoom||this.props.removeMode==="onclickonmarker"&&this.props.click&&(this.props.click.features||[]).find(function(feature){return feature.id==="startupposmarker"})){prevProps.removeMarker("startupposmarker");this.markerSet=false}}}},{key:"render",value:function render(){return null}}])}(React.Component);_defineProperty(StartupMarker,"propTypes",{addMarker:PropTypes.func,click:PropTypes.object,map:PropTypes.object,removeMarker:PropTypes.func,/** When to remove the marker. Possible choices: onpan, onzoom, onclickonmarker. */removeMode:PropTypes.string,// onpan, onzoom, onclickonmarker
11
+ */var StartupMarker=/*#__PURE__*/function(_React$Component){function StartupMarker(props){var _this;_classCallCheck(this,StartupMarker);_this=_callSuper(this,StartupMarker,[props]);_this.markerSet=false;return _this}_inherits(StartupMarker,_React$Component);return _createClass(StartupMarker,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var highlight=["true","1"].includes(""+(this.props.startupParams&&this.props.startupParams.hc||"").toLowerCase());if(highlight&&this.props.theme&&!prevProps.theme&&this.props.startupParams.c){var point=this.props.startupParams.c.split(/[;,]/g).map(function(x){return parseFloat(x)});prevProps.addMarker("startupposmarker",point,"",this.props.startupParams.crs||this.props.map.projection);this.markerSet=true}else if(this.markerSet){if(this.props.removeMode==="onpan"&&this.props.map.center!==prevProps.map.center&&this.props.map.zoom===prevProps.map.zoom||this.props.removeMode==="onzoom"&&this.props.map.zoom!==prevProps.map.zoom||this.props.removeMode==="onclickonmarker"&&this.props.click&&(this.props.click.features||[]).find(function(feature){return feature.id==="startupposmarker"})){prevProps.removeMarker("startupposmarker");this.markerSet=false}}}},{key:"render",value:function render(){return null}}])}(React.Component);_defineProperty(StartupMarker,"propTypes",{addMarker:PropTypes.func,click:PropTypes.object,map:PropTypes.object,removeMarker:PropTypes.func,/** When to remove the marker. Possible choices: onpan, onzoom, onclickonmarker. */removeMode:PropTypes.string,// onpan, onzoom, onclickonmarker
12
12
  startupParams:PropTypes.object,theme:PropTypes.object});_defineProperty(StartupMarker,"defaultProps",{removeMode:"onpan"});export default connect(function(state){return{startupParams:state.localConfig.startupParams,click:state.map.click||{},map:state.map,theme:state.theme.current}},{addMarker:addMarker,removeMarker:removeMarker})(StartupMarker);