terra-draw 1.18.1 → 1.20.0

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.
@@ -1,2 +1,2 @@
1
- function t(){return t=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var o in i)({}).hasOwnProperty.call(i,o)&&(t[o]=i[o])}return t},t.apply(null,arguments)}var e;!function(t){t.Commit="commit",t.Provisional="provisional",t.Finish="finish"}(e||(e={}));const i="https://raw.githubusercontent.com/JamesLMilner/terra-draw/refs/heads/main/assets/markers/marker-blue.png",o={SELECTED:"selected",MID_POINT:"midPoint",SELECTION_POINT_FEATURE_ID:"selectionPointFeatureId",SELECTION_POINT:"selectionPoint"},s={MODE:"mode",CURRENTLY_DRAWING:"currentlyDrawing",EDITED:"edited",CLOSING_POINT:"closingPoint",SNAPPING_POINT:"snappingPoint",COORDINATE_POINT:"coordinatePoint",COORDINATE_POINT_FEATURE_ID:"coordinatePointFeatureId",COORDINATE_POINT_IDS:"coordinatePointIds",PROVISIONAL_COORDINATE_COUNT:"provisionalCoordinateCount",COMMITTED_COORDINATE_COUNT:"committedCoordinateCount",MARKER:"marker"},r=10;function n(t){return Boolean(t&&"object"==typeof t&&null!==t&&!Array.isArray(t))}function a(t){return Boolean(t&&"object"==typeof t&&"properties"in t&&"object"==typeof t.properties&&null!==t.properties&&"mode"in t.properties)}function d(t){return!!function(t){return"number"==typeof t&&!isNaN(new Date(t).valueOf())}(t)}const h="Feature is not a Polygon",l="Feature mode property does not match the mode being added to";var c;!function(t){t.Drawing="drawing",t.Select="select",t.Static="static",t.Render="render"}(c||(c={}));const u={rightClick:!0,contextMenu:!1,leftClick:!0,onDragStart:!0,onDrag:!0,onDragEnd:!0};class p{get state(){return this._state}set state(t){throw new Error("Please use the modes lifecycle methods")}get styles(){return this._styles}set styles(t){if("object"!=typeof t)throw new Error("Styling must be an object");this.onStyleChange&&this.onStyleChange([],"styling"),this._styles=t}registerBehaviors(t){}constructor(t,e=!1){this._state="unregistered",this._styles={},this.pointerEvents=u,this.behaviors=[],this.validate=void 0,this.pointerDistance=40,this.coordinatePrecision=void 0,this.onStyleChange=void 0,this.store=void 0,this.projection="web-mercator",this.setDoubleClickToZoom=void 0,this.unproject=void 0,this.project=void 0,this.setCursor=void 0,this.type=c.Drawing,this.mode="base",e||this.updateOptions(t)}updateOptions(e){null!=e&&e.styles&&(this.styles=t({},this._styles,e.styles)),null!=e&&e.pointerDistance&&(this.pointerDistance=e.pointerDistance),null!=e&&e.validation&&(this.validate=e&&e.validation),null!=e&&e.projection&&(this.projection=e.projection),void 0!==(null==e?void 0:e.pointerEvents)&&(this.pointerEvents=e.pointerEvents)}allowPointerEvent(t,e){return"boolean"==typeof t?t:"function"!=typeof t||t(e)}setDrawing(){if("started"!==this._state)throw new Error("Mode must be unregistered or stopped to start");this._state="drawing"}setStarted(){if("stopped"!==this._state&&"registered"!==this._state&&"drawing"!==this._state&&"selecting"!==this._state)throw new Error("Mode must be unregistered or stopped to start");this._state="started",this.setDoubleClickToZoom(!1)}setStopped(){if("started"!==this._state)throw new Error("Mode must be started to be stopped");this._state="stopped",this.setDoubleClickToZoom(!0)}register(t){if("unregistered"!==this._state)throw new Error("Can not register unless mode is unregistered");this._state="registered",this.store=t.store,this.store.registerOnChange(t.onChange),this.setDoubleClickToZoom=t.setDoubleClickToZoom,this.project=t.project,this.unproject=t.unproject,this.onSelect=t.onSelect,this.onDeselect=t.onDeselect,this.setCursor=t.setCursor,this.onStyleChange=t.onChange,this.onFinish=t.onFinish,this.coordinatePrecision=t.coordinatePrecision,this.registerBehaviors({mode:t.mode,store:this.store,project:this.project,unproject:this.unproject,pointerDistance:this.pointerDistance,coordinatePrecision:t.coordinatePrecision,projection:this.projection})}validateFeature(t){return this.performFeatureValidation(t)}afterFeatureAdded(t){}afterFeatureUpdated(t){}performFeatureValidation(t){if("unregistered"===this._state)throw new Error("Mode must be registered");const i=function(t,e){let i;if(n(t))if(null==t.id)i="Feature has no id";else if("string"!=typeof t.id&&"number"!=typeof t.id)i="Feature must be string or number as per GeoJSON spec";else if(e(t.id))if(n(t.geometry))if(n(t.properties))if("string"==typeof t.geometry.type&&["Polygon","LineString","Point"].includes(t.geometry.type))if(Array.isArray(t.geometry.coordinates)){if(!t.properties.mode||"string"!=typeof t.properties.mode)return{valid:!1,reason:"Feature does not have a valid mode property"}}else i="Feature coordinates is not an array";else i="Feature is not Point, LineString or Polygon";else i="Feature has no properties";else i="Feature has no geometry";else i="Feature must match the id strategy (default is UUID4)";else i="Feature is not object";return i?{valid:!1,reason:i}:{valid:!0}}(t,this.store.idStrategy.isValidId);if(this.validate){const o=this.validate(t,{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional});return{valid:i.valid&&o.valid,reason:o.reason}}return{valid:i.valid,reason:i.reason}}validateModeFeature(t,e){const i=this.performFeatureValidation(t);return i.valid?t.properties.mode!==this.mode?{valid:!1,reason:l}:e(t):{valid:!1,reason:i.reason}}onFinish(t,e){}onDeselect(t){}onSelect(t){}onKeyDown(t){}onKeyUp(t){}onMouseMove(t){}onClick(t){}onDragStart(t,e){}onDrag(t,e){}onDragEnd(t,e){}getHexColorStylingValue(t,e,i){return this.getStylingValue(t,e,i)}getNumericStylingValue(t,e,i){return this.getStylingValue(t,e,i)}getUrlStylingValue(t,e,i){return this.getStylingValue(t,e,i)}getStylingValue(t,e,i){return void 0===t?e:"function"==typeof t?t(i):t}}class g extends p{constructor(...t){super(...t),this.type=c.Select}}function y(t,e){const i=t=>t*Math.PI/180,o=i(t[1]),s=i(t[0]),r=i(e[1]),n=r-o,a=i(e[0])-s,d=Math.sin(n/2)*Math.sin(n/2)+Math.cos(o)*Math.cos(r)*Math.sin(a/2)*Math.sin(a/2);return 2*Math.atan2(Math.sqrt(d),Math.sqrt(1-d))*6371e3/1e3}const f=6371008.8;function m(t){return t%360*Math.PI/180}function v(t){return t/6371.0088}function C(t){return t%(2*Math.PI)*180/Math.PI}function P(t,e=9){const i=Math.pow(10,e);return Math.round(t*i)/i}const I=57.29577951308232,x=.017453292519943295,E=6378137,S=(t,e)=>({x:0===t?0:t*x*E,y:0===e?0:Math.log(Math.tan(Math.PI/4+e*x/2))*E}),M=(t,e)=>({lng:0===t?0:I*(t/E),lat:0===e?0:(2*Math.atan(Math.exp(e/E))-Math.PI/2)*I});function F(t,e,i){const o=m(t[0]),s=m(t[1]),r=m(i),n=v(e),a=Math.asin(Math.sin(s)*Math.cos(n)+Math.cos(s)*Math.sin(n)*Math.cos(r));return[C(o+Math.atan2(Math.sin(r)*Math.sin(n)*Math.cos(s),Math.cos(n)-Math.sin(s)*Math.sin(a))),C(a)]}function D(t){const{center:e,radiusKilometers:i,coordinatePrecision:o}=t,s=t.steps?t.steps:64,r=[];for(let t=0;t<s;t++){const n=F(e,i,-360*t/s);r.push([P(n[0],o),P(n[1],o)])}return r.push(r[0]),{type:"Feature",geometry:{type:"Polygon",coordinates:[r]},properties:{}}}function w(t){let e;if("Polygon"===t.geometry.type)e=t.geometry.coordinates;else{if("LineString"!==t.geometry.type)throw new Error("Self intersects only accepts Polygons and LineStrings");e=[t.geometry.coordinates]}const i=[];for(let t=0;t<e.length;t++)for(let i=0;i<e[t].length-1;i++)for(let o=0;o<e.length;o++)for(let r=0;r<e[o].length-1;r++)s(t,i,o,r);return i.length>0;function o(t){return t<0||t>1}function s(t,s,r,n){const a=e[t][s],d=e[t][s+1],h=e[r][n],l=e[r][n+1],c=function(t,e,i,o){if(O(t,i)||O(t,o)||O(e,i)||O(o,i))return null;const s=t[0],r=t[1],n=e[0],a=e[1],d=i[0],h=i[1],l=o[0],c=o[1],u=(s-n)*(h-c)-(r-a)*(d-l);return 0===u?null:[((s*a-r*n)*(d-l)-(s-n)*(d*c-h*l))/u,((s*a-r*n)*(h-c)-(r-a)*(d*c-h*l))/u]}(a,d,h,l);if(null===c)return;let u,p;u=d[0]!==a[0]?(c[0]-a[0])/(d[0]-a[0]):(c[1]-a[1])/(d[1]-a[1]),p=l[0]!==h[0]?(c[0]-h[0])/(l[0]-h[0]):(c[1]-h[1])/(l[1]-h[1]),o(u)||o(p)||(c.toString(),i.push(c))}}function O(t,e){return t[0]===e[0]&&t[1]===e[1]}function k(t,e){return b(t[0])<=e&&b(t[1])<=e}function _(t){return 2===t.length&&"number"==typeof t[0]&&"number"==typeof t[1]&&Infinity!==t[0]&&Infinity!==t[1]&&(i=t[0])>=-180&&i<=180&&(e=t[1])>=-90&&e<=90;var e,i}function b(t){let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}const N="Feature has holes",T="Feature has less than 4 coordinates",W="Feature has invalid coordinates",j="Feature coordinates are not closed";function B(t,e){if("Polygon"!==t.geometry.type)return{valid:!1,reason:"Feature is not a Polygon"};if(1!==t.geometry.coordinates.length)return{valid:!1,reason:N};if(t.geometry.coordinates[0].length<4)return{valid:!1,reason:T};for(let i=0;i<t.geometry.coordinates[0].length;i++){if(!_(t.geometry.coordinates[0][i]))return{valid:!1,reason:W};if(!k(t.geometry.coordinates[0][i],e))return{valid:!1,reason:"Feature has coordinates with excessive precision"}}return(i=t.geometry.coordinates[0][0])[0]!==(o=t.geometry.coordinates[0][t.geometry.coordinates[0].length-1])[0]||i[1]!==o[1]?{valid:!1,reason:j}:{valid:!0};var i,o}function G(t,e){const i=B(t,e);return i.valid?w(t)?{valid:!1,reason:"Feature intersects itself"}:{valid:!0}:i}const R={cancel:"Escape",finish:"Enter"},U={start:"crosshair"};class L extends p{constructor(t){super(t,!0),this.mode="circle",this.center=void 0,this.clickCount=0,this.currentCircleId=void 0,this.keyEvents=R,this.cursors=U,this.startingRadiusKilometers=1e-5,this.cursorMovedAfterInitialCursorDown=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.startingRadiusKilometers&&(this.startingRadiusKilometers=e.startingRadiusKilometers)}close(){if(void 0===this.currentCircleId)return;this.store.updateProperty([{id:this.currentCircleId,property:s.CURRENTLY_DRAWING,value:void 0}]);const t=this.currentCircleId;if(this.validate&&t){const i=this.store.getGeometryCopy(t);if(!this.validate({type:"Feature",id:t,geometry:i,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid)return}this.cursorMovedAfterInitialCursorDown=!1,this.center=void 0,this.currentCircleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),this.onFinish(t,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))if(0===this.clickCount){this.center=[t.lng,t.lat];const e=D({center:this.center,radiusKilometers:this.startingRadiusKilometers,coordinatePrecision:this.coordinatePrecision}),[i]=this.store.create([{geometry:e.geometry,properties:{mode:this.mode,radiusKilometers:this.startingRadiusKilometers,[s.CURRENTLY_DRAWING]:!0}}]);this.currentCircleId=i,this.clickCount++,this.cursorMovedAfterInitialCursorDown=!1,this.setDrawing()}else 1===this.clickCount&&this.center&&void 0!==this.currentCircleId&&this.cursorMovedAfterInitialCursorDown&&this.updateCircle(t),this.close()}onMouseMove(t){this.cursorMovedAfterInitialCursorDown=!0,this.updateCircle(t)}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentCircleId;this.center=void 0,this.currentCircleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t])}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return"Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r,i):i}validateFeature(t){return this.validateModeFeature(t,t=>G(t,this.coordinatePrecision))}updateCircle(t){if(1===this.clickCount&&this.center&&this.currentCircleId){const i=y(this.center,[t.lng,t.lat]);let o;if("web-mercator"===this.projection){const e=function(t,e){const i=1e3*y(t,e);if(0===i)return 1;const{x:o,y:s}=S(t[0],t[1]),{x:r,y:n}=S(e[0],e[1]);return Math.sqrt(Math.pow(r-o,2)+Math.pow(n-s,2))/i}(this.center,[t.lng,t.lat]);o=function(t){const{center:e,radiusKilometers:i,coordinatePrecision:o}=t,s=t.steps?t.steps:64,r=1e3*i,[n,a]=e,{x:d,y:h}=S(n,a),l=[];for(let t=0;t<s;t++){const e=360*t/s*Math.PI/180,i=r*Math.cos(e),n=r*Math.sin(e),[a,c]=[d+i,h+n],{lng:u,lat:p}=M(a,c);l.push([P(u,o),P(p,o)])}return l.push(l[0]),{type:"Feature",geometry:{type:"Polygon",coordinates:[l]},properties:{}}}({center:this.center,radiusKilometers:i*e,coordinatePrecision:this.coordinatePrecision})}else{if("globe"!==this.projection)throw new Error("Invalid projection");o=D({center:this.center,radiusKilometers:i,coordinatePrecision:this.coordinatePrecision})}if(this.validate&&!this.validate({type:"Feature",id:this.currentCircleId,geometry:o.geometry,properties:{radiusKilometers:i}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional}).valid)return;this.store.updateGeometry([{id:this.currentCircleId,geometry:o.geometry}]),this.store.updateProperty([{id:this.currentCircleId,property:"radiusKilometers",value:i}])}}afterFeatureUpdated(t){this.currentCircleId===t.id&&(this.cursorMovedAfterInitialCursorDown=!1,this.center=void 0,this.currentCircleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted())}}const A=(t,e)=>{const{x:i,y:o}=t,{x:s,y:r}=e,n=s-i,a=r-o;return Math.sqrt(a*a+n*n)};function V(t){const e=function(t){const e=t.coordinates[0];let i=0;for(let t=0;t<e.length-1;t++){const[o,s]=e[t],[r,n]=e[t+1];i+=(r-o)*(n+s)}return i<0}(t);if(!e)return{type:"Polygon",coordinates:[t.coordinates[0].reverse()]}}const Y={cancel:"Escape",finish:"Enter"},K={start:"crosshair",close:"pointer"};class z extends p{constructor(t){super(t,!0),this.mode="freehand",this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,this.minDistance=20,this.keyEvents=Y,this.cursors=K,this.preventPointsNearClose=!0,this.autoClose=!1,this.autoCloseTimeout=500,this.hasLeftStartingPoint=!1,this.preventNewFeature=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.minDistance&&(this.minDistance=e.minDistance),void 0!==(null==e?void 0:e.preventPointsNearClose)&&(this.preventPointsNearClose=e.preventPointsNearClose),void 0!==(null==e?void 0:e.autoClose)&&(this.autoClose=e.autoClose),null!=e&&e.autoCloseTimeout&&(this.autoCloseTimeout=e.autoCloseTimeout),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors))}close(){if(void 0===this.currentId)return;if(this.currentId){const t=V(this.store.getGeometryCopy(this.currentId));t&&this.store.updateGeometry([{id:this.currentId,geometry:t}]),this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}])}const t=this.currentId;if(this.validate&&t){const i=this.store.getGeometryCopy(t);if(!this.validate({type:"Feature",id:t,geometry:i,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid)return}this.closingPointId&&this.store.delete([this.closingPointId]),this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,this.hasLeftStartingPoint=!1,"drawing"===this.state&&this.setStarted(),this.onFinish(t,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){if(void 0===this.currentId||!1===this.startingClick)return void this.setCursor(this.cursors.start);const i=this.store.getGeometryCopy(this.currentId),o=i.coordinates[0].length-2,[s,r]=i.coordinates[0][o],{x:n,y:a}=this.project(s,r),d=A({x:n,y:a},{x:t.containerX,y:t.containerY}),[h,l]=i.coordinates[0][0],{x:c,y:u}=this.project(h,l);if(A({x:c,y:u},{x:t.containerX,y:t.containerY})<this.pointerDistance){if(this.autoClose&&this.hasLeftStartingPoint&&(this.preventNewFeature=!0,setTimeout(()=>{this.preventNewFeature=!1},this.autoCloseTimeout),this.close()),this.setCursor(this.cursors.close),this.preventPointsNearClose)return}else this.hasLeftStartingPoint=!0,this.setCursor(this.cursors.start);if(d<this.minDistance)return;i.coordinates[0].pop();const p={type:"Polygon",coordinates:[[...i.coordinates[0],[t.lng,t.lat],i.coordinates[0][0]]]};this.validate&&!this.validate({type:"Feature",id:this.currentId,geometry:p,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional}).valid||this.store.updateGeometry([{id:this.currentId,geometry:p}])}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)){if(this.preventNewFeature)return;if(!1===this.startingClick){const[e,i]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}},{geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:{mode:this.mode,[s.CLOSING_POINT]:!0}}]);return this.currentId=e,this.closingPointId=i,this.startingClick=!0,void("drawing"!==this.state&&this.setDrawing())}this.close()}}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&!0===this.startingClick&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentId,e=this.closingPointId;this.closingPointId=void 0,this.currentId=void 0,this.startingClick=!1,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]),void 0!==e&&this.store.delete([e])}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return"Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r,i):"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode?(i.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),i.zIndex=50,i):i}validateFeature(t){return this.validateModeFeature(t,t=>B(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentId===t.id&&(this.closingPointId&&this.store.delete([this.closingPointId]),this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,this.hasLeftStartingPoint=!1)}}class H{constructor({store:t,mode:e,project:i,unproject:o,pointerDistance:s,coordinatePrecision:r,projection:n}){this.store=void 0,this.mode=void 0,this.project=void 0,this.unproject=void 0,this.pointerDistance=void 0,this.coordinatePrecision=void 0,this.projection=void 0,this.store=t,this.mode=e,this.project=i,this.unproject=o,this.pointerDistance=s,this.coordinatePrecision=r,this.projection=n}}function X({unproject:t,point:e,pointerDistance:i}){const o=i/2,{x:s,y:r}=e;return{type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[[t(s-o,r-o),t(s+o,r-o),t(s+o,r+o),t(s-o,r+o),t(s-o,r-o)].map(t=>[t.lng,t.lat])]}}}class $ extends H{constructor(t){super(t)}create(t){const{containerX:e,containerY:i}=t;return X({unproject:this.unproject,point:{x:e,y:i},pointerDistance:this.pointerDistance})}}class q extends H{constructor(t){super(t)}measure(t,e){const{x:i,y:o}=this.project(e[0],e[1]);return A({x:i,y:o},{x:t.containerX,y:t.containerY})}}class Z extends H{constructor(t,e,i){super(t),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=t=>this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode)).coordinate,this.getSnappableCoordinate=(t,e)=>this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode&&t.id!==e)).coordinate,this.config=t,this.pixelDistance=e,this.clickBoundingBox=i}getSnappable(t,e){const i=this.clickBoundingBox.create(t),o=this.store.search(i,e),s={featureId:void 0,featureCoordinateIndex:void 0,coordinate:void 0,minDist:Infinity};return o.forEach(e=>{let i;if("Polygon"===e.geometry.type)i=e.geometry.coordinates[0];else{if("LineString"!==e.geometry.type)return;i=e.geometry.coordinates}i.forEach((i,o)=>{const r=this.pixelDistance.measure(t,i);r<s.minDist&&r<this.pointerDistance&&(s.coordinate=i,s.minDist=r,s.featureId=e.id,s.featureCoordinateIndex=o)})}),s}}function J(t,e,i){const o=m(t[0]),s=m(t[1]),r=m(i),n=v(e),a=Math.asin(Math.sin(s)*Math.cos(n)+Math.cos(s)*Math.sin(n)*Math.cos(r));return[C(o+Math.atan2(Math.sin(r)*Math.sin(n)*Math.cos(s),Math.cos(n)-Math.sin(s)*Math.sin(a))),C(a)]}function Q({x:t,y:e},i,o){const s=m(o);return{x:t+i*Math.cos(s),y:e+i*Math.sin(s)}}function tt(t,e){const i=m(t[0]),o=m(e[0]),s=m(t[1]),r=m(e[1]),n=Math.sin(o-i)*Math.cos(r),a=Math.cos(s)*Math.sin(r)-Math.sin(s)*Math.cos(r)*Math.cos(o-i);return C(Math.atan2(n,a))}function et({x:t,y:e},{x:i,y:o}){const s=i-t,r=o-e;if(0===s&&0===r)return 0;let n=Math.atan2(r,s);return n*=180/Math.PI,n>180?n-=360:n<-180&&(n+=360),n}function it(t){return(t+360)%360}function ot(t,e,i){const o=[],s=t.length;let r,n,a,d=0;for(let s=0;s<t.length&&!(e>=d&&s===t.length-1);s++){if(d>e&&0===o.length){if(r=e-d,!r)return o.push(t[s]),o;n=tt(t[s],t[s-1])-180,a=J(t[s],r,n),o.push(a)}if(d>=i)return r=i-d,r?(n=tt(t[s],t[s-1])-180,a=J(t[s],r,n),o.push(a),o):(o.push(t[s]),o);if(d>=e&&o.push(t[s]),s===t.length-1)return o;d+=y(t[s],t[s+1])}if(d<e&&t.length===s)throw new Error("Start position is beyond line");const h=t[t.length-1];return[h,h]}function st(t){return t*(Math.PI/180)}function rt(t){return t*(180/Math.PI)}class nt extends H{constructor(t){super(t),this.config=void 0,this.config=t}generateInsertionCoordinates(t,e,i){const o=[t,e];let s=0;for(let t=0;t<o.length-1;t++)s+=y(o[0],o[1]);if(s<=i)return o;let r=s/i-1;Number.isInteger(r)||(r=Math.floor(r)+1);const n=[];for(let t=0;t<r;t++){const e=ot(o,i*t,i*(t+1));n.push(e)}const a=[];for(let t=0;t<n.length;t++)a.push(n[t][1]);return this.limitCoordinates(a)}generateInsertionGeodesicCoordinates(t,e,i){const o=y(t,e),s=function(t,e,i){const o=[],s=st(t[1]),r=st(t[0]),n=st(e[1]),a=st(e[0]);i+=1;const d=2*Math.asin(Math.sqrt(Math.sin((n-s)/2)**2+Math.cos(s)*Math.cos(n)*Math.sin((a-r)/2)**2));if(0===d||isNaN(d))return o;for(let t=0;t<=i;t++){const e=t/i,h=Math.sin((1-e)*d)/Math.sin(d),l=Math.sin(e*d)/Math.sin(d),c=h*Math.cos(s)*Math.cos(r)+l*Math.cos(n)*Math.cos(a),u=h*Math.cos(s)*Math.sin(r)+l*Math.cos(n)*Math.sin(a),p=h*Math.sin(s)+l*Math.sin(n);if(isNaN(c)||isNaN(u)||isNaN(p))continue;const g=Math.atan2(p,Math.sqrt(c**2+u**2)),y=Math.atan2(u,c);isNaN(g)||isNaN(y)||o.push([rt(y),rt(g)])}return o.slice(1,-1)}(t,e,Math.floor(o/i));return this.limitCoordinates(s)}limitCoordinates(t){return t.map(t=>[P(t[0],this.config.coordinatePrecision),P(t[1],this.config.coordinatePrecision)])}}function at(t,e){return t[0]===e[0]&&t[1]===e[1]}function dt(t,e){if("LineString"!==t.geometry.type)return{valid:!1,reason:"Feature is not a LineString"};if(t.geometry.coordinates.length<2)return{valid:!1,reason:"Feature has less than 2 coordinates"};for(let i=0;i<t.geometry.coordinates.length;i++){if(!_(t.geometry.coordinates[i]))return{valid:!1,reason:"Feature has invalid coordinates"};if(!k(t.geometry.coordinates[i],e))return{valid:!1,reason:"Feature has coordinates with excessive precision"}}return{valid:!0}}function ht(t){return Math.sqrt(Math.pow(t[0],2)+Math.pow(t[1],2)+Math.pow(t[2],2))}function lt(t,e){const i=function(t,e){const[i,o,s]=t,[r,n,a]=e;return i*r+o*n+s*a}(t,e)/(ht(t)*ht(e));return Math.acos(Math.min(Math.max(i,-1),1))}function ct(t){const e=m(t[1]),i=m(t[0]);return[Math.cos(e)*Math.cos(i),Math.cos(e)*Math.sin(i),Math.sin(e)]}function ut(t){const[e,i,o]=t,s=C(Math.asin(o));return[C(Math.atan2(i,e)),s]}function pt(t,e,i){const o=ct(t),s=ct(e),r=ct(i),[n,a,d]=r,[h,l,c]=function(t,e){const[i,o,s]=t,[r,n,a]=e;return[o*a-s*n,s*r-i*a,i*n-o*r]}(o,s),u=l*d-c*a,p=c*n-h*d,g=h*a-l*n,f=g*l-p*c,m=u*c-g*h,v=p*h-u*l,C=1/Math.sqrt(Math.pow(f,2)+Math.pow(m,2)+Math.pow(v,2)),P=[f*C,m*C,v*C],I=[-1*f*C,-1*m*C,-1*v*C],x=lt(o,s),E=lt(o,P),S=lt(s,P),M=lt(o,I),F=lt(s,I);let D;return D=E<M&&E<F||S<M&&S<F?P:I,lt(o,D)>x||lt(s,D)>x?y(ut(D),ut(o))<=y(ut(D),ut(s))?[ut(o),!0,!1]:[ut(s),!1,!0]:[ut(D),!1,!1]}function gt(t,e,i){const o=e.x-t.x,s=e.y-t.y,r=Math.max(0,Math.min(1,((i.x-t.x)*o+(i.y-t.y)*s)/(o*o+s*s)));return{x:t.x+r*o,y:t.y+r*s}}class yt extends H{constructor(t,e,i){super(t),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=t=>{const e=this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode));return e.coordinate?[P(e.coordinate[0],this.config.coordinatePrecision),P(e.coordinate[1],this.config.coordinatePrecision)]:void 0},this.getSnappableCoordinate=(t,e)=>{const i=this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode&&t.id!==e));return i.coordinate?[P(i.coordinate[0],this.config.coordinatePrecision),P(i.coordinate[1],this.config.coordinatePrecision)]:void 0},this.config=t,this.pixelDistance=e,this.clickBoundingBox=i}getSnappable(t,e){const i=this.clickBoundingBox.create(t),o=this.store.search(i,e),s={featureId:void 0,featureCoordinateIndex:void 0,coordinate:void 0,minDistance:Infinity};return o.forEach(e=>{let i;if("Polygon"===e.geometry.type)i=e.geometry.coordinates[0];else{if("LineString"!==e.geometry.type)return;i=e.geometry.coordinates}const o=[];for(let t=0;t<i.length-1;t++)o.push([i[t],i[t+1]]);let r;const n=[t.lng,t.lat];if("web-mercator"===this.config.projection?r=function(t,e){let i=[Infinity,Infinity],o=Infinity,s=0;for(let r of e){const n=r[0],a=r[1];let d,h=Infinity;const l=S(n[0],n[1]),c=S(a[0],a[1]),u=S(t[0],t[1]);if(n[0]===t[0]&&n[1]===t[1])d=n;else if(a[0]===t[0]&&a[1]===t[1])d=a;else{const{x:t,y:e}=gt(l,c,u),{lng:i,lat:o}=M(t,e);d=[i,o]}d&&(h=A(u,S(d[0],d[1])),h<o&&(i=d,o=h,s=e.indexOf(r)))}return Infinity===o?void 0:{coordinate:i,lineIndex:s,distance:o}}(n,o):"globe"===this.config.projection&&(r=function(t,e){let i=[Infinity,Infinity],o=Infinity,s=0;for(let r of e){const n=r[0],a=r[1];let d,h=Infinity;n[0]===t[0]&&n[1]===t[1]?d=n:a[0]===t[0]&&a[1]===t[1]?d=a:[d]=pt(n,a,t),d&&(h=y(t,d),h<o&&(i=d,o=h,s=e.indexOf(r)))}return Infinity===o?void 0:{coordinate:i,distance:o,lineIndex:s}}(n,o)),!r)return;const a=this.pixelDistance.measure(t,r.coordinate);a<s.minDistance&&a<this.pointerDistance&&(s.featureId=e.id,s.coordinate=[P(r.coordinate[0],this.config.coordinatePrecision),P(r.coordinate[1],this.config.coordinatePrecision)],s.featureCoordinateIndex=r.lineIndex,s.minDistance=a)}),s}}const ft={cancel:"Escape",finish:"Enter"},mt={start:"crosshair",close:"pointer",dragStart:"grabbing",dragEnd:"crosshair"};class vt extends p{constructor(t){super(t,!0),this.mode="linestring",this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.keyEvents=ft,this.snapping=void 0,this.cursors=mt,this.mouseMove=!1,this.insertCoordinates=void 0,this.lastCommittedCoordinates=void 0,this.snappedPointId=void 0,this.lastMouseMoveEvent=void 0,this.editable=!1,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0,this.editedInsertIndex=void 0,this.editedPointId=void 0,this.coordinateSnapping=void 0,this.insertPoint=void 0,this.lineSnapping=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null!=e&&e.snapping&&(this.snapping=e.snapping),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.insertCoordinates&&(this.insertCoordinates=e.insertCoordinates),e&&e.editable&&(this.editable=e.editable)}updateSnappedCoordinate(t){const e=this.snapCoordinate(t);if(e){if(this.snappedPointId)this.store.updateGeometry([{id:this.snappedPointId,geometry:{type:"Point",coordinates:e}}]);else{const[t]=this.store.create([{geometry:{type:"Point",coordinates:e},properties:{mode:this.mode,[s.SNAPPING_POINT]:!0}}]);this.snappedPointId=t}t.lng=e[0],t.lat=e[1]}else this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0);return e}close(){if(void 0===this.currentId)return;const t=this.store.getGeometryCopy(this.currentId);t.coordinates.pop(),this.updateGeometries([...t.coordinates],void 0,e.Commit),this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}]);const i=this.currentId;this.closingPointId&&this.store.delete([this.closingPointId]),this.snappedPointId&&this.store.delete([this.snappedPointId]),this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.snappedPointId=void 0,this.lastCommittedCoordinates=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(i,{mode:this.mode,action:"draw"})}updateGeometries(t,e,i){if(!this.currentId)return;const o={type:"LineString",coordinates:t};if(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}).valid)return;const s=[{id:this.currentId,geometry:o}];this.closingPointId&&e&&s.push({id:this.closingPointId,geometry:{type:"Point",coordinates:e}}),"commit"===i&&(this.lastCommittedCoordinates=o.coordinates),this.store.updateGeometry(s)}generateInsertCoordinates(t,e){if(!this.insertCoordinates||!this.lastCommittedCoordinates)throw new Error("Not able to insert coordinates");if("amount"!==this.insertCoordinates.strategy)throw new Error("Strategy does not exist");const i=y(t,e)/(this.insertCoordinates.value+1);let o=[];return"globe"===this.projection?o=this.insertPoint.generateInsertionGeodesicCoordinates(t,e,i):"web-mercator"===this.projection&&(o=this.insertPoint.generateInsertionCoordinates(t,e,i)),o}createLine(t){const[e]=this.store.create([{geometry:{type:"LineString",coordinates:[t,t]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}}]);this.lastCommittedCoordinates=[t,t],this.currentId=e,this.currentCoordinate++,this.setDrawing()}firstUpdateToLine(t){if(!this.currentId)return;const i=this.store.getGeometryCopy(this.currentId).coordinates,[o]=this.store.create([{geometry:{type:"Point",coordinates:[...t]},properties:{mode:this.mode,[s.CLOSING_POINT]:!0}}]);this.closingPointId=o,this.setCursor(this.cursors.close);const r=[...i,t];this.updateGeometries(r,void 0,e.Commit),this.currentCoordinate++}updateToLine(t,i){if(!this.currentId)return;const o=this.store.getGeometryCopy(this.currentId).coordinates,[s,r]=this.lastCommittedCoordinates?this.lastCommittedCoordinates[this.lastCommittedCoordinates.length-1]:o[o.length-2],{x:n,y:a}=this.project(s,r);if(A({x:n,y:a},{x:i.x,y:i.y})<this.pointerDistance)return void this.close();this.setCursor(this.cursors.close);const d=[...o,t];this.updateGeometries(d,o[o.length-1],e.Commit),this.currentCoordinate++}registerBehaviors(t){this.coordinateSnapping=new Z(t,new q(t),new $(t)),this.insertPoint=new nt(t),this.clickBoundingBox=new $(t),this.pixelDistance=new q(t),this.lineSnapping=new yt(t,this.pixelDistance,this.clickBoundingBox),this.coordinateSnapping=new Z(t,this.pixelDistance,this.clickBoundingBox)}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){this.mouseMove=!0,this.setCursor(this.cursors.start),this.lastMouseMoveEvent=t;const i=this.updateSnappedCoordinate(t)||[t.lng,t.lat];if(void 0===this.currentId||0===this.currentCoordinate)return;const o=this.store.getGeometryCopy(this.currentId).coordinates;if(o.pop(),this.closingPointId){const[e,i]=o[o.length-1],{x:s,y:r}=this.project(e,i);A({x:s,y:r},{x:t.containerX,y:t.containerY})<this.pointerDistance&&this.setCursor(this.cursors.close)}let s=[...o,i];if(this.insertCoordinates&&this.currentId&&this.lastCommittedCoordinates){const t=this.lastCommittedCoordinates[this.lastCommittedCoordinates.length-1],e=i;if(!at(t,e)){const o=this.generateInsertCoordinates(t,e);s=[...this.lastCommittedCoordinates.slice(0,-1),...o,i]}}this.updateGeometries(s,void 0,e.Provisional)}onRightClick(t){if(!this.editable||"started"!==this.state)return;const{featureId:i,featureCoordinateIndex:o}=this.coordinateSnapping.getSnappable(t,t=>this.lineStringFilter(t));if(!i||void 0===o)return;const s=this.store.getGeometryCopy(i);let r;if("LineString"===s.type&&(r=s.coordinates,!(r.length<=2))){if(r.splice(o,1),this.validate&&!this.validate({id:i,type:"Feature",geometry:s,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Commit}).valid)return;this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),this.store.updateGeometry([{id:i,geometry:s}]),this.onFinish(i,{mode:this.mode,action:"edit"})}}onLeftClick(t){this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0);const e=this.snapCoordinate(t)||[t.lng,t.lat];0===this.currentCoordinate?this.createLine(e):1===this.currentCoordinate&&this.currentId?this.firstUpdateToLine(e):this.currentId&&this.updateToLine(e,{x:t.containerX,y:t.containerY})}onClick(t){("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))&&(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,"right"===t.button?this.onRightClick(t):"left"===t.button&&this.onLeftClick(t))}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel&&this.cleanUp(),t.key===this.keyEvents.finish&&this.close()}onDragStart(t,e){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,t))return;if(!this.editable)return;let i;if("started"===this.state){const e=this.lineSnapping.getSnappable(t,t=>this.lineStringFilter(t));e.coordinate&&(this.editedSnapType="line",this.editedFeatureCoordinateIndex=e.featureCoordinateIndex,this.editedFeatureId=e.featureId,i=e.coordinate);const o=this.coordinateSnapping.getSnappable(t,t=>this.lineStringFilter(t));o.coordinate&&(this.editedSnapType="coordinate",this.editedFeatureCoordinateIndex=o.featureCoordinateIndex,this.editedFeatureId=o.featureId,i=o.coordinate)}if(this.editedFeatureId&&i){if(!this.editedPointId){const[t]=this.store.create([{geometry:{type:"Point",coordinates:i},properties:{mode:this.mode,[s.EDITED]:!0}}]);this.editedPointId=t}this.setCursor(this.cursors.dragStart),e(!1)}}onDrag(t,i){if(!this.allowPointerEvent(this.pointerEvents.onDrag,t))return;if(void 0===this.editedFeatureId||void 0===this.editedFeatureCoordinateIndex)return;const o=this.store.getGeometryCopy(this.editedFeatureId);"coordinate"===this.editedSnapType||"line"===this.editedSnapType&&void 0!==this.editedInsertIndex?o.coordinates[this.editedFeatureCoordinateIndex]=[t.lng,t.lat]:"line"===this.editedSnapType&&void 0===this.editedInsertIndex&&(this.editedInsertIndex=this.editedFeatureCoordinateIndex+1,o.coordinates.splice(this.editedInsertIndex,0,[t.lng,t.lat]),this.editedFeatureCoordinateIndex++);const r={type:"LineString",coordinates:o.coordinates};this.validate&&!this.validate({type:"Feature",geometry:r,properties:this.store.getPropertiesCopy(this.editedFeatureId)},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional}).valid||(this.snapping&&this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),this.store.updateGeometry([{id:this.editedFeatureId,geometry:r}]),this.editedPointId&&this.store.updateGeometry([{id:this.editedPointId,geometry:{type:"Point",coordinates:[t.lng,t.lat]}}]),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!0}]))}onDragEnd(t,e){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&void 0!==this.editedFeatureId&&(this.setCursor(this.cursors.dragEnd),this.editedPointId&&(this.store.delete([this.editedPointId]),this.editedPointId=void 0),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!1}]),this.onFinish(this.editedFeatureId,{mode:this.mode,action:"edit"}),this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0,e(!0))}cleanUp(){const t=this.currentId,e=this.closingPointId,i=this.snappedPointId;this.closingPointId=void 0,this.snappedPointId=void 0,this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]),void 0!==i&&this.store.delete([i]),void 0!==e&&this.store.delete([e])}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});if("Feature"===e.type&&"LineString"===e.geometry.type&&e.properties.mode===this.mode)return i.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,i.lineStringColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,i.lineStringWidth,e),i.zIndex=r,i;if("Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode){const t=e.properties[s.CLOSING_POINT];return i.pointColor=this.getHexColorStylingValue(t?this.styles.closingPointColor:this.styles.snappingPointColor,i.pointColor,e),i.pointWidth=this.getNumericStylingValue(t?this.styles.closingPointWidth:this.styles.snappingPointWidth,i.pointWidth,e),i.pointOutlineColor=this.getHexColorStylingValue(t?this.styles.closingPointOutlineColor:this.styles.snappingPointOutlineColor,"#ffffff",e),i.pointOutlineWidth=this.getNumericStylingValue(t?this.styles.closingPointOutlineWidth:this.styles.snappingPointOutlineWidth,2,e),i.zIndex=50,i}return i}validateFeature(t){return this.validateModeFeature(t,t=>dt(t,this.coordinatePrecision))}lineStringFilter(t){return Boolean("LineString"===t.geometry.type&&t.properties&&t.properties.mode===this.mode)}snapCoordinate(t){var e,i,o;let s;if(null!=(e=this.snapping)&&e.toLine){let e;e=this.currentId?this.lineSnapping.getSnappableCoordinate(t,this.currentId):this.lineSnapping.getSnappableCoordinateFirstClick(t),e&&(s=e)}return null!=(i=this.snapping)&&i.toCoordinate&&(s=this.currentId?this.coordinateSnapping.getSnappableCoordinate(t,this.currentId):this.coordinateSnapping.getSnappableCoordinateFirstClick(t)),null!=(o=this.snapping)&&o.toCustom&&(s=this.snapping.toCustom(t,{currentCoordinate:this.currentCoordinate,currentId:this.currentId,getCurrentGeometrySnapshot:this.currentId?()=>this.store.getGeometryCopy(this.currentId):()=>null,project:this.project,unproject:this.unproject})),s}afterFeatureUpdated(t){this.editedFeatureId===t.id&&this.editedPointId&&(this.store.delete([this.editedPointId]),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0),this.snappedPointId&&this.lastMouseMoveEvent&&this.updateSnappedCoordinate(this.lastMouseMoveEvent),this.currentId===t.id&&(this.closingPointId&&(this.store.delete([this.closingPointId]),this.closingPointId=void 0),this.currentCoordinate=0,this.currentId=void 0,"drawing"===this.state&&this.setStarted())}}const Ct="Feature is not a Point",Pt="Feature has invalid coordinates",It="Feature has coordinates with excessive precision";function xt(t,e){return"Point"!==t.geometry.type?{valid:!1,reason:Ct}:_(t.geometry.coordinates)?k(t.geometry.coordinates,e)?{valid:!0}:{valid:!1,reason:It}:{valid:!1,reason:Pt}}const Et={create:"crosshair",dragStart:"grabbing",dragEnd:"crosshair"};class St extends p{constructor(t){super(t,!0),this.mode="point",this.cursors=Et,this.editable=!1,this.editedFeatureId=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null!=e&&e.editable&&(this.editable=e.editable)}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(t){"right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)?this.onRightClick(t):"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)&&this.onLeftClick(t)}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){this.editedFeatureId=void 0}onDragStart(t,e){if(this.allowPointerEvent(this.pointerEvents.onDragStart,t)){if(this.editable){const e=this.getNearestPointFeature(t);this.editedFeatureId=null==e?void 0:e.id}this.editedFeatureId&&(this.setCursor(this.cursors.dragStart),e(!1))}}onDrag(t,i){this.allowPointerEvent(this.pointerEvents.onDrag,t)&&void 0!==this.editedFeatureId&&(this.validate&&!this.validate({type:"Feature",geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:this.store.getPropertiesCopy(this.editedFeatureId)},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid||(this.store.updateGeometry([{id:this.editedFeatureId,geometry:{type:"Point",coordinates:[t.lng,t.lat]}}]),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!0}])))}onDragEnd(t,e){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&void 0!==this.editedFeatureId&&(this.onFinish(this.editedFeatureId,{mode:this.mode,action:"edit"}),this.setCursor(this.cursors.dragEnd),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!1}]),this.editedFeatureId=void 0,e(!0))}registerBehaviors(t){this.pixelDistance=new q(t),this.clickBoundingBox=new $(t)}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});if("Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode){const t=Boolean(e.id&&this.editedFeatureId===e.id);i.pointWidth=this.getNumericStylingValue(t?this.styles.editedPointWidth:this.styles.pointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(t?this.styles.editedPointColor:this.styles.pointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(t?this.styles.editedPointOutlineColor:this.styles.pointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(t?this.styles.editedPointOutlineWidth:this.styles.pointOutlineWidth,2,e),i.zIndex=30}return i}validateFeature(t){return this.validateModeFeature(t,t=>xt(t,this.coordinatePrecision))}onLeftClick(t){const i={type:"Point",coordinates:[t.lng,t.lat]},o={mode:this.mode};if(this.validate&&!this.validate({type:"Feature",geometry:i,properties:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid)return;const[s]=this.store.create([{geometry:i,properties:o}]);this.onFinish(s,{mode:this.mode,action:"draw"})}onRightClick(t){if(!this.editable)return;const e=this.getNearestPointFeature(t);e&&this.store.delete([e.id])}getNearestPointFeature(t){const e=this.clickBoundingBox.create(t),i=this.store.search(e);let o,s=Infinity;for(let e=0;e<i.length;e++){const r=i[e];if("Point"!==r.geometry.type||r.properties.mode!==this.mode)continue;const n=this.pixelDistance.measure(t,r.geometry.coordinates);n>s||n>this.pointerDistance||(s=n,o=r)}return o}afterFeatureUpdated(t){this.editedFeatureId===t.id&&(this.editedFeatureId=void 0,this.setCursor(this.cursors.create))}}class Mt extends H{constructor(t,e){super(t),this.config=void 0,this.pixelDistance=void 0,this._startEndPoints=[],this.config=t,this.pixelDistance=e}get ids(){return this._startEndPoints.concat()}set ids(t){}create(t,e){if(this.ids.length)throw new Error("Opening and closing points already created");if(t.length<=3)throw new Error("Requires at least 4 coordinates");this._startEndPoints=this.store.create([{geometry:{type:"Point",coordinates:t[0]},properties:{mode:e,[s.CLOSING_POINT]:!0}},{geometry:{type:"Point",coordinates:t[t.length-2]},properties:{mode:e,[s.CLOSING_POINT]:!0}}])}delete(){this.ids.length&&(this.store.delete(this.ids),this._startEndPoints=[])}update(t){if(2!==this.ids.length)throw new Error("No closing points to update");this.store.updateGeometry([{id:this.ids[0],geometry:{type:"Point",coordinates:t[0]}},{id:this.ids[1],geometry:{type:"Point",coordinates:t[t.length-3]}}])}isClosingPoint(t){const e=this.store.getGeometryCopy(this.ids[0]),i=this.store.getGeometryCopy(this.ids[1]),o=this.pixelDistance.measure(t,e.coordinates),s=this.pixelDistance.measure(t,i.coordinates);return{isClosing:o<this.pointerDistance,isPreviousClosing:s<this.pointerDistance}}}class Ft extends H{constructor(t){super(t)}createOrUpdate(t){const e=this.store.getGeometryCopy(t),i=this.store.getPropertiesCopy(t);let o;if("Polygon"===e.type)o=e.coordinates[0].slice(0,-1);else{if("LineString"!==e.type)return;o=e.coordinates}const s=this.store.getPropertiesCopy(t),r=s.coordinatePointIds;if(r)if(r&&r.every(t=>this.store.has(t))){const e=s.coordinatePointIds,r=e.map(t=>this.store.getGeometryCopy(t).coordinates);if(e.length!==o.length){this.deleteCoordinatePoints(e);const s=this.createPoints(o,i.mode,t);this.setFeatureCoordinatePoints(t,s)}else o.forEach((t,i)=>{t[0]===r[i][0]&&t[1]===r[i][1]||this.store.updateGeometry([{id:e[i],geometry:{type:"Point",coordinates:t}}])})}else{const e=r.filter(t=>this.store.has(t));e.length&&this.deleteCoordinatePoints(e);const s=this.createPoints(o,i.mode,t);this.setFeatureCoordinatePoints(t,s)}else{const e=this.createPoints(o,i.mode,t);this.setFeatureCoordinatePoints(t,e)}}deletePointsByFeatureIds(t){for(const e of t)this.deleteIfPresent(e)}getUpdated(e,i){const o=this.store.getPropertiesCopy(e);if(o.coordinatePointIds)return o.coordinatePointIds.map((e,o)=>({id:e,geometry:t({},this.store.getGeometryCopy(e),{coordinates:i[o]})}))}createPoints(t,e,i){return this.store.create(t.map((t,o)=>({geometry:{type:"Point",coordinates:t},properties:{mode:e,[s.COORDINATE_POINT]:!0,[s.COORDINATE_POINT_FEATURE_ID]:i,index:o}})))}setFeatureCoordinatePoints(t,e){this.store.updateProperty([{id:t,property:s.COORDINATE_POINT_IDS,value:e}])}deleteCoordinatePoints(t){const e=t.filter(t=>this.store.has(t));this.store.delete(e)}deleteIfPresent(t){const e=this.store.getPropertiesCopy(t).coordinatePointIds;e&&(this.deleteCoordinatePoints(e),this.setFeatureCoordinatePoints(t,null))}}const Dt={cancel:"Escape",finish:"Enter"},wt={start:"crosshair",close:"pointer",dragStart:"grabbing",dragEnd:"crosshair"};class Ot extends p{constructor(t){super(t,!0),this.mode="polygon",this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=Dt,this.cursors=wt,this.mouseMove=!1,this.showCoordinatePoints=!1,this.lastMouseMoveEvent=void 0,this.snapping=void 0,this.snappedPointId=void 0,this.editable=!1,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0,this.editedInsertIndex=void 0,this.editedPointId=void 0,this.coordinatePoints=void 0,this.lineSnapping=void 0,this.coordinateSnapping=void 0,this.pixelDistance=void 0,this.closingPoints=void 0,this.clickBoundingBox=void 0,this.updateOptions(t)}updateOptions(e){if(super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.snapping&&(this.snapping=e.snapping),void 0!==(null==e?void 0:e.editable)&&(this.editable=e.editable),void 0!==(null==e?void 0:e.pointerEvents)&&(this.pointerEvents=e.pointerEvents),void 0!==(null==e?void 0:e.showCoordinatePoints))if(this.showCoordinatePoints=e.showCoordinatePoints,this.coordinatePoints&&!0===e.showCoordinatePoints)this.store.copyAllWhere(t=>t.mode===this.mode).map(t=>t.id).forEach(t=>{this.coordinatePoints.createOrUpdate(t)});else if(this.coordinatePoints&&!1===this.showCoordinatePoints){const t=this.store.copyAllWhere(t=>t.mode===this.mode&&Boolean(t[s.COORDINATE_POINT_IDS]));this.coordinatePoints.deletePointsByFeatureIds(t.map(t=>t.id))}}close(){if(void 0===this.currentId)return;const t=this.store.getGeometryCopy(this.currentId).coordinates[0];if(t.length<5)return;if(!this.updatePolygonGeometry([...t.slice(0,-2),t[0]],e.Finish))return;const i=this.currentId;if(this.currentId){const t=V(this.store.getGeometryCopy(this.currentId));t&&(this.store.updateGeometry([{id:this.currentId,geometry:t}]),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(this.currentId)),this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0},{id:this.currentId,property:s.COMMITTED_COORDINATE_COUNT,value:void 0},{id:this.currentId,property:s.PROVISIONAL_COORDINATE_COUNT,value:void 0}])}this.snappedPointId&&this.store.delete([this.snappedPointId]),this.currentCoordinate=0,this.currentId=void 0,this.snappedPointId=void 0,this.closingPoints.delete(),"drawing"===this.state&&this.setStarted(),this.onFinish(i,{mode:this.mode,action:"draw"})}registerBehaviors(t){this.clickBoundingBox=new $(t),this.pixelDistance=new q(t),this.lineSnapping=new yt(t,this.pixelDistance,this.clickBoundingBox),this.coordinateSnapping=new Z(t,this.pixelDistance,this.clickBoundingBox),this.closingPoints=new Mt(t,this.pixelDistance),this.coordinatePoints=new Ft(t)}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}updateSnappedCoordinate(t){const e=this.snapCoordinate(t);if(e){if(this.snappedPointId)this.store.updateGeometry([{id:this.snappedPointId,geometry:{type:"Point",coordinates:e}}]);else{const[t]=this.store.create([{geometry:{type:"Point",coordinates:e},properties:{mode:this.mode,[s.SNAPPING_POINT]:!0}}]);this.snappedPointId=t}t.lng=e[0],t.lat=e[1]}else this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0)}onMouseMove(t){if(this.mouseMove=!0,this.setCursor(this.cursors.start),this.lastMouseMoveEvent=t,this.updateSnappedCoordinate(t),void 0===this.currentId||0===this.currentCoordinate)return;const i=this.store.getGeometryCopy(this.currentId).coordinates[0];let o;if(1===this.currentCoordinate){const e=1/Math.pow(10,this.coordinatePrecision-1),s=Math.max(1e-6,e);o=[i[0],[t.lng,t.lat],[t.lng,t.lat-s],i[0]]}else if(2===this.currentCoordinate)o=[i[0],i[1],[t.lng,t.lat],i[0]];else{const{isClosing:e,isPreviousClosing:s}=this.closingPoints.isClosingPoint(t);s||e?(this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),this.setCursor(this.cursors.close),o=[...i.slice(0,-2),i[0],i[0]]):o=[...i.slice(0,-2),[t.lng,t.lat],i[0]]}this.store.updateProperty([{id:this.currentId,property:s.PROVISIONAL_COORDINATE_COUNT,value:this.currentCoordinate+1}]),this.updatePolygonGeometry(o,e.Provisional)}updatePolygonGeometry(t,e){if(!this.currentId)return!1;const i={type:"Polygon",coordinates:[t]};return!(this.validate&&!this.validate({type:"Feature",geometry:i},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e}).valid||(this.store.updateGeometry([{id:this.currentId,geometry:i}]),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(this.currentId),0))}snapCoordinate(t){var e,i,o;let s;if(null!=(e=this.snapping)&&e.toLine){let e;e=this.currentId?this.lineSnapping.getSnappableCoordinate(t,this.currentId):this.lineSnapping.getSnappableCoordinateFirstClick(t),e&&(s=e)}if(null!=(i=this.snapping)&&i.toCoordinate){let e;e=this.currentId?this.coordinateSnapping.getSnappableCoordinate(t,this.currentId):this.coordinateSnapping.getSnappableCoordinateFirstClick(t),e&&(s=e)}return null!=(o=this.snapping)&&o.toCustom&&(s=this.snapping.toCustom(t,{currentCoordinate:this.currentCoordinate,currentId:this.currentId,getCurrentGeometrySnapshot:this.currentId?()=>this.store.getGeometryCopy(this.currentId):()=>null,project:this.project,unproject:this.unproject})),s}polygonFilter(t){return Boolean("Polygon"===t.geometry.type&&t.properties&&t.properties.mode===this.mode)}onRightClick(t){if(!this.editable||"started"!==this.state)return;const{featureId:i,featureCoordinateIndex:o}=this.coordinateSnapping.getSnappable(t,t=>this.polygonFilter(t));if(!i||void 0===o)return;const s=this.store.getGeometryCopy(i);let r;"Polygon"===s.type&&(r=s.coordinates[0],r.length<=4||("Polygon"!==s.type||0!==o&&o!==r.length-1?r.splice(o,1):(r.shift(),r.pop(),r.push([r[0][0],r[0][1]])),(!this.validate||this.validate({id:i,type:"Feature",geometry:s,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Commit}).valid)&&(this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),this.store.updateGeometry([{id:i,geometry:s}]),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(i),this.onFinish(i,{mode:this.mode,action:"edit"}))))}onLeftClick(t){if(this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),0===this.currentCoordinate){const e=this.snapCoordinate(t);e&&(t.lng=e[0],t.lat=e[1]);const[i]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0,[s.COMMITTED_COORDINATE_COUNT]:this.currentCoordinate+1,[s.PROVISIONAL_COORDINATE_COUNT]:this.currentCoordinate+1}}]);this.currentId=i,this.currentCoordinate++,this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(i),this.setDrawing()}else if(1===this.currentCoordinate&&this.currentId){const i=this.snapCoordinate(t);i&&(t.lng=i[0],t.lat=i[1]);const o=this.store.getGeometryCopy(this.currentId);if(at([t.lng,t.lat],o.coordinates[0][0]))return;if(!this.updatePolygonGeometry([o.coordinates[0][0],[t.lng,t.lat],[t.lng,t.lat],o.coordinates[0][0]],e.Commit))return;this.store.updateProperty([{id:this.currentId,property:s.COMMITTED_COORDINATE_COUNT,value:this.currentCoordinate+1}]),this.currentCoordinate++}else if(2===this.currentCoordinate&&this.currentId){const i=this.snapCoordinate(t);i&&(t.lng=i[0],t.lat=i[1]);const o=this.store.getGeometryCopy(this.currentId).coordinates[0];if(at([t.lng,t.lat],o[1]))return;if(!this.updatePolygonGeometry([o[0],o[1],[t.lng,t.lat],[t.lng,t.lat],o[0]],e.Commit))return;2===this.currentCoordinate&&this.closingPoints.create(o,"polygon"),this.store.updateProperty([{id:this.currentId,property:s.COMMITTED_COORDINATE_COUNT,value:this.currentCoordinate+1}]),this.currentCoordinate++}else if(this.currentId){const i=this.store.getGeometryCopy(this.currentId).coordinates[0],{isClosing:o,isPreviousClosing:r}=this.closingPoints.isClosingPoint(t);if(r||o)this.close();else{const o=this.snapCoordinate(t);if(o&&(t.lng=o[0],t.lat=o[1]),at([t.lng,t.lat],i[this.currentCoordinate-1]))return;const r=function(t=[[[0,0],[0,1],[1,1],[1,0],[0,0]]]){return{type:"Feature",geometry:{type:"Polygon",coordinates:t},properties:{}}}([[...i.slice(0,-1),[t.lng,t.lat],i[0]]]);if(!this.updatePolygonGeometry(r.geometry.coordinates[0],e.Commit))return;this.store.updateProperty([{id:this.currentId,property:s.COMMITTED_COORDINATE_COUNT,value:this.currentCoordinate+1}]),this.currentCoordinate++,this.closingPoints.ids.length&&this.closingPoints.update(r.geometry.coordinates[0])}}}onClick(t){this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,"right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)?this.onRightClick(t):"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)&&this.onLeftClick(t)}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(t,e){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,t))return;if(!this.editable)return;let i;if("started"===this.state){const e=this.lineSnapping.getSnappable(t,t=>this.polygonFilter(t));e.coordinate&&(this.editedSnapType="line",this.editedFeatureCoordinateIndex=e.featureCoordinateIndex,this.editedFeatureId=e.featureId,i=e.coordinate);const o=this.coordinateSnapping.getSnappable(t,t=>this.polygonFilter(t));o.coordinate&&(this.editedSnapType="coordinate",this.editedFeatureCoordinateIndex=o.featureCoordinateIndex,this.editedFeatureId=o.featureId,i=o.coordinate)}if(this.editedFeatureId&&i){if(!this.editedPointId){const[t]=this.store.create([{geometry:{type:"Point",coordinates:i},properties:{mode:this.mode,[s.EDITED]:!0}}]);this.editedPointId=t}this.setCursor(this.cursors.dragStart),e(!1)}}onDrag(t,i){if(!this.allowPointerEvent(this.pointerEvents.onDrag,t))return;if(void 0===this.editedFeatureId||void 0===this.editedFeatureCoordinateIndex)return;const o=this.store.getGeometryCopy(this.editedFeatureId),r=o.coordinates[0];"coordinate"===this.editedSnapType||"line"===this.editedSnapType&&void 0!==this.editedInsertIndex?0===this.editedFeatureCoordinateIndex||this.editedFeatureCoordinateIndex===o.coordinates[0].length-1?(r[0]=[t.lng,t.lat],r[r.length-1]=[t.lng,t.lat]):r[this.editedFeatureCoordinateIndex]=[t.lng,t.lat]:"line"===this.editedSnapType&&void 0===this.editedInsertIndex&&(this.editedInsertIndex=this.editedFeatureCoordinateIndex+1,o.coordinates[0].splice(this.editedInsertIndex,0,[t.lng,t.lat]),this.editedFeatureCoordinateIndex++);const n={type:"Polygon",coordinates:o.coordinates};this.validate&&!this.validate({type:"Feature",geometry:n,properties:this.store.getPropertiesCopy(this.editedFeatureId)},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional}).valid||(this.snapping&&this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),this.store.updateGeometry([{id:this.editedFeatureId,geometry:n}]),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(this.editedFeatureId),this.editedPointId&&this.store.updateGeometry([{id:this.editedPointId,geometry:{type:"Point",coordinates:[t.lng,t.lat]}}]),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!0}]))}onDragEnd(t,e){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&void 0!==this.editedFeatureId&&(this.setCursor(this.cursors.dragEnd),this.editedPointId&&(this.store.delete([this.editedPointId]),this.editedPointId=void 0),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!1}]),this.onFinish(this.editedFeatureId,{mode:this.mode,action:"edit"}),this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0,e(!0))}cleanUp(){const t=this.currentId,e=this.snappedPointId,i=this.editedPointId;this.currentId=void 0,this.snappedPointId=void 0,this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{t&&this.coordinatePoints.deletePointsByFeatureIds([t]),void 0!==t&&this.store.delete([t]),void 0!==i&&this.store.delete([i]),void 0!==e&&this.store.delete([e]),this.closingPoints.ids.length&&this.closingPoints.delete()}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});if(e.properties.mode===this.mode){if("Polygon"===e.geometry.type)return i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r,i;if("Point"===e.geometry.type){const t=e.properties[s.EDITED],o=e.properties[s.COORDINATE_POINT],r=t?"editedPoint":e.properties[s.CLOSING_POINT]?"closingPoint":e.properties[s.SNAPPING_POINT]?"snappingPoint":o?"coordinatePoint":void 0;if(!r)return i;const n={editedPoint:{width:this.styles.editedPointOutlineWidth,color:this.styles.editedPointColor,outlineColor:this.styles.editedPointOutlineColor,outlineWidth:this.styles.editedPointOutlineWidth},closingPoint:{width:this.styles.closingPointWidth,color:this.styles.closingPointColor,outlineColor:this.styles.closingPointOutlineColor,outlineWidth:this.styles.closingPointOutlineWidth},snappingPoint:{width:this.styles.snappingPointWidth,color:this.styles.snappingPointColor,outlineColor:this.styles.snappingPointOutlineColor,outlineWidth:this.styles.snappingPointOutlineWidth},coordinatePoint:{width:this.styles.coordinatePointWidth,color:this.styles.coordinatePointColor,outlineColor:this.styles.coordinatePointOutlineColor,outlineWidth:this.styles.coordinatePointOutlineWidth}};return i.pointWidth=this.getNumericStylingValue(n[r].width,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(n[r].color,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(n[r].outlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(n[r].outlineWidth,2,e),i.zIndex=t?40:o?20:30,i}}return i}afterFeatureAdded(t){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(t.id)}afterFeatureUpdated(t){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(t.id),this.editedFeatureId===t.id&&this.editedPointId&&(this.store.delete([this.editedPointId]),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0),this.snappedPointId&&this.lastMouseMoveEvent&&this.updateSnappedCoordinate(this.lastMouseMoveEvent),this.currentId===t.id&&(this.currentCoordinate=0,this.currentId=void 0,this.closingPoints.delete(),"drawing"===this.state&&this.setStarted())}validateFeature(t){return this.validateModeFeature(t,t=>B(t,this.coordinatePrecision))}}const kt={cancel:"Escape",finish:"Enter"},_t={start:"crosshair"};class bt extends p{constructor(t){super(t,!0),this.mode="rectangle",this.center=void 0,this.clickCount=0,this.currentRectangleId=void 0,this.keyEvents=kt,this.cursors=_t,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents))}updateRectangle(t,e){if(1===this.clickCount&&this.center&&this.currentRectangleId){const i=this.store.getGeometryCopy(this.currentRectangleId).coordinates[0][0],o={type:"Polygon",coordinates:[[i,[t.lng,i[1]],[t.lng,t.lat],[i[0],t.lat],i]]};if(this.validate&&!this.validate({id:this.currentRectangleId,geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e}).valid)return;this.store.updateGeometry([{id:this.currentRectangleId,geometry:o}])}}close(){const t=this.currentRectangleId;if(t){const e=V(this.store.getGeometryCopy(t));e&&this.store.updateGeometry([{id:t,geometry:e}]),this.store.updateProperty([{id:t,property:s.CURRENTLY_DRAWING,value:void 0}])}this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),void 0!==t&&this.onFinish(t,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))if(0===this.clickCount){this.center=[t.lng,t.lat];const[e]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}}]);this.currentRectangleId=e,this.clickCount++,this.setDrawing()}else this.updateRectangle(t,e.Finish),this.close()}onMouseMove(t){this.updateRectangle(t,e.Provisional)}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentRectangleId;this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),void 0!==t&&this.store.delete([t])}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return"Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r,i):i}validateFeature(t){return this.validateModeFeature(t,t=>G(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentRectangleId===t.id&&(this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted())}}class Nt extends p{constructor(t){if(!t.modeName)throw new Error("Mode name is required for TerraDrawRenderMode");super(t,!0),this.type=c.Render,this.mode="render",this.updateOptions(t)}updateOptions(t){super.updateOptions(t),null!=t&&t.modeName&&(this.mode=t.modeName)}registerBehaviors(t){this.mode=t.mode}start(){this.setStarted()}stop(){this.setStopped()}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(t){return{pointColor:this.getHexColorStylingValue(this.styles.pointColor,"#3f97e0",t),pointWidth:this.getNumericStylingValue(this.styles.pointWidth,6,t),pointOutlineColor:this.getHexColorStylingValue(this.styles.pointOutlineColor,"#ffffff",t),pointOutlineWidth:this.getNumericStylingValue(this.styles.pointOutlineWidth,0,t),polygonFillColor:this.getHexColorStylingValue(this.styles.polygonFillColor,"#3f97e0",t),polygonFillOpacity:this.getNumericStylingValue(this.styles.polygonFillOpacity,.3,t),polygonOutlineColor:this.getHexColorStylingValue(this.styles.polygonOutlineColor,"#3f97e0",t),polygonOutlineWidth:this.getNumericStylingValue(this.styles.polygonOutlineWidth,4,t),lineStringWidth:this.getNumericStylingValue(this.styles.lineStringWidth,4,t),lineStringColor:this.getHexColorStylingValue(this.styles.lineStringColor,"#3f97e0",t),zIndex:this.getNumericStylingValue(this.styles.zIndex,0,t)}}validateFeature(t){const e=super.validateFeature(t);if(e.valid){const e=t,i=xt(e,this.coordinatePrecision).valid||B(e,this.coordinatePrecision).valid||dt(e,this.coordinatePrecision).valid;return i?{valid:!0}:{valid:i,reason:"Feature is not a valid Point, Polygon or LineString feature"}}return e}}function Tt(t,e){const i=t,o=e,s=m(i[1]),r=m(o[1]);let n=m(o[0]-i[0]);n>Math.PI&&(n-=2*Math.PI),n<-Math.PI&&(n+=2*Math.PI);const a=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),d=(C(Math.atan2(n,a))+360)%360;return d>180?-(360-d):d}function Wt(t,e,i){let o=e;e<0&&(o=-Math.abs(o));const s=o/f,r=t[0]*Math.PI/180,n=m(t[1]),a=m(i),d=s*Math.cos(a);let h=n+d;Math.abs(h)>Math.PI/2&&(h=h>0?Math.PI-h:-Math.PI-h);const l=Math.log(Math.tan(h/2+Math.PI/4)/Math.tan(n/2+Math.PI/4)),c=Math.abs(l)>1e-11?d/l:Math.cos(n),u=[(180*(r+s*Math.sin(a)/c)/Math.PI+540)%360-180,180*h/Math.PI];return u[0]+=u[0]-t[0]>180?-360:t[0]-u[0]>180?360:0,u}function jt(t,e,i,o,s){const r=o(t[0],t[1]),n=o(e[0],e[1]),{lng:a,lat:d}=s((r.x+n.x)/2,(r.y+n.y)/2);return[P(a,i),P(d,i)]}function Bt(t,e,i){const o=Wt(t,1e3*y(t,e)/2,Tt(t,e));return[P(o[0],i),P(o[1],i)]}function Gt({featureCoords:t,precision:e,unproject:i,project:o,projection:s}){const r=[];for(let n=0;n<t.length-1;n++){let a;if("web-mercator"===s)a=jt(t[n],t[n+1],e,o,i);else{if("globe"!==s)throw new Error("Invalid projection");a=Bt(t[n],t[n+1],e)}r.push(a)}return r}class Rt extends H{constructor(t,e,i){super(t),this.config=void 0,this.selectionPointBehavior=void 0,this.coordinatePointBehavior=void 0,this._midPoints=[],this.config=t,this.selectionPointBehavior=e,this.coordinatePointBehavior=i}get ids(){return this._midPoints.concat()}set ids(t){}insert(t,e,i){const o=this.store.getGeometryCopy(e),{midPointFeatureId:r,midPointSegment:n}=this.store.getPropertiesCopy(e),a=this.store.getGeometryCopy(r),d="Polygon"===a.type?a.coordinates[0]:a.coordinates;d.splice(n+1,0,o.coordinates),a.coordinates="Polygon"===a.type?[d]:d,this.store.updateGeometry([{id:r,geometry:a}]),this.store.getPropertiesCopy(t)[s.COORDINATE_POINT_IDS]&&this.coordinatePointBehavior.createOrUpdate(t),this.store.delete([...this._midPoints,...this.selectionPointBehavior.ids]),this.create(d,r,i),this.selectionPointBehavior.create(d,a.type,r)}create(t,e,i){if(!this.store.has(e))throw new Error("Store does not have feature with this id");this._midPoints=this.store.create(function(t,e,i,o,s,r){return Gt({featureCoords:t,precision:i,project:o,unproject:s,projection:r}).map((t,i)=>({geometry:{type:"Point",coordinates:t},properties:e(i)}))}(t,t=>({mode:this.mode,[o.MID_POINT]:!0,midPointSegment:t,midPointFeatureId:e}),i,this.config.project,this.config.unproject,this.projection))}delete(){this._midPoints.length&&(this.store.delete(this._midPoints),this._midPoints=[])}getUpdated(t){if(0!==this._midPoints.length)return Gt({featureCoords:t,precision:this.coordinatePrecision,project:this.config.project,unproject:this.config.unproject,projection:this.config.projection}).map((t,e)=>({id:this._midPoints[e],geometry:{type:"Point",coordinates:t}}))}}class Ut extends H{constructor(t){super(t),this._selectionPoints=[]}get ids(){return this._selectionPoints.concat()}set ids(t){}create(t,e,i){this._selectionPoints=this.store.create(function(t,e,i){const o=[],s="Polygon"===e?t.length-1:t.length;for(let e=0;e<s;e++)o.push({geometry:{type:"Point",coordinates:t[e]},properties:i(e)});return o}(t,e,t=>({mode:this.mode,index:t,[o.SELECTION_POINT]:!0,[o.SELECTION_POINT_FEATURE_ID]:i})))}delete(){this.ids.length&&(this.store.delete(this.ids),this._selectionPoints=[])}getUpdated(t){if(0!==this._selectionPoints.length)return this._selectionPoints.map((e,i)=>({id:e,geometry:{type:"Point",coordinates:t[i]}}))}getOneUpdated(t,e){if(void 0!==this._selectionPoints[t])return{id:this._selectionPoints[t],geometry:{type:"Point",coordinates:e}}}}function Lt(t,e){let i=!1;for(let n=0,a=e.length;n<a;n++){const a=e[n];for(let e=0,n=a.length,d=n-1;e<n;d=e++)(s=a[e])[1]>(o=t)[1]!=(r=a[d])[1]>o[1]&&o[0]<(r[0]-s[0])*(o[1]-s[1])/(r[1]-s[1])+s[0]&&(i=!i)}var o,s,r;return i}const At=(t,e,i)=>{const o=t=>t*t,s=(t,e)=>o(t.x-e.x)+o(t.y-e.y);return Math.sqrt(((t,e,i)=>{const o=s(e,i);if(0===o)return s(t,e);let r=((t.x-e.x)*(i.x-e.x)+(t.y-e.y)*(i.y-e.y))/o;return r=Math.max(0,Math.min(1,r)),s(t,{x:e.x+r*(i.x-e.x),y:e.y+r*(i.y-e.y)})})(t,e,i))};class Vt extends H{constructor(t,e,i){super(t),this.config=void 0,this.createClickBoundingBox=void 0,this.pixelDistance=void 0,this.config=t,this.createClickBoundingBox=e,this.pixelDistance=i}find(t,e){let i,s,r,n,a=Infinity,d=Infinity,h=Infinity;const l=this.createClickBoundingBox.create(t),c=this.store.search(l);for(let l=0;l<c.length;l++){const u=c[l],p=u.geometry;if("Point"===p.type){if(u.properties.selectionPoint||u.properties.coordinatePoint||!e&&u.properties[o.MID_POINT])continue;const s=this.pixelDistance.measure(t,p.coordinates);u.properties[o.MID_POINT]&&s<this.pointerDistance&&s<h?(h=s,r=u):!u.properties[o.MID_POINT]&&s<this.pointerDistance&&s<a&&(a=s,i=u)}else if("LineString"===p.type){if(i)continue;for(let e=0;e<p.coordinates.length-1;e++){const i=p.coordinates[e],o=p.coordinates[e+1],r=At({x:t.containerX,y:t.containerY},this.project(i[0],i[1]),this.project(o[0],o[1]));r<this.pointerDistance&&r<d&&(d=r,s=u)}}else if("Polygon"===p.type){if(i||s)continue;Lt([t.lng,t.lat],p.coordinates)&&(n=u)}}return{clickedFeature:i||s||n,clickedMidPoint:r}}}class Yt extends H{constructor(t,e,i,o,s){super(t),this.config=void 0,this.featuresAtCursorEvent=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.draggedFeatureId=null,this.dragPosition=void 0,this.config=t,this.featuresAtCursorEvent=e,this.selectionPoints=i,this.midPoints=o,this.coordinatePoints=s}startDragging(t,e){this.draggedFeatureId=e,this.dragPosition=[t.lng,t.lat]}stopDragging(){this.draggedFeatureId=null,this.dragPosition=void 0}isDragging(){return null!==this.draggedFeatureId}canDrag(t,e){const{clickedFeature:i}=this.featuresAtCursorEvent.find(t,!0);return!(!i||i.id!==e)}drag(t,i){if(!this.draggedFeatureId)return;const o=this.store.getGeometryCopy(this.draggedFeatureId),s=[t.lng,t.lat];if("Polygon"===o.type||"LineString"===o.type){let r,n;if("Polygon"===o.type?(r=o.coordinates[0],n=r.length-1):(r=o.coordinates,n=r.length),!this.dragPosition)return!1;for(let t=0;t<n;t++){const e=r[t];let i,o;if("web-mercator"===this.config.projection){const t=S(this.dragPosition[0],this.dragPosition[1]),r=S(s[0],s[1]),n=S(e[0],e[1]),a={x:t.x-r.x,y:t.y-r.y},d=n.x-a.x,h=n.y-a.y,{lng:l,lat:c}=M(d,h);i=l,o=c}else{const t=[this.dragPosition[0]-s[0],this.dragPosition[1]-s[1]];i=e[0]-t[0],o=e[1]-t[1]}if(i=P(i,this.config.coordinatePrecision),o=P(o,this.config.coordinatePrecision),i>180||i<-180||o>90||o<-90)return!1;r[t]=[i,o]}"Polygon"===o.type&&(r[r.length-1]=[r[0][0],r[0][1]]);const a=this.selectionPoints.getUpdated(r)||[],d=this.midPoints.getUpdated(r)||[],h=this.coordinatePoints.getUpdated(this.draggedFeatureId,r)||[];if(i&&!i({type:"Feature",id:this.draggedFeatureId,geometry:o,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:e.Provisional}).valid)return!1;this.store.updateGeometry([{id:this.draggedFeatureId,geometry:o},...a,...d,...h]),this.dragPosition=[t.lng,t.lat]}else"Point"===o.type&&(this.store.updateGeometry([{id:this.draggedFeatureId,geometry:{type:"Point",coordinates:s}}]),this.dragPosition=[t.lng,t.lat])}}class Kt extends H{constructor(t,e,i,o,s,r,n){super(t),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.coordinateSnapping=void 0,this.lineSnapping=void 0,this.draggedCoordinate={id:null,index:-1},this.config=t,this.pixelDistance=e,this.selectionPoints=i,this.midPoints=o,this.coordinatePoints=s,this.coordinateSnapping=r,this.lineSnapping=n}getClosestCoordinate(t,e){const i={dist:Infinity,index:-1,isFirstOrLastPolygonCoord:!1};let o;if("LineString"===e.type)o=e.coordinates;else{if("Polygon"!==e.type)return i;o=e.coordinates[0]}for(let s=0;s<o.length;s++){const r=this.pixelDistance.measure(t,o[s]);if(r<this.pointerDistance&&r<i.dist){const t="Polygon"===e.type&&(s===o.length-1||0===s);i.dist=r,i.index=t?0:s,i.isFirstOrLastPolygonCoord=t}}return i}getDraggableIndex(t,e){const i=this.store.getGeometryCopy(e),o=this.getClosestCoordinate(t,i);return-1===o.index?-1:o.index}snapCoordinate(t,e,i){let o=[t.lng,t.lat];const s=t=>Boolean(t.properties&&t.properties.mode===i.properties.mode&&t.id!==this.draggedCoordinate.id);if(null!=e&&e.toLine){let e;e=this.lineSnapping.getSnappable(t,s).coordinate,e&&(o=e)}if(e.toCoordinate){let e;e=this.coordinateSnapping.getSnappable(t,s).coordinate,e&&(o=e)}if(null!=e&&e.toCustom){let s;s=e.toCustom(t,{currentCoordinate:this.draggedCoordinate.index,currentId:i.id,getCurrentGeometrySnapshot:i.id?()=>this.store.getGeometryCopy(i.id):()=>null,project:this.project,unproject:this.unproject}),s&&(o=s)}return o}drag(t,i,o,s){const r=this.draggedCoordinate.id;if(null===r)return!1;const n=this.draggedCoordinate.index,a=this.store.getGeometryCopy(r),d=this.store.getPropertiesCopy(r),h="LineString"===a.type?a.coordinates:a.coordinates[0],l="Polygon"===a.type&&(n===h.length-1||0===n),c={type:"Feature",id:r,geometry:a,properties:d},u=this.snapCoordinate(t,s,c);if(t.lng>180||t.lng<-180||t.lat>90||t.lat<-90)return!1;if(l){const t=h.length-1;h[0]=u,h[t]=u}else h[n]=u;const p=this.selectionPoints.getOneUpdated(n,u),g=p?[p]:[],y=this.midPoints.getUpdated(h)||[],f=this.coordinatePoints.getUpdated(r,h)||[];return!("Point"!==a.type&&!i&&w({type:"Feature",geometry:a,properties:{}})||o&&!o(c,{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:e.Provisional}).valid||(this.store.updateGeometry([{id:r,geometry:a},...g,...y,...f]),0))}isDragging(){return null!==this.draggedCoordinate.id}startDragging(t,e){this.draggedCoordinate={id:t,index:e}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}}function zt(t){let e=0,i=0,o=0;return("Polygon"===t.geometry.type?t.geometry.coordinates[0].slice(0,-1):t.geometry.coordinates).forEach(t=>{e+=t[0],i+=t[1],o++},!0),[e/o,i/o]}const Ht=(t,e)=>{if(0===e||360===e||-360===e)return t;const i=.017453292519943295*e,o=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(([t,e])=>S(t,e)),s=o.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0});s.x/=o.length,s.y/=o.length;const r=o.map(t=>({x:s.x+(t.x-s.x)*Math.cos(i)-(t.y-s.y)*Math.sin(i),y:s.y+(t.x-s.x)*Math.sin(i)+(t.y-s.y)*Math.cos(i)})).map(({x:t,y:e})=>[M(t,e).lng,M(t,e).lat]);return"Polygon"===t.geometry.type?t.geometry.coordinates[0]=r:t.geometry.coordinates=r,t};function Xt(t){const e=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(t=>{const{x:e,y:i}=S(t[0],t[1]);return[e,i]});return"Polygon"===t.geometry.type?function(t){let e=0,i=0,o=0;const s=t.length;for(let r=0;r<s-1;r++){const[s,n]=t[r],[a,d]=t[r+1],h=s*d-a*n;e+=h,i+=(s+a)*h,o+=(n+d)*h}return e/=2,i/=6*e,o/=6*e,{x:i,y:o}}(e):function(t){const e=t.length;let i=0,o=0;for(let s=0;s<e;s++){const[e,r]=t[s];i+=e,o+=r}return{x:i/e,y:o/e}}(e)}class $t extends H{constructor(t,e,i,o){super(t),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.lastBearing=void 0,this.selectedGeometry=void 0,this.selectedGeometryCentroid=void 0,this.selectedGeometryWebMercatorCentroid=void 0,this.config=t,this.selectionPoints=e,this.midPoints=i,this.coordinatePoints=o}reset(){this.lastBearing=void 0,this.selectedGeometry=void 0,this.selectedGeometryWebMercatorCentroid=void 0,this.selectedGeometryCentroid=void 0}rotate(t,i,o){this.selectedGeometry||(this.selectedGeometry=this.store.getGeometryCopy(i));const s=this.selectedGeometry;if("Polygon"!==s.type&&"LineString"!==s.type)return;const r=[t.lng,t.lat];let n;const a={type:"Feature",geometry:s,properties:{}};if("web-mercator"===this.config.projection){this.selectedGeometryWebMercatorCentroid||(this.selectedGeometryWebMercatorCentroid=Xt(a));const e=S(t.lng,t.lat);if(n=et(this.selectedGeometryWebMercatorCentroid,e),0===n)return;if(!this.lastBearing)return void(this.lastBearing=n);Ht(a,-(this.lastBearing-n))}else{if("globe"!==this.config.projection)throw new Error("Unsupported projection");if(this.selectedGeometryCentroid||(this.selectedGeometryCentroid=zt({type:"Feature",geometry:s,properties:{}})),n=Tt(this.selectedGeometryCentroid,r),!this.lastBearing)return void(this.lastBearing=n+180);!function(t,e){if(0===e||360===e||-360===e)return t;const i=zt(t);("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).forEach(t=>{const o=Tt(i,t)+e,s=function(t,e){t[0]+=t[0]-e[0]>180?-360:e[0]-t[0]>180?360:0;const i=f,o=e[1]*Math.PI/180,s=t[1]*Math.PI/180,r=s-o;let n=Math.abs(t[0]-e[0])*Math.PI/180;n>Math.PI&&(n-=2*Math.PI);const a=Math.log(Math.tan(s/2+Math.PI/4)/Math.tan(o/2+Math.PI/4)),d=Math.abs(a)>1e-11?r/a:Math.cos(o);return Math.sqrt(r*r+d*d*n*n)*i}(i,t),r=Wt(i,s,o);t[0]=r[0],t[1]=r[1]})}(a,-(this.lastBearing-(n+180)))}const d="Polygon"===s.type?s.coordinates[0]:s.coordinates;d.forEach(t=>{t[0]=P(t[0],this.coordinatePrecision),t[1]=P(t[1],this.coordinatePrecision)});const h=this.midPoints.getUpdated(d)||[],l=this.selectionPoints.getUpdated(d)||[],c=this.coordinatePoints.getUpdated(i,d)||[];if(o&&!o({id:i,type:"Feature",geometry:s,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:e.Provisional}))return!1;this.store.updateGeometry([{id:i,geometry:s},...l,...h,...c]),"web-mercator"===this.projection?this.lastBearing=n:"globe"===this.projection&&(this.lastBearing=n+180)}}class qt extends H{constructor(t,e){super(t),this.config=void 0,this.dragCoordinateResizeBehavior=void 0,this.config=t,this.dragCoordinateResizeBehavior=e}scale(t,e,i){if(!this.dragCoordinateResizeBehavior.isDragging()){const i=this.dragCoordinateResizeBehavior.getDraggableIndex(t,e);this.dragCoordinateResizeBehavior.startDragging(e,i)}this.dragCoordinateResizeBehavior.drag(t,"center-fixed",i)}reset(){this.dragCoordinateResizeBehavior.stopDragging()}}function Zt({coordinates:t,originX:e,originY:i,xScale:o,yScale:s}){1===o&&1===s||t.forEach(t=>{const{x:r,y:n}=S(t[0],t[1]),a=e+(r-e)*o,d=i+(n-i)*s,{lng:h,lat:l}=M(a,d);t[0]=h,t[1]=l})}class Jt extends H{constructor(t,e,i,o,s){super(t),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.minimumScale=1e-4,this.draggedCoordinate={id:null,index:-1},this.boundingBoxMaps={opposite:{0:4,1:5,2:6,3:7,4:0,5:1,6:2,7:3}},this.config=t,this.pixelDistance=e,this.selectionPoints=i,this.midPoints=o,this.coordinatePoints=s}getClosestCoordinate(t,e){const i={dist:Infinity,index:-1,isFirstOrLastPolygonCoord:!1};let o;if("LineString"===e.type)o=e.coordinates;else{if("Polygon"!==e.type)return i;o=e.coordinates[0]}for(let s=0;s<o.length;s++){const r=this.pixelDistance.measure(t,o[s]);if(r<this.pointerDistance&&r<i.dist){const t="Polygon"===e.type&&(s===o.length-1||0===s);i.dist=r,i.index=t?0:s,i.isFirstOrLastPolygonCoord=t}}return i}isValidDragWebMercator(t,e,i){switch(t){case 0:if(e<=0||i>=0)return!1;break;case 1:if(i>=0)return!1;break;case 2:if(e>=0||i>=0)return!1;break;case 3:if(e>=0)return!1;break;case 4:if(e>=0||i<=0)return!1;break;case 5:if(i<=0)return!1;break;case 6:if(e<=0||i<=0)return!1;break;case 7:if(e<=0)return!1}return!0}getSelectedFeatureDataWebMercator(){if(!this.draggedCoordinate.id||-1===this.draggedCoordinate.index)return null;const t=this.getFeature(this.draggedCoordinate.id);if(!t)return null;const e=this.getNormalisedCoordinates(t.geometry);return{boundingBox:this.getBBoxWebMercator(e),feature:t,updatedCoords:e,selectedCoordinate:e[this.draggedCoordinate.index]}}centerWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{feature:i,boundingBox:o,updatedCoords:s,selectedCoordinate:r}=e,n=Xt(i);if(!n)return null;const a=S(r[0],r[1]),{closestBBoxIndex:d}=this.getIndexesWebMercator(o,a),h=S(t.lng,t.lat);return this.scaleWebMercator({closestBBoxIndex:d,updatedCoords:s,webMercatorCursor:h,webMercatorSelected:a,webMercatorOrigin:n}),s}centerFixedWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{feature:i,boundingBox:o,updatedCoords:s,selectedCoordinate:r}=e,n=Xt(i);if(!n)return null;const a=S(r[0],r[1]),{closestBBoxIndex:d}=this.getIndexesWebMercator(o,a),h=S(t.lng,t.lat);return this.scaleFixedWebMercator({closestBBoxIndex:d,updatedCoords:s,webMercatorCursor:h,webMercatorSelected:a,webMercatorOrigin:n}),s}scaleFixedWebMercator({closestBBoxIndex:t,webMercatorOrigin:e,webMercatorSelected:i,webMercatorCursor:o,updatedCoords:s}){if(!this.isValidDragWebMercator(t,e.x-o.x,e.y-o.y))return null;let r=A(e,o)/A(e,i);return r<0&&(r=this.minimumScale),Zt({coordinates:s,originX:e.x,originY:e.y,xScale:r,yScale:r}),s}oppositeFixedWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{boundingBox:i,updatedCoords:o,selectedCoordinate:s}=e,r=S(s[0],s[1]),{oppositeBboxIndex:n,closestBBoxIndex:a}=this.getIndexesWebMercator(i,r),d={x:i[n][0],y:i[n][1]},h=S(t.lng,t.lat);return this.scaleFixedWebMercator({closestBBoxIndex:a,updatedCoords:o,webMercatorCursor:h,webMercatorSelected:r,webMercatorOrigin:d}),o}oppositeWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{boundingBox:i,updatedCoords:o,selectedCoordinate:s}=e,r=S(s[0],s[1]),{oppositeBboxIndex:n,closestBBoxIndex:a}=this.getIndexesWebMercator(i,r),d={x:i[n][0],y:i[n][1]},h=S(t.lng,t.lat);return this.scaleWebMercator({closestBBoxIndex:a,updatedCoords:o,webMercatorCursor:h,webMercatorSelected:r,webMercatorOrigin:d}),o}scaleWebMercator({closestBBoxIndex:t,webMercatorOrigin:e,webMercatorSelected:i,webMercatorCursor:o,updatedCoords:s}){const r=e.x-o.x,n=e.y-o.y;if(!this.isValidDragWebMercator(t,r,n))return null;let a=1;0!==r&&1!==t&&5!==t&&(a=1-(e.x-i.x-r)/r);let d=1;return 0!==n&&3!==t&&7!==t&&(d=1-(e.y-i.y-n)/n),this.validateScale(a,d)?(a<0&&(a=this.minimumScale),d<0&&(d=this.minimumScale),this.performWebMercatorScale(s,e.x,e.y,a,d),s):null}getFeature(t){if(null===this.draggedCoordinate.id)return null;const e=this.store.getGeometryCopy(t);return"Polygon"!==e.type&&"LineString"!==e.type?null:{id:t,type:"Feature",geometry:e,properties:{}}}getNormalisedCoordinates(t){return"Polygon"===t.type?t.coordinates[0]:t.coordinates}validateScale(t,e){const i=!isNaN(t)&&e<Number.MAX_SAFE_INTEGER,o=!isNaN(e)&&e<Number.MAX_SAFE_INTEGER;return i&&o}performWebMercatorScale(t,e,i,o,s){t.forEach(t=>{const{x:r,y:n}=S(t[0],t[1]),a=e+(r-e)*o,d=i+(n-i)*s,{lng:h,lat:l}=M(a,d);t[0]=h,t[1]=l})}getBBoxWebMercator(t){const e=[Infinity,Infinity,-Infinity,-Infinity];(t=t.map(t=>{const{x:e,y:i}=S(t[0],t[1]);return[e,i]})).forEach(([t,i])=>{t<e[0]&&(e[0]=t),i<e[1]&&(e[1]=i),t>e[2]&&(e[2]=t),i>e[3]&&(e[3]=i)});const[i,o,s,r]=e;return[[i,r],[(i+s)/2,r],[s,r],[s,r+(o-r)/2],[s,o],[(i+s)/2,o],[i,o],[i,r+(o-r)/2]]}getIndexesWebMercator(t,e){let i,o=Infinity;for(let s=0;s<t.length;s++){const r=A({x:e.x,y:e.y},{x:t[s][0],y:t[s][1]});r<o&&(i=s,o=r)}if(void 0===i)throw new Error("No closest coordinate found");return{oppositeBboxIndex:this.boundingBoxMaps.opposite[i],closestBBoxIndex:i}}isDragging(){return null!==this.draggedCoordinate.id}startDragging(t,e){this.draggedCoordinate={id:t,index:e}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}getDraggableIndex(t,e){const i=this.store.getGeometryCopy(e),o=this.getClosestCoordinate(t,i);return-1===o.index?-1:o.index}drag(t,i,o){if(!this.draggedCoordinate.id)return!1;const s=this.getFeature(this.draggedCoordinate.id);if(!s)return!1;let r=null;if("center"===i?r=this.centerWebMercatorDrag(t):"opposite"===i?r=this.oppositeWebMercatorDrag(t):"center-fixed"===i?r=this.centerFixedWebMercatorDrag(t):"opposite-fixed"===i&&(r=this.oppositeFixedWebMercatorDrag(t)),!r)return!1;for(let t=0;t<r.length;t++){const e=r[t];if(e[0]=P(e[0],this.coordinatePrecision),e[1]=P(e[1],this.coordinatePrecision),!k(e,this.coordinatePrecision))return!1}const n=this.midPoints.getUpdated(r)||[],a=this.selectionPoints.getUpdated(r)||[],d=this.coordinatePoints.getUpdated(s.id,r)||[],h={type:s.geometry.type,coordinates:"Polygon"===s.geometry.type?[r]:r};return!(o&&!o({id:this.draggedCoordinate.id,type:"Feature",geometry:h,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:e.Provisional}).valid||(this.store.updateGeometry([{id:this.draggedCoordinate.id,geometry:h},...a,...n,...d]),0))}}const Qt={deselect:"Escape",delete:"Delete",rotate:["Control","r"],scale:["Control","s"]},te={pointerOver:"move",dragStart:"move",dragEnd:"move",insertMidpoint:"crosshair"};class ee extends g{constructor(t){super(t,!0),this.mode="select",this.allowManualDeselection=!0,this.dragEventThrottle=5,this.dragEventCount=0,this.selected=[],this.flags={},this.keyEvents=Qt,this.cursors=te,this.validations={},this.selectionPoints=void 0,this.midPoints=void 0,this.coordinateSnap=void 0,this.featuresAtMouseEvent=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.dragFeature=void 0,this.dragCoordinate=void 0,this.rotateFeature=void 0,this.scaleFeature=void 0,this.dragCoordinateResizeFeature=void 0,this.coordinatePoints=void 0,this.lineSnap=void 0,this.updateOptions(t)}updateOptions(e){if(super.updateOptions(e),this.cursors=e&&e.cursors?t({},this.cursors,e.cursors):te,null===(null==e?void 0:e.keyEvents)?this.keyEvents={deselect:null,delete:null,rotate:null,scale:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),void 0!==(null==e?void 0:e.dragEventThrottle)&&(this.dragEventThrottle=e.dragEventThrottle),void 0!==(null==e?void 0:e.allowManualDeselection)&&(this.allowManualDeselection=e.allowManualDeselection),null!=e&&e.flags){this.flags=t({},this.flags,e.flags),this.validations={};for(const t in this.flags){const e=this.flags[t].feature;e&&e.validation&&(this.validations[t]=e.validation)}}}selectFeature(t){this.select(t,!1)}setSelecting(){if("started"!==this._state)throw new Error("Mode must be started to move to selecting state");this._state="selecting"}registerBehaviors(t){this.pixelDistance=new q(t),this.clickBoundingBox=new $(t),this.featuresAtMouseEvent=new Vt(t,this.clickBoundingBox,this.pixelDistance),this.selectionPoints=new Ut(t),this.coordinatePoints=new Ft(t),this.midPoints=new Rt(t,this.selectionPoints,this.coordinatePoints),this.coordinateSnap=new Z(t,this.pixelDistance,this.clickBoundingBox),this.lineSnap=new yt(t,this.pixelDistance,this.clickBoundingBox),this.rotateFeature=new $t(t,this.selectionPoints,this.midPoints,this.coordinatePoints),this.dragFeature=new Yt(t,this.featuresAtMouseEvent,this.selectionPoints,this.midPoints,this.coordinatePoints),this.dragCoordinate=new Kt(t,this.pixelDistance,this.selectionPoints,this.midPoints,this.coordinatePoints,this.coordinateSnap,this.lineSnap),this.dragCoordinateResizeFeature=new Jt(t,this.pixelDistance,this.selectionPoints,this.midPoints,this.coordinatePoints),this.scaleFeature=new qt(t,this.dragCoordinateResizeFeature)}deselectFeature(){this.deselect()}deselect(){const t=this.selected.filter(t=>this.store.has(t)).map(t=>({id:t,property:o.SELECTED,value:!1}));this.store.updateProperty(t),this.onDeselect(this.selected[0]),this.selected=[],this.selectionPoints.delete(),this.midPoints.delete()}deleteSelected(){this.store.delete(this.selected),this.selected=[]}onRightClick(t){if(!this.selectionPoints.ids.length)return;let i,o=Infinity;if(this.selectionPoints.ids.forEach(e=>{const s=this.store.getGeometryCopy(e),r=this.pixelDistance.measure(t,s.coordinates);r<this.pointerDistance&&r<o&&(o=r,i=this.store.getPropertiesCopy(e))}),!i)return;const s=i.selectionPointFeatureId,r=i.index,n=this.store.getPropertiesCopy(s),a=this.flags[n.mode],d=this.validations[n.mode];if(!(a&&a.feature&&a.feature.coordinates&&a.feature.coordinates.deletable))return;const h=this.store.getGeometryCopy(s);let l;if("Polygon"===h.type){if(l=h.coordinates[0],l.length<=4)return}else if("LineString"===h.type&&(l=h.coordinates,l.length<=2))return;if(!l)return;if("Polygon"!==h.type||0!==r&&r!==l.length-1?l.splice(r,1):(l.shift(),l.pop(),l.push([l[0][0],l[0][1]])),d&&!d({id:s,type:"Feature",geometry:h,properties:n},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Commit}).valid)return;const c=[...this.midPoints.ids,...this.selectionPoints.ids];this.store.delete(c),this.store.updateGeometry([{id:s,geometry:h}]),n.coordinatePointIds&&this.coordinatePoints.createOrUpdate(s),this.selectionPoints.create(l,h.type,s),a&&a.feature&&a.feature.coordinates&&a.feature.coordinates.midpoints&&this.midPoints.create(l,s,this.coordinatePrecision)}select(t,e=!0){if(this.selected[0]===t)return;const{mode:i}=this.store.getPropertiesCopy(t),s=this.flags[i];if(!s||!s.feature)return;const r=this.selected[0];if(r){if(r===t)return;this.deselect()}e&&this.setCursor(this.cursors.pointerOver),this.selected=[t],this.store.updateProperty([{id:t,property:o.SELECTED,value:!0}]),this.onSelect(t);const{type:n,coordinates:a}=this.store.getGeometryCopy(t);if("LineString"!==n&&"Polygon"!==n)return;const d="LineString"===n?a:a[0];d&&s&&s.feature.coordinates&&(this.selectionPoints.create(d,n,t),s.feature.coordinates.midpoints&&this.midPoints.create(d,t,this.coordinatePrecision))}onLeftClick(t){const{clickedFeature:e,clickedMidPoint:i}=this.featuresAtMouseEvent.find(t,this.selected.length>0);if(this.selected.length&&i)this.midPoints.insert(this.selected[0],i.id,this.coordinatePrecision);else if(e&&e.id)this.select(e.id,!0);else if(this.selected.length&&this.allowManualDeselection)return void this.deselect()}start(){this.setStarted(),this.setSelecting()}stop(){this.cleanUp(),this.setStarted(),this.setStopped()}onClick(t){"right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)?this.onRightClick(t):"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)&&this.onLeftClick(t)}canScale(t){return this.keyEvents.scale&&this.keyEvents.scale.every(e=>t.heldKeys.includes(e))}canRotate(t){return this.keyEvents.rotate&&this.keyEvents.rotate.every(e=>t.heldKeys.includes(e))}preventDefaultKeyEvent(t){const e=this.canRotate(t),i=this.canScale(t);(e||i)&&t.preventDefault()}onKeyDown(t){this.preventDefaultKeyEvent(t)}onKeyUp(t){if(this.preventDefaultKeyEvent(t),this.keyEvents.delete&&t.key===this.keyEvents.delete){if(!this.selected.length)return;const t=this.selected[0];this.onDeselect(this.selected[0]),this.coordinatePoints.deletePointsByFeatureIds([t]),this.deleteSelected(),this.selectionPoints.delete(),this.midPoints.delete()}else this.keyEvents.deselect&&t.key===this.keyEvents.deselect&&this.cleanUp()}cleanUp(){this.selected.length&&this.deselect()}onDragStart(t,e){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,t))return;if(!this.selected.length)return;const i=this.store.getPropertiesCopy(this.selected[0]),o=this.flags[i.mode];if(!(o&&o.feature&&(o.feature.draggable||o.feature.coordinates&&o.feature.coordinates.draggable||o.feature.coordinates&&o.feature.coordinates.resizable||o.feature.coordinates&&"object"==typeof o.feature.coordinates.midpoints&&o.feature.coordinates.midpoints.draggable)))return;this.dragEventCount=0;const s=this.selected[0],r=this.dragCoordinate.getDraggableIndex(t,s);if(o&&o.feature&&o.feature.coordinates&&(o.feature.coordinates.draggable||o.feature.coordinates.resizable)&&-1!==r)return this.setCursor(this.cursors.dragStart),o.feature.coordinates.resizable?this.dragCoordinateResizeFeature.startDragging(s,r):this.dragCoordinate.startDragging(s,r),void e(!1);if(o&&o.feature&&o.feature.coordinates&&"object"==typeof o.feature.coordinates.midpoints&&o.feature.coordinates.midpoints.draggable){const{clickedMidPoint:i}=this.featuresAtMouseEvent.find(t,this.selected.length>0);if(this.selected.length&&i){this.midPoints.insert(s,i.id,this.coordinatePrecision);const o=this.dragCoordinate.getDraggableIndex(t,s);return this.dragCoordinate.startDragging(s,o),void e(!1)}}return o&&o.feature&&o.feature.draggable&&this.dragFeature.canDrag(t,s)?(this.setCursor(this.cursors.dragStart),this.dragFeature.startDragging(t,s),void e(!1)):void 0}onDrag(t,e){if(!this.allowPointerEvent(this.pointerEvents.onDrag,t))return;const i=this.selected[0];if(!i)return;const o=this.store.getPropertiesCopy(i),s=this.flags[o.mode],r=!0===(s&&s.feature&&s.feature.selfIntersectable);if(this.dragEventCount++,this.dragEventCount%this.dragEventThrottle==0)return;const n=this.validations[o.mode];if(s&&s.feature&&s.feature.rotateable&&this.canRotate(t))return e(!1),void this.rotateFeature.rotate(t,i,n);if(s&&s.feature&&s.feature.scaleable&&this.canScale(t))return e(!1),void this.scaleFeature.scale(t,i,n);if(this.dragCoordinateResizeFeature.isDragging()&&s.feature&&s.feature.coordinates&&s.feature.coordinates.resizable){if("globe"===this.projection)throw new Error("Globe is currently unsupported projection for resizable");return e(!1),void this.dragCoordinateResizeFeature.drag(t,s.feature.coordinates.resizable,n)}if(this.dragCoordinate.isDragging()){var a;const e=null==(a=s.feature)||null==(a=a.coordinates)?void 0:a.snappable;let i={toCoordinate:!1};return!0===e?i={toCoordinate:!0}:"object"==typeof e&&(i=e),void this.dragCoordinate.drag(t,r,n,i)}this.dragFeature.isDragging()?this.dragFeature.drag(t,n):e(!0)}onDragEnd(t,e){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&(this.setCursor(this.cursors.dragEnd),this.dragCoordinate.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinate"}):this.dragFeature.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragFeature"}):this.dragCoordinateResizeFeature.isDragging()&&this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinateResize"}),this.dragCoordinate.stopDragging(),this.dragFeature.stopDragging(),this.dragCoordinateResizeFeature.stopDragging(),this.rotateFeature.reset(),this.scaleFeature.reset(),e(!0))}onMouseMove(t){if(!this.selected.length)return void this.setCursor("unset");if(this.dragFeature.isDragging())return;let e=!1;this.midPoints.ids.forEach(i=>{if(e)return;const o=this.store.getGeometryCopy(i);this.pixelDistance.measure(t,o.coordinates)<this.pointerDistance&&(e=!0)});let i=!1;if(this.selectionPoints.ids.forEach(o=>{const s=this.store.getGeometryCopy(o);this.pixelDistance.measure(t,s.coordinates)<this.pointerDistance&&(e=!1,i=!0)}),e)return void this.setCursor(this.cursors.insertMidpoint);const{clickedFeature:o}=this.featuresAtMouseEvent.find(t,!0);this.setCursor(this.selected.length>0&&(o&&o.id===this.selected[0]||i)?this.cursors.pointerOver:"unset")}styleFeature(e){const n=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});if(e.properties.mode===this.mode&&"Point"===e.geometry.type){if(e.properties[o.SELECTION_POINT])return n.pointColor=this.getHexColorStylingValue(this.styles.selectionPointColor,n.pointColor,e),n.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectionPointOutlineColor,n.pointOutlineColor,e),n.pointWidth=this.getNumericStylingValue(this.styles.selectionPointWidth,n.pointWidth,e),n.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectionPointOutlineWidth,2,e),n.zIndex=30,n;if(e.properties[o.MID_POINT])return n.pointColor=this.getHexColorStylingValue(this.styles.midPointColor,n.pointColor,e),n.pointOutlineColor=this.getHexColorStylingValue(this.styles.midPointOutlineColor,n.pointOutlineColor,e),n.pointWidth=this.getNumericStylingValue(this.styles.midPointWidth,4,e),n.pointOutlineWidth=this.getNumericStylingValue(this.styles.midPointOutlineWidth,2,e),n.zIndex=50,n}else if(e.properties[o.SELECTED]){if("Point"===e.geometry.type&&e.properties[s.MARKER])return n.markerUrl=this.getUrlStylingValue(this.styles.selectedMarkerUrl,i,e),n.markerHeight=this.getNumericStylingValue(this.styles.selectedMarkerHeight,40,e),n.markerWidth=this.getNumericStylingValue(this.styles.selectedMarkerWidth,32,e),n;if("Polygon"===e.geometry.type)return n.polygonFillColor=this.getHexColorStylingValue(this.styles.selectedPolygonColor,n.polygonFillColor,e),n.polygonOutlineWidth=this.getNumericStylingValue(this.styles.selectedPolygonOutlineWidth,n.polygonOutlineWidth,e),n.polygonOutlineColor=this.getHexColorStylingValue(this.styles.selectedPolygonOutlineColor,n.polygonOutlineColor,e),n.polygonFillOpacity=this.getNumericStylingValue(this.styles.selectedPolygonFillOpacity,n.polygonFillOpacity,e),n.zIndex=r,n;if("LineString"===e.geometry.type)return n.lineStringColor=this.getHexColorStylingValue(this.styles.selectedLineStringColor,n.lineStringColor,e),n.lineStringWidth=this.getNumericStylingValue(this.styles.selectedLineStringWidth,n.lineStringWidth,e),n.zIndex=r,n;if("Point"===e.geometry.type)return n.pointWidth=this.getNumericStylingValue(this.styles.selectedPointWidth,n.pointWidth,e),n.pointColor=this.getHexColorStylingValue(this.styles.selectedPointColor,n.pointColor,e),n.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectedPointOutlineColor,n.pointOutlineColor,e),n.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectedPointOutlineWidth,n.pointOutlineWidth,e),n.zIndex=r,n}return n}afterFeatureUpdated(t){if(this.selected.length&&t.id===this.selected[0]){var e,i;const o=this.flags[t.properties.mode];if(null==o||null==(e=o.feature)||!e.coordinates)return;const s=t.geometry.type,r=t.id;let n;if(this.selectionPoints.delete(),this.midPoints.delete(),"Polygon"===s)n=t.geometry.coordinates[0];else{if("LineString"!==s)return;n=t.geometry.coordinates}this.selectionPoints.create(n,s,r),null!=o&&null!=(i=o.feature)&&null!=(i=i.coordinates)&&i.midpoints&&this.midPoints.create("Polygon"===s?t.geometry.coordinates[0]:t.geometry.coordinates,r,this.coordinatePrecision)}}}class ie extends p{constructor(...t){super(...t),this.type=c.Static,this.mode="static"}start(){}stop(){}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(){return t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0})}}function oe(t,e,i,o,s){for(;o>i;){if(o-i>600){const r=o-i+1,n=e-i+1,a=Math.log(r),d=.5*Math.exp(2*a/3),h=.5*Math.sqrt(a*d*(r-d)/r)*(n-r/2<0?-1:1);oe(t,e,Math.max(i,Math.floor(e-n*d/r+h)),Math.min(o,Math.floor(e+(r-n)*d/r+h)),s)}const r=t[e];let n=i,a=o;for(se(t,i,e),s(t[o],r)>0&&se(t,i,o);n<a;){for(se(t,n,a),n++,a--;s(t[n],r)<0;)n++;for(;s(t[a],r)>0;)a--}0===s(t[i],r)?se(t,i,a):(a++,se(t,a,o)),a<=e&&(i=a+1),e<=a&&(o=a-1)}}function se(t,e,i){const o=t[e];t[e]=t[i],t[i]=o}function re(t,e){ne(t,0,t.children.length,e,t)}function ne(t,e,i,o,s){s||(s=ye([])),s.minX=Infinity,s.minY=Infinity,s.maxX=-Infinity,s.maxY=-Infinity;for(let r=e;r<i;r++){const e=t.children[r];ae(s,t.leaf?o(e):e)}return s}function ae(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function de(t,e){return t.minX-e.minX}function he(t,e){return t.minY-e.minY}function le(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function ce(t){return t.maxX-t.minX+(t.maxY-t.minY)}function ue(t,e){const i=Math.max(t.minX,e.minX),o=Math.max(t.minY,e.minY),s=Math.min(t.maxX,e.maxX),r=Math.min(t.maxY,e.maxY);return Math.max(0,s-i)*Math.max(0,r-o)}function pe(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function ge(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function ye(t){return{children:t,height:1,leaf:!0,minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity}}function fe(t,e,i,o,s){const r=[e,i];for(;r.length;){if((i=r.pop())-(e=r.pop())<=o)continue;const n=e+Math.ceil((i-e)/o/2)*o;oe(t,n,e,i,s),r.push(e,n,n,i)}}class me{constructor(t){this._maxEntries=void 0,this._minEntries=void 0,this.data=void 0,this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}search(t){let e=this.data;const i=[];if(!ge(t,e))return i;const o=this.toBBox,s=[];for(;e;){for(let r=0;r<e.children.length;r++){const n=e.children[r],a=e.leaf?o(n):n;ge(t,a)&&(e.leaf?i.push(n):pe(t,a)?this._all(n,i):s.push(n))}e=s.pop()}return i}collides(t){let e=this.data;if(ge(t,e)){const i=[];for(;e;){for(let o=0;o<e.children.length;o++){const s=e.children[o],r=e.leaf?this.toBBox(s):s;if(ge(t,r)){if(e.leaf||pe(t,r))return!0;i.push(s)}}e=i.pop()}}return!1}load(t){if(t.length<this._minEntries){for(let e=0;e<t.length;e++)this.insert(t[e]);return}let e=this._build(t.slice(),0,t.length-1,0);if(this.data.children.length)if(this.data.height===e.height)this._splitRoot(this.data,e);else{if(this.data.height<e.height){const t=this.data;this.data=e,e=t}this._insert(e,this.data.height-e.height-1,!0)}else this.data=e}insert(t){this._insert(t,this.data.height-1)}clear(){this.data=ye([])}remove(t){let e=this.data;const i=this.toBBox(t),o=[],s=[];let r,n,a=!1;for(;e||o.length;){if(e||(e=o.pop(),n=o[o.length-1],r=s.pop(),a=!0),e.leaf){const i=e.children.indexOf(t);-1!==i&&(e.children.splice(i,1),o.push(e),this._condense(o))}a||e.leaf||!pe(e,i)?n?(r++,e=n.children[r],a=!1):e=null:(o.push(e),s.push(r),r=0,n=e,e=e.children[0])}}toBBox(t){return t}compareMinX(t,e){return t.minX-e.minX}compareMinY(t,e){return t.minY-e.minY}_all(t,e){const i=[];for(;t;)t.leaf?e.push(...t.children):i.push(...t.children),t=i.pop();return e}_build(t,e,i,o){const s=i-e+1;let r,n=this._maxEntries;if(s<=n)return r=ye(t.slice(e,i+1)),re(r,this.toBBox),r;o||(o=Math.ceil(Math.log(s)/Math.log(n)),n=Math.ceil(s/Math.pow(n,o-1))),r=ye([]),r.leaf=!1,r.height=o;const a=Math.ceil(s/n),d=a*Math.ceil(Math.sqrt(n));fe(t,e,i,d,this.compareMinX);for(let s=e;s<=i;s+=d){const e=Math.min(s+d-1,i);fe(t,s,e,a,this.compareMinY);for(let i=s;i<=e;i+=a){const s=Math.min(i+a-1,e);r.children.push(this._build(t,i,s,o-1))}}return re(r,this.toBBox),r}_chooseSubtree(t,e,i,o){for(;o.push(e),!e.leaf&&o.length-1!==i;){let i,o=Infinity,n=Infinity;for(let a=0;a<e.children.length;a++){const d=e.children[a],h=le(d),l=(s=t,r=d,(Math.max(r.maxX,s.maxX)-Math.min(r.minX,s.minX))*(Math.max(r.maxY,s.maxY)-Math.min(r.minY,s.minY))-h);l<n?(n=l,o=h<o?h:o,i=d):l===n&&h<o&&(o=h,i=d)}e=i||e.children[0]}var s,r;return e}_insert(t,e,i){const o=i?t:this.toBBox(t),s=[],r=this._chooseSubtree(o,this.data,e,s);for(r.children.push(t),ae(r,o);e>=0&&s[e].children.length>this._maxEntries;)this._split(s,e),e--;this._adjustParentBBoxes(o,s,e)}_split(t,e){const i=t[e],o=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,o);const r=this._chooseSplitIndex(i,s,o),n=ye(i.children.splice(r,i.children.length-r));n.height=i.height,n.leaf=i.leaf,re(i,this.toBBox),re(n,this.toBBox),e?t[e-1].children.push(n):this._splitRoot(i,n)}_splitRoot(t,e){this.data=ye([t,e]),this.data.height=t.height+1,this.data.leaf=!1,re(this.data,this.toBBox)}_chooseSplitIndex(t,e,i){let o,s=Infinity,r=Infinity;for(let n=e;n<=i-e;n++){const e=ne(t,0,n,this.toBBox),a=ne(t,n,i,this.toBBox),d=ue(e,a),h=le(e)+le(a);d<s?(s=d,o=n,r=h<r?h:r):d===s&&h<r&&(r=h,o=n)}return o||i-e}_chooseSplitAxis(t,e,i){const o=t.leaf?this.compareMinX:de,s=t.leaf?this.compareMinY:he;this._allDistMargin(t,e,i,o)<this._allDistMargin(t,e,i,s)&&t.children.sort(o)}_allDistMargin(t,e,i,o){t.children.sort(o);const s=this.toBBox,r=ne(t,0,e,s),n=ne(t,i-e,i,s);let a=ce(r)+ce(n);for(let o=e;o<i-e;o++){const e=t.children[o];ae(r,t.leaf?s(e):e),a+=ce(r)}for(let o=i-e-1;o>=e;o--){const e=t.children[o];ae(n,t.leaf?s(e):e),a+=ce(n)}return a}_adjustParentBBoxes(t,e,i){for(let o=i;o>=0;o--)ae(e[o],t)}_condense(t){for(let e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children,e.splice(e.indexOf(t[i]),1)):this.clear():re(t[i],this.toBBox)}}class ve{constructor(t){this.tree=void 0,this.idToNode=void 0,this.nodeToId=void 0,this.tree=new me(t&&t.maxEntries?t.maxEntries:9),this.idToNode=new Map,this.nodeToId=new Map}setMaps(t,e){this.idToNode.set(t.id,e),this.nodeToId.set(e,t.id)}toBBox(t){const e=[],i=[];let o;if("Polygon"===t.geometry.type)o=t.geometry.coordinates[0];else if("LineString"===t.geometry.type)o=t.geometry.coordinates;else{if("Point"!==t.geometry.type)throw new Error("Not a valid feature to turn into a bounding box");o=[t.geometry.coordinates]}for(let t=0;t<o.length;t++)i.push(o[t][1]),e.push(o[t][0]);const s=Math.min(...i),r=Math.max(...i);return{minX:Math.min(...e),minY:s,maxX:Math.max(...e),maxY:r}}insert(t){if(this.idToNode.get(String(t.id)))throw new Error("Feature already exists");const e=this.toBBox(t);this.setMaps(t,e),this.tree.insert(e)}load(t){const e=[],i=new Set;t.forEach(t=>{const o=this.toBBox(t);if(this.setMaps(t,o),i.has(String(t.id)))throw new Error(`Duplicate feature ID found ${t.id}`);i.add(String(t.id)),e.push(o)}),this.tree.load(e)}update(t){this.remove(t.id);const e=this.toBBox(t);this.setMaps(t,e),this.tree.insert(e)}remove(t){const e=this.idToNode.get(t);if(!e)throw new Error(`${t} not inserted into the spatial index`);this.tree.remove(e)}clear(){this.tree.clear()}search(t){return this.tree.search(this.toBBox(t)).map(t=>this.nodeToId.get(t))}collides(t){return this.tree.collides(this.toBBox(t))}}const Ce={getId:()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)}),isValidId:t=>"string"==typeof t&&36===t.length};class Pe{constructor(t){this.idStrategy=void 0,this.tracked=void 0,this.spatialIndex=void 0,this.store=void 0,this._onChange=()=>{},this.store={},this.spatialIndex=new ve,this.tracked=!t||!1!==t.tracked,this.idStrategy=t&&t.idStrategy?t.idStrategy:Ce}clone(t){return JSON.parse(JSON.stringify(t))}getId(){return this.idStrategy.getId()}has(t){return Boolean(this.store[t])}load(t,e,i,o){if(0===t.length)return[];let s=this.clone(t);const r=[],n=[];s=s.filter(t=>{null==t.id&&(t.id=this.idStrategy.getId());const i=t.id;if(e){const o=e(t);if(!o.valid)return r.push({id:i,valid:!1,reason:o.reason}),!1}if(this.tracked){if(t.properties.createdAt){if(!d(t.properties.createdAt))return r.push({id:t.id,valid:!1,reason:"createdAt is not a valid numeric timestamp"}),!1}else t.properties.createdAt=+new Date;if(t.properties.updatedAt){if(!d(t.properties.updatedAt))return r.push({id:t.id,valid:!1,reason:"updatedAt is not a valid numeric timestamp"}),!1}else t.properties.updatedAt=+new Date}return this.has(i)?(r.push({id:i,valid:!1,reason:`Feature already exists with this id: ${i}`}),!1):(this.store[i]=t,n.push(t),r.push({id:i,valid:!0}),!0)}),this.spatialIndex.load(s);const a=n.map(({id:t})=>t);return a.length>0&&(this._onChange(a,"create",o),i&&n.forEach(t=>{i(t)})),r}search(t,e){const i=this.spatialIndex.search(t).map(t=>this.store[t]);return this.clone(e?i.filter(e):i)}registerOnChange(t){this._onChange=(e,i,o)=>{t(e,i,o)}}getGeometryCopy(t){const e=this.store[t];if(!e)throw new Error(`No feature with this id (${t}), can not get geometry copy`);return this.clone(e.geometry)}getPropertiesCopy(t){const e=this.store[t];if(!e)throw new Error(`No feature with this id (${t}), can not get properties copy`);return this.clone(e.properties)}updateProperty(t,e){const i=[];t.forEach(({id:t,property:e,value:o})=>{const s=this.store[t];if(!s)throw new Error(`No feature with this (${t}), can not update geometry`);i.push(t),void 0===o?delete s.properties[e]:s.properties[e]=o,this.tracked&&(s.properties.updatedAt=+new Date)}),this._onChange&&this._onChange(i,"update",e)}updateGeometry(t,e){const i=[];t.forEach(({id:t,geometry:e})=>{i.push(t);const o=this.store[t];if(!o)throw new Error(`No feature with this (${t}), can not update geometry`);o.geometry=this.clone(e),this.spatialIndex.update(o),this.tracked&&(o.properties.updatedAt=+new Date)}),this._onChange&&this._onChange(i,"update",e)}create(e,i){const o=[];return e.forEach(({geometry:e,properties:i})=>{let s,r=t({},i);this.tracked&&(s=+new Date,i?(r.createdAt="number"==typeof i.createdAt?i.createdAt:s,r.updatedAt="number"==typeof i.updatedAt?i.updatedAt:s):r={createdAt:s,updatedAt:s});const n=this.getId(),a={id:n,type:"Feature",geometry:e,properties:r};this.store[n]=a,this.spatialIndex.insert(a),o.push(n)}),this._onChange&&this._onChange([...o],"create",i),o}delete(t,e){t.forEach(t=>{if(!this.store[t])throw new Error(`No feature with id ${t}, can not delete`);delete this.store[t],this.spatialIndex.remove(t)}),this._onChange&&this._onChange([...t],"delete",e)}copy(t){return this.clone(this.store[t])}copyAll(){return this.clone(Object.keys(this.store).map(t=>this.store[t]))}copyAllWhere(t){return this.clone(Object.keys(this.store).map(t=>this.store[t]).filter(e=>e.properties&&t(e.properties)))}clear(){this.store={},this.spatialIndex.clear()}size(){return Object.keys(this.store).length}}function Ie(t){const e=t.coordinates;let i=0;if(e&&e.length>0){i+=Math.abs(Se(e[0]));for(let t=1;t<e.length;t++)i-=Math.abs(Se(e[t]))}return i}const xe=20294876564838.72,Ee=Math.PI/180;function Se(t){const e=t.length;if(e<=2)return 0;let i=0,o=0;for(;o<e;)i+=(t[o+2>=e?(o+2)%e:o+2][0]*Ee-t[o][0]*Ee)*Math.sin(t[o+1===e?0:o+1][1]*Ee),o++;return i*xe}const Me="Feature is smaller than the minimum area",Fe=(t,e)=>"Polygon"!==t.geometry.type?{valid:!1,reason:h}:Ie(t.geometry)<e?{valid:!1,reason:Me}:{valid:!0},De=(t,e)=>"Polygon"!==t.geometry.type?{valid:!1,reason:h}:Ie(t.geometry)>e?{valid:!1,reason:"Feature is larger than the maximum area"}:{valid:!0},we="Feature is not a Polygon or LineString",Oe="Feature intersects itself",ke=t=>"Polygon"!==t.geometry.type&&"LineString"!==t.geometry.type?{valid:!1,reason:we}:w(t)?{valid:!1,reason:Oe}:{valid:!0};function _e(t,e,i){const o=et(t,e);let s=et(e,i)-o;return s<0&&(s+=360),180-Math.abs(s-90-90)}const be={cancel:"Escape",finish:"Enter"},Ne={start:"crosshair",close:"pointer"};class Te extends p{constructor(t){super(t,!0),this.mode="angled-rectangle",this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=be,this.cursors=Ne,this.mouseMove=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents))}close(){if(void 0===this.currentId)return;this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}]);const t=this.currentId;this.currentCoordinate=0,this.currentId=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(t,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){if(this.mouseMove=!0,this.setCursor(this.cursors.start),void 0===this.currentId||0===this.currentCoordinate)return;const i=this.store.getGeometryCopy(this.currentId).coordinates[0];let o;if(1===this.currentCoordinate){const e=1/Math.pow(10,this.coordinatePrecision-1),s=Math.max(1e-6,e);o=[i[0],[t.lng,t.lat],[t.lng,t.lat-s],i[0]]}else if(2===this.currentCoordinate){const e=i[0],s=i[1],r=jt(e,s,this.coordinatePrecision,this.project,this.unproject),n=S(e[0],e[1]),a=S(r[0],r[1]),d=S(s[0],s[1]),h=S(t.lng,t.lat),l=A(h,n)<A(h,d),c=_e(n,a,h),u=l?90-c:_e(n,a,h)-90,p=A(a,h),g=Math.cos(m(u))*p,y=et(n,d)+("right"===function(t,e,i){const o=(i.x-e.x)*(t.y-e.y)-(i.y-e.y)*(t.x-e.x);return o>1e-10?"left":o<-1e-10?"right":"left"}(n,d,h)?-90:90),f=Q(n,g,y),v=Q(d,g,y),C=M(f.x,f.y),I=M(v.x,v.y);o=[i[0],i[1],[P(I.lng,this.coordinatePrecision),P(I.lat,this.coordinatePrecision)],[P(C.lng,this.coordinatePrecision),P(C.lat,this.coordinatePrecision)],i[0]]}o&&this.updatePolygonGeometry(this.currentId,o,e.Provisional)}updatePolygonGeometry(t,e,i){const o={type:"Polygon",coordinates:[e]};return!(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}).valid||(this.store.updateGeometry([{id:t,geometry:o}]),0))}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))if(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,0===this.currentCoordinate){const[e]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}}]);this.currentId=e,this.currentCoordinate++,this.setDrawing()}else if(1===this.currentCoordinate&&this.currentId){const i=this.store.getGeometryCopy(this.currentId);if(at([t.lng,t.lat],i.coordinates[0][0]))return;if(!this.updatePolygonGeometry(this.currentId,[i.coordinates[0][0],[t.lng,t.lat],[t.lng,t.lat],i.coordinates[0][0]],e.Commit))return;this.currentCoordinate++}else 2===this.currentCoordinate&&this.currentId&&this.close()}onKeyUp(t){if(t.key===this.keyEvents.cancel)this.cleanUp();else if(t.key===this.keyEvents.finish){if(this.currentCoordinate<2)return void this.cleanUp();this.close()}}onKeyDown(){}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentId&&this.store.delete([this.currentId])}catch(t){}this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted()}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return e.properties.mode===this.mode&&"Polygon"===e.geometry.type&&(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r),i}validateFeature(t){return this.validateModeFeature(t,t=>G(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentId===t.id&&(this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted())}}function We(t,e,i){return(e.x-t.x)*(i.y-t.y)-(e.y-t.y)*(i.x-t.x)<=0}const je={cancel:"Escape",finish:"Enter"},Be={start:"crosshair",close:"pointer"};class Ge extends p{constructor(t){super(t,!0),this.mode="sector",this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=je,this.direction=void 0,this.arcPoints=64,this.cursors=Be,this.mouseMove=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.arcPoints&&(this.arcPoints=e.arcPoints)}close(){if(void 0===this.currentId)return;const t=V(this.store.getGeometryCopy(this.currentId));t&&this.store.updateGeometry([{id:this.currentId,geometry:t}]),this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}]);const e=this.currentId;this.currentCoordinate=0,this.currentId=void 0,this.direction=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){if(this.mouseMove=!0,this.setCursor(this.cursors.start),void 0===this.currentId||0===this.currentCoordinate)return;const i=this.store.getGeometryCopy(this.currentId).coordinates[0];let o;if(1===this.currentCoordinate){const e=1/Math.pow(10,this.coordinatePrecision-1),s=Math.max(1e-6,e);o=[i[0],[t.lng,t.lat],[t.lng,t.lat-s],i[0]]}else if(2===this.currentCoordinate){const e=i[0],s=i[1],r=[t.lng,t.lat],n=S(e[0],e[1]),a=S(s[0],s[1]),d=S(r[0],r[1]);if(void 0===this.direction){const t=We(n,a,d);this.direction=t?"clockwise":"anticlockwise"}const h=A(n,a),l=et(n,a),c=et(n,d),u=this.arcPoints,p=[e],g=it(l),y=it(c);let f;"anticlockwise"===this.direction?(f=y-g,f<0&&(f+=360)):(f=g-y,f<0&&(f+=360));const m=("anticlockwise"===this.direction?1:-1)*f/u;p.push(s);for(let t=0;t<=u;t++){const e=Q(n,h,g+t*m),{lng:i,lat:o}=M(e.x,e.y),s=[P(i,this.coordinatePrecision),P(o,this.coordinatePrecision)];s[0]!==p[p.length-1][0]&&s[1]!==p[p.length-1][1]&&p.push(s)}p.push(e),o=[...p]}o&&this.updatePolygonGeometry(this.currentId,o,e.Provisional)}updatePolygonGeometry(t,e,i){const o={type:"Polygon",coordinates:[e]};return!(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}).valid||(this.store.updateGeometry([{id:t,geometry:o}]),0))}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))if(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,0===this.currentCoordinate){const[e]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}}]);this.currentId=e,this.currentCoordinate++,this.setDrawing()}else if(1===this.currentCoordinate&&this.currentId){const i=this.store.getGeometryCopy(this.currentId);if(at([t.lng,t.lat],i.coordinates[0][0]))return;if(!this.updatePolygonGeometry(this.currentId,[i.coordinates[0][0],[t.lng,t.lat],[t.lng,t.lat],i.coordinates[0][0]],e.Commit))return;this.currentCoordinate++}else 2===this.currentCoordinate&&this.currentId&&this.close()}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentId&&this.store.delete([this.currentId])}catch(t){}this.currentId=void 0,this.direction=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted()}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return e.properties.mode===this.mode&&"Polygon"===e.geometry.type&&(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r),i}validateFeature(t){return this.validateModeFeature(t,t=>G(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentId===t.id&&(this.currentId=void 0,this.direction=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted())}}const Re={cancel:"Escape",finish:"Enter"},Ue={start:"crosshair",close:"pointer"};class Le extends p{constructor(t){super(t,!0),this.mode="sensor",this.currentCoordinate=0,this.currentId=void 0,this.currentInitialArcId=void 0,this.currentStartingPointId=void 0,this.keyEvents=Re,this.direction=void 0,this.arcPoints=64,this.cursors=Ue,this.mouseMove=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.arcPoints&&(this.arcPoints=e.arcPoints)}close(){if(void 0===this.currentStartingPointId)return;const t=this.currentStartingPointId,e=this.currentInitialArcId,i=this.currentId;if(t&&this.store.delete([t]),e&&this.store.delete([e]),this.currentId){const t=V(this.store.getGeometryCopy(this.currentId));t&&this.store.updateGeometry([{id:this.currentId,geometry:t}]),this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}])}this.currentCoordinate=0,this.currentStartingPointId=void 0,this.currentInitialArcId=void 0,this.currentId=void 0,this.direction=void 0,"drawing"===this.state&&this.setStarted(),i&&this.onFinish(i,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){if(this.mouseMove=!0,this.setCursor(this.cursors.start),void 0!==this.currentInitialArcId&&void 0!==this.currentStartingPointId&&0!==this.currentCoordinate)if(2===this.currentCoordinate){const i=this.store.getGeometryCopy(this.currentInitialArcId).coordinates,o=this.store.getGeometryCopy(this.currentStartingPointId).coordinates,s=i[0],r=[t.lng,t.lat],n=S(s[0],s[1]),a=S(r[0],r[1]),d=S(o[0],o[1]),h=A(d,n);if(void 0===this.direction){const t=We(d,n,a);this.direction=t?"clockwise":"anticlockwise"}const l=et(d,n),c=et(d,a),u=this.arcPoints,p=[s],g=it(l),y=it(c);let f;"anticlockwise"===this.direction?(f=y-g,f<0&&(f+=360)):(f=g-y,f<0&&(f+=360));const m=("anticlockwise"===this.direction?1:-1)*f/u;for(let t=0;t<=u;t++){const e=Q(d,h,g+t*m),{lng:i,lat:o}=M(e.x,e.y),s=[P(i,this.coordinatePrecision),P(o,this.coordinatePrecision)];s[0]!==p[p.length-1][0]&&s[1]!==p[p.length-1][1]&&p.push(s)}this.updateLineStringGeometry(this.currentInitialArcId,p,e.Provisional)}else if(3===this.currentCoordinate){const i=this.store.getGeometryCopy(this.currentInitialArcId).coordinates;if(i.length<2)return;if(!this.direction)return;const o=this.store.getGeometryCopy(this.currentStartingPointId).coordinates,r=i[0],n=i[i.length-1],a=S(t.lng,t.lat),d=S(r[0],r[1]),h=S(n[0],n[1]),l=S(o[0],o[1]),c=A(l,d),u=A(l,a)<c?d:a,p=et(l,a),g=et(l,d),y=et(l,h),f=it(g),m=it(y),v=it(p);if(this.notInSector({normalizedCursor:v,normalizedStart:f,normalizedEnd:m,direction:this.direction}))return;const C=this.getDeltaBearing(this.direction,f,m),I=this.arcPoints,x=("anticlockwise"===this.direction?1:-1)*C/I,E=A(l,u),F=[];for(let t=0;t<=I;t++){const e=Q(l,E,f+t*x),{lng:o,lat:s}=M(e.x,e.y),r=[P(o,this.coordinatePrecision),P(s,this.coordinatePrecision)];r[0]!==i[i.length-1][0]&&r[1]!==i[i.length-1][1]&&F.unshift(r)}i.push(...F),i.push(i[0]),this.currentId?this.updatePolygonGeometry(this.currentId,i,e.Provisional):[this.currentId]=this.store.create([{geometry:{type:"Polygon",coordinates:[i]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}}])}}updateLineStringGeometry(t,e,i){const o={type:"LineString",coordinates:e};return!(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}).valid||(this.store.updateGeometry([{id:t,geometry:o}]),0))}updatePolygonGeometry(t,e,i){const o={type:"Polygon",coordinates:[e]};return!(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}).valid||(this.store.updateGeometry([{id:t,geometry:o}]),0))}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))if(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,0===this.currentCoordinate){const[e]=this.store.create([{geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:{mode:this.mode}}]);this.currentStartingPointId=e,this.currentCoordinate++,this.setDrawing()}else if(1===this.currentCoordinate&&this.currentStartingPointId){const[e]=this.store.create([{geometry:{type:"LineString",coordinates:[[t.lng,t.lat],[t.lng,t.lat]]},properties:{mode:this.mode}}]);this.currentInitialArcId=e,this.currentCoordinate++}else 2===this.currentCoordinate&&this.currentStartingPointId?this.currentCoordinate++:3===this.currentCoordinate&&this.currentStartingPointId&&this.close()}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentStartingPointId&&this.store.delete([this.currentStartingPointId]),this.currentInitialArcId&&this.store.delete([this.currentInitialArcId]),this.currentId&&this.store.delete([this.currentId])}catch(t){}this.currentStartingPointId=void 0,this.direction=void 0,this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted()}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return e.properties.mode===this.mode&&("Polygon"===e.geometry.type?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r):"LineString"===e.geometry.type?(i.lineStringColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.zIndex=r):"Point"===e.geometry.type&&(i.pointColor=this.getHexColorStylingValue(this.styles.centerPointColor,i.pointColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.centerPointWidth,i.pointWidth,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.centerPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.centerPointOutlineWidth,i.pointOutlineWidth,e),i.zIndex=20)),i}validateFeature(t){return this.validateModeFeature(t,t=>G(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentId===t.id&&(this.currentStartingPointId&&this.store.delete([this.currentStartingPointId]),this.currentInitialArcId&&this.store.delete([this.currentInitialArcId]),this.currentStartingPointId=void 0,this.direction=void 0,this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted())}getDeltaBearing(t,e,i){let o;return"anticlockwise"===t?(o=i-e,o<0&&(o+=360)):(o=e-i,o<0&&(o+=360)),o}notInSector({normalizedCursor:t,normalizedStart:e,normalizedEnd:i,direction:o}){return"clockwise"===o?e<=i?t>=e&&t<=i:t>=e||t<=i:e>=i?t<=e&&t>=i:t<=e||t>=i}}class Ae{constructor({name:t,callback:e,unregister:i,register:o}){this.name=void 0,this.callback=void 0,this.registered=!1,this.register=void 0,this.unregister=void 0,this.name=t,this.register=()=>{this.registered||(this.registered=!0,o(e))},this.unregister=()=>{this.register&&(this.registered=!1,i(e))},this.callback=e}}var Ve={__proto__:null,GeoJSONStore:Pe,TerraDrawBaseDrawMode:p,TerraDrawBaseSelectMode:g,TerraDrawBaseAdapter:class{constructor(t){this._nextKeyUpIsContextMenu=!1,this._lastPointerDownEventTarget=void 0,this._ignoreMismatchedPointerEvents=!1,this._minPixelDragDistance=void 0,this._minPixelDragDistanceDrawing=void 0,this._minPixelDragDistanceSelecting=void 0,this._lastDrawEvent=void 0,this._coordinatePrecision=void 0,this._heldKeys=new Set,this._listeners=[],this._dragState="not-dragging",this._currentModeCallbacks=void 0,this._ignoreMismatchedPointerEvents="boolean"==typeof t.ignoreMismatchedPointerEvents&&t.ignoreMismatchedPointerEvents,this._minPixelDragDistance="number"==typeof t.minPixelDragDistance?t.minPixelDragDistance:1,this._minPixelDragDistanceSelecting="number"==typeof t.minPixelDragDistanceSelecting?t.minPixelDragDistanceSelecting:1,this._minPixelDragDistanceDrawing="number"==typeof t.minPixelDragDistanceDrawing?t.minPixelDragDistanceDrawing:8,this._coordinatePrecision="number"==typeof t.coordinatePrecision?t.coordinatePrecision:9}getButton(t){return-1===t.button?"neither":0===t.button?"left":1===t.button?"middle":2===t.button?"right":"neither"}getMapElementXYPosition(t){const e=this.getMapEventElement(),{left:i,top:o}=e.getBoundingClientRect();return{containerX:t.clientX-i,containerY:t.clientY-o}}getDrawEventFromEvent(t,e=!1){const i=this.getLngLatFromEvent(t);if(!i)return null;const{lng:o,lat:s}=i,{containerX:r,containerY:n}=this.getMapElementXYPosition(t),a=this.getButton(t),d=Array.from(this._heldKeys);return{lng:P(o,this._coordinatePrecision),lat:P(s,this._coordinatePrecision),containerX:r,containerY:n,button:a,heldKeys:d,isContextMenu:e}}register(t){this._currentModeCallbacks=t,this._listeners=this.getAdapterListeners(),this._listeners.forEach(t=>{t.register()})}getCoordinatePrecision(){return this._coordinatePrecision}getAdapterListeners(){return[new Ae({name:"pointerdown",callback:t=>{if(!this._currentModeCallbacks)return;if(!t.isPrimary)return;const e=this.getDrawEventFromEvent(t);e&&(this._dragState="pre-dragging",this._lastDrawEvent=e,this._lastPointerDownEventTarget=t.target?t.target:void 0)},register:t=>{this.getMapEventElement().addEventListener("pointerdown",t)},unregister:t=>{this.getMapEventElement().removeEventListener("pointerdown",t)}}),new Ae({name:"pointermove",callback:t=>{if(!this._currentModeCallbacks)return;if(!t.isPrimary)return;t.preventDefault();const e=this.getDrawEventFromEvent(t);if(e)if("not-dragging"===this._dragState)this._currentModeCallbacks.onMouseMove(e),this._lastDrawEvent=e;else if("pre-dragging"===this._dragState){if(!this._lastDrawEvent)return;const t={x:this._lastDrawEvent.containerX,y:this._lastDrawEvent.containerY},i={x:e.containerX,y:e.containerY},o=this._currentModeCallbacks.getState(),s=A(t,i);let r=!1;if(r="drawing"===o?s<this._minPixelDragDistanceDrawing:"selecting"===o?s<this._minPixelDragDistanceSelecting:s<this._minPixelDragDistance,r)return;this._nextKeyUpIsContextMenu=!1,this._dragState="dragging",this._currentModeCallbacks.onDragStart(e,t=>{this.setDraggability.bind(this)(t)})}else"dragging"===this._dragState&&this._currentModeCallbacks.onDrag(e,t=>{this.setDraggability.bind(this)(t)})},register:t=>{this.getMapEventElement().addEventListener("pointermove",t)},unregister:t=>{this.getMapEventElement().removeEventListener("pointermove",t)}}),new Ae({name:"contextmenu",callback:t=>{this._currentModeCallbacks&&(t.preventDefault(),this._nextKeyUpIsContextMenu=!0)},register:t=>{this.getMapEventElement().addEventListener("contextmenu",t)},unregister:t=>{this.getMapEventElement().removeEventListener("contextmenu",t)}}),new Ae({name:"pointerup",callback:t=>{if(!this._currentModeCallbacks)return;if(t.target!==this.getMapEventElement())return;if(this._ignoreMismatchedPointerEvents&&this._lastPointerDownEventTarget!==t.target)return;if(this._lastPointerDownEventTarget=void 0,!t.isPrimary)return;const e=this.getDrawEventFromEvent(t);e&&("dragging"===this._dragState?this._currentModeCallbacks.onDragEnd(e,t=>{this.setDraggability.bind(this)(t)}):"not-dragging"!==this._dragState&&"pre-dragging"!==this._dragState||(this._nextKeyUpIsContextMenu&&(e.isContextMenu=!0,this._nextKeyUpIsContextMenu=!1),this._currentModeCallbacks.onClick(e)),this._dragState="not-dragging",this.setDraggability(!0))},register:t=>{this.getMapEventElement().addEventListener("pointerup",t)},unregister:t=>{this.getMapEventElement().removeEventListener("pointerup",t)}}),new Ae({name:"keyup",callback:t=>{this._currentModeCallbacks&&(this._heldKeys.delete(t.key),this._currentModeCallbacks.onKeyUp({key:t.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>t.preventDefault()}))},register:t=>{this.getMapEventElement().addEventListener("keyup",t)},unregister:t=>{this.getMapEventElement().removeEventListener("keyup",t)}}),new Ae({name:"keydown",callback:t=>{this._currentModeCallbacks&&(this._heldKeys.add(t.key),this._currentModeCallbacks.onKeyDown({key:t.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>t.preventDefault()}))},register:t=>{this.getMapEventElement().addEventListener("keydown",t)},unregister:t=>{this.getMapEventElement().removeEventListener("keydown",t)}})]}unregister(){this._listeners.forEach(t=>{t.unregister()}),this.clear(),this._currentModeCallbacks=void 0,this._lastDrawEvent=void 0,this._lastPointerDownEventTarget=void 0,this._nextKeyUpIsContextMenu=!1}},getDefaultStyling:()=>({polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0}),SELECT_PROPERTIES:o};const Ye={ValidationReasonFeatureNotPoint:Ct,ValidationReasonFeatureInvalidCoordinates:Pt,ValidationReasonFeatureInvalidCoordinatePrecision:It,ValidationReasonFeatureNotPolygon:h,ValidationReasonFeatureHasHoles:N,ValidationReasonFeatureLessThanFourCoordinates:T,ValidationReasonFeatureHasInvalidCoordinates:W,ValidationReasonFeatureCoordinatesNotClosed:j,ValidationReasonFeatureNotPolygonOrLineString:we,ValidationReasonFeatureSelfIntersects:Oe,ValidationReasonFeatureLessThanMinSize:Me,ValidationReasonModeMismatch:l},Ke={cancel:"Escape",finish:"Enter"},ze={start:"crosshair",close:"pointer"};class He extends p{constructor(t){super(t,!0),this.mode="freehand-linestring",this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,this.minDistance=20,this.keyEvents=Ke,this.cursors=ze,this.preventNewFeature=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.minDistance&&(this.minDistance=e.minDistance),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors))}close(){if(void 0===this.currentId)return;this.currentId&&this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}]);const t=this.currentId;if(this.validate&&t){const i=this.store.getGeometryCopy(t);if(!this.validate({type:"Feature",id:t,geometry:i,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid)return}this.closingPointId&&this.store.delete([this.closingPointId]),this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(t,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){if(void 0===this.currentId||!1===this.startingClick)return void this.setCursor(this.cursors.start);const i=this.store.getGeometryCopy(this.currentId),o=i.coordinates.length-2,[s,r]=i.coordinates[o],{x:n,y:a}=this.project(s,r),d=A({x:n,y:a},{x:t.containerX,y:t.containerY}),[h,l]=i.coordinates[i.coordinates.length-1],{x:c,y:u}=this.project(h,l),p=A({x:c,y:u},{x:t.containerX,y:t.containerY});if(this.setCursor(p<this.pointerDistance?this.cursors.close:this.cursors.start),d<this.minDistance)return;const g={type:"LineString",coordinates:[...i.coordinates,[t.lng,t.lat]]};this.validate&&!this.validate({type:"Feature",id:this.currentId,geometry:g,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional}).valid||(this.store.updateGeometry([{id:this.currentId,geometry:g}]),this.closingPointId&&this.store.updateGeometry([{id:this.closingPointId,geometry:{type:"Point",coordinates:[t.lng,t.lat]}}]))}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)){if(this.preventNewFeature)return;if(!1===this.startingClick){const[e,i]=this.store.create([{geometry:{type:"LineString",coordinates:[[t.lng,t.lat],[t.lng,t.lat]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}},{geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:{mode:this.mode,[s.CLOSING_POINT]:!0}}]);return this.currentId=e,this.closingPointId=i,this.startingClick=!0,void("drawing"!==this.state&&this.setDrawing())}this.close()}}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&!0===this.startingClick&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentId,e=this.closingPointId;this.closingPointId=void 0,this.currentId=void 0,this.startingClick=!1,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]),void 0!==e&&this.store.delete([e])}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return"Feature"===e.type&&"LineString"===e.geometry.type&&e.properties.mode===this.mode?(i.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,i.lineStringColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,i.lineStringWidth,e),i.zIndex=r,i):"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode?(i.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),i.zIndex=50,i):i}validateFeature(t){return this.validateModeFeature(t,t=>dt(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentId===t.id&&(this.closingPointId&&this.store.delete([this.closingPointId]),this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0)}}function Xe(t){if(null===t)return!0;if("boolean"==typeof t)return!0;if("string"==typeof t)return!0;if(void 0===t)return!1;if("number"==typeof t)return Number.isFinite(t);if("bigint"==typeof t)return!1;if("symbol"==typeof t)return!1;if("function"==typeof t)return!1;if(t instanceof RegExp)return!1;if(t instanceof Map)return!1;if(t instanceof Set)return!1;if(t instanceof Date)return!1;if("object"==typeof t&&null!==t&&!Array.isArray(t)){const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&null!==e)return!1}if(ArrayBuffer.isView(t)&&!(t instanceof DataView))return!1;if(Array.isArray(t))for(const e of t)if(!Xe(e))return!1;return"object"==typeof t&&Object.keys(t).every(e=>"string"==typeof e&&Xe(t[e]))}const $e={create:"crosshair",dragStart:"grabbing",dragEnd:"crosshair"};class qe extends p{constructor(t){super(t,!0),this.mode="marker",this.cursors=$e,this.editable=!1,this.editedFeatureId=void 0,this.markerUrl=void 0,this.markerHeight=void 0,this.markerWidth=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null!=e&&e.editable&&(this.editable=e.editable)}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(t){"right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)?this.onRightClick(t):"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)&&this.onLeftClick(t)}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){this.editedFeatureId=void 0}onDragStart(t,e){if(this.allowPointerEvent(this.pointerEvents.onDragStart,t)){if(this.editable){const e=this.getNearestPointFeature(t);this.editedFeatureId=null==e?void 0:e.id}this.editedFeatureId&&(this.setCursor(this.cursors.dragStart),e(!1))}}onDrag(t,i){this.allowPointerEvent(this.pointerEvents.onDrag,t)&&void 0!==this.editedFeatureId&&(this.validate&&!this.validate({type:"Feature",geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:this.store.getPropertiesCopy(this.editedFeatureId)},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid||(this.store.updateGeometry([{id:this.editedFeatureId,geometry:{type:"Point",coordinates:[t.lng,t.lat]}}]),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!0}])))}onDragEnd(t,e){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&void 0!==this.editedFeatureId&&(this.onFinish(this.editedFeatureId,{mode:this.mode,action:"edit"}),this.setCursor(this.cursors.dragEnd),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!1}]),this.editedFeatureId=void 0,e(!0))}registerBehaviors(t){this.pixelDistance=new q(t),this.clickBoundingBox=new $(t)}styleFeature(e){const o=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});var s,r,n;return"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode&&(o.zIndex=30,o.markerHeight=this.getNumericStylingValue(null==(s=this.styles)?void 0:s.markerHeight,40,e),o.markerWidth=this.getNumericStylingValue(null==(r=this.styles)?void 0:r.markerWidth,32,e),o.markerUrl=this.getUrlStylingValue(null==(n=this.styles)?void 0:n.markerUrl,i,e)),o}validateFeature(t){return this.validateModeFeature(t,t=>xt(t,this.coordinatePrecision))}onLeftClick(t){const i={type:"Point",coordinates:[t.lng,t.lat]},o={mode:this.mode,[s.MARKER]:!0};if(this.validate&&!this.validate({type:"Feature",geometry:i,properties:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid)return;const[r]=this.store.create([{geometry:i,properties:o}]);this.onFinish(r,{mode:this.mode,action:"draw"})}onRightClick(t){if(!this.editable)return;const e=this.getNearestPointFeature(t);e&&this.store.delete([e.id])}getNearestPointFeature(t){const e=this.clickBoundingBox.create(t),i=this.store.search(e);let o,s=Infinity;for(let e=0;e<i.length;e++){const r=i[e];if("Point"!==r.geometry.type||r.properties.mode!==this.mode)continue;const n=this.pixelDistance.measure(t,r.geometry.coordinates);n>s||n>this.pointerDistance||(s=n,o=r)}return o}afterFeatureUpdated(t){this.editedFeatureId===t.id&&(this.editedFeatureId=void 0,this.setCursor(this.cursors.create))}}class Ze{constructor(e){this._modes=void 0,this._mode=void 0,this._adapter=void 0,this._enabled=!1,this._store=void 0,this._eventListeners=void 0,this._instanceSelectMode=void 0,this._adapter=e.adapter,this._mode=new ie;const i=new Set,o=e.modes.reduce((t,e)=>{if(i.has(e.mode))throw new Error(`There is already a ${e.mode} mode provided`);return i.add(e.mode),t[e.mode]=e,t},{}),s=Object.keys(o);if(0===s.length)throw new Error("No modes provided");s.forEach(t=>{if(o[t].type===c.Select){if(this._instanceSelectMode)throw new Error("only one type of select mode can be provided");this._instanceSelectMode=t}}),this._modes=t({},o,{static:this._mode}),this._eventListeners={change:[],select:[],deselect:[],finish:[],ready:[]},this._store=new Pe({tracked:!!e.tracked,idStrategy:e.idStrategy?e.idStrategy:void 0});const r=t=>{const e=[],i=this._store.copyAll().filter(i=>!t.includes(i.id)||(e.push(i),!1));return{changed:e,unchanged:i}},n=(t,e)=>{this._enabled&&this._eventListeners.finish.forEach(i=>{i(t,e)})},a=(t,e,i)=>{if(!this._enabled)return;this._eventListeners.change.forEach(o=>{o(t,e,i)});const{changed:o,unchanged:s}=r(t);"create"===e?this._adapter.render({created:o,deletedIds:[],unchanged:s,updated:[]},this.getModeStyles()):"update"===e?this._adapter.render({created:[],deletedIds:[],unchanged:s,updated:o},this.getModeStyles()):"delete"===e?this._adapter.render({created:[],deletedIds:t,unchanged:s,updated:[]},this.getModeStyles()):"styling"===e&&this._adapter.render({created:[],deletedIds:[],unchanged:s,updated:[]},this.getModeStyles())},d=t=>{if(!this._enabled)return;this._eventListeners.select.forEach(e=>{e(t)});const{changed:e,unchanged:i}=r([t]);this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:e},this.getModeStyles())},h=t=>{if(!this._enabled)return;this._eventListeners.deselect.forEach(t=>{t()});const{changed:e,unchanged:i}=r([t]);e&&this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:e},this.getModeStyles())};Object.keys(this._modes).forEach(t=>{this._modes[t].register({mode:t,store:this._store,setCursor:this._adapter.setCursor.bind(this._adapter),project:this._adapter.project.bind(this._adapter),unproject:this._adapter.unproject.bind(this._adapter),setDoubleClickToZoom:this._adapter.setDoubleClickToZoom.bind(this._adapter),onChange:a,onSelect:d,onDeselect:h,onFinish:n,coordinatePrecision:this._adapter.getCoordinatePrecision()})})}checkEnabled(){if(!this._enabled)throw new Error("Terra Draw is not enabled")}getModeStyles(){const t={};return Object.keys(this._modes).forEach(e=>{t[e]=t=>this._instanceSelectMode&&t.properties[o.SELECTED]?this._modes[this._instanceSelectMode].styleFeature.bind(this._modes[this._instanceSelectMode])(t):this._modes[e].styleFeature.bind(this._modes[e])(t)}),t}featuresAtLocation({lng:t,lat:e},i){const r=i&&void 0!==i.pointerDistance?i.pointerDistance:30,n=!i||void 0===i.ignoreSelectFeatures||i.ignoreSelectFeatures,a=!(!i||void 0===i.ignoreCoordinatePoints)&&i.ignoreCoordinatePoints,d=!(!i||void 0===i.ignoreCurrentlyDrawing)&&i.ignoreCurrentlyDrawing,h=!(!i||void 0===i.ignoreClosingPoints)&&i.ignoreClosingPoints,l=!(!i||void 0===i.ignoreSnappingPoints)&&i.ignoreSnappingPoints,c=this._adapter.unproject.bind(this._adapter),u=this._adapter.project.bind(this._adapter),p=u(t,e),g=X({unproject:c,point:p,pointerDistance:r});return this._store.search(g).filter(c=>{if(n&&(c.properties[o.MID_POINT]||c.properties[o.SELECTION_POINT]))return!1;if(a&&c.properties[s.COORDINATE_POINT])return!1;if(h&&c.properties[s.CLOSING_POINT])return!1;if(d&&c.properties[s.CURRENTLY_DRAWING])return!1;if(l&&c.properties[s.SNAPPING_POINT])return!1;if("Point"===c.geometry.type){const t=c.geometry.coordinates,e=u(t[0],t[1]);return A(p,e)<r}if("LineString"===c.geometry.type){const t=c.geometry.coordinates;for(let e=0;e<t.length-1;e++){const i=t[e],o=t[e+1];if(At(p,u(i[0],i[1]),u(o[0],o[1]))<r)return!0}return!1}if(Lt([t,e],c.geometry.coordinates))return!0;if(null!=i&&i.includePolygonsWithinPointerDistance){const t=c.geometry.coordinates;for(const e of t)for(let t=0;t<e.length-1;t++){const i=e[t],o=e[t+1],s=u(i[0],i[1]),n=u(o[0],o[1]);if(At(p,s,n)<r)return!0}}return!1}).map(o=>{if(null==i||!i.addClosestCoordinateInfoToProperties)return o;let s;if("Polygon"===o.geometry.type)s=o.geometry.coordinates[0].slice(0,-1);else{if("LineString"!==o.geometry.type)return o;s=o.geometry.coordinates}let r,n=-1,a=Infinity;for(let t=0;t<s.length;t++){const e=s[t],i=A(u(e[0],e[1]),p);i<a&&(n=t,a=i,r=e)}return o.properties.closestCoordinateIndexToEvent=n,o.properties.closestCoordinatePixelDistanceToEvent=a,o.properties.closestCoordinateDistanceKmToEvent=y(r,[t,e]),o})}getSelectModeOrThrow(){const t=this.getSelectMode({switchToSelectMode:!0});if(!t)throw new Error("No select mode defined in instance");return t}getSelectMode({switchToSelectMode:t}){if(this.checkEnabled(),!this._instanceSelectMode)return null;const e=this.getMode();return t&&e!==this._instanceSelectMode&&this.setMode(this._instanceSelectMode),this._modes[this._instanceSelectMode]}isGuidanceFeature(t){return Boolean(t.properties[o.MID_POINT]||t.properties[o.SELECTION_POINT]||t.properties[s.COORDINATE_POINT]||t.properties[s.SNAPPING_POINT])}setModeStyles(t,e){if(this.checkEnabled(),!this._modes[t])throw new Error("No mode with this name present");this._modes[t].styles=e}updateModeOptions(t,e){if(this.checkEnabled(),!this._modes[t])throw new Error("No mode with this name present");this._modes[t].updateOptions(e)}getSnapshot(){return this._store.copyAll()}getSnapshotFeature(t){if(this._store.has(t))return this._store.copy(t)}clear(){this.checkEnabled(),this._adapter.clear()}get enabled(){return this._enabled}set enabled(t){throw new Error("Enabled is read only")}getMode(){return this._mode.mode}getModeState(){return this._mode.state}setMode(t){if(this.checkEnabled(),!this._modes[t])throw new Error("No mode with this name present");this._mode.stop(),this._mode=this._modes[t],this._mode.start()}removeFeatures(t){this.checkEnabled();const e=[];t.forEach(t=>{if(!this._store.has(t))throw new Error(`No feature with id ${t}, can not delete`);const i=this._store.copy(t);i.properties[o.SELECTED]&&this.deselectFeature(t),i.properties[s.COORDINATE_POINT_IDS]&&e.push(...i.properties[s.COORDINATE_POINT_IDS])}),this._store.delete([...t,...e],{origin:"api"})}selectFeature(t){this.getSelectModeOrThrow().selectFeature(t)}deselectFeature(t){this.getSelectModeOrThrow().deselectFeature(t)}getFeatureId(){return this._store.getId()}hasFeature(t){return this._store.has(t)}checkIsReservedProperty(t){return![...Object.values(o),...Object.values(s)].includes(t)}updateFeatureProperties(t,e){if(!this._store.has(t))throw new Error(`No feature with id ${t} present in store`);const i=this._store.copy(t);if(this.isGuidanceFeature(i))throw new Error("Guidance features are not allowed to be updated directly.");const o=i.properties.mode;if(!this._modes[o])throw new Error(`No mode with name ${o} present in instance`);const s=Object.entries(e);s.forEach(([t,e])=>{if(!this.checkIsReservedProperty(t))throw new Error(`You are trying to update a reserved property name: ${t}. Please choose another name.`);if(void 0!==e&&!Xe(e))throw new Error(`Invalid JSON value provided for property ${t}`)}),this._store.updateProperty(s.map(([t,e])=>({id:i.id,property:t,value:e})),{origin:"api"})}updateFeatureGeometry(e,i){if(!this._store.has(e))throw new Error(`No feature with id ${e} present in store`);const s=this._store.copy(e);if(this.isGuidanceFeature(s))throw new Error("Guidance features are not allowed to be updated directly.");if(!(s&&i&&i.type&&i.coordinates))throw new Error("Invalid geometry provided");if(i.type!==s.geometry.type)throw new Error(`Geometry type mismatch: expected ${s.geometry.type}, got ${i.type}`);const r=s.properties.mode,n=this._modes[r];if(!n)throw new Error(`No mode with name ${r} present in instance`);const a=t({},s,{geometry:i}),d=n.validateFeature(a);if(!d.valid)throw new Error(`Feature validation failed: ${d.reason||"Unknown reason"}`);if(this._store.updateGeometry([{id:s.id,geometry:i}],{origin:"api"}),n.afterFeatureUpdated){n.afterFeatureUpdated(a);const t=a.properties[o.SELECTED],e=this.getSelectMode({switchToSelectMode:!1});e&&t&&e.afterFeatureUpdated(a)}}transformFeatureGeometry(t,e){if(!this._store.has(t))throw new Error(`No feature with id ${t} present in store`);let i=this._store.copy(t);if(this.isGuidanceFeature(i))throw new Error("Guidance features are not allowed to be updated directly.");const s=i.properties.mode,r=this._modes[s];if(!r)throw new Error(`No mode with name ${s} present in instance`);let n;if("Polygon"===i.geometry.type)n=i.geometry.coordinates[0];else{if("LineString"!==i.geometry.type)throw new Error(`Feature geometry type ${i.geometry.type} is not supported for transformation`);n=i.geometry.coordinates}if("web-mercator"!=e.projection)throw new Error(`Projection ${e.projection} is not currently supported for transformation`);if("scale"===e.type){const{x:t,y:i}=S(e.origin[0],e.origin[1]);Zt({coordinates:n,originX:t,originY:i,xScale:e.options.xScale||1,yScale:e.options.yScale||1})}else"rotate"===e.type&&(i=Ht(i,e.options.angle||0),n="Polygon"===i.geometry.type?i.geometry.coordinates[0]:i.geometry.coordinates);if(n=n.map(t=>[P(t[0],this._adapter.getCoordinatePrecision()),P(t[1],this._adapter.getCoordinatePrecision())]),i.geometry.coordinates="Polygon"===i.geometry.type?[n]:n,this._store.updateGeometry([{id:i.id,geometry:i.geometry}],{origin:"api"}),r.afterFeatureUpdated){r.afterFeatureUpdated(i);const t=i.properties[o.SELECTED],e=this.getSelectMode({switchToSelectMode:!1});e&&t&&e.afterFeatureUpdated(i)}}addFeatures(t){return this.checkEnabled(),0===t.length?[]:this._store.load(t,t=>{if(a(t)){const e=t.properties.mode,i=this._modes[e];if(!i)return{id:t.id,valid:!1,reason:`${e} mode is not in the list of instantiated modes`};const o=i.validateFeature.bind(i)(t);return{id:t.id,valid:o.valid,reason:o.reason?o.reason:o.valid?void 0:"Feature is invalid"}}return{id:t.id,valid:!1,reason:"Mode property does not exist"}},t=>{if(a(t)){const e=this._modes[t.properties.mode];e&&e.afterFeatureAdded&&e.afterFeatureAdded(t)}},{origin:"api"})}start(){this._enabled||(this._enabled=!0,this._adapter.register({onReady:()=>{this._eventListeners.ready.forEach(t=>{t()})},getState:()=>this._mode.state,onClick:t=>{this._mode.onClick(t)},onMouseMove:t=>{this._mode.onMouseMove(t)},onKeyDown:t=>{this._mode.onKeyDown(t)},onKeyUp:t=>{this._mode.onKeyUp(t)},onDragStart:(t,e)=>{this._mode.onDragStart(t,e)},onDrag:(t,e)=>{this._mode.onDrag(t,e)},onDragEnd:(t,e)=>{this._mode.onDragEnd(t,e)},onClear:()=>{this._mode.cleanUp(),this._store.clear()}}))}getFeaturesAtLngLat(t,e){const{lng:i,lat:o}=t;return this.featuresAtLocation({lng:i,lat:o},e)}getFeaturesAtPointerEvent(t,e){const i=this._adapter.getLngLatFromEvent.bind(this._adapter)(t);return null===i?[]:this.featuresAtLocation(i,e)}stop(){this._enabled&&(this._enabled=!1,this._adapter.unregister())}on(t,e){const i=this._eventListeners[t];i.includes(e)||i.push(e)}off(t,e){const i=this._eventListeners[t];i.includes(e)&&i.splice(i.indexOf(e),1)}}export{Ze as TerraDraw,Te as TerraDrawAngledRectangleMode,L as TerraDrawCircleMode,Ve as TerraDrawExtend,He as TerraDrawFreehandLineStringMode,z as TerraDrawFreehandMode,vt as TerraDrawLineStringMode,qe as TerraDrawMarkerMode,St as TerraDrawPointMode,Ot as TerraDrawPolygonMode,bt as TerraDrawRectangleMode,Nt as TerraDrawRenderMode,Ge as TerraDrawSectorMode,ee as TerraDrawSelectMode,Le as TerraDrawSensorMode,De as ValidateMaxAreaSquareMeters,Fe as ValidateMinAreaSquareMeters,ke as ValidateNotSelfIntersecting,Ye as ValidationReasons};
1
+ function t(){return t=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var o in i)({}).hasOwnProperty.call(i,o)&&(t[o]=i[o])}return t},t.apply(null,arguments)}var e;!function(t){t.Commit="commit",t.Provisional="provisional",t.Finish="finish"}(e||(e={}));const i="https://raw.githubusercontent.com/JamesLMilner/terra-draw/refs/heads/main/assets/markers/marker-blue.png",o={SELECTED:"selected",MID_POINT:"midPoint",SELECTION_POINT_FEATURE_ID:"selectionPointFeatureId",SELECTION_POINT:"selectionPoint"},s={MODE:"mode",CURRENTLY_DRAWING:"currentlyDrawing",EDITED:"edited",CLOSING_POINT:"closingPoint",SNAPPING_POINT:"snappingPoint",COORDINATE_POINT:"coordinatePoint",COORDINATE_POINT_FEATURE_ID:"coordinatePointFeatureId",COORDINATE_POINT_IDS:"coordinatePointIds",PROVISIONAL_COORDINATE_COUNT:"provisionalCoordinateCount",COMMITTED_COORDINATE_COUNT:"committedCoordinateCount",MARKER:"marker"},r=10;function n(t){return Boolean(t&&"object"==typeof t&&null!==t&&!Array.isArray(t))}function a(t){return Boolean(t&&"object"==typeof t&&"properties"in t&&"object"==typeof t.properties&&null!==t.properties&&"mode"in t.properties)}function d(t){return!!function(t){return"number"==typeof t&&!isNaN(new Date(t).valueOf())}(t)}const h="Feature is not a Polygon",l="Feature mode property does not match the mode being added to";var c;!function(t){t.Drawing="drawing",t.Select="select",t.Static="static",t.Render="render"}(c||(c={}));const u={rightClick:!0,contextMenu:!1,leftClick:!0,onDragStart:!0,onDrag:!0,onDragEnd:!0};class p{get state(){return this._state}set state(t){throw new Error("Please use the modes lifecycle methods")}get styles(){return this._styles}set styles(t){if("object"!=typeof t)throw new Error("Styling must be an object");this.onStyleChange&&this.onStyleChange([],"styling"),this._styles=t}registerBehaviors(t){}constructor(e,i=!1){this._state="unregistered",this._styles={},this.pointerEvents=u,this.behaviors=[],this.validate=void 0,this.pointerDistance=40,this.coordinatePrecision=void 0,this.onStyleChange=void 0,this.store=void 0,this.projection="web-mercator",this.setDoubleClickToZoom=void 0,this.unproject=void 0,this.project=void 0,this.setCursor=void 0,this.isInitialUpdate=!1,this.type=c.Drawing,this.mode="base",i?this.isInitialUpdate=!0:this.updateOptions(t({},e))}updateOptions(e){null!=e&&e.styles&&(this.styles=t({},this._styles,e.styles)),null!=e&&e.pointerDistance&&(this.pointerDistance=e.pointerDistance),null!=e&&e.validation&&(this.validate=e&&e.validation),null!=e&&e.projection&&(this.projection=e.projection),void 0!==(null==e?void 0:e.pointerEvents)&&(this.pointerEvents=e.pointerEvents),null!=e&&e.modeName&&!0===this.isInitialUpdate&&(this.mode=e.modeName),this.isInitialUpdate=!1}allowPointerEvent(t,e){return"boolean"==typeof t?t:"function"!=typeof t||t(e)}setDrawing(){if("started"!==this._state)throw new Error("Mode must be unregistered or stopped to start");this._state="drawing"}setStarted(){if("stopped"!==this._state&&"registered"!==this._state&&"drawing"!==this._state&&"selecting"!==this._state)throw new Error("Mode must be unregistered or stopped to start");this._state="started",this.setDoubleClickToZoom(!1)}setStopped(){if("started"!==this._state)throw new Error("Mode must be started to be stopped");this._state="stopped",this.setDoubleClickToZoom(!0)}register(t){if("unregistered"!==this._state)throw new Error("Can not register unless mode is unregistered");this._state="registered",this.store=t.store,this.store.registerOnChange(t.onChange),this.setDoubleClickToZoom=t.setDoubleClickToZoom,this.project=t.project,this.unproject=t.unproject,this.onSelect=t.onSelect,this.onDeselect=t.onDeselect,this.setCursor=t.setCursor,this.onStyleChange=t.onChange,this.onFinish=t.onFinish,this.coordinatePrecision=t.coordinatePrecision,this.registerBehaviors({mode:t.mode,store:this.store,project:this.project,unproject:this.unproject,pointerDistance:this.pointerDistance,coordinatePrecision:t.coordinatePrecision,projection:this.projection})}validateFeature(t){return this.performFeatureValidation(t)}afterFeatureAdded(t){}afterFeatureUpdated(t){}performFeatureValidation(t){if("unregistered"===this._state)throw new Error("Mode must be registered");const i=function(t,e){let i;if(n(t))if(null==t.id)i="Feature has no id";else if("string"!=typeof t.id&&"number"!=typeof t.id)i="Feature must be string or number as per GeoJSON spec";else if(e(t.id))if(n(t.geometry))if(n(t.properties))if("string"==typeof t.geometry.type&&["Polygon","LineString","Point"].includes(t.geometry.type))if(Array.isArray(t.geometry.coordinates)){if(!t.properties.mode||"string"!=typeof t.properties.mode)return{valid:!1,reason:"Feature does not have a valid mode property"}}else i="Feature coordinates is not an array";else i="Feature is not Point, LineString or Polygon";else i="Feature has no properties";else i="Feature has no geometry";else i="Feature must match the id strategy (default is UUID4)";else i="Feature is not object";return i?{valid:!1,reason:i}:{valid:!0}}(t,this.store.idStrategy.isValidId);if(this.validate){const o=this.validate(t,{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional});return{valid:i.valid&&o.valid,reason:o.reason}}return{valid:i.valid,reason:i.reason}}validateModeFeature(t,e){const i=this.performFeatureValidation(t);return i.valid?t.properties.mode!==this.mode?{valid:!1,reason:l}:e(t):{valid:!1,reason:i.reason}}onFinish(t,e){}onDeselect(t){}onSelect(t){}onKeyDown(t){}onKeyUp(t){}onMouseMove(t){}onClick(t){}onDragStart(t,e){}onDrag(t,e){}onDragEnd(t,e){}getHexColorStylingValue(t,e,i){return this.getStylingValue(t,e,i)}getNumericStylingValue(t,e,i){return this.getStylingValue(t,e,i)}getUrlStylingValue(t,e,i){return this.getStylingValue(t,e,i)}getStylingValue(t,e,i){return void 0===t?e:"function"==typeof t?t(i):t}}class g extends p{constructor(...t){super(...t),this.type=c.Select}}function y(t,e){const i=t=>t*Math.PI/180,o=i(t[1]),s=i(t[0]),r=i(e[1]),n=r-o,a=i(e[0])-s,d=Math.sin(n/2)*Math.sin(n/2)+Math.cos(o)*Math.cos(r)*Math.sin(a/2)*Math.sin(a/2);return 2*Math.atan2(Math.sqrt(d),Math.sqrt(1-d))*6371e3/1e3}const m=6371008.8;function f(t){return t%360*Math.PI/180}function v(t){return t/6371.0088}function C(t){return t%(2*Math.PI)*180/Math.PI}function P(t,e=9){const i=Math.pow(10,e);return Math.round(t*i)/i}const I=57.29577951308232,x=.017453292519943295,E=6378137,S=(t,e)=>({x:0===t?0:t*x*E,y:0===e?0:Math.log(Math.tan(Math.PI/4+e*x/2))*E}),M=(t,e)=>({lng:0===t?0:I*(t/E),lat:0===e?0:(2*Math.atan(Math.exp(e/E))-Math.PI/2)*I});function w(t,e,i){const o=f(t[0]),s=f(t[1]),r=f(i),n=v(e),a=Math.asin(Math.sin(s)*Math.cos(n)+Math.cos(s)*Math.sin(n)*Math.cos(r));return[C(o+Math.atan2(Math.sin(r)*Math.sin(n)*Math.cos(s),Math.cos(n)-Math.sin(s)*Math.sin(a))),C(a)]}function F(t){const{center:e,radiusKilometers:i,coordinatePrecision:o}=t,s=t.steps?t.steps:64,r=[];for(let t=0;t<s;t++){const n=w(e,i,-360*t/s);r.push([P(n[0],o),P(n[1],o)])}return r.push(r[0]),{type:"Feature",geometry:{type:"Polygon",coordinates:[r]},properties:{}}}function D(t){let e;if("Polygon"===t.geometry.type)e=t.geometry.coordinates;else{if("LineString"!==t.geometry.type)throw new Error("Self intersects only accepts Polygons and LineStrings");e=[t.geometry.coordinates]}const i=[];for(let t=0;t<e.length;t++)for(let i=0;i<e[t].length-1;i++)for(let o=0;o<e.length;o++)for(let r=0;r<e[o].length-1;r++)s(t,i,o,r);return i.length>0;function o(t){return t<0||t>1}function s(t,s,r,n){const a=e[t][s],d=e[t][s+1],h=e[r][n],l=e[r][n+1],c=function(t,e,i,o){if(O(t,i)||O(t,o)||O(e,i)||O(o,i))return null;const s=t[0],r=t[1],n=e[0],a=e[1],d=i[0],h=i[1],l=o[0],c=o[1],u=(s-n)*(h-c)-(r-a)*(d-l);return 0===u?null:[((s*a-r*n)*(d-l)-(s-n)*(d*c-h*l))/u,((s*a-r*n)*(h-c)-(r-a)*(d*c-h*l))/u]}(a,d,h,l);if(null===c)return;let u,p;u=d[0]!==a[0]?(c[0]-a[0])/(d[0]-a[0]):(c[1]-a[1])/(d[1]-a[1]),p=l[0]!==h[0]?(c[0]-h[0])/(l[0]-h[0]):(c[1]-h[1])/(l[1]-h[1]),o(u)||o(p)||(c.toString(),i.push(c))}}function O(t,e){return t[0]===e[0]&&t[1]===e[1]}function k(t,e){return b(t[0])<=e&&b(t[1])<=e}function _(t){return 2===t.length&&"number"==typeof t[0]&&"number"==typeof t[1]&&Infinity!==t[0]&&Infinity!==t[1]&&(i=t[0])>=-180&&i<=180&&(e=t[1])>=-90&&e<=90;var e,i}function b(t){let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}const N="Feature has holes",T="Feature has less than 4 coordinates",W="Feature has invalid coordinates",j="Feature coordinates are not closed";function B(t,e){if("Polygon"!==t.geometry.type)return{valid:!1,reason:"Feature is not a Polygon"};if(1!==t.geometry.coordinates.length)return{valid:!1,reason:N};if(t.geometry.coordinates[0].length<4)return{valid:!1,reason:T};for(let i=0;i<t.geometry.coordinates[0].length;i++){if(!_(t.geometry.coordinates[0][i]))return{valid:!1,reason:W};if(!k(t.geometry.coordinates[0][i],e))return{valid:!1,reason:"Feature has coordinates with excessive precision"}}return(i=t.geometry.coordinates[0][0])[0]!==(o=t.geometry.coordinates[0][t.geometry.coordinates[0].length-1])[0]||i[1]!==o[1]?{valid:!1,reason:j}:{valid:!0};var i,o}function G(t,e){const i=B(t,e);return i.valid?D(t)?{valid:!1,reason:"Feature intersects itself"}:{valid:!0}:i}const R={cancel:"Escape",finish:"Enter"},U={start:"crosshair"};class L extends p{constructor(t){super(t,!0),this.mode="circle",this.center=void 0,this.clickCount=0,this.currentCircleId=void 0,this.keyEvents=R,this.cursors=U,this.startingRadiusKilometers=1e-5,this.cursorMovedAfterInitialCursorDown=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.startingRadiusKilometers&&(this.startingRadiusKilometers=e.startingRadiusKilometers)}close(){if(void 0===this.currentCircleId)return;this.store.updateProperty([{id:this.currentCircleId,property:s.CURRENTLY_DRAWING,value:void 0}]);const t=this.currentCircleId;if(this.validate&&t){const i=this.store.getGeometryCopy(t);if(!this.validate({type:"Feature",id:t,geometry:i,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid)return}this.cursorMovedAfterInitialCursorDown=!1,this.center=void 0,this.currentCircleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),this.onFinish(t,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))if(0===this.clickCount){this.center=[t.lng,t.lat];const e=F({center:this.center,radiusKilometers:this.startingRadiusKilometers,coordinatePrecision:this.coordinatePrecision}),[i]=this.store.create([{geometry:e.geometry,properties:{mode:this.mode,radiusKilometers:this.startingRadiusKilometers,[s.CURRENTLY_DRAWING]:!0}}]);this.currentCircleId=i,this.clickCount++,this.cursorMovedAfterInitialCursorDown=!1,this.setDrawing()}else 1===this.clickCount&&this.center&&void 0!==this.currentCircleId&&this.cursorMovedAfterInitialCursorDown&&this.updateCircle(t),this.close()}onMouseMove(t){this.cursorMovedAfterInitialCursorDown=!0,this.updateCircle(t)}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentCircleId;this.center=void 0,this.currentCircleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t])}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return"Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r,i):i}validateFeature(t){return this.validateModeFeature(t,t=>G(t,this.coordinatePrecision))}updateCircle(t){if(1===this.clickCount&&this.center&&this.currentCircleId){const i=y(this.center,[t.lng,t.lat]);let o;if("web-mercator"===this.projection){const e=function(t,e){const i=1e3*y(t,e);if(0===i)return 1;const{x:o,y:s}=S(t[0],t[1]),{x:r,y:n}=S(e[0],e[1]);return Math.sqrt(Math.pow(r-o,2)+Math.pow(n-s,2))/i}(this.center,[t.lng,t.lat]);o=function(t){const{center:e,radiusKilometers:i,coordinatePrecision:o}=t,s=t.steps?t.steps:64,r=1e3*i,[n,a]=e,{x:d,y:h}=S(n,a),l=[];for(let t=0;t<s;t++){const e=360*t/s*Math.PI/180,i=r*Math.cos(e),n=r*Math.sin(e),[a,c]=[d+i,h+n],{lng:u,lat:p}=M(a,c);l.push([P(u,o),P(p,o)])}return l.push(l[0]),{type:"Feature",geometry:{type:"Polygon",coordinates:[l]},properties:{}}}({center:this.center,radiusKilometers:i*e,coordinatePrecision:this.coordinatePrecision})}else{if("globe"!==this.projection)throw new Error("Invalid projection");o=F({center:this.center,radiusKilometers:i,coordinatePrecision:this.coordinatePrecision})}if(this.validate&&!this.validate({type:"Feature",id:this.currentCircleId,geometry:o.geometry,properties:{radiusKilometers:i}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional}).valid)return;this.store.updateGeometry([{id:this.currentCircleId,geometry:o.geometry}]),this.store.updateProperty([{id:this.currentCircleId,property:"radiusKilometers",value:i}])}}afterFeatureUpdated(t){this.currentCircleId===t.id&&(this.cursorMovedAfterInitialCursorDown=!1,this.center=void 0,this.currentCircleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted())}}const A=(t,e)=>{const{x:i,y:o}=t,{x:s,y:r}=e,n=s-i,a=r-o;return Math.sqrt(a*a+n*n)};function V(t){const e=function(t){const e=t.coordinates[0];let i=0;for(let t=0;t<e.length-1;t++){const[o,s]=e[t],[r,n]=e[t+1];i+=(r-o)*(n+s)}return i<0}(t);if(!e)return{type:"Polygon",coordinates:[t.coordinates[0].reverse()]}}const Y={cancel:"Escape",finish:"Enter"},K={start:"crosshair",close:"pointer"};class z extends p{constructor(t){super(t,!0),this.mode="freehand",this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,this.minDistance=20,this.keyEvents=Y,this.cursors=K,this.preventPointsNearClose=!0,this.autoClose=!1,this.autoCloseTimeout=500,this.hasLeftStartingPoint=!1,this.preventNewFeature=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.minDistance&&(this.minDistance=e.minDistance),void 0!==(null==e?void 0:e.preventPointsNearClose)&&(this.preventPointsNearClose=e.preventPointsNearClose),void 0!==(null==e?void 0:e.autoClose)&&(this.autoClose=e.autoClose),null!=e&&e.autoCloseTimeout&&(this.autoCloseTimeout=e.autoCloseTimeout),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors))}close(){if(void 0===this.currentId)return;if(this.currentId){const t=V(this.store.getGeometryCopy(this.currentId));t&&this.store.updateGeometry([{id:this.currentId,geometry:t}]),this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}])}const t=this.currentId;if(this.validate&&t){const i=this.store.getGeometryCopy(t);if(!this.validate({type:"Feature",id:t,geometry:i,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid)return}this.closingPointId&&this.store.delete([this.closingPointId]),this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,this.hasLeftStartingPoint=!1,"drawing"===this.state&&this.setStarted(),this.onFinish(t,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){if(void 0===this.currentId||!1===this.startingClick)return void this.setCursor(this.cursors.start);const i=this.store.getGeometryCopy(this.currentId),o=i.coordinates[0].length-2,[s,r]=i.coordinates[0][o],{x:n,y:a}=this.project(s,r),d=A({x:n,y:a},{x:t.containerX,y:t.containerY}),[h,l]=i.coordinates[0][0],{x:c,y:u}=this.project(h,l);if(A({x:c,y:u},{x:t.containerX,y:t.containerY})<this.pointerDistance){if(this.autoClose&&this.hasLeftStartingPoint&&(this.preventNewFeature=!0,setTimeout(()=>{this.preventNewFeature=!1},this.autoCloseTimeout),this.close()),this.setCursor(this.cursors.close),this.preventPointsNearClose)return}else this.hasLeftStartingPoint=!0,this.setCursor(this.cursors.start);if(d<this.minDistance)return;i.coordinates[0].pop();const p={type:"Polygon",coordinates:[[...i.coordinates[0],[t.lng,t.lat],i.coordinates[0][0]]]};this.validate&&!this.validate({type:"Feature",id:this.currentId,geometry:p,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional}).valid||this.store.updateGeometry([{id:this.currentId,geometry:p}])}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)){if(this.preventNewFeature)return;if(!1===this.startingClick){const[e,i]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}},{geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:{mode:this.mode,[s.CLOSING_POINT]:!0}}]);return this.currentId=e,this.closingPointId=i,this.startingClick=!0,void("drawing"!==this.state&&this.setDrawing())}this.close()}}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&!0===this.startingClick&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentId,e=this.closingPointId;this.closingPointId=void 0,this.currentId=void 0,this.startingClick=!1,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]),void 0!==e&&this.store.delete([e])}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return"Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r,i):"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode?(i.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),i.zIndex=50,i):i}validateFeature(t){return this.validateModeFeature(t,t=>B(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentId===t.id&&(this.closingPointId&&this.store.delete([this.closingPointId]),this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,this.hasLeftStartingPoint=!1)}}class H{constructor({store:t,mode:e,project:i,unproject:o,pointerDistance:s,coordinatePrecision:r,projection:n}){this.store=void 0,this.mode=void 0,this.project=void 0,this.unproject=void 0,this.pointerDistance=void 0,this.coordinatePrecision=void 0,this.projection=void 0,this.store=t,this.mode=e,this.project=i,this.unproject=o,this.pointerDistance=s,this.coordinatePrecision=r,this.projection=n}}function X({unproject:t,point:e,pointerDistance:i}){const o=i/2,{x:s,y:r}=e;return{type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[[t(s-o,r-o),t(s+o,r-o),t(s+o,r+o),t(s-o,r+o),t(s-o,r-o)].map(t=>[t.lng,t.lat])]}}}class $ extends H{constructor(t){super(t)}create(t){const{containerX:e,containerY:i}=t;return X({unproject:this.unproject,point:{x:e,y:i},pointerDistance:this.pointerDistance})}}class q extends H{constructor(t){super(t)}measure(t,e){const{x:i,y:o}=this.project(e[0],e[1]);return A({x:i,y:o},{x:t.containerX,y:t.containerY})}}class Z extends H{constructor(t,e,i){super(t),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=t=>this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode)).coordinate,this.getSnappableCoordinate=(t,e)=>this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode&&t.id!==e)).coordinate,this.config=t,this.pixelDistance=e,this.clickBoundingBox=i}getSnappable(t,e){const i=this.clickBoundingBox.create(t),o=this.store.search(i,e),s={featureId:void 0,featureCoordinateIndex:void 0,coordinate:void 0,minDist:Infinity};return o.forEach(e=>{let i;if("Polygon"===e.geometry.type)i=e.geometry.coordinates[0];else{if("LineString"!==e.geometry.type)return;i=e.geometry.coordinates}i.forEach((i,o)=>{const r=this.pixelDistance.measure(t,i);r<s.minDist&&r<this.pointerDistance&&(s.coordinate=i,s.minDist=r,s.featureId=e.id,s.featureCoordinateIndex=o)})}),s}}function J(t,e,i){const o=f(t[0]),s=f(t[1]),r=f(i),n=v(e),a=Math.asin(Math.sin(s)*Math.cos(n)+Math.cos(s)*Math.sin(n)*Math.cos(r));return[C(o+Math.atan2(Math.sin(r)*Math.sin(n)*Math.cos(s),Math.cos(n)-Math.sin(s)*Math.sin(a))),C(a)]}function Q({x:t,y:e},i,o){const s=f(o);return{x:t+i*Math.cos(s),y:e+i*Math.sin(s)}}function tt(t,e){const i=f(t[0]),o=f(e[0]),s=f(t[1]),r=f(e[1]),n=Math.sin(o-i)*Math.cos(r),a=Math.cos(s)*Math.sin(r)-Math.sin(s)*Math.cos(r)*Math.cos(o-i);return C(Math.atan2(n,a))}function et({x:t,y:e},{x:i,y:o}){const s=i-t,r=o-e;if(0===s&&0===r)return 0;let n=Math.atan2(r,s);return n*=180/Math.PI,n>180?n-=360:n<-180&&(n+=360),n}function it(t){return(t+360)%360}function ot(t,e,i){const o=[],s=t.length;let r,n,a,d=0;for(let s=0;s<t.length&&!(e>=d&&s===t.length-1);s++){if(d>e&&0===o.length){if(r=e-d,!r)return o.push(t[s]),o;n=tt(t[s],t[s-1])-180,a=J(t[s],r,n),o.push(a)}if(d>=i)return r=i-d,r?(n=tt(t[s],t[s-1])-180,a=J(t[s],r,n),o.push(a),o):(o.push(t[s]),o);if(d>=e&&o.push(t[s]),s===t.length-1)return o;d+=y(t[s],t[s+1])}if(d<e&&t.length===s)throw new Error("Start position is beyond line");const h=t[t.length-1];return[h,h]}function st(t){return t*(Math.PI/180)}function rt(t){return t*(180/Math.PI)}class nt extends H{constructor(t){super(t),this.config=void 0,this.config=t}generateInsertionCoordinates(t,e,i){const o=[t,e];let s=0;for(let t=0;t<o.length-1;t++)s+=y(o[0],o[1]);if(s<=i)return o;let r=s/i-1;Number.isInteger(r)||(r=Math.floor(r)+1);const n=[];for(let t=0;t<r;t++){const e=ot(o,i*t,i*(t+1));n.push(e)}const a=[];for(let t=0;t<n.length;t++)a.push(n[t][1]);return this.limitCoordinates(a)}generateInsertionGeodesicCoordinates(t,e,i){const o=y(t,e),s=function(t,e,i){const o=[],s=st(t[1]),r=st(t[0]),n=st(e[1]),a=st(e[0]);i+=1;const d=2*Math.asin(Math.sqrt(Math.sin((n-s)/2)**2+Math.cos(s)*Math.cos(n)*Math.sin((a-r)/2)**2));if(0===d||isNaN(d))return o;for(let t=0;t<=i;t++){const e=t/i,h=Math.sin((1-e)*d)/Math.sin(d),l=Math.sin(e*d)/Math.sin(d),c=h*Math.cos(s)*Math.cos(r)+l*Math.cos(n)*Math.cos(a),u=h*Math.cos(s)*Math.sin(r)+l*Math.cos(n)*Math.sin(a),p=h*Math.sin(s)+l*Math.sin(n);if(isNaN(c)||isNaN(u)||isNaN(p))continue;const g=Math.atan2(p,Math.sqrt(c**2+u**2)),y=Math.atan2(u,c);isNaN(g)||isNaN(y)||o.push([rt(y),rt(g)])}return o.slice(1,-1)}(t,e,Math.floor(o/i));return this.limitCoordinates(s)}limitCoordinates(t){return t.map(t=>[P(t[0],this.config.coordinatePrecision),P(t[1],this.config.coordinatePrecision)])}}function at(t,e){return t[0]===e[0]&&t[1]===e[1]}function dt(t,e){if("LineString"!==t.geometry.type)return{valid:!1,reason:"Feature is not a LineString"};if(t.geometry.coordinates.length<2)return{valid:!1,reason:"Feature has less than 2 coordinates"};for(let i=0;i<t.geometry.coordinates.length;i++){if(!_(t.geometry.coordinates[i]))return{valid:!1,reason:"Feature has invalid coordinates"};if(!k(t.geometry.coordinates[i],e))return{valid:!1,reason:"Feature has coordinates with excessive precision"}}return{valid:!0}}function ht(t){return Math.sqrt(Math.pow(t[0],2)+Math.pow(t[1],2)+Math.pow(t[2],2))}function lt(t,e){const i=function(t,e){const[i,o,s]=t,[r,n,a]=e;return i*r+o*n+s*a}(t,e)/(ht(t)*ht(e));return Math.acos(Math.min(Math.max(i,-1),1))}function ct(t){const e=f(t[1]),i=f(t[0]);return[Math.cos(e)*Math.cos(i),Math.cos(e)*Math.sin(i),Math.sin(e)]}function ut(t){const[e,i,o]=t,s=C(Math.asin(o));return[C(Math.atan2(i,e)),s]}function pt(t,e,i){const o=ct(t),s=ct(e),r=ct(i),[n,a,d]=r,[h,l,c]=function(t,e){const[i,o,s]=t,[r,n,a]=e;return[o*a-s*n,s*r-i*a,i*n-o*r]}(o,s),u=l*d-c*a,p=c*n-h*d,g=h*a-l*n,m=g*l-p*c,f=u*c-g*h,v=p*h-u*l,C=1/Math.sqrt(Math.pow(m,2)+Math.pow(f,2)+Math.pow(v,2)),P=[m*C,f*C,v*C],I=[-1*m*C,-1*f*C,-1*v*C],x=lt(o,s),E=lt(o,P),S=lt(s,P),M=lt(o,I),w=lt(s,I);let F;return F=E<M&&E<w||S<M&&S<w?P:I,lt(o,F)>x||lt(s,F)>x?y(ut(F),ut(o))<=y(ut(F),ut(s))?[ut(o),!0,!1]:[ut(s),!1,!0]:[ut(F),!1,!1]}function gt(t,e,i){const o=e.x-t.x,s=e.y-t.y,r=Math.max(0,Math.min(1,((i.x-t.x)*o+(i.y-t.y)*s)/(o*o+s*s)));return{x:t.x+r*o,y:t.y+r*s}}class yt extends H{constructor(t,e,i){super(t),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=t=>{const e=this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode));return e.coordinate?[P(e.coordinate[0],this.config.coordinatePrecision),P(e.coordinate[1],this.config.coordinatePrecision)]:void 0},this.getSnappableCoordinate=(t,e)=>{const i=this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode&&t.id!==e));return i.coordinate?[P(i.coordinate[0],this.config.coordinatePrecision),P(i.coordinate[1],this.config.coordinatePrecision)]:void 0},this.config=t,this.pixelDistance=e,this.clickBoundingBox=i}getSnappable(t,e){const i=this.clickBoundingBox.create(t),o=this.store.search(i,e),s={featureId:void 0,featureCoordinateIndex:void 0,coordinate:void 0,minDistance:Infinity};return o.forEach(e=>{let i;if("Polygon"===e.geometry.type)i=e.geometry.coordinates[0];else{if("LineString"!==e.geometry.type)return;i=e.geometry.coordinates}const o=[];for(let t=0;t<i.length-1;t++)o.push([i[t],i[t+1]]);let r;const n=[t.lng,t.lat];if("web-mercator"===this.config.projection?r=function(t,e){let i=[Infinity,Infinity],o=Infinity,s=0;for(let r of e){const n=r[0],a=r[1];let d,h=Infinity;const l=S(n[0],n[1]),c=S(a[0],a[1]),u=S(t[0],t[1]);if(n[0]===t[0]&&n[1]===t[1])d=n;else if(a[0]===t[0]&&a[1]===t[1])d=a;else{const{x:t,y:e}=gt(l,c,u),{lng:i,lat:o}=M(t,e);d=[i,o]}d&&(h=A(u,S(d[0],d[1])),h<o&&(i=d,o=h,s=e.indexOf(r)))}return Infinity===o?void 0:{coordinate:i,lineIndex:s,distance:o}}(n,o):"globe"===this.config.projection&&(r=function(t,e){let i=[Infinity,Infinity],o=Infinity,s=0;for(let r of e){const n=r[0],a=r[1];let d,h=Infinity;n[0]===t[0]&&n[1]===t[1]?d=n:a[0]===t[0]&&a[1]===t[1]?d=a:[d]=pt(n,a,t),d&&(h=y(t,d),h<o&&(i=d,o=h,s=e.indexOf(r)))}return Infinity===o?void 0:{coordinate:i,distance:o,lineIndex:s}}(n,o)),!r)return;const a=this.pixelDistance.measure(t,r.coordinate);a<s.minDistance&&a<this.pointerDistance&&(s.featureId=e.id,s.coordinate=[P(r.coordinate[0],this.config.coordinatePrecision),P(r.coordinate[1],this.config.coordinatePrecision)],s.featureCoordinateIndex=r.lineIndex,s.minDistance=a)}),s}}const mt={cancel:"Escape",finish:"Enter"},ft={start:"crosshair",close:"pointer",dragStart:"grabbing",dragEnd:"crosshair"};class vt extends p{constructor(t){super(t,!0),this.mode="linestring",this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.keyEvents=mt,this.snapping=void 0,this.cursors=ft,this.mouseMove=!1,this.insertCoordinates=void 0,this.lastCommittedCoordinates=void 0,this.snappedPointId=void 0,this.lastMouseMoveEvent=void 0,this.editable=!1,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0,this.editedInsertIndex=void 0,this.editedPointId=void 0,this.coordinateSnapping=void 0,this.insertPoint=void 0,this.lineSnapping=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null!=e&&e.snapping&&(this.snapping=e.snapping),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.insertCoordinates&&(this.insertCoordinates=e.insertCoordinates),e&&e.editable&&(this.editable=e.editable)}updateSnappedCoordinate(t){const e=this.snapCoordinate(t);if(e){if(this.snappedPointId)this.store.updateGeometry([{id:this.snappedPointId,geometry:{type:"Point",coordinates:e}}]);else{const[t]=this.store.create([{geometry:{type:"Point",coordinates:e},properties:{mode:this.mode,[s.SNAPPING_POINT]:!0}}]);this.snappedPointId=t}t.lng=e[0],t.lat=e[1]}else this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0);return e}close(){if(void 0===this.currentId)return;const t=this.store.getGeometryCopy(this.currentId);t.coordinates.pop(),this.updateGeometries([...t.coordinates],void 0,e.Commit),this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}]);const i=this.currentId;this.closingPointId&&this.store.delete([this.closingPointId]),this.snappedPointId&&this.store.delete([this.snappedPointId]),this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.snappedPointId=void 0,this.lastCommittedCoordinates=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(i,{mode:this.mode,action:"draw"})}updateGeometries(t,e,i){if(!this.currentId)return;const o={type:"LineString",coordinates:t};if(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}).valid)return;const s=[{id:this.currentId,geometry:o}];this.closingPointId&&e&&s.push({id:this.closingPointId,geometry:{type:"Point",coordinates:e}}),"commit"===i&&(this.lastCommittedCoordinates=o.coordinates),this.store.updateGeometry(s)}generateInsertCoordinates(t,e){if(!this.insertCoordinates||!this.lastCommittedCoordinates)throw new Error("Not able to insert coordinates");if("amount"!==this.insertCoordinates.strategy)throw new Error("Strategy does not exist");const i=y(t,e)/(this.insertCoordinates.value+1);let o=[];return"globe"===this.projection?o=this.insertPoint.generateInsertionGeodesicCoordinates(t,e,i):"web-mercator"===this.projection&&(o=this.insertPoint.generateInsertionCoordinates(t,e,i)),o}createLine(t){const[e]=this.store.create([{geometry:{type:"LineString",coordinates:[t,t]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}}]);this.lastCommittedCoordinates=[t,t],this.currentId=e,this.currentCoordinate++,this.setDrawing()}firstUpdateToLine(t){if(!this.currentId)return;const i=this.store.getGeometryCopy(this.currentId).coordinates,[o]=this.store.create([{geometry:{type:"Point",coordinates:[...t]},properties:{mode:this.mode,[s.CLOSING_POINT]:!0}}]);this.closingPointId=o,this.setCursor(this.cursors.close);const r=[...i,t];this.updateGeometries(r,void 0,e.Commit),this.currentCoordinate++}updateToLine(t,i){if(!this.currentId)return;const o=this.store.getGeometryCopy(this.currentId).coordinates,[s,r]=this.lastCommittedCoordinates?this.lastCommittedCoordinates[this.lastCommittedCoordinates.length-1]:o[o.length-2],{x:n,y:a}=this.project(s,r);if(A({x:n,y:a},{x:i.x,y:i.y})<this.pointerDistance)return void this.close();this.setCursor(this.cursors.close);const d=[...o,t];this.updateGeometries(d,o[o.length-1],e.Commit),this.currentCoordinate++}registerBehaviors(t){this.coordinateSnapping=new Z(t,new q(t),new $(t)),this.insertPoint=new nt(t),this.clickBoundingBox=new $(t),this.pixelDistance=new q(t),this.lineSnapping=new yt(t,this.pixelDistance,this.clickBoundingBox),this.coordinateSnapping=new Z(t,this.pixelDistance,this.clickBoundingBox)}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){this.mouseMove=!0,this.setCursor(this.cursors.start),this.lastMouseMoveEvent=t;const i=this.updateSnappedCoordinate(t)||[t.lng,t.lat];if(void 0===this.currentId||0===this.currentCoordinate)return;const o=this.store.getGeometryCopy(this.currentId).coordinates;if(o.pop(),this.closingPointId){const[e,i]=o[o.length-1],{x:s,y:r}=this.project(e,i);A({x:s,y:r},{x:t.containerX,y:t.containerY})<this.pointerDistance&&this.setCursor(this.cursors.close)}let s=[...o,i];if(this.insertCoordinates&&this.currentId&&this.lastCommittedCoordinates){const t=this.lastCommittedCoordinates[this.lastCommittedCoordinates.length-1],e=i;if(!at(t,e)){const o=this.generateInsertCoordinates(t,e);s=[...this.lastCommittedCoordinates.slice(0,-1),...o,i]}}this.updateGeometries(s,void 0,e.Provisional)}onRightClick(t){if(!this.editable||"started"!==this.state)return;const{featureId:i,featureCoordinateIndex:o}=this.coordinateSnapping.getSnappable(t,t=>this.lineStringFilter(t));if(!i||void 0===o)return;const s=this.store.getGeometryCopy(i);let r;if("LineString"===s.type&&(r=s.coordinates,!(r.length<=2))){if(r.splice(o,1),this.validate&&!this.validate({id:i,type:"Feature",geometry:s,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Commit}).valid)return;this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),this.store.updateGeometry([{id:i,geometry:s}]),this.onFinish(i,{mode:this.mode,action:"edit"})}}onLeftClick(t){this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0);const e=this.snapCoordinate(t)||[t.lng,t.lat];0===this.currentCoordinate?this.createLine(e):1===this.currentCoordinate&&this.currentId?this.firstUpdateToLine(e):this.currentId&&this.updateToLine(e,{x:t.containerX,y:t.containerY})}onClick(t){("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))&&(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,"right"===t.button?this.onRightClick(t):"left"===t.button&&this.onLeftClick(t))}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel&&this.cleanUp(),t.key===this.keyEvents.finish&&this.close()}onDragStart(t,e){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,t))return;if(!this.editable)return;let i;if("started"===this.state){const e=this.lineSnapping.getSnappable(t,t=>this.lineStringFilter(t));e.coordinate&&(this.editedSnapType="line",this.editedFeatureCoordinateIndex=e.featureCoordinateIndex,this.editedFeatureId=e.featureId,i=e.coordinate);const o=this.coordinateSnapping.getSnappable(t,t=>this.lineStringFilter(t));o.coordinate&&(this.editedSnapType="coordinate",this.editedFeatureCoordinateIndex=o.featureCoordinateIndex,this.editedFeatureId=o.featureId,i=o.coordinate)}if(this.editedFeatureId&&i){if(!this.editedPointId){const[t]=this.store.create([{geometry:{type:"Point",coordinates:i},properties:{mode:this.mode,[s.EDITED]:!0}}]);this.editedPointId=t}this.setCursor(this.cursors.dragStart),e(!1)}}onDrag(t,i){if(!this.allowPointerEvent(this.pointerEvents.onDrag,t))return;if(void 0===this.editedFeatureId||void 0===this.editedFeatureCoordinateIndex)return;const o=this.store.getGeometryCopy(this.editedFeatureId);"coordinate"===this.editedSnapType||"line"===this.editedSnapType&&void 0!==this.editedInsertIndex?o.coordinates[this.editedFeatureCoordinateIndex]=[t.lng,t.lat]:"line"===this.editedSnapType&&void 0===this.editedInsertIndex&&(this.editedInsertIndex=this.editedFeatureCoordinateIndex+1,o.coordinates.splice(this.editedInsertIndex,0,[t.lng,t.lat]),this.editedFeatureCoordinateIndex++);const r={type:"LineString",coordinates:o.coordinates};this.validate&&!this.validate({type:"Feature",geometry:r,properties:this.store.getPropertiesCopy(this.editedFeatureId)},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional}).valid||(this.snapping&&this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),this.store.updateGeometry([{id:this.editedFeatureId,geometry:r}]),this.editedPointId&&this.store.updateGeometry([{id:this.editedPointId,geometry:{type:"Point",coordinates:[t.lng,t.lat]}}]),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!0}]))}onDragEnd(t,e){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&void 0!==this.editedFeatureId&&(this.setCursor(this.cursors.dragEnd),this.editedPointId&&(this.store.delete([this.editedPointId]),this.editedPointId=void 0),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!1}]),this.onFinish(this.editedFeatureId,{mode:this.mode,action:"edit"}),this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0,e(!0))}cleanUp(){const t=this.currentId,e=this.closingPointId,i=this.snappedPointId;this.closingPointId=void 0,this.snappedPointId=void 0,this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]),void 0!==i&&this.store.delete([i]),void 0!==e&&this.store.delete([e])}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});if("Feature"===e.type&&"LineString"===e.geometry.type&&e.properties.mode===this.mode)return i.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,i.lineStringColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,i.lineStringWidth,e),i.zIndex=r,i;if("Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode){const t=e.properties[s.CLOSING_POINT];return i.pointColor=this.getHexColorStylingValue(t?this.styles.closingPointColor:this.styles.snappingPointColor,i.pointColor,e),i.pointWidth=this.getNumericStylingValue(t?this.styles.closingPointWidth:this.styles.snappingPointWidth,i.pointWidth,e),i.pointOutlineColor=this.getHexColorStylingValue(t?this.styles.closingPointOutlineColor:this.styles.snappingPointOutlineColor,"#ffffff",e),i.pointOutlineWidth=this.getNumericStylingValue(t?this.styles.closingPointOutlineWidth:this.styles.snappingPointOutlineWidth,2,e),i.zIndex=50,i}return i}validateFeature(t){return this.validateModeFeature(t,t=>dt(t,this.coordinatePrecision))}lineStringFilter(t){return Boolean("LineString"===t.geometry.type&&t.properties&&t.properties.mode===this.mode)}snapCoordinate(t){var e,i,o;let s;if(null!=(e=this.snapping)&&e.toLine){let e;e=this.currentId?this.lineSnapping.getSnappableCoordinate(t,this.currentId):this.lineSnapping.getSnappableCoordinateFirstClick(t),e&&(s=e)}return null!=(i=this.snapping)&&i.toCoordinate&&(s=this.currentId?this.coordinateSnapping.getSnappableCoordinate(t,this.currentId):this.coordinateSnapping.getSnappableCoordinateFirstClick(t)),null!=(o=this.snapping)&&o.toCustom&&(s=this.snapping.toCustom(t,{currentCoordinate:this.currentCoordinate,currentId:this.currentId,getCurrentGeometrySnapshot:this.currentId?()=>this.store.getGeometryCopy(this.currentId):()=>null,project:this.project,unproject:this.unproject})),s}afterFeatureUpdated(t){this.editedFeatureId===t.id&&this.editedPointId&&(this.store.delete([this.editedPointId]),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0),this.snappedPointId&&this.lastMouseMoveEvent&&this.updateSnappedCoordinate(this.lastMouseMoveEvent),this.currentId===t.id&&(this.closingPointId&&(this.store.delete([this.closingPointId]),this.closingPointId=void 0),this.currentCoordinate=0,this.currentId=void 0,"drawing"===this.state&&this.setStarted())}}const Ct="Feature is not a Point",Pt="Feature has invalid coordinates",It="Feature has coordinates with excessive precision";function xt(t,e){return"Point"!==t.geometry.type?{valid:!1,reason:Ct}:_(t.geometry.coordinates)?k(t.geometry.coordinates,e)?{valid:!0}:{valid:!1,reason:It}:{valid:!1,reason:Pt}}const Et={create:"crosshair",dragStart:"grabbing",dragEnd:"crosshair"};class St extends p{constructor(t){super(t,!0),this.mode="point",this.cursors=Et,this.editable=!1,this.editedFeatureId=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null!=e&&e.editable&&(this.editable=e.editable)}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(t){"right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)?this.onRightClick(t):"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)&&this.onLeftClick(t)}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){this.editedFeatureId=void 0}onDragStart(t,e){if(this.allowPointerEvent(this.pointerEvents.onDragStart,t)){if(this.editable){const e=this.getNearestPointFeature(t);this.editedFeatureId=null==e?void 0:e.id}this.editedFeatureId&&(this.setCursor(this.cursors.dragStart),e(!1))}}onDrag(t,i){this.allowPointerEvent(this.pointerEvents.onDrag,t)&&void 0!==this.editedFeatureId&&(this.validate&&!this.validate({type:"Feature",geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:this.store.getPropertiesCopy(this.editedFeatureId)},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid||(this.store.updateGeometry([{id:this.editedFeatureId,geometry:{type:"Point",coordinates:[t.lng,t.lat]}}]),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!0}])))}onDragEnd(t,e){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&void 0!==this.editedFeatureId&&(this.onFinish(this.editedFeatureId,{mode:this.mode,action:"edit"}),this.setCursor(this.cursors.dragEnd),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!1}]),this.editedFeatureId=void 0,e(!0))}registerBehaviors(t){this.pixelDistance=new q(t),this.clickBoundingBox=new $(t)}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});if("Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode){const t=Boolean(e.id&&this.editedFeatureId===e.id);i.pointWidth=this.getNumericStylingValue(t?this.styles.editedPointWidth:this.styles.pointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(t?this.styles.editedPointColor:this.styles.pointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(t?this.styles.editedPointOutlineColor:this.styles.pointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(t?this.styles.editedPointOutlineWidth:this.styles.pointOutlineWidth,2,e),i.zIndex=30}return i}validateFeature(t){return this.validateModeFeature(t,t=>xt(t,this.coordinatePrecision))}onLeftClick(t){const i={type:"Point",coordinates:[t.lng,t.lat]},o={mode:this.mode};if(this.validate&&!this.validate({type:"Feature",geometry:i,properties:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid)return;const[s]=this.store.create([{geometry:i,properties:o}]);this.onFinish(s,{mode:this.mode,action:"draw"})}onRightClick(t){if(!this.editable)return;const e=this.getNearestPointFeature(t);e&&this.store.delete([e.id])}getNearestPointFeature(t){const e=this.clickBoundingBox.create(t),i=this.store.search(e);let o,s=Infinity;for(let e=0;e<i.length;e++){const r=i[e];if("Point"!==r.geometry.type||r.properties.mode!==this.mode)continue;const n=this.pixelDistance.measure(t,r.geometry.coordinates);n>s||n>this.pointerDistance||(s=n,o=r)}return o}afterFeatureUpdated(t){this.editedFeatureId===t.id&&(this.editedFeatureId=void 0,this.setCursor(this.cursors.create))}}class Mt extends H{constructor(t,e){super(t),this.config=void 0,this.pixelDistance=void 0,this._startEndPoints=[],this.config=t,this.pixelDistance=e}get ids(){return this._startEndPoints.concat()}set ids(t){}create(t,e){if(this.ids.length)throw new Error("Opening and closing points already created");if(t.length<=3)throw new Error("Requires at least 4 coordinates");this._startEndPoints=this.store.create([{geometry:{type:"Point",coordinates:t[0]},properties:{mode:e,[s.CLOSING_POINT]:!0}},{geometry:{type:"Point",coordinates:t[t.length-2]},properties:{mode:e,[s.CLOSING_POINT]:!0}}])}delete(){this.ids.length&&(this.store.delete(this.ids),this._startEndPoints=[])}update(t){if(2!==this.ids.length)throw new Error("No closing points to update");this.store.updateGeometry([{id:this.ids[0],geometry:{type:"Point",coordinates:t[0]}},{id:this.ids[1],geometry:{type:"Point",coordinates:t[t.length-3]}}])}isClosingPoint(t){const e=this.store.getGeometryCopy(this.ids[0]),i=this.store.getGeometryCopy(this.ids[1]),o=this.pixelDistance.measure(t,e.coordinates),s=this.pixelDistance.measure(t,i.coordinates);return{isClosing:o<this.pointerDistance,isPreviousClosing:s<this.pointerDistance}}}class wt extends H{constructor(t){super(t)}createOrUpdate(t){const e=this.store.getGeometryCopy(t),i=this.store.getPropertiesCopy(t);let o;if("Polygon"===e.type)o=e.coordinates[0].slice(0,-1);else{if("LineString"!==e.type)return;o=e.coordinates}const s=this.store.getPropertiesCopy(t),r=s.coordinatePointIds;if(r)if(r&&r.every(t=>this.store.has(t))){const e=s.coordinatePointIds,r=e.map(t=>this.store.getGeometryCopy(t).coordinates);if(e.length!==o.length){this.deleteCoordinatePoints(e);const s=this.createPoints(o,i.mode,t);this.setFeatureCoordinatePoints(t,s)}else o.forEach((t,i)=>{t[0]===r[i][0]&&t[1]===r[i][1]||this.store.updateGeometry([{id:e[i],geometry:{type:"Point",coordinates:t}}])})}else{const e=r.filter(t=>this.store.has(t));e.length&&this.deleteCoordinatePoints(e);const s=this.createPoints(o,i.mode,t);this.setFeatureCoordinatePoints(t,s)}else{const e=this.createPoints(o,i.mode,t);this.setFeatureCoordinatePoints(t,e)}}deletePointsByFeatureIds(t){for(const e of t)this.deleteIfPresent(e)}getUpdated(e,i){const o=this.store.getPropertiesCopy(e);if(o.coordinatePointIds)return o.coordinatePointIds.map((e,o)=>({id:e,geometry:t({},this.store.getGeometryCopy(e),{coordinates:i[o]})}))}createPoints(t,e,i){return this.store.create(t.map((t,o)=>({geometry:{type:"Point",coordinates:t},properties:{mode:e,[s.COORDINATE_POINT]:!0,[s.COORDINATE_POINT_FEATURE_ID]:i,index:o}})))}setFeatureCoordinatePoints(t,e){this.store.updateProperty([{id:t,property:s.COORDINATE_POINT_IDS,value:e}])}deleteCoordinatePoints(t){const e=t.filter(t=>this.store.has(t));this.store.delete(e)}deleteIfPresent(t){const e=this.store.getPropertiesCopy(t).coordinatePointIds;e&&(this.deleteCoordinatePoints(e),this.setFeatureCoordinatePoints(t,null))}}const Ft={cancel:"Escape",finish:"Enter"},Dt={start:"crosshair",close:"pointer",dragStart:"grabbing",dragEnd:"crosshair"};class Ot extends p{constructor(t){super(t,!0),this.mode="polygon",this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=Ft,this.cursors=Dt,this.mouseMove=!1,this.showCoordinatePoints=!1,this.lastMouseMoveEvent=void 0,this.snapping=void 0,this.snappedPointId=void 0,this.editable=!1,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0,this.editedInsertIndex=void 0,this.editedPointId=void 0,this.coordinatePoints=void 0,this.lineSnapping=void 0,this.coordinateSnapping=void 0,this.pixelDistance=void 0,this.closingPoints=void 0,this.clickBoundingBox=void 0,this.updateOptions(t)}updateOptions(e){if(super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.snapping&&(this.snapping=e.snapping),void 0!==(null==e?void 0:e.editable)&&(this.editable=e.editable),void 0!==(null==e?void 0:e.pointerEvents)&&(this.pointerEvents=e.pointerEvents),void 0!==(null==e?void 0:e.showCoordinatePoints))if(this.showCoordinatePoints=e.showCoordinatePoints,this.coordinatePoints&&!0===e.showCoordinatePoints)this.store.copyAllWhere(t=>t.mode===this.mode).map(t=>t.id).forEach(t=>{this.coordinatePoints.createOrUpdate(t)});else if(this.coordinatePoints&&!1===this.showCoordinatePoints){const t=this.store.copyAllWhere(t=>t.mode===this.mode&&Boolean(t[s.COORDINATE_POINT_IDS]));this.coordinatePoints.deletePointsByFeatureIds(t.map(t=>t.id))}}close(){if(void 0===this.currentId)return;const t=this.store.getGeometryCopy(this.currentId).coordinates[0];if(t.length<5)return;if(!this.updatePolygonGeometry([...t.slice(0,-2),t[0]],e.Finish))return;const i=this.currentId;if(this.currentId){const t=V(this.store.getGeometryCopy(this.currentId));t&&(this.store.updateGeometry([{id:this.currentId,geometry:t}]),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(this.currentId)),this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0},{id:this.currentId,property:s.COMMITTED_COORDINATE_COUNT,value:void 0},{id:this.currentId,property:s.PROVISIONAL_COORDINATE_COUNT,value:void 0}])}this.snappedPointId&&this.store.delete([this.snappedPointId]),this.currentCoordinate=0,this.currentId=void 0,this.snappedPointId=void 0,this.closingPoints.delete(),"drawing"===this.state&&this.setStarted(),this.onFinish(i,{mode:this.mode,action:"draw"})}registerBehaviors(t){this.clickBoundingBox=new $(t),this.pixelDistance=new q(t),this.lineSnapping=new yt(t,this.pixelDistance,this.clickBoundingBox),this.coordinateSnapping=new Z(t,this.pixelDistance,this.clickBoundingBox),this.closingPoints=new Mt(t,this.pixelDistance),this.coordinatePoints=new wt(t)}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}updateSnappedCoordinate(t){const e=this.snapCoordinate(t);if(e){if(this.snappedPointId)this.store.updateGeometry([{id:this.snappedPointId,geometry:{type:"Point",coordinates:e}}]);else{const[t]=this.store.create([{geometry:{type:"Point",coordinates:e},properties:{mode:this.mode,[s.SNAPPING_POINT]:!0}}]);this.snappedPointId=t}t.lng=e[0],t.lat=e[1]}else this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0)}onMouseMove(t){if(this.mouseMove=!0,this.setCursor(this.cursors.start),this.lastMouseMoveEvent=t,this.updateSnappedCoordinate(t),void 0===this.currentId||0===this.currentCoordinate)return;const i=this.store.getGeometryCopy(this.currentId).coordinates[0];let o;if(1===this.currentCoordinate){const e=1/Math.pow(10,this.coordinatePrecision-1),s=Math.max(1e-6,e);o=[i[0],[t.lng,t.lat],[t.lng,t.lat-s],i[0]]}else if(2===this.currentCoordinate)o=[i[0],i[1],[t.lng,t.lat],i[0]];else{const{isClosing:e,isPreviousClosing:s}=this.closingPoints.isClosingPoint(t);s||e?(this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),this.setCursor(this.cursors.close),o=[...i.slice(0,-2),i[0],i[0]]):o=[...i.slice(0,-2),[t.lng,t.lat],i[0]]}this.store.updateProperty([{id:this.currentId,property:s.PROVISIONAL_COORDINATE_COUNT,value:this.currentCoordinate+1}]),this.updatePolygonGeometry(o,e.Provisional)}updatePolygonGeometry(t,e){if(!this.currentId)return!1;const i={type:"Polygon",coordinates:[t]};return!(this.validate&&!this.validate({type:"Feature",geometry:i},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e}).valid||(this.store.updateGeometry([{id:this.currentId,geometry:i}]),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(this.currentId),0))}snapCoordinate(t){var e,i,o;let s;if(null!=(e=this.snapping)&&e.toLine){let e;e=this.currentId?this.lineSnapping.getSnappableCoordinate(t,this.currentId):this.lineSnapping.getSnappableCoordinateFirstClick(t),e&&(s=e)}if(null!=(i=this.snapping)&&i.toCoordinate){let e;e=this.currentId?this.coordinateSnapping.getSnappableCoordinate(t,this.currentId):this.coordinateSnapping.getSnappableCoordinateFirstClick(t),e&&(s=e)}return null!=(o=this.snapping)&&o.toCustom&&(s=this.snapping.toCustom(t,{currentCoordinate:this.currentCoordinate,currentId:this.currentId,getCurrentGeometrySnapshot:this.currentId?()=>this.store.getGeometryCopy(this.currentId):()=>null,project:this.project,unproject:this.unproject})),s}polygonFilter(t){return Boolean("Polygon"===t.geometry.type&&t.properties&&t.properties.mode===this.mode)}onRightClick(t){if(!this.editable||"started"!==this.state)return;const{featureId:i,featureCoordinateIndex:o}=this.coordinateSnapping.getSnappable(t,t=>this.polygonFilter(t));if(!i||void 0===o)return;const s=this.store.getGeometryCopy(i);let r;"Polygon"===s.type&&(r=s.coordinates[0],r.length<=4||("Polygon"!==s.type||0!==o&&o!==r.length-1?r.splice(o,1):(r.shift(),r.pop(),r.push([r[0][0],r[0][1]])),(!this.validate||this.validate({id:i,type:"Feature",geometry:s,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Commit}).valid)&&(this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),this.store.updateGeometry([{id:i,geometry:s}]),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(i),this.onFinish(i,{mode:this.mode,action:"edit"}))))}onLeftClick(t){if(this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),0===this.currentCoordinate){const e=this.snapCoordinate(t);e&&(t.lng=e[0],t.lat=e[1]);const[i]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0,[s.COMMITTED_COORDINATE_COUNT]:this.currentCoordinate+1,[s.PROVISIONAL_COORDINATE_COUNT]:this.currentCoordinate+1}}]);this.currentId=i,this.currentCoordinate++,this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(i),this.setDrawing()}else if(1===this.currentCoordinate&&this.currentId){const i=this.snapCoordinate(t);i&&(t.lng=i[0],t.lat=i[1]);const o=this.store.getGeometryCopy(this.currentId);if(at([t.lng,t.lat],o.coordinates[0][0]))return;if(!this.updatePolygonGeometry([o.coordinates[0][0],[t.lng,t.lat],[t.lng,t.lat],o.coordinates[0][0]],e.Commit))return;this.store.updateProperty([{id:this.currentId,property:s.COMMITTED_COORDINATE_COUNT,value:this.currentCoordinate+1}]),this.currentCoordinate++}else if(2===this.currentCoordinate&&this.currentId){const i=this.snapCoordinate(t);i&&(t.lng=i[0],t.lat=i[1]);const o=this.store.getGeometryCopy(this.currentId).coordinates[0];if(at([t.lng,t.lat],o[1]))return;if(!this.updatePolygonGeometry([o[0],o[1],[t.lng,t.lat],[t.lng,t.lat],o[0]],e.Commit))return;2===this.currentCoordinate&&this.closingPoints.create(o,"polygon"),this.store.updateProperty([{id:this.currentId,property:s.COMMITTED_COORDINATE_COUNT,value:this.currentCoordinate+1}]),this.currentCoordinate++}else if(this.currentId){const i=this.store.getGeometryCopy(this.currentId).coordinates[0],{isClosing:o,isPreviousClosing:r}=this.closingPoints.isClosingPoint(t);if(r||o)this.close();else{const o=this.snapCoordinate(t);if(o&&(t.lng=o[0],t.lat=o[1]),at([t.lng,t.lat],i[this.currentCoordinate-1]))return;const r=function(t=[[[0,0],[0,1],[1,1],[1,0],[0,0]]]){return{type:"Feature",geometry:{type:"Polygon",coordinates:t},properties:{}}}([[...i.slice(0,-1),[t.lng,t.lat],i[0]]]);if(!this.updatePolygonGeometry(r.geometry.coordinates[0],e.Commit))return;this.store.updateProperty([{id:this.currentId,property:s.COMMITTED_COORDINATE_COUNT,value:this.currentCoordinate+1}]),this.currentCoordinate++,this.closingPoints.ids.length&&this.closingPoints.update(r.geometry.coordinates[0])}}}onClick(t){this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,"right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)?this.onRightClick(t):"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)&&this.onLeftClick(t)}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(t,e){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,t))return;if(!this.editable)return;let i;if("started"===this.state){const e=this.lineSnapping.getSnappable(t,t=>this.polygonFilter(t));e.coordinate&&(this.editedSnapType="line",this.editedFeatureCoordinateIndex=e.featureCoordinateIndex,this.editedFeatureId=e.featureId,i=e.coordinate);const o=this.coordinateSnapping.getSnappable(t,t=>this.polygonFilter(t));o.coordinate&&(this.editedSnapType="coordinate",this.editedFeatureCoordinateIndex=o.featureCoordinateIndex,this.editedFeatureId=o.featureId,i=o.coordinate)}if(this.editedFeatureId&&i){if(!this.editedPointId){const[t]=this.store.create([{geometry:{type:"Point",coordinates:i},properties:{mode:this.mode,[s.EDITED]:!0}}]);this.editedPointId=t}this.setCursor(this.cursors.dragStart),e(!1)}}onDrag(t,i){if(!this.allowPointerEvent(this.pointerEvents.onDrag,t))return;if(void 0===this.editedFeatureId||void 0===this.editedFeatureCoordinateIndex)return;const o=this.store.getGeometryCopy(this.editedFeatureId),r=o.coordinates[0];"coordinate"===this.editedSnapType||"line"===this.editedSnapType&&void 0!==this.editedInsertIndex?0===this.editedFeatureCoordinateIndex||this.editedFeatureCoordinateIndex===o.coordinates[0].length-1?(r[0]=[t.lng,t.lat],r[r.length-1]=[t.lng,t.lat]):r[this.editedFeatureCoordinateIndex]=[t.lng,t.lat]:"line"===this.editedSnapType&&void 0===this.editedInsertIndex&&(this.editedInsertIndex=this.editedFeatureCoordinateIndex+1,o.coordinates[0].splice(this.editedInsertIndex,0,[t.lng,t.lat]),this.editedFeatureCoordinateIndex++);const n={type:"Polygon",coordinates:o.coordinates};this.validate&&!this.validate({type:"Feature",geometry:n,properties:this.store.getPropertiesCopy(this.editedFeatureId)},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional}).valid||(this.snapping&&this.snappedPointId&&(this.store.delete([this.snappedPointId]),this.snappedPointId=void 0),this.store.updateGeometry([{id:this.editedFeatureId,geometry:n}]),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(this.editedFeatureId),this.editedPointId&&this.store.updateGeometry([{id:this.editedPointId,geometry:{type:"Point",coordinates:[t.lng,t.lat]}}]),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!0}]))}onDragEnd(t,e){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&void 0!==this.editedFeatureId&&(this.setCursor(this.cursors.dragEnd),this.editedPointId&&(this.store.delete([this.editedPointId]),this.editedPointId=void 0),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!1}]),this.onFinish(this.editedFeatureId,{mode:this.mode,action:"edit"}),this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0,e(!0))}cleanUp(){const t=this.currentId,e=this.snappedPointId,i=this.editedPointId;this.currentId=void 0,this.snappedPointId=void 0,this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{t&&this.coordinatePoints.deletePointsByFeatureIds([t]),void 0!==t&&this.store.delete([t]),void 0!==i&&this.store.delete([i]),void 0!==e&&this.store.delete([e]),this.closingPoints.ids.length&&this.closingPoints.delete()}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});if(e.properties.mode===this.mode){if("Polygon"===e.geometry.type)return i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r,i;if("Point"===e.geometry.type){const t=e.properties[s.EDITED],o=e.properties[s.COORDINATE_POINT],r=t?"editedPoint":e.properties[s.CLOSING_POINT]?"closingPoint":e.properties[s.SNAPPING_POINT]?"snappingPoint":o?"coordinatePoint":void 0;if(!r)return i;const n={editedPoint:{width:this.styles.editedPointOutlineWidth,color:this.styles.editedPointColor,outlineColor:this.styles.editedPointOutlineColor,outlineWidth:this.styles.editedPointOutlineWidth},closingPoint:{width:this.styles.closingPointWidth,color:this.styles.closingPointColor,outlineColor:this.styles.closingPointOutlineColor,outlineWidth:this.styles.closingPointOutlineWidth},snappingPoint:{width:this.styles.snappingPointWidth,color:this.styles.snappingPointColor,outlineColor:this.styles.snappingPointOutlineColor,outlineWidth:this.styles.snappingPointOutlineWidth},coordinatePoint:{width:this.styles.coordinatePointWidth,color:this.styles.coordinatePointColor,outlineColor:this.styles.coordinatePointOutlineColor,outlineWidth:this.styles.coordinatePointOutlineWidth}};return i.pointWidth=this.getNumericStylingValue(n[r].width,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(n[r].color,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(n[r].outlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(n[r].outlineWidth,2,e),i.zIndex=t?40:o?20:30,i}}return i}afterFeatureAdded(t){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(t.id)}afterFeatureUpdated(t){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate(t.id),this.editedFeatureId===t.id&&this.editedPointId&&(this.store.delete([this.editedPointId]),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0),this.snappedPointId&&this.lastMouseMoveEvent&&this.updateSnappedCoordinate(this.lastMouseMoveEvent),this.currentId===t.id&&(this.currentCoordinate=0,this.currentId=void 0,this.closingPoints.delete(),"drawing"===this.state&&this.setStarted())}validateFeature(t){return this.validateModeFeature(t,t=>B(t,this.coordinatePrecision))}}const kt={cancel:"Escape",finish:"Enter"},_t={start:"crosshair"};class bt extends p{constructor(t){super(t,!0),this.mode="rectangle",this.center=void 0,this.clickCount=0,this.currentRectangleId=void 0,this.keyEvents=kt,this.cursors=_t,this.drawInteraction="click-move",this.drawType=void 0,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.drawInteraction&&(this.drawInteraction=e.drawInteraction)}updateRectangle(t,e){if(1===this.clickCount&&this.center&&this.currentRectangleId){const i=this.store.getGeometryCopy(this.currentRectangleId).coordinates[0][0],o={type:"Polygon",coordinates:[[i,[t.lng,i[1]],[t.lng,t.lat],[i[0],t.lat],i]]};if(this.validate&&!this.validate({id:this.currentRectangleId,geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e}).valid)return;this.store.updateGeometry([{id:this.currentRectangleId,geometry:o}])}}close(){const t=this.currentRectangleId;if(t){const e=V(this.store.getGeometryCopy(t));e&&this.store.updateGeometry([{id:t,geometry:e}]),this.store.updateProperty([{id:t,property:s.CURRENTLY_DRAWING,value:void 0}])}this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,this.drawType=void 0,"drawing"===this.state&&this.setStarted(),void 0!==t&&this.onFinish(t,{mode:this.mode,action:"draw"})}beginDrawing(t,e="click"){this.center=[t.lng,t.lat];const[i]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}}]);this.currentRectangleId=i,this.clickCount++,this.drawType=e,this.setDrawing()}moveDrawAllowed(){return"click-move"===this.drawInteraction||"click-move-or-drag"===this.drawInteraction}dragDrawAllowed(){return"click-drag"===this.drawInteraction||"click-move-or-drag"===this.drawInteraction}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(t){this.moveDrawAllowed()&&("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))&&(0===this.clickCount?this.beginDrawing(t):(this.updateRectangle(t,e.Finish),this.close()))}onMouseMove(t){this.updateRectangle(t,e.Provisional)}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onDragStart(t,e){"drawing"!==this.state&&this.allowPointerEvent(this.pointerEvents.onDragStart,t)&&this.dragDrawAllowed()&&(this.beginDrawing(t,"drag"),e(!1))}onDrag(t,i){this.allowPointerEvent(this.pointerEvents.onDrag,t)&&this.dragDrawAllowed()&&"drag"===this.drawType&&this.updateRectangle(t,e.Provisional)}onDragEnd(t,i){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&this.dragDrawAllowed()&&"drag"===this.drawType&&(this.updateRectangle(t,e.Finish),this.close(),i(!0))}cleanUp(){const t=this.currentRectangleId;this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,this.drawType=void 0,"drawing"===this.state&&this.setStarted(),void 0!==t&&this.store.delete([t])}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return"Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r,i):i}validateFeature(t){return this.validateModeFeature(t,t=>G(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentRectangleId===t.id&&(this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,this.drawType=void 0,"drawing"===this.state&&this.setStarted())}}class Nt extends p{constructor(t){if(!t.modeName)throw new Error("Mode name is required for TerraDrawRenderMode");super(t,!0),this.type=c.Render,this.mode="render",this.updateOptions(t)}updateOptions(t){super.updateOptions(t)}registerBehaviors(t){this.mode=t.mode}start(){this.setStarted()}stop(){this.setStopped()}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(t){return{pointColor:this.getHexColorStylingValue(this.styles.pointColor,"#3f97e0",t),pointWidth:this.getNumericStylingValue(this.styles.pointWidth,6,t),pointOutlineColor:this.getHexColorStylingValue(this.styles.pointOutlineColor,"#ffffff",t),pointOutlineWidth:this.getNumericStylingValue(this.styles.pointOutlineWidth,0,t),polygonFillColor:this.getHexColorStylingValue(this.styles.polygonFillColor,"#3f97e0",t),polygonFillOpacity:this.getNumericStylingValue(this.styles.polygonFillOpacity,.3,t),polygonOutlineColor:this.getHexColorStylingValue(this.styles.polygonOutlineColor,"#3f97e0",t),polygonOutlineWidth:this.getNumericStylingValue(this.styles.polygonOutlineWidth,4,t),lineStringWidth:this.getNumericStylingValue(this.styles.lineStringWidth,4,t),lineStringColor:this.getHexColorStylingValue(this.styles.lineStringColor,"#3f97e0",t),zIndex:this.getNumericStylingValue(this.styles.zIndex,0,t)}}validateFeature(t){const e=super.validateFeature(t);if(e.valid){const e=t,i=xt(e,this.coordinatePrecision).valid||B(e,this.coordinatePrecision).valid||dt(e,this.coordinatePrecision).valid;return i?{valid:!0}:{valid:i,reason:"Feature is not a valid Point, Polygon or LineString feature"}}return e}}function Tt(t,e){const i=t,o=e,s=f(i[1]),r=f(o[1]);let n=f(o[0]-i[0]);n>Math.PI&&(n-=2*Math.PI),n<-Math.PI&&(n+=2*Math.PI);const a=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),d=(C(Math.atan2(n,a))+360)%360;return d>180?-(360-d):d}function Wt(t,e,i){let o=e;e<0&&(o=-Math.abs(o));const s=o/m,r=t[0]*Math.PI/180,n=f(t[1]),a=f(i),d=s*Math.cos(a);let h=n+d;Math.abs(h)>Math.PI/2&&(h=h>0?Math.PI-h:-Math.PI-h);const l=Math.log(Math.tan(h/2+Math.PI/4)/Math.tan(n/2+Math.PI/4)),c=Math.abs(l)>1e-11?d/l:Math.cos(n),u=[(180*(r+s*Math.sin(a)/c)/Math.PI+540)%360-180,180*h/Math.PI];return u[0]+=u[0]-t[0]>180?-360:t[0]-u[0]>180?360:0,u}function jt(t,e,i,o,s){const r=o(t[0],t[1]),n=o(e[0],e[1]),{lng:a,lat:d}=s((r.x+n.x)/2,(r.y+n.y)/2);return[P(a,i),P(d,i)]}function Bt(t,e,i){const o=Wt(t,1e3*y(t,e)/2,Tt(t,e));return[P(o[0],i),P(o[1],i)]}function Gt({featureCoords:t,precision:e,unproject:i,project:o,projection:s}){const r=[];for(let n=0;n<t.length-1;n++){let a;if("web-mercator"===s)a=jt(t[n],t[n+1],e,o,i);else{if("globe"!==s)throw new Error("Invalid projection");a=Bt(t[n],t[n+1],e)}r.push(a)}return r}class Rt extends H{constructor(t,e,i){super(t),this.config=void 0,this.selectionPointBehavior=void 0,this.coordinatePointBehavior=void 0,this._midPoints=[],this.config=t,this.selectionPointBehavior=e,this.coordinatePointBehavior=i}get ids(){return this._midPoints.concat()}set ids(t){}insert(t,e,i){const o=this.store.getGeometryCopy(e),{midPointFeatureId:r,midPointSegment:n}=this.store.getPropertiesCopy(e),a=this.store.getGeometryCopy(r),d="Polygon"===a.type?a.coordinates[0]:a.coordinates;d.splice(n+1,0,o.coordinates),a.coordinates="Polygon"===a.type?[d]:d,this.store.updateGeometry([{id:r,geometry:a}]),this.store.getPropertiesCopy(t)[s.COORDINATE_POINT_IDS]&&this.coordinatePointBehavior.createOrUpdate(t),this.store.delete([...this._midPoints,...this.selectionPointBehavior.ids]),this.create(d,r,i),this.selectionPointBehavior.create(d,a.type,r)}create(t,e,i){if(!this.store.has(e))throw new Error("Store does not have feature with this id");this._midPoints=this.store.create(function(t,e,i,o,s,r){return Gt({featureCoords:t,precision:i,project:o,unproject:s,projection:r}).map((t,i)=>({geometry:{type:"Point",coordinates:t},properties:e(i)}))}(t,t=>({mode:this.mode,[o.MID_POINT]:!0,midPointSegment:t,midPointFeatureId:e}),i,this.config.project,this.config.unproject,this.projection))}delete(){this._midPoints.length&&(this.store.delete(this._midPoints),this._midPoints=[])}getUpdated(t){if(0!==this._midPoints.length)return Gt({featureCoords:t,precision:this.coordinatePrecision,project:this.config.project,unproject:this.config.unproject,projection:this.config.projection}).map((t,e)=>({id:this._midPoints[e],geometry:{type:"Point",coordinates:t}}))}}class Ut extends H{constructor(t){super(t),this._selectionPoints=[]}get ids(){return this._selectionPoints.concat()}set ids(t){}create(t,e,i){this._selectionPoints=this.store.create(function(t,e,i){const o=[],s="Polygon"===e?t.length-1:t.length;for(let e=0;e<s;e++)o.push({geometry:{type:"Point",coordinates:t[e]},properties:i(e)});return o}(t,e,t=>({mode:this.mode,index:t,[o.SELECTION_POINT]:!0,[o.SELECTION_POINT_FEATURE_ID]:i})))}delete(){this.ids.length&&(this.store.delete(this.ids),this._selectionPoints=[])}getUpdated(t){if(0!==this._selectionPoints.length)return this._selectionPoints.map((e,i)=>({id:e,geometry:{type:"Point",coordinates:t[i]}}))}getOneUpdated(t,e){if(void 0!==this._selectionPoints[t])return{id:this._selectionPoints[t],geometry:{type:"Point",coordinates:e}}}}function Lt(t,e){let i=!1;for(let n=0,a=e.length;n<a;n++){const a=e[n];for(let e=0,n=a.length,d=n-1;e<n;d=e++)(s=a[e])[1]>(o=t)[1]!=(r=a[d])[1]>o[1]&&o[0]<(r[0]-s[0])*(o[1]-s[1])/(r[1]-s[1])+s[0]&&(i=!i)}var o,s,r;return i}const At=(t,e,i)=>{const o=t=>t*t,s=(t,e)=>o(t.x-e.x)+o(t.y-e.y);return Math.sqrt(((t,e,i)=>{const o=s(e,i);if(0===o)return s(t,e);let r=((t.x-e.x)*(i.x-e.x)+(t.y-e.y)*(i.y-e.y))/o;return r=Math.max(0,Math.min(1,r)),s(t,{x:e.x+r*(i.x-e.x),y:e.y+r*(i.y-e.y)})})(t,e,i))};class Vt extends H{constructor(t,e,i){super(t),this.config=void 0,this.createClickBoundingBox=void 0,this.pixelDistance=void 0,this.config=t,this.createClickBoundingBox=e,this.pixelDistance=i}find(t,e){let i,s,r,n,a=Infinity,d=Infinity,h=Infinity;const l=this.createClickBoundingBox.create(t),c=this.store.search(l);for(let l=0;l<c.length;l++){const u=c[l],p=u.geometry;if("Point"===p.type){if(u.properties.selectionPoint||u.properties.coordinatePoint||!e&&u.properties[o.MID_POINT])continue;const s=this.pixelDistance.measure(t,p.coordinates);u.properties[o.MID_POINT]&&s<this.pointerDistance&&s<h?(h=s,r=u):!u.properties[o.MID_POINT]&&s<this.pointerDistance&&s<a&&(a=s,i=u)}else if("LineString"===p.type){if(i)continue;for(let e=0;e<p.coordinates.length-1;e++){const i=p.coordinates[e],o=p.coordinates[e+1],r=At({x:t.containerX,y:t.containerY},this.project(i[0],i[1]),this.project(o[0],o[1]));r<this.pointerDistance&&r<d&&(d=r,s=u)}}else if("Polygon"===p.type){if(i||s)continue;Lt([t.lng,t.lat],p.coordinates)&&(n=u)}}return{clickedFeature:i||s||n,clickedMidPoint:r}}}class Yt extends H{constructor(t,e,i,o,s){super(t),this.config=void 0,this.featuresAtCursorEvent=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.draggedFeatureId=null,this.dragPosition=void 0,this.config=t,this.featuresAtCursorEvent=e,this.selectionPoints=i,this.midPoints=o,this.coordinatePoints=s}startDragging(t,e){this.draggedFeatureId=e,this.dragPosition=[t.lng,t.lat]}stopDragging(){this.draggedFeatureId=null,this.dragPosition=void 0}isDragging(){return null!==this.draggedFeatureId}canDrag(t,e){const{clickedFeature:i}=this.featuresAtCursorEvent.find(t,!0);return!(!i||i.id!==e)}drag(t,i){if(!this.draggedFeatureId)return;const o=this.store.getGeometryCopy(this.draggedFeatureId),s=[t.lng,t.lat];if("Polygon"===o.type||"LineString"===o.type){let r,n;if("Polygon"===o.type?(r=o.coordinates[0],n=r.length-1):(r=o.coordinates,n=r.length),!this.dragPosition)return!1;for(let t=0;t<n;t++){const e=r[t];let i,o;if("web-mercator"===this.config.projection){const t=S(this.dragPosition[0],this.dragPosition[1]),r=S(s[0],s[1]),n=S(e[0],e[1]),a={x:t.x-r.x,y:t.y-r.y},d=n.x-a.x,h=n.y-a.y,{lng:l,lat:c}=M(d,h);i=l,o=c}else{const t=[this.dragPosition[0]-s[0],this.dragPosition[1]-s[1]];i=e[0]-t[0],o=e[1]-t[1]}if(i=P(i,this.config.coordinatePrecision),o=P(o,this.config.coordinatePrecision),i>180||i<-180||o>90||o<-90)return!1;r[t]=[i,o]}"Polygon"===o.type&&(r[r.length-1]=[r[0][0],r[0][1]]);const a=this.selectionPoints.getUpdated(r)||[],d=this.midPoints.getUpdated(r)||[],h=this.coordinatePoints.getUpdated(this.draggedFeatureId,r)||[];if(i&&!i({type:"Feature",id:this.draggedFeatureId,geometry:o,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:e.Provisional}).valid)return!1;this.store.updateGeometry([{id:this.draggedFeatureId,geometry:o},...a,...d,...h]),this.dragPosition=[t.lng,t.lat]}else"Point"===o.type&&(this.store.updateGeometry([{id:this.draggedFeatureId,geometry:{type:"Point",coordinates:s}}]),this.dragPosition=[t.lng,t.lat])}}class Kt extends H{constructor(t,e,i,o,s,r,n){super(t),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.coordinateSnapping=void 0,this.lineSnapping=void 0,this.draggedCoordinate={id:null,index:-1},this.config=t,this.pixelDistance=e,this.selectionPoints=i,this.midPoints=o,this.coordinatePoints=s,this.coordinateSnapping=r,this.lineSnapping=n}getClosestCoordinate(t,e){const i={dist:Infinity,index:-1,isFirstOrLastPolygonCoord:!1};let o;if("LineString"===e.type)o=e.coordinates;else{if("Polygon"!==e.type)return i;o=e.coordinates[0]}for(let s=0;s<o.length;s++){const r=this.pixelDistance.measure(t,o[s]);if(r<this.pointerDistance&&r<i.dist){const t="Polygon"===e.type&&(s===o.length-1||0===s);i.dist=r,i.index=t?0:s,i.isFirstOrLastPolygonCoord=t}}return i}getDraggableIndex(t,e){const i=this.store.getGeometryCopy(e),o=this.getClosestCoordinate(t,i);return-1===o.index?-1:o.index}snapCoordinate(t,e,i){let o=[t.lng,t.lat];const s=t=>Boolean(t.properties&&t.properties.mode===i.properties.mode&&t.id!==this.draggedCoordinate.id);if(null!=e&&e.toLine){let e;e=this.lineSnapping.getSnappable(t,s).coordinate,e&&(o=e)}if(e.toCoordinate){let e;e=this.coordinateSnapping.getSnappable(t,s).coordinate,e&&(o=e)}if(null!=e&&e.toCustom){let s;s=e.toCustom(t,{currentCoordinate:this.draggedCoordinate.index,currentId:i.id,getCurrentGeometrySnapshot:i.id?()=>this.store.getGeometryCopy(i.id):()=>null,project:this.project,unproject:this.unproject}),s&&(o=s)}return o}drag(t,i,o,s){const r=this.draggedCoordinate.id;if(null===r)return!1;const n=this.draggedCoordinate.index,a=this.store.getGeometryCopy(r),d=this.store.getPropertiesCopy(r),h="LineString"===a.type?a.coordinates:a.coordinates[0],l="Polygon"===a.type&&(n===h.length-1||0===n),c={type:"Feature",id:r,geometry:a,properties:d},u=this.snapCoordinate(t,s,c);if(t.lng>180||t.lng<-180||t.lat>90||t.lat<-90)return!1;if(l){const t=h.length-1;h[0]=u,h[t]=u}else h[n]=u;const p=this.selectionPoints.getOneUpdated(n,u),g=p?[p]:[],y=this.midPoints.getUpdated(h)||[],m=this.coordinatePoints.getUpdated(r,h)||[];return!("Point"!==a.type&&!i&&D({type:"Feature",geometry:a,properties:{}})||o&&!o(c,{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:e.Provisional}).valid||(this.store.updateGeometry([{id:r,geometry:a},...g,...y,...m]),0))}isDragging(){return null!==this.draggedCoordinate.id}startDragging(t,e){this.draggedCoordinate={id:t,index:e}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}}function zt(t){let e=0,i=0,o=0;return("Polygon"===t.geometry.type?t.geometry.coordinates[0].slice(0,-1):t.geometry.coordinates).forEach(t=>{e+=t[0],i+=t[1],o++},!0),[e/o,i/o]}const Ht=(t,e)=>{if(0===e||360===e||-360===e)return t;const i=.017453292519943295*e,o=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(([t,e])=>S(t,e)),s=o.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0});s.x/=o.length,s.y/=o.length;const r=o.map(t=>({x:s.x+(t.x-s.x)*Math.cos(i)-(t.y-s.y)*Math.sin(i),y:s.y+(t.x-s.x)*Math.sin(i)+(t.y-s.y)*Math.cos(i)})).map(({x:t,y:e})=>[M(t,e).lng,M(t,e).lat]);return"Polygon"===t.geometry.type?t.geometry.coordinates[0]=r:t.geometry.coordinates=r,t};function Xt(t){const e=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(t=>{const{x:e,y:i}=S(t[0],t[1]);return[e,i]});return"Polygon"===t.geometry.type?function(t){let e=0,i=0,o=0;const s=t.length;for(let r=0;r<s-1;r++){const[s,n]=t[r],[a,d]=t[r+1],h=s*d-a*n;e+=h,i+=(s+a)*h,o+=(n+d)*h}return e/=2,i/=6*e,o/=6*e,{x:i,y:o}}(e):function(t){const e=t.length;let i=0,o=0;for(let s=0;s<e;s++){const[e,r]=t[s];i+=e,o+=r}return{x:i/e,y:o/e}}(e)}class $t extends H{constructor(t,e,i,o){super(t),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.lastBearing=void 0,this.selectedGeometry=void 0,this.selectedGeometryCentroid=void 0,this.selectedGeometryWebMercatorCentroid=void 0,this.config=t,this.selectionPoints=e,this.midPoints=i,this.coordinatePoints=o}reset(){this.lastBearing=void 0,this.selectedGeometry=void 0,this.selectedGeometryWebMercatorCentroid=void 0,this.selectedGeometryCentroid=void 0}rotate(t,i,o){this.selectedGeometry||(this.selectedGeometry=this.store.getGeometryCopy(i));const s=this.selectedGeometry;if("Polygon"!==s.type&&"LineString"!==s.type)return;const r=[t.lng,t.lat];let n;const a={type:"Feature",geometry:s,properties:{}};if("web-mercator"===this.config.projection){this.selectedGeometryWebMercatorCentroid||(this.selectedGeometryWebMercatorCentroid=Xt(a));const e=S(t.lng,t.lat);if(n=et(this.selectedGeometryWebMercatorCentroid,e),0===n)return;if(!this.lastBearing)return void(this.lastBearing=n);Ht(a,-(this.lastBearing-n))}else{if("globe"!==this.config.projection)throw new Error("Unsupported projection");if(this.selectedGeometryCentroid||(this.selectedGeometryCentroid=zt({type:"Feature",geometry:s,properties:{}})),n=Tt(this.selectedGeometryCentroid,r),!this.lastBearing)return void(this.lastBearing=n+180);!function(t,e){if(0===e||360===e||-360===e)return t;const i=zt(t);("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).forEach(t=>{const o=Tt(i,t)+e,s=function(t,e){t[0]+=t[0]-e[0]>180?-360:e[0]-t[0]>180?360:0;const i=m,o=e[1]*Math.PI/180,s=t[1]*Math.PI/180,r=s-o;let n=Math.abs(t[0]-e[0])*Math.PI/180;n>Math.PI&&(n-=2*Math.PI);const a=Math.log(Math.tan(s/2+Math.PI/4)/Math.tan(o/2+Math.PI/4)),d=Math.abs(a)>1e-11?r/a:Math.cos(o);return Math.sqrt(r*r+d*d*n*n)*i}(i,t),r=Wt(i,s,o);t[0]=r[0],t[1]=r[1]})}(a,-(this.lastBearing-(n+180)))}const d="Polygon"===s.type?s.coordinates[0]:s.coordinates;d.forEach(t=>{t[0]=P(t[0],this.coordinatePrecision),t[1]=P(t[1],this.coordinatePrecision)});const h=this.midPoints.getUpdated(d)||[],l=this.selectionPoints.getUpdated(d)||[],c=this.coordinatePoints.getUpdated(i,d)||[];if(o&&!o({id:i,type:"Feature",geometry:s,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:e.Provisional}))return!1;this.store.updateGeometry([{id:i,geometry:s},...l,...h,...c]),"web-mercator"===this.projection?this.lastBearing=n:"globe"===this.projection&&(this.lastBearing=n+180)}}class qt extends H{constructor(t,e){super(t),this.config=void 0,this.dragCoordinateResizeBehavior=void 0,this.config=t,this.dragCoordinateResizeBehavior=e}scale(t,e,i){if(!this.dragCoordinateResizeBehavior.isDragging()){const i=this.dragCoordinateResizeBehavior.getDraggableIndex(t,e);this.dragCoordinateResizeBehavior.startDragging(e,i)}this.dragCoordinateResizeBehavior.drag(t,"center-fixed",i)}reset(){this.dragCoordinateResizeBehavior.stopDragging()}}function Zt({coordinates:t,originX:e,originY:i,xScale:o,yScale:s}){1===o&&1===s||t.forEach(t=>{const{x:r,y:n}=S(t[0],t[1]),a=e+(r-e)*o,d=i+(n-i)*s,{lng:h,lat:l}=M(a,d);t[0]=h,t[1]=l})}class Jt extends H{constructor(t,e,i,o,s){super(t),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.minimumScale=1e-4,this.draggedCoordinate={id:null,index:-1},this.boundingBoxMaps={opposite:{0:4,1:5,2:6,3:7,4:0,5:1,6:2,7:3}},this.config=t,this.pixelDistance=e,this.selectionPoints=i,this.midPoints=o,this.coordinatePoints=s}getClosestCoordinate(t,e){const i={dist:Infinity,index:-1,isFirstOrLastPolygonCoord:!1};let o;if("LineString"===e.type)o=e.coordinates;else{if("Polygon"!==e.type)return i;o=e.coordinates[0]}for(let s=0;s<o.length;s++){const r=this.pixelDistance.measure(t,o[s]);if(r<this.pointerDistance&&r<i.dist){const t="Polygon"===e.type&&(s===o.length-1||0===s);i.dist=r,i.index=t?0:s,i.isFirstOrLastPolygonCoord=t}}return i}isValidDragWebMercator(t,e,i){switch(t){case 0:if(e<=0||i>=0)return!1;break;case 1:if(i>=0)return!1;break;case 2:if(e>=0||i>=0)return!1;break;case 3:if(e>=0)return!1;break;case 4:if(e>=0||i<=0)return!1;break;case 5:if(i<=0)return!1;break;case 6:if(e<=0||i<=0)return!1;break;case 7:if(e<=0)return!1}return!0}getSelectedFeatureDataWebMercator(){if(!this.draggedCoordinate.id||-1===this.draggedCoordinate.index)return null;const t=this.getFeature(this.draggedCoordinate.id);if(!t)return null;const e=this.getNormalisedCoordinates(t.geometry);return{boundingBox:this.getBBoxWebMercator(e),feature:t,updatedCoords:e,selectedCoordinate:e[this.draggedCoordinate.index]}}centerWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{feature:i,boundingBox:o,updatedCoords:s,selectedCoordinate:r}=e,n=Xt(i);if(!n)return null;const a=S(r[0],r[1]),{closestBBoxIndex:d}=this.getIndexesWebMercator(o,a),h=S(t.lng,t.lat);return this.scaleWebMercator({closestBBoxIndex:d,updatedCoords:s,webMercatorCursor:h,webMercatorSelected:a,webMercatorOrigin:n}),s}centerFixedWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{feature:i,boundingBox:o,updatedCoords:s,selectedCoordinate:r}=e,n=Xt(i);if(!n)return null;const a=S(r[0],r[1]),{closestBBoxIndex:d}=this.getIndexesWebMercator(o,a),h=S(t.lng,t.lat);return this.scaleFixedWebMercator({closestBBoxIndex:d,updatedCoords:s,webMercatorCursor:h,webMercatorSelected:a,webMercatorOrigin:n}),s}scaleFixedWebMercator({closestBBoxIndex:t,webMercatorOrigin:e,webMercatorSelected:i,webMercatorCursor:o,updatedCoords:s}){if(!this.isValidDragWebMercator(t,e.x-o.x,e.y-o.y))return null;let r=A(e,o)/A(e,i);return r<0&&(r=this.minimumScale),Zt({coordinates:s,originX:e.x,originY:e.y,xScale:r,yScale:r}),s}oppositeFixedWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{boundingBox:i,updatedCoords:o,selectedCoordinate:s}=e,r=S(s[0],s[1]),{oppositeBboxIndex:n,closestBBoxIndex:a}=this.getIndexesWebMercator(i,r),d={x:i[n][0],y:i[n][1]},h=S(t.lng,t.lat);return this.scaleFixedWebMercator({closestBBoxIndex:a,updatedCoords:o,webMercatorCursor:h,webMercatorSelected:r,webMercatorOrigin:d}),o}oppositeWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{boundingBox:i,updatedCoords:o,selectedCoordinate:s}=e,r=S(s[0],s[1]),{oppositeBboxIndex:n,closestBBoxIndex:a}=this.getIndexesWebMercator(i,r),d={x:i[n][0],y:i[n][1]},h=S(t.lng,t.lat);return this.scaleWebMercator({closestBBoxIndex:a,updatedCoords:o,webMercatorCursor:h,webMercatorSelected:r,webMercatorOrigin:d}),o}scaleWebMercator({closestBBoxIndex:t,webMercatorOrigin:e,webMercatorSelected:i,webMercatorCursor:o,updatedCoords:s}){const r=e.x-o.x,n=e.y-o.y;if(!this.isValidDragWebMercator(t,r,n))return null;let a=1;0!==r&&1!==t&&5!==t&&(a=1-(e.x-i.x-r)/r);let d=1;return 0!==n&&3!==t&&7!==t&&(d=1-(e.y-i.y-n)/n),this.validateScale(a,d)?(a<0&&(a=this.minimumScale),d<0&&(d=this.minimumScale),this.performWebMercatorScale(s,e.x,e.y,a,d),s):null}getFeature(t){if(null===this.draggedCoordinate.id)return null;const e=this.store.getGeometryCopy(t);return"Polygon"!==e.type&&"LineString"!==e.type?null:{id:t,type:"Feature",geometry:e,properties:{}}}getNormalisedCoordinates(t){return"Polygon"===t.type?t.coordinates[0]:t.coordinates}validateScale(t,e){const i=!isNaN(t)&&e<Number.MAX_SAFE_INTEGER,o=!isNaN(e)&&e<Number.MAX_SAFE_INTEGER;return i&&o}performWebMercatorScale(t,e,i,o,s){t.forEach(t=>{const{x:r,y:n}=S(t[0],t[1]),a=e+(r-e)*o,d=i+(n-i)*s,{lng:h,lat:l}=M(a,d);t[0]=h,t[1]=l})}getBBoxWebMercator(t){const e=[Infinity,Infinity,-Infinity,-Infinity];(t=t.map(t=>{const{x:e,y:i}=S(t[0],t[1]);return[e,i]})).forEach(([t,i])=>{t<e[0]&&(e[0]=t),i<e[1]&&(e[1]=i),t>e[2]&&(e[2]=t),i>e[3]&&(e[3]=i)});const[i,o,s,r]=e;return[[i,r],[(i+s)/2,r],[s,r],[s,r+(o-r)/2],[s,o],[(i+s)/2,o],[i,o],[i,r+(o-r)/2]]}getIndexesWebMercator(t,e){let i,o=Infinity;for(let s=0;s<t.length;s++){const r=A({x:e.x,y:e.y},{x:t[s][0],y:t[s][1]});r<o&&(i=s,o=r)}if(void 0===i)throw new Error("No closest coordinate found");return{oppositeBboxIndex:this.boundingBoxMaps.opposite[i],closestBBoxIndex:i}}isDragging(){return null!==this.draggedCoordinate.id}startDragging(t,e){this.draggedCoordinate={id:t,index:e}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}getDraggableIndex(t,e){const i=this.store.getGeometryCopy(e),o=this.getClosestCoordinate(t,i);return-1===o.index?-1:o.index}drag(t,i,o){if(!this.draggedCoordinate.id)return!1;const s=this.getFeature(this.draggedCoordinate.id);if(!s)return!1;let r=null;if("center"===i?r=this.centerWebMercatorDrag(t):"opposite"===i?r=this.oppositeWebMercatorDrag(t):"center-fixed"===i?r=this.centerFixedWebMercatorDrag(t):"opposite-fixed"===i&&(r=this.oppositeFixedWebMercatorDrag(t)),!r)return!1;for(let t=0;t<r.length;t++){const e=r[t];if(e[0]=P(e[0],this.coordinatePrecision),e[1]=P(e[1],this.coordinatePrecision),!k(e,this.coordinatePrecision))return!1}const n=this.midPoints.getUpdated(r)||[],a=this.selectionPoints.getUpdated(r)||[],d=this.coordinatePoints.getUpdated(s.id,r)||[],h={type:s.geometry.type,coordinates:"Polygon"===s.geometry.type?[r]:r};return!(o&&!o({id:this.draggedCoordinate.id,type:"Feature",geometry:h,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:e.Provisional}).valid||(this.store.updateGeometry([{id:this.draggedCoordinate.id,geometry:h},...a,...n,...d]),0))}}const Qt={deselect:"Escape",delete:"Delete",rotate:["Control","r"],scale:["Control","s"]},te={pointerOver:"move",dragStart:"move",dragEnd:"move",insertMidpoint:"crosshair"};class ee extends g{constructor(t){super(t,!0),this.mode="select",this.allowManualDeselection=!0,this.dragEventThrottle=5,this.dragEventCount=0,this.selected=[],this.flags={},this.keyEvents=Qt,this.cursors=te,this.validations={},this.selectionPoints=void 0,this.midPoints=void 0,this.coordinateSnap=void 0,this.featuresAtMouseEvent=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.dragFeature=void 0,this.dragCoordinate=void 0,this.rotateFeature=void 0,this.scaleFeature=void 0,this.dragCoordinateResizeFeature=void 0,this.coordinatePoints=void 0,this.lineSnap=void 0,this.updateOptions(t)}updateOptions(e){if(super.updateOptions(e),this.cursors=e&&e.cursors?t({},this.cursors,e.cursors):te,null===(null==e?void 0:e.keyEvents)?this.keyEvents={deselect:null,delete:null,rotate:null,scale:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),void 0!==(null==e?void 0:e.dragEventThrottle)&&(this.dragEventThrottle=e.dragEventThrottle),void 0!==(null==e?void 0:e.allowManualDeselection)&&(this.allowManualDeselection=e.allowManualDeselection),null!=e&&e.flags){this.flags=t({},this.flags,e.flags),this.validations={};for(const t in this.flags){const e=this.flags[t].feature;e&&e.validation&&(this.validations[t]=e.validation)}}}selectFeature(t){this.select(t,!1)}setSelecting(){if("started"!==this._state)throw new Error("Mode must be started to move to selecting state");this._state="selecting"}registerBehaviors(t){this.pixelDistance=new q(t),this.clickBoundingBox=new $(t),this.featuresAtMouseEvent=new Vt(t,this.clickBoundingBox,this.pixelDistance),this.selectionPoints=new Ut(t),this.coordinatePoints=new wt(t),this.midPoints=new Rt(t,this.selectionPoints,this.coordinatePoints),this.coordinateSnap=new Z(t,this.pixelDistance,this.clickBoundingBox),this.lineSnap=new yt(t,this.pixelDistance,this.clickBoundingBox),this.rotateFeature=new $t(t,this.selectionPoints,this.midPoints,this.coordinatePoints),this.dragFeature=new Yt(t,this.featuresAtMouseEvent,this.selectionPoints,this.midPoints,this.coordinatePoints),this.dragCoordinate=new Kt(t,this.pixelDistance,this.selectionPoints,this.midPoints,this.coordinatePoints,this.coordinateSnap,this.lineSnap),this.dragCoordinateResizeFeature=new Jt(t,this.pixelDistance,this.selectionPoints,this.midPoints,this.coordinatePoints),this.scaleFeature=new qt(t,this.dragCoordinateResizeFeature)}deselectFeature(){this.deselect()}deselect(){const t=this.selected.filter(t=>this.store.has(t)).map(t=>({id:t,property:o.SELECTED,value:!1}));this.store.updateProperty(t),this.onDeselect(this.selected[0]),this.selected=[],this.selectionPoints.delete(),this.midPoints.delete()}deleteSelected(){this.store.delete(this.selected),this.selected=[]}onRightClick(t){if(!this.selectionPoints.ids.length)return;let i,o=Infinity;if(this.selectionPoints.ids.forEach(e=>{const s=this.store.getGeometryCopy(e),r=this.pixelDistance.measure(t,s.coordinates);r<this.pointerDistance&&r<o&&(o=r,i=this.store.getPropertiesCopy(e))}),!i)return;const s=i.selectionPointFeatureId,r=i.index,n=this.store.getPropertiesCopy(s),a=this.flags[n.mode],d=this.validations[n.mode];if(!(a&&a.feature&&a.feature.coordinates&&a.feature.coordinates.deletable))return;const h=this.store.getGeometryCopy(s);let l;if("Polygon"===h.type){if(l=h.coordinates[0],l.length<=4)return}else if("LineString"===h.type&&(l=h.coordinates,l.length<=2))return;if(!l)return;if("Polygon"!==h.type||0!==r&&r!==l.length-1?l.splice(r,1):(l.shift(),l.pop(),l.push([l[0][0],l[0][1]])),d&&!d({id:s,type:"Feature",geometry:h,properties:n},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Commit}).valid)return;const c=[...this.midPoints.ids,...this.selectionPoints.ids];this.store.delete(c),this.store.updateGeometry([{id:s,geometry:h}]),n.coordinatePointIds&&this.coordinatePoints.createOrUpdate(s),this.selectionPoints.create(l,h.type,s),a&&a.feature&&a.feature.coordinates&&a.feature.coordinates.midpoints&&this.midPoints.create(l,s,this.coordinatePrecision),this.onFinish(s,{action:"deleteCoordinate",mode:this.mode})}select(t,e=!0){if(this.selected[0]===t)return;const{mode:i}=this.store.getPropertiesCopy(t),s=this.flags[i];if(!s||!s.feature)return;const r=this.selected[0];if(r){if(r===t)return;this.deselect()}e&&this.setCursor(this.cursors.pointerOver),this.selected=[t],this.store.updateProperty([{id:t,property:o.SELECTED,value:!0}]),this.onSelect(t);const{type:n,coordinates:a}=this.store.getGeometryCopy(t);if("LineString"!==n&&"Polygon"!==n)return;const d="LineString"===n?a:a[0];d&&s&&s.feature.coordinates&&(this.selectionPoints.create(d,n,t),s.feature.coordinates.midpoints&&this.midPoints.create(d,t,this.coordinatePrecision))}onLeftClick(t){const{clickedFeature:e,clickedMidPoint:i}=this.featuresAtMouseEvent.find(t,this.selected.length>0);if(this.selected.length&&i)return this.midPoints.insert(this.selected[0],i.id,this.coordinatePrecision),void this.onFinish(this.selected[0],{action:"insertMidpoint",mode:this.mode});if(e&&e.id)this.select(e.id,!0);else if(this.selected.length&&this.allowManualDeselection)return void this.deselect()}start(){this.setStarted(),this.setSelecting()}stop(){this.cleanUp(),this.setStarted(),this.setStopped()}onClick(t){"right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)?this.onRightClick(t):"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)&&this.onLeftClick(t)}canScale(t){return this.keyEvents.scale&&this.keyEvents.scale.every(e=>t.heldKeys.includes(e))}canRotate(t){return this.keyEvents.rotate&&this.keyEvents.rotate.every(e=>t.heldKeys.includes(e))}preventDefaultKeyEvent(t){const e=this.canRotate(t),i=this.canScale(t);(e||i)&&t.preventDefault()}onKeyDown(t){this.preventDefaultKeyEvent(t)}onKeyUp(t){if(this.preventDefaultKeyEvent(t),this.keyEvents.delete&&t.key===this.keyEvents.delete){if(!this.selected.length)return;const t=this.selected[0];this.onDeselect(this.selected[0]),this.coordinatePoints.deletePointsByFeatureIds([t]),this.deleteSelected(),this.selectionPoints.delete(),this.midPoints.delete()}else this.keyEvents.deselect&&t.key===this.keyEvents.deselect&&this.cleanUp()}cleanUp(){this.selected.length&&this.deselect()}onDragStart(t,e){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,t))return;if(!this.selected.length)return;const i=this.store.getPropertiesCopy(this.selected[0]),o=this.flags[i.mode];if(!(o&&o.feature&&(o.feature.draggable||o.feature.coordinates&&o.feature.coordinates.draggable||o.feature.coordinates&&o.feature.coordinates.resizable||o.feature.coordinates&&"object"==typeof o.feature.coordinates.midpoints&&o.feature.coordinates.midpoints.draggable)))return;this.dragEventCount=0;const s=this.selected[0],r=this.dragCoordinate.getDraggableIndex(t,s);if(o&&o.feature&&o.feature.coordinates&&(o.feature.coordinates.draggable||o.feature.coordinates.resizable)&&-1!==r)return this.setCursor(this.cursors.dragStart),o.feature.coordinates.resizable?this.dragCoordinateResizeFeature.startDragging(s,r):this.dragCoordinate.startDragging(s,r),void e(!1);if(o&&o.feature&&o.feature.coordinates&&"object"==typeof o.feature.coordinates.midpoints&&o.feature.coordinates.midpoints.draggable){const{clickedMidPoint:i}=this.featuresAtMouseEvent.find(t,this.selected.length>0);if(this.selected.length&&i){this.midPoints.insert(s,i.id,this.coordinatePrecision),this.onFinish(this.selected[0],{action:"insertMidpoint",mode:this.mode});const o=this.dragCoordinate.getDraggableIndex(t,s);return this.dragCoordinate.startDragging(s,o),void e(!1)}}return o&&o.feature&&o.feature.draggable&&this.dragFeature.canDrag(t,s)?(this.setCursor(this.cursors.dragStart),this.dragFeature.startDragging(t,s),void e(!1)):void 0}onDrag(t,e){if(!this.allowPointerEvent(this.pointerEvents.onDrag,t))return;const i=this.selected[0];if(!i)return;const o=this.store.getPropertiesCopy(i),s=this.flags[o.mode],r=!0===(s&&s.feature&&s.feature.selfIntersectable);if(this.dragEventCount++,this.dragEventCount%this.dragEventThrottle==0)return;const n=this.validations[o.mode];if(s&&s.feature&&s.feature.rotateable&&this.canRotate(t))return e(!1),void this.rotateFeature.rotate(t,i,n);if(s&&s.feature&&s.feature.scaleable&&this.canScale(t))return e(!1),void this.scaleFeature.scale(t,i,n);if(this.dragCoordinateResizeFeature.isDragging()&&s.feature&&s.feature.coordinates&&s.feature.coordinates.resizable){if("globe"===this.projection)throw new Error("Globe is currently unsupported projection for resizable");return e(!1),void this.dragCoordinateResizeFeature.drag(t,s.feature.coordinates.resizable,n)}if(this.dragCoordinate.isDragging()){var a;const e=null==(a=s.feature)||null==(a=a.coordinates)?void 0:a.snappable;let i={toCoordinate:!1};return!0===e?i={toCoordinate:!0}:"object"==typeof e&&(i=e),void this.dragCoordinate.drag(t,r,n,i)}this.dragFeature.isDragging()?this.dragFeature.drag(t,n):e(!0)}onDragEnd(t,e){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&(this.setCursor(this.cursors.dragEnd),this.dragCoordinate.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinate"}):this.dragFeature.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragFeature"}):this.dragCoordinateResizeFeature.isDragging()&&this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinateResize"}),this.dragCoordinate.stopDragging(),this.dragFeature.stopDragging(),this.dragCoordinateResizeFeature.stopDragging(),this.rotateFeature.reset(),this.scaleFeature.reset(),e(!0))}onMouseMove(t){if(!this.selected.length)return void this.setCursor("unset");if(this.dragFeature.isDragging())return;let e=!1;this.midPoints.ids.forEach(i=>{if(e)return;const o=this.store.getGeometryCopy(i);this.pixelDistance.measure(t,o.coordinates)<this.pointerDistance&&(e=!0)});let i=!1;if(this.selectionPoints.ids.forEach(o=>{const s=this.store.getGeometryCopy(o);this.pixelDistance.measure(t,s.coordinates)<this.pointerDistance&&(e=!1,i=!0)}),e)return void this.setCursor(this.cursors.insertMidpoint);const{clickedFeature:o}=this.featuresAtMouseEvent.find(t,!0);this.setCursor(this.selected.length>0&&(o&&o.id===this.selected[0]||i)?this.cursors.pointerOver:"unset")}styleFeature(e){const n=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});if(e.properties.mode===this.mode&&"Point"===e.geometry.type){if(e.properties[o.SELECTION_POINT])return n.pointColor=this.getHexColorStylingValue(this.styles.selectionPointColor,n.pointColor,e),n.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectionPointOutlineColor,n.pointOutlineColor,e),n.pointWidth=this.getNumericStylingValue(this.styles.selectionPointWidth,n.pointWidth,e),n.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectionPointOutlineWidth,2,e),n.zIndex=30,n;if(e.properties[o.MID_POINT])return n.pointColor=this.getHexColorStylingValue(this.styles.midPointColor,n.pointColor,e),n.pointOutlineColor=this.getHexColorStylingValue(this.styles.midPointOutlineColor,n.pointOutlineColor,e),n.pointWidth=this.getNumericStylingValue(this.styles.midPointWidth,4,e),n.pointOutlineWidth=this.getNumericStylingValue(this.styles.midPointOutlineWidth,2,e),n.zIndex=50,n}else if(e.properties[o.SELECTED]){if("Point"===e.geometry.type&&e.properties[s.MARKER])return n.markerUrl=this.getUrlStylingValue(this.styles.selectedMarkerUrl,i,e),n.markerHeight=this.getNumericStylingValue(this.styles.selectedMarkerHeight,40,e),n.markerWidth=this.getNumericStylingValue(this.styles.selectedMarkerWidth,32,e),n;if("Polygon"===e.geometry.type)return n.polygonFillColor=this.getHexColorStylingValue(this.styles.selectedPolygonColor,n.polygonFillColor,e),n.polygonOutlineWidth=this.getNumericStylingValue(this.styles.selectedPolygonOutlineWidth,n.polygonOutlineWidth,e),n.polygonOutlineColor=this.getHexColorStylingValue(this.styles.selectedPolygonOutlineColor,n.polygonOutlineColor,e),n.polygonFillOpacity=this.getNumericStylingValue(this.styles.selectedPolygonFillOpacity,n.polygonFillOpacity,e),n.zIndex=r,n;if("LineString"===e.geometry.type)return n.lineStringColor=this.getHexColorStylingValue(this.styles.selectedLineStringColor,n.lineStringColor,e),n.lineStringWidth=this.getNumericStylingValue(this.styles.selectedLineStringWidth,n.lineStringWidth,e),n.zIndex=r,n;if("Point"===e.geometry.type)return n.pointWidth=this.getNumericStylingValue(this.styles.selectedPointWidth,n.pointWidth,e),n.pointColor=this.getHexColorStylingValue(this.styles.selectedPointColor,n.pointColor,e),n.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectedPointOutlineColor,n.pointOutlineColor,e),n.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectedPointOutlineWidth,n.pointOutlineWidth,e),n.zIndex=r,n}return n}afterFeatureUpdated(t){if(this.selected.length&&t.id===this.selected[0]){var e,i;const o=this.flags[t.properties.mode];if(null==o||null==(e=o.feature)||!e.coordinates)return;const s=t.geometry.type,r=t.id;let n;if(this.selectionPoints.delete(),this.midPoints.delete(),"Polygon"===s)n=t.geometry.coordinates[0];else{if("LineString"!==s)return;n=t.geometry.coordinates}this.selectionPoints.create(n,s,r),null!=o&&null!=(i=o.feature)&&null!=(i=i.coordinates)&&i.midpoints&&this.midPoints.create("Polygon"===s?t.geometry.coordinates[0]:t.geometry.coordinates,r,this.coordinatePrecision)}}}class ie extends p{constructor(...t){super(...t),this.type=c.Static,this.mode="static"}start(){}stop(){}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(){return t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0})}}function oe(t,e,i,o,s){for(;o>i;){if(o-i>600){const r=o-i+1,n=e-i+1,a=Math.log(r),d=.5*Math.exp(2*a/3),h=.5*Math.sqrt(a*d*(r-d)/r)*(n-r/2<0?-1:1);oe(t,e,Math.max(i,Math.floor(e-n*d/r+h)),Math.min(o,Math.floor(e+(r-n)*d/r+h)),s)}const r=t[e];let n=i,a=o;for(se(t,i,e),s(t[o],r)>0&&se(t,i,o);n<a;){for(se(t,n,a),n++,a--;s(t[n],r)<0;)n++;for(;s(t[a],r)>0;)a--}0===s(t[i],r)?se(t,i,a):(a++,se(t,a,o)),a<=e&&(i=a+1),e<=a&&(o=a-1)}}function se(t,e,i){const o=t[e];t[e]=t[i],t[i]=o}function re(t,e){ne(t,0,t.children.length,e,t)}function ne(t,e,i,o,s){s||(s=ye([])),s.minX=Infinity,s.minY=Infinity,s.maxX=-Infinity,s.maxY=-Infinity;for(let r=e;r<i;r++){const e=t.children[r];ae(s,t.leaf?o(e):e)}return s}function ae(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function de(t,e){return t.minX-e.minX}function he(t,e){return t.minY-e.minY}function le(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function ce(t){return t.maxX-t.minX+(t.maxY-t.minY)}function ue(t,e){const i=Math.max(t.minX,e.minX),o=Math.max(t.minY,e.minY),s=Math.min(t.maxX,e.maxX),r=Math.min(t.maxY,e.maxY);return Math.max(0,s-i)*Math.max(0,r-o)}function pe(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function ge(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function ye(t){return{children:t,height:1,leaf:!0,minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity}}function me(t,e,i,o,s){const r=[e,i];for(;r.length;){if((i=r.pop())-(e=r.pop())<=o)continue;const n=e+Math.ceil((i-e)/o/2)*o;oe(t,n,e,i,s),r.push(e,n,n,i)}}class fe{constructor(t){this._maxEntries=void 0,this._minEntries=void 0,this.data=void 0,this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}search(t){let e=this.data;const i=[];if(!ge(t,e))return i;const o=this.toBBox,s=[];for(;e;){for(let r=0;r<e.children.length;r++){const n=e.children[r],a=e.leaf?o(n):n;ge(t,a)&&(e.leaf?i.push(n):pe(t,a)?this._all(n,i):s.push(n))}e=s.pop()}return i}collides(t){let e=this.data;if(ge(t,e)){const i=[];for(;e;){for(let o=0;o<e.children.length;o++){const s=e.children[o],r=e.leaf?this.toBBox(s):s;if(ge(t,r)){if(e.leaf||pe(t,r))return!0;i.push(s)}}e=i.pop()}}return!1}load(t){if(t.length<this._minEntries){for(let e=0;e<t.length;e++)this.insert(t[e]);return}let e=this._build(t.slice(),0,t.length-1,0);if(this.data.children.length)if(this.data.height===e.height)this._splitRoot(this.data,e);else{if(this.data.height<e.height){const t=this.data;this.data=e,e=t}this._insert(e,this.data.height-e.height-1,!0)}else this.data=e}insert(t){this._insert(t,this.data.height-1)}clear(){this.data=ye([])}remove(t){let e=this.data;const i=this.toBBox(t),o=[],s=[];let r,n,a=!1;for(;e||o.length;){if(e||(e=o.pop(),n=o[o.length-1],r=s.pop(),a=!0),e.leaf){const i=e.children.indexOf(t);-1!==i&&(e.children.splice(i,1),o.push(e),this._condense(o))}a||e.leaf||!pe(e,i)?n?(r++,e=n.children[r],a=!1):e=null:(o.push(e),s.push(r),r=0,n=e,e=e.children[0])}}toBBox(t){return t}compareMinX(t,e){return t.minX-e.minX}compareMinY(t,e){return t.minY-e.minY}_all(t,e){const i=[];for(;t;)t.leaf?e.push(...t.children):i.push(...t.children),t=i.pop();return e}_build(t,e,i,o){const s=i-e+1;let r,n=this._maxEntries;if(s<=n)return r=ye(t.slice(e,i+1)),re(r,this.toBBox),r;o||(o=Math.ceil(Math.log(s)/Math.log(n)),n=Math.ceil(s/Math.pow(n,o-1))),r=ye([]),r.leaf=!1,r.height=o;const a=Math.ceil(s/n),d=a*Math.ceil(Math.sqrt(n));me(t,e,i,d,this.compareMinX);for(let s=e;s<=i;s+=d){const e=Math.min(s+d-1,i);me(t,s,e,a,this.compareMinY);for(let i=s;i<=e;i+=a){const s=Math.min(i+a-1,e);r.children.push(this._build(t,i,s,o-1))}}return re(r,this.toBBox),r}_chooseSubtree(t,e,i,o){for(;o.push(e),!e.leaf&&o.length-1!==i;){let i,o=Infinity,n=Infinity;for(let a=0;a<e.children.length;a++){const d=e.children[a],h=le(d),l=(s=t,r=d,(Math.max(r.maxX,s.maxX)-Math.min(r.minX,s.minX))*(Math.max(r.maxY,s.maxY)-Math.min(r.minY,s.minY))-h);l<n?(n=l,o=h<o?h:o,i=d):l===n&&h<o&&(o=h,i=d)}e=i||e.children[0]}var s,r;return e}_insert(t,e,i){const o=i?t:this.toBBox(t),s=[],r=this._chooseSubtree(o,this.data,e,s);for(r.children.push(t),ae(r,o);e>=0&&s[e].children.length>this._maxEntries;)this._split(s,e),e--;this._adjustParentBBoxes(o,s,e)}_split(t,e){const i=t[e],o=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,o);const r=this._chooseSplitIndex(i,s,o),n=ye(i.children.splice(r,i.children.length-r));n.height=i.height,n.leaf=i.leaf,re(i,this.toBBox),re(n,this.toBBox),e?t[e-1].children.push(n):this._splitRoot(i,n)}_splitRoot(t,e){this.data=ye([t,e]),this.data.height=t.height+1,this.data.leaf=!1,re(this.data,this.toBBox)}_chooseSplitIndex(t,e,i){let o,s=Infinity,r=Infinity;for(let n=e;n<=i-e;n++){const e=ne(t,0,n,this.toBBox),a=ne(t,n,i,this.toBBox),d=ue(e,a),h=le(e)+le(a);d<s?(s=d,o=n,r=h<r?h:r):d===s&&h<r&&(r=h,o=n)}return o||i-e}_chooseSplitAxis(t,e,i){const o=t.leaf?this.compareMinX:de,s=t.leaf?this.compareMinY:he;this._allDistMargin(t,e,i,o)<this._allDistMargin(t,e,i,s)&&t.children.sort(o)}_allDistMargin(t,e,i,o){t.children.sort(o);const s=this.toBBox,r=ne(t,0,e,s),n=ne(t,i-e,i,s);let a=ce(r)+ce(n);for(let o=e;o<i-e;o++){const e=t.children[o];ae(r,t.leaf?s(e):e),a+=ce(r)}for(let o=i-e-1;o>=e;o--){const e=t.children[o];ae(n,t.leaf?s(e):e),a+=ce(n)}return a}_adjustParentBBoxes(t,e,i){for(let o=i;o>=0;o--)ae(e[o],t)}_condense(t){for(let e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children,e.splice(e.indexOf(t[i]),1)):this.clear():re(t[i],this.toBBox)}}class ve{constructor(t){this.tree=void 0,this.idToNode=void 0,this.nodeToId=void 0,this.tree=new fe(t&&t.maxEntries?t.maxEntries:9),this.idToNode=new Map,this.nodeToId=new Map}setMaps(t,e){this.idToNode.set(t.id,e),this.nodeToId.set(e,t.id)}toBBox(t){const e=[],i=[];let o;if("Polygon"===t.geometry.type)o=t.geometry.coordinates[0];else if("LineString"===t.geometry.type)o=t.geometry.coordinates;else{if("Point"!==t.geometry.type)throw new Error("Not a valid feature to turn into a bounding box");o=[t.geometry.coordinates]}for(let t=0;t<o.length;t++)i.push(o[t][1]),e.push(o[t][0]);const s=Math.min(...i),r=Math.max(...i);return{minX:Math.min(...e),minY:s,maxX:Math.max(...e),maxY:r}}insert(t){if(this.idToNode.get(String(t.id)))throw new Error("Feature already exists");const e=this.toBBox(t);this.setMaps(t,e),this.tree.insert(e)}load(t){const e=[],i=new Set;t.forEach(t=>{const o=this.toBBox(t);if(this.setMaps(t,o),i.has(String(t.id)))throw new Error(`Duplicate feature ID found ${t.id}`);i.add(String(t.id)),e.push(o)}),this.tree.load(e)}update(t){this.remove(t.id);const e=this.toBBox(t);this.setMaps(t,e),this.tree.insert(e)}remove(t){const e=this.idToNode.get(t);if(!e)throw new Error(`${t} not inserted into the spatial index`);this.tree.remove(e)}clear(){this.tree.clear()}search(t){return this.tree.search(this.toBBox(t)).map(t=>this.nodeToId.get(t))}collides(t){return this.tree.collides(this.toBBox(t))}}const Ce={getId:()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)}),isValidId:t=>"string"==typeof t&&36===t.length},Pe={target:"geometry"},Ie={target:"properties"};class xe{constructor(t){this.idStrategy=void 0,this.tracked=void 0,this.spatialIndex=void 0,this.store=void 0,this._onChange=()=>{},this.store={},this.spatialIndex=new ve,this.tracked=!t||!1!==t.tracked,this.idStrategy=t&&t.idStrategy?t.idStrategy:Ce}clone(t){return JSON.parse(JSON.stringify(t))}getId(){return this.idStrategy.getId()}has(t){return Boolean(this.store[t])}load(t,e,i,o){if(0===t.length)return[];let s=this.clone(t);const r=[],n=[];s=s.filter(t=>{null==t.id&&(t.id=this.idStrategy.getId());const i=t.id;if(e){const o=e(t);if(!o.valid)return r.push({id:i,valid:!1,reason:o.reason}),!1}if(this.tracked){if(t.properties.createdAt){if(!d(t.properties.createdAt))return r.push({id:t.id,valid:!1,reason:"createdAt is not a valid numeric timestamp"}),!1}else t.properties.createdAt=+new Date;if(t.properties.updatedAt){if(!d(t.properties.updatedAt))return r.push({id:t.id,valid:!1,reason:"updatedAt is not a valid numeric timestamp"}),!1}else t.properties.updatedAt=+new Date}return this.has(i)?(r.push({id:i,valid:!1,reason:`Feature already exists with this id: ${i}`}),!1):(this.store[i]=t,n.push(t),r.push({id:i,valid:!0}),!0)}),this.spatialIndex.load(s);const a=n.map(({id:t})=>t);return a.length>0&&(this._onChange(a,"create",o),i&&n.forEach(t=>{i(t)})),r}search(t,e){const i=this.spatialIndex.search(t).map(t=>this.store[t]);return this.clone(e?i.filter(e):i)}registerOnChange(t){this._onChange=(e,i,o)=>{t(e,i,o)}}getGeometryCopy(t){const e=this.store[t];if(!e)throw new Error(`No feature with this id (${t}), can not get geometry copy`);return this.clone(e.geometry)}getPropertiesCopy(t){const e=this.store[t];if(!e)throw new Error(`No feature with this id (${t}), can not get properties copy`);return this.clone(e.properties)}updateProperty(e,i){const o=new Set;e.forEach(({id:t,property:e,value:i})=>{const s=this.store[t];if(!s)throw new Error(`No feature with this (${t}), can not update geometry`);s.properties[e]!==i&&(o.add(t),void 0===i?delete s.properties[e]:s.properties[e]=i,this.tracked&&(s.properties.updatedAt=+new Date))}),this._onChange&&o.size>0&&this._onChange([...o],"update",i?t({},i,Ie):Ie)}updateGeometry(e,i){const o=new Set;e.forEach(({id:t,geometry:e})=>{o.add(t);const i=this.store[t];if(!i)throw new Error(`No feature with this (${t}), can not update geometry`);i.geometry=this.clone(e),this.spatialIndex.update(i),this.tracked&&(i.properties.updatedAt=+new Date)}),this._onChange&&o.size>0&&this._onChange([...o],"update",i?t({},i,Pe):Pe)}create(e,i){const o=[];return e.forEach(({geometry:e,properties:i})=>{let s,r=t({},i);this.tracked&&(s=+new Date,i?(r.createdAt="number"==typeof i.createdAt?i.createdAt:s,r.updatedAt="number"==typeof i.updatedAt?i.updatedAt:s):r={createdAt:s,updatedAt:s});const n=this.getId(),a={id:n,type:"Feature",geometry:e,properties:r};this.store[n]=a,this.spatialIndex.insert(a),o.push(n)}),this._onChange&&this._onChange([...o],"create",i),o}delete(t,e){t.forEach(t=>{if(!this.store[t])throw new Error(`No feature with id ${t}, can not delete`);delete this.store[t],this.spatialIndex.remove(t)}),this._onChange&&this._onChange([...t],"delete",e)}copy(t){return this.clone(this.store[t])}copyAll(){return this.clone(Object.keys(this.store).map(t=>this.store[t]))}copyAllWhere(t){return this.clone(Object.keys(this.store).map(t=>this.store[t]).filter(e=>e.properties&&t(e.properties)))}clear(){this.store={},this.spatialIndex.clear()}size(){return Object.keys(this.store).length}}function Ee(t){const e=t.coordinates;let i=0;if(e&&e.length>0){i+=Math.abs(we(e[0]));for(let t=1;t<e.length;t++)i-=Math.abs(we(e[t]))}return i}const Se=20294876564838.72,Me=Math.PI/180;function we(t){const e=t.length;if(e<=2)return 0;let i=0,o=0;for(;o<e;)i+=(t[o+2>=e?(o+2)%e:o+2][0]*Me-t[o][0]*Me)*Math.sin(t[o+1===e?0:o+1][1]*Me),o++;return i*Se}const Fe="Feature is smaller than the minimum area",De=(t,e)=>"Polygon"!==t.geometry.type?{valid:!1,reason:h}:Ee(t.geometry)<e?{valid:!1,reason:Fe}:{valid:!0},Oe=(t,e)=>"Polygon"!==t.geometry.type?{valid:!1,reason:h}:Ee(t.geometry)>e?{valid:!1,reason:"Feature is larger than the maximum area"}:{valid:!0},ke="Feature is not a Polygon or LineString",_e="Feature intersects itself",be=t=>"Polygon"!==t.geometry.type&&"LineString"!==t.geometry.type?{valid:!1,reason:ke}:D(t)?{valid:!1,reason:_e}:{valid:!0};function Ne(t,e,i){const o=et(t,e);let s=et(e,i)-o;return s<0&&(s+=360),180-Math.abs(s-90-90)}const Te={cancel:"Escape",finish:"Enter"},We={start:"crosshair",close:"pointer"};class je extends p{constructor(t){super(t,!0),this.mode="angled-rectangle",this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=Te,this.cursors=We,this.mouseMove=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents))}close(){if(void 0===this.currentId)return;this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}]);const t=this.currentId;this.currentCoordinate=0,this.currentId=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(t,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){if(this.mouseMove=!0,this.setCursor(this.cursors.start),void 0===this.currentId||0===this.currentCoordinate)return;const i=this.store.getGeometryCopy(this.currentId).coordinates[0];let o;if(1===this.currentCoordinate){const e=1/Math.pow(10,this.coordinatePrecision-1),s=Math.max(1e-6,e);o=[i[0],[t.lng,t.lat],[t.lng,t.lat-s],i[0]]}else if(2===this.currentCoordinate){const e=i[0],s=i[1],r=jt(e,s,this.coordinatePrecision,this.project,this.unproject),n=S(e[0],e[1]),a=S(r[0],r[1]),d=S(s[0],s[1]),h=S(t.lng,t.lat),l=A(h,n)<A(h,d),c=Ne(n,a,h),u=l?90-c:Ne(n,a,h)-90,p=A(a,h),g=Math.cos(f(u))*p,y=et(n,d)+("right"===function(t,e,i){const o=(i.x-e.x)*(t.y-e.y)-(i.y-e.y)*(t.x-e.x);return o>1e-10?"left":o<-1e-10?"right":"left"}(n,d,h)?-90:90),m=Q(n,g,y),v=Q(d,g,y),C=M(m.x,m.y),I=M(v.x,v.y);o=[i[0],i[1],[P(I.lng,this.coordinatePrecision),P(I.lat,this.coordinatePrecision)],[P(C.lng,this.coordinatePrecision),P(C.lat,this.coordinatePrecision)],i[0]]}o&&this.updatePolygonGeometry(this.currentId,o,e.Provisional)}updatePolygonGeometry(t,e,i){const o={type:"Polygon",coordinates:[e]};return!(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}).valid||(this.store.updateGeometry([{id:t,geometry:o}]),0))}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))if(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,0===this.currentCoordinate){const[e]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}}]);this.currentId=e,this.currentCoordinate++,this.setDrawing()}else if(1===this.currentCoordinate&&this.currentId){const i=this.store.getGeometryCopy(this.currentId);if(at([t.lng,t.lat],i.coordinates[0][0]))return;if(!this.updatePolygonGeometry(this.currentId,[i.coordinates[0][0],[t.lng,t.lat],[t.lng,t.lat],i.coordinates[0][0]],e.Commit))return;this.currentCoordinate++}else 2===this.currentCoordinate&&this.currentId&&this.close()}onKeyUp(t){if(t.key===this.keyEvents.cancel)this.cleanUp();else if(t.key===this.keyEvents.finish){if(this.currentCoordinate<2)return void this.cleanUp();this.close()}}onKeyDown(){}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentId&&this.store.delete([this.currentId])}catch(t){}this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted()}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return e.properties.mode===this.mode&&"Polygon"===e.geometry.type&&(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r),i}validateFeature(t){return this.validateModeFeature(t,t=>G(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentId===t.id&&(this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted())}}function Be(t,e,i){return(e.x-t.x)*(i.y-t.y)-(e.y-t.y)*(i.x-t.x)<=0}const Ge={cancel:"Escape",finish:"Enter"},Re={start:"crosshair",close:"pointer"};class Ue extends p{constructor(t){super(t,!0),this.mode="sector",this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=Ge,this.direction=void 0,this.arcPoints=64,this.cursors=Re,this.mouseMove=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.arcPoints&&(this.arcPoints=e.arcPoints)}close(){if(void 0===this.currentId)return;const t=V(this.store.getGeometryCopy(this.currentId));t&&this.store.updateGeometry([{id:this.currentId,geometry:t}]),this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}]);const e=this.currentId;this.currentCoordinate=0,this.currentId=void 0,this.direction=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){if(this.mouseMove=!0,this.setCursor(this.cursors.start),void 0===this.currentId||0===this.currentCoordinate)return;const i=this.store.getGeometryCopy(this.currentId).coordinates[0];let o;if(1===this.currentCoordinate){const e=1/Math.pow(10,this.coordinatePrecision-1),s=Math.max(1e-6,e);o=[i[0],[t.lng,t.lat],[t.lng,t.lat-s],i[0]]}else if(2===this.currentCoordinate){const e=i[0],s=i[1],r=[t.lng,t.lat],n=S(e[0],e[1]),a=S(s[0],s[1]),d=S(r[0],r[1]);if(void 0===this.direction){const t=Be(n,a,d);this.direction=t?"clockwise":"anticlockwise"}const h=A(n,a),l=et(n,a),c=et(n,d),u=this.arcPoints,p=[e],g=it(l),y=it(c);let m;"anticlockwise"===this.direction?(m=y-g,m<0&&(m+=360)):(m=g-y,m<0&&(m+=360));const f=("anticlockwise"===this.direction?1:-1)*m/u;p.push(s);for(let t=0;t<=u;t++){const e=Q(n,h,g+t*f),{lng:i,lat:o}=M(e.x,e.y),s=[P(i,this.coordinatePrecision),P(o,this.coordinatePrecision)];s[0]!==p[p.length-1][0]&&s[1]!==p[p.length-1][1]&&p.push(s)}p.push(e),o=[...p]}o&&this.updatePolygonGeometry(this.currentId,o,e.Provisional)}updatePolygonGeometry(t,e,i){const o={type:"Polygon",coordinates:[e]};return!(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}).valid||(this.store.updateGeometry([{id:t,geometry:o}]),0))}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))if(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,0===this.currentCoordinate){const[e]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}}]);this.currentId=e,this.currentCoordinate++,this.setDrawing()}else if(1===this.currentCoordinate&&this.currentId){const i=this.store.getGeometryCopy(this.currentId);if(at([t.lng,t.lat],i.coordinates[0][0]))return;if(!this.updatePolygonGeometry(this.currentId,[i.coordinates[0][0],[t.lng,t.lat],[t.lng,t.lat],i.coordinates[0][0]],e.Commit))return;this.currentCoordinate++}else 2===this.currentCoordinate&&this.currentId&&this.close()}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentId&&this.store.delete([this.currentId])}catch(t){}this.currentId=void 0,this.direction=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted()}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return e.properties.mode===this.mode&&"Polygon"===e.geometry.type&&(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r),i}validateFeature(t){return this.validateModeFeature(t,t=>G(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentId===t.id&&(this.currentId=void 0,this.direction=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted())}}const Le={cancel:"Escape",finish:"Enter"},Ae={start:"crosshair",close:"pointer"};class Ve extends p{constructor(t){super(t,!0),this.mode="sensor",this.currentCoordinate=0,this.currentId=void 0,this.currentInitialArcId=void 0,this.currentStartingPointId=void 0,this.keyEvents=Le,this.direction=void 0,this.arcPoints=64,this.cursors=Ae,this.mouseMove=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.arcPoints&&(this.arcPoints=e.arcPoints)}close(){if(void 0===this.currentStartingPointId)return;const t=this.currentStartingPointId,e=this.currentInitialArcId,i=this.currentId;if(t&&this.store.delete([t]),e&&this.store.delete([e]),this.currentId){const t=V(this.store.getGeometryCopy(this.currentId));t&&this.store.updateGeometry([{id:this.currentId,geometry:t}]),this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}])}this.currentCoordinate=0,this.currentStartingPointId=void 0,this.currentInitialArcId=void 0,this.currentId=void 0,this.direction=void 0,"drawing"===this.state&&this.setStarted(),i&&this.onFinish(i,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){if(this.mouseMove=!0,this.setCursor(this.cursors.start),void 0!==this.currentInitialArcId&&void 0!==this.currentStartingPointId&&0!==this.currentCoordinate)if(2===this.currentCoordinate){const i=this.store.getGeometryCopy(this.currentInitialArcId).coordinates,o=this.store.getGeometryCopy(this.currentStartingPointId).coordinates,s=i[0],r=[t.lng,t.lat],n=S(s[0],s[1]),a=S(r[0],r[1]),d=S(o[0],o[1]),h=A(d,n);if(void 0===this.direction){const t=Be(d,n,a);this.direction=t?"clockwise":"anticlockwise"}const l=et(d,n),c=et(d,a),u=this.arcPoints,p=[s],g=it(l),y=it(c);let m;"anticlockwise"===this.direction?(m=y-g,m<0&&(m+=360)):(m=g-y,m<0&&(m+=360));const f=("anticlockwise"===this.direction?1:-1)*m/u;for(let t=0;t<=u;t++){const e=Q(d,h,g+t*f),{lng:i,lat:o}=M(e.x,e.y),s=[P(i,this.coordinatePrecision),P(o,this.coordinatePrecision)];s[0]!==p[p.length-1][0]&&s[1]!==p[p.length-1][1]&&p.push(s)}this.updateLineStringGeometry(this.currentInitialArcId,p,e.Provisional)}else if(3===this.currentCoordinate){const i=this.store.getGeometryCopy(this.currentInitialArcId).coordinates;if(i.length<2)return;if(!this.direction)return;const o=this.store.getGeometryCopy(this.currentStartingPointId).coordinates,r=i[0],n=i[i.length-1],a=S(t.lng,t.lat),d=S(r[0],r[1]),h=S(n[0],n[1]),l=S(o[0],o[1]),c=A(l,d),u=A(l,a)<c?d:a,p=et(l,a),g=et(l,d),y=et(l,h),m=it(g),f=it(y),v=it(p);if(this.notInSector({normalizedCursor:v,normalizedStart:m,normalizedEnd:f,direction:this.direction}))return;const C=this.getDeltaBearing(this.direction,m,f),I=this.arcPoints,x=("anticlockwise"===this.direction?1:-1)*C/I,E=A(l,u),w=[];for(let t=0;t<=I;t++){const e=Q(l,E,m+t*x),{lng:o,lat:s}=M(e.x,e.y),r=[P(o,this.coordinatePrecision),P(s,this.coordinatePrecision)];r[0]!==i[i.length-1][0]&&r[1]!==i[i.length-1][1]&&w.unshift(r)}i.push(...w),i.push(i[0]),this.currentId?this.updatePolygonGeometry(this.currentId,i,e.Provisional):[this.currentId]=this.store.create([{geometry:{type:"Polygon",coordinates:[i]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}}])}}updateLineStringGeometry(t,e,i){const o={type:"LineString",coordinates:e};return!(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}).valid||(this.store.updateGeometry([{id:t,geometry:o}]),0))}updatePolygonGeometry(t,e,i){const o={type:"Polygon",coordinates:[e]};return!(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}).valid||(this.store.updateGeometry([{id:t,geometry:o}]),0))}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t))if(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,0===this.currentCoordinate){const[e]=this.store.create([{geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:{mode:this.mode}}]);this.currentStartingPointId=e,this.currentCoordinate++,this.setDrawing()}else if(1===this.currentCoordinate&&this.currentStartingPointId){const[e]=this.store.create([{geometry:{type:"LineString",coordinates:[[t.lng,t.lat],[t.lng,t.lat]]},properties:{mode:this.mode}}]);this.currentInitialArcId=e,this.currentCoordinate++}else 2===this.currentCoordinate&&this.currentStartingPointId?this.currentCoordinate++:3===this.currentCoordinate&&this.currentStartingPointId&&this.close()}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentStartingPointId&&this.store.delete([this.currentStartingPointId]),this.currentInitialArcId&&this.store.delete([this.currentInitialArcId]),this.currentId&&this.store.delete([this.currentId])}catch(t){}this.currentStartingPointId=void 0,this.direction=void 0,this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted()}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return e.properties.mode===this.mode&&("Polygon"===e.geometry.type?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=r):"LineString"===e.geometry.type?(i.lineStringColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.zIndex=r):"Point"===e.geometry.type&&(i.pointColor=this.getHexColorStylingValue(this.styles.centerPointColor,i.pointColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.centerPointWidth,i.pointWidth,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.centerPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.centerPointOutlineWidth,i.pointOutlineWidth,e),i.zIndex=20)),i}validateFeature(t){return this.validateModeFeature(t,t=>G(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentId===t.id&&(this.currentStartingPointId&&this.store.delete([this.currentStartingPointId]),this.currentInitialArcId&&this.store.delete([this.currentInitialArcId]),this.currentStartingPointId=void 0,this.direction=void 0,this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted())}getDeltaBearing(t,e,i){let o;return"anticlockwise"===t?(o=i-e,o<0&&(o+=360)):(o=e-i,o<0&&(o+=360)),o}notInSector({normalizedCursor:t,normalizedStart:e,normalizedEnd:i,direction:o}){return"clockwise"===o?e<=i?t>=e&&t<=i:t>=e||t<=i:e>=i?t<=e&&t>=i:t<=e||t>=i}}class Ye{constructor({name:t,callback:e,unregister:i,register:o}){this.name=void 0,this.callback=void 0,this.registered=!1,this.register=void 0,this.unregister=void 0,this.name=t,this.register=()=>{this.registered||(this.registered=!0,o(e))},this.unregister=()=>{this.register&&(this.registered=!1,i(e))},this.callback=e}}var Ke={__proto__:null,GeoJSONStore:xe,TerraDrawBaseDrawMode:p,TerraDrawBaseSelectMode:g,TerraDrawBaseAdapter:class{constructor(t){this._nextKeyUpIsContextMenu=!1,this._lastPointerDownEventTarget=void 0,this._ignoreMismatchedPointerEvents=!1,this._minPixelDragDistance=void 0,this._minPixelDragDistanceDrawing=void 0,this._minPixelDragDistanceSelecting=void 0,this._lastDrawEvent=void 0,this._coordinatePrecision=void 0,this._heldKeys=new Set,this._listeners=[],this._dragState="not-dragging",this._currentModeCallbacks=void 0,this._ignoreMismatchedPointerEvents="boolean"==typeof t.ignoreMismatchedPointerEvents&&t.ignoreMismatchedPointerEvents,this._minPixelDragDistance="number"==typeof t.minPixelDragDistance?t.minPixelDragDistance:1,this._minPixelDragDistanceSelecting="number"==typeof t.minPixelDragDistanceSelecting?t.minPixelDragDistanceSelecting:1,this._minPixelDragDistanceDrawing="number"==typeof t.minPixelDragDistanceDrawing?t.minPixelDragDistanceDrawing:8,this._coordinatePrecision="number"==typeof t.coordinatePrecision?t.coordinatePrecision:9}getButton(t){return-1===t.button?"neither":0===t.button?"left":1===t.button?"middle":2===t.button?"right":"neither"}getMapElementXYPosition(t){const e=this.getMapEventElement(),{left:i,top:o}=e.getBoundingClientRect();return{containerX:t.clientX-i,containerY:t.clientY-o}}getDrawEventFromEvent(t,e=!1){const i=this.getLngLatFromEvent(t);if(!i)return null;const{lng:o,lat:s}=i,{containerX:r,containerY:n}=this.getMapElementXYPosition(t),a=this.getButton(t),d=Array.from(this._heldKeys);return{lng:P(o,this._coordinatePrecision),lat:P(s,this._coordinatePrecision),containerX:r,containerY:n,button:a,heldKeys:d,isContextMenu:e}}register(t){this._currentModeCallbacks=t,this._listeners=this.getAdapterListeners(),this._listeners.forEach(t=>{t.register()})}getCoordinatePrecision(){return this._coordinatePrecision}getAdapterListeners(){return[new Ye({name:"pointerdown",callback:t=>{if(!this._currentModeCallbacks)return;if(!t.isPrimary)return;const e=this.getDrawEventFromEvent(t);e&&(this._dragState="pre-dragging",this._lastDrawEvent=e,this._lastPointerDownEventTarget=t.target?t.target:void 0)},register:t=>{this.getMapEventElement().addEventListener("pointerdown",t)},unregister:t=>{this.getMapEventElement().removeEventListener("pointerdown",t)}}),new Ye({name:"pointermove",callback:t=>{if(!this._currentModeCallbacks)return;if(!t.isPrimary)return;t.preventDefault();const e=this.getDrawEventFromEvent(t);if(e)if("not-dragging"===this._dragState)this._currentModeCallbacks.onMouseMove(e),this._lastDrawEvent=e;else if("pre-dragging"===this._dragState){if(!this._lastDrawEvent)return;const t={x:this._lastDrawEvent.containerX,y:this._lastDrawEvent.containerY},i={x:e.containerX,y:e.containerY},o=this._currentModeCallbacks.getState(),s=A(t,i);let r=!1;if(r="drawing"===o?s<this._minPixelDragDistanceDrawing:"selecting"===o?s<this._minPixelDragDistanceSelecting:s<this._minPixelDragDistance,r)return;this._nextKeyUpIsContextMenu=!1,this._dragState="dragging",this._currentModeCallbacks.onDragStart(e,t=>{this.setDraggability.bind(this)(t)})}else"dragging"===this._dragState&&this._currentModeCallbacks.onDrag(e,t=>{this.setDraggability.bind(this)(t)})},register:t=>{this.getMapEventElement().addEventListener("pointermove",t)},unregister:t=>{this.getMapEventElement().removeEventListener("pointermove",t)}}),new Ye({name:"contextmenu",callback:t=>{this._currentModeCallbacks&&(t.preventDefault(),this._nextKeyUpIsContextMenu=!0)},register:t=>{this.getMapEventElement().addEventListener("contextmenu",t)},unregister:t=>{this.getMapEventElement().removeEventListener("contextmenu",t)}}),new Ye({name:"pointerup",callback:t=>{if(!this._currentModeCallbacks)return;if(t.target!==this.getMapEventElement())return;if(this._ignoreMismatchedPointerEvents&&this._lastPointerDownEventTarget!==t.target)return;if(this._lastPointerDownEventTarget=void 0,!t.isPrimary)return;const e=this.getDrawEventFromEvent(t);e&&("dragging"===this._dragState?this._currentModeCallbacks.onDragEnd(e,t=>{this.setDraggability.bind(this)(t)}):"not-dragging"!==this._dragState&&"pre-dragging"!==this._dragState||(this._nextKeyUpIsContextMenu&&(e.isContextMenu=!0,this._nextKeyUpIsContextMenu=!1),this._currentModeCallbacks.onClick(e)),this._dragState="not-dragging",this.setDraggability(!0))},register:t=>{this.getMapEventElement().addEventListener("pointerup",t)},unregister:t=>{this.getMapEventElement().removeEventListener("pointerup",t)}}),new Ye({name:"keyup",callback:t=>{this._currentModeCallbacks&&(this._heldKeys.delete(t.key),this._currentModeCallbacks.onKeyUp({key:t.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>t.preventDefault()}))},register:t=>{this.getMapEventElement().addEventListener("keyup",t)},unregister:t=>{this.getMapEventElement().removeEventListener("keyup",t)}}),new Ye({name:"keydown",callback:t=>{this._currentModeCallbacks&&(this._heldKeys.add(t.key),this._currentModeCallbacks.onKeyDown({key:t.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>t.preventDefault()}))},register:t=>{this.getMapEventElement().addEventListener("keydown",t)},unregister:t=>{this.getMapEventElement().removeEventListener("keydown",t)}})]}unregister(){this._listeners.forEach(t=>{t.unregister()}),this.clear(),this._currentModeCallbacks=void 0,this._lastDrawEvent=void 0,this._lastPointerDownEventTarget=void 0,this._nextKeyUpIsContextMenu=!1}},getDefaultStyling:()=>({polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0}),SELECT_PROPERTIES:o};const ze={ValidationReasonFeatureNotPoint:Ct,ValidationReasonFeatureInvalidCoordinates:Pt,ValidationReasonFeatureInvalidCoordinatePrecision:It,ValidationReasonFeatureNotPolygon:h,ValidationReasonFeatureHasHoles:N,ValidationReasonFeatureLessThanFourCoordinates:T,ValidationReasonFeatureHasInvalidCoordinates:W,ValidationReasonFeatureCoordinatesNotClosed:j,ValidationReasonFeatureNotPolygonOrLineString:ke,ValidationReasonFeatureSelfIntersects:_e,ValidationReasonFeatureLessThanMinSize:Fe,ValidationReasonModeMismatch:l},He={cancel:"Escape",finish:"Enter"},Xe={start:"crosshair",close:"pointer"};class $e extends p{constructor(t){super(t,!0),this.mode="freehand-linestring",this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,this.minDistance=20,this.keyEvents=He,this.cursors=Xe,this.preventNewFeature=!1,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.minDistance&&(this.minDistance=e.minDistance),null===(null==e?void 0:e.keyEvents)?this.keyEvents={cancel:null,finish:null}:null!=e&&e.keyEvents&&(this.keyEvents=t({},this.keyEvents,e.keyEvents)),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors))}close(){if(void 0===this.currentId)return;this.currentId&&this.store.updateProperty([{id:this.currentId,property:s.CURRENTLY_DRAWING,value:void 0}]);const t=this.currentId;if(this.validate&&t){const i=this.store.getGeometryCopy(t);if(!this.validate({type:"Feature",id:t,geometry:i,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid)return}this.closingPointId&&this.store.delete([this.closingPointId]),this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(t,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onMouseMove(t){if(void 0===this.currentId||!1===this.startingClick)return void this.setCursor(this.cursors.start);const i=this.store.getGeometryCopy(this.currentId),o=i.coordinates.length-2,[s,r]=i.coordinates[o],{x:n,y:a}=this.project(s,r),d=A({x:n,y:a},{x:t.containerX,y:t.containerY}),[h,l]=i.coordinates[i.coordinates.length-1],{x:c,y:u}=this.project(h,l),p=A({x:c,y:u},{x:t.containerX,y:t.containerY});if(this.setCursor(p<this.pointerDistance?this.cursors.close:this.cursors.start),d<this.minDistance)return;const g={type:"LineString",coordinates:[...i.coordinates,[t.lng,t.lat]]};this.validate&&!this.validate({type:"Feature",id:this.currentId,geometry:g,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Provisional}).valid||(this.store.updateGeometry([{id:this.currentId,geometry:g}]),this.closingPointId&&this.store.updateGeometry([{id:this.closingPointId,geometry:{type:"Point",coordinates:[t.lng,t.lat]}}]))}onClick(t){if("right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)){if(this.preventNewFeature)return;if(!1===this.startingClick){const[e,i]=this.store.create([{geometry:{type:"LineString",coordinates:[[t.lng,t.lat],[t.lng,t.lat]]},properties:{mode:this.mode,[s.CURRENTLY_DRAWING]:!0}},{geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:{mode:this.mode,[s.CLOSING_POINT]:!0}}]);return this.currentId=e,this.closingPointId=i,this.startingClick=!0,void("drawing"!==this.state&&this.setDrawing())}this.close()}}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&!0===this.startingClick&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentId,e=this.closingPointId;this.closingPointId=void 0,this.currentId=void 0,this.startingClick=!1,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]),void 0!==e&&this.store.delete([e])}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});return"Feature"===e.type&&"LineString"===e.geometry.type&&e.properties.mode===this.mode?(i.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,i.lineStringColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,i.lineStringWidth,e),i.zIndex=r,i):"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode?(i.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),i.zIndex=50,i):i}validateFeature(t){return this.validateModeFeature(t,t=>dt(t,this.coordinatePrecision))}afterFeatureUpdated(t){this.currentId===t.id&&(this.closingPointId&&this.store.delete([this.closingPointId]),this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0)}}function qe(t){if(null===t)return!0;if("boolean"==typeof t)return!0;if("string"==typeof t)return!0;if(void 0===t)return!1;if("number"==typeof t)return Number.isFinite(t);if("bigint"==typeof t)return!1;if("symbol"==typeof t)return!1;if("function"==typeof t)return!1;if(t instanceof RegExp)return!1;if(t instanceof Map)return!1;if(t instanceof Set)return!1;if(t instanceof Date)return!1;if("object"==typeof t&&null!==t&&!Array.isArray(t)){const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&null!==e)return!1}if(ArrayBuffer.isView(t)&&!(t instanceof DataView))return!1;if(Array.isArray(t))for(const e of t)if(!qe(e))return!1;return"object"==typeof t&&Object.keys(t).every(e=>"string"==typeof e&&qe(t[e]))}const Ze={create:"crosshair",dragStart:"grabbing",dragEnd:"crosshair"};class Je extends p{constructor(t){super(t,!0),this.mode="marker",this.cursors=Ze,this.editable=!1,this.editedFeatureId=void 0,this.markerUrl=void 0,this.markerHeight=void 0,this.markerWidth=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.updateOptions(t)}updateOptions(e){super.updateOptions(e),null!=e&&e.cursors&&(this.cursors=t({},this.cursors,e.cursors)),null!=e&&e.editable&&(this.editable=e.editable)}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(t){"right"===t.button&&this.allowPointerEvent(this.pointerEvents.rightClick,t)||t.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,t)?this.onRightClick(t):"left"===t.button&&this.allowPointerEvent(this.pointerEvents.leftClick,t)&&this.onLeftClick(t)}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){this.editedFeatureId=void 0}onDragStart(t,e){if(this.allowPointerEvent(this.pointerEvents.onDragStart,t)){if(this.editable){const e=this.getNearestPointFeature(t);this.editedFeatureId=null==e?void 0:e.id}this.editedFeatureId&&(this.setCursor(this.cursors.dragStart),e(!1))}}onDrag(t,i){this.allowPointerEvent(this.pointerEvents.onDrag,t)&&void 0!==this.editedFeatureId&&(this.validate&&!this.validate({type:"Feature",geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:this.store.getPropertiesCopy(this.editedFeatureId)},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid||(this.store.updateGeometry([{id:this.editedFeatureId,geometry:{type:"Point",coordinates:[t.lng,t.lat]}}]),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!0}])))}onDragEnd(t,e){this.allowPointerEvent(this.pointerEvents.onDragEnd,t)&&void 0!==this.editedFeatureId&&(this.onFinish(this.editedFeatureId,{mode:this.mode,action:"edit"}),this.setCursor(this.cursors.dragEnd),this.store.updateProperty([{id:this.editedFeatureId,property:s.EDITED,value:!1}]),this.editedFeatureId=void 0,e(!0))}registerBehaviors(t){this.pixelDistance=new q(t),this.clickBoundingBox=new $(t)}styleFeature(e){const o=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0});var s,r,n;return"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode&&(o.zIndex=30,o.markerHeight=this.getNumericStylingValue(null==(s=this.styles)?void 0:s.markerHeight,40,e),o.markerWidth=this.getNumericStylingValue(null==(r=this.styles)?void 0:r.markerWidth,32,e),o.markerUrl=this.getUrlStylingValue(null==(n=this.styles)?void 0:n.markerUrl,i,e)),o}validateFeature(t){return this.validateModeFeature(t,t=>xt(t,this.coordinatePrecision))}onLeftClick(t){const i={type:"Point",coordinates:[t.lng,t.lat]},o={mode:this.mode,[s.MARKER]:!0};if(this.validate&&!this.validate({type:"Feature",geometry:i,properties:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e.Finish}).valid)return;const[r]=this.store.create([{geometry:i,properties:o}]);this.onFinish(r,{mode:this.mode,action:"draw"})}onRightClick(t){if(!this.editable)return;const e=this.getNearestPointFeature(t);e&&this.store.delete([e.id])}getNearestPointFeature(t){const e=this.clickBoundingBox.create(t),i=this.store.search(e);let o,s=Infinity;for(let e=0;e<i.length;e++){const r=i[e];if("Point"!==r.geometry.type||r.properties.mode!==this.mode)continue;const n=this.pixelDistance.measure(t,r.geometry.coordinates);n>s||n>this.pointerDistance||(s=n,o=r)}return o}afterFeatureUpdated(t){this.editedFeatureId===t.id&&(this.editedFeatureId=void 0,this.setCursor(this.cursors.create))}}class Qe{constructor(e){this._modes=void 0,this._mode=void 0,this._adapter=void 0,this._enabled=!1,this._store=void 0,this._eventListeners=void 0,this._instanceSelectMode=void 0,this._adapter=e.adapter,this._mode=new ie;const i=new Set,o=e.modes.reduce((t,e)=>{if(i.has(e.mode))throw new Error(`There is already a ${e.mode} mode provided`);return i.add(e.mode),t[e.mode]=e,t},{}),s=Object.keys(o);if(0===s.length)throw new Error("No modes provided");s.forEach(t=>{if(o[t].type===c.Select){if(this._instanceSelectMode)throw new Error("only one type of select mode can be provided");this._instanceSelectMode=t}}),this._modes=t({},o,{static:this._mode}),this._eventListeners={change:[],select:[],deselect:[],finish:[],ready:[]},this._store=new xe({tracked:!!e.tracked,idStrategy:e.idStrategy?e.idStrategy:void 0});const r=t=>{const e=[],i=this._store.copyAll().filter(i=>!t.includes(i.id)||(e.push(i),!1));return{changed:e,unchanged:i}},n=(t,e)=>{this._enabled&&this._eventListeners.finish.forEach(i=>{i(t,e)})},a=(t,e,i)=>{if(!this._enabled)return;this._eventListeners.change.forEach(o=>{o(t,e,i)});const{changed:o,unchanged:s}=r(t);"create"===e?this._adapter.render({created:o,deletedIds:[],unchanged:s,updated:[]},this.getModeStyles()):"update"===e?this._adapter.render({created:[],deletedIds:[],unchanged:s,updated:o},this.getModeStyles()):"delete"===e?this._adapter.render({created:[],deletedIds:t,unchanged:s,updated:[]},this.getModeStyles()):"styling"===e&&this._adapter.render({created:[],deletedIds:[],unchanged:s,updated:[]},this.getModeStyles())},d=t=>{if(!this._enabled)return;this._eventListeners.select.forEach(e=>{e(t)});const{changed:e,unchanged:i}=r([t]);this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:e},this.getModeStyles())},h=t=>{if(!this._enabled)return;this._eventListeners.deselect.forEach(t=>{t()});const{changed:e,unchanged:i}=r([t]);e&&this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:e},this.getModeStyles())};Object.keys(this._modes).forEach(t=>{this._modes[t].register({mode:t,store:this._store,setCursor:this._adapter.setCursor.bind(this._adapter),project:this._adapter.project.bind(this._adapter),unproject:this._adapter.unproject.bind(this._adapter),setDoubleClickToZoom:this._adapter.setDoubleClickToZoom.bind(this._adapter),onChange:a,onSelect:d,onDeselect:h,onFinish:n,coordinatePrecision:this._adapter.getCoordinatePrecision()})})}checkEnabled(){if(!this._enabled)throw new Error("Terra Draw is not enabled")}getModeStyles(){const t={};return Object.keys(this._modes).forEach(e=>{t[e]=t=>this._instanceSelectMode&&t.properties[o.SELECTED]?this._modes[this._instanceSelectMode].styleFeature.bind(this._modes[this._instanceSelectMode])(t):this._modes[e].styleFeature.bind(this._modes[e])(t)}),t}featuresAtLocation({lng:t,lat:e},i){const r=i&&void 0!==i.pointerDistance?i.pointerDistance:30,n=!i||void 0===i.ignoreSelectFeatures||i.ignoreSelectFeatures,a=!(!i||void 0===i.ignoreCoordinatePoints)&&i.ignoreCoordinatePoints,d=!(!i||void 0===i.ignoreCurrentlyDrawing)&&i.ignoreCurrentlyDrawing,h=!(!i||void 0===i.ignoreClosingPoints)&&i.ignoreClosingPoints,l=!(!i||void 0===i.ignoreSnappingPoints)&&i.ignoreSnappingPoints,c=this._adapter.unproject.bind(this._adapter),u=this._adapter.project.bind(this._adapter),p=u(t,e),g=X({unproject:c,point:p,pointerDistance:r});return this._store.search(g).filter(c=>{if(n&&(c.properties[o.MID_POINT]||c.properties[o.SELECTION_POINT]))return!1;if(a&&c.properties[s.COORDINATE_POINT])return!1;if(h&&c.properties[s.CLOSING_POINT])return!1;if(d&&c.properties[s.CURRENTLY_DRAWING])return!1;if(l&&c.properties[s.SNAPPING_POINT])return!1;if("Point"===c.geometry.type){const t=c.geometry.coordinates,e=u(t[0],t[1]);return A(p,e)<r}if("LineString"===c.geometry.type){const t=c.geometry.coordinates;for(let e=0;e<t.length-1;e++){const i=t[e],o=t[e+1];if(At(p,u(i[0],i[1]),u(o[0],o[1]))<r)return!0}return!1}if(Lt([t,e],c.geometry.coordinates))return!0;if(null!=i&&i.includePolygonsWithinPointerDistance){const t=c.geometry.coordinates;for(const e of t)for(let t=0;t<e.length-1;t++){const i=e[t],o=e[t+1],s=u(i[0],i[1]),n=u(o[0],o[1]);if(At(p,s,n)<r)return!0}}return!1}).map(o=>{if(null==i||!i.addClosestCoordinateInfoToProperties)return o;let s;if("Polygon"===o.geometry.type)s=o.geometry.coordinates[0].slice(0,-1);else{if("LineString"!==o.geometry.type)return o;s=o.geometry.coordinates}let r,n=-1,a=Infinity;for(let t=0;t<s.length;t++){const e=s[t],i=A(u(e[0],e[1]),p);i<a&&(n=t,a=i,r=e)}return o.properties.closestCoordinateIndexToEvent=n,o.properties.closestCoordinatePixelDistanceToEvent=a,o.properties.closestCoordinateDistanceKmToEvent=y(r,[t,e]),o})}getSelectModeOrThrow(){const t=this.getSelectMode({switchToSelectMode:!0});if(!t)throw new Error("No select mode defined in instance");return t}getSelectMode({switchToSelectMode:t}){if(this.checkEnabled(),!this._instanceSelectMode)return null;const e=this.getMode();return t&&e!==this._instanceSelectMode&&this.setMode(this._instanceSelectMode),this._modes[this._instanceSelectMode]}isGuidanceFeature(t){return Boolean(t.properties[o.MID_POINT]||t.properties[o.SELECTION_POINT]||t.properties[s.COORDINATE_POINT]||t.properties[s.SNAPPING_POINT])}setModeStyles(t,e){if(this.checkEnabled(),!this._modes[t])throw new Error("No mode with this name present");this._modes[t].styles=e}updateModeOptions(t,e){if(this.checkEnabled(),!this._modes[t])throw new Error("No mode with this name present");this._modes[t].updateOptions(e)}getSnapshot(){return this._store.copyAll()}getSnapshotFeature(t){if(this._store.has(t))return this._store.copy(t)}clear(){this.checkEnabled(),this._adapter.clear()}get enabled(){return this._enabled}set enabled(t){throw new Error("Enabled is read only")}getMode(){return this._mode.mode}getModeState(){return this._mode.state}setMode(t){if(this.checkEnabled(),!this._modes[t])throw new Error("No mode with this name present");this._mode.stop(),this._mode=this._modes[t],this._mode.start()}removeFeatures(t){this.checkEnabled();const e=[];t.forEach(t=>{if(!this._store.has(t))throw new Error(`No feature with id ${t}, can not delete`);const i=this._store.copy(t);i.properties[o.SELECTED]&&this.deselectFeature(t),i.properties[s.COORDINATE_POINT_IDS]&&e.push(...i.properties[s.COORDINATE_POINT_IDS])}),this._store.delete([...t,...e],{origin:"api"})}selectFeature(t){this.getSelectModeOrThrow().selectFeature(t)}deselectFeature(t){this.getSelectModeOrThrow().deselectFeature(t)}getFeatureId(){return this._store.getId()}hasFeature(t){return this._store.has(t)}checkIsReservedProperty(t){return![...Object.values(o),...Object.values(s)].includes(t)}updateFeatureProperties(t,e){if(!this._store.has(t))throw new Error(`No feature with id ${t} present in store`);const i=this._store.copy(t);if(this.isGuidanceFeature(i))throw new Error("Guidance features are not allowed to be updated directly.");const o=i.properties.mode;if(!this._modes[o])throw new Error(`No mode with name ${o} present in instance`);const s=Object.entries(e);s.forEach(([t,e])=>{if(!this.checkIsReservedProperty(t))throw new Error(`You are trying to update a reserved property name: ${t}. Please choose another name.`);if(void 0!==e&&!qe(e))throw new Error(`Invalid JSON value provided for property ${t}`)}),this._store.updateProperty(s.map(([t,e])=>({id:i.id,property:t,value:e})),{origin:"api"})}updateFeatureGeometry(e,i){if(!this._store.has(e))throw new Error(`No feature with id ${e} present in store`);const s=this._store.copy(e);if(this.isGuidanceFeature(s))throw new Error("Guidance features are not allowed to be updated directly.");if(!(s&&i&&i.type&&i.coordinates))throw new Error("Invalid geometry provided");if(i.type!==s.geometry.type)throw new Error(`Geometry type mismatch: expected ${s.geometry.type}, got ${i.type}`);const r=s.properties.mode,n=this._modes[r];if(!n)throw new Error(`No mode with name ${r} present in instance`);const a=t({},s,{geometry:i}),d=n.validateFeature(a);if(!d.valid)throw new Error(`Feature validation failed: ${d.reason||"Unknown reason"}`);if(this._store.updateGeometry([{id:s.id,geometry:i}],{origin:"api"}),n.afterFeatureUpdated){n.afterFeatureUpdated(a);const t=a.properties[o.SELECTED],e=this.getSelectMode({switchToSelectMode:!1});e&&t&&e.afterFeatureUpdated(a)}}transformFeatureGeometry(t,e){if(!this._store.has(t))throw new Error(`No feature with id ${t} present in store`);let i=this._store.copy(t);if(this.isGuidanceFeature(i))throw new Error("Guidance features are not allowed to be updated directly.");const s=i.properties.mode,r=this._modes[s];if(!r)throw new Error(`No mode with name ${s} present in instance`);let n;if("Polygon"===i.geometry.type)n=i.geometry.coordinates[0];else{if("LineString"!==i.geometry.type)throw new Error(`Feature geometry type ${i.geometry.type} is not supported for transformation`);n=i.geometry.coordinates}if("web-mercator"!=e.projection)throw new Error(`Projection ${e.projection} is not currently supported for transformation`);if("scale"===e.type){const{x:t,y:i}=S(e.origin[0],e.origin[1]);Zt({coordinates:n,originX:t,originY:i,xScale:e.options.xScale||1,yScale:e.options.yScale||1})}else"rotate"===e.type&&(i=Ht(i,e.options.angle||0),n="Polygon"===i.geometry.type?i.geometry.coordinates[0]:i.geometry.coordinates);if(n=n.map(t=>[P(t[0],this._adapter.getCoordinatePrecision()),P(t[1],this._adapter.getCoordinatePrecision())]),i.geometry.coordinates="Polygon"===i.geometry.type?[n]:n,this._store.updateGeometry([{id:i.id,geometry:i.geometry}],{origin:"api"}),r.afterFeatureUpdated){r.afterFeatureUpdated(i);const t=i.properties[o.SELECTED],e=this.getSelectMode({switchToSelectMode:!1});e&&t&&e.afterFeatureUpdated(i)}}addFeatures(t){return this.checkEnabled(),0===t.length?[]:this._store.load(t,t=>{if(a(t)){const e=t.properties.mode,i=this._modes[e];if(!i)return{id:t.id,valid:!1,reason:`${e} mode is not in the list of instantiated modes`};const o=i.validateFeature.bind(i)(t);return{id:t.id,valid:o.valid,reason:o.reason?o.reason:o.valid?void 0:"Feature is invalid"}}return{id:t.id,valid:!1,reason:"Mode property does not exist"}},t=>{if(a(t)){const e=this._modes[t.properties.mode];e&&e.afterFeatureAdded&&e.afterFeatureAdded(t)}},{origin:"api"})}start(){this._enabled||(this._enabled=!0,this._adapter.register({onReady:()=>{this._eventListeners.ready.forEach(t=>{t()})},getState:()=>this._mode.state,onClick:t=>{this._mode.onClick(t)},onMouseMove:t=>{this._mode.onMouseMove(t)},onKeyDown:t=>{this._mode.onKeyDown(t)},onKeyUp:t=>{this._mode.onKeyUp(t)},onDragStart:(t,e)=>{this._mode.onDragStart(t,e)},onDrag:(t,e)=>{this._mode.onDrag(t,e)},onDragEnd:(t,e)=>{this._mode.onDragEnd(t,e)},onClear:()=>{this._mode.cleanUp(),this._store.clear()}}))}getFeaturesAtLngLat(t,e){const{lng:i,lat:o}=t;return this.featuresAtLocation({lng:i,lat:o},e)}getFeaturesAtPointerEvent(t,e){const i=this._adapter.getLngLatFromEvent.bind(this._adapter)(t);return null===i?[]:this.featuresAtLocation(i,e)}stop(){this._enabled&&(this._enabled=!1,this._adapter.unregister())}on(t,e){const i=this._eventListeners[t];i.includes(e)||i.push(e)}off(t,e){const i=this._eventListeners[t];i.includes(e)&&i.splice(i.indexOf(e),1)}}export{Qe as TerraDraw,je as TerraDrawAngledRectangleMode,L as TerraDrawCircleMode,Ke as TerraDrawExtend,$e as TerraDrawFreehandLineStringMode,z as TerraDrawFreehandMode,vt as TerraDrawLineStringMode,Je as TerraDrawMarkerMode,St as TerraDrawPointMode,Ot as TerraDrawPolygonMode,bt as TerraDrawRectangleMode,Nt as TerraDrawRenderMode,Ue as TerraDrawSectorMode,ee as TerraDrawSelectMode,Ve as TerraDrawSensorMode,Oe as ValidateMaxAreaSquareMeters,De as ValidateMinAreaSquareMeters,be as ValidateNotSelfIntersecting,ze as ValidationReasons};
2
2
  //# sourceMappingURL=terra-draw.modern.js.map