qwc2
Version:
QGIS Web Client
932 lines (930 loc) • 43.1 kB
JavaScript
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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return 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); }
/**
* Copyright 2017-2024 Sourcepole AG
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { connect } from 'react-redux';
import FileSaver from 'file-saver';
import isEmpty from 'lodash.isempty';
import Mousetrap from 'mousetrap';
import ol from 'openlayers';
import PropTypes from 'prop-types';
import { v4 as uuidv4 } from 'uuid';
import { LayerRole, addLayerFeatures, removeLayerFeatures } from '../../actions/layers';
import { changeRedliningState } from '../../actions/redlining';
import FeatureAttributesWindow from '../../components/FeatureAttributesWindow';
import LocationRecorder from '../../components/LocationRecorder';
import NumericInputWindow from '../../components/NumericInputWindow';
import { OlLayerAdded, OlLayerUpdated } from '../../components/map/OlLayer';
import FeatureStyles from '../../utils/FeatureStyles';
import MapUtils from '../../utils/MapUtils';
import MeasureUtils from '../../utils/MeasureUtils';
import VectorLayerUtils from '../../utils/VectorLayerUtils';
var GeomTypeConfig = {
Text: {
drawInteraction: function drawInteraction(opts) {
return new ol.interaction.Draw(_objectSpread(_objectSpread({}, opts), {}, {
type: "Point"
}));
},
editTool: 'Pick',
drawNodes: true
},
Point: {
drawInteraction: function drawInteraction(opts) {
return new ol.interaction.Draw(_objectSpread(_objectSpread({}, opts), {}, {
type: "Point"
}));
},
editTool: 'Pick',
drawNodes: true,
showRecordLocation: true
},
LineString: {
drawInteraction: function drawInteraction(opts) {
return new ol.interaction.Draw(_objectSpread(_objectSpread({}, opts), {}, {
type: "LineString"
}));
},
editTool: 'Pick',
drawNodes: true,
showRecordLocation: true
},
Polygon: {
drawInteraction: function drawInteraction(opts) {
return new ol.interaction.Draw(_objectSpread(_objectSpread({}, opts), {}, {
type: "Polygon"
}));
},
editTool: 'Pick',
drawNodes: true
},
Circle: {
drawInteraction: function drawInteraction(opts) {
return new ol.interaction.Draw(_objectSpread(_objectSpread({}, opts), {}, {
type: "Circle"
}));
},
editTool: 'Pick',
drawNodes: true,
regular: true
},
Ellipse: {
drawInteraction: function drawInteraction(opts) {
return new ol.interaction.DrawRegular(_objectSpread(_objectSpread({}, opts), {}, {
sides: 0
}));
},
editTool: 'Transform',
drawNodes: false
},
Box: {
drawInteraction: function drawInteraction(opts) {
return new ol.interaction.Draw(_objectSpread(_objectSpread({}, opts), {}, {
type: "Circle",
geometryFunction: ol.interaction.createBox()
}));
},
editTool: 'Transform',
drawNodes: true
},
Square: {
drawInteraction: function drawInteraction(opts) {
return new ol.interaction.DrawRegular(_objectSpread(_objectSpread({}, opts), {}, {
sides: 4,
squareCondition: function squareCondition() {
return true;
}
}));
},
editTool: 'Transform',
regular: true
}
};
/**
* Redlining support for the map component.
*/
var RedliningSupport = /*#__PURE__*/function (_React$Component) {
function RedliningSupport(props) {
var _this;
_classCallCheck(this, RedliningSupport);
_this = _callSuper(this, RedliningSupport, [props]);
_defineProperty(_this, "state", {
showRecordLocation: false
});
_defineProperty(_this, "updateCurrentFeature", function (feature) {
var deletedKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
if (_this.selectedFeatures.length === 1 && _this.props.redlining.selectedFeature) {
if (feature.circleParams) {
var circleParams = feature.circleParams;
_this.selectedFeatures[0].setGeometry(new ol.geom.Circle(circleParams.center, circleParams.radius));
} else {
_this.selectedFeatures[0].getGeometry().setCoordinates(feature.geometry.coordinates);
}
_this.selectedFeatures[0].setProperties(feature.properties, true);
deletedKeys.forEach(function (key) {
_this.selectedFeatures[0].unset(key);
});
_this.props.changeRedliningState({
selectedFeature: feature,
geomType: feature.shape
});
}
});
_defineProperty(_this, "styleOptions", function (styleProps, isText) {
return {
strokeColor: isText ? styleProps.textOutlineColor : styleProps.borderColor,
strokeWidth: 1 + 0.5 * styleProps.size,
strokeDash: styleProps.strokeDash,
fillColor: isText ? styleProps.textFillColor : styleProps.fillColor,
circleRadius: 5 + styleProps.size,
headmarker: styleProps.headmarker,
tailmarker: styleProps.tailmarker
};
});
_defineProperty(_this, "styleProps", function (feature) {
var styleOptions = feature.get('styleOptions');
var label = feature.get("label") || "";
var isText = feature.get("shape") === "Text";
return _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, isText ? "textOutlineColor" : "borderColor", styleOptions.strokeColor), "strokeDash", styleOptions.strokeDash), "size", (styleOptions.strokeWidth - 1) * 2), isText ? "textFillColor" : "fillColor", styleOptions.fillColor), "text", label), "headmarker", styleOptions.headmarker), "tailmarker", styleOptions.tailmarker);
});
_defineProperty(_this, "updateFeatureStyle", function (feature) {
_this.blockOnChange = true;
var styleProps = _this.props.redlining.style;
var isText = feature.get("shape") === "Text";
var styleName = isText ? "text" : "default";
var opts = _this.styleOptions(styleProps, isText);
if (!feature.get('measurements')) {
feature.set('label', styleProps.text);
}
feature.set('styleName', styleName);
feature.set('styleOptions', opts);
_this.blockOnChange = false;
});
_defineProperty(_this, "toggleFeatureMeasurements", function (feature) {
if (_this.props.redlining.measurements) {
var settings = {
displayCrs: _this.props.displayCrs,
lenUnit: _this.props.redlining.lenUnit,
areaUnit: _this.props.redlining.areaUnit
};
MeasureUtils.updateFeatureMeasurements(feature, feature.get('shape'), _this.props.mapCrs, settings);
} else if (feature.get('measurements')) {
feature.set('measurements', undefined);
feature.set('segment_labels', undefined);
feature.set('label', '');
}
});
_defineProperty(_this, "updateMeasurements", function (ev) {
if (_this.blockOnChange) {
return;
}
var feature = ev.target;
if (feature.get('measurements')) {
var settings = {
displayCrs: _this.props.displayCrs,
lenUnit: _this.props.redlining.lenUnit,
areaUnit: _this.props.redlining.areaUnit
};
MeasureUtils.updateFeatureMeasurements(feature, feature.get('shape'), _this.props.mapCrs, settings);
}
});
_defineProperty(_this, "styleFunction", function (feature) {
var styleOptions = feature.get("styleOptions");
var styleName = feature.get("styleName");
var styles = [];
if (styleName === "text") {
styles.push(_this.selectedTextStyle(feature, styleOptions));
}
styles.push.apply(styles, _toConsumableArray(FeatureStyles[styleName](feature, styleOptions)));
var shape = feature.get('shape');
var geomTypeConfig = GeomTypeConfig[shape];
if ((geomTypeConfig || {}).drawNodes !== false) {
styles.push(_this.selectedStyle);
}
return styles;
});
_defineProperty(_this, "searchRedliningLayer", function (layerId) {
var _this$props$map$getLa;
return (_this$props$map$getLa = _this.props.map.getLayers().getArray().find(function (l) {
return l.get('id') === layerId;
})) !== null && _this$props$map$getLa !== void 0 ? _this$props$map$getLa : null;
});
_defineProperty(_this, "waitForFeatureAndLayer", function (layerId, featureId, callback) {
var redliningLayer = _this.searchRedliningLayer(layerId);
if (!redliningLayer) {
OlLayerAdded.connect(function (layer) {
if (layer.get("id") === layerId) {
var feature = featureId ? layer.getSource().getFeatureById(featureId) : null;
callback(layer, feature);
return true;
}
return false;
});
} else if (featureId) {
var feature = redliningLayer.getSource().getFeatureById(featureId);
if (feature) {
callback(redliningLayer, feature);
} else {
OlLayerUpdated.connect(function (layer) {
if (layer.get("id") === layerId) {
var feat = layer.getSource().getFeatureById(featureId);
if (feat) {
callback(layer, feat);
return true;
}
}
return false;
});
}
} else {
callback(redliningLayer, null);
}
});
_defineProperty(_this, "addDrawInteraction", function () {
var geomTypeConfig = GeomTypeConfig[_this.props.redlining.geomType];
if (!geomTypeConfig) {
return;
}
var isFreeHand = _this.props.redlining.freehand;
var drawInteraction = geomTypeConfig.drawInteraction({
stopClick: true,
condition: function condition(event) {
return event.originalEvent.buttons === 1;
},
style: function style() {
return _this.picking ? [] : FeatureStyles.sketchInteraction();
},
freehand: isFreeHand
});
drawInteraction.on('drawstart', function (ev) {
if (_this.picking && _this.props.redlining.drawMultiple === false) {
return;
}
_this.leaveTemporaryEditMode();
ev.feature.setId(uuidv4());
ev.feature.set('shape', _this.props.redlining.geomType);
_this.updateFeatureStyle(ev.feature);
_this.toggleFeatureMeasurements(ev.feature);
_this.selectFeatures([ev.feature]);
}, _this);
drawInteraction.on('drawend', function (ev) {
_this.commitFeatures([ev.feature], _this.props.redlining, true);
_this.enterTemporaryEditMode(ev.feature.getId(), _this.props.redlining.layer, geomTypeConfig.editTool);
}, _this);
_this.props.map.addInteraction(drawInteraction);
_this.interactions.push(drawInteraction);
_this.setState({
showRecordLocation: geomTypeConfig.showRecordLocation
});
});
_defineProperty(_this, "enterTemporaryEditMode", function (featureId, layerId, editTool) {
_this.waitForFeatureAndLayer(layerId, featureId, function (redliningLayer, feature) {
if (!feature) {
return;
}
_this.selectFeatures([feature]);
if (editTool === 'Transform') {
_this.setupTransformInteraction(redliningLayer, _this.selectedFeatures);
} else {
_this.setupModifyInteraction(_this.selectedFeatures);
}
_this.picking = true;
});
});
_defineProperty(_this, "leaveTemporaryEditMode", function () {
_this.commitFeatures(_this.selectedFeatures, _this.props.redlining);
if (_this.picking) {
// Remove modify interactions
_this.props.map.removeInteraction(_this.interactions.pop());
_this.picking = false;
}
});
_defineProperty(_this, "addPickInteraction", function () {
var redliningLayer = _this.searchRedliningLayer(_this.props.redlining.layer);
if (!redliningLayer) {
return;
}
var selectInteraction = new ol.interaction.Select({
layers: [redliningLayer],
hitTolerance: 5
});
var currentEditInteraction = null;
selectInteraction.on('select', function (evt) {
if (evt.selected.length === 1 && _this.selectedFeatures.includes(evt.selected[0])) {
return;
}
_this.commitFeatures(_this.selectedFeatures, _this.props.redlining);
if (currentEditInteraction) {
_this.props.map.removeInteraction(currentEditInteraction);
_this.interactions = _this.interactions.filter(function (i) {
return i !== currentEditInteraction;
});
currentEditInteraction = null;
}
if (evt.selected.length === 1) {
_this.selectFeatures(evt.selected);
var geomTypeConfig = GeomTypeConfig[evt.selected[0].get('shape')];
if (geomTypeConfig && geomTypeConfig.editTool === 'Transform') {
currentEditInteraction = _this.setupTransformInteraction(redliningLayer, [evt.selected[0]]);
currentEditInteraction.on('select', function (ev) {
// Clear selection when selecting a different feature, and let the parent select interaction deal with the new feature
if (!isEmpty(_this.selectedFeatures) && !_this.selectedFeatures.includes(ev.feature)) {
_this.commitFeatures(_this.selectedFeatures, _this.props.redlining);
currentEditInteraction.setSelection(new ol.Collection());
}
});
} else {
currentEditInteraction = _this.setupModifyInteraction(selectInteraction.getFeatures().getArray());
}
}
}, _this);
if (_this.props.redlining.action === 'PickDraw') {
_this.props.map.on('click', _this.maybeEnterTemporaryDrawMode);
}
_this.props.map.addInteraction(selectInteraction);
_this.interactions.push(selectInteraction);
_this.picking = true;
});
_defineProperty(_this, "addTransformInteraction", function () {
var redliningLayer = _this.searchRedliningLayer(_this.props.redlining.layer);
if (!redliningLayer) {
return null;
}
var transformInteraction = _this.setupTransformInteraction(redliningLayer, [], true);
transformInteraction.on('select', function (evt) {
var added = evt.features.getArray().filter(function (x) {
return !_this.selectedFeatures.includes(x);
});
var removed = _this.selectedFeatures.filter(function (x) {
return !evt.features.getArray().includes(x);
});
_this.selectFeatures(added);
_this.commitFeatures(removed, _this.props.redlining);
});
_this.picking = true;
return transformInteraction;
});
_defineProperty(_this, "maybeEnterTemporaryDrawMode", function (ev) {
var redliningLayer = _this.searchRedliningLayer(_this.props.redlining.layer);
if (_this.selectedFeatures.length || !_this.props.redlining.drawMultiple && redliningLayer.getSource().getFeatures().length > 0) {
return;
}
var featureHit = false;
_this.props.map.forEachFeatureAtPixel(ev.pixel, function (feature, layer) {
featureHit |= layer === redliningLayer;
}, {
hitTolerance: 5
});
if (!redliningLayer || featureHit) {
return;
}
_this.reset(_this.props.redlining);
_this.props.map.un('click', _this.maybeEnterTemporaryDrawMode);
var geomTypeConfig = GeomTypeConfig[_this.props.redlining.geomType];
if (!geomTypeConfig) {
return;
}
var isFreeHand = _this.props.redlining.freehand;
var drawInteraction = geomTypeConfig.drawInteraction({
stopClick: true,
condition: function condition(event) {
return event.originalEvent.buttons === 1;
},
style: function style() {
return _this.picking ? [] : FeatureStyles.sketchInteraction();
},
freehand: isFreeHand
});
drawInteraction.on('drawstart', function (evt) {
evt.feature.setId(uuidv4());
evt.feature.set('shape', _this.props.redlining.geomType);
_this.updateFeatureStyle(evt.feature);
_this.toggleFeatureMeasurements(evt.feature);
_this.selectFeatures([evt.feature]);
}, _this);
drawInteraction.on('drawend', function () {
// Draw end
_this.commitFeatures(_this.selectedFeatures, _this.props.redlining, true);
_this.reset(_this.props.redlining);
// Ughh... Apparently we need to wait 250ms for the 'singleclick' event processing to finish to avoid pick interactions picking up the current event
setTimeout(function () {
return _this.addPickInteraction(true);
}, 300);
}, _this);
_this.props.map.addInteraction(drawInteraction);
_this.interactions.push(drawInteraction);
_this.picking = false;
var clickCoord = MapUtils.getHook(MapUtils.GET_SNAPPED_COORDINATES_FROM_PIXEL_HOOK)(ev.pixel);
drawInteraction.appendCoordinates([clickCoord]);
if (_this.props.redlining.geomType === 'Point') {
drawInteraction.finishDrawing();
}
});
_defineProperty(_this, "setupModifyInteraction", function () {
var selectedFeatures = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var modifyInteraction = new ol.interaction.Modify({
features: new ol.Collection(selectedFeatures),
condition: function condition(event) {
return event.originalEvent.buttons === 1;
},
deleteCondition: function deleteCondition(event) {
// delete vertices on SHIFT + click
if (event.type === "pointerdown" && ol.events.condition.shiftKeyOnly(event)) {
_this.props.map.setIgnoreNextClick(true);
}
return ol.events.condition.shiftKeyOnly(event) && ol.events.condition.singleClick(event);
}
});
modifyInteraction.on('modifyend', _this.updateSelectedFeature);
_this.props.map.addInteraction(modifyInteraction);
_this.interactions.push(modifyInteraction);
return modifyInteraction;
});
_defineProperty(_this, "setupTransformInteraction", function (redliningLayer) {
var selectedFeatures = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var multi = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var transformInteraction = new ol.interaction.Transform({
stretch: false,
addCondition: multi ? function (ev) {
return ev.originalEvent.ctrlKey;
} : null,
keepAspectRatio: function keepAspectRatio(ev) {
return _this.selectedFeatures.find(function (f) {
return GeomTypeConfig[f.get('shape')].regular;
}) || ol.events.condition.shiftKeyOnly(ev);
},
layers: [redliningLayer],
translateFeature: true
});
// Hacky workaround translateFeature interfering with ctrl-click to deselect selected features
var origHandleDownEvent = transformInteraction.handleDownEvent;
transformInteraction.handleDownEvent = function (evt) {
if (evt.originalEvent.ctrlKey) {
transformInteraction.set('translateFeature', false);
}
var ret = origHandleDownEvent.call(transformInteraction, evt);
transformInteraction.set('translateFeature', true);
return ret;
};
transformInteraction.on('rotating', function (ev) {
ev.features.forEach(function (feature) {
if (feature.get('shape') === 'Text') {
feature.set('rotation', -ev.angle);
}
});
});
transformInteraction.on('rotateend', _this.updateSelectedFeature);
transformInteraction.on('translateend', _this.updateSelectedFeature);
transformInteraction.on('scaleend', _this.updateSelectedFeature);
_this.props.map.addInteraction(transformInteraction);
_this.interactions.push(transformInteraction);
transformInteraction.setSelection(new ol.Collection(selectedFeatures));
return transformInteraction;
});
_defineProperty(_this, "updateSelectedFeature", function () {
var _featureObj$shape, _featureObj;
var featureObj = null;
if (_this.selectedFeatures.length === 1) {
featureObj = _this.serializeFeature(_this.selectedFeatures[0]);
} else if (_this.selectedFeatures.length > 1) {
featureObj = {
type: "FeatureCollection",
features: []
};
}
_this.props.changeRedliningState({
selectedFeature: featureObj,
geomType: (_featureObj$shape = (_featureObj = featureObj) === null || _featureObj === void 0 ? void 0 : _featureObj.shape) !== null && _featureObj$shape !== void 0 ? _featureObj$shape : _this.props.redlining.geomType
});
});
_defineProperty(_this, "triggerDelete", function () {
_this.props.changeRedliningState({
action: "Delete"
});
});
_defineProperty(_this, "deleteCurrentFeatures", function () {
if (_this.selectedFeatures.length) {
_this.props.removeLayerFeatures(_this.props.redlining.layer, _this.selectedFeatures.map(function (f) {
return f.getId();
}), true);
_this.selectedFeatures = [];
}
});
_defineProperty(_this, "cloneCurrentFeatures", function () {
if (isEmpty(_this.selectedFeatures)) {
return;
}
var _shiftCoordinates = function shiftCoordinates(coords) {
if (typeof coords[0] === 'number') {
coords[0] += 10;
coords[1] += 10;
} else {
coords.map(_shiftCoordinates);
}
};
var cloneIds = [];
var newFeatureObjs = _this.selectedFeatures.map(function (feature) {
_this.deselectFeature(feature, false);
var featureObj = _this.serializeFeature(feature);
featureObj.id = uuidv4();
_shiftCoordinates(featureObj.geometry.coordinates);
cloneIds.push(featureObj.id);
return featureObj;
});
_this.updateRedliningState(true);
var layer = {
id: _this.props.redlining.layer,
title: _this.props.redlining.layerTitle,
role: LayerRole.USERLAYER
};
_this.props.addLayerFeatures(layer, newFeatureObjs);
_this.waitForFeatureAndLayer(_this.props.redlining.layer, cloneIds[0], function (l) {
var features = cloneIds.map(function (id) {
return l.getSource().getFeatureById(id);
});
_this.selectFeatures(features);
while (_this.interactions.length > 0) {
_this.props.map.removeInteraction(_this.interactions.shift());
}
_this.addTransformInteraction().setSelection(new ol.Collection(features));
});
});
_defineProperty(_this, "updateRedliningState", function (firstSelection) {
if (_this.selectedFeatures.length > 0) {
var features = _this.selectedFeatures;
var featureObj = features.length === 1 ? _this.serializeFeature(features[0]) : {
type: "FeatureCollection",
features: []
};
var newRedliningState = {
selectedFeature: featureObj
};
if (firstSelection || _this.selectedFeatures.length === 1) {
var _featureObj$shape2;
newRedliningState.style = _this.styleProps(features[0]);
newRedliningState.measurements = !!features[0].get('measurements');
newRedliningState.geomType = (_featureObj$shape2 = featureObj === null || featureObj === void 0 ? void 0 : featureObj.shape) !== null && _featureObj$shape2 !== void 0 ? _featureObj$shape2 : _this.props.redlining.geomType;
var measurements = features[0].get('measurements');
if (measurements) {
newRedliningState.lenUnit = measurements.lenUnit;
newRedliningState.areaUnit = measurements.areaUnit;
}
}
_this.props.changeRedliningState(newRedliningState);
} else {
_this.props.changeRedliningState({
selectedFeature: null
});
}
});
_defineProperty(_this, "selectFeatures", function (features) {
var firstSelection = isEmpty(_this.selectedFeatures);
features.forEach(function (feature) {
feature.setStyle(_this.styleFunction);
feature.on('change', _this.updateMeasurements);
_this.selectedFeatures.push(feature);
});
_this.updateRedliningState(firstSelection);
});
_defineProperty(_this, "deselectFeature", function (feature, updateState) {
var styleName = feature.get("shape") === "Text" ? "text" : "default";
var style = FeatureStyles[styleName](feature, feature.get('styleOptions'));
feature.setStyle(style);
feature.un('change', _this.updateMeasurements);
_this.selectedFeatures = _this.selectedFeatures.filter(function (f) {
return f !== feature;
});
if (updateState) {
_this.updateRedliningState(false);
}
});
_defineProperty(_this, "commitFeatures", function (features, redliningProps) {
var newFeature = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var featureObjects = features.map(function (feature) {
var _featureObj$geometry;
_this.deselectFeature(feature, false);
var featureObj = _this.serializeFeature(feature);
// Don't commit empty/invalid features
if (featureObj.shape === "Text" && !featureObj.properties.label || featureObj.shape === "Circle" && featureObj.circleParams.radius === 0 || ((_featureObj$geometry = featureObj.geometry) === null || _featureObj$geometry === void 0 ? void 0 : _featureObj$geometry.type) === "Polygon" && feature.getGeometry().getArea() === 0) {
if (!newFeature) {
_this.props.removeLayerFeatures(redliningProps.layer, [featureObj.id]);
}
return null;
}
if (featureObj.shape === "Circle") {
var _featureObj$circlePar = featureObj.circleParams,
center = _featureObj$circlePar.center,
radius = _featureObj$circlePar.radius;
var deg2rad = Math.PI / 180;
featureObj.geometry.type = "Polygon";
featureObj.geometry.coordinates = [Array.apply(null, Array(91)).map(function (item, index) {
return [center[0] + radius * Math.cos(4 * index * deg2rad), center[1] + radius * Math.sin(4 * index * deg2rad)];
})];
}
if (featureObj.geometry.type === "LineString" || featureObj.geometry.type === "Polygon") {
featureObj.geometry.coordinates = VectorLayerUtils.removeDuplicateNodes(featureObj.geometry.coordinates);
}
return featureObj;
}).filter(Boolean);
if (isEmpty(featureObjects)) {
return null;
}
var layer = {
id: redliningProps.layer,
title: redliningProps.layerTitle,
role: LayerRole.USERLAYER
};
_this.props.addLayerFeatures(layer, featureObjects);
_this.updateRedliningState();
return featureObjects;
});
_defineProperty(_this, "reset", function (redliningProps) {
_this.setState({
showRecordLocation: false
});
while (_this.interactions.length > 0) {
_this.props.map.removeInteraction(_this.interactions.shift());
}
if (_this.picking) {
_this.commitFeatures(_this.selectedFeatures, redliningProps, false);
} else {
_this.selectedFeatures.forEach(function (feature) {
_this.deselectFeature(feature, false);
});
_this.updateRedliningState(false);
}
_this.props.map.un('click', _this.maybeEnterTemporaryDrawMode);
_this.picking = false;
});
_defineProperty(_this, "serializeFeature", function (feature) {
var format = new ol.format.GeoJSON();
var featureObject = format.writeFeatureObject(feature);
if (feature.get("shape") === "Circle") {
featureObject.circleParams = {
center: feature.getGeometry().getCenter(),
radius: feature.getGeometry().getRadius()
};
}
featureObject.styleName = feature.get('styleName');
featureObject.styleOptions = feature.get('styleOptions');
featureObject.shape = feature.get('shape');
featureObject.measurements = feature.get('measurements');
featureObject.crs = _this.props.mapCrs;
// Don't pollute GeoJSON object properties with internal props
delete featureObject.properties.styleName;
delete featureObject.properties.styleOptions;
delete featureObject.properties.shape;
delete featureObject.properties.measurements;
delete featureObject.properties.circleParams;
// Don't store empty label prop
if (featureObject.properties.label === "") {
delete featureObject.properties.label;
}
return featureObject;
});
_defineProperty(_this, "export", function () {
var committedFeatures = _this.commitFeatures(_this.selectedFeatures, _this.props.redlining);
var layer = _this.props.layers.find(function (l) {
return l.id === _this.props.redlining.layer;
});
if (!layer) {
return;
}
if (_this.props.redlining.format === "geojson") {
var geojson = JSON.stringify({
type: "FeatureCollection",
features: layer.features.map(function (feature) {
var _committedFeatures$fi;
var newFeature = _objectSpread({}, (_committedFeatures$fi = committedFeatures.find(function (f) {
return f.id === feature.id;
})) !== null && _committedFeatures$fi !== void 0 ? _committedFeatures$fi : feature);
newFeature.geometry = VectorLayerUtils.reprojectGeometry(feature.geometry, feature.crs || _this.props.mapCrs, 'EPSG:4326');
delete newFeature.crs;
return newFeature;
})
}, null, ' ');
FileSaver.saveAs(new Blob([geojson], {
type: "text/plain;charset=utf-8"
}), layer.title + ".json");
} else if (_this.props.redlining.format === "kml") {
var nativeLayer = _this.searchRedliningLayer(_this.props.redlining.layer);
if (!nativeLayer) {
return;
}
var kmlFormat = new ol.format.KML();
var features = nativeLayer.getSource().getFeatures().map(function (feature) {
// Circle is not supported by kml format
if (feature.getGeometry() instanceof ol.geom.Circle) {
feature = feature.clone();
feature.setGeometry(ol.geom.polygonFromCircle(feature.getGeometry()));
}
return feature;
});
var data = kmlFormat.writeFeatures(features, {
featureProjection: _this.props.mapCrs
});
FileSaver.saveAs(new Blob([data], {
type: "application/vnd.google-earth.kml+xml"
}), layer.title + ".kml");
}
});
_this.interactions = [];
_this.picking = false;
_this.selectedFeatures = [];
_this.blockOnChange = false;
_this.selectedTextStyle = function (feature, opts) {
return new ol.style.Style({
text: new ol.style.Text({
font: '10pt sans-serif',
text: feature.getProperties().label || "",
rotation: feature.getProperties().rotation || 0,
scale: opts.strokeWidth,
fill: new ol.style.Fill({
color: opts.textFillColor
}),
stroke: new ol.style.Stroke({
color: [0, 0, 0, 0.5],
width: 4
})
})
});
};
var geometryFunction = function geometryFunction(feature) {
if (feature.getGeometry().getType() === "Point") {
return new ol.geom.MultiPoint([feature.getGeometry().getCoordinates()]);
} else if (feature.getGeometry().getType() === "LineString") {
return new ol.geom.MultiPoint(feature.getGeometry().getCoordinates());
} else if (feature.getGeometry().getType() === "Polygon") {
return new ol.geom.MultiPoint(feature.getGeometry().getCoordinates()[0]);
} else if (feature.getGeometry().getType() === "Circle") {
var center = feature.getGeometry().getCenter();
return new ol.geom.MultiPoint([center, [center[0] + feature.getGeometry().getRadius(), center[1]]]);
}
return null;
};
_this.selectedStyle = FeatureStyles.interactionVertex({
geometryFunction: geometryFunction
});
return _this;
}
_inherits(RedliningSupport, _React$Component);
return _createClass(RedliningSupport, [{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
var _this2 = this;
// Bind keyboard shortcuts to delete features
if (this.props.redlining.action && !prevProps.redlining.action) {
Mousetrap.bind('del', this.triggerDelete);
Mousetrap.bind('backspace', this.triggerDelete);
} else if (!this.props.redlining.action && prevProps.redlining.action) {
Mousetrap.unbind('del', this.triggerDelete);
Mousetrap.unbind('backspace', this.triggerDelete);
}
// Handle delete action immediately and reset the redlining state to the previous action
if (this.props.redlining.action === 'Delete') {
this.deleteCurrentFeatures();
this.props.changeRedliningState(_objectSpread(_objectSpread({}, prevProps.redlining), {}, {
selectedFeature: null
}));
return;
}
if (this.props.redlining.action === 'Clone') {
this.cloneCurrentFeatures();
this.props.changeRedliningState(_objectSpread(_objectSpread({}, prevProps.redlining), {}, {
selectedFeature: null
}));
return;
}
if (this.props.redlining.action === 'Export') {
this["export"]();
this.props.changeRedliningState(_objectSpread(_objectSpread({}, prevProps.redlining), {}, {
selectedFeature: null
}));
return;
}
var recreateInteraction = this.props.redlining.action !== prevProps.redlining.action || this.props.redlining.layer !== prevProps.redlining.layer || ['Draw', 'PickDraw'].includes(this.props.redlining.action) && this.props.redlining.geomType !== prevProps.redlining.geomType || this.props.redlining.freehand !== prevProps.redlining.freehand || this.props.redlining.drawMultiple !== prevProps.redlining.drawMultiple;
if (recreateInteraction) {
// Commit to previous layer in case layer changed
this.reset(prevProps.redlining);
if (this.props.redlining.action === 'Draw') {
this.addDrawInteraction();
} else if (this.props.redlining.action === 'Transform') {
this.addTransformInteraction();
} else if (this.props.redlining.action === 'Pick' || this.props.redlining.action === 'Buffer') {
this.addPickInteraction();
} else if (this.props.redlining.action === 'PickDraw') {
this.waitForFeatureAndLayer(this.props.redlining.layer, null, function () {
return _this2.addPickInteraction();
});
}
}
if (this.selectedFeatures) {
// Update feature style
if (this.props.redlining.style !== prevProps.redlining.style) {
this.selectedFeatures.forEach(this.updateFeatureStyle);
}
// Update current feature measurements
if (this.props.redlining.measurements !== prevProps.redlining.measurements) {
this.selectedFeatures.forEach(this.toggleFeatureMeasurements);
} else if (this.props.map.displayCrs !== prevProps.map.displayCrs || this.props.redlining.lenUnit !== prevProps.redlining.lenUnit || this.props.redlining.areaUnit !== prevProps.redlining.areaUnit) {
this.selectedFeatures.forEach(function (feature) {
return feature.changed();
});
}
}
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var widgets = [];
if (this.props.redlining.extraAction === "NumericInput") {
widgets.push(/*#__PURE__*/React.createElement(NumericInputWindow, {
feature: this.props.redlining.selectedFeature,
key: "NumericInputWindow",
onClose: function onClose() {
return _this3.props.changeRedliningState({
extraAction: null
});
},
onFeatureChanged: this.updateCurrentFeature
}));
} else if (this.props.redlining.extraAction === "FeatureAttributes") {
widgets.push(/*#__PURE__*/React.createElement(FeatureAttributesWindow, {
feature: this.props.redlining.selectedFeature,
key: "FeatureAttributesWindow",
layerid: this.props.redlining.layer,
onClose: function onClose() {
return _this3.props.changeRedliningState({
extraAction: null
});
},
onFeatureChanged: this.updateCurrentFeature
}));
}
if (this.state.showRecordLocation) {
var drawInteraction = this.interactions.find(function (interaction) {
return interaction instanceof ol.interaction.Draw;
});
widgets.push(/*#__PURE__*/React.createElement(LocationRecorder, {
drawInteraction: drawInteraction,
geomType: this.props.redlining.geomType,
key: "LocationRecorder",
map: this.props.map
}));
}
return widgets;
}
}]);
}(React.Component);
_defineProperty(RedliningSupport, "propTypes", {
addLayerFeatures: PropTypes.func,
changeRedliningState: PropTypes.func,
displayCrs: PropTypes.string,
layers: PropTypes.array,
map: PropTypes.object,
mapCrs: PropTypes.string,
redlining: PropTypes.object,
removeLayerFeatures: PropTypes.func
});
_defineProperty(RedliningSupport, "defaultProps", {
redlining: {}
});
export default connect(function (state) {
return {
displayCrs: state.map.displayCrs,
mapCrs: state.map.projection,
redlining: state.redlining,
layers: state.layers.flat
};
}, {
changeRedliningState: changeRedliningState,
addLayerFeatures: addLayerFeatures,
removeLayerFeatures: removeLayerFeatures
})(RedliningSupport);