terra-draw 0.0.1-alpha.8 → 1.0.0-beta.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.
Files changed (119) hide show
  1. package/.devcontainer/Dockerfile +8 -0
  2. package/.devcontainer/devcontainer.json +27 -0
  3. package/.devcontainer/post-create.sh +16 -0
  4. package/README.md +23 -13
  5. package/dist/adapters/arcgis-maps-sdk.adapter.d.ts +106 -0
  6. package/dist/adapters/google-maps.adapter.d.ts +90 -39
  7. package/dist/adapters/leaflet.adapter.d.ts +99 -33
  8. package/dist/adapters/mapbox-gl.adapter.d.ts +91 -37
  9. package/dist/adapters/maplibre-gl.adapter.d.ts +72 -0
  10. package/dist/adapters/openlayers.adapter.d.ts +120 -0
  11. package/dist/common.d.ts +118 -98
  12. package/dist/geometry/boolean/is-valid-coordinate.d.ts +4 -0
  13. package/dist/geometry/boolean/point-in-polygon.d.ts +2 -2
  14. package/dist/geometry/boolean/self-intersects.d.ts +2 -2
  15. package/dist/geometry/centroid.d.ts +2 -2
  16. package/dist/geometry/coordinates-identical.d.ts +2 -2
  17. package/dist/geometry/get-coordinates-as-points.d.ts +6 -6
  18. package/dist/geometry/get-midpoints.d.ts +14 -7
  19. package/dist/geometry/helpers.d.ts +4 -4
  20. package/dist/geometry/limit-decimal-precision.d.ts +1 -1
  21. package/dist/geometry/measure/area.d.ts +2 -0
  22. package/dist/geometry/measure/bearing.d.ts +9 -0
  23. package/dist/geometry/measure/destination.d.ts +2 -0
  24. package/dist/geometry/measure/haversine-distance.d.ts +2 -2
  25. package/dist/geometry/measure/pixel-distance-to-line.d.ts +10 -10
  26. package/dist/geometry/measure/pixel-distance.d.ts +7 -7
  27. package/dist/geometry/measure/rhumb-bearing.d.ts +2 -2
  28. package/dist/geometry/measure/rhumb-destination.d.ts +2 -2
  29. package/dist/geometry/measure/rhumb-distance.d.ts +2 -2
  30. package/dist/geometry/measure/slice-along.d.ts +2 -0
  31. package/dist/geometry/midpoint-coordinate.d.ts +4 -2
  32. package/dist/geometry/project/web-mercator.d.ts +20 -0
  33. package/dist/geometry/shape/create-bbox.d.ts +10 -0
  34. package/dist/geometry/shape/create-circle.d.ts +13 -7
  35. package/dist/geometry/shape/great-circle-coordinates.d.ts +2 -0
  36. package/dist/geometry/shape/web-mercator-distortion.d.ts +2 -0
  37. package/dist/geometry/transform/rotate.d.ts +9 -2
  38. package/dist/geometry/transform/scale.d.ts +9 -2
  39. package/dist/geometry/web-mercator-centroid.d.ts +11 -0
  40. package/dist/modes/base.behavior.d.ts +21 -19
  41. package/dist/modes/base.mode.d.ts +66 -33
  42. package/dist/modes/circle/circle.mode.d.ts +66 -37
  43. package/dist/modes/click-bounding-box.behavior.d.ts +6 -7
  44. package/dist/modes/freehand/freehand.mode.d.ts +63 -39
  45. package/dist/modes/insert-coordinates.behavior.d.ts +9 -0
  46. package/dist/modes/linestring/linestring.mode.d.ts +78 -47
  47. package/dist/modes/pixel-distance.behavior.d.ts +7 -7
  48. package/dist/modes/point/point.mode.d.ts +44 -26
  49. package/dist/modes/polygon/behaviors/closing-points.behavior.d.ts +19 -19
  50. package/dist/modes/polygon/polygon.mode.d.ts +69 -51
  51. package/dist/modes/rectangle/rectangle.mode.d.ts +55 -0
  52. package/dist/modes/render/render.mode.d.ts +52 -23
  53. package/dist/modes/select/behaviors/drag-coordinate-resize.behavior.d.ts +62 -0
  54. package/dist/modes/select/behaviors/drag-coordinate.behavior.d.ts +20 -13
  55. package/dist/modes/select/behaviors/drag-feature.behavior.d.ts +20 -17
  56. package/dist/modes/select/behaviors/{features-at-mouse-event.behavior.d.ts → feature-at-pointer-event.behavior.d.ts} +15 -15
  57. package/dist/modes/select/behaviors/midpoint.behavior.d.ts +19 -18
  58. package/dist/modes/select/behaviors/rotate-feature.behavior.d.ts +14 -13
  59. package/dist/modes/select/behaviors/scale-feature.behavior.d.ts +14 -13
  60. package/dist/modes/select/behaviors/selection-point.behavior.d.ts +19 -18
  61. package/dist/modes/select/select.mode.d.ts +119 -78
  62. package/dist/modes/snapping.behavior.d.ts +16 -13
  63. package/dist/modes/static/static.mode.d.ts +32 -30
  64. package/dist/store/spatial-index/quickselect.d.ts +2 -2
  65. package/dist/store/spatial-index/rbush.d.ts +35 -35
  66. package/dist/store/spatial-index/spatial-index.d.ts +18 -18
  67. package/dist/store/store-feature-validation.d.ts +16 -0
  68. package/dist/store/store.d.ts +59 -48
  69. package/dist/terra-draw.cjs +1 -1
  70. package/dist/terra-draw.cjs.map +1 -1
  71. package/dist/terra-draw.d.ts +222 -48
  72. package/dist/terra-draw.modern.js +1 -1
  73. package/dist/terra-draw.modern.js.map +1 -1
  74. package/dist/terra-draw.module.js +1 -1
  75. package/dist/terra-draw.module.js.map +1 -1
  76. package/dist/terra-draw.umd.js +1 -1
  77. package/dist/terra-draw.umd.js.map +1 -1
  78. package/dist/util/geoms.d.ts +3 -3
  79. package/dist/util/id.d.ts +1 -1
  80. package/dist/util/styling.d.ts +2 -2
  81. package/dist/validations/linestring.validation.d.ts +2 -0
  82. package/dist/validations/max-size.validation.d.ts +2 -0
  83. package/dist/validations/min-size.validation.d.ts +2 -0
  84. package/dist/validations/not-self-intersecting.validation.d.ts +2 -0
  85. package/dist/validations/point.validation.d.ts +2 -0
  86. package/dist/validations/polygon.validation.d.ts +3 -0
  87. package/e2e/README.md +29 -0
  88. package/e2e/package-lock.json +4274 -0
  89. package/e2e/package.json +26 -0
  90. package/e2e/playwright.config.ts +77 -0
  91. package/e2e/public/favicon.ico +0 -0
  92. package/e2e/public/index.html +52 -0
  93. package/e2e/tests/leaflet.spec.ts +657 -0
  94. package/e2e/tests/setup.ts +181 -0
  95. package/e2e/webpack.config.js +36 -0
  96. package/jest.nocheck.config.ts +17 -0
  97. package/package.json +159 -87
  98. package/readme.gif +0 -0
  99. package/tsconfig.json +25 -12
  100. package/CODE_OF_CONDUCT.md +0 -36
  101. package/CONTRIBUTING.md +0 -17
  102. package/DEVELOPMENT.md +0 -77
  103. package/dist/bundle.js +0 -6
  104. package/dist/bundle.js.LICENSE.txt +0 -4
  105. package/dist/geometry/create-circle.d.ts +0 -6
  106. package/dist/geometry/get-pixel-distance-to-line.d.ts +0 -10
  107. package/dist/geometry/get-pixel-distance.d.ts +0 -7
  108. package/dist/geometry/haversine-distance.d.ts +0 -1
  109. package/dist/geometry/point-in-polygon.d.ts +0 -1
  110. package/dist/geometry/self-intersects.d.ts +0 -2
  111. package/dist/modes/circle.mode.d.ts +0 -18
  112. package/dist/modes/freehand.mode.d.ts +0 -20
  113. package/dist/modes/line-string.mode.d.ts +0 -21
  114. package/dist/modes/point.mode.d.ts +0 -14
  115. package/dist/modes/polygon/behaviors/start-end-point.behavior.d.ts +0 -11
  116. package/dist/modes/polygon.mode.d.ts +0 -21
  117. package/dist/modes/select.mode.d.ts +0 -21
  118. package/dist/modes/static.mode.d.ts +0 -10
  119. package/jest.config.ts +0 -27
@@ -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)Object.prototype.hasOwnProperty.call(i,o)&&(t[o]=i[o])}return t},t.apply(this,arguments)}function e(t,e=9){const i=Math.pow(10,e);return Math.round(t*i)/i}class i{constructor(t){this._heldKeys=new Set,this._cursor=void 0,this._cursorStyleSheet=void 0,this._coordinatePrecision=void 0,this._lib=void 0,this._map=void 0,this._onMouseMoveListener=void 0,this._onMouseMoveCallback=void 0,this._onClickListener=void 0,this._onRightClickListener=void 0,this._onClickCallback=void 0,this._onKeyUpListener=void 0,this._onDragStartListener=void 0,this._onDragListener=void 0,this._onDragEndListener=void 0,this._layers=!1,this.getMapContainer=void 0,this.unproject=void 0,this.project=void 0,this.setCursor=void 0,this._lib=t.lib,this._map=t.map,this._coordinatePrecision="number"==typeof t.coordinatePrecision?t.coordinatePrecision:9,this.getMapContainer=()=>this._map.getDiv(),this.project=(t,e)=>{const i=this._map.getBounds();if(void 0===i)throw new Error("cannot get bounds");const o=new this._lib.LatLng(i.getNorthEast().lat(),i.getSouthWest().lng()),s=this._map.getProjection();if(void 0===s)throw new Error("cannot get projection");const n=s.fromLatLngToPoint(o);if(null===n)throw new Error("cannot get projectedNorthWest");const r=s.fromLatLngToPoint({lng:t,lat:e});if(null===r)throw new Error("cannot get projected lng lat");const a=this._map.getZoom();if(void 0===a)throw new Error("cannot get zoom");const h=Math.pow(2,a);return{x:Math.floor((r.x-n.x)*h),y:Math.floor((r.y-n.y)*h)}},this.unproject=(t,e)=>{const i=this._map.getProjection();if(void 0===i)throw new Error("cannot get projection");const o=this._map.getBounds();if(void 0===o)throw new Error("cannot get bounds");const s=i.fromLatLngToPoint(o.getNorthEast());if(null===s)throw new Error("cannot get topRight");const n=i.fromLatLngToPoint(o.getSouthWest());if(null===n)throw new Error("cannot get bottomLeft");const r=this._map.getZoom();if(void 0===r)throw new Error("zoom get bounds");const a=Math.pow(2,r),h=new google.maps.Point(t/a+n.x,e/a+s.y),l=i.fromPointToLatLng(h);if(null===l)throw new Error("zoom get bounds");return{lng:l.lng(),lat:l.lat()}},this.setCursor=t=>{if(t!==this._cursor){if(this._cursorStyleSheet&&(this._cursorStyleSheet.remove(),this._cursorStyleSheet=void 0),"unset"!==t){const e=this.getMapContainer(),i=document.createElement("style");i.type="text/css",i.innerHTML=`#${e.id} [aria-label="Map"] { cursor: ${t} !important; }`,document.getElementsByTagName("head")[0].appendChild(i),this._cursorStyleSheet=i}this._cursor=t}}}circlePath(t,e,i){return"M "+t+" "+e+" m -"+i+", 0 a "+i+","+i+" 0 1,0 "+2*i+",0 a "+i+","+i+" 0 1,0 -"+2*i+",0"}register(t){this._onClickCallback=i=>{i.latLng&&t.onClick({lng:e(i.latLng.lng(),this._coordinatePrecision),lat:e(i.latLng.lat(),this._coordinatePrecision),containerX:i.domEvent.clientX-this.getMapContainer().offsetLeft,containerY:i.domEvent.clientY-this.getMapContainer().offsetTop,button:0===i.domEvent.button?"left":"right",heldKeys:[...this._heldKeys]})},this._onClickListener=this._map.addListener("click",this._onClickCallback),this._onRightClickListener=this._map.addListener("rightclick",this._onClickCallback),this._onMouseMoveCallback=i=>{i.latLng&&t.onMouseMove({lng:e(i.latLng.lng(),this._coordinatePrecision),lat:e(i.latLng.lat(),this._coordinatePrecision),containerX:i.domEvent.clientX-this.getMapContainer().offsetLeft,containerY:i.domEvent.clientY-this.getMapContainer().offsetTop,button:0===i.domEvent.button?"left":"right",heldKeys:[...this._heldKeys]})},this._onMouseMoveListener=this._map.addListener("mousemove",this._onMouseMoveCallback),this._onKeyUpListener=e=>{t.onKeyUp({key:e.key})},this.getMapContainer().addEventListener("keyup",this._onKeyUpListener);let i="not-dragging";this._onDragStartListener=t=>{i="pre-dragging"};const o=this.getMapContainer();o.addEventListener("mousedown",this._onDragStartListener),this._onDragListener=s=>{const n={x:s.clientX-o.offsetLeft,y:s.clientY-o.offsetTop},{lng:r,lat:a}=this.unproject(n.x,n.y),h={lng:e(r,this._coordinatePrecision),lat:e(a,this._coordinatePrecision),containerX:s.clientX-o.offsetLeft,containerY:s.clientY-o.offsetTop,button:0===s.button?"left":"right",heldKeys:[...this._heldKeys]};"pre-dragging"===i?(i="dragging",t.onDragStart(h,t=>{this._map.setOptions({draggable:!1})})):"dragging"===i&&t.onDrag(h)},o.addEventListener("mousemove",this._onDragListener),this._onDragEndListener=s=>{if("dragging"===i){const i={x:s.clientX-o.offsetLeft,y:s.clientY-o.offsetTop},{lng:n,lat:r}=this.unproject(i.x,i.y);t.onDragEnd({lng:e(n,this._coordinatePrecision),lat:e(r,this._coordinatePrecision),containerX:s.clientX-o.offsetLeft,containerY:s.clientY-o.offsetTop,button:0===s.button?"left":"right",heldKeys:[...this._heldKeys]},t=>{this._map.setOptions({draggable:t})})}i="not-dragging"},o.addEventListener("mouseup",this._onDragEndListener)}unregister(){this._onClickListener&&(this._onClickCallback=void 0,this._onClickListener.remove(),this._onClickListener=void 0),this._onRightClickListener&&(this._onClickCallback=void 0,this._onRightClickListener.remove(),this._onRightClickListener=void 0),this._onMouseMoveListener&&(this._onMouseMoveCallback=void 0,this._onMouseMoveListener.remove(),this._onMouseMoveListener=void 0),this._onKeyUpListener&&(this.getMapContainer().removeEventListener("keyup",this._onKeyUpListener),this._onKeyUpListener=void 0)}render(t,e){this._layers?(t.deletedIds.forEach(t=>{const e=this._map.data.getFeatureById(t);e&&this._map.data.remove(e)}),t.updated.forEach(t=>{if(!t||!t.id)throw new Error("Feature is not valid");const e=this._map.data.getFeatureById(t.id);if(!e)throw new Error("Feature could not be found by Google Maps API");switch(e.forEachProperty((t,i)=>{e.setProperty(i,void 0)}),Object.keys(t.properties).forEach(i=>{e.setProperty(i,t.properties[i])}),t.geometry.type){case"Point":{const i=t.geometry.coordinates;e.setGeometry(new google.maps.Data.Point(new google.maps.LatLng(i[1],i[0])))}break;case"LineString":{const i=t.geometry.coordinates,o=[];for(let t=0;t<i.length;t++){const e=i[t],s=new google.maps.LatLng(e[1],e[0]);o.push(s)}e.setGeometry(new google.maps.Data.LineString(o))}break;case"Polygon":{const i=t.geometry.coordinates,o=[];for(let t=0;t<i.length;t++){const e=[];for(let o=0;o<i[t].length;o++){const s=new google.maps.LatLng(i[t][o][1],i[t][o][0]);e.push(s)}o.push(e)}e.setGeometry(new google.maps.Data.Polygon(o))}}}),t.created.forEach(t=>{this._map.data.addGeoJson(t)})):(this._map.data.addListener("click",t=>{this._onClickCallback&&this._onClickCallback(t)}),this._map.data.addListener("mousemove",t=>{this._onMouseMoveCallback&&this._onMouseMoveCallback(t)}));const i={type:"FeatureCollection",features:[...t.created]};this._map.data.addGeoJson(i),this._map.data.setStyle(t=>{const i=t.getProperty("mode"),o=t.getGeometry();if(!o)throw new Error("Google Maps geometry not found");const s=o.getType(),n={};t.forEachProperty((t,e)=>{n[e]=t});const r=e[i]({type:"Feature",geometry:{type:s,coordinates:[]},properties:n});switch(s){case"Point":return{clickable:!1,icon:{path:this.circlePath(0,0,r.pointWidth),fillColor:r.pointColor,fillOpacity:1,strokeColor:r.pointOutlineColor,strokeWeight:r.pointOutlineWidth,rotation:0,scale:1}};case"LineString":return{strokeColor:r.lineStringColor,strokeWeight:r.lineStringWidth};case"Polygon":return{strokeColor:r.polygonOutlineColor,strokeWeight:r.polygonOutlineWidth,fillOpacity:r.polygonFillOpacity,fillColor:r.polygonFillColor}}throw Error("Unknown feature type")}),this._layers=!0}}class o{constructor(t){this._heldKeys=new Set,this._lib=void 0,this._coordinatePrecision=void 0,this._map=void 0,this._onMouseMoveListener=void 0,this._onClickListener=void 0,this._onKeyUpListener=void 0,this._onKeyDownListener=void 0,this._onDragStartListener=void 0,this._onDragListener=void 0,this._onDragEndListener=void 0,this._layer=void 0,this._panes={},this.project=void 0,this.unproject=void 0,this.setCursor=void 0,this.getMapContainer=void 0,this._lib=t.lib,this._map=t.map,this._coordinatePrecision="number"==typeof t.coordinatePrecision?t.coordinatePrecision:9,this.getMapContainer=()=>this._map.getContainer(),this.project=(t,e)=>{const{x:i,y:o}=this._map.latLngToContainerPoint({lng:t,lat:e});return{x:i,y:o}},this.unproject=(t,e)=>{const{lng:i,lat:o}=this._map.containerPointToLatLng({x:t,y:e});return{lng:i,lat:o}},this.setCursor=t=>{"unset"===t?this.getMapContainer().style.removeProperty("cursor"):this.getMapContainer().style.cursor=t}}createPaneStyleSheet(t,e){const i=document.createElement("style");return i.type="text/css",i.innerHTML=`.leaflet-${t} {z-index: ${e};}`,document.getElementsByTagName("head")[0].appendChild(i),this._map.createPane(t),i}register(t){const i=this.getMapContainer();let o="not-dragging";this._onClickListener=i=>{"not-dragging"!==o&&"pre-dragging"!==o||t.onClick({lng:e(i.latlng.lng,this._coordinatePrecision),lat:e(i.latlng.lat,this._coordinatePrecision),containerX:i.originalEvent.clientX-this.getMapContainer().offsetLeft,containerY:i.originalEvent.clientY-this.getMapContainer().offsetTop,button:0===i.originalEvent.button?"left":"right",heldKeys:[...this._heldKeys]})},this._map.on("mouseup",this._onClickListener),this._map.on("contextmenu",this._onClickListener),this._onMouseMoveListener=i=>{i.originalEvent.preventDefault(),t.onMouseMove({lng:e(i.latlng.lng,this._coordinatePrecision),lat:e(i.latlng.lat,this._coordinatePrecision),containerX:i.originalEvent.clientX-this.getMapContainer().offsetLeft,containerY:i.originalEvent.clientY-this.getMapContainer().offsetTop,button:0===i.originalEvent.button?"left":"right",heldKeys:[...this._heldKeys]})},this._map.on("mousemove",this._onMouseMoveListener),this._onDragStartListener=t=>{o="pre-dragging"},i.addEventListener("pointerdown",this._onDragStartListener),this._onDragListener=s=>{const n={x:s.clientX-i.offsetLeft,y:s.clientY-i.offsetTop},{lng:r,lat:a}=this._map.containerPointToLatLng(n),h={lng:e(r,this._coordinatePrecision),lat:e(a,this._coordinatePrecision),containerX:s.clientX-i.offsetLeft,containerY:s.clientY-i.offsetTop,button:0===s.button?"left":"right",heldKeys:[...this._heldKeys]};"pre-dragging"===o?(o="dragging",t.onDragStart(h,t=>{t?this._map.dragging.enable():this._map.dragging.disable()})):"dragging"===o&&t.onDrag(h)},i.addEventListener("pointermove",this._onDragListener),this._onDragEndListener=s=>{if(s.preventDefault(),"dragging"===o){const n={x:s.clientX-i.offsetLeft,y:s.clientY-i.offsetTop},{lng:r,lat:a}=this._map.containerPointToLatLng(n);return t.onDragEnd({lng:e(r,this._coordinatePrecision),lat:e(a,this._coordinatePrecision),containerX:s.clientX-i.offsetLeft,containerY:s.clientY-i.offsetTop,button:0===s.button?"left":"right",heldKeys:[...this._heldKeys]},t=>{t?this._map.dragging.enable():this._map.dragging.disable()}),o="after-dragging",void this._map.dragging.enable()}o="not-dragging",this._map.dragging.enable()},i.addEventListener("pointerup",this._onDragEndListener),this._onKeyUpListener=e=>{e.preventDefault(),this._heldKeys.delete(e.key),t.onKeyUp({key:e.key})},i.addEventListener("keyup",this._onKeyUpListener),this._onKeyDownListener=e=>{e.preventDefault(),this._heldKeys.add(e.key),t.onKeyDown({key:e.key})},i.addEventListener("keydown",this._onKeyDownListener)}unregister(){this._onClickListener&&(this._map.off("contextmenu",this._onClickListener),this._map.off("click",this._onClickListener),this._onClickListener=void 0),this._onMouseMoveListener&&(this._map.off("click",this._onClickListener),this._onClickListener=void 0),Object.keys(this._panes).forEach(t=>{const e=this._map.getPane(t);e&&e.remove()})}render(t,e){const i=[...t.created,...t.updated,...t.unchanged];this._layer&&this._map.removeLayer(this._layer);const o=this._lib.geoJSON({type:"FeatureCollection",features:i},{pointToLayer:(t,i)=>{if(!t.properties)throw new Error("Feature has no properties");if("string"!=typeof t.properties.mode)throw new Error("Feature mode is not a string");const o=(0,e[t.properties.mode])(t),s=String(o.zIndex);return this._panes[s]||(this._panes[s]=this.createPaneStyleSheet(s,o.zIndex)),this._lib.circleMarker(i,{radius:o.pointWidth,stroke:o.pointOutlineWidth||!1,color:o.pointOutlineColor,weight:o.pointOutlineWidth,fillOpacity:.8,fillColor:o.pointColor,pane:s,interactive:!1})},style:t=>{if(!t||!t.properties)return{};const i=t,o=(0,e[i.properties.mode])(i);return"LineString"===i.geometry.type?{interactive:!1,color:o.lineStringColor,weight:o.lineStringWidth}:"Polygon"===i.geometry.type?{interactive:!1,fillOpacity:o.polygonFillOpacity,fillColor:o.polygonFillColor,weight:o.polygonOutlineWidth,stroke:!0,color:o.polygonFillColor}:{}}});this._map.addLayer(o),this._layer=o}}class s{constructor(t){this.unproject=void 0,this.project=void 0,this.setCursor=void 0,this.getMapContainer=void 0,this._heldKeys=new Set,this._coordinatePrecision=void 0,this._map=void 0,this._onMouseMoveListener=void 0,this._onClickListener=void 0,this._onDragStartListener=void 0,this._onDragListener=void 0,this._onDragEndListener=void 0,this._onKeyDownListener=void 0,this._onKeyUpListener=void 0,this._rendered={},this._map=t.map,this._coordinatePrecision="number"==typeof t.coordinatePrecision?t.coordinatePrecision:9,this.project=(t,e)=>{const{x:i,y:o}=this._map.project({lng:t,lat:e});return{x:i,y:o}},this.unproject=(t,e)=>{const{lng:i,lat:o}=this._map.unproject({x:t,y:e});return{lng:i,lat:o}},this.setCursor=t=>{this._map.getCanvas().style.cursor=t},this.getMapContainer=()=>this._map.getContainer()}_addGeoJSONSource(t,e){this._map.addSource(t,{type:"geojson",data:{type:"FeatureCollection",features:e}})}_addFillLayer(t,e){return this._map.addLayer({id:t,source:t,type:"fill",filter:["all",["match",["geometry-type"],"Polygon",!0,!1],["match",["get","mode"],e,!0,!1]],paint:{"fill-color":["get","polygonFillColor"],"fill-opacity":["get","polygonFillOpacity"]}})}_addFillOutlineLayer(t,e,i){const o=this._map.addLayer({id:t+"outline",source:t,type:"line",filter:["all",["match",["geometry-type"],"Polygon",!0,!1],["match",["get","mode"],e,!0,!1]],paint:{"line-width":["get","polygonOutlineWidth"],"line-color":["get","polygonOutlineColor"]}});return i&&this._map.moveLayer(t,i),o}_addLineLayer(t,e,i){const o=this._map.addLayer({id:t,source:t,type:"line",filter:["all",["match",["geometry-type"],"LineString",!0,!1],["match",["get","mode"],e,!0,!1]],paint:{"line-width":["get","lineStringWidth"],"line-color":["get","lineStringColor"]}});return i&&this._map.moveLayer(t,i),o}_addPointLayer(t,e,i){const o=this._map.addLayer({id:t,source:t,type:"circle",filter:["all",["match",["geometry-type"],"Point",!0,!1],["match",["get","mode"],e,!0,!1]],paint:{"circle-stroke-color":["get","pointOutlineColor"],"circle-stroke-width":["get","pointOutlineWidth"],"circle-radius":["get","pointWidth"],"circle-color":["get","pointColor"]}});return i&&this._map.moveLayer(t,i),o}_addLayer(t,e,i,o){"Point"===i&&this._addPointLayer(t,e,o),"LineString"===i&&this._addLineLayer(t,e,o),"Polygon"===i&&(this._addFillLayer(t,e),this._addFillOutlineLayer(t,e,o))}_addGeoJSONLayer(t,e,i){const o=`td-${t}-${e.toLowerCase()}`;return this._addGeoJSONSource(o,i),this._addLayer(o,t,e),o}_setGeoJSONLayerData(t,e,i){const o=`td-${t}-${e.toLowerCase()}`;return this._map.getSource(o).setData({type:"FeatureCollection",features:i}),o}register(t){this._onClickListener=i=>{t.onClick({lng:e(i.lngLat.lng,this._coordinatePrecision),lat:e(i.lngLat.lat,this._coordinatePrecision),containerX:i.originalEvent.clientX-this.getMapContainer().offsetLeft,containerY:i.originalEvent.clientY-this.getMapContainer().offsetTop,button:0===i.originalEvent.button?"left":"right",heldKeys:[...this._heldKeys]})},this._map.on("click",this._onClickListener),this._map.on("contextmenu",this._onClickListener),this._onMouseMoveListener=i=>{t.onMouseMove({lng:e(i.lngLat.lng,this._coordinatePrecision),lat:e(i.lngLat.lat,this._coordinatePrecision),containerX:i.originalEvent.clientX-this.getMapContainer().offsetLeft,containerY:i.originalEvent.clientY-this.getMapContainer().offsetTop,button:0===i.originalEvent.button?"left":"right",heldKeys:[...this._heldKeys]})},this._map.on("mousemove",this._onMouseMoveListener);let i="not-dragging";this._onDragStartListener=t=>{i="pre-dragging"};const o=this.getMapContainer();o.addEventListener("mousedown",this._onDragStartListener),this._onDragListener=s=>{const{lng:n,lat:r}=this._map.unproject({x:s.clientX-o.offsetLeft,y:s.clientY-o.offsetTop}),a={lng:e(n,this._coordinatePrecision),lat:e(r,this._coordinatePrecision),containerX:s.clientX-o.offsetLeft,containerY:s.clientY-o.offsetTop,button:0===s.button?"left":"right",heldKeys:[...this._heldKeys]};"pre-dragging"===i?(i="dragging",t.onDragStart(a,t=>{t?this._map.dragPan.enable():this._map.dragPan.disable()})):"dragging"===i&&t.onDrag(a)},o.addEventListener("mousemove",this._onDragListener),this._onDragEndListener=s=>{if("dragging"===i){const i={x:s.clientX-o.offsetLeft,y:s.clientY-o.offsetTop},{lng:n,lat:r}=this._map.unproject(i);t.onDragEnd({lng:e(n,this._coordinatePrecision),lat:e(r,this._coordinatePrecision),containerX:s.clientX-o.offsetLeft,containerY:s.clientY-o.offsetTop,button:0===s.button?"left":"right",heldKeys:[...this._heldKeys]},t=>{t?this._map.dragPan.enable():this._map.dragPan.disable()})}i="not-dragging"},o.addEventListener("mouseup",this._onDragEndListener),this._onKeyUpListener=e=>{e.preventDefault(),this._heldKeys.delete(e.key),t.onKeyUp({key:e.key})},o.addEventListener("keyup",this._onKeyUpListener),this._onKeyDownListener=e=>{e.preventDefault(),this._heldKeys.add(e.key),t.onKeyDown({key:e.key})},o.addEventListener("keydown",this._onKeyDownListener)}unregister(){this._onClickListener&&(this._map.off("contextmenue",this._onClickListener),this._map.off("click",this._onClickListener),this._onClickListener=void 0),this._onMouseMoveListener&&(this._map.off("mousemove",this._onMouseMoveListener),this._onMouseMoveListener=void 0),this._onKeyUpListener&&this._map.getCanvas().removeEventListener("keypress",this._onKeyUpListener),this._onDragStartListener&&this._map.getCanvas().removeEventListener("mousedown",this._onDragStartListener),this._onDragListener&&this._map.getCanvas().removeEventListener("mousemove",this._onDragListener),this._onDragEndListener&&this._map.getCanvas().removeEventListener("mouseup",this._onDragEndListener)}render(t,e){const i=[...t.created,...t.updated,...t.unchanged],o={};Object.keys(e).forEach(t=>{o[t]||(o[t]={points:[],linestrings:[],polygons:[]})});for(let t=0;t<i.length;t++){const s=i[t];Object.keys(e).forEach(t=>{const{properties:i}=s;if(i.mode!==t)return;const n=e[t](s);"Point"===s.geometry.type?(i.pointColor=n.pointColor,i.pointOutlineColor=n.pointOutlineColor,i.pointOutlineWidth=n.pointOutlineWidth,i.pointWidth=n.pointWidth,o[t].points.push(s)):"LineString"===s.geometry.type?(i.lineStringColor=n.lineStringColor,i.lineStringWidth=n.lineStringWidth,o[t].linestrings.push(s)):"Polygon"===s.geometry.type&&(i.polygonFillColor=n.polygonFillColor,i.polygonFillOpacity=n.polygonFillOpacity,i.polygonOutlineColor=n.polygonOutlineColor,i.polygonOutlineWidth=n.polygonOutlineWidth,o[t].polygons.push(s))})}Object.keys(e).forEach(t=>{if(!o[t])return;const{points:e,linestrings:i,polygons:s}=o[t];if(this._rendered[t]){const o=this._setGeoJSONLayerData(t,"Point",e);this._setGeoJSONLayerData(t,"LineString",i),this._setGeoJSONLayerData(t,"Polygon",s),this._map.moveLayer(o)}else this._addGeoJSONLayer(t,"Point",e),this._addGeoJSONLayer(t,"LineString",i),this._addGeoJSONLayer(t,"Polygon",s),this._rendered[t]=!0}),this._map.style&&(this._map._frame&&(this._map._frame.cancel(),this._map._frame=null),this._map._render())}}function n(t,e){const i=t=>t*Math.PI/180,o=i(t[1]),s=i(t[0]),n=i(e[1]),r=n-o,a=i(e[0])-s,h=Math.sin(r/2)*Math.sin(r/2)+Math.cos(o)*Math.cos(n)*Math.sin(a/2)*Math.sin(a/2);return 2*Math.atan2(Math.sqrt(h),Math.sqrt(1-h))*6371e3/1e3}function r(t){return t%360*Math.PI/180}function a(t){return t%(2*Math.PI)*180/Math.PI}function h(t,e,i){const o=r(t[0]),s=r(t[1]),n=r(i),h=function(t){return t/6371.0088}(e),l=Math.asin(Math.sin(s)*Math.cos(h)+Math.cos(s)*Math.sin(h)*Math.cos(n));return[a(o+Math.atan2(Math.sin(n)*Math.sin(h)*Math.cos(s),Math.cos(h)-Math.sin(s)*Math.sin(l))),a(l)]}function l(t){const{center:e,radiusKilometers:i}=t,o=t.steps?t.steps:64,s=[];for(let t=0;t<o;t++)s.push(h(e,i,-360*t/o));return s.push(s[0]),{type:"Feature",geometry:{type:"Polygon",coordinates:[s]},properties:{}}}class d{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([],"styling"),this._styles=t}registerBehaviors(t){}constructor(e){this._state=void 0,this._styles=void 0,this.behaviors=[],this.pointerDistance=void 0,this.coordinatePrecision=void 0,this.onStyleChange=void 0,this.store=void 0,this.unproject=void 0,this.project=void 0,this.setCursor=void 0,this._state="unregistered",this._styles=e&&e.styles?t({},e.styles):{},this.pointerDistance=e&&e.pointerDistance||40,this.coordinatePrecision=e&&e.coordinatePrecision||9}setStarted(){if("stopped"!==this._state&&"registered"!==this._state)throw new Error("Mode must be unregistered or stopped to start");this._state="started"}setStopped(){if("started"!==this._state)throw new Error("Mode must be started to be stopped");this._state="stopped"}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.project=t.project,this.unproject=t.unproject,this.onSelect=t.onSelect,this.onDeselect=t.onDeselect,this.setCursor=t.setCursor,this.onStyleChange=t.onChange,this.registerBehaviors({mode:t.mode,store:this.store,project:this.project,unproject:this.unproject,pointerDistance:this.pointerDistance,coordinatePrecision:this.coordinatePrecision})}onDeselect(t){}onSelect(t){}styleFeature(t){}}class c extends d{constructor(t){super(t),this.mode="circle",this.center=void 0,this.clickCount=0,this.currentCircleId=void 0,this.keyEvents=void 0,this.keyEvents=t&&t.keyEvents?t.keyEvents:{cancel:"Escape",finish:"Enter"}}close(){this.center=void 0,this.currentCircleId=void 0,this.clickCount=0}start(){this.setStarted(),this.setCursor("crosshair")}stop(){this.setStopped(),this.setCursor("unset"),this.cleanUp()}onClick(t){if(0===this.clickCount){this.center=[t.lng,t.lat];const e=l({center:this.center,radiusKilometers:1e-5}),[i]=this.store.create([{geometry:e.geometry,properties:{mode:this.mode}}]);this.currentCircleId=i,this.clickCount++}else this.close()}onMouseMove(t){if(1===this.clickCount&&this.center&&this.currentCircleId){const e=n(this.center,[t.lng,t.lat]),i=l({center:this.center,radiusKilometers:e});this.store.updateGeometry([{id:this.currentCircleId,geometry:i.geometry}])}}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentCircleId&&this.store.delete([this.currentCircleId])}catch(t){}this.center=void 0,this.currentCircleId=void 0,this.clickCount=0}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});return"Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(this.styles.fillColor&&(i.polygonFillColor=this.styles.fillColor),this.styles.outlineColor&&(i.polygonOutlineColor=this.styles.outlineColor),this.styles.outlineWidth&&(i.polygonOutlineWidth=this.styles.outlineWidth),this.styles.fillOpacity&&(i.polygonFillOpacity=this.styles.fillOpacity),i):i}}class p extends d{constructor(t){super(t),this.mode="freehand",this.startingClick=!1,this.currentId=void 0,this.skip=0,this.everyNthMouseEvent=void 0,this.keyEvents=void 0,this.everyNthMouseEvent=t&&t.everyNthMouseEvent||10,this.keyEvents=t&&t.keyEvents?t.keyEvents:{cancel:"Escape",finish:"Enter"}}close(){this.startingClick=!1,this.currentId=void 0}start(){this.setStarted(),this.setCursor("crosshair")}stop(){this.setStopped(),this.setCursor("unset"),this.cleanUp()}onMouseMove(t){if(this.currentId&&!1!==this.startingClick){if(this.skip>this.everyNthMouseEvent){this.skip=0;const e=this.store.getGeometryCopy(this.currentId);e.coordinates[0].pop(),this.store.updateGeometry([{id:this.currentId,geometry:{type:"Polygon",coordinates:[[...e.coordinates[0],[t.lng,t.lat],e.coordinates[0][0]]]}}])}this.skip++}}onClick(t){if(!1===this.startingClick){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}}]);return this.currentId=e,void(this.startingClick=!0)}this.close()}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentId&&this.store.delete([this.currentId])}catch(t){}this.currentId=void 0,this.startingClick=!1}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});return"Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(this.styles.fillColor&&(i.polygonFillColor=this.styles.fillColor),this.styles.outlineColor&&(i.polygonOutlineColor=this.styles.outlineColor),this.styles.outlineWidth&&(i.polygonOutlineWidth=this.styles.outlineWidth),this.styles.fillOpacity&&(i.polygonFillOpacity=this.styles.fillOpacity),i):i}}function g(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 n=0;n<e[o].length-1;n++)s(t,i,o,n);return i.length>0;function o(t){return t<0||t>1}function s(t,s,n,r){const a=e[t][s],h=e[t][s+1],l=e[n][r],d=e[n][r+1],c=function(t,e,i,o){if(u(t,i)||u(t,o)||u(e,i)||u(o,i))return null;const s=t[0],n=t[1],r=e[0],a=e[1],h=i[0],l=i[1],d=o[0],c=o[1],p=(s-r)*(l-c)-(n-a)*(h-d);return 0===p?null:[((s*a-n*r)*(h-d)-(s-r)*(h*c-l*d))/p,((s*a-n*r)*(l-c)-(n-a)*(h*c-l*d))/p]}(a,h,l,d);if(null===c)return;let p,g;p=h[0]!==a[0]?(c[0]-a[0])/(h[0]-a[0]):(c[1]-a[1])/(h[1]-a[1]),g=d[0]!==l[0]?(c[0]-l[0])/(d[0]-l[0]):(c[1]-l[1])/(d[1]-l[1]),o(p)||o(g)||(c.toString(),i.push(c))}}function u(t,e){return t[0]===e[0]&&t[1]===e[1]}const y=(t,e)=>{const{x:i,y:o}=t,{x:s,y:n}=e,r=s-i,a=n-o;return Math.sqrt(a*a+r*r)};class f{constructor({store:t,mode:e,project:i,unproject:o,pointerDistance:s,coordinatePrecision: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.store=t,this.mode=e,this.project=i,this.unproject=o,this.pointerDistance=s,this.coordinatePrecision=n}}class m extends f{constructor(t){super(t)}create(t){const{containerX:e,containerY:i}=t,o=this.pointerDistance/2;return{type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[[this.unproject(e-o,i-o),this.unproject(e+o,i-o),this.unproject(e+o,i+o),this.unproject(e-o,i+o),this.unproject(e-o,i-o)].map(t=>[t.lng,t.lat])]}}}}class _ extends f{constructor(t){super(t)}measure(t,e){const{x:i,y:o}=this.project(e[0],e[1]);return y({x:i,y:o},{x:t.containerX,y:t.containerY})}}class C extends f{constructor(t,e,i){super(t),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinate=(t,e)=>this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode&&t.id!==e)),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={coord: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(e=>{const i=this.pixelDistance.measure(t,e);i<s.minDist&&i<this.pointerDistance&&(s.coord=e)})}),s.coord}}class v extends d{constructor(t){super(t),this.mode="linestring",this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.allowSelfIntersections=void 0,this.keyEvents=void 0,this.snappingEnabled=void 0,this.snapping=void 0,this.snappingEnabled=!(!t||void 0===t.snapping)&&t.snapping,this.allowSelfIntersections=!t||void 0===t.allowSelfIntersections||t.allowSelfIntersections,this.keyEvents=t&&t.keyEvents?t.keyEvents:{cancel:"Escape",finish:"Enter"}}close(){if(!this.currentId)return;const t=this.store.getGeometryCopy(this.currentId);t.coordinates.pop(),this.store.updateGeometry([{id:this.currentId,geometry:{type:"LineString",coordinates:[...t.coordinates]}}]),this.closingPointId&&this.store.delete([this.closingPointId]),this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0}registerBehaviors(t){this.snapping=new C(t,new _(t),new m(t))}start(){this.setStarted(),this.setCursor("crosshair")}stop(){this.setStopped(),this.setCursor("unset"),this.cleanUp()}onMouseMove(t){if(this.setCursor("crosshair"),!this.currentId||0===this.currentCoordinate)return;const e=this.store.getGeometryCopy(this.currentId);e.coordinates.pop();const i=this.snappingEnabled&&this.snapping.getSnappableCoordinate(t,this.currentId)||[t.lng,t.lat];if(this.closingPointId){const[i,o]=e.coordinates[e.coordinates.length-1],{x:s,y:n}=this.project(i,o);y({x:s,y:n},{x:t.containerX,y:t.containerY})<this.pointerDistance&&this.setCursor("pointer")}this.store.updateGeometry([{id:this.currentId,geometry:{type:"LineString",coordinates:[...e.coordinates,i]}}])}onClick(t){const e=this.currentId&&this.snappingEnabled&&this.snapping.getSnappableCoordinate(t,this.currentId)||[t.lng,t.lat];if(0===this.currentCoordinate){const[t]=this.store.create([{geometry:{type:"LineString",coordinates:[e,e]},properties:{mode:this.mode}}]);this.currentId=t,this.currentCoordinate++}else if(1===this.currentCoordinate&&this.currentId){const t=this.store.getGeometryCopy(this.currentId),[i]=this.store.create([{geometry:{type:"Point",coordinates:[...e]},properties:{mode:this.mode}}]);this.closingPointId=i,this.setCursor("pointer"),this.store.updateGeometry([{id:this.currentId,geometry:{type:"LineString",coordinates:[t.coordinates[0],e,e]}}]),this.currentCoordinate++}else if(this.currentId){const i=this.store.getGeometryCopy(this.currentId),[o,s]=i.coordinates[i.coordinates.length-2],{x:n,y:r}=this.project(o,s);if(y({x:n,y:r},{x:t.containerX,y:t.containerY})<this.pointerDistance)this.close();else{const t={type:"LineString",coordinates:[...i.coordinates,e]};if(!this.allowSelfIntersections&&g({type:"Feature",geometry:t,properties:{}}))return;this.closingPointId&&(this.setCursor("pointer"),this.store.updateGeometry([{id:this.currentId,geometry:t},{id:this.closingPointId,geometry:{type:"Point",coordinates:i.coordinates[i.coordinates.length-1]}}]),this.currentCoordinate++)}}}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel&&this.cleanUp(),t.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentId&&this.store.delete([this.currentId]),this.closingPointId&&this.store.delete([this.closingPointId])}catch(t){}this.closingPointId=void 0,this.currentId=void 0,this.currentCoordinate=0}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});return"Feature"===e.type&&"LineString"===e.geometry.type&&e.properties.mode===this.mode?(this.styles.lineStringColor&&(i.lineStringColor=this.styles.lineStringColor),this.styles.lineStringWidth&&(i.lineStringWidth=this.styles.lineStringWidth),i):"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode?(this.styles.closingPointColor&&(i.pointColor=this.styles.closingPointColor),this.styles.closingPointWidth&&(i.pointWidth=this.styles.closingPointWidth),i.pointOutlineColor=void 0!==this.styles.closingPointOutlineColor?this.styles.closingPointOutlineColor:"#ffffff",i.pointOutlineWidth=void 0!==this.styles.closingPointOutlineWidth?this.styles.closingPointOutlineWidth:2,i):i}}class P extends d{constructor(t){super(t),this.mode="point"}start(){this.setStarted(),this.setCursor("crosshair")}stop(){this.setStopped(),this.setCursor("unset"),this.cleanUp()}onClick(t){if(!this.store)throw new Error("Mode must be registered first");this.store.create([{geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:{mode:this.mode}}])}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){}onDragStart(){}onDrag(){}onDragEnd(){}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});return"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode?(this.styles.pointColor&&(i.pointColor=this.styles.pointColor),this.styles.pointOutlineColor&&(i.pointOutlineColor=this.styles.pointOutlineColor),this.styles.pointWidth&&(i.pointWidth=this.styles.pointWidth),i):i}}function M(t,e){return t[0]===e[0]&&t[1]===e[1]}class L extends f{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 creating");if(t.length<=3)throw new Error("Requires at least 4 cooridnates");this._startEndPoints=this.store.create([{geometry:{type:"Point",coordinates:t[0]},properties:{mode:e,closingPoint:!0}},{geometry:{type:"Point",coordinates:t[t.length-2]},properties:{mode:e,closingPoint:!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 x extends d{constructor(t){super(t),this.mode="polygon",this.currentCoordinate=0,this.currentId=void 0,this.allowSelfIntersections=void 0,this.keyEvents=void 0,this.snappingEnabled=void 0,this.isClosed=!1,this.snapping=void 0,this.pixelDistance=void 0,this.closingPoints=void 0,this.snappingEnabled=!(!t||void 0===t.snapping)&&t.snapping,this.allowSelfIntersections=!t||void 0===t.allowSelfIntersections||t.allowSelfIntersections,this.keyEvents=t&&t.keyEvents?t.keyEvents:{cancel:"Escape",finish:"Enter"}}close(){if(!this.currentId)return;const t=this.store.getGeometryCopy(this.currentId).coordinates[0];t.length<5||(this.store.updateGeometry([{id:this.currentId,geometry:{type:"Polygon",coordinates:[[...t.slice(0,-2),t[0]]]}}]),this.currentCoordinate=0,this.currentId=void 0,this.closingPoints.delete())}registerBehaviors(t){this.pixelDistance=new _(t),this.snapping=new C(t,this.pixelDistance,new m(t)),this.closingPoints=new L(t,this.pixelDistance)}start(){this.setStarted(),this.setCursor("crosshair")}stop(){this.setStopped(),this.setCursor("unset"),this.cleanUp()}onMouseMove(t){if(this.setCursor("crosshair"),!this.currentId||0===this.currentCoordinate)return;const e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):void 0,i=this.store.getGeometryCopy(this.currentId).coordinates[0];let o;if(e&&(t.lng=e[0],t.lat=e[1]),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.setCursor("pointer"),o=[...i.slice(0,-2),i[0],i[0]],this.isClosed||(this.isClosed=!0)):(this.isClosed&&(this.isClosed=!1),o=[...i.slice(0,-2),[t.lng,t.lat],i[0]])}this.store.updateGeometry([{id:this.currentId,geometry:{type:"Polygon",coordinates:[o]}}]),this.closingPoints.ids.length&&this.closingPoints.update(o)}onClick(t){const e=this.currentId&&this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):void 0;if(0===this.currentCoordinate){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}}]);this.currentId=i,this.currentCoordinate++}else if(1===this.currentCoordinate&&this.currentId){e&&(t.lng=e[0],t.lat=e[1]);const i=this.store.getGeometryCopy(this.currentId);if(M([t.lng,t.lat],i.coordinates[0][0]))return;this.store.updateGeometry([{id:this.currentId,geometry:{type:"Polygon",coordinates:[[i.coordinates[0][0],[t.lng,t.lat],[t.lng,t.lat],i.coordinates[0][0]]]}}]),this.currentCoordinate++}else if(2===this.currentCoordinate&&this.currentId){e&&(t.lng=e[0],t.lat=e[1]);const i=this.store.getGeometryCopy(this.currentId).coordinates[0];if(M([t.lng,t.lat],i[1]))return;2===this.currentCoordinate&&this.closingPoints.create(i,"polygon"),this.store.updateGeometry([{id:this.currentId,geometry:{type:"Polygon",coordinates:[[i[0],i[1],[t.lng,t.lat],[t.lng,t.lat],i[0]]]}}]),this.currentCoordinate++}else if(this.currentId){const i=this.store.getGeometryCopy(this.currentId).coordinates[0],{isClosing:o,isPreviousClosing:s}=this.closingPoints.isClosingPoint(t);if(s||o)this.close();else{if(e&&(t.lng=e[0],t.lat=e[1]),M([t.lng,t.lat],i[this.currentCoordinate-1]))return;const o=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.currentCoordinate>2&&!this.allowSelfIntersections&&g(o))return;this.store.updateGeometry([{id:this.currentId,geometry:o.geometry}]),this.currentCoordinate++}}}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(){this.setCursor("unset")}onDrag(){}onDragEnd(){this.setCursor("crosshair")}cleanUp(){try{this.currentId&&this.store.delete([this.currentId]),this.closingPoints.ids.length&&this.closingPoints.delete()}catch(t){}this.currentId=void 0,this.currentCoordinate=0}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});if(e.properties.mode===this.mode){if("Polygon"===e.geometry.type)return i.polygonFillColor=this.styles.fillColor||i.polygonFillColor,i.polygonOutlineColor=this.styles.outlineColor||i.polygonOutlineColor,i.polygonOutlineWidth=this.styles.outlineWidth||i.polygonOutlineWidth,i.polygonFillColor=this.styles.fillColor||i.polygonFillColor,i.zIndex=10,i;if("Point"===e.geometry.type)return i.pointWidth=this.styles.closingPointWidth||i.pointWidth,i.pointColor=this.styles.closingPointColor||i.pointColor,i.pointOutlineColor=this.styles.closingPointOutlineColor||"#ffffff",i.pointOutlineWidth=this.styles.closingPointOutlineWidth||2,i.zIndex=30,i}return i}}class E extends d{constructor(t){super({styles:t.styles}),this.mode="render"}registerBehaviors(t){this.mode=t.mode}start(){this.setStarted()}stop(){this.setStopped()}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}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},this.styles)}}function k(t,i,o){const s=n(t,i),l=function(t,e){const i=r(t[0]),o=r(e[0]),s=r(t[1]),n=r(e[1]),h=Math.sin(o-i)*Math.cos(n),l=Math.cos(s)*Math.sin(n)-Math.sin(s)*Math.cos(n)*Math.cos(o-i);return a(Math.atan2(h,l))}(t,i),d=h(t,s/2,l);return[e(d[0],o),e(d[1],o)]}function S(t,e){const i=[];for(let o=0;o<t.length-1;o++){const s=k(t[o],t[o+1],e);i.push(s)}return i}class w extends f{constructor(t,e){super(t),this.config=void 0,this.selectionPointBehavior=void 0,this._midPoints=[],this.config=t,this.selectionPointBehavior=e}get ids(){return this._midPoints.concat()}set ids(t){}insert(t,e){const i=this.store.getGeometryCopy(t),{midPointFeatureId:o,midPointSegment:s}=this.store.getPropertiesCopy(t),n=this.store.getGeometryCopy(o),r="Polygon"===n.type?n.coordinates[0]:n.coordinates;r.splice(s+1,0,i.coordinates),n.coordinates="Polygon"===n.type?[r]:r,this.store.updateGeometry([{id:o,geometry:n}]),this.store.delete([...this._midPoints,...this.selectionPointBehavior.ids]),this.create(r,o,e),this.selectionPointBehavior.create(r,n.type,o)}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){return S(t,i).map((t,i)=>({geometry:{type:"Point",coordinates:t},properties:e(i)}))}(t,t=>({mode:this.mode,midPoint:!0,midPointSegment:t,midPointFeatureId:e}),i))}delete(){this._midPoints.length&&(this.store.delete(this._midPoints),this._midPoints=[])}getUpdated(t){if(0!==this._midPoints.length)return S(t,this.coordinatePrecision).map((t,e)=>({id:this._midPoints[e],geometry:{type:"Point",coordinates:t}}))}}class D extends f{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,selectionPoint:!0,selectionPointFeatureId:i,index:t})))}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 I(t,e){let i=!1;for(let r=0,a=e.length;r<a;r++){const a=e[r];for(let e=0,r=a.length,h=r-1;e<r;h=e++)(s=a[e])[1]>(o=t)[1]!=(n=a[h])[1]>o[1]&&o[0]<(n[0]-s[0])*(o[1]-s[1])/(n[1]-s[1])+s[0]&&(i=!i)}var o,s,n;return i}const O=(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 n=((t.x-e.x)*(i.x-e.x)+(t.y-e.y)*(i.y-e.y))/o;return n=Math.max(0,Math.min(1,n)),s(t,{x:e.x+n*(i.x-e.x),y:e.y+n*(i.y-e.y)})})(t,e,i))};class b extends f{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,o,s=Infinity,n=Infinity;const r=this.createClickBoundingBox.create(t),a=this.store.search(r);for(let r=0;r<a.length;r++){const h=a[r],l=h.geometry;if("Point"===l.type){const r=!e&&h.properties.midPoint;if(h.properties.selectionPoint||r)continue;const a=this.pixelDistance.measure(t,l.coordinates);h.properties.midPoint&&a<this.pointerDistance&&a<n?(n=a,o=h):!h.properties.midPoint&&a<this.pointerDistance&&a<s&&(s=a,i=h)}else if("LineString"===l.type)for(let e=0;e<l.coordinates.length-1;e++){const o=l.coordinates[e],n=l.coordinates[e+1],r=O({x:t.containerX,y:t.containerY},this.project(o[0],o[1]),this.project(n[0],n[1]));r<this.pointerDistance&&r<s&&(s=r,i=h)}else"Polygon"===l.type&&I([t.lng,t.lat],l.coordinates)&&(s=0,i=h)}return{clickedFeature:i,clickedMidPoint:o}}}class F extends f{constructor(t,e,i,o){super(t),this.config=void 0,this.featuresAtMouseEvent=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.dragPosition=void 0,this.config=t,this.featuresAtMouseEvent=e,this.selectionPoints=i,this.midPoints=o}get position(){return this.dragPosition?this.dragPosition.concat():void 0}set position(t){if(void 0!==t){if(!Array.isArray(t)||2!==t.length||"number"!=typeof t[0]||"number"!=typeof t[1])throw new Error("Position must be [number, number] array");this.dragPosition=t.concat()}else this.dragPosition=void 0}drag(t,e){const{clickedFeature:i}=this.featuresAtMouseEvent.find(t,!0);if(!i||i.id!==e)return;const o=this.store.getGeometryCopy(e),s=[t.lng,t.lat];if("Polygon"===o.type||"LineString"===o.type){let t,i;if("Polygon"===o.type?(t=o.coordinates[0],i=t.length-1):"LineString"===o.type&&(t=o.coordinates,i=t.length),void 0===i||!t||!this.dragPosition)return!1;for(let e=0;e<i;e++){const i=t[e],o=[this.dragPosition[0]-s[0],this.dragPosition[1]-s[1]];t[e]=[i[0]-o[0],i[1]-o[1]]}"Polygon"===o.type&&(t[t.length-1]=[t[0][0],t[0][1]]);const n=this.selectionPoints.getUpdated(t)||[],r=this.midPoints.getUpdated(t)||[];this.store.updateGeometry([{id:e,geometry:o},...n,...r])}else"Point"===o.type&&this.store.updateGeometry([{id:e,geometry:{type:"Point",coordinates:s}}])}}class W extends f{constructor(t,e,i,o){super(t),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.config=t,this.pixelDistance=e,this.selectionPoints=i,this.midPoints=o}drag(t,e){const i=this.store.getGeometryCopy(e);let o;if("LineString"===i.type)o=i.coordinates;else{if("Polygon"!==i.type)return!1;o=i.coordinates[0]}const s={dist:Infinity,index:-1,isFirstOrLastPolygonCoord:!1};for(let e=0;e<o.length;e++){const n=this.pixelDistance.measure(t,o[e]);if(n<this.pointerDistance&&n<s.dist){const t="Polygon"===i.type&&(e===o.length-1||0===e);s.dist=n,s.index=t?0:e,s.isFirstOrLastPolygonCoord=t}}if(-1===s.index)return!1;const n=[t.lng,t.lat];if(s.isFirstOrLastPolygonCoord){const t=o.length-1;o[0]=n,o[t]=n}else o[s.index]=n;const r=this.selectionPoints.getOneUpdated(s.index,n),a=r?[r]:[],h=this.midPoints.getUpdated(o)||[];return this.store.updateGeometry([{id:e,geometry:i},...a,...h]),!0}}function B(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]}function K(t,e){const i=t,o=e,s=r(i[1]),n=r(o[1]);let h=r(o[0]-i[0]);h>Math.PI&&(h-=2*Math.PI),h<-Math.PI&&(h+=2*Math.PI);const l=Math.log(Math.tan(n/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),d=(a(Math.atan2(h,l))+360)%360;return d>180?-(360-d):d}function X(t,e,i){const o=e/6371008.8,s=t[0]*Math.PI/180,n=r(t[1]),a=r(i),h=o*Math.cos(a);let l=n+h;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);const d=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(n/2+Math.PI/4)),c=Math.abs(d)>1e-11?h/d:Math.cos(n),p=[(180*(s+o*Math.sin(a)/c)/Math.PI+540)%360-180,180*l/Math.PI];return p[0]+=p[0]-t[0]>180?-360:t[0]-p[0]>180?360:0,p}function Y(t,e){t[0]+=t[0]-e[0]>180?-360:e[0]-t[0]>180?360:0;const i=e[1]*Math.PI/180,o=t[1]*Math.PI/180,s=o-i;let n=Math.abs(t[0]-e[0])*Math.PI/180;n>Math.PI&&(n-=2*Math.PI);const r=Math.log(Math.tan(o/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),a=Math.abs(r)>1e-11?s/r:Math.cos(i);return 6371008.8*Math.sqrt(s*s+a*a*n*n)}class j extends f{constructor(t,e,i){super(t),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.lastBearing=void 0,this.config=t,this.selectionPoints=e,this.midPoints=i}reset(){this.lastBearing=void 0}rotate(t,i){const o=this.store.getGeometryCopy(i);if("Polygon"!==o.type&&"LineString"!==o.type)return;const s=[t.lng,t.lat],n=K(B({type:"Feature",geometry:o,properties:{}}),s);if(!this.lastBearing)return void(this.lastBearing=n+180);let r;if(function(t,e){if(0===e)return t;const i=B(t);("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).forEach(t=>{const o=K(i,t)+e,s=Y(i,t),n=X(i,s,o);t[0]=n[0],t[1]=n[1]})}({type:"Feature",geometry:o,properties:{}},-(this.lastBearing-(n+180))),"Polygon"===o.type)r=o.coordinates[0];else{if("LineString"!==o.type)return;r=o.coordinates}r.forEach(t=>{t[0]=e(t[0],this.coordinatePrecision),t[1]=e(t[1],this.coordinatePrecision)});const a=this.midPoints.getUpdated(r)||[],h=this.selectionPoints.getUpdated(r)||[];this.store.updateGeometry([{id:i,geometry:o},...h,...a]),this.lastBearing=n+180}}class G extends f{constructor(t,e,i){super(t),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.lastDistance=void 0,this.config=t,this.selectionPoints=e,this.midPoints=i}reset(){this.lastDistance=void 0}scale(t,i){const o=this.store.getGeometryCopy(i);if("Polygon"!==o.type&&"LineString"!==o.type)return;const s=[t.lng,t.lat],r=n(B({type:"Feature",geometry:o,properties:{}}),s);if(!this.lastDistance)return void(this.lastDistance=r);let a;if(function(t,e){if(1===e)return t;const i=B(t);("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).forEach(t=>{const o=Y(i,t),s=K(i,t),n=X(i,o*e,s);t[0]=n[0],t[1]=n[1]})}({type:"Feature",geometry:o,properties:{}},1-(this.lastDistance-r)/r),"Polygon"===o.type)a=o.coordinates[0];else{if("LineString"!==o.type)return;a=o.coordinates}a.forEach(t=>{t[0]=e(t[0],this.coordinatePrecision),t[1]=e(t[1],this.coordinatePrecision)});const h=this.midPoints.getUpdated(a)||[],l=this.selectionPoints.getUpdated(a)||[];this.store.updateGeometry([{id:i,geometry:o},...l,...h]),this.lastDistance=r}}class U extends d{constructor(t){super(t),this.mode="select",this.dragEventThrottle=5,this.dragEventCount=0,this.selected=[],this.flags=void 0,this.keyEvents=void 0,this.selectionPoints=void 0,this.midPoints=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.flags=t&&t.flags?t.flags:{},this.keyEvents=t&&t.keyEvents?t.keyEvents:{deselect:"Escape",delete:"Delete",rotate:"r",scale:"s"},this.dragEventThrottle=t&&void 0!==t.dragEventThrottle&&t.dragEventThrottle||5}registerBehaviors(t){this.pixelDistance=new _(t),this.clickBoundingBox=new m(t),this.featuresAtMouseEvent=new b(t,this.clickBoundingBox,this.pixelDistance),this.selectionPoints=new D(t),this.midPoints=new w(t,this.selectionPoints),this.rotateFeature=new j(t,this.selectionPoints,this.midPoints),this.scaleFeature=new G(t,this.selectionPoints,this.midPoints),this.dragFeature=new F(t,this.featuresAtMouseEvent,this.selectionPoints,this.midPoints),this.dragCoordinate=new W(t,this.pixelDistance,this.selectionPoints,this.midPoints)}deselect(){this.store.updateProperty(this.selected.map(t=>({id:t,property:"selected",value:!1}))),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 e,i=Infinity;if(this.selectionPoints.ids.forEach(o=>{const s=this.store.getGeometryCopy(o),n=this.pixelDistance.measure(t,s.coordinates);n<this.pointerDistance&&n<i&&(i=n,e=this.store.getPropertiesCopy(o))}),!e)return;const o=e.selectionPointFeatureId,s=e.index,n=this.store.getPropertiesCopy(o),r=this.flags[n.mode];if(!(r&&r.feature&&r.feature.coordinates&&r.feature.coordinates.deletable))return;const a=this.store.getGeometryCopy(o);let h;if("Polygon"===a.type){if(h=a.coordinates[0],h.length<=4)return}else if("LineString"===a.type&&(h=a.coordinates,h.length<=3))return;h&&("Polygon"===a.type&&0===s||s===h.length-1?(h.shift(),h.pop(),h.push([h[0][0],h[0][1]])):h.splice(s,1),this.store.delete([...this.midPoints.ids,...this.selectionPoints.ids]),this.store.updateGeometry([{id:o,geometry:a}]),this.selectionPoints.create(h,a.type,o),r&&r.feature&&r.feature.coordinates&&r.feature.coordinates.midpoints&&this.midPoints.create(h,o,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(i.id,this.coordinatePrecision);else if(e){const{mode:t}=this.store.getPropertiesCopy(e.id),i=this.selected[0];if(i){if(i===e.id)return;this.deselect()}const o=this.flags[t];if(!o||!o.feature)return;this.selected=[e.id],this.store.updateProperty([{id:e.id,property:"selected",value:!0}]),this.onSelect(e.id);const{type:s,coordinates:n}=this.store.getGeometryCopy(e.id);let r;"LineString"===s?r=n:"Polygon"===s&&(r=n[0]),r&&o&&o.feature.coordinates&&(this.selectionPoints.create(r,s,e.id),o.feature.coordinates.midpoints&&this.midPoints.create(r,e.id,this.coordinatePrecision))}else if(this.selected.length)return void this.deselect()}start(){this.setStarted()}stop(){this.setStopped(),this.cleanUp()}onClick(t){"right"!==t.button?"left"===t.button&&this.onLeftClick(t):this.onRightClick(t)}onKeyDown(){}onKeyUp(t){if(t.key===this.keyEvents.delete){if(!this.selected.length)return;this.onDeselect(this.selected[0]),this.deleteSelected(),this.selectionPoints.delete(),this.midPoints.delete()}else t.key===this.keyEvents.deselect&&this.cleanUp()}cleanUp(){this.selected.length&&this.deselect()}onDragStart(t,e){if(!this.selected.length)return;const i=this.store.getPropertiesCopy(this.selected[0]),o=this.flags[i.mode];o&&o.feature&&(o.feature.draggable||o.feature.coordinates&&o.feature.coordinates.draggable)&&(this.dragEventCount=0,this.setCursor("grabbing"),this.dragFeature.position=[t.lng,t.lat],e(!1))}onDrag(t){const e=this.selected[0];if(!e||!this.dragFeature.position)return;const i=this.store.getPropertiesCopy(e),o=this.flags[i.mode];if(this.dragEventCount++,this.dragEventCount%this.dragEventThrottle!=0)if(o&&o.feature&&o.feature.rotateable&&t.heldKeys.includes("r"))this.rotateFeature.rotate(t,e);else if(o&&o.feature&&o.feature.scaleable&&t.heldKeys.includes("s"))this.scaleFeature.scale(t,e);else{if(o&&o.feature&&o.feature.coordinates&&o.feature.coordinates.draggable&&this.dragCoordinate.drag(t,e))return;o&&o.feature&&o.feature.draggable&&(this.dragFeature.drag(t,e),this.dragFeature.position=[t.lng,t.lat])}}onDragEnd(t,e){this.setCursor("grab"),this.dragFeature.position=void 0,this.rotateFeature.reset(),this.scaleFeature.reset(),e(!0)}onMouseMove(t){if(!this.selected.length||this.dragFeature.position)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)}),this.selectionPoints.ids.forEach(i=>{const o=this.store.getGeometryCopy(i);this.pixelDistance.measure(t,o.coordinates)<this.pointerDistance&&(e=!1)}),this.setCursor(e?"crosshair":"unset")}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});if(e.properties.mode===this.mode){if("Polygon"===e.geometry.type)return this.styles.selectedColor&&(i.polygonFillColor=this.styles.selectedColor),this.styles.selectedColor&&(i.polygonOutlineColor=this.styles.selectedColor),i.zIndex=10,i;if("Point"===e.geometry.type){if(e.properties.selectionPoint)return i.pointColor=this.styles.selectionPointColor||i.pointColor,i.pointOutlineColor=this.styles.selectionPointOutlineColor||i.pointOutlineColor,i.pointWidth=this.styles.selectionPointWidth||i.pointWidth,i.pointOutlineWidth=this.styles.midPointOutlineWidth||2,i.zIndex=30,i;if(e.properties.midPoint)return i.pointColor=this.styles.midPointColor||i.pointColor,i.pointOutlineColor=this.styles.midPointOutlineColor||i.pointOutlineColor,i.pointWidth=this.styles.midPointWidth||4,i.pointOutlineWidth=this.styles.midPointOutlineWidth||2,i.zIndex=40,i}}return i}}class T extends d{constructor(...t){super(...t),this.mode="static"}start(){}stop(){}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}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})}}const N=function(){return"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)})};function A(t,e,i,o,s){for(;o>i;){if(o-i>600){const n=o-i+1,r=e-i+1,a=Math.log(n),h=.5*Math.exp(2*a/3),l=.5*Math.sqrt(a*h*(n-h)/n)*(r-n/2<0?-1:1);A(t,e,Math.max(i,Math.floor(e-r*h/n+l)),Math.min(o,Math.floor(e+(n-r)*h/n+l)),s)}const n=t[e];let r=i,a=o;for(z(t,i,e),s(t[o],n)>0&&z(t,i,o);r<a;){for(z(t,r,a),r++,a--;s(t[r],n)<0;)r++;for(;s(t[a],n)>0;)a--}0===s(t[i],n)?z(t,i,a):(a++,z(t,a,o)),a<=e&&(i=a+1),e<=a&&(o=a-1)}}function z(t,e,i){const o=t[e];t[e]=t[i],t[i]=o}function J(t,e){$(t,0,t.children.length,e,t)}function $(t,e,i,o,s){s||(s=it([])),s.minX=Infinity,s.minY=Infinity,s.maxX=-Infinity,s.maxY=-Infinity;for(let n=e;n<i;n++){const e=t.children[n];R(s,t.leaf?o(e):e)}return s}function R(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 q(t,e){return t.minX-e.minX}function H(t,e){return t.minY-e.minY}function Z(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function Q(t){return t.maxX-t.minX+(t.maxY-t.minY)}function V(t,e){const i=Math.max(t.minX,e.minX),o=Math.max(t.minY,e.minY),s=Math.min(t.maxX,e.maxX),n=Math.min(t.maxY,e.maxY);return Math.max(0,s-i)*Math.max(0,n-o)}function tt(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function et(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function it(t){return{children:t,height:1,leaf:!0,minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity}}function ot(t,e,i,o,s){const n=[e,i];for(;n.length;){if((i=n.pop())-(e=n.pop())<=o)continue;const r=e+Math.ceil((i-e)/o/2)*o;A(t,r,e,i,s),n.push(e,r,r,i)}}class st{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(!et(t,e))return i;const o=this.toBBox,s=[];for(;e;){for(let n=0;n<e.children.length;n++){const r=e.children[n],a=e.leaf?o(r):r;et(t,a)&&(e.leaf?i.push(r):tt(t,a)?this._all(r,i):s.push(r))}e=s.pop()}return i}collides(t){let e=this.data;if(et(t,e)){const i=[];for(;e;){for(let o=0;o<e.children.length;o++){const s=e.children[o],n=e.leaf?this.toBBox(s):s;if(et(t,n)){if(e.leaf||tt(t,n))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=it([])}remove(t){let e=this.data;const i=this.toBBox(t),o=[],s=[];let n,r,a=!1;for(;e||o.length;){if(e||(e=o.pop(),r=o[o.length-1],n=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||!tt(e,i)?r?(n++,e=r.children[n],a=!1):e=null:(o.push(e),s.push(n),n=0,r=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 n,r=this._maxEntries;if(s<=r)return n=it(t.slice(e,i+1)),J(n,this.toBBox),n;o||(o=Math.ceil(Math.log(s)/Math.log(r)),r=Math.ceil(s/Math.pow(r,o-1))),n=it([]),n.leaf=!1,n.height=o;const a=Math.ceil(s/r),h=a*Math.ceil(Math.sqrt(r));ot(t,e,i,h,this.compareMinX);for(let s=e;s<=i;s+=h){const e=Math.min(s+h-1,i);ot(t,s,e,a,this.compareMinY);for(let i=s;i<=e;i+=a){const s=Math.min(i+a-1,e);n.children.push(this._build(t,i,s,o-1))}}return J(n,this.toBBox),n}_chooseSubtree(t,e,i,o){for(;o.push(e),!e.leaf&&o.length-1!==i;){let i,o=Infinity,r=Infinity;for(let a=0;a<e.children.length;a++){const h=e.children[a],l=Z(h),d=(s=t,n=h,(Math.max(n.maxX,s.maxX)-Math.min(n.minX,s.minX))*(Math.max(n.maxY,s.maxY)-Math.min(n.minY,s.minY))-l);d<r?(r=d,o=l<o?l:o,i=h):d===r&&l<o&&(o=l,i=h)}e=i||e.children[0]}var s,n;return e}_insert(t,e,i){const o=i?t:this.toBBox(t),s=[],n=this._chooseSubtree(o,this.data,e,s);for(n.children.push(t),R(n,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 n=this._chooseSplitIndex(i,s,o),r=it(i.children.splice(n,i.children.length-n));r.height=i.height,r.leaf=i.leaf,J(i,this.toBBox),J(r,this.toBBox),e?t[e-1].children.push(r):this._splitRoot(i,r)}_splitRoot(t,e){this.data=it([t,e]),this.data.height=t.height+1,this.data.leaf=!1,J(this.data,this.toBBox)}_chooseSplitIndex(t,e,i){let o,s=Infinity,n=Infinity;for(let r=e;r<=i-e;r++){const e=$(t,0,r,this.toBBox),a=$(t,r,i,this.toBBox),h=V(e,a),l=Z(e)+Z(a);h<s?(s=h,o=r,n=l<n?l:n):h===s&&l<n&&(n=l,o=r)}return o||i-e}_chooseSplitAxis(t,e,i){const o=t.leaf?this.compareMinX:q,s=t.leaf?this.compareMinY:H;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,n=$(t,0,e,s),r=$(t,i-e,i,s);let a=Q(n)+Q(r);for(let o=e;o<i-e;o++){const e=t.children[o];R(n,t.leaf?s(e):e),a+=Q(n)}for(let o=i-e-1;o>=e;o--){const e=t.children[o];R(r,t.leaf?s(e):e),a+=Q(r)}return a}_adjustParentBBoxes(t,e,i){for(let o=i;o>=0;o--)R(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():J(t[i],this.toBBox)}}class nt{constructor(t){this.tree=void 0,this.idToNode=void 0,this.nodeToId=void 0,this.tree=new st(t&&t.maxEntries?t.maxEntries:9),this.idToNode=new Map,this.nodeToId=new Map}setMaps(t,e){this.idToNode.set(String(t.id),e),this.nodeToId.set(e,String(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),n=Math.max(...i);return{minX:Math.min(...e),minY:s,maxX:Math.max(...e),maxY:n}}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))}}class rt{constructor(t){this.tracked=void 0,this.spatialIndex=void 0,this.store=void 0,this._onChange=()=>{},this.store={},this.spatialIndex=new nt,this.tracked=!t||!1!==t.tracked,t&&t.data&&this.load(t.data,t.validateFeature)}getId(){return N()}clone(t){return JSON.parse(JSON.stringify(t))}has(t){return Boolean(this.store[t])}load(t,e){if(0===t.length)return;const i=this.clone(t);i.forEach(t=>{t.id||(t.id=N()),this.tracked&&(t.properties.createdAt||(t.properties.createdAt=+new Date),t.properties.updatedAt||(t.properties.updatedAt=+new Date))});const o=[];i.forEach(t=>{e&&e(t),this.store[t.id]=t,o.push(t.id)}),this.spatialIndex.load(i),this._onChange(o,"create")}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)=>{t(e,i)}}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){const e=[];t.forEach(({id:t,property:i,value:o})=>{const s=this.store[t];if(!s)throw new Error(`No feature with this (${t}), can not update geometry`);e.push(t),s.properties[i]=o,this.tracked&&(s.properties.updatedAt=+new Date)}),this._onChange&&this._onChange(e,"update")}updateGeometry(t){const e=[];t.forEach(({id:t,geometry:i})=>{e.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(i),this.spatialIndex.update(o),this.tracked&&(o.properties.updatedAt=+new Date)}),this._onChange&&this._onChange(e,"update")}create(e){const i=[];return e.forEach(({geometry:e,properties:o})=>{let s,n=t({},o);this.tracked&&(s=+new Date,o?(n.createdAt="number"==typeof o.createdAt?o.createdAt:s,n.updatedAt="number"==typeof o.updatedAt?o.updatedAt:s):n={createdAt:s,updatedAt:s});const r=this.getId(),a={id:r,type:"Feature",geometry:e,properties:n};this.store[r]=a,this.spatialIndex.insert(a),i.push(r)}),this._onChange&&this._onChange([...i],"create"),i}delete(t){t.forEach(t=>{if(!this.store[t])throw new Error("No feature with this id, can not delete");delete this.store[t],this.spatialIndex.remove(t)}),this._onChange&&this._onChange([...t],"delete")}copyAll(){return this.clone(Object.keys(this.store).map(t=>this.store[t]))}}class at{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._adapter=e.adapter,this._mode=new T,this._modes=t({},e.modes,{static:this._mode}),this._eventListeners={change:[],select:[],deselect:[]},this._store=e.data?new rt({data:e.data}):new rt;const i=t=>{const e=[],i=this._store.copyAll().filter(i=>!t.includes(i.id)||(e.push(i),!1));return{changed:e,unchanged:i}},o=(t,e)=>{this._eventListeners.change.forEach(i=>{i(t,e)});const{changed:o,unchanged:s}=i(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())},s=t=>{this._eventListeners.select.forEach(e=>{e(t)});const{changed:e,unchanged:o}=i([t]);this._adapter.render({created:[],deletedIds:[],unchanged:o,updated:e},this.getModeStyles())},n=t=>{this._eventListeners.deselect.forEach(t=>{t()});const{changed:e,unchanged:o}=i([t]);e&&this._adapter.render({created:[],deletedIds:[],unchanged:o,updated:e},this.getModeStyles())};if(Object.keys(this._modes).forEach(t=>{this._modes[t].register({mode:t,store:this._store,setCursor:this._adapter.setCursor,project:this._adapter.project,unproject:this._adapter.unproject,onChange:o,onSelect:s,onDeselect:n})}),e.data){const t=this._store.copyAll().filter(t=>!(t.properties&&!Object.keys(this._modes).includes(t.properties.mode)&&(this._store.delete([t.id]),1)));this._adapter.render({created:t,deletedIds:[],unchanged:[],updated:[]},this.getModeStyles())}}getModeStyles(){const t={};return Object.keys(this._modes).forEach(e=>{t[e]=this._modes[e].styleFeature.bind(this._modes[e])}),t}setModeStyles(t,e){this._modes[t].styles=e}getSnapshot(){return this._store.copyAll()}get enabled(){return this._enabled}set enabled(t){throw new Error("Enabled is read only")}getCurrentMode(){return this._mode.mode}changeMode(t){if(!this._modes[t])throw new Error("No mode with this name present");this._mode.stop(),this._mode=this._modes[t],this._mode.start()}start(){this._enabled=!0,this._adapter.register({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=>{this._mode.onDrag(t)},onDragEnd:(t,e)=>{this._mode.onDragEnd(t,e)}})}stop(){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{at as TerraDraw,c as TerraDrawCircleMode,p as TerraDrawFreehandMode,i as TerraDrawGoogleMapsAdapter,o as TerraDrawLeafletAdapter,v as TerraDrawLineStringMode,s as TerraDrawMapboxGLAdapter,P as TerraDrawPointMode,x as TerraDrawPolygonMode,E as TerraDrawRenderMode,U as TerraDrawSelectMode};
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)Object.prototype.hasOwnProperty.call(i,o)&&(t[o]=i[o])}return t},t.apply(this,arguments)}function e(t,e=9){const i=Math.pow(10,e);return Math.round(t*i)/i}const i=(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)};class o{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}}class s{constructor(t){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._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){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),l=Array.from(this._heldKeys);return{lng:e(o,this._coordinatePrecision),lat:e(s,this._coordinatePrecision),containerX:r,containerY:n,button:a,heldKeys:l}}register(t){this._currentModeCallbacks=t,this._listeners=this.getAdapterListeners(),this._listeners.forEach(t=>{t.register()})}getCoordinatePrecision(){return this._coordinatePrecision}getAdapterListeners(){return[new o({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)},register:t=>{this.getMapEventElement().addEventListener("pointerdown",t)},unregister:t=>{this.getMapEventElement().removeEventListener("pointerdown",t)}}),new o({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},o={x:e.containerX,y:e.containerY},s=this._currentModeCallbacks.getState(),r=i(t,o);let n=!1;if(n="drawing"===s?r<this._minPixelDragDistanceDrawing:"selecting"===s?r<this._minPixelDragDistanceSelecting:r<this._minPixelDragDistance,n)return;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 o({name:"contextmenu",callback:t=>{this._currentModeCallbacks&&t.preventDefault()},register:t=>{this.getMapEventElement().addEventListener("contextmenu",t)},unregister:t=>{this.getMapEventElement().removeEventListener("contextmenu",t)}}),new o({name:"pointerup",callback:t=>{if(!this._currentModeCallbacks)return;if(t.target!==this.getMapEventElement())return;if(!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._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 o({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 o({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()}}class r extends s{constructor(t){if(super(t),this._cursor=void 0,this._cursorStyleSheet=void 0,this._lib=void 0,this._map=void 0,this._overlay=void 0,this._clickEventListener=void 0,this._mouseMoveEventListener=void 0,this.renderedFeatureIds=new Set,this._lib=t.lib,this._map=t.map,!this._map.getDiv().id)throw new Error("Google Map container div requires and id to be set");this._coordinatePrecision="number"==typeof t.coordinatePrecision?t.coordinatePrecision:9}get _layers(){var t;return Boolean((null==(t=this.renderedFeatureIds)?void 0:t.size)>0)}circlePath(t,e,i){const o=2*i;return`M ${t} ${e} m -${i}, 0 a ${i},${i} 0 1,0 ${o},0 a ${i},${i} 0 1,0 -${o},0`}register(t){super.register(t),this._overlay=new this._lib.OverlayView,this._overlay.draw=function(){},this._overlay.onAdd=()=>{this._currentModeCallbacks&&this._currentModeCallbacks.onReady&&this._currentModeCallbacks.onReady()},this._overlay.setMap(this._map),this._clickEventListener=this._map.data.addListener("click",t=>{const e=this._listeners.find(({name:t})=>"click"===t);e&&e.callback(t)}),this._mouseMoveEventListener=this._map.data.addListener("mousemove",t=>{const e=this._listeners.find(({name:t})=>"mousemove"===t);e&&e.callback(t)})}unregister(){var t,e,i;super.unregister(),null==(t=this._clickEventListener)||t.remove(),null==(e=this._mouseMoveEventListener)||e.remove(),null==(i=this._overlay)||i.setMap(null),this._overlay=void 0}getLngLatFromEvent(t){if(!this._overlay)throw new Error("cannot get overlay");const e=this._map.getBounds();if(!e)return null;const i=e.getNorthEast(),o=e.getSouthWest(),s=new this._lib.LatLngBounds(o,i),r=this._map.getDiv(),n=t.clientX-r.getBoundingClientRect().left,a=t.clientY-r.getBoundingClientRect().top,l=new this._lib.Point(n,a),h=this._overlay.getProjection();if(!h)return null;const c=h.fromContainerPixelToLatLng(l);return c&&s.contains(c)?{lng:c.lng(),lat:c.lat()}:null}getMapEventElement(){return this._map.getDiv().querySelector('div[style*="z-index: 3;"]')}project(t,e){if(!this._overlay)throw new Error("cannot get overlay");if(void 0===this._map.getBounds())throw new Error("cannot get bounds");const i=this._overlay.getProjection();if(void 0===i)throw new Error("cannot get projection");const o=i.fromLatLngToContainerPixel(new this._lib.LatLng(e,t));if(null===o)throw new Error("cannot project coordinates");return{x:o.x,y:o.y}}unproject(t,e){if(!this._overlay)throw new Error("cannot get overlay");const i=this._overlay.getProjection();if(void 0===i)throw new Error("cannot get projection");const o=i.fromContainerPixelToLatLng(new this._lib.Point(t,e));if(null===o)throw new Error("cannot unproject coordinates");return{lng:o.lng(),lat:o.lat()}}setCursor(t){if(t!==this._cursor){if(this._cursorStyleSheet&&(this._cursorStyleSheet.remove(),this._cursorStyleSheet=void 0),"unset"!==t){const e=this._map.getDiv(),i=document.querySelector(`#${e.id} .gm-style > div`);if(i){i.classList.add("terra-draw-google-maps");const e=document.createElement("style");e.innerHTML=`.terra-draw-google-maps { cursor: ${t} !important; }`,document.getElementsByTagName("head")[0].appendChild(e),this._cursorStyleSheet=e}}this._cursor=t}}setDoubleClickToZoom(t){this._map.setOptions(t?{disableDoubleClickZoom:!1}:{disableDoubleClickZoom:!0})}setDraggability(t){this._map.setOptions({draggable:t})}render(t,e){this._layers&&(t.deletedIds.forEach(t=>{const e=this._map.data.getFeatureById(t);e&&(this._map.data.remove(e),this.renderedFeatureIds.delete(t))}),t.updated.forEach(t=>{if(!t||!t.id)throw new Error("Feature is not valid");const e=this._map.data.getFeatureById(t.id);if(!e)throw new Error("Feature could not be found by Google Maps API");switch(e.forEachProperty((t,i)=>{e.setProperty(i,void 0)}),Object.keys(t.properties).forEach(i=>{e.setProperty(i,t.properties[i])}),t.geometry.type){case"Point":{const i=t.geometry.coordinates;e.setGeometry(new this._lib.Data.Point(new this._lib.LatLng(i[1],i[0])))}break;case"LineString":{const i=t.geometry.coordinates,o=[];for(let t=0;t<i.length;t++){const e=i[t],s=new this._lib.LatLng(e[1],e[0]);o.push(s)}e.setGeometry(new this._lib.Data.LineString(o))}break;case"Polygon":{const i=t.geometry.coordinates,o=[];for(let t=0;t<i.length;t++){const e=[];for(let o=0;o<i[t].length;o++){const s=new this._lib.LatLng(i[t][o][1],i[t][o][0]);e.push(s)}o.push(e)}e.setGeometry(new this._lib.Data.Polygon(o))}}}),t.created.forEach(t=>{this.renderedFeatureIds.add(t.id),this._map.data.addGeoJson(t)})),t.created.forEach(t=>{this.renderedFeatureIds.add(t.id)});const i={type:"FeatureCollection",features:[...t.created]};this._map.data.addGeoJson(i),this._map.data.setStyle(t=>{const i=t.getProperty("mode"),o=t.getGeometry();if(!o)throw new Error("Google Maps geometry not found");const s=o.getType(),r={};t.forEachProperty((t,e)=>{r[e]=t});const n=e[i]({type:"Feature",geometry:{type:s,coordinates:[]},properties:r});switch(s){case"Point":return{clickable:!1,icon:{path:this.circlePath(0,0,n.pointWidth),fillColor:n.pointColor,fillOpacity:1,strokeColor:n.pointOutlineColor,strokeWeight:n.pointOutlineWidth,rotation:0,scale:1}};case"LineString":return{strokeColor:n.lineStringColor,strokeWeight:n.lineStringWidth};case"Polygon":return{strokeColor:n.polygonOutlineColor,strokeWeight:n.polygonOutlineWidth,fillOpacity:n.polygonFillOpacity,fillColor:n.polygonFillColor}}throw Error("Unknown feature type")})}clearLayers(){this._layers&&(this._map.data.forEach(t=>{const e=t.getId();this.renderedFeatureIds.has(e)&&this._map.data.remove(t)}),this.renderedFeatureIds=new Set)}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this.clearLayers())}getCoordinatePrecision(){return super.getCoordinatePrecision()}}class n extends s{constructor(t){super(t),this._lib=void 0,this._map=void 0,this._panes={},this._container=void 0,this._layers={},this._lib=t.lib,this._map=t.map,this._container=this._map.getContainer()}createPaneStyleSheet(t,e){const i=document.createElement("style");return i.innerHTML=`.leaflet-${t}-pane {z-index: ${e+600};}`,document.getElementsByTagName("head")[0].appendChild(i),this._map.createPane(t),i}clearPanes(){Object.values(this._panes).forEach(t=>{t&&t.remove()}),this._panes={}}clearLayers(){Object.values(this._layers).forEach(t=>{this._map.removeLayer(t)}),this._layers={}}styleGeoJSONLayer(t){return{pointToLayer:(e,i)=>{if(!e.properties)throw new Error("Feature has no properties");if("string"!=typeof e.properties.mode)throw new Error("Feature mode is not a string");const o=(0,t[e.properties.mode])(e),s=String(o.zIndex);return this._panes[s]||(this._panes[s]=this.createPaneStyleSheet(s,o.zIndex)),this._lib.circleMarker(i,{radius:o.pointWidth,stroke:o.pointOutlineWidth||!1,color:o.pointOutlineColor,weight:o.pointOutlineWidth,fillOpacity:.8,fillColor:o.pointColor,pane:s,interactive:!1})},style:e=>{if(!e||!e.properties)return{};const i=e,o=(0,t[i.properties.mode])(i),s=String(o.zIndex);return this._panes[s]||(this._panes[s]=this.createPaneStyleSheet(s,o.zIndex)),"LineString"===i.geometry.type?{interactive:!1,color:o.lineStringColor,weight:o.lineStringWidth,pane:s}:"Polygon"===i.geometry.type?{interactive:!1,fillOpacity:o.polygonFillOpacity,fillColor:o.polygonFillColor,weight:o.polygonOutlineWidth,stroke:!0,color:o.polygonFillColor,pane:s}:{}}}}getLngLatFromEvent(t){const{containerX:e,containerY:i}=this.getMapElementXYPosition(t),o={x:e,y:i};if(isNaN(o.x)||isNaN(o.y))return null;const s=this._map.containerPointToLatLng(o);return isNaN(s.lng)||isNaN(s.lat)?null:{lng:s.lng,lat:s.lat}}getMapEventElement(){return this._container}setDraggability(t){t?this._map.dragging.enable():this._map.dragging.disable()}project(t,e){const{x:i,y:o}=this._map.latLngToContainerPoint({lng:t,lat:e});return{x:i,y:o}}unproject(t,e){const{lng:i,lat:o}=this._map.containerPointToLatLng({x:t,y:e});return{lng:i,lat:o}}setCursor(t){"unset"===t?this.getMapEventElement().style.removeProperty("cursor"):this.getMapEventElement().style.cursor=t}setDoubleClickToZoom(t){t?this._map.doubleClickZoom.enable():this._map.doubleClickZoom.disable()}render(t,e){t.created.forEach(t=>{this._layers[t.id]=this._lib.geoJSON(t,this.styleGeoJSONLayer(e)),this._map.addLayer(this._layers[t.id])}),t.deletedIds.forEach(t=>{this._map.removeLayer(this._layers[t])}),t.updated.forEach(t=>{this._map.removeLayer(this._layers[t.id]),this._layers[t.id]=this._lib.geoJSON(t,this.styleGeoJSONLayer(e)),this._map.addLayer(this._layers[t.id])})}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this.clearLayers(),this.clearPanes())}register(t){super.register(t),this._currentModeCallbacks&&this._currentModeCallbacks.onReady&&this._currentModeCallbacks.onReady()}getCoordinatePrecision(){return super.getCoordinatePrecision()}unregister(){return super.unregister()}}class a extends s{constructor(t){super(t),this._nextRender=void 0,this._map=void 0,this._container=void 0,this._rendered=!1,this.changedIds={deletion:!1,points:!1,linestrings:!1,polygons:!1,styling:!1},this._map=t.map,this._container=this._map.getContainer()}clearLayers(){this._rendered&&(["point","linestring","polygon"].forEach(t=>{const e=`td-${t.toLowerCase()}`;this._map.removeLayer(e),"polygon"===t&&this._map.removeLayer(e+"-outline"),this._map.removeSource(e)}),this._rendered=!1,this._nextRender&&(cancelAnimationFrame(this._nextRender),this._nextRender=void 0))}_addGeoJSONSource(t,e){this._map.addSource(t,{type:"geojson",data:{type:"FeatureCollection",features:e},tolerance:0})}_addFillLayer(t){return this._map.addLayer({id:t,source:t,type:"fill",paint:{"fill-color":["get","polygonFillColor"],"fill-opacity":["get","polygonFillOpacity"]}})}_addFillOutlineLayer(t,e){const i=this._map.addLayer({id:t+"-outline",source:t,type:"line",paint:{"line-width":["get","polygonOutlineWidth"],"line-color":["get","polygonOutlineColor"]}});return e&&this._map.moveLayer(t,e),i}_addLineLayer(t,e){const i=this._map.addLayer({id:t,source:t,type:"line",paint:{"line-width":["get","lineStringWidth"],"line-color":["get","lineStringColor"]}});return e&&this._map.moveLayer(t,e),i}_addPointLayer(t,e){const i=this._map.addLayer({id:t,source:t,type:"circle",paint:{"circle-stroke-color":["get","pointOutlineColor"],"circle-stroke-width":["get","pointOutlineWidth"],"circle-radius":["get","pointWidth"],"circle-color":["get","pointColor"]}});return e&&this._map.moveLayer(t,e),i}_addLayer(t,e,i){"Point"===e&&this._addPointLayer(t,i),"LineString"===e&&this._addLineLayer(t,i),"Polygon"===e&&(this._addFillLayer(t),this._addFillOutlineLayer(t,i))}_addGeoJSONLayer(t,e){const i=`td-${t.toLowerCase()}`;return this._addGeoJSONSource(i,e),this._addLayer(i,t),i}_setGeoJSONLayerData(t,e){const i=`td-${t.toLowerCase()}`;return this._map.getSource(i).setData({type:"FeatureCollection",features:e}),i}getEmptyGeometries(){return{points:[],linestrings:[],polygons:[]}}updateChangedIds(t){[...t.updated,...t.created].forEach(t=>{"Point"===t.geometry.type?this.changedIds.points=!0:"LineString"===t.geometry.type?this.changedIds.linestrings=!0:"Polygon"===t.geometry.type&&(this.changedIds.polygons=!0)}),t.deletedIds.length>0&&(this.changedIds.deletion=!0),0===t.created.length&&0===t.updated.length&&0===t.deletedIds.length&&(this.changedIds.styling=!0)}getLngLatFromEvent(t){const{left:e,top:i}=this._container.getBoundingClientRect();return this.unproject(t.clientX-e,t.clientY-i)}getMapEventElement(){return this._map.getCanvas()}setDraggability(t){t?(this._map.dragRotate.enable(),this._map.dragPan.enable()):(this._map.dragRotate.disable(),this._map.dragPan.disable())}project(t,e){const{x:i,y:o}=this._map.project({lng:t,lat:e});return{x:i,y:o}}unproject(t,e){const{lng:i,lat:o}=this._map.unproject({x:t,y:e});return{lng:i,lat:o}}setCursor(t){const e=this._map.getCanvas();"unset"===t?e.style.removeProperty("cursor"):e.style.cursor=t}setDoubleClickToZoom(t){t?this._map.doubleClickZoom.enable():this._map.doubleClickZoom.disable()}render(t,e){this.updateChangedIds(t),this._nextRender&&cancelAnimationFrame(this._nextRender),this._nextRender=requestAnimationFrame(()=>{const i=[...t.created,...t.updated,...t.unchanged],o=this.getEmptyGeometries();for(let t=0;t<i.length;t++){const s=i[t];Object.keys(e).forEach(t=>{const{properties:i}=s;if(i.mode!==t)return;const r=e[t](s);"Point"===s.geometry.type?(i.pointColor=r.pointColor,i.pointOutlineColor=r.pointOutlineColor,i.pointOutlineWidth=r.pointOutlineWidth,i.pointWidth=r.pointWidth,o.points.push(s)):"LineString"===s.geometry.type?(i.lineStringColor=r.lineStringColor,i.lineStringWidth=r.lineStringWidth,o.linestrings.push(s)):"Polygon"===s.geometry.type&&(i.polygonFillColor=r.polygonFillColor,i.polygonFillOpacity=r.polygonFillOpacity,i.polygonOutlineColor=r.polygonOutlineColor,i.polygonOutlineWidth=r.polygonOutlineWidth,o.polygons.push(s))})}const{points:s,linestrings:r,polygons:n}=o;if(this._rendered){const t=this.changedIds.deletion||this.changedIds.styling,e=t||this.changedIds.linestrings,i=t||this.changedIds.polygons;let o;(t||this.changedIds.points)&&(o=this._setGeoJSONLayerData("Point",s)),e&&this._setGeoJSONLayerData("LineString",r),i&&this._setGeoJSONLayerData("Polygon",n),o&&this._map.moveLayer(o)}else{const t=this._addGeoJSONLayer("Point",s);this._addGeoJSONLayer("LineString",r),this._addGeoJSONLayer("Polygon",n),this._rendered=!0,t&&this._map.moveLayer(t)}this.changedIds={points:!1,linestrings:!1,polygons:!1,deletion:!1,styling:!1}})}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this.clearLayers())}getCoordinatePrecision(){return super.getCoordinatePrecision()}unregister(){return super.unregister()}register(t){super.register(t),this._currentModeCallbacks&&this._currentModeCallbacks.onReady&&this._currentModeCallbacks.onReady()}}class l extends s{constructor(t){super(t),this.mapboxglAdapter=void 0,this.mapboxglAdapter=new a(t)}register(t){this.mapboxglAdapter.register(t)}unregister(){this.mapboxglAdapter.unregister()}getCoordinatePrecision(){return this.mapboxglAdapter.getCoordinatePrecision()}getLngLatFromEvent(t){return this.mapboxglAdapter.getLngLatFromEvent(t)}getMapEventElement(){return this.mapboxglAdapter.getMapEventElement()}setDraggability(t){this.mapboxglAdapter.setDraggability(t)}project(t,e){return this.mapboxglAdapter.project(t,e)}unproject(t,e){return this.mapboxglAdapter.unproject(t,e)}setCursor(t){this.mapboxglAdapter.setCursor(t)}setDoubleClickToZoom(t){this.mapboxglAdapter.setDoubleClickToZoom(t)}render(t,e){this.mapboxglAdapter.render(t,e)}clear(){this.mapboxglAdapter.clear()}}function h(){throw new Error("Unimplemented abstract method.")}let c=0;function d(t,e){return Array.isArray(t)?t:(void 0===e?e=[t,t]:(e[0]=t,e[1]=t),e)}class u{constructor(t){this.opacity_=t.opacity,this.rotateWithView_=t.rotateWithView,this.rotation_=t.rotation,this.scale_=t.scale,this.scaleArray_=d(t.scale),this.displacement_=t.displacement,this.declutterMode_=t.declutterMode}clone(){const t=this.getScale();return new u({opacity:this.getOpacity(),scale:Array.isArray(t)?t.slice():t,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()})}getOpacity(){return this.opacity_}getRotateWithView(){return this.rotateWithView_}getRotation(){return this.rotation_}getScale(){return this.scale_}getScaleArray(){return this.scaleArray_}getDisplacement(){return this.displacement_}getDeclutterMode(){return this.declutterMode_}getAnchor(){return h()}getImage(t){return h()}getHitDetectionImage(){return h()}getPixelRatio(t){return 1}getImageState(){return h()}getImageSize(){return h()}getOrigin(){return h()}getSize(){return h()}setDisplacement(t){this.displacement_=t}setOpacity(t){this.opacity_=t}setRotateWithView(t){this.rotateWithView_=t}setRotation(t){this.rotation_=t}setScale(t){this.scale_=t,this.scaleArray_=d(t)}listenImageChange(t){h()}load(){h()}unlistenImageChange(t){h()}}var g=u;const p={1:"The view center is not defined",2:"The view resolution is not defined",3:"The view rotation is not defined",4:"`image` and `src` cannot be provided at the same time",5:"`imgSize` must be set when `image` is provided",7:"`format` must be set when `url` is set",8:"Unknown `serverType` configured",9:"`url` must be configured or set using `#setUrl()`",10:"The default `geometryFunction` can only handle `Point` geometries",11:"`options.featureTypes` must be an Array",12:"`options.geometryName` must also be provided when `options.bbox` is set",13:"Invalid corner",14:"Invalid color",15:"Tried to get a value for a key that does not exist in the cache",16:"Tried to set a value for a key that is used already",17:"`resolutions` must be sorted in descending order",18:"Either `origin` or `origins` must be configured, never both",19:"Number of `tileSizes` and `resolutions` must be equal",20:"Number of `origins` and `resolutions` must be equal",22:"Either `tileSize` or `tileSizes` must be configured, never both",24:"Invalid extent or geometry provided as `geometry`",25:"Cannot fit empty extent provided as `geometry`",26:"Features must have an id set",27:"Features must have an id set",28:'`renderMode` must be `"hybrid"` or `"vector"`',30:"The passed `feature` was already added to the source",31:"Tried to enqueue an `element` that was already added to the queue",32:"Transformation matrix cannot be inverted",33:"Invalid units",34:"Invalid geometry layout",36:"Unknown SRS type",37:"Unknown geometry type found",38:"`styleMapValue` has an unknown type",39:"Unknown geometry type",40:"Expected `feature` to have a geometry",41:"Expected an `ol/style/Style` or an array of `ol/style/Style.js`",42:"Question unknown, the answer is 42",43:"Expected `layers` to be an array or a `Collection`",47:"Expected `controls` to be an array or an `ol/Collection`",48:"Expected `interactions` to be an array or an `ol/Collection`",49:"Expected `overlays` to be an array or an `ol/Collection`",50:"`options.featureTypes` should be an Array",51:"Either `url` or `tileJSON` options must be provided",52:"Unknown `serverType` configured",53:"Unknown `tierSizeCalculation` configured",55:"The {-y} placeholder requires a tile grid with extent",56:"mapBrowserEvent must originate from a pointer event",57:"At least 2 conditions are required",59:"Invalid command found in the PBF",60:"Missing or invalid `size`",61:"Cannot determine IIIF Image API version from provided image information JSON",62:"A `WebGLArrayBuffer` must either be of type `ELEMENT_ARRAY_BUFFER` or `ARRAY_BUFFER`",64:"Layer opacity must be a number",66:"`forEachFeatureAtCoordinate` cannot be used on a WebGL layer if the hit detection logic has not been enabled. This is done by providing adequate shaders using the `hitVertexShader` and `hitFragmentShader` properties of `WebGLPointsLayerRenderer`",67:"A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both",68:"A VectorTile source can only be rendered if it has a projection compatible with the view projection"};class y extends Error{constructor(t){const e=p[t];super(e),this.code=t,this.name="AssertionError",this.message=e}}var m=y;function f(t,e,i){return Math.min(Math.max(t,e),i)}const v=/^#([a-f0-9]{3}|[a-f0-9]{4}(?:[a-f0-9]{2}){0,2})$/i,_=/^([a-z]*)$|^hsla?\(.*\)$/i,C=function(){const t={};let e=0;return function(i){let o;if(t.hasOwnProperty(i))o=t[i];else{if(e>=1024){let i=0;for(const o in t)3&i++||(delete t[o],--e)}o=function(t){let e,i,o,s,r;if(_.exec(t)&&(t=function(t){const e=document.createElement("div");if(e.style.color=t,""!==e.style.color){document.body.appendChild(e);const t=getComputedStyle(e).color;return document.body.removeChild(e),t}return""}(t)),v.exec(t)){const n=t.length-1;let a;a=n<=4?1:2;const l=4===n||8===n;e=parseInt(t.substr(1+0*a,a),16),i=parseInt(t.substr(1+1*a,a),16),o=parseInt(t.substr(1+2*a,a),16),s=l?parseInt(t.substr(1+3*a,a),16):255,1==a&&(e=(e<<4)+e,i=(i<<4)+i,o=(o<<4)+o,l&&(s=(s<<4)+s)),r=[e,i,o,s/255]}else t.startsWith("rgba(")?(r=t.slice(5,-1).split(",").map(Number),P(r)):t.startsWith("rgb(")?(r=t.slice(4,-1).split(",").map(Number),r.push(1),P(r)):function(t,e){throw new m(14)}();return r}(i),t[i]=o,++e}return o}}();function P(t){return t[0]=f(t[0]+.5|0,0,255),t[1]=f(t[1]+.5|0,0,255),t[2]=f(t[2]+.5|0,0,255),t[3]=f(t[3],0,1),t}function x(t){return Array.isArray(t)?function(t){let e=t[0];e!=(0|e)&&(e=e+.5|0);let i=t[1];i!=(0|i)&&(i=i+.5|0);let o=t[2];return o!=(0|o)&&(o=o+.5|0),"rgba("+e+","+i+","+o+","+(void 0===t[3]?1:Math.round(100*t[3])/100)+")"}(t):t}const b="undefined"!=typeof navigator&&void 0!==navigator.userAgent?navigator.userAgent.toLowerCase():"";b.includes("firefox"),b.includes("safari")&&!b.includes("chrom")&&(b.includes("version/15.4")||/cpu (os|iphone os) 15_4 like mac os x/.test(b)),b.includes("webkit")&&b.includes("edge"),b.includes("macintosh");const M="undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas&&self instanceof WorkerGlobalScope;function S(t,e,i,o){let s;return s=i&&i.length?i.shift():M?new OffscreenCanvas(t||300,e||300):document.createElement("canvas"),t&&(s.width=t),e&&(s.height=e),s.getContext("2d",o)}!function(){let t=!1;try{const e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("_",null,e),window.removeEventListener("_",null,e)}catch(t){}}();var w=class{constructor(t){this.type=t,this.target=null}preventDefault(){this.defaultPrevented=!0}stopPropagation(){this.propagationStopped=!0}},E=class{constructor(){this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposeInternal())}disposeInternal(){}};function I(){}function D(t){for(const e in t)delete t[e]}var k=class extends E{constructor(t){super(),this.eventTarget_=t,this.pendingRemovals_=null,this.dispatching_=null,this.listeners_=null}addEventListener(t,e){if(!t||!e)return;const i=this.listeners_||(this.listeners_={}),o=i[t]||(i[t]=[]);o.includes(e)||o.push(e)}dispatchEvent(t){const e="string"==typeof t,i=e?t:t.type,o=this.listeners_&&this.listeners_[i];if(!o)return;const s=e?new w(t):t;s.target||(s.target=this.eventTarget_||this);const r=this.dispatching_||(this.dispatching_={}),n=this.pendingRemovals_||(this.pendingRemovals_={});let a;i in r||(r[i]=0,n[i]=0),++r[i];for(let t=0,e=o.length;t<e;++t)if(a="handleEvent"in o[t]?o[t].handleEvent(s):o[t].call(this,s),!1===a||s.propagationStopped){a=!1;break}if(0==--r[i]){let t=n[i];for(delete n[i];t--;)this.removeEventListener(i,I);delete r[i]}return a}disposeInternal(){this.listeners_&&D(this.listeners_)}getListeners(t){return this.listeners_&&this.listeners_[t]||void 0}hasListener(t){return!!this.listeners_&&(t?t in this.listeners_:Object.keys(this.listeners_).length>0)}removeEventListener(t,e){const i=this.listeners_&&this.listeners_[t];if(i){const o=i.indexOf(e);-1!==o&&(this.pendingRemovals_&&t in this.pendingRemovals_?(i[o]=I,++this.pendingRemovals_[t]):(i.splice(o,1),0===i.length&&delete this.listeners_[t]))}}};function F(t,e,i,o,s){if(o&&o!==t&&(i=i.bind(o)),s){const o=i;i=function(){t.removeEventListener(e,i),o.apply(this,arguments)}}const r={target:t,type:e,listener:i};return t.addEventListener(e,i),r}function O(t,e,i,o){return F(t,e,i,o,!0)}function L(t){t&&t.target&&(t.target.removeEventListener(t.type,t.listener),D(t))}var W=class extends k{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0}changed(){++this.revision_,this.dispatchEvent("change")}getRevision(){return this.revision_}onInternal(t,e){if(Array.isArray(t)){const i=t.length,o=new Array(i);for(let s=0;s<i;++s)o[s]=F(this,t[s],e);return o}return F(this,t,e)}onceInternal(t,e){let i;if(Array.isArray(t)){const o=t.length;i=new Array(o);for(let s=0;s<o;++s)i[s]=O(this,t[s],e)}else i=O(this,t,e);return e.ol_key=i,i}unInternal(t,e){const i=e.ol_key;if(i)!function(t){if(Array.isArray(t))for(let e=0,i=t.length;e<i;++e)L(t[e]);else L(t)}(i);else if(Array.isArray(t))for(let i=0,o=t.length;i<o;++i)this.removeEventListener(t[i],e);else this.removeEventListener(t,e)}};class j extends w{constructor(t,e,i){super(t),this.key=e,this.oldValue=i}}const B="#000",A="round";new class extends W{constructor(t){super(),this.ol_uid||(this.ol_uid=String(++c)),this.values_=null,void 0!==t&&this.setProperties(t)}get(t){let e;return this.values_&&this.values_.hasOwnProperty(t)&&(e=this.values_[t]),e}getKeys(){return this.values_&&Object.keys(this.values_)||[]}getProperties(){return this.values_&&Object.assign({},this.values_)||{}}hasProperties(){return!!this.values_}notify(t,e){let i;i=`change:${t}`,this.hasListener(i)&&this.dispatchEvent(new j(i,t,e)),i="propertychange",this.hasListener(i)&&this.dispatchEvent(new j(i,t,e))}addChangeListener(t,e){this.addEventListener(`change:${t}`,e)}removeChangeListener(t,e){this.removeEventListener(`change:${t}`,e)}set(t,e,i){const o=this.values_||(this.values_={});if(i)o[t]=e;else{const i=o[t];o[t]=e,i!==e&&this.notify(t,i)}}setProperties(t,e){for(const i in t)this.set(i,t[i],e)}applyProperties(t){t.values_&&Object.assign(this.values_||(this.values_={}),t.values_)}unset(t,e){if(this.values_&&t in this.values_){const i=this.values_[t];delete this.values_[t],function(t){let e;for(e in t)return!1;return!e}(this.values_)&&(this.values_=null),e||this.notify(t,i)}}};class N extends g{constructor(t){super({opacity:1,rotateWithView:void 0!==t.rotateWithView&&t.rotateWithView,rotation:void 0!==t.rotation?t.rotation:0,scale:void 0!==t.scale?t.scale:1,displacement:void 0!==t.displacement?t.displacement:[0,0],declutterMode:t.declutterMode}),this.canvas_=void 0,this.hitDetectionCanvas_=null,this.fill_=void 0!==t.fill?t.fill:null,this.origin_=[0,0],this.points_=t.points,this.radius_=void 0!==t.radius?t.radius:t.radius1,this.radius2_=t.radius2,this.angle_=void 0!==t.angle?t.angle:0,this.stroke_=void 0!==t.stroke?t.stroke:null,this.size_=null,this.renderOptions_=null,this.render()}clone(){const t=this.getScale(),e=new N({fill:this.getFill()?this.getFill().clone():void 0,points:this.getPoints(),radius:this.getRadius(),radius2:this.getRadius2(),angle:this.getAngle(),stroke:this.getStroke()?this.getStroke().clone():void 0,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),scale:Array.isArray(t)?t.slice():t,displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()});return e.setOpacity(this.getOpacity()),e}getAnchor(){const t=this.size_;if(!t)return null;const e=this.getDisplacement(),i=this.getScaleArray();return[t[0]/2-e[0]/i[0],t[1]/2+e[1]/i[1]]}getAngle(){return this.angle_}getFill(){return this.fill_}setFill(t){this.fill_=t,this.render()}getHitDetectionImage(){return this.hitDetectionCanvas_||this.createHitDetectionCanvas_(this.renderOptions_),this.hitDetectionCanvas_}getImage(t){let e=this.canvas_[t];if(!e){const i=this.renderOptions_,o=S(i.size*t,i.size*t);this.draw_(i,o,t),e=o.canvas,this.canvas_[t]=e}return e}getPixelRatio(t){return t}getImageSize(){return this.size_}getImageState(){return 2}getOrigin(){return this.origin_}getPoints(){return this.points_}getRadius(){return this.radius_}getRadius2(){return this.radius2_}getSize(){return this.size_}getStroke(){return this.stroke_}setStroke(t){this.stroke_=t,this.render()}listenImageChange(t){}load(){}unlistenImageChange(t){}calculateLineJoinSize_(t,e,i){if(0===e||Infinity===this.points_||"bevel"!==t&&"miter"!==t)return e;let o=this.radius_,s=void 0===this.radius2_?o:this.radius2_;if(o<s){const t=o;o=s,s=t}const r=2*Math.PI/(void 0===this.radius2_?this.points_:2*this.points_),n=s*Math.sin(r),a=o-Math.sqrt(s*s-n*n),l=Math.sqrt(n*n+a*a),h=l/n;if("miter"===t&&h<=i)return h*e;const c=e/2/h,d=e/2*(a/l),u=Math.sqrt((o+c)*(o+c)+d*d)-o;if(void 0===this.radius2_||"bevel"===t)return 2*u;const g=o*Math.sin(r),p=s-Math.sqrt(o*o-g*g),y=Math.sqrt(g*g+p*p)/g;return y<=i?2*Math.max(u,y*e/2-s-o):2*u}createRenderOptions(){let t,e=A,i=0,o=null,s=0,r=0;this.stroke_&&(t=this.stroke_.getColor(),null===t&&(t="#000"),t=x(t),r=this.stroke_.getWidth(),void 0===r&&(r=1),o=this.stroke_.getLineDash(),s=this.stroke_.getLineDashOffset(),e=this.stroke_.getLineJoin(),void 0===e&&(e=A),i=this.stroke_.getMiterLimit(),void 0===i&&(i=10));const n=this.calculateLineJoinSize_(e,r,i),a=Math.max(this.radius_,this.radius2_||0);return{strokeStyle:t,strokeWidth:r,size:Math.ceil(2*a+n),lineDash:o,lineDashOffset:s,lineJoin:e,miterLimit:i}}render(){this.renderOptions_=this.createRenderOptions();const t=this.renderOptions_.size;this.canvas_={},this.size_=[t,t]}draw_(t,e,i){if(e.scale(i,i),e.translate(t.size/2,t.size/2),this.createPath_(e),this.fill_){let t=this.fill_.getColor();null===t&&(t=B),e.fillStyle=x(t),e.fill()}this.stroke_&&(e.strokeStyle=t.strokeStyle,e.lineWidth=t.strokeWidth,t.lineDash&&(e.setLineDash(t.lineDash),e.lineDashOffset=t.lineDashOffset),e.lineJoin=t.lineJoin,e.miterLimit=t.miterLimit,e.stroke())}createHitDetectionCanvas_(t){if(this.fill_){let e=this.fill_.getColor(),i=0;if("string"==typeof e&&(e=function(t){return Array.isArray(t)?t:C(t)}(e)),null===e?i=1:Array.isArray(e)&&(i=4===e.length?e[3]:1),0===i){const e=S(t.size,t.size);this.hitDetectionCanvas_=e.canvas,this.drawHitDetectionCanvas_(t,e)}}this.hitDetectionCanvas_||(this.hitDetectionCanvas_=this.getImage(1))}createPath_(t){let e=this.points_;const i=this.radius_;if(Infinity===e)t.arc(0,0,i,0,2*Math.PI);else{const o=void 0===this.radius2_?i:this.radius2_;void 0!==this.radius2_&&(e*=2);const s=this.angle_-Math.PI/2,r=2*Math.PI/e;for(let n=0;n<e;n++){const e=s+n*r,a=n%2==0?i:o;t.lineTo(a*Math.cos(e),a*Math.sin(e))}t.closePath()}}drawHitDetectionCanvas_(t,e){e.translate(t.size/2,t.size/2),this.createPath_(e),e.fillStyle=B,e.fill(),this.stroke_&&(e.strokeStyle=t.strokeStyle,e.lineWidth=t.strokeWidth,t.lineDash&&(e.setLineDash(t.lineDash),e.lineDashOffset=t.lineDashOffset),e.lineJoin=t.lineJoin,e.miterLimit=t.miterLimit,e.stroke())}}var G=N;class R extends G{constructor(t){super({points:Infinity,fill:(t=t||{radius:5}).fill,radius:t.radius,stroke:t.stroke,scale:void 0!==t.scale?t.scale:1,rotation:void 0!==t.rotation?t.rotation:0,rotateWithView:void 0!==t.rotateWithView&&t.rotateWithView,displacement:void 0!==t.displacement?t.displacement:[0,0],declutterMode:t.declutterMode})}clone(){const t=this.getScale(),e=new R({fill:this.getFill()?this.getFill().clone():void 0,stroke:this.getStroke()?this.getStroke().clone():void 0,radius:this.getRadius(),scale:Array.isArray(t)?t.slice():t,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()});return e.setOpacity(this.getOpacity()),e}setRadius(t){this.radius_=t,this.render()}}var V=R;class T{constructor(t){this.color_=void 0!==(t=t||{}).color?t.color:null}clone(){const t=this.getColor();return new T({color:Array.isArray(t)?t.slice():t||void 0})}getColor(){return this.color_}setColor(t){this.color_=t}}var z=T;class U{constructor(t){this.color_=void 0!==(t=t||{}).color?t.color:null,this.lineCap_=t.lineCap,this.lineDash_=void 0!==t.lineDash?t.lineDash:null,this.lineDashOffset_=t.lineDashOffset,this.lineJoin_=t.lineJoin,this.miterLimit_=t.miterLimit,this.width_=t.width}clone(){const t=this.getColor();return new U({color:Array.isArray(t)?t.slice():t||void 0,lineCap:this.getLineCap(),lineDash:this.getLineDash()?this.getLineDash().slice():void 0,lineDashOffset:this.getLineDashOffset(),lineJoin:this.getLineJoin(),miterLimit:this.getMiterLimit(),width:this.getWidth()})}getColor(){return this.color_}getLineCap(){return this.lineCap_}getLineDash(){return this.lineDash_}getLineDashOffset(){return this.lineDashOffset_}getLineJoin(){return this.lineJoin_}getMiterLimit(){return this.miterLimit_}getWidth(){return this.width_}setColor(t){this.color_=t}setLineCap(t){this.lineCap_=t}setLineDash(t){this.lineDash_=t}setLineDashOffset(t){this.lineDashOffset_=t}setLineJoin(t){this.lineJoin_=t}setMiterLimit(t){this.miterLimit_=t}setWidth(t){this.width_=t}}var X=U;class Y{constructor(t){t=t||{},this.geometry_=null,this.geometryFunction_=H,void 0!==t.geometry&&this.setGeometry(t.geometry),this.fill_=void 0!==t.fill?t.fill:null,this.image_=void 0!==t.image?t.image:null,this.renderer_=void 0!==t.renderer?t.renderer:null,this.hitDetectionRenderer_=void 0!==t.hitDetectionRenderer?t.hitDetectionRenderer:null,this.stroke_=void 0!==t.stroke?t.stroke:null,this.text_=void 0!==t.text?t.text:null,this.zIndex_=t.zIndex}clone(){let t=this.getGeometry();return t&&"object"==typeof t&&(t=t.clone()),new Y({geometry:t,fill:this.getFill()?this.getFill().clone():void 0,image:this.getImage()?this.getImage().clone():void 0,renderer:this.getRenderer(),stroke:this.getStroke()?this.getStroke().clone():void 0,text:this.getText()?this.getText().clone():void 0,zIndex:this.getZIndex()})}getRenderer(){return this.renderer_}setRenderer(t){this.renderer_=t}setHitDetectionRenderer(t){this.hitDetectionRenderer_=t}getHitDetectionRenderer(){return this.hitDetectionRenderer_}getGeometry(){return this.geometry_}getGeometryFunction(){return this.geometryFunction_}getFill(){return this.fill_}setFill(t){this.fill_=t}getImage(){return this.image_}setImage(t){this.image_=t}getStroke(){return this.stroke_}setStroke(t){this.stroke_=t}getText(){return this.text_}setText(t){this.text_=t}getZIndex(){return this.zIndex_}setGeometry(t){"function"==typeof t?this.geometryFunction_=t:"string"==typeof t?this.geometryFunction_=function(e){return e.get(t)}:t?void 0!==t&&(this.geometryFunction_=function(){return t}):this.geometryFunction_=H,this.geometry_=t}setZIndex(t){this.zIndex_=t}}function H(t){return t.getGeometry()}var K=Y;const J={radians:6370997/(2*Math.PI),degrees:2*Math.PI*6370997/360,ft:.3048,m:1,"us-ft":1200/3937};var $=class{constructor(t){this.code_=t.code,this.units_=t.units,this.extent_=void 0!==t.extent?t.extent:null,this.worldExtent_=void 0!==t.worldExtent?t.worldExtent:null,this.axisOrientation_=void 0!==t.axisOrientation?t.axisOrientation:"enu",this.global_=void 0!==t.global&&t.global,this.canWrapX_=!(!this.global_||!this.extent_),this.getPointResolutionFunc_=t.getPointResolution,this.defaultTileGrid_=null,this.metersPerUnit_=t.metersPerUnit}canWrapX(){return this.canWrapX_}getCode(){return this.code_}getExtent(){return this.extent_}getUnits(){return this.units_}getMetersPerUnit(){return this.metersPerUnit_||J[this.units_]}getWorldExtent(){return this.worldExtent_}getAxisOrientation(){return this.axisOrientation_}isGlobal(){return this.global_}setGlobal(t){this.global_=t,this.canWrapX_=!(!t||!this.extent_)}getDefaultTileGrid(){return this.defaultTileGrid_}setDefaultTileGrid(t){this.defaultTileGrid_=t}setExtent(t){this.extent_=t,this.canWrapX_=!(!this.global_||!t)}setWorldExtent(t){this.worldExtent_=t}setGetPointResolution(t){this.getPointResolutionFunc_=t}getPointResolutionFunc(){return this.getPointResolutionFunc_}};const q=6378137,Z=Math.PI*q,Q=[-Z,-Z,Z,Z],tt=[-180,-85,180,85],et=q*Math.log(Math.tan(Math.PI/2));class it extends ${constructor(t){super({code:t,units:"m",extent:Q,global:!0,worldExtent:tt,getPointResolution:function(t,e){return t/Math.cosh(e[1]/q)}})}}const ot=[new it("EPSG:3857"),new it("EPSG:102100"),new it("EPSG:102113"),new it("EPSG:900913"),new it("http://www.opengis.net/def/crs/EPSG/0/3857"),new it("http://www.opengis.net/gml/srs/epsg.xml#3857")],st=[-180,-90,180,90],rt=6378137*Math.PI/180;class nt extends ${constructor(t,e){super({code:t,units:"degrees",extent:st,axisOrientation:e,global:!0,metersPerUnit:rt,worldExtent:st})}}const at=[new nt("CRS:84"),new nt("EPSG:4326","neu"),new nt("urn:ogc:def:crs:OGC:1.3:CRS84"),new nt("urn:ogc:def:crs:OGC:2:84"),new nt("http://www.opengis.net/def/crs/OGC/1.3/CRS84"),new nt("http://www.opengis.net/gml/srs/epsg.xml#4326","neu"),new nt("http://www.opengis.net/def/crs/EPSG/0/4326","neu")];let lt={},ht={};function ct(t,e,i){const o=t.getCode(),s=e.getCode();o in ht||(ht[o]={}),ht[o][s]=i}function dt(t,e,i){if(void 0!==e)for(let i=0,o=t.length;i<o;++i)e[i]=t[i];else e=t.slice();return e}function ut(t,e,i){if(void 0!==e&&t!==e){for(let i=0,o=t.length;i<o;++i)e[i]=t[i];t=e}return t}function gt(t){!function(t,e){lt[t]=e}(t.getCode(),t),ct(t,t,dt)}function pt(t){return"string"==typeof t?lt[e=t]||lt[e.replace(/urn:(x-)?ogc:def:crs:EPSG:(.*:)?(\w+)$/,"EPSG:$3")]||null:t||null;var e}function yt(t){!function(t){t.forEach(gt)}(t),t.forEach(function(e){t.forEach(function(t){e!==t&&ct(e,t,dt)})})}function mt(t,e,i){const o=function(t,e){return function(t,e){let i=function(t,e){let i;return t in ht&&e in ht[t]&&(i=ht[t][e]),i}(t.getCode(),e.getCode());return i||(i=ut),i}(pt(t),pt(e))}(e,i);return o(t,void 0,t.length)}var ft,vt,_t,Ct;yt(ot),yt(at),ft=ot,vt=function(t,e,i){const o=t.length;i=i>1?i:2,void 0===e&&(e=i>2?t.slice():new Array(o));for(let s=0;s<o;s+=i){e[s]=Z*t[s]/180;let i=q*Math.log(Math.tan(Math.PI*(+t[s+1]+90)/360));i>et?i=et:i<-et&&(i=-et),e[s+1]=i}return e},_t=function(t,e,i){const o=t.length;i=i>1?i:2,void 0===e&&(e=i>2?t.slice():new Array(o));for(let s=0;s<o;s+=i)e[s]=180*t[s]/Z,e[s+1]=360*Math.atan(Math.exp(t[s+1]/q))/Math.PI-90;return e},at.forEach(function(t){ft.forEach(function(e){ct(t,e,vt),ct(e,t,_t)})});class Pt extends s{constructor(t){super(t),this.stylingFunction=()=>({}),this._lib=void 0,this._map=void 0,this._container=void 0,this._projection="EPSG:3857",this._vectorSource=void 0,this._geoJSONReader=void 0,this._map=t.map,this._lib=t.lib,this._geoJSONReader=new this._lib.GeoJSON,this._container=this._map.getViewport(),this._container.setAttribute("tabindex","0");const e=new this._lib.VectorSource({features:[]});this._vectorSource=e;const i=new this._lib.VectorLayer({source:e,style:t=>this.getStyles(t,this.stylingFunction())});this._map.addLayer(i)}hexToRGB(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}getStyles(t,e){const i=t.getGeometry();if(i)return{Point:t=>{const i=t.getProperties(),o=e[i.mode]({type:"Feature",geometry:{type:"Point",coordinates:[]},properties:i});return new this._lib.Style({image:new V({radius:o.pointWidth,fill:new z({color:o.pointColor}),stroke:new X({color:o.pointOutlineColor,width:o.pointOutlineWidth})})})},LineString:t=>{const i=t.getProperties(),o=e[i.mode]({type:"Feature",geometry:{type:"LineString",coordinates:[]},properties:i});return new this._lib.Style({stroke:new this._lib.Stroke({color:o.lineStringColor,width:o.lineStringWidth})})},Polygon:t=>{const i=t.getProperties(),o=e[i.mode]({type:"Feature",geometry:{type:"LineString",coordinates:[]},properties:i}),{r:s,g:r,b:n}=this.hexToRGB(o.polygonFillColor);return new K({stroke:new X({color:o.polygonOutlineColor,width:o.polygonOutlineWidth}),fill:new z({color:`rgba(${s},${r},${n},${o.polygonFillOpacity})`})})}}[i.getType()](t)}clearLayers(){this._vectorSource&&this._vectorSource.clear()}addFeature(t){if(!this._vectorSource||!this._geoJSONReader)throw new Error("Vector Source not initalised");{const e=this._geoJSONReader.readFeature(t,{featureProjection:this._projection});this._vectorSource.addFeature(e)}}removeFeature(t){if(!this._vectorSource)throw new Error("Vector Source not initalised");{const e=this._vectorSource.getFeatureById(t);if(!e)return;this._vectorSource.removeFeature(e)}}getLngLatFromEvent(t){const{containerX:e,containerY:i}=this.getMapElementXYPosition(t);try{return this.unproject(e,i)}catch(t){return null}}getMapEventElement(){const t=this._container.querySelectorAll("canvas");if(t.length>1)throw Error("Terra Draw currently only supports 1 canvas with OpenLayers");return t[0]}setDraggability(t){this._map.getInteractions().forEach(e=>{"DragPan"===e.constructor.name&&e.setActive(t)})}project(t,e){const[i,o]=this._map.getPixelFromCoordinate(mt([t,e],"EPSG:4326","EPSG:3857"));return{x:i,y:o}}unproject(t,e){const[i,o]=function(t,e){const i=mt(t,"EPSG:3857","EPSG:4326"),o=i[0];return(o<-180||o>180)&&(i[0]=function(t,e){const i=t%360;return 360*i<0?i+360:i}(o+180)-180),i}(this._map.getCoordinateFromPixel([t,e]));return{lng:i,lat:o}}setCursor(t){"unset"===t?this.getMapEventElement().style.removeProperty("cursor"):this.getMapEventElement().style.cursor=t}setDoubleClickToZoom(t){this._map.getInteractions().forEach(function(e){"DoubleClickZoom"===e.constructor.name&&e.setActive(t)})}render(t,e){if(this.stylingFunction=()=>e,!this._vectorSource)throw new Error("Vector Layer source has disappeared");t.deletedIds.forEach(t=>{this.removeFeature(t)}),t.updated.forEach(t=>{this.removeFeature(t.id),this.addFeature(t)}),t.created.forEach(t=>{this.addFeature(t)})}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this.clearLayers())}register(t){super.register(t),this._currentModeCallbacks&&this._currentModeCallbacks.onReady&&this._currentModeCallbacks.onReady()}getCoordinatePrecision(){return super.getCoordinatePrecision()}unregister(){return super.unregister()}}class xt extends s{constructor(t){super(t),this._lib=void 0,this._mapView=void 0,this._container=void 0,this._featureIdAttributeName="__tdId",this._featureLayerName="__terraDrawFeatures",this._featureLayer=void 0,this._dragEnabled=!0,this._zoomEnabled=!0,this._dragHandler=void 0,this._doubleClickHandler=void 0,this._mapView=t.map,this._lib=t.lib,this._container=this._mapView.container,this._featureLayer=new this._lib.GraphicsLayer({id:this._featureLayerName}),this._mapView.map.add(this._featureLayer)}register(t){super.register(t),this._dragHandler=this._mapView.on("drag",t=>{this._dragEnabled||t.stopPropagation()}),this._doubleClickHandler=this._mapView.on("double-click",t=>{this._zoomEnabled||t.stopPropagation()}),this._currentModeCallbacks&&this._currentModeCallbacks.onReady&&this._currentModeCallbacks.onReady()}unregister(){super.unregister(),this._dragHandler&&this._dragHandler.remove(),this._doubleClickHandler&&this._doubleClickHandler.remove()}getCoordinatePrecision(){return super.getCoordinatePrecision()}getLngLatFromEvent(t){const{containerX:e,containerY:i}=this.getMapElementXYPosition(t);return this.unproject(e,i)}getMapEventElement(){return this._container.querySelector(".esri-view-surface")}setDraggability(t){this._dragEnabled=t}project(t,e){const i=new this._lib.Point({longitude:t,latitude:e}),{x:o,y:s}=this._mapView.toScreen(i);return{x:o,y:s}}unproject(t,e){const{latitude:i,longitude:o}=this._mapView.toMap({x:t,y:e});return{lng:o,lat:i}}setCursor(t){"unset"===t?this.getMapEventElement().style.removeProperty("cursor"):this.getMapEventElement().style.cursor=t}setDoubleClickToZoom(t){this._zoomEnabled=t}render(t,e){t.created.forEach(t=>{this.addFeature(t,e)}),t.updated.forEach(t=>{this.removeFeatureById(t.id),this.addFeature(t,e)}),t.deletedIds.forEach(t=>{this.removeFeatureById(t)})}clear(){this._featureLayer.graphics.removeAll()}removeFeatureById(t){const e=this._featureLayer.graphics.find(e=>e.attributes[this._featureIdAttributeName]===t);this._featureLayer.remove(e)}addFeature(t,e){const{coordinates:i,type:o}=t.geometry,s=e[t.properties.mode](t);let r,n;switch(o){case"Point":n=new this._lib.Point({latitude:i[1],longitude:i[0]}),r=new this._lib.SimpleMarkerSymbol({color:this.getColorFromHex(s.pointColor),size:2*s.pointWidth+"px",outline:{color:this.getColorFromHex(s.pointOutlineColor),width:s.pointOutlineWidth+"px"}});break;case"LineString":n=new this._lib.Polyline({paths:[i]}),r=new this._lib.SimpleLineSymbol({color:this.getColorFromHex(s.lineStringColor),width:s.lineStringWidth+"px"});break;case"Polygon":n=new this._lib.Polygon({rings:i}),r=new this._lib.SimpleFillSymbol({color:this.getColorFromHex(s.polygonFillColor,s.polygonFillOpacity),outline:{color:this.getColorFromHex(s.polygonOutlineColor),width:s.polygonOutlineWidth+"px"}})}const a=new this._lib.Graphic({geometry:n,symbol:r,attributes:{[this._featureIdAttributeName]:t.id}});"Point"===o?this._featureLayer.graphics.add(a):this._featureLayer.graphics.add(a,0)}getColorFromHex(t,e){const i=this._lib.Color.fromHex(t);return e&&(i.a=e),i}}!function(t){t.Commit="commit",t.Provisional="provisional",t.Finish="finish"}(Ct||(Ct={}));const bt="selected",Mt="midPoint",St="closingPoint";function wt(t){return Boolean(t&&"object"==typeof t&&null!==t&&!Array.isArray(t))}function Et(t){if(!function(t){return"number"==typeof t&&!isNaN(new Date(t).valueOf())}(t))throw new Error("updatedAt and createdAt are not valid timestamps");return!0}var It;!function(t){t.Drawing="drawing",t.Select="select",t.Static="static",t.Render="render"}(It||(It={}));class Dt{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([],"styling"),this._styles=t}registerBehaviors(t){}constructor(e){this._state=void 0,this._styles=void 0,this.behaviors=[],this.validate=void 0,this.pointerDistance=void 0,this.coordinatePrecision=void 0,this.onStyleChange=void 0,this.store=void 0,this.setDoubleClickToZoom=void 0,this.unproject=void 0,this.project=void 0,this.setCursor=void 0,this.projection=void 0,this.type=It.Drawing,this.mode="base",this._state="unregistered",this._styles=e&&e.styles?t({},e.styles):{},this.pointerDistance=e&&e.pointerDistance||40,this.validate=e&&e.validation,this.projection=e&&e.projection||"web-mercator"}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){if("unregistered"===this._state)throw new Error("Mode must be registered");const e=function(t,e){let i;if(wt(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(wt(t.geometry))if(wt(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)throw new Error("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";if(i)throw new Error(i);return!0}(t,this.store.idStrategy.isValidId);return this.validate?this.validate(t,{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Ct.Provisional}):e}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)}getStylingValue(t,e,i){return void 0===t?e:"function"==typeof t?t(i):t}}class kt extends Dt{constructor(...t){super(...t),this.type=It.Select}}function Ft(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,l=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(l),Math.sqrt(1-l))*6371e3/1e3}const Ot=6371008.8;function Lt(t){return t%360*Math.PI/180}function Wt(t){return t/(Ot/1e3)}function jt(t){return t%(2*Math.PI)*180/Math.PI}const Bt=57.29577951308232,At=.017453292519943295,Nt=6378137,Gt=(t,e)=>({x:0===t?0:t*At*Nt,y:0===e?0:Math.log(Math.tan(Math.PI/4+e*At/2))*Nt}),Rt=(t,e)=>({lng:0===t?0:Bt*(t/Nt),lat:0===e?0:(2*Math.atan(Math.exp(e/Nt))-Math.PI/2)*Bt});function Vt(t,e,i){const o=Lt(t[0]),s=Lt(t[1]),r=Lt(i),n=Wt(e),a=Math.asin(Math.sin(s)*Math.cos(n)+Math.cos(s)*Math.sin(n)*Math.cos(r));return[jt(o+Math.atan2(Math.sin(r)*Math.sin(n)*Math.cos(s),Math.cos(n)-Math.sin(s)*Math.sin(a))),jt(a)]}function Tt(t){const{center:i,radiusKilometers:o,coordinatePrecision:s}=t,r=t.steps?t.steps:64,n=[];for(let t=0;t<r;t++){const a=Vt(i,o,-360*t/r);n.push([e(a[0],s),e(a[1],s)])}return n.push(n[0]),{type:"Feature",geometry:{type:"Polygon",coordinates:[n]},properties:{}}}function zt(t){const e={epsilon:0};let i;if("Polygon"===t.geometry.type)i=t.geometry.coordinates;else{if("LineString"!==t.geometry.type)throw new Error("Self intersects only accepts Polygons and LineStrings");i=[t.geometry.coordinates]}const o=[];for(let t=0;t<i.length;t++)for(let e=0;e<i[t].length-1;e++)for(let o=0;o<i.length;o++)for(let s=0;s<i[o].length-1;s++)r(t,e,o,s);return o.length>0;function s(t){return t<0-e.epsilon||t>1+e.epsilon}function r(t,e,r,n){const a=i[t][e],l=i[t][e+1],h=i[r][n],c=i[r][n+1],d=function(t,e,i,o){if(Ut(t,i)||Ut(t,o)||Ut(e,i)||Ut(o,i))return null;const s=t[0],r=t[1],n=e[0],a=e[1],l=i[0],h=i[1],c=o[0],d=o[1],u=(s-n)*(h-d)-(r-a)*(l-c);return 0===u?null:[((s*a-r*n)*(l-c)-(s-n)*(l*d-h*c))/u,((s*a-r*n)*(h-d)-(r-a)*(l*d-h*c))/u]}(a,l,h,c);if(null===d)return;let u,g;u=l[0]!==a[0]?(d[0]-a[0])/(l[0]-a[0]):(d[1]-a[1])/(l[1]-a[1]),g=c[0]!==h[0]?(d[0]-h[0])/(c[0]-h[0]):(d[1]-h[1])/(c[1]-h[1]),s(u)||s(g)||(d.toString(),o.push(d))}}function Ut(t,e){return t[0]===e[0]&&t[1]===e[1]}function Xt(t,e){return 2===t.length&&"number"==typeof t[0]&&"number"==typeof t[1]&&Infinity!==t[0]&&Infinity!==t[1]&&(o=t[0])>=-180&&o<=180&&(i=t[1])>=-90&&i<=90&&Yt(t[0])<=e&&Yt(t[1])<=e;var i,o}function Yt(t){let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function Ht(t,e){return"Polygon"===t.geometry.type&&1===t.geometry.coordinates.length&&t.geometry.coordinates[0].length>=4&&t.geometry.coordinates[0].every(t=>Xt(t,e))&&(i=t.geometry.coordinates[0][0])[0]===(o=t.geometry.coordinates[0][t.geometry.coordinates[0].length-1])[0]&&i[1]===o[1];var i,o}function Kt(t,e){return Ht(t,e)&&!zt(t)}class Jt extends Dt{constructor(e){var i;super(e),this.mode="circle",this.center=void 0,this.clickCount=0,this.currentCircleId=void 0,this.keyEvents=void 0,this.cursors=void 0,this.startingRadiusKilometers=1e-5;const o={start:"crosshair"};if(this.cursors=e&&e.cursors?t({},o,e.cursors):o,null===(null==e?void 0:e.keyEvents))this.keyEvents={cancel:null,finish:null};else{const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i}this.startingRadiusKilometers=null!=(i=null==e?void 0:e.startingRadiusKilometers)?i:1e-5,this.validate=null==e?void 0:e.validation}close(){if(void 0===this.currentCircleId)return;const t=this.currentCircleId;if(this.validate&&t){const e=this.store.getGeometryCopy(t);if(!this.validate({type:"Feature",id:t,geometry:e,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Ct.Finish}))return}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(0===this.clickCount){this.center=[t.lng,t.lat];const e=Tt({center:this.center,radiusKilometers:this.startingRadiusKilometers,coordinatePrecision:this.coordinatePrecision}),[i]=this.store.create([{geometry:e.geometry,properties:{mode:this.mode,radiusKilometers:this.startingRadiusKilometers}}]);this.currentCircleId=i,this.clickCount++,this.setDrawing()}else 1===this.clickCount&&this.center&&void 0!==this.currentCircleId&&this.updateCircle(t),this.close()}onMouseMove(t){this.updateCircle(t)}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{void 0!==this.currentCircleId&&this.store.delete([this.currentCircleId])}catch(t){}this.center=void 0,this.currentCircleId=void 0,this.clickCount=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});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=10,i):i}validateFeature(t){return!!super.validateFeature(t)&&t.properties.mode===this.mode&&Kt(t,this.coordinatePrecision)}updateCircle(t){if(1===this.clickCount&&this.center&&this.currentCircleId){const i=Ft(this.center,[t.lng,t.lat]);let o;if("web-mercator"===this.projection){const s=function(t,e){const i=1e3*Ft(t,e);if(0===i)return 1;const{x:o,y:s}=Gt(t[0],t[1]),{x:r,y:n}=Gt(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:i,radiusKilometers:o,coordinatePrecision:s}=t,r=t.steps?t.steps:64,n=1e3*o,[a,l]=i,{x:h,y:c}=Gt(a,l),d=[];for(let t=0;t<r;t++){const i=360*t/r*Math.PI/180,o=n*Math.cos(i),a=n*Math.sin(i),[l,u]=[h+o,c+a],{lng:g,lat:p}=Rt(l,u);d.push([e(g,s),e(p,s)])}return d.push(d[0]),{type:"Feature",geometry:{type:"Polygon",coordinates:[d]},properties:{}}}({center:this.center,radiusKilometers:i*s,coordinatePrecision:this.coordinatePrecision})}else{if("globe"!==this.projection)throw new Error("Invalid projection");o=Tt({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:Ct.Provisional}))return;this.store.updateGeometry([{id:this.currentCircleId,geometry:o.geometry}]),this.store.updateProperty([{id:this.currentCircleId,property:"radiusKilometers",value:i}])}}}class $t extends Dt{constructor(e){super(e),this.mode="freehand",this.startingClick=!1,this.currentId=void 0,this.closingPointId=void 0,this.minDistance=void 0,this.keyEvents=void 0,this.cursors=void 0,this.preventPointsNearClose=void 0;const i={start:"crosshair",close:"pointer"};if(this.cursors=e&&e.cursors?t({},i,e.cursors):i,this.preventPointsNearClose=e&&e.preventPointsNearClose||!0,this.minDistance=e&&e.minDistance||20,null===(null==e?void 0:e.keyEvents))this.keyEvents={cancel:null,finish:null};else{const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i}this.validate=null==e?void 0:e.validation}close(){if(void 0===this.currentId)return;const t=this.currentId;if(this.validate&&t){const e=this.store.getGeometryCopy(t);if(!this.validate({type:"Feature",id:t,geometry:e,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Ct.Finish}))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;const e=this.store.getGeometryCopy(this.currentId),[o,s]=e.coordinates[0][e.coordinates[0].length-2],{x:r,y:n}=this.project(o,s),a=i({x:r,y:n},{x:t.containerX,y:t.containerY}),[l,h]=e.coordinates[0][0],{x:c,y:d}=this.project(l,h);if(i({x:c,y:d},{x:t.containerX,y:t.containerY})<this.pointerDistance){if(this.setCursor(this.cursors.close),this.preventPointsNearClose)return}else this.setCursor(this.cursors.start);if(a<this.minDistance)return;e.coordinates[0].pop();const u={type:"Polygon",coordinates:[[...e.coordinates[0],[t.lng,t.lat],e.coordinates[0][0]]]};this.validate&&!this.validate({type:"Feature",id:this.currentId,geometry:u,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Ct.Provisional})||this.store.updateGeometry([{id:this.currentId,geometry:u}])}onClick(t){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}},{geometry:{type:"Point",coordinates:[t.lng,t.lat]},properties:{mode:this.mode}}]);return this.currentId=e,this.closingPointId=i,this.startingClick=!0,void this.setDrawing()}this.close()}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentId&&this.store.delete([this.currentId]),this.closingPointId&&this.store.delete([this.closingPointId])}catch(t){}this.closingPointId=void 0,this.currentId=void 0,this.startingClick=!1,"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});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=10,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=40,i):i}validateFeature(t){return!!super.validateFeature(t)&&t.properties.mode===this.mode&&Ht(t,this.coordinatePrecision)}}class qt{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 Zt({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 Qt extends qt{constructor(t){super(t)}create(t){const{containerX:e,containerY:i}=t;return Zt({unproject:this.unproject,point:{x:e,y:i},pointerDistance:this.pointerDistance})}}class te extends qt{constructor(t){super(t)}measure(t,e){const{x:o,y:s}=this.project(e[0],e[1]);return i({x:o,y:s},{x:t.containerX,y:t.containerY})}}class ee extends qt{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)),this.getSnappableCoordinate=(t,e)=>this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode&&t.id!==e)),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={coord: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(e=>{const i=this.pixelDistance.measure(t,e);i<s.minDist&&i<this.pointerDistance&&(s.coord=e,s.minDist=i)})}),s.coord}}function ie(t,e,i){const o=Lt(t[0]),s=Lt(t[1]),r=Lt(i),n=Wt(e),a=Math.asin(Math.sin(s)*Math.cos(n)+Math.cos(s)*Math.sin(n)*Math.cos(r));return[jt(o+Math.atan2(Math.sin(r)*Math.sin(n)*Math.cos(s),Math.cos(n)-Math.sin(s)*Math.sin(a))),jt(a)]}function oe(t,e){const i=Lt(t[0]),o=Lt(e[0]),s=Lt(t[1]),r=Lt(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 jt(Math.atan2(n,a))}function se(t,e,i){const o=[],s=t.length;let r,n,a,l=0;for(let s=0;s<t.length&&!(e>=l&&s===t.length-1);s++){if(l>e&&0===o.length){if(r=e-l,!r)return o.push(t[s]),o;n=oe(t[s],t[s-1])-180,a=ie(t[s],r,n),o.push(a)}if(l>=i)return r=i-l,r?(n=oe(t[s],t[s-1])-180,a=ie(t[s],r,n),o.push(a),o):(o.push(t[s]),o);if(l>=e&&o.push(t[s]),s===t.length-1)return o;l+=Ft(t[s],t[s+1])}if(l<e&&t.length===s)throw new Error("Start position is beyond line");const h=t[t.length-1];return[h,h]}function re(t){return t*(Math.PI/180)}function ne(t){return t*(180/Math.PI)}class ae extends qt{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+=Ft(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=se(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=Ft(t,e),s=function(t,e,i){const o=[],s=re(t[1]),r=re(t[0]),n=re(e[1]),a=re(e[0]);i+=1;const l=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===l||isNaN(l))return o;for(let t=0;t<=i;t++){const e=t/i,h=Math.sin((1-e)*l)/Math.sin(l),c=Math.sin(e*l)/Math.sin(l),d=h*Math.cos(s)*Math.cos(r)+c*Math.cos(n)*Math.cos(a),u=h*Math.cos(s)*Math.sin(r)+c*Math.cos(n)*Math.sin(a),g=h*Math.sin(s)+c*Math.sin(n);if(isNaN(d)||isNaN(u)||isNaN(g))continue;const p=Math.atan2(g,Math.sqrt(d**2+u**2)),y=Math.atan2(u,d);isNaN(p)||isNaN(y)||o.push([ne(y),ne(p)])}return o.slice(1,-1)}(t,e,Math.floor(o/i));return this.limitCoordinates(s)}limitCoordinates(t){return t.map(t=>[e(t[0],this.config.coordinatePrecision),e(t[1],this.config.coordinatePrecision)])}}function le(t,e){return t[0]===e[0]&&t[1]===e[1]}class he extends Dt{constructor(e){super(e),this.mode="linestring",this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.keyEvents=void 0,this.snappingEnabled=void 0,this.cursors=void 0,this.mouseMove=!1,this.insertCoordinates=void 0,this.lastCommitedCoordinates=void 0,this.snapping=void 0,this.insertPoint=void 0;const i={start:"crosshair",close:"pointer"};if(this.cursors=e&&e.cursors?t({},i,e.cursors):i,this.snappingEnabled=!(!e||void 0===e.snapping)&&e.snapping,null===(null==e?void 0:e.keyEvents))this.keyEvents={cancel:null,finish:null};else{const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i}this.validate=null==e?void 0:e.validation,this.insertCoordinates=null==e?void 0:e.insertCoordinates}close(){if(void 0===this.currentId)return;const t=this.store.getGeometryCopy(this.currentId);t.coordinates.pop(),this.updateGeometries([...t.coordinates],void 0,Ct.Commit);const e=this.currentId;this.closingPointId&&this.store.delete([this.closingPointId]),this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.lastCommitedCoordinates=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(e,{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}))return;const s=[{id:this.currentId,geometry:o}];this.closingPointId&&e&&s.push({id:this.closingPointId,geometry:{type:"Point",coordinates:e}}),"commit"===i&&(this.lastCommitedCoordinates=o.coordinates),this.store.updateGeometry(s)}generateInsertCoordinates(t,e){if(!this.insertCoordinates||!this.lastCommitedCoordinates)throw new Error("Not able to insert coordinates");if("amount"!==this.insertCoordinates.strategy)throw new Error("Strategy does not exist");const i=Ft(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}}]);this.lastCommitedCoordinates=[t,t],this.currentId=e,this.currentCoordinate++,this.setDrawing()}firstUpdateToLine(t){if(!this.currentId)return;const e=this.store.getGeometryCopy(this.currentId).coordinates,[i]=this.store.create([{geometry:{type:"Point",coordinates:[...t]},properties:{mode:this.mode}}]);this.closingPointId=i,this.setCursor(this.cursors.close);const o=[...e,t];this.updateGeometries(o,void 0,Ct.Commit),this.currentCoordinate++}updateToLine(t,e){if(!this.currentId)return;const o=this.store.getGeometryCopy(this.currentId).coordinates,[s,r]=this.lastCommitedCoordinates?this.lastCommitedCoordinates[this.lastCommitedCoordinates.length-1]:o[o.length-2],{x:n,y:a}=this.project(s,r);if(i({x:n,y:a},{x:e.x,y:e.y})<this.pointerDistance)return void this.close();this.setCursor(this.cursors.close);const l=[...o,t];this.updateGeometries(l,o[o.length-1],Ct.Commit),this.currentCoordinate++}registerBehaviors(t){this.snapping=new ee(t,new te(t),new Qt(t)),this.insertPoint=new ae(t)}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 e=this.store.getGeometryCopy(this.currentId).coordinates;e.pop();const o=this.snappingEnabled&&this.snapping.getSnappableCoordinate(t,this.currentId)||[t.lng,t.lat];if(this.closingPointId){const[o,s]=e[e.length-1],{x:r,y:n}=this.project(o,s);i({x:r,y:n},{x:t.containerX,y:t.containerY})<this.pointerDistance&&this.setCursor(this.cursors.close)}let s=[...e,o];if(this.insertCoordinates&&this.currentId&&this.lastCommitedCoordinates){const t=this.lastCommitedCoordinates[this.lastCommitedCoordinates.length-1],e=o;if(!le(t,e)){const i=this.generateInsertCoordinates(t,e);s=[...this.lastCommitedCoordinates.slice(0,-1),...i,o]}}this.updateGeometries(s,void 0,Ct.Provisional)}onClick(t){this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1;const e=this.currentId&&this.snappingEnabled&&this.snapping.getSnappableCoordinate(t,this.currentId)||[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})}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel&&this.cleanUp(),t.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){try{this.currentId&&this.store.delete([this.currentId]),this.closingPointId&&this.store.delete([this.closingPointId])}catch(t){}this.closingPointId=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});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=10,i):"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode?(i.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,i.pointColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,i.pointWidth,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,"#ffffff",e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),i.zIndex=40,i):i}validateFeature(t){return!!super.validateFeature(t)&&"LineString"===t.geometry.type&&t.properties.mode===this.mode&&t.geometry.coordinates.length>=2}}function ce(t,e){return"Point"===t.geometry.type&&Xt(t.geometry.coordinates,e)}class de extends Dt{constructor(e){super(e),this.mode="point",this.cursors=void 0;const i={create:"crosshair"};this.cursors=e&&e.cursors?t({},i,e.cursors):i}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(t){if(!this.store)throw new Error("Mode must be registered first");const e={type:"Point",coordinates:[t.lng,t.lat]},i={mode:this.mode};if(this.validate&&!this.validate({type:"Feature",geometry:e,properties:i},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Ct.Finish}))return;const[o]=this.store.create([{geometry:e,properties:i}]);this.onFinish(o,{mode:this.mode,action:"draw"})}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){}onDragStart(){}onDrag(){}onDragEnd(){}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});return"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode&&(i.pointWidth=this.getNumericStylingValue(this.styles.pointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.pointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.pointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.pointOutlineWidth,2,e),i.zIndex=30),i}validateFeature(t){return!!super.validateFeature(t)&&t.properties.mode===this.mode&&ce(t,this.coordinatePrecision)}}class ue extends qt{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,[St]:!0}},{geometry:{type:"Point",coordinates:t[t.length-2]},properties:{mode:e,[St]:!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 ge extends Dt{constructor(e){super(e),this.mode="polygon",this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=void 0,this.snappingEnabled=void 0,this.snapping=void 0,this.pixelDistance=void 0,this.closingPoints=void 0,this.cursors=void 0,this.mouseMove=!1;const i={start:"crosshair",close:"pointer"};if(this.cursors=e&&e.cursors?t({},i,e.cursors):i,this.snappingEnabled=!(!e||void 0===e.snapping)&&e.snapping,null===(null==e?void 0:e.keyEvents))this.keyEvents={cancel:null,finish:null};else{const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i}}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]],Ct.Finish))return;const e=this.currentId;this.currentCoordinate=0,this.currentId=void 0,this.closingPoints.delete(),"drawing"===this.state&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:"draw"})}registerBehaviors(t){this.pixelDistance=new te(t),this.snapping=new ee(t,this.pixelDistance,new Qt(t)),this.closingPoints=new ue(t,this.pixelDistance)}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 e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):void 0,i=this.store.getGeometryCopy(this.currentId).coordinates[0];let o;if(e&&(t.lng=e[0],t.lat=e[1]),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.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.updatePolygonGeometry(o,Ct.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})||(this.store.updateGeometry([{id:this.currentId,geometry:i}]),0))}onClick(t){if(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=!1,0===this.currentCoordinate){const e=this.snappingEnabled?this.snapping.getSnappableCoordinateFirstClick(t):void 0;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}}]);this.currentId=i,this.currentCoordinate++,this.setDrawing()}else if(1===this.currentCoordinate&&this.currentId){const e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):void 0;e&&(t.lng=e[0],t.lat=e[1]);const i=this.store.getGeometryCopy(this.currentId);if(le([t.lng,t.lat],i.coordinates[0][0]))return;if(!this.updatePolygonGeometry([i.coordinates[0][0],[t.lng,t.lat],[t.lng,t.lat],i.coordinates[0][0]],Ct.Commit))return;this.currentCoordinate++}else if(2===this.currentCoordinate&&this.currentId){const e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):void 0;e&&(t.lng=e[0],t.lat=e[1]);const i=this.store.getGeometryCopy(this.currentId).coordinates[0];if(le([t.lng,t.lat],i[1]))return;if(!this.updatePolygonGeometry([i[0],i[1],[t.lng,t.lat],[t.lng,t.lat],i[0]],Ct.Commit))return;2===this.currentCoordinate&&this.closingPoints.create(i,"polygon"),this.currentCoordinate++}else if(this.currentId){const e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):void 0,i=this.store.getGeometryCopy(this.currentId).coordinates[0],{isClosing:o,isPreviousClosing:s}=this.closingPoints.isClosingPoint(t);if(s||o)this.close();else{if(e&&(t.lng=e[0],t.lat=e[1]),le([t.lng,t.lat],i[this.currentCoordinate-1]))return;const o=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(o.geometry.coordinates[0],Ct.Commit))return;this.currentCoordinate++,this.closingPoints.ids.length&&this.closingPoints.update(o.geometry.coordinates[0])}}}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(){this.setCursor("unset")}onDrag(){}onDragEnd(){this.setCursor(this.cursors.start)}cleanUp(){try{this.currentId&&this.store.delete([this.currentId]),this.closingPoints.ids.length&&this.closingPoints.delete()}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});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=10,i;if("Point"===e.geometry.type)return 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=30,i}return i}validateFeature(t){return!!super.validateFeature(t)&&t.properties.mode===this.mode&&Ht(t,this.coordinatePrecision)}}class pe extends Dt{constructor(e){super(e),this.mode="rectangle",this.center=void 0,this.clickCount=0,this.currentRectangleId=void 0,this.keyEvents=void 0,this.cursors=void 0;const i={start:"crosshair"};if(this.cursors=e&&e.cursors?t({},i,e.cursors):i,null===(null==e?void 0:e.keyEvents))this.keyEvents={cancel:null,finish:null};else{const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i}}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}))return;this.store.updateGeometry([{id:this.currentRectangleId,geometry:o}])}}close(){const t=this.currentRectangleId;this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),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(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}}]);this.currentRectangleId=e,this.clickCount++,this.setDrawing()}else this.updateRectangle(t,Ct.Finish),this.close()}onMouseMove(t){this.updateRectangle(t,Ct.Provisional)}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){this.currentRectangleId&&this.store.delete([this.currentRectangleId]),this.center=void 0,this.currentRectangleId=void 0,this.clickCount=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});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=10,i):i}validateFeature(t){return!!super.validateFeature(t)&&t.properties.mode===this.mode&&Kt(t,this.coordinatePrecision)}}class ye extends Dt{constructor(t){super({styles:t.styles}),this.type=It.Render,this.mode="render",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){return super.validateFeature(t)&&(ce(t,this.coordinatePrecision)||Ht(t,this.coordinatePrecision)||function(t,e){return"LineString"===t.geometry.type&&t.geometry.coordinates.length>=2&&t.geometry.coordinates.every(t=>Xt(t,e))}(t,this.coordinatePrecision))}}function me(t,e){const i=t,o=e,s=Lt(i[1]),r=Lt(o[1]);let n=Lt(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)),l=(jt(Math.atan2(n,a))+360)%360;return l>180?-(360-l):l}function fe(t,e,i){let o=e;e<0&&(o=-Math.abs(o));const s=o/Ot,r=t[0]*Math.PI/180,n=Lt(t[1]),a=Lt(i),l=s*Math.cos(a);let h=n+l;Math.abs(h)>Math.PI/2&&(h=h>0?Math.PI-h:-Math.PI-h);const c=Math.log(Math.tan(h/2+Math.PI/4)/Math.tan(n/2+Math.PI/4)),d=Math.abs(c)>1e-11?l/c:Math.cos(n),u=[(180*(r+s*Math.sin(a)/d)/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 ve(t,i,o,s,r){const n=s(t[0],t[1]),a=s(i[0],i[1]),{lng:l,lat:h}=r((n.x+a.x)/2,(n.y+a.y)/2);return[e(l,o),e(h,o)]}function _e(t,i,o){const s=fe(t,1e3*Ft(t,i)/2,me(t,i));return[e(s[0],o),e(s[1],o)]}function Ce({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=ve(t[n],t[n+1],e,o,i);else{if("globe"!==s)throw new Error("Invalid projection");a=_e(t[n],t[n+1],e)}r.push(a)}return r}class Pe extends qt{constructor(t,e){super(t),this.config=void 0,this.selectionPointBehavior=void 0,this._midPoints=[],this.config=t,this.selectionPointBehavior=e}get ids(){return this._midPoints.concat()}set ids(t){}insert(t,e){const i=this.store.getGeometryCopy(t),{midPointFeatureId:o,midPointSegment:s}=this.store.getPropertiesCopy(t),r=this.store.getGeometryCopy(o),n="Polygon"===r.type?r.coordinates[0]:r.coordinates;n.splice(s+1,0,i.coordinates),r.coordinates="Polygon"===r.type?[n]:n,this.store.updateGeometry([{id:o,geometry:r}]),this.store.delete([...this._midPoints,...this.selectionPointBehavior.ids]),this.create(n,o,e),this.selectionPointBehavior.create(n,r.type,o)}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 Ce({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,[Mt]:!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 Ce({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 xe extends qt{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,selectionPoint:!0,selectionPointFeatureId:i,index:t})))}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 be(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,l=n-1;e<n;l=e++)(s=a[e])[1]>(o=t)[1]!=(r=a[l])[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 Me=(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 Se extends qt{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,o,s=Infinity,r=Infinity;const n=this.createClickBoundingBox.create(t),a=this.store.search(n);for(let n=0;n<a.length;n++){const l=a[n],h=l.geometry;if("Point"===h.type){if(l.properties.selectionPoint||!e&&l.properties[Mt])continue;const n=this.pixelDistance.measure(t,h.coordinates);l.properties[Mt]&&n<this.pointerDistance&&n<r?(r=n,o=l):!l.properties[Mt]&&n<this.pointerDistance&&n<s&&(s=n,i=l)}else if("LineString"===h.type)for(let e=0;e<h.coordinates.length-1;e++){const o=h.coordinates[e],r=h.coordinates[e+1],n=Me({x:t.containerX,y:t.containerY},this.project(o[0],o[1]),this.project(r[0],r[1]));n<this.pointerDistance&&n<s&&(s=n,i=l)}else"Polygon"===h.type&&be([t.lng,t.lat],h.coordinates)&&(s=0,i=l)}return{clickedFeature:i,clickedMidPoint:o}}}class we extends qt{constructor(t,e,i,o){super(t),this.config=void 0,this.featuresAtMouseEvent=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.draggedFeatureId=null,this.dragPosition=void 0,this.config=t,this.featuresAtMouseEvent=e,this.selectionPoints=i,this.midPoints=o}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.featuresAtMouseEvent.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 i=r[t],o=[this.dragPosition[0]-s[0],this.dragPosition[1]-s[1]],n=e(i[0]-o[0],this.config.coordinatePrecision),a=e(i[1]-o[1],this.config.coordinatePrecision);if(n>180||n<-180||a>90||a<-90)return!1;r[t]=[n,a]}"Polygon"===o.type&&(r[r.length-1]=[r[0][0],r[0][1]]);const a=this.selectionPoints.getUpdated(r)||[],l=this.midPoints.getUpdated(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:Ct.Provisional}))return!1;this.store.updateGeometry([{id:this.draggedFeatureId,geometry:o},...a,...l]),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 Ee extends qt{constructor(t,e,i,o){super(t),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.draggedCoordinate={id:null,index:-1},this.config=t,this.pixelDistance=e,this.selectionPoints=i,this.midPoints=o}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}drag(t,e,i){if(!this.draggedCoordinate.id)return!1;const o=this.draggedCoordinate.index,s=this.store.getGeometryCopy(this.draggedCoordinate.id),r="LineString"===s.type?s.coordinates:s.coordinates[0],n=[t.lng,t.lat];if(t.lng>180||t.lng<-180||t.lat>90||t.lat<-90)return!1;if("Polygon"!==s.type||o!==r.length-1&&0!==o)r[o]=n;else{const t=r.length-1;r[0]=n,r[t]=n}const a=this.selectionPoints.getOneUpdated(o,n),l=a?[a]:[],h=this.midPoints.getUpdated(r)||[];return!("Point"!==s.type&&!e&&zt({type:"Feature",geometry:s,properties:{}})||i&&!i({type:"Feature",id:this.draggedCoordinate.id,geometry:s,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Ct.Provisional})||(this.store.updateGeometry([{id:this.draggedCoordinate.id,geometry:s},...l,...h]),0))}isDragging(){return null!==this.draggedCoordinate.id}startDragging(t,e){this.draggedCoordinate={id:t,index:e}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}}function Ie(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]}function De(t,e){t[0]+=t[0]-e[0]>180?-360:e[0]-t[0]>180?360:0;const i=Ot,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)),l=Math.abs(a)>1e-11?r/a:Math.cos(o);return Math.sqrt(r*r+l*l*n*n)*i}function ke(t){const e=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(t=>{const{x:e,y:i}=Gt(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,l]=t[r+1],h=s*l-a*n;e+=h,i+=(s+a)*h,o+=(n+l)*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 Fe extends qt{constructor(t,e,i){super(t),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.lastBearing=void 0,this.config=t,this.selectionPoints=e,this.midPoints=i}reset(){this.lastBearing=void 0}rotate(t,i,o){const s=this.store.getGeometryCopy(i);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){if(n=function({x:t,y:e},{x:i,y:o}){let s=Math.atan2(o-e,i-t);return s*=180/Math.PI,s>180?s-=360:s<-180&&(s+=360),s}(ke(a),Gt(t.lng,t.lat)),!this.lastBearing)return void(this.lastBearing=n);((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])=>Gt(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})=>[Rt(t,e).lng,Rt(t,e).lat]);"Polygon"===t.geometry.type?t.geometry.coordinates[0]=r:(console.log("rotatedCoordinates linestring",r),t.geometry.coordinates=r)})(a,-(this.lastBearing-n))}else{if("globe"!==this.config.projection)throw new Error("Unsupported projection");if(n=me(Ie({type:"Feature",geometry:s,properties:{}}),r),!this.lastBearing)return void(this.lastBearing=n+180);!function(t,e){if(0===e||360===e||-360===e)return t;const i=Ie(t);("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).forEach(t=>{const o=me(i,t)+e,s=De(i,t),r=fe(i,s,o);t[0]=r[0],t[1]=r[1]})}(a,-(this.lastBearing-(n+180)))}const l="Polygon"===s.type?s.coordinates[0]:s.coordinates;l.forEach(t=>{t[0]=e(t[0],this.coordinatePrecision),t[1]=e(t[1],this.coordinatePrecision)});const h=this.midPoints.getUpdated(l)||[],c=this.selectionPoints.getUpdated(l)||[];if(o&&!o({id:i,type:"Feature",geometry:s,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Ct.Provisional}))return!1;this.store.updateGeometry([{id:i,geometry:s},...c,...h]),"web-mercator"===this.projection?this.lastBearing=n:"globe"===this.projection&&(this.lastBearing=n+180)}}class Oe extends qt{constructor(t,e,i){super(t),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.lastDistance=void 0,this.config=t,this.selectionPoints=e,this.midPoints=i}reset(){this.lastDistance=void 0}scale(t,o,s){const r=this.store.getGeometryCopy(o);if("Polygon"!==r.type&&"LineString"!==r.type)return;const n=[t.lng,t.lat],a={type:"Feature",geometry:r,properties:{}};let l;const h=ke(a);if("web-mercator"===this.config.projection){const e=Gt(t.lng,t.lat);l=i(h,e)}else{if("globe"!==this.config.projection)throw new Error("Invalid projection");l=Ft(Ie({type:"Feature",geometry:r,properties:{}}),n)}if(!this.lastDistance)return void(this.lastDistance=l);const c=1-(this.lastDistance-l)/l;if("web-mercator"===this.config.projection){const{lng:t,lat:e}=Rt(h.x,h.y);!function(t,e,i){if(1===e)return t;const o=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(([t,e])=>Gt(t,e)),s=Gt(i[0],i[1]),r=o.map(t=>({x:s.x+(t.x-s.x)*e,y:s.y+(t.y-s.y)*e})).map(({x:t,y:e})=>[Rt(t,e).lng,Rt(t,e).lat]);"Polygon"===t.geometry.type?t.geometry.coordinates[0]=r:t.geometry.coordinates=r}(a,c,[t,e])}else"globe"===this.config.projection&&function(t,e,i,o="xy"){1===e||("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).forEach(t=>{const s=De(i,t),r=me(i,t),n=fe(i,s*e,r);"x"!==o&&"xy"!==o||(t[0]=n[0]),"y"!==o&&"xy"!==o||(t[1]=n[1])})}(a,c,Ie(a));const d="Polygon"===r.type?r.coordinates[0]:r.coordinates;d.forEach(t=>{t[0]=e(t[0],this.coordinatePrecision),t[1]=e(t[1],this.coordinatePrecision)});const u=this.midPoints.getUpdated(d)||[],g=this.selectionPoints.getUpdated(d)||[];if(s&&!s({id:o,type:"Feature",geometry:r,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Ct.Provisional}))return!1;this.store.updateGeometry([{id:o,geometry:r},...g,...u]),this.lastDistance=l}}class Le extends qt{constructor(t,e,i,o){super(t),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=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}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=ke(i);if(!n)return null;const a=Gt(r[0],r[1]),{closestBBoxIndex:l}=this.getIndexesWebMercator(o,a),h=Gt(t.lng,t.lat);return this.scaleWebMercator({closestBBoxIndex:l,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=ke(i);if(!n)return null;const a=Gt(r[0],r[1]),{closestBBoxIndex:l}=this.getIndexesWebMercator(o,a),h=Gt(t.lng,t.lat);return this.scaleFixedWebMercator({closestBBoxIndex:l,updatedCoords:s,webMercatorCursor:h,webMercatorSelected:a,webMercatorOrigin:n}),s}scaleFixedWebMercator({closestBBoxIndex:t,webMercatorOrigin:e,webMercatorSelected:o,webMercatorCursor:s,updatedCoords:r}){if(!this.isValidDragWebMercator(t,e.x-s.x,e.y-s.y))return null;let n=i(e,s)/i(e,o);return n<0&&(n=this.minimumScale),this.performWebMercatorScale(r,e.x,e.y,n,n),r}oppositeFixedWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{boundingBox:i,updatedCoords:o,selectedCoordinate:s}=e,r=Gt(s[0],s[1]),{oppositeBboxIndex:n,closestBBoxIndex:a}=this.getIndexesWebMercator(i,r),l={x:i[n][0],y:i[n][1]},h=Gt(t.lng,t.lat);return this.scaleFixedWebMercator({closestBBoxIndex:a,updatedCoords:o,webMercatorCursor:h,webMercatorSelected:r,webMercatorOrigin:l}),o}oppositeWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{boundingBox:i,updatedCoords:o,selectedCoordinate:s}=e,r=Gt(s[0],s[1]),{oppositeBboxIndex:n,closestBBoxIndex:a}=this.getIndexesWebMercator(i,r),l={x:i[n][0],y:i[n][1]},h=Gt(t.lng,t.lat);return this.scaleWebMercator({closestBBoxIndex:a,updatedCoords:o,webMercatorCursor:h,webMercatorSelected:r,webMercatorOrigin:l}),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 l=1;return 0!==n&&3!==t&&7!==t&&(l=1-(e.y-i.y-n)/n),this.validateScale(a,l)?(a<0&&(a=this.minimumScale),l<0&&(l=this.minimumScale),this.performWebMercatorScale(s,e.x,e.y,a,l),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:{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}=Gt(t[0],t[1]),a=e+(r-e)*o,l=i+(n-i)*s,{lng:h,lat:c}=Rt(a,l);t[0]=h,t[1]=c})}getBBoxWebMercator(t){const e=[Infinity,Infinity,-Infinity,-Infinity];(t=t.map(t=>{const{x:e,y:i}=Gt(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 o,s=Infinity;for(let r=0;r<t.length;r++){const n=i({x:e.x,y:e.y},{x:t[r][0],y:t[r][1]});n<s&&(o=r,s=n)}if(void 0===o)throw new Error("No closest coordinate found");return{oppositeBboxIndex:this.boundingBoxMaps.opposite[o],closestBBoxIndex:o}}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 i=r[t];if(i[0]=e(i[0],this.coordinatePrecision),i[1]=e(i[1],this.coordinatePrecision),!Xt(i,this.coordinatePrecision))return!1}const n=this.midPoints.getUpdated(r)||[],a=this.selectionPoints.getUpdated(r)||[],l={type:s.geometry.type,coordinates:"Polygon"===s.geometry.type?[r]:r};return!(o&&!o({id:this.draggedCoordinate.id,type:"Feature",geometry:l,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Ct.Provisional})||(this.store.updateGeometry([{id:this.draggedCoordinate.id,geometry:l},...a,...n]),0))}}class We extends kt{constructor(e){var i;super(e),this.mode="select",this.allowManualDeselection=!0,this.dragEventThrottle=5,this.dragEventCount=0,this.selected=[],this.flags=void 0,this.keyEvents=void 0,this.selectionPoints=void 0,this.midPoints=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.cursors=void 0,this.validations={},this.flags=e&&e.flags?e.flags:{};const o={pointerOver:"move",dragStart:"move",dragEnd:"move",insertMidpoint:"crosshair"};if(this.cursors=e&&e.cursors?t({},o,e.cursors):o,null===(null==e?void 0:e.keyEvents))this.keyEvents={deselect:null,delete:null,rotate:null,scale:null};else{const i={deselect:"Escape",delete:"Delete",rotate:["Control","r"],scale:["Control","s"]};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i}if(this.dragEventThrottle=e&&void 0!==e.dragEventThrottle&&e.dragEventThrottle||5,this.allowManualDeselection=null==(i=null==e?void 0:e.allowManualDeselection)||i,e&&e.flags&&e.flags)for(const t in e.flags){const i=e.flags[t].feature;i&&i.validation&&(this.validations[t]=i.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 te(t),this.clickBoundingBox=new Qt(t),this.featuresAtMouseEvent=new Se(t,this.clickBoundingBox,this.pixelDistance),this.selectionPoints=new xe(t),this.midPoints=new Pe(t,this.selectionPoints),this.rotateFeature=new Fe(t,this.selectionPoints,this.midPoints),this.scaleFeature=new Oe(t,this.selectionPoints,this.midPoints),this.dragFeature=new we(t,this.featuresAtMouseEvent,this.selectionPoints,this.midPoints),this.dragCoordinate=new Ee(t,this.pixelDistance,this.selectionPoints,this.midPoints),this.dragCoordinateResizeFeature=new Le(t,this.pixelDistance,this.selectionPoints,this.midPoints)}deselectFeature(){this.deselect()}deselect(){const t=this.selected.filter(t=>this.store.has(t)).map(t=>({id:t,property:bt,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 e,i=Infinity;if(this.selectionPoints.ids.forEach(o=>{const s=this.store.getGeometryCopy(o),r=this.pixelDistance.measure(t,s.coordinates);r<this.pointerDistance&&r<i&&(i=r,e=this.store.getPropertiesCopy(o))}),!e)return;const o=e.selectionPointFeatureId,s=e.index,r=this.store.getPropertiesCopy(o),n=this.flags[r.mode],a=this.validations[r.mode];if(!(n&&n.feature&&n.feature.coordinates&&n.feature.coordinates.deletable))return;const l=this.store.getGeometryCopy(o);let h;if("Polygon"===l.type){if(h=l.coordinates[0],h.length<=4)return}else if("LineString"===l.type&&(h=l.coordinates,h.length<=3))return;if(h){if("Polygon"===l.type&&0===s||s===h.length-1?(h.shift(),h.pop(),h.push([h[0][0],h[0][1]])):h.splice(s,1),a&&!a({id:o,type:"Feature",geometry:l,properties:r},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Ct.Commit}))return;this.store.delete([...this.midPoints.ids,...this.selectionPoints.ids]),this.store.updateGeometry([{id:o,geometry:l}]),this.selectionPoints.create(h,l.type,o),n&&n.feature&&n.feature.coordinates&&n.feature.coordinates.midpoints&&this.midPoints.create(h,o,this.coordinatePrecision)}}select(t,e=!0){if(this.selected[0]===t)return;const{mode:i}=this.store.getPropertiesCopy(t),o=this.flags[i];if(!o||!o.feature)return;const s=this.selected[0];if(s){if(s===t)return;this.deselect()}e&&this.setCursor(this.cursors.pointerOver),this.selected=[t],this.store.updateProperty([{id:t,property:"selected",value:!0}]),this.onSelect(t);const{type:r,coordinates:n}=this.store.getGeometryCopy(t);if("LineString"!==r&&"Polygon"!==r)return;const a="LineString"===r?n:n[0];a&&o&&o.feature.coordinates&&(this.selectionPoints.create(a,r,t),o.feature.coordinates.midpoints&&this.midPoints.create(a,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(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?"left"===t.button&&this.onLeftClick(t):this.onRightClick(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;this.onDeselect(this.selected[0]),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.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)))return;this.dragEventCount=0;const s=this.selected[0],r=this.dragCoordinate.getDraggableIndex(t,s);return o&&o.feature&&o.feature.coordinates&&(o.feature.coordinates.draggable||o.feature.coordinates.resizable)&&-1!==r?(this.setCursor(this.cursors.dragStart),o.feature.coordinates.resizable?this.dragCoordinateResizeFeature.startDragging(s,r):this.dragCoordinate.startDragging(s,r),void e(!1)):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){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)}this.dragCoordinate.isDragging()?this.dragCoordinate.drag(t,r,n):this.dragFeature.isDragging()?this.dragFeature.drag(t,n):e(!0)}onDragEnd(t,e){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 i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});if(e.properties.mode===this.mode&&"Point"===e.geometry.type){if(e.properties.selectionPoint)return i.pointColor=this.getHexColorStylingValue(this.styles.selectionPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectionPointOutlineColor,i.pointOutlineColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.selectionPointWidth,i.pointWidth,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectionPointOutlineWidth,2,e),i.zIndex=30,i;if(e.properties.midPoint)return i.pointColor=this.getHexColorStylingValue(this.styles.midPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.midPointOutlineColor,i.pointOutlineColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.midPointWidth,4,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.midPointOutlineWidth,2,e),i.zIndex=40,i}else if(e.properties[bt]){if("Polygon"===e.geometry.type)return i.polygonFillColor=this.getHexColorStylingValue(this.styles.selectedPolygonColor,i.polygonFillColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.selectedPolygonOutlineWidth,i.polygonOutlineWidth,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.selectedPolygonOutlineColor,i.polygonOutlineColor,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.selectedPolygonFillOpacity,i.polygonFillOpacity,e),i.zIndex=10,i;if("LineString"===e.geometry.type)return i.lineStringColor=this.getHexColorStylingValue(this.styles.selectedLineStringColor,i.lineStringColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.selectedLineStringWidth,i.lineStringWidth,e),i.zIndex=10,i;if("Point"===e.geometry.type)return i.pointWidth=this.getNumericStylingValue(this.styles.selectedPointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.selectedPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectedPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectedPointOutlineWidth,i.pointOutlineWidth,e),i.zIndex=10,i}return i}}class je extends Dt{constructor(...t){super(...t),this.type=It.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})}}function Be(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),l=.5*Math.exp(2*a/3),h=.5*Math.sqrt(a*l*(r-l)/r)*(n-r/2<0?-1:1);Be(t,e,Math.max(i,Math.floor(e-n*l/r+h)),Math.min(o,Math.floor(e+(r-n)*l/r+h)),s)}const r=t[e];let n=i,a=o;for(Ae(t,i,e),s(t[o],r)>0&&Ae(t,i,o);n<a;){for(Ae(t,n,a),n++,a--;s(t[n],r)<0;)n++;for(;s(t[a],r)>0;)a--}0===s(t[i],r)?Ae(t,i,a):(a++,Ae(t,a,o)),a<=e&&(i=a+1),e<=a&&(o=a-1)}}function Ae(t,e,i){const o=t[e];t[e]=t[i],t[i]=o}function Ne(t,e){Ge(t,0,t.children.length,e,t)}function Ge(t,e,i,o,s){s||(s=Ke([])),s.minX=Infinity,s.minY=Infinity,s.maxX=-Infinity,s.maxY=-Infinity;for(let r=e;r<i;r++){const e=t.children[r];Re(s,t.leaf?o(e):e)}return s}function Re(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 Ve(t,e){return t.minX-e.minX}function Te(t,e){return t.minY-e.minY}function ze(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function Ue(t){return t.maxX-t.minX+(t.maxY-t.minY)}function Xe(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 Ye(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function He(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function Ke(t){return{children:t,height:1,leaf:!0,minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity}}function Je(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;Be(t,n,e,i,s),r.push(e,n,n,i)}}class $e{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(!He(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;He(t,a)&&(e.leaf?i.push(n):Ye(t,a)?this._all(n,i):s.push(n))}e=s.pop()}return i}collides(t){let e=this.data;if(He(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(He(t,r)){if(e.leaf||Ye(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=Ke([])}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||!Ye(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=Ke(t.slice(e,i+1)),Ne(r,this.toBBox),r;o||(o=Math.ceil(Math.log(s)/Math.log(n)),n=Math.ceil(s/Math.pow(n,o-1))),r=Ke([]),r.leaf=!1,r.height=o;const a=Math.ceil(s/n),l=a*Math.ceil(Math.sqrt(n));Je(t,e,i,l,this.compareMinX);for(let s=e;s<=i;s+=l){const e=Math.min(s+l-1,i);Je(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 Ne(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 l=e.children[a],h=ze(l),c=(s=t,r=l,(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);c<n?(n=c,o=h<o?h:o,i=l):c===n&&h<o&&(o=h,i=l)}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),Re(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=Ke(i.children.splice(r,i.children.length-r));n.height=i.height,n.leaf=i.leaf,Ne(i,this.toBBox),Ne(n,this.toBBox),e?t[e-1].children.push(n):this._splitRoot(i,n)}_splitRoot(t,e){this.data=Ke([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Ne(this.data,this.toBBox)}_chooseSplitIndex(t,e,i){let o,s=Infinity,r=Infinity;for(let n=e;n<=i-e;n++){const e=Ge(t,0,n,this.toBBox),a=Ge(t,n,i,this.toBBox),l=Xe(e,a),h=ze(e)+ze(a);l<s?(s=l,o=n,r=h<r?h:r):l===s&&h<r&&(r=h,o=n)}return o||i-e}_chooseSplitAxis(t,e,i){const o=t.leaf?this.compareMinX:Ve,s=t.leaf?this.compareMinY:Te;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=Ge(t,0,e,s),n=Ge(t,i-e,i,s);let a=Ue(r)+Ue(n);for(let o=e;o<i-e;o++){const e=t.children[o];Re(r,t.leaf?s(e):e),a+=Ue(r)}for(let o=i-e-1;o>=e;o--){const e=t.children[o];Re(n,t.leaf?s(e):e),a+=Ue(n)}return a}_adjustParentBBoxes(t,e,i){for(let o=i;o>=0;o--)Re(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():Ne(t[i],this.toBBox)}}class qe{constructor(t){this.tree=void 0,this.idToNode=void 0,this.nodeToId=void 0,this.tree=new $e(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 Ze={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 Qe{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 qe,this.tracked=!t||!1!==t.tracked,this.idStrategy=t&&t.idStrategy?t.idStrategy:Ze}clone(t){return JSON.parse(JSON.stringify(t))}getId(){return this.idStrategy.getId()}has(t){return Boolean(this.store[t])}load(t,e){if(0===t.length)return;const i=this.clone(t);i.forEach(t=>{null==t.id&&(t.id=this.idStrategy.getId()),this.tracked&&(t.properties.createdAt?Et(t.properties.createdAt):t.properties.createdAt=+new Date,t.properties.updatedAt?Et(t.properties.updatedAt):t.properties.updatedAt=+new Date)});const o=[];i.forEach(t=>{const i=t.id;if(e&&!e(t))throw new Error(`Feature is not ${i} valid: ${JSON.stringify(t)}`);if(this.has(i))throw new Error(`Feature already exists with this id: ${i}`);this.store[i]=t,o.push(i)}),this.spatialIndex.load(i),this._onChange(o,"create")}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)=>{t(e,i)}}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){const e=[];t.forEach(({id:t,property:i,value:o})=>{const s=this.store[t];if(!s)throw new Error(`No feature with this (${t}), can not update geometry`);e.push(t),s.properties[i]=o,this.tracked&&(s.properties.updatedAt=+new Date)}),this._onChange&&this._onChange(e,"update")}updateGeometry(t){const e=[];t.forEach(({id:t,geometry:i})=>{e.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(i),this.spatialIndex.update(o),this.tracked&&(o.properties.updatedAt=+new Date)}),this._onChange&&this._onChange(e,"update")}create(e){const i=[];return e.forEach(({geometry:e,properties:o})=>{let s,r=t({},o);this.tracked&&(s=+new Date,o?(r.createdAt="number"==typeof o.createdAt?o.createdAt:s,r.updatedAt="number"==typeof o.updatedAt?o.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),i.push(n)}),this._onChange&&this._onChange([...i],"create"),i}delete(t){t.forEach(t=>{if(!this.store[t])throw new Error("No feature with this id, can not delete");delete this.store[t],this.spatialIndex.remove(t)}),this._onChange&&this._onChange([...t],"delete")}copyAll(){return this.clone(Object.keys(this.store).map(t=>this.store[t]))}clear(){this.store={},this.spatialIndex.clear()}size(){return Object.keys(this.store).length}}function ti(t){const e=t.coordinates;let i=0;if(e&&e.length>0){i+=Math.abs(oi(e[0]));for(let t=1;t<e.length;t++)i-=Math.abs(oi(e[t]))}return i}const ei=Ot*Ot/2,ii=Math.PI/180;function oi(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]*ii-t[o][0]*ii)*Math.sin(t[o+1===e?0:o+1][1]*ii),o++;return i*ei}const si=(t,e)=>"Polygon"===t.geometry.type&&ti(t.geometry)>e,ri=(t,e)=>"Polygon"===t.geometry.type&&ti(t.geometry)<e,ni=t=>("Polygon"===t.geometry.type||"LineString"===t.geometry.type)&&!zt(t);class ai{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 je;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===It.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 Qe({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)=>{if(!this._enabled)return;this._eventListeners.change.forEach(i=>{i(t,e)});const{changed:i,unchanged:o}=r(t);"create"===e?this._adapter.render({created:i,deletedIds:[],unchanged:o,updated:[]},this.getModeStyles()):"update"===e?this._adapter.render({created:[],deletedIds:[],unchanged:o,updated:i},this.getModeStyles()):"delete"===e?this._adapter.render({created:[],deletedIds:t,unchanged:o,updated:[]},this.getModeStyles()):"styling"===e&&this._adapter.render({created:[],deletedIds:[],unchanged:o,updated:[]},this.getModeStyles())},l=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:l,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[bt]?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},o){const s=o&&void 0!==o.pointerDistance?o.pointerDistance:30,r=!o||void 0===o.ignoreSelectFeatures||o.ignoreSelectFeatures,n=this._adapter.unproject.bind(this._adapter),a=this._adapter.project.bind(this._adapter),l=a(t,e),h=Zt({unproject:n,point:l,pointerDistance:s});return this._store.search(h).filter(o=>{if(r&&(o.properties[Mt]||o.properties.selectionPoint))return!1;if("Point"===o.geometry.type){const t=o.geometry.coordinates,e=a(t[0],t[1]);return i(l,e)<s}if("LineString"===o.geometry.type){const t=o.geometry.coordinates;for(let e=0;e<t.length-1;e++){const i=t[e],o=t[e+1];if(Me(l,a(i[0],i[1]),a(o[0],o[1]))<s)return!0}return!1}return!!be([t,e],o.geometry.coordinates)||void 0})}getSelectMode(){if(this.checkEnabled(),!this._instanceSelectMode)throw new Error("No select mode defined in instance");return this.getMode()!==this._instanceSelectMode&&this.setMode(this._instanceSelectMode),this._modes[this._instanceSelectMode]}setModeStyles(t,e){if(this.checkEnabled(),!this._modes[t])throw new Error("No mode with this name present");this._modes[t].styles=e}getSnapshot(){return this._store.copyAll()}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}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(),this._store.delete(t)}selectFeature(t){this.getSelectMode().selectFeature(t)}deselectFeature(t){this.getSelectMode().deselectFeature(t)}getFeatureId(){return this._store.getId()}hasFeature(t){return this._store.has(t)}addFeatures(t){this.checkEnabled(),0!==t.length&&this._store.load(t,t=>{if(Boolean(t&&"object"==typeof t&&"properties"in t&&"object"==typeof t.properties&&null!==t.properties&&"mode"in t.properties)){const e=this._modes[t.properties.mode];return!!e&&e.validateFeature.bind(e)(t)}return!1})}start(){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=!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)}}const li={TerraDrawBaseDrawMode:Dt,TerraDrawBaseAdapter:s};export{ai as TerraDraw,xt as TerraDrawArcGISMapsSDKAdapter,Jt as TerraDrawCircleMode,li as TerraDrawExtend,$t as TerraDrawFreehandMode,r as TerraDrawGoogleMapsAdapter,n as TerraDrawLeafletAdapter,he as TerraDrawLineStringMode,l as TerraDrawMapLibreGLAdapter,a as TerraDrawMapboxGLAdapter,Pt as TerraDrawOpenLayersAdapter,de as TerraDrawPointMode,ge as TerraDrawPolygonMode,pe as TerraDrawRectangleMode,ye as TerraDrawRenderMode,We as TerraDrawSelectMode,ri as ValidateMaxAreaSquareMeters,si as ValidateMinAreaSquareMeters,ni as ValidateNotSelfIntersecting};
2
2
  //# sourceMappingURL=terra-draw.modern.js.map