UNPKG

@watergis/maplibre-gl-terradraw

Version:

This plugin is to add controls to your Maplibre for drawing powered by Terra Draw library.

7 lines 298 kB
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("maplibre-gl")):typeof define==`function`&&define.amd?define([`exports`,`maplibre-gl`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.MaplibreTerradrawControl={},e.maplibregl))})(this,function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},n.apply(null,arguments)}var r=`draw`,i=`edit`,a=`deleteCoordinate`,o=`insertMidpoint`,s;(function(e){e.Commit=`commit`,e.Provisional=`provisional`,e.Finish=`finish`})(s||={});var c=`https://raw.githubusercontent.com/JamesLMilner/terra-draw/refs/heads/main/assets/markers/marker-blue.png`,l={SELECTED:`selected`,MID_POINT:`midPoint`,SELECTION_POINT_FEATURE_ID:`selectionPointFeatureId`,SELECTION_POINT:`selectionPoint`},u={MODE:`mode`,CURRENTLY_DRAWING:`currentlyDrawing`,EDITED:`edited`,CLOSING_POINT:`closingPoint`,SNAPPING_POINT:`snappingPoint`,COORDINATE_POINT:`coordinatePoint`,COORDINATE_POINT_FEATURE_ID:`coordinatePointFeatureId`,COORDINATE_POINT_IDS:`coordinatePointIds`,PROVISIONAL_COORDINATE_COUNT:`provisionalCoordinateCount`,COMMITTED_COORDINATE_COUNT:`committedCoordinateCount`,MARKER:`marker`},d=10;function f(e){return!!(e&&typeof e==`object`&&e&&!Array.isArray(e))}function p(e){return!!(e&&typeof e==`object`&&`properties`in e&&typeof e.properties==`object`&&e.properties!==null&&`mode`in e.properties)}function m(e){return!!function(e){return typeof e==`number`&&!isNaN(new Date(e).valueOf())}(e)}var h=`Feature mode property does not match the mode being added to`,g;(function(e){e.Drawing=`drawing`,e.Select=`select`,e.Static=`static`,e.Render=`render`})(g||={});var _={rightClick:!0,contextMenu:!1,leftClick:!0,onDragStart:!0,onDrag:!0,onDragEnd:!0},v=class{get state(){return this._state}set state(e){throw Error(`Please use the modes lifecycle methods`)}get styles(){return this._styles}set styles(e){if(typeof e!=`object`)throw Error(`Styling must be an object`);this.onStyleChange&&this.onStyleChange([],`styling`),this._styles=e}registerBehaviors(e){}constructor(e,t=!1){this._state=`unregistered`,this._styles={},this.pointerEvents=_,this.behaviors=[],this.validate=void 0,this.pointerDistance=40,this.coordinatePrecision=void 0,this.undoRedoMaxStackSize=void 0,this.onStyleChange=void 0,this.store=void 0,this.projection=`web-mercator`,this.setDoubleClickToZoom=void 0,this.unproject=void 0,this.project=void 0,this.setCursor=void 0,this.isInitialUpdate=!1,this.type=g.Drawing,this.mode=`base`,t?this.isInitialUpdate=!0:this.updateOptions(n({},e))}updateOptions(e){e!=null&&e.styles&&(this.styles=n({},this._styles,e.styles)),e!=null&&e.pointerDistance&&(this.pointerDistance=e.pointerDistance),e!=null&&e.validation&&(this.validate=e&&e.validation),e!=null&&e.projection&&(this.projection=e.projection),e?.pointerEvents!==void 0&&(this.pointerEvents=e.pointerEvents),e!=null&&e.modeName&&!0===this.isInitialUpdate&&(this.mode=e.modeName),this.isInitialUpdate=!1}allowPointerEvent(e,t){return typeof e==`boolean`?e:typeof e!=`function`||e(t)}setDrawing(){if(this._state!==`started`)throw Error(`Mode must be unregistered or stopped to start`);this._state=`drawing`}setStarted(){if(this._state!==`stopped`&&this._state!==`registered`&&this._state!==`drawing`&&this._state!==`selecting`)throw Error(`Mode must be unregistered or stopped to start`);this._state=`started`,this.setDoubleClickToZoom(!1)}setStopped(){if(this._state!==`started`)throw Error(`Mode must be started to be stopped`);this._state=`stopped`,this.setDoubleClickToZoom(!0)}register(e){if(this._state!==`unregistered`)throw Error(`Can not register unless mode is unregistered`);this._state=`registered`,this.store=e.store,this.store.registerOnChange(e.onChange),this.setDoubleClickToZoom=e.setDoubleClickToZoom,this.project=e.project,this.unproject=e.unproject,this.onSelect=e.onSelect,this.onDeselect=e.onDeselect,this.setCursor=e.setCursor,this.onStyleChange=e.onChange,this.onFinish=e.onFinish,this.coordinatePrecision=e.coordinatePrecision,this.undoRedoMaxStackSize=e.undoRedoMaxStackSize,this.registerBehaviors({mode:e.mode,store:this.store,project:this.project,unproject:this.unproject,pointerDistance:this.pointerDistance,coordinatePrecision:e.coordinatePrecision,projection:this.projection,undoRedoMaxStackSize:e.undoRedoMaxStackSize})}validateFeature(e){return this.performFeatureValidation(e)}afterFeatureAdded(e){}afterFeatureUpdated(e){}performFeatureValidation(e){if(this._state===`unregistered`)throw Error(`Mode must be registered`);let t=function(e,t){let n;if(f(e))if(e.id==null)n=`Feature has no id`;else if(typeof e.id!=`string`&&typeof e.id!=`number`)n=`Feature must be string or number as per GeoJSON spec`;else if(t(e.id))if(f(e.geometry))if(f(e.properties))if(typeof e.geometry.type==`string`&&[`Polygon`,`LineString`,`Point`].includes(e.geometry.type))if(Array.isArray(e.geometry.coordinates)){if(!e.properties.mode||typeof e.properties.mode!=`string`)return{valid:!1,reason:`Feature does not have a valid mode property`}}else n=`Feature coordinates is not an array`;else n=`Feature is not Point, LineString or Polygon`;else n=`Feature has no properties`;else n=`Feature has no geometry`;else n=`Feature must match the id strategy (default is UUID4)`;else n=`Feature is not object`;return n?{valid:!1,reason:n}:{valid:!0}}(e,this.store.idStrategy.isValidId);if(!t.valid)return t;if(this.validate){let n=this.validate(e,{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:s.Provisional});return{valid:t.valid&&n.valid,reason:n.reason}}return{valid:t.valid,reason:t.reason}}validateModeFeature(e,t){let n=this.performFeatureValidation(e);return n.valid?e.properties.mode===this.mode?t(e):{valid:!1,reason:h}:{valid:!1,reason:n.reason}}onFinish(e,t){}onDeselect(e){}onSelect(e){}onKeyDown(e){}onKeyUp(e){}undo(){}clearHistory(){}undoSize(){return 0}redoSize(){return 0}redo(){}onMouseMove(e){}onClick(e){}onDragStart(e,t){}onDrag(e,t){}onDragEnd(e,t){}getHexColorStylingValue(e,t,n){return this.getStylingValue(e,t,n)}getNumericStylingValue(e,t,n){return this.getStylingValue(e,t,n)}getUrlStylingValue(e,t,n){return this.getStylingValue(e,t,n)}getStylingValue(e,t,n){return e===void 0?t:typeof e==`function`?(r=e(n))??t:e;var r}},y=class extends v{constructor(...e){super(...e),this.type=g.Select}};function b(e,t){let n=e=>e*Math.PI/180,r=n(e[1]),i=n(e[0]),a=n(t[1]),o=a-r,s=n(t[0])-i,c=Math.sin(o/2)*Math.sin(o/2)+Math.cos(r)*Math.cos(a)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))*6371e3/1e3}var x=6371008.8;function S(e){return e%360*Math.PI/180}function ee(e){return e/6371.0088}function C(e){return e%(2*Math.PI)*180/Math.PI}function w(e,t=9){let n=10**t;return Math.round(e*n)/n}var T=57.29577951308232,te=.017453292519943295,ne=6378137,E=(e,t)=>({x:e===0?0:e*te*ne,y:t===0?0:Math.log(Math.tan(Math.PI/4+t*te/2))*ne}),D=(e,t)=>({lng:e===0?0:e/ne*T,lat:t===0?0:(2*Math.atan(Math.exp(t/ne))-Math.PI/2)*T});function re(e,t,n){let r=S(e[0]),i=S(e[1]),a=S(n),o=ee(t),s=Math.asin(Math.sin(i)*Math.cos(o)+Math.cos(i)*Math.sin(o)*Math.cos(a));return[C(r+Math.atan2(Math.sin(a)*Math.sin(o)*Math.cos(i),Math.cos(o)-Math.sin(i)*Math.sin(s))),C(s)]}function ie(e){let{center:t,radiusKilometers:n,coordinatePrecision:r}=e,i=e.steps?e.steps:64,a=[];for(let e=0;e<i;e++){let o=re(t,n,-360*e/i);a.push([w(o[0],r),w(o[1],r)])}return a.push(a[0]),{type:`Feature`,geometry:{type:`Polygon`,coordinates:[a]},properties:{}}}function ae(e){let t;if(e.geometry.type===`Polygon`)t=e.geometry.coordinates;else{if(e.geometry.type!==`LineString`)throw Error(`Self intersects only accepts Polygons and LineStrings`);t=[e.geometry.coordinates]}let n=[];for(let e=0;e<t.length;e++)for(let n=0;n<t[e].length-1;n++)for(let r=0;r<t.length;r++)for(let a=0;a<t[r].length-1;a++)i(e,n,r,a);return n.length>0;function r(e){return e<0||e>1}function i(e,i,a,o){let s=t[e][i],c=t[e][i+1],l=t[a][o],u=t[a][o+1],d=function(e,t,n,r){if(oe(e,n)||oe(e,r)||oe(t,n)||oe(r,n))return null;let i=e[0],a=e[1],o=t[0],s=t[1],c=n[0],l=n[1],u=r[0],d=r[1],f=(i-o)*(l-d)-(a-s)*(c-u);return f===0?null:[((i*s-a*o)*(c-u)-(i-o)*(c*d-l*u))/f,((i*s-a*o)*(l-d)-(a-s)*(c*d-l*u))/f]}(s,c,l,u);if(d===null)return;let f,p;f=c[0]===s[0]?(d[1]-s[1])/(c[1]-s[1]):(d[0]-s[0])/(c[0]-s[0]),p=u[0]===l[0]?(d[1]-l[1])/(u[1]-l[1]):(d[0]-l[0])/(u[0]-l[0]),r(f)||r(p)||(d.toString(),n.push(d))}}function oe(e,t){return e[0]===t[0]&&e[1]===t[1]}function se(e,t){return le(e[0])<=t&&le(e[1])<=t}function ce(e){return e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`&&e[0]!==1/0&&e[1]!==1/0&&(n=e[0])>=-180&&n<=180&&(t=e[1])>=-90&&t<=90;var t,n}function le(e){let t=1,n=0;for(;Math.round(e*t)/t!==e;)t*=10,n++;return n}var ue=`Feature has holes`,de=`Feature has less than 4 coordinates`,fe=`Feature has invalid coordinates`,pe=`Feature coordinates are not closed`;function me(e,t){if(e.geometry.type!==`Polygon`)return{valid:!1,reason:`Feature is not a Polygon`};if(e.geometry.coordinates.length!==1)return{valid:!1,reason:ue};if(e.geometry.coordinates[0].length<4)return{valid:!1,reason:de};for(let n=0;n<e.geometry.coordinates[0].length;n++){if(!ce(e.geometry.coordinates[0][n]))return{valid:!1,reason:fe};if(!se(e.geometry.coordinates[0][n],t))return{valid:!1,reason:`Feature has coordinates with excessive precision`}}return(n=e.geometry.coordinates[0][0])[0]!==(r=e.geometry.coordinates[0][e.geometry.coordinates[0].length-1])[0]||n[1]!==r[1]?{valid:!1,reason:pe}:{valid:!0};var n,r}function he(e,t){let n=me(e,t);return n.valid?ae(e)?{valid:!1,reason:`Feature intersects itself`}:{valid:!0}:n}var O=class{constructor({store:e,mode:t,project:n,unproject:r,pointerDistance:i,coordinatePrecision:a,projection:o,undoRedoMaxStackSize:s}){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.undoRedoMaxStackSize=void 0,this.store=e,this.mode=t,this.project=n,this.unproject=r,this.pointerDistance=i,this.coordinatePrecision=a,this.projection=o,this.undoRedoMaxStackSize=s}};function ge(e){if(!function(e){let t=e.coordinates[0],n=0;for(let e=0;e<t.length-1;e++){let[r,i]=t[e],[a,o]=t[e+1];n+=(a-r)*(o+i)}return n<0}(e))return{type:`Polygon`,coordinates:[e.coordinates[0].reverse()]}}var _e=`insert-before`,k=`insert-after`,A=`update`,j=`delete`,M=`replace`,N=class extends O{constructor(e,t){super(e),this.options=void 0,this.options=t}createPoint({coordinates:e,properties:t,context:n}){if(n?.updateType!==s.Finish||this.validateGeometryWithUpdateType({geometry:{type:`Point`,coordinates:e},properties:t,updateType:s.Finish}))return this.handleCreateFeature({geometry:{type:`Point`,coordinates:e},properties:t})}createLineString({coordinates:e,properties:t}){return this.handleCreateFeature({geometry:{type:`LineString`,coordinates:e},properties:t})}createPolygon({coordinates:e,properties:t,context:n}){let r=ge({type:`Polygon`,coordinates:[e]}),i={type:`Polygon`,coordinates:r?r.coordinates:[e]};if(n?.updateType!==s.Finish||this.validateGeometryWithUpdateType({geometry:i,properties:t,updateType:s.Finish}))return this.handleCreateFeature({geometry:i,properties:t})}createGuidancePoint({coordinate:e,type:t}){return this.createGuidancePoints({coordinates:[e],type:t})[0]}createGuidancePoints({coordinates:e,type:t,additionalProperties:r}){let i=e.map((e,i)=>({type:`Feature`,geometry:{type:`Point`,coordinates:e},properties:n({mode:this.mode,[t]:!0},r?r(i):{})}));return this.createFeatures(i)}updatePoint({featureId:e,coordinateMutations:t,propertyMutations:n,context:r}){return this.handleMutateFeature({type:`Point`,featureId:e,coordinateMutations:t,propertyMutations:n,context:r})}updatePolygon({featureId:e,coordinateMutations:t,context:n,propertyMutations:r}){return this.handleMutateFeature({type:`Polygon`,featureId:e,coordinateMutations:t,propertyMutations:r,context:n})}updateLineString({featureId:e,coordinateMutations:t,context:n,propertyMutations:r}){return this.handleMutateFeature({type:`LineString`,featureId:e,coordinateMutations:t,propertyMutations:r,context:n})}deleteFeatureIfPresent(e){e&&this.store.has(e)&&this.store.delete([e])}deleteFeaturesIfPresent(e){if(e.length===0)return;let t=e.filter(e=>this.store.has(e));t.length&&this.store.delete(t)}setDeselected(e){let t=e.filter(e=>this.store.has(e)).map(e=>({featureId:e,properties:{[l.SELECTED]:!1}}));this.updateFeatureProperties(t)}setSelected(e){let{type:t}=this.store.getGeometryCopy(e),n={featureId:e,propertyMutations:{[l.SELECTED]:!0},context:{updateType:s.Commit}};t===`Polygon`?this.updatePolygon(n):t===`LineString`?this.updateLineString(n):t===`Point`&&this.updatePoint(n)}updateGuidancePoints(e){this.updateFeatureGeometries(e.map(({featureId:e,coordinate:t})=>({id:e,geometry:{type:`Point`,coordinates:t}})))}handleCreateFeature({geometry:e,properties:t}){return this.createFeatureWithGeometry({geometry:e,properties:t})}handleMutateFeature({type:e,featureId:t,coordinateMutations:r,propertyMutations:i,context:a}){if(!this.mutateFeature({type:e,featureId:t,coordinateMutations:r,propertyMutations:i,context:a.updateType===s.Finish?n({},a,{correctRightHandRule:!0}):n({},a)}))return null;let o=this.buildFeatureWithGeometry(t);return a.updateType!==s.Finish||r||this.validateGeometryWithUpdateType({geometry:o.geometry,properties:o.properties,updateType:a.updateType})?o:null}mutateFeature({type:e,featureId:t,coordinateMutations:n,propertyMutations:r,context:i}){if(!t)return!1;let a=this.store.getGeometryCopy(t),o=this.store.getPropertiesCopy(t);if(a.type!==e)throw Error(`${e} geometries cannot be updated on features with ${a.type} geometries`);if(n){let e=this.applyCoordinateMutations(a,n);if(i.correctRightHandRule&&e.type===`Polygon`){let t=ge(e);t&&(e=t)}if(!this.validateGeometryWithUpdateType({geometry:e,properties:o,updateType:i.updateType}))return!1;this.updateFeatureGeometries([{id:t,geometry:e}])}return r&&this.updateFeatureProperties([{featureId:t,properties:r}]),!0}applyCoordinateMutations(e,t){if(this.isReplaceMutation(t))return n({},e,{coordinates:t.coordinates});if(e.type===`Point`)throw Error(`Coordinate mutations are not supported for Point geometries`);let r=e.type===`Polygon`,i=r?e.coordinates[0].slice():e.coordinates.slice(),a=i.length,o=e=>{let t=e<0?a+e:e;if(t<0||t>=a)throw RangeError(`Index ${e} (normalized to ${t}) is out of bounds`);return t},s=Array(a).fill(void 0),c=Array.from({length:a},()=>[]),l=Array.from({length:a},()=>[]),u=[];for(let e of t){if(e.type===_e||e.type===k){let t=e.index,n=t<0?a+t:t;if(n<0||n>a)throw RangeError(`Index ${e.index} (normalized to ${n}) is out of bounds`);if(e.type===_e){if(n>=a)throw RangeError(`INSERT_BEFORE index ${e.index} (normalized to ${n}) is out of bounds for length ${a}`);c[n].push(e)}else n===a?u.push(e):l[n].push(e);continue}let t=o(e.index);s[t]=n({},e,{index:t})}let d=[];for(let e=0;e<a;e++){let t=c[e];for(let e of t)d.push(e.coordinate);let n=s[e];n?n.type===j||d.push(n.coordinate):d.push(i[e]);let r=l[e];for(let e of r)d.push(e.coordinate)}for(let e of u)d.push(e.coordinate);return n({},e,r?{coordinates:[d,...e.coordinates.slice(1)]}:{coordinates:d})}isReplaceMutation(e){return e.type===M}createFeatureWithGeometry({geometry:e,properties:t}){let[n]=this.createFeatures([{type:`Feature`,geometry:e,properties:t}]);return{id:n,type:`Feature`,properties:this.store.getPropertiesCopy(n),geometry:this.store.getGeometryCopy(n)}}validateGeometryWithUpdateType({geometry:e,properties:t,updateType:n}){return!this.options.validate||this.options.validate({type:`Feature`,geometry:e,properties:t||{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:n}).valid}buildFeatureWithGeometry(e){return{id:e,type:`Feature`,properties:this.store.getPropertiesCopy(e),geometry:this.store.getGeometryCopy(e)}}createFeatures(e){return this.store.create(e)}updateFeatureGeometries(e){this.store.updateGeometry(e)}updateFeatureProperties(e){let t=e.map(({featureId:e,properties:t})=>Object.entries(t).map(([t,n])=>({id:e,property:t,value:n}))).flat();this.store.updateProperty(t)}},ve={cancel:`Escape`,finish:`Enter`},ye={start:`crosshair`},be=class extends v{constructor(e){super(e,!0),this.mode=`circle`,this.center=void 0,this.endPosition=void 0,this.segments=64,this.currentCircleId=void 0,this.keyEvents=ve,this.cursors=ye,this.startingRadiusKilometers=1e-5,this.cursorMovedAfterInitialCursorDown=!1,this.drawInteraction=`click-move`,this.drawType=void 0,this.mutateFeature=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors)),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=n({},this.keyEvents,e.keyEvents)),e!=null&&e.startingRadiusKilometers&&(this.startingRadiusKilometers=e.startingRadiusKilometers),e!=null&&e.drawInteraction&&(this.drawInteraction=e.drawInteraction),e!=null&&e.segments&&(this.segments=e.segments<3?3:e.segments)}close(){if(this.currentCircleId===void 0||this.endPosition===void 0||!this.updateCircle(this.endPosition,s.Finish))return;let e=this.currentCircleId;this.cursorMovedAfterInitialCursorDown=!1,this.center=void 0,this.currentCircleId=void 0,this.drawType=void 0,this.state===`drawing`&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:r})}beginDrawing(e,t=`click`){this.center=[e.lng,e.lat],this.endPosition=[e.lng,e.lat];let n=ie({center:this.center,radiusKilometers:this.startingRadiusKilometers,coordinatePrecision:this.coordinatePrecision}),r=this.mutateFeature.createPolygon({coordinates:n.geometry.coordinates[0],properties:{mode:this.mode,radiusKilometers:this.startingRadiusKilometers,[u.CURRENTLY_DRAWING]:!0}});r&&(this.currentCircleId=r.id,this.cursorMovedAfterInitialCursorDown=!1,this.drawType=t,this.setDrawing())}dragDrawAllowed(){return this.drawInteraction===`click-drag`||this.drawInteraction===`click-move-or-drag`}moveDrawAllowed(){return this.drawInteraction===`click-move`||this.drawInteraction===`click-move-or-drag`}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onClick(e){this.moveDrawAllowed()&&(e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e))&&(this.center?this.center&&this.currentCircleId!==void 0&&(this.endPosition=[e.lng,e.lat],this.close()):this.beginDrawing(e))}onMouseMove(e){this.cursorMovedAfterInitialCursorDown=!0,this.endPosition=[e.lng,e.lat],this.updateCircle(this.endPosition,s.Provisional)}onKeyDown(){}onKeyUp(e){e.key===this.keyEvents.cancel?this.cleanUp():e.key===this.keyEvents.finish&&this.close()}onDragStart(e,t){this.state!==`drawing`&&this.allowPointerEvent(this.pointerEvents.onDragStart,e)&&this.dragDrawAllowed()&&(this.beginDrawing(e,`drag`),t(!1))}onDrag(e,t){this.allowPointerEvent(this.pointerEvents.onDrag,e)&&this.dragDrawAllowed()&&this.drawType===`drag`&&(this.cursorMovedAfterInitialCursorDown=!0,this.endPosition=[e.lng,e.lat],this.updateCircle(this.endPosition,s.Provisional))}onDragEnd(e,t){this.allowPointerEvent(this.pointerEvents.onDragEnd,e)&&this.dragDrawAllowed()&&this.drawType===`drag`&&(this.endPosition=[e.lng,e.lat],this.close(),t(!0))}cleanUp(){let e=this.currentCircleId;this.center=void 0,this.currentCircleId=void 0,this.drawType=void 0,this.state===`drawing`&&this.setStarted(),this.mutateFeature.deleteFeatureIfPresent(e)}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});return e.type===`Feature`&&e.geometry.type===`Polygon`&&e.properties.mode===this.mode?(t.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,t.polygonFillColor,e),t.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,t.polygonOutlineColor,e),t.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,t.polygonOutlineWidth,e),t.polygonOutlineOpacity=this.getNumericStylingValue(this.styles.outlineOpacity,1,e),t.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,t.polygonFillOpacity,e),t.zIndex=d,t):t}validateFeature(e){return this.validateModeFeature(e,e=>he(e,this.coordinatePrecision))}updateCircle(e,t){if(this.currentCircleId===void 0||this.center===void 0)return;let n=t===s.Finish,i,a;if(this.cursorMovedAfterInitialCursorDown)if(a=b(this.center,e),this.projection===`web-mercator`){let t=function(e,t){let n=1e3*b(e,t);if(n===0)return 1;let{x:r,y:i}=E(e[0],e[1]),{x:a,y:o}=E(t[0],t[1]);return Math.sqrt((a-r)**2+(o-i)**2)/n}(this.center,e);i=function(e){let{center:t,radiusKilometers:n,coordinatePrecision:r}=e,i=e.steps?e.steps:64,a=1e3*n,[o,s]=t,{x:c,y:l}=E(o,s),u=[];for(let e=0;e<i;e++){let t=360*e/i*Math.PI/180,n=a*Math.cos(t),o=a*Math.sin(t),[s,d]=[c+n,l+o],{lng:f,lat:p}=D(s,d);u.push([w(f,r),w(p,r)])}return u.push(u[0]),{type:`Feature`,geometry:{type:`Polygon`,coordinates:[u]},properties:{}}}({center:this.center,radiusKilometers:a*t,coordinatePrecision:this.coordinatePrecision,steps:this.segments})}else{if(this.projection!==`globe`)throw Error(`Invalid projection`);i=ie({center:this.center,radiusKilometers:a,coordinatePrecision:this.coordinatePrecision,steps:this.segments})}let o={};return i&&a&&(o.radiusKilometers=a),n&&(o[u.CURRENTLY_DRAWING]=void 0),this.mutateFeature.updatePolygon({featureId:this.currentCircleId,coordinateMutations:i?{type:M,coordinates:i.geometry.coordinates}:void 0,propertyMutations:o,context:n?{updateType:t,action:r}:{updateType:t}})}afterFeatureUpdated(e){this.currentCircleId===e.id&&(this.cursorMovedAfterInitialCursorDown=!1,this.center=void 0,this.currentCircleId=void 0,this.drawType=void 0,this.state===`drawing`&&this.setStarted())}registerBehaviors(e){this.mutateFeature=new N(e,{validate:this.validate})}},P=(e,t)=>{let{x:n,y:r}=e,{x:i,y:a}=t,o=i-n,s=a-r;return Math.sqrt(s*s+o*o)};function xe(e,t){return e[0]===t[0]&&e[1]===t[1]}var F=class extends O{constructor(e){super(e)}getGeometryType(e){return this.store.getGeometryCopy(e).type}coordinateAtIndexIsIdentical({featureId:e,newCoordinate:t,index:n}){let r=this.store.getGeometryCopy(e),i;if(r.type===`Polygon`)i=r.coordinates[0][n];else if(r.type===`LineString`)i=r.coordinates[n];else{if(n!==0)throw Error(`Point geometries only have one coordinate at index 0`);i=r.coordinates}return xe(t,i)}getGeometry(e){return this.store.getGeometryCopy(e)}getCoordinates(e){let{type:t,coordinates:n}=this.store.getGeometryCopy(e);return t===`Polygon`?n[0]:n}getCoordinate(e,t){let n=this.getCoordinates(e),r=t<0?n.length+t:t;if(r<0||r>=n.length)throw RangeError(`Index ${t} (normalized to ${r}) is out of bounds`);return n[r]}getProperties(e){return this.store.getPropertiesCopy(e)}hasFeature(e){return this.store.has(e)}getAllFeatureIdsWhere(e){return this.store.copyAllWhere(e).map(({id:e})=>e)}},Se={cancel:`Escape`,finish:`Enter`},Ce={start:`crosshair`,close:`pointer`},we=class extends v{constructor(e){super(e,!0),this.mode=`freehand`,this.canClose=!1,this.currentId=void 0,this.closingPointId=void 0,this.minDistance=20,this.keyEvents=Se,this.cursors=Ce,this.preventPointsNearClose=!0,this.autoClose=!1,this.autoCloseTimeout=500,this.hasLeftStartingPoint=!1,this.preventNewFeature=!1,this.drawInteraction=`click-move`,this.drawType=void 0,this.smoothing=0,this.mutateFeature=void 0,this.readFeature=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.minDistance&&(this.minDistance=e.minDistance),e?.smoothing!==void 0&&(this.smoothing=Math.min(Math.max(e.smoothing,0),.999)),e?.preventPointsNearClose!==void 0&&(this.preventPointsNearClose=e.preventPointsNearClose),e?.autoClose!==void 0&&(this.autoClose=e.autoClose),e!=null&&e.autoCloseTimeout&&(this.autoCloseTimeout=e.autoCloseTimeout),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=n({},this.keyEvents,e.keyEvents)),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors)),e!=null&&e.drawInteraction&&(this.drawInteraction=e.drawInteraction)}moveDrawAllowed(){return this.drawInteraction===`click-move`||this.drawInteraction===`click-move-or-drag`}dragDrawAllowed(){return this.drawInteraction===`click-drag`||this.drawInteraction===`click-move-or-drag`}beginDrawing(e,t=`click`){let{id:n}=this.mutateFeature.createPolygon({coordinates:[[e.lng,e.lat],[e.lng,e.lat],[e.lng,e.lat],[e.lng,e.lat]],properties:{mode:this.mode,[u.CURRENTLY_DRAWING]:!0}});this.currentId=n,this.drawType=t,this.closingPointId=this.mutateFeature.createGuidancePoint({coordinate:[e.lng,e.lat],type:u.CLOSING_POINT}),this.canClose=!0,this.state!==`drawing`&&this.setDrawing()}addCoordinate(e){if(this.currentId===void 0||!1===this.canClose)return void this.setCursor(this.cursors.start);let[t,n]=this.readFeature.getCoordinate(this.currentId,-2),{x:r,y:i}=this.project(t,n),a=P({x:r,y:i},{x:e.containerX,y:e.containerY}),[o,c]=this.readFeature.getCoordinate(this.currentId,0),{x:l,y:u}=this.project(o,c);if(P({x:l,y:u},{x:e.containerX,y:e.containerY})<this.pointerDistance){if(this.autoClose&&this.hasLeftStartingPoint&&(this.preventNewFeature=!0,setTimeout(()=>{this.preventNewFeature=!1},this.autoCloseTimeout),this.close()),this.setCursor(this.cursors.close),this.preventPointsNearClose)return}else this.hasLeftStartingPoint=!0,this.setCursor(this.cursors.start);if(a<this.minDistance)return;let d=this.getSmoothedCoordinate([t,n],[e.lng,e.lat]);this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:[{type:_e,index:-1,coordinate:d}],context:{updateType:s.Provisional}})}getSmoothedCoordinate(e,t){if(this.smoothing===0)return t;let[n,r]=e,[i,a]=t;return[n*this.smoothing+i*(1-this.smoothing),r*this.smoothing+a*(1-this.smoothing)]}close(){if(this.currentId===void 0||!this.mutateFeature.updatePolygon({featureId:this.currentId,propertyMutations:{[u.CURRENTLY_DRAWING]:void 0},context:{updateType:s.Finish,action:r}}))return;let e=this.currentId;this.mutateFeature.deleteFeatureIfPresent(this.closingPointId),this.canClose=!1,this.currentId=void 0,this.closingPointId=void 0,this.hasLeftStartingPoint=!1,this.drawType=void 0,this.state===`drawing`&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:r})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onMouseMove(e){this.moveDrawAllowed()&&this.drawType===`click`&&this.addCoordinate(e)}onClick(e){if(this.moveDrawAllowed()&&(e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e))){if(this.preventNewFeature)return;if(!1===this.canClose)return void this.beginDrawing(e);this.close()}}onKeyDown(){}onKeyUp(e){e.key===this.keyEvents.cancel?this.cleanUp():e.key===this.keyEvents.finish&&!0===this.canClose&&this.close()}onDragStart(e,t){this.state!==`drawing`&&(this.preventNewFeature||this.allowPointerEvent(this.pointerEvents.onDragStart,e)&&this.dragDrawAllowed()&&(this.beginDrawing(e,`drag`),t(!1)))}onDrag(e,t){this.allowPointerEvent(this.pointerEvents.onDrag,e)&&this.dragDrawAllowed()&&this.drawType===`drag`&&this.addCoordinate(e)}onDragEnd(e,t){this.allowPointerEvent(this.pointerEvents.onDragEnd,e)&&this.dragDrawAllowed()&&this.drawType===`drag`&&(this.preventNewFeature=!0,setTimeout(()=>{this.preventNewFeature=!1},this.autoCloseTimeout),this.close(),t(!0))}cleanUp(){let e=this.currentId,t=this.closingPointId;this.closingPointId=void 0,this.currentId=void 0,this.canClose=!1,this.hasLeftStartingPoint=!1,this.drawType=void 0,this.state===`drawing`&&this.setStarted(),this.mutateFeature.deleteFeatureIfPresent(e),this.mutateFeature.deleteFeatureIfPresent(t)}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});return e.type===`Feature`&&e.geometry.type===`Polygon`&&e.properties.mode===this.mode?(t.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,t.polygonFillColor,e),t.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,t.polygonOutlineColor,e),t.polygonOutlineOpacity=this.getNumericStylingValue(this.styles.outlineOpacity,1,e),t.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,t.polygonOutlineWidth,e),t.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,t.polygonFillOpacity,e),t.zIndex=d,t):e.type===`Feature`&&e.geometry.type===`Point`&&e.properties.mode===this.mode?(t.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,t.pointWidth,e),t.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.closingPointOpacity,t.pointOpacity===void 0?1:t.pointOpacity,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,t.pointOutlineColor,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.closingPointOutlineOpacity,t.pointOutlineOpacity===void 0?1:t.pointOutlineOpacity,e),t.zIndex=50,t):t}validateFeature(e){return this.validateModeFeature(e,e=>me(e,this.coordinatePrecision))}afterFeatureUpdated(e){this.currentId===e.id&&(this.mutateFeature.deleteFeatureIfPresent(this.closingPointId),this.canClose=!1,this.currentId=void 0,this.closingPointId=void 0,this.hasLeftStartingPoint=!1)}registerBehaviors(e){this.readFeature=new F(e),this.mutateFeature=new N(e,{validate:this.validate})}};function Te({unproject:e,point:t,pointerDistance:n}){let r=n/2,{x:i,y:a}=t;return{type:`Feature`,properties:{},geometry:{type:`Polygon`,coordinates:[[e(i-r,a-r),e(i+r,a-r),e(i+r,a+r),e(i-r,a+r),e(i-r,a-r)].map(e=>[e.lng,e.lat])]}}}var Ee=class extends O{constructor(e){super(e)}create(e){let{containerX:t,containerY:n}=e;return Te({unproject:this.unproject,point:{x:t,y:n},pointerDistance:this.pointerDistance})}},I=class extends O{constructor(e){super(e)}measure(e,t){let{x:n,y:r}=this.project(t[0],t[1]);return P({x:n,y:r},{x:e.containerX,y:e.containerY})}},De=class extends O{constructor(e,t,n){super(e),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=e=>this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode)).coordinate,this.getSnappableCoordinate=(e,t)=>this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode&&e.id!==t)).coordinate,this.config=e,this.pixelDistance=t,this.clickBoundingBox=n}getSnappable(e,t){let n=this.clickBoundingBox.create(e),r=this.store.search(n,t),i={featureId:void 0,featureCoordinateIndex:void 0,coordinate:void 0,minDist:1/0};return r.forEach(t=>{let n;if(t.geometry.type===`Polygon`)n=t.geometry.coordinates[0];else{if(t.geometry.type!==`LineString`)return;n=t.geometry.coordinates}n.forEach((n,r)=>{let a=this.pixelDistance.measure(e,n);a<i.minDist&&a<this.pointerDistance&&(i.coordinate=n,i.minDist=a,i.featureId=t.id,i.featureCoordinateIndex=r)})}),i}};function Oe(e,t,n){let r=S(e[0]),i=S(e[1]),a=S(n),o=ee(t),s=Math.asin(Math.sin(i)*Math.cos(o)+Math.cos(i)*Math.sin(o)*Math.cos(a));return[C(r+Math.atan2(Math.sin(a)*Math.sin(o)*Math.cos(i),Math.cos(o)-Math.sin(i)*Math.sin(s))),C(s)]}function ke({x:e,y:t},n,r){let i=S(r);return{x:e+n*Math.cos(i),y:t+n*Math.sin(i)}}function Ae(e,t){let n=S(e[0]),r=S(t[0]),i=S(e[1]),a=S(t[1]),o=Math.sin(r-n)*Math.cos(a),s=Math.cos(i)*Math.sin(a)-Math.sin(i)*Math.cos(a)*Math.cos(r-n);return C(Math.atan2(o,s))}function L({x:e,y:t},{x:n,y:r}){let i=n-e,a=r-t;if(i===0&&a===0)return 0;let o=Math.atan2(a,i);return o*=180/Math.PI,o>180?o-=360:o<-180&&(o+=360),o}function R(e){return(e+360)%360}function je(e,t,n){let r=[],i=e.length,a,o,s,c=0;for(let i=0;i<e.length&&!(t>=c&&i===e.length-1);i++){if(c>t&&r.length===0){if(a=t-c,!a)return r.push(e[i]),r;o=Ae(e[i],e[i-1])-180,s=Oe(e[i],a,o),r.push(s)}if(c>=n)return a=n-c,a?(o=Ae(e[i],e[i-1])-180,s=Oe(e[i],a,o),r.push(s),r):(r.push(e[i]),r);if(c>=t&&r.push(e[i]),i===e.length-1)return r;c+=b(e[i],e[i+1])}if(c<t&&e.length===i)throw Error(`Start position is beyond line`);let l=e[e.length-1];return[l,l]}function Me(e){return Math.PI/180*e}function Ne(e){return 180/Math.PI*e}var Pe=class extends O{constructor(e){super(e),this.config=void 0,this.config=e}generateInsertionCoordinates(e,t,n){let r=[e,t],i=0;for(let e=0;e<r.length-1;e++)i+=b(r[0],r[1]);if(i<=n)return r;let a=i/n-1;Number.isInteger(a)||(a=Math.floor(a)+1);let o=[];for(let e=0;e<a;e++){let t=je(r,n*e,n*(e+1));o.push(t)}let s=[];for(let e=0;e<o.length;e++)s.push(o[e][1]);return this.limitCoordinates(s)}generateInsertionGeodesicCoordinates(e,t,n){let r=b(e,t),i=function(e,t,n){let r=[],i=Me(e[1]),a=Me(e[0]),o=Me(t[1]),s=Me(t[0]);n+=1;let c=2*Math.asin(Math.sqrt(Math.sin((o-i)/2)**2+Math.cos(i)*Math.cos(o)*Math.sin((s-a)/2)**2));if(c===0||isNaN(c))return r;for(let e=0;e<=n;e++){let t=e/n,l=Math.sin((1-t)*c)/Math.sin(c),u=Math.sin(t*c)/Math.sin(c),d=l*Math.cos(i)*Math.cos(a)+u*Math.cos(o)*Math.cos(s),f=l*Math.cos(i)*Math.sin(a)+u*Math.cos(o)*Math.sin(s),p=l*Math.sin(i)+u*Math.sin(o);if(isNaN(d)||isNaN(f)||isNaN(p))continue;let m=Math.atan2(p,Math.sqrt(d**2+f**2)),h=Math.atan2(f,d);isNaN(m)||isNaN(h)||r.push([Ne(h),Ne(m)])}return r.slice(1,-1)}(e,t,Math.floor(r/n));return this.limitCoordinates(i)}limitCoordinates(e){return e.map(e=>[w(e[0],this.config.coordinatePrecision),w(e[1],this.config.coordinatePrecision)])}};function Fe(e,t){if(e.geometry.type!==`LineString`)return{valid:!1,reason:`Feature is not a LineString`};if(e.geometry.coordinates.length<2)return{valid:!1,reason:`Feature has less than 2 coordinates`};for(let n=0;n<e.geometry.coordinates.length;n++){if(!ce(e.geometry.coordinates[n]))return{valid:!1,reason:`Feature has invalid coordinates`};if(!se(e.geometry.coordinates[n],t))return{valid:!1,reason:`Feature has coordinates with excessive precision`}}return{valid:!0}}function Ie(e){return Math.sqrt(e[0]**2+e[1]**2+e[2]**2)}function z(e,t){let n=function(e,t){let[n,r,i]=e,[a,o,s]=t;return n*a+r*o+i*s}(e,t)/(Ie(e)*Ie(t));return Math.acos(Math.min(Math.max(n,-1),1))}function Le(e){let t=S(e[1]),n=S(e[0]);return[Math.cos(t)*Math.cos(n),Math.cos(t)*Math.sin(n),Math.sin(t)]}function B(e){let[t,n,r]=e,i=C(Math.asin(r));return[C(Math.atan2(n,t)),i]}function Re(e,t,n){let r=Le(e),i=Le(t),[a,o,s]=Le(n),[c,l,u]=function(e,t){let[n,r,i]=e,[a,o,s]=t;return[r*s-i*o,i*a-n*s,n*o-r*a]}(r,i),d=l*s-u*o,f=u*a-c*s,p=c*o-l*a,m=p*l-f*u,h=d*u-p*c,g=f*c-d*l,_=1/Math.sqrt(m**2+h**2+g**2),v=[m*_,h*_,g*_],y=[-1*m*_,-1*h*_,-1*g*_],x=z(r,i),S=z(r,v),ee=z(i,v),C=z(r,y),w=z(i,y),T;return T=S<C&&S<w||ee<C&&ee<w?v:y,z(r,T)>x||z(i,T)>x?b(B(T),B(r))<=b(B(T),B(i))?[B(r),!0,!1]:[B(i),!1,!0]:[B(T),!1,!1]}function ze(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.max(0,Math.min(1,((n.x-e.x)*r+(n.y-e.y)*i)/(r*r+i*i)));return{x:e.x+a*r,y:e.y+a*i}}var Be=class extends O{constructor(e,t,n){super(e),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=e=>{let t=this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode));return t.coordinate?[w(t.coordinate[0],this.config.coordinatePrecision),w(t.coordinate[1],this.config.coordinatePrecision)]:void 0},this.getSnappableCoordinate=(e,t)=>{let n=this.getSnappable(e,e=>!!(e.properties&&e.properties.mode===this.mode&&e.id!==t));return n.coordinate?[w(n.coordinate[0],this.config.coordinatePrecision),w(n.coordinate[1],this.config.coordinatePrecision)]:void 0},this.config=e,this.pixelDistance=t,this.clickBoundingBox=n}getSnappable(e,t){let n=this.clickBoundingBox.create(e),r=this.store.search(n,t),i={featureId:void 0,featureCoordinateIndex:void 0,coordinate:void 0,minDistance:1/0};return r.forEach(t=>{let n;if(t.geometry.type===`Polygon`)n=t.geometry.coordinates[0];else{if(t.geometry.type!==`LineString`)return;n=t.geometry.coordinates}let r=[];for(let e=0;e<n.length-1;e++)r.push([n[e],n[e+1]]);let a,o=[e.lng,e.lat];if(this.config.projection===`web-mercator`?a=function(e,t){let n=[1/0,1/0],r=1/0,i=0;for(let a of t){let o=a[0],s=a[1],c,l=1/0,u=E(o[0],o[1]),d=E(s[0],s[1]),f=E(e[0],e[1]);if(o[0]===e[0]&&o[1]===e[1])c=o;else if(s[0]===e[0]&&s[1]===e[1])c=s;else{let{x:e,y:t}=ze(u,d,f),{lng:n,lat:r}=D(e,t);c=[n,r]}c&&(l=P(f,E(c[0],c[1])),l<r&&(n=c,r=l,i=t.indexOf(a)))}return r===1/0?void 0:{coordinate:n,lineIndex:i,distance:r}}(o,r):this.config.projection===`globe`&&(a=function(e,t){let n=[1/0,1/0],r=1/0,i=0;for(let a of t){let o=a[0],s=a[1],c,l=1/0;o[0]===e[0]&&o[1]===e[1]?c=o:s[0]===e[0]&&s[1]===e[1]?c=s:[c]=Re(o,s,e),c&&(l=b(e,c),l<r&&(n=c,r=l,i=t.indexOf(a)))}return r===1/0?void 0:{coordinate:n,distance:r,lineIndex:i}}(o,r)),!a)return;let s=this.pixelDistance.measure(e,a.coordinate);s<i.minDistance&&s<this.pointerDistance&&(i.featureId=t.id,i.coordinate=[w(a.coordinate[0],this.config.coordinatePrecision),w(a.coordinate[1],this.config.coordinatePrecision)],i.featureCoordinateIndex=a.lineIndex,i.minDistance=s)}),i}};function Ve(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])&&Array.isArray(e[0][0])}var He=e=>Ve(e)?e[0].slice(0,-1):e,Ue=e=>Ve(e)?e[0]:e,We=class extends O{constructor(e,t,n,r){super(e),this.config=void 0,this.pixelDistance=void 0,this.mutateFeatureBehavior=void 0,this.readFeatureBehavior=void 0,this._startEndPoints=[],this.config=e,this.pixelDistance=t,this.mutateFeatureBehavior=n,this.readFeatureBehavior=r}get ids(){return this._startEndPoints.concat()}set ids(e){}create(e){if(this.ids.length)throw Error(`Opening and closing points already created`);let t=Ve(e),n=Ue(e);if(t){if(n.length<=3)throw Error(`Requires at least 4 coordinates`);this._startEndPoints=this.mutateFeatureBehavior.createGuidancePoints({coordinates:[n[0],n[n.length-2]],type:u.CLOSING_POINT})}else this._startEndPoints=[this.mutateFeatureBehavior.createGuidancePoint({coordinate:n[n.length-2],type:u.CLOSING_POINT})]}delete(){this.ids.length&&(this.mutateFeatureBehavior.deleteFeaturesIfPresent(this.ids),this._startEndPoints=[])}updateOne(e,t){this.mutateFeatureBehavior.updateGuidancePoints([{featureId:this.ids[e],coordinate:t}])}update(e){let t=Ue(e);this.ids.length===1?this.mutateFeatureBehavior.updateGuidancePoints([{featureId:this.ids[0],coordinate:t[t.length-2]}]):this.ids.length===2&&this.mutateFeatureBehavior.updateGuidancePoints([{featureId:this.ids[0],coordinate:t[0]},{featureId:this.ids[1],coordinate:t[t.length-3]}])}isLineStringClosingPoint(e){if(this.ids.length!==1)return{isClosing:!1};let t=this.readFeatureBehavior.getGeometry(this.ids[0]);return{isClosing:this.pixelDistance.measure(e,t.coordinates)<this.pointerDistance}}isPolygonClosingPoints(e){if(this.ids.length!==2)return{isClosing:!1,isPreviousClosing:!1};let t=this.readFeatureBehavior.getGeometry(this.ids[0]),n=this.readFeatureBehavior.getGeometry(this.ids[1]),r=this.pixelDistance.measure(e,t.coordinates),i=this.pixelDistance.measure(e,n.coordinates);return{isClosing:r<this.pointerDistance,isPreviousClosing:i<this.pointerDistance}}},Ge=class extends O{constructor(e,t,n){super(e),this.readFeature=void 0,this.mutateFeature=void 0,this.readFeature=t,this.mutateFeature=n}createOrUpdate({featureId:e,featureCoordinates:t}){if(!this.readFeature.hasFeature(e))return void this.deleteOrphanedPoints(e);let n=He(t),r=this.readFeature.getProperties(e),i=r.coordinatePointIds;if(i)if(i&&i.every(e=>this.readFeature.hasFeature(e))){let t=r.coordinatePointIds,i=t.map(e=>this.readFeature.getGeometry(e).coordinates);if(t.length!==n.length){this.deleteCoordinatePoints(t);let i=this.createPoints(n,r.mode,e);this.setFeatureCoordinatePoints(e,i)}else{let e=[];n.forEach((n,r)=>{n[0]===i[r][0]&&n[1]===i[r][1]||e.push({featureId:t[r],coordinate:n})}),this.mutateFeature.updateGuidancePoints(e)}}else{let t=i.filter(e=>this.readFeature.hasFeature(e));t.length&&this.deleteCoordinatePoints(t);let a=this.createPoints(n,r.mode,e);this.setFeatureCoordinatePoints(e,a)}else{let t=this.createPoints(n,r.mode,e);this.setFeatureCoordinatePoints(e,t)}}deletePointsByFeatureIds(e){for(let t of e)this.deleteIfPresent(t)}updateOneAtIndex(e,t,n){let r=this.readFeature.getProperties(e).coordinatePointIds;r&&r.length!==0&&r[t]!==void 0&&this.mutateFeature.updateGuidancePoints([{featureId:r[t],coordinate:n}])}updateAllInPlace({featureId:e,featureCoordinates:t}){let n=this.readFeature.getProperties(e);if(!n.coordinatePointIds)return;let r=He(t);r.length===n.coordinatePointIds.length&&this.mutateFeature.updateGuidancePoints(n.coordinatePointIds.map((e,t)=>({featureId:e,coordinate:r[t]})))}createPoints(e,t,n){return this.mutateFeature.createGuidancePoints({coordinates:e,type:u.COORDINATE_POINT,additionalProperties:e=>({mode:t,[u.COORDINATE_POINT]:!0,[u.COORDINATE_POINT_FEATURE_ID]:n,index:e})})}setFeatureCoordinatePoints(e,t,n=s.Commit){let r=this.readFeature.getGeometryType(e),i={featureId:e,propertyMutations:{[u.COORDINATE_POINT_IDS]:t},context:{updateType:n}};if(r===`Polygon`)this.mutateFeature.updatePolygon(i);else{if(r!==`LineString`)throw Error(`Unsupported geometry type for coordinate points`);this.mutateFeature.updateLineString(i)}}deleteCoordinatePoints(e){this.mutateFeature.deleteFeaturesIfPresent(e)}deleteIfPresent(e){if(!this.readFeature.hasFeature(e))return;let t=this.readFeature.getProperties(e).coordinatePointIds;t&&(this.deleteCoordinatePoints(t),this.setFeatureCoordinatePoints(e,null))}deleteOrphanedPoints(e){let t=this.readFeature.getAllFeatureIdsWhere(t=>t[u.COORDINATE_POINT_FEATURE_ID]===e);this.mutateFeature.deleteFeaturesIfPresent(t)}},Ke=class{constructor(e){this.undoHistory=[],this.redoHistory=[],this.cloneCoordinatesFunction=void 0,this.maxStackSize=void 0,this.cloneCoordinatesFunction=e=>this.cloneRecursively(e);let t=e?.maxStackSize;this.maxStackSize=t!==void 0&&Number.isFinite(t)?Math.max(0,Math.floor(t)):1/0}setMaxStackSize(e){Number.isFinite(e)?(this.maxStackSize=Math.max(0,Math.floor(e)),this.trimHistoryToMax(this.undoHistory),this.trimHistoryToMax(this.redoHistory)):this.maxStackSize=1/0}trimHistoryToMax(e){if(Number.isFinite(this.maxStackSize))for(;e.length>this.maxStackSize;)e.shift()}pushUndoEntry(e){this.maxStackSize!==0&&(this.undoHistory.push(e),this.trimHistoryToMax(this.undoHistory))}pushRedoEntry(e){this.maxStackSize!==0&&(this.redoHistory.push(e),this.trimHistoryToMax(this.redoHistory))}cloneRecursively(e){return Array.isArray(e)?e.map(e=>this.cloneRecursively(e)):typeof e==`object`&&e?n({},e):e}cloneCoordinates(e){return this.cloneCoordinatesFunction(e)}cloneEntry(e){return{featureCoordinates:this.cloneCoordinates(e.featureCoordinates),currentCoordinate:e.currentCoordinate}}clear(){this.undoHistory=[],this.redoHistory=[]}undoSize(){return this.undoHistory.length}redoSize(){return this.redoHistory.length}recordSnapshot(e){this.pushUndoEntry(this.cloneEntry(e)),this.redoHistory=[]}beginUndo(){let e=this.undoHistory.pop();if(!e)return;let t=this.cloneEntry(e);this.pushRedoEntry(t);let n=this.undoHistory[this.undoHistory.length-1];return{undoneEntry:t,previousEntry:n?this.cloneEntry(n):void 0}}takeRedo(){let e=this.redoHistory.pop();if(e)return this.cloneEntry(e)}commitRedo(e){this.pushUndoEntry(this.cloneEntry(e))}},qe={cancel:`Escape`,finish:`Enter`},Je={start:`crosshair`,close:`pointer`,dragStart:`grabbing`,dragEnd:`crosshair`},Ye=class extends v{constructor(e){super(e,!0),this.mode=`linestring`,this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=qe,this.snapping=void 0,this.cursors=Je,this.mouseMove=!1,this.insertCoordinates=void 0,this.lastCommittedCoordinates=void 0,this.snappedPointId=void 0,this.lastMouseMoveEvent=void 0,this.showCoordinatePoints=!1,this.finishOnNthCoordinate=void 0,this.editable=!1,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0,this.editedInsertIndex=void 0,this.editedPointId=void 0,this.coordinateSnapping=void 0,this.insertPoint=void 0,this.lineSnapping=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.closingPoints=void 0,this.coordinatePoints=void 0,this.undoRedo=void 0,this.updateOptions(e)}updateOptions(e){if(super.updateOptions(e),e?.finishOnNthCoordinate!==void 0&&Number.isInteger(e.finishOnNthCoordinate)&&e.finishOnNthCoordinate>1&&(this.finishOnNthCoordinate=Math.floor(e.finishOnNthCoordinate)),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors)),e!=null&&e.snapping&&(this.snapping=e.snapping),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=n({},this.keyEvents,e.keyEvents)),e!=null&&e.insertCoordinates&&(this.insertCoordinates=e.insertCoordinates),e&&e.editable&&(this.editable=e.editable),e?.showCoordinatePoints!==void 0){if(this.showCoordinatePoints=e.showCoordinatePoints,this.coordinatePoints&&!0===e.showCoordinatePoints)this.store.copyAllWhere(e=>e.mode===this.mode).forEach(e=>{this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates})});else if(this.coordinatePoints&&!1===this.showCoordinatePoints){let e=this.store.copyAllWhere(e=>e.mode===this.mode&&!!e[u.COORDINATE_POINT_IDS]?.length);this.coordinatePoints.deletePointsByFeatureIds(e.map(e=>e.id))}}}shouldFinishOnCommit(e){return!!this.finishOnNthCoordinate&&Math.max(0,e.coordinates.length-1)>=this.finishOnNthCoordinate}updateSnappedCoordinate(e){let t=this.snapCoordinate(e);return t?(this.snappedPointId?this.mutateFeature.updateGuidancePoints([{featureId:this.snappedPointId,coordinate:t}]):this.snappedPointId=this.mutateFeature.createGuidancePoint({coordinate:t,type:u.SNAPPING_POINT}),e.lng=t[0],e.lat=t[1]):this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),t}close(){if(this.currentId===void 0)return;let e=this.mutateFeature.updateLineString({featureId:this.currentId,context:{updateType:s.Finish,action:r},coordinateMutations:[{type:j,index:-1}],propertyMutations:{[u.CURRENTLY_DRAWING]:void 0}});if(!e)return;this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:e.geometry.coordinates});let t=this.currentId;this.currentCoordinate=0,this.currentId=void 0,this.lastCommittedCoordinates=void 0,this.undoRedo.clear(),this.state===`drawing`&&this.setStarted(),this.closingPoints.delete(),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0),this.onFinish(t,{mode:this.mode,action:r})}generateInsertCoordinates(e,t){if(!this.insertCoordinates||!this.lastCommittedCoordinates)throw Error(`Not able to insert coordinates`);if(this.insertCoordinates.strategy!==`amount`)throw Error(`Strategy does not exist`);let n=b(e,t)/(this.insertCoordinates.value+1),r=[];return this.projection===`globe`?r=this.insertPoint.generateInsertionGeodesicCoordinates(e,t,n):this.projection===`web-mercator`&&(r=this.insertPoint.generateInsertionCoordinates(e,t,n)),r}createLine(e){let t=this.mutateFeature.createLineString({coordinates:[e,e],properties:{mode:this.mode,[u.CURRENTLY_DRAWING]:!0}});this.lastCommittedCoordinates=t.geometry.coordinates,this.currentId=t.id,this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.setDrawing(),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:t.geometry.coordinates})}firstUpdateToLine(e){if(!this.currentId)return;this.setCursor(this.cursors.close);let t=this.mutateFeature.updateLineString({featureId:this.currentId,context:{updateType:s.Commit},coordinateMutations:[{type:k,index:-1,coordinate:e}]});t&&(this.closingPoints.create(t.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:t.geometry.coordinates}),this.lastCommittedCoordinates=t.geometry.coordinates,this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.shouldFinishOnCommit(t.geometry)&&this.close())}updateToLine(e,t){if(!this.currentId)return;let{isClosing:n}=this.closingPoints.isLineStringClosingPoint(e);if(n)return void this.close();this.setCursor(this.cursors.close);let r=this.mutateFeature.updateLineString({featureId:this.currentId,context:{updateType:s.Commit},coordinateMutations:[{type:k,index:-1,coordinate:t}]});r&&(this.closingPoints.update(r.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:r.geometry.coordinates}),this.lastCommittedCoordinates=r.geometry.coordinates,this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.shouldFinishOnCommit(r.geometry)&&this.close())}undoSize(){return this.undoRedo.undoSize()}clearHistory(){this.undoRedo.clear()}pushHistorySnapshot(e,t){let n=this.readFeature.getGeometry(e);this.undoRedo.recordSnapshot({featureCoordinates:n.coordinates,currentCoordinate:t})}updateSnappedGuidancePointFromLastMouseMove(){this.snapping&&this.lastMouseMoveEvent?this.updateSnappedCoordinate(this.lastMouseMoveEvent):this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0)}syncClosingPoints(e){this.currentCoordinate>=2?this.closingPoints.ids.length?this.closingPoints.update(e):this.closingPoints.create(e):this.closingPoints.delete()}undo(){if(this.state!==`drawing`||!this.currentId)return;let e=this.undoRedo.beginUndo();if(!e)return;let{previousEntry:t}=e;if(!t){let e=this.currentId;this.currentId=void 0,this.currentCoordinate=0,this.lastCommittedCoordinates=void 0,this.closingPoints.delete(),this.state===`drawing`&&this.setStarted(),this.showCoordinatePoints&&this.coordinatePoints.deletePointsByFeatureIds([e]),this.mutateFeature.deleteFeatureIfPresent(e),this.updateSnappedGuidancePointFromLastMouseMove();return}let n=this.mutateFeature.updateLineString({featureId:this.currentId,coordinateMutations:{type:M,coordinates:t.featureCoordinates},propertyMutations:{[u.CURRENTLY_DRAWING]:!0},context:{updateType:s.Commit}});n&&(this.currentCoordinate=t.currentCoordinate,this.lastCommittedCoordinates=n.geometry.coordinates,this.syncClosingPoints(n.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:n.geometry.coordinates}),this.updateSnappedGuidancePointFromLastMouseMove())}redoSize(){return this.undoRedo.redoSize()}redo(){let e=this.undoRedo.takeRedo();if(e){if(this.currentId){let t=this.mutateFeature.updateLineString({featureId:this.currentId,coordinateMutations:{type:M,coordinates:e.featureCoordinates},propertyMutations:{[u.CURRENTLY_DRAWING]:!0},context:{updateType:s.Commit}});if(!t)return;this.currentCoordinate=e.currentCoordinate,this.lastCommittedCoordinates=t.geometry.coordinates,this.syncClosingPoints(t.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:t.geometry.coordinates})}else{let{id:t,geometry:n}=this.mutateFeature.createLineString({coordinates:e.featureCoordinates,properties:{mode:this.mode,[u.CURRENTLY_DRAWING]:!0}});this.currentId=t,this.currentCoordinate=e.currentCoordinate,this.lastCommittedCoordinates=n.coordinates,this.state===`started`&&this.setDrawing(),this.syncClosingPoints(n.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:t,featureCoordinates:n.coordinates})}this.undoRedo.commitRedo(e),this.updateSnappedGuidancePointFromLastMouseMove()}}registerBehaviors(e){this.insertPoint=new Pe(e),this.clickBoundingBox=new Ee(e),this.pixelDistance=new I(e),this.lineSnapping=new Be(e,this.pixelDistance,this.clickBoundingBox),this.coordinateSnapping=new De(e,this.pixelDistance,this.clickBoundingBox),this.readFeature=new F(e),this.mutateFeature=new N(e,{validate:this.validate}),this.closingPoints=new We(e,this.pixelDistance,this.mutateFeature,this.readFeature),this.coordinatePoints=new Ge(e,this.readFeature,this.mutateFeature),this.undoRedo=new Ke({maxStackSize:e.undoRedoMaxStackSize})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onMouseMove(e){this.mouseMove=!0,this.setCursor(this.cursors.start),this.lastMouseMoveEvent=e;let t=this.updateSnappedCoordinate(e)||[e.lng,e.lat];if(this.currentId===void 0||this.currentCoordinate===0)return;let{isClosing:n}=this.closingPoints.isLineStringClosingPoint(e);n&&this.setCursor(this.cursors.close);let r=[{type:A,index:-1,coordinate:t}];if(this.insertCoordinates){let e=this.getInsertCoordinates(t);e&&(r={type:M,coordinates:e})}let i=this.mutateFeature.updateLineString({coordinateMutations:r,featureId:this.currentId,context:{updateType:s.Provisional}});i&&this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:i.geometry.coordinates})}getInsertCoordinates(e){if(!this.lastCommittedCoordinates)return;let t=this.lastCommittedCoordinates[this.lastCommittedCoordinates.length-1];if(xe(t,e))return;let n=this.generateInsertCoordinates(t,e);return[...this.lastCommittedCoordinates.slice(0,-1),...n,e]}onRightClick(e){if(!this.editable||this.state!==`started`)return;let{featureId:t,featureCoordinateIndex:n}=this.coordinateSnapping.getSnappable(e,e=>this.lineStringFilter(e));if(!t||n===void 0)return;let r=this.readFeature.getGeometry(t),o;if(r.type!==`LineString`||(o=r.coordinates,o.length<=2))return;let c=this.mutateFeature.updateLineString({featureId:t,coordinateMutations:[{type:j,index:n}],context:{updateType:s.Finish,action:i}});c&&this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:t,featureCoordinates:c.geometry.coordinates}),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0),this.closingPoints.delete(),this.onFinish(t,{mode:this.mode,action:a})}onLeftClick(e){this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0);let t=this.snapCoordinate(e)||[e.lng,e.lat];this.currentCoordinate===0?this.createLine(t):this.currentCoordinate===1&&this.currentId?this.firstUpdateToLine(t):this.currentId&&this.updateToLine(e,t)}onClick(e){this.currentId===void 0||this.readFeature.hasFeature(this.currentId)||this.cleanUp(),(e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e))&&(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(e),this.mouseMove=!1,e.button===`right`?this.onRightClick(e):e.button===`left`&&this.onLeftClick(e))}onKeyDown(){}onKeyUp(e){e.key===this.keyEvents.cancel&&this.cleanUp(),e.key===this.keyEvents.finish&&this.close()}onDragStart(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,e)||!this.editable)return;let n;if(this.state===`started`){let t=this.lineSnapping.getSnappable(e,e=>this.lineStringFilter(e));t.coordinate&&(this.editedSnapType=`line`,this.editedFeatureCoordinateIndex=t.featureCoordinateIndex,this.editedFeatureId=t.featureId,n=t.coordinate);let r=this.coordinateSnapping.getSnappable(e,e=>this.lineStringFilter(e));r.coordinate&&(this.editedSnapType=`coordinate`,this.editedFeatureCoordinateIndex=r.featureCoordinateIndex,this.editedFeatureId=r.featureId,n=r.coordinate)}this.editedFeatureId&&n&&(this.editedPointId||=this.mutateFeature.createGuidancePoint({coordinate:n,type:u.EDITED}),this.setCursor(this.cursors.dragStart),t(!1))}onDrag(e,t){if(this.allowPointerEvent(this.pointerEvents.onDrag,e)&&this.editedFeatureId!==void 0&&this.editedFeatureCoordinateIndex!==void 0){if(this.editedSnapType===`coordinate`||this.editedSnapType===`line`&&this.editedInsertIndex!==void 0){let t=this.mutateFeature.updateLineString({featureId:this.editedFeatureId,context:{updateType:s.Provisional},coordinateMutations:[{type:A,index:this.editedFeatureCoordinateIndex,coordinate:[e.lng,e.lat]}]});if(!t)return;this.showCoordinatePoints&&(this.editedInsertIndex===void 0?this.coordinatePoints.updateOneAtIndex(this.editedFeatureId,this.editedFeatureCoordinateIndex,[e.lng,e.lat]):this.coordinatePoints.createOrUpdate({featureId:this.editedFeatureId,featureCoordinates:t.geometry.coordinates}))}else if(this.editedSnapType===`line`&&this.editedInsertIndex===void 0){this.editedInsertIndex=this.editedFeatureCoordinateIndex+1;let e=this.mutateFeature.updateLineString({featureId:this.editedFeatureId,context:{updateType:s.Provisional}});if(!e)return;this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.editedFeatureId,featureCoordinates:e.geometry.coordinates}),this.editedFeatureCoordinateIndex++}this.snapping&&this.snappedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),this.snappedPointId=void 0),this.editedPointId&&this.mutateFeature.updateGuidancePoints([{featureId:this.editedPointId,coordinate:[e.lng,e.lat]}]),this.mutateFeature.updateLineString({featureId:this.editedFeatureId,context:{updateType:s.Provisional},propertyMutations:{[u.EDITED]:!0}})}}onDragEnd(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragEnd,e)||this.editedFeatureId===void 0||(this.setCursor(this.cursors.dragEnd),!this.mutateFeature.updateLineString({featureId:this.editedFeatureId,propertyMutations:{[u.EDITED]:!1},context:{updateType:s.Finish,action:i}})))return;let n=this.editedFeatureId;t(!0),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0),this.closingPoints.delete(),this.onFinish(n,{mode:this.mode,action:i})}cleanUp(){let e=this.currentId,t=this.snappedPointId;this.snappedPointId=void 0,this.currentId=void 0,this.currentCoordinate=0,this.lastCommittedCoordinates=void 0,this.undoRedo.clear(),this.state===`drawing`&&this.setStarted(),e&&this.showCoordinatePoints&&this.coordinatePoints.deletePointsByFeatureIds([e]),this.mutateFeature.deleteFeatureIfPresent(e),this.mutateFeature.deleteFeatureIfPresent(t),this.closingPoints.delete()}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});if(e.type===`Feature`&&e.geometry.type===`LineString`&&e.properties.mode===this.mode)return t.lineStringDash=this.styles.lineStringDash,t.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,t.lineStringColor,e),t.lineStringOpacity=this.getNumericStylingValue(this.styles.lineStringOpacity,t.lineStringOpacity===void 0?1:t.lineStringOpacity,e),t.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,t.lineStringWidth,e),t.zIndex=d,t;if(e.type===`Feature`&&e.geometry.type===`Point`&&e.properties.mode===this.mode){let n=e.properties[u.COORDINATE_POINT],r=e.properties[u.CLOSING_POINT]?`closingPoint`:e.properties[u.SNAPPING_POINT]?`snappingPoint`:n?`coordinatePoint`:void 0;if(!r)return t;let i={closingPoint:{width:this.styles.closingPointWidth,color:this.styles.closingPointColor,opacity:this.styles.closingPointOpacity,outlineColor:this.styles.closingPointOutlineColor,outlineWidth:this.styles.closingPointOutlineWidth,outlineOpacity:this.styles.closingPointOutlineOpacity},snappingPoint:{width:this.styles.snappingPointWidth,color:this.styles.snappingPointColor,opacity:this.styles.snappingPointOpacity,outlineColor:this.styles.snappingPointOutlineColor,outlineWidth:this.styles.snappingPointOutlineWidth,outlineOpacity:this.styles.snappingPointOutlineOpacity},coordinatePoint:{width:this.styles.coordinatePointWidth,color:this.styles.coordinatePointColor,opacity:this.styles.coordinatePointOpacity,outlineColor:this.styles.coordinatePointOutlineColor,outlineWidth:this.styles.coordinatePointOutlineWidth,outlineOpacity:this.styles.coordinatePointOutlineOpacity}};return t.pointWidth=this.getNumericStylingValue(i[r].width,t.pointWidth,e),t.pointOpacity=this.getNumericStylingValue(i[r].opacity,1,e),t.pointColor=this.getHexColorStylingValue(i[r].color,t.pointColor,e),t.pointOutlineColor=this.getHexColorStylingValue(i[r].outlineColor,`#ffffff`,e),t.pointOutlineWidth=this.getNumericStylingValue(i[r].outlineWidth,2,e),t.pointOutlineOpacity=this.getNumericStylingValue(i[r].outlineOpacity,1,e),t.zIndex=n?20:50,t}return t}validateFeature(e){return this.validateModeFeature(e,e=>Fe(e,this.coordinatePrecision))}lineStringFilter(e){return!!(e.geometry.type===`LineString`&&e.properties&&e.properties.mode===this.mode)}snapCoordinate(e){var t,n,r;let i;if((t=this.snapping)!=null&&t.toLine){let t;t=this.currentId?this.lineSnapping.getSnappableCoordinate(e,this.currentId):this.lineSnapping.getSnappableCoordinateFirstClick(e),t&&(i=t)}if((n=this.snapping)!=null&&n.toCoordinate){let t;t=this.currentId?this.coordinateSnapping.getSnappableCoordinate(e,this.currentId):this.coordinateSnapping.getSnappableCoordinateFirstClick(e),t&&(i=t)}if((r=this.snapping)!=null&&r.toCustom){let t=this.snapping.toCustom(e,{currentCoordinate:this.currentCoordinate,currentId:this.currentId,getCurrentGeometrySnapshot:this.currentId?()=>this.readFeature.getGeometry(this.currentId):()=>null,project:this.project,unproject:this.unproject});t&&(i=t)}return i}afterFeatureUpdated(e){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates}),this.editedFeatureId===e.id&&this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0),this.snappedPointId&&this.lastMouseMoveEvent&&this.updateSnappedCoordinate(this.lastMouseMoveEvent),this.currentId===e.id&&(this.closingPoints.delete(),this.currentCoordinate=0,this.currentId=void 0,this.lastCommittedCoordinates=void 0,this.undoRedo.clear(),this.state===`drawing`&&this.setStarted())}afterFeatureAdded(e){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates})}},Xe=`Feature is not a Point`,Ze=`Feature has invalid coordinates`,Qe=`Feature has coordinates with excessive precision`;function $e(e,t){return e.geometry.type===`Point`?ce(e.geometry.coordinates)?se(e.geometry.coordinates,t)?{valid:!0}:{valid:!1,reason:Qe}:{valid:!1,reason:Ze}:{valid:!1,reason:Xe}}var et=class extends O{constructor(e,t,n){super(e),this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.pixelDistance=t,this.clickBoundingBox=n}getNearestPointFeature(e){let t=this.clickBoundingBox.create(e),n=this.store.search(t),r,i=1/0;for(let t=0;t<n.length;t++){let a=n[t];if(a.geometry.type!==`Point`||a.properties.mode!==this.mode)continue;let o=this.pixelDistance.measure(e,a.geometry.coordinates);o>i||o>this.pointerDistance||(i=o,r=a)}return r}},tt={create:`crosshair`,dragStart:`grabbing`,dragEnd:`crosshair`},nt=class extends v{constructor(e){super(e,!0),this.mode=`point`,this.cursors=tt,this.editable=!1,this.editedFeatureId=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.pointSearch=void 0,this.mutateFeature=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors)),e!=null&&e.editable&&(this.editable=e.editable)}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onClick(e){e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e)?this.onRightClick(e):e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)&&this.onLeftClick(e)}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){this.editedFeatureId=void 0}onDragStart(e,t){if(this.allowPointerEvent(this.pointerEvents.onDragStart,e)){if(this.editable){let t=this.pointSearch.getNearestPointFeature(e);this.editedFeatureId=t?.id}this.editedFeatureId&&(this.setCursor(this.cursors.dragStart),t(!1))}}onDrag(e,t){this.allowPointerEvent(this.pointerEvents.onDrag,e)&&this.editedFeatureId!==void 0&&this.mutateFeature.updatePoint({featureId:this.editedFeatureId,coordinateMutations:{type:M,coordinates:[e.lng,e.lat]},propertyMutations:{[u.EDITED]:!0},context:{updateType:s.Provisional}})}onDragEnd(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragEnd,e)||this.editedFeatureId===void 0||!this.mutateFeature.updatePoint({featureId:this.editedFeatureId,propertyMutations:{mode:this.mode,[u.EDITED]:!1},context:{updateType:s.Finish,action:`edit`}}))return;let n=this.editedFeatureId;this.setCursor(this.cursors.dragEnd),this.editedFeatureId=void 0,t(!0),this.onFinish(n,{mode:this.mode,action:r})}registerBehaviors(e){this.pixelDistance=new I(e),this.clickBoundingBox=new Ee(e),this.pointSearch=new et(e,this.pixelDistance,this.clickBoundingBox),this.mutateFeature=new N(e,{validate:this.validate})}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});if(e.type===`Feature`&&e.geometry.type===`Point`&&e.properties.mode===this.mode){let n=!!(e.id&&this.editedFeatureId===e.id);t.pointWidth=this.getNumericStylingValue(n?this.styles.editedPointWidth:this.styles.pointWidth,t.pointWidth,e),t.pointOpacity=this.getNumericStylingValue(this.styles.pointOpacity,t.pointOpacity===void 0?1:t.pointOpacity,e),t.pointColor=this.getHexColorStylingValue(n?this.styles.editedPointColor:this.styles.pointColor,t.pointColor,e),t.pointOutlineColor=this.getHexColorStylingValue(n?this.styles.editedPointOutlineColor:this.styles.pointOutlineColor,t.pointOutlineColor,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.pointOutlineOpacity,t.pointOutlineOpacity===void 0?1:t.pointOutlineOpacity,e),t.pointOutlineWidth=this.getNumericStylingValue(n?this.styles.editedPointOutlineWidth:this.styles.pointOutlineWidth,2,e),t.zIndex=30}return t}validateFeature(e){return this.validateModeFeature(e,e=>$e(e,this.coordinatePrecision))}onLeftClick(e){let t=this.mutateFeature.createPoint({coordinates:[e.lng,e.lat],properties:{mode:this.mode},context:{updateType:s.Finish,action:r}});t&&this.onFinish(t.id,{mode:this.mode,action:r})}onRightClick(e){if(!this.editable)return;let t=this.pointSearch.getNearestPointFeature(e);t&&this.mutateFeature.deleteFeatureIfPresent(t.id)}afterFeatureUpdated(e){this.editedFeatureId===e.id&&(this.editedFeatureId=void 0,this.setCursor(this.cursors.create))}},rt={cancel:`Escape`,finish:`Enter`},it={start:`crosshair`,close:`pointer`,dragStart:`grabbing`,dragEnd:`crosshair`},at=class extends v{constructor(e){super(e,!0),this.mode=`polygon`,this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=rt,this.cursors=it,this.mouseMove=!1,this.showCoordinatePoints=!1,this.lastMouseMoveEvent=void 0,this.snapping=void 0,this.snappedPointId=void 0,this.editable=!1,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0,this.editedInsertIndex=void 0,this.editedPointId=void 0,this.coordinatePoints=void 0,this.lineSnapping=void 0,this.coordinateSnapping=void 0,this.pixelDistance=void 0,this.closingPoints=void 0,this.clickBoundingBox=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.undoRedo=void 0,this.updateOptions(e)}updateOptions(e){if(super.updateOptions(e),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors)),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=n({},this.keyEvents,e.keyEvents)),e!=null&&e.snapping&&(this.snapping=e.snapping),e?.editable!==void 0&&(this.editable=e.editable),e?.pointerEvents!==void 0&&(this.pointerEvents=e.pointerEvents),e?.showCoordinatePoints!==void 0){if(this.showCoordinatePoints=e.showCoordinatePoints,this.coordinatePoints&&!0===e.showCoordinatePoints)this.store.copyAllWhere(e=>e.mode===this.mode).filter(e=>e.geometry.type===`Polygon`).forEach(e=>{this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates})});else if(this.coordinatePoints&&!1===this.showCoordinatePoints){let e=this.store.copyAllWhere(e=>e.mode===this.mode&&!!e[u.COORDINATE_POINT_IDS]).filter(e=>e.geometry.type===`Polygon`);this.coordinatePoints.deletePointsByFeatureIds(e.map(e=>e.id))}}}close(){if(this.currentId===void 0||this.readFeature.getCoordinates(this.currentId).length<5)return;let e=this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:[{type:j,index:-2}],propertyMutations:{[u.CURRENTLY_DRAWING]:void 0,[u.COMMITTED_COORDINATE_COUNT]:void 0,[u.PROVISIONAL_COORDINATE_COUNT]:void 0},context:{updateType:s.Finish,action:r}});if(!e)return;this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:e.geometry.coordinates}),this.state===`drawing`&&this.setStarted(),this.editedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),void 0),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.closingPoints.delete();let t=this.currentId;this.currentCoordinate=0,this.currentId=void 0,this.undoRedo.clear(),this.onFinish(t,{mode:this.mode,action:r})}registerBehaviors(e){this.readFeature=new F(e),this.mutateFeature=new N(e,{validate:this.validate}),this.clickBoundingBox=new Ee(e),this.pixelDistance=new I(e),this.lineSnapping=new Be(e,this.pixelDistance,this.clickBoundingBox),this.coordinateSnapping=new De(e,this.pixelDistance,this.clickBoundingBox),this.closingPoints=new We(e,this.pixelDistance,this.mutateFeature,this.readFeature),this.coordinatePoints=new Ge(e,this.readFeature,this.mutateFeature),this.undoRedo=new Ke({maxStackSize:e.undoRedoMaxStackSize})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}updateSnappedCoordinate(e){let t=this.snapCoordinate(e);t?(this.snappedPointId?this.mutateFeature.updateGuidancePoints([{featureId:this.snappedPointId,coordinate:t}]):this.snappedPointId=this.mutateFeature.createGuidancePoint({coordinate:t,type:u.SNAPPING_POINT}),e.lng=t[0],e.lat=t[1]):this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0)}undoSize(){return this.undoRedo.undoSize()}clearHistory(){this.undoRedo.clear()}pushHistorySnapshot(e,t){let n=this.readFeature.getGeometry(e);this.undoRedo.recordSnapshot({featureCoordinates:n.coordinates,currentCoordinate:t})}updateSnappedGuidancePointFromLastMouseMove(){this.snapping&&this.lastMouseMoveEvent?this.updateSnappedCoordinate(this.lastMouseMoveEvent):this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0)}syncClosingPoints(e){this.currentCoordinate>=3?this.closingPoints.ids.length?this.closingPoints.update(e):this.closingPoints.create(e):this.closingPoints.delete()}undo(){if(this.state!==`drawing`||!this.currentId)return;let e=this.undoRedo.beginUndo();if(!e)return;let{previousEntry:t}=e;if(!t){let e=this.currentId;this.currentId=void 0,this.currentCoordinate=0,this.closingPoints.delete(),this.state===`drawing`&&this.setStarted(),this.showCoordinatePoints&&this.coordinatePoints.deletePointsByFeatureIds([e]),this.mutateFeature.deleteFeatureIfPresent(e),this.updateSnappedGuidancePointFromLastMouseMove();return}let n=this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:{type:M,coordinates:t.featureCoordinates},propertyMutations:{[u.CURRENTLY_DRAWING]:!0,[u.COMMITTED_COORDINATE_COUNT]:t.currentCoordinate,[u.PROVISIONAL_COORDINATE_COUNT]:t.currentCoordinate},context:{updateType:s.Commit}});n&&(this.currentCoordinate=t.currentCoordinate,this.syncClosingPoints(n.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:n.geometry.coordinates}),this.updateSnappedGuidancePointFromLastMouseMove())}redoSize(){return this.undoRedo.redoSize()}redo(){let e=this.undoRedo.takeRedo();if(e){if(this.currentId){let t=this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:{type:M,coordinates:e.featureCoordinates},propertyMutations:{[u.CURRENTLY_DRAWING]:!0,[u.COMMITTED_COORDINATE_COUNT]:e.currentCoordinate,[u.PROVISIONAL_COORDINATE_COUNT]:e.currentCoordinate},context:{updateType:s.Commit}});if(!t)return;this.currentCoordinate=e.currentCoordinate,this.syncClosingPoints(t.geometry.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:t.geometry.coordinates})}else{let t=this.undoRedo.cloneCoordinates(e.featureCoordinates)[0],{id:n,geometry:r}=this.mutateFeature.createPolygon({coordinates:t,properties:{mode:this.mode,[u.CURRENTLY_DRAWING]:!0,[u.COMMITTED_COORDINATE_COUNT]:e.currentCoordinate,[u.PROVISIONAL_COORDINATE_COUNT]:e.currentCoordinate}});this.currentId=n,this.currentCoordinate=e.currentCoordinate,this.state===`started`&&this.setDrawing(),this.syncClosingPoints(r.coordinates),this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:n,featureCoordinates:r.coordinates})}this.undoRedo.commitRedo(e),this.updateSnappedGuidancePointFromLastMouseMove()}}onMouseMove(e){if(this.mouseMove=!0,this.setCursor(this.cursors.start),this.lastMouseMoveEvent=e,this.updateSnappedCoordinate(e),this.currentId===void 0||this.currentCoordinate===0)return;let t=this.readFeature.getCoordinate(this.currentId,0),n=[e.lng,e.lat],r;if(this.currentCoordinate===1)r=[{type:A,index:1,coordinate:n},{type:A,index:2,coordinate:[e.lng,e.lat]}];else if(this.currentCoordinate===2)r=[{type:A,index:2,coordinate:n}];else{let{isClosing:i,isPreviousClosing:a}=this.closingPoints.isPolygonClosingPoints(e);a||i?(this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.setCursor(this.cursors.close),r=[{type:A,index:-1,coordinate:t},{type:A,index:-2,coordinate:t}]):r=[{type:A,index:-2,coordinate:n},{type:A,index:-1,coordinate:t}]}let i=this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:r,propertyMutations:{[u.PROVISIONAL_COORDINATE_COUNT]:this.currentCoordinate+1},context:{updateType:s.Provisional}});i&&this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:i.geometry.coordinates})}snapCoordinate(e){var t,n,r;let i;if((t=this.snapping)!=null&&t.toLine){let t;t=this.currentId?this.lineSnapping.getSnappableCoordinate(e,this.currentId):this.lineSnapping.getSnappableCoordinateFirstClick(e),t&&(i=t)}if((n=this.snapping)!=null&&n.toCoordinate){let t;t=this.currentId?this.coordinateSnapping.getSnappableCoordinate(e,this.currentId):this.coordinateSnapping.getSnappableCoordinateFirstClick(e),t&&(i=t)}if((r=this.snapping)!=null&&r.toCustom){let t=this.snapping.toCustom(e,{currentCoordinate:this.currentCoordinate,currentId:this.currentId,getCurrentGeometrySnapshot:this.currentId?()=>this.readFeature.getGeometry(this.currentId):()=>null,project:this.project,unproject:this.unproject});t&&(i=t)}return i}polygonFilter(e){return!!(e.geometry.type===`Polygon`&&e.properties&&e.properties.mode===this.mode)}onRightClick(e){if(!this.editable||this.state!==`started`)return;let{featureId:t,featureCoordinateIndex:n}=this.coordinateSnapping.getSnappable(e,e=>this.polygonFilter(e));if(!t||n===void 0)return;let r=this.readFeature.getGeometry(t);if(r.type!==`Polygon`)return;let a=r.coordinates[0];if(a.length<=4)return;let o;o=n===0||n===a.length-1?[{type:j,index:0},{type:j,index:-1},{type:k,index:-1,coordinate:a[1]}]:[{type:j,index:n}];let c=this.mutateFeature.updatePolygon({featureId:t,coordinateMutations:o,context:{updateType:s.Finish,action:i}});if(c){if(this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:t,featureCoordinates:c.geometry.coordinates}),this.snappedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),this.snappedPointId=void 0,this.snapping)){let t=this.snapCoordinate(e);if(t){let[e]=this.mutateFeature.createGuidancePoints({type:u.SNAPPING_POINT,coordinates:[t]});this.snappedPointId=e}}this.onFinish(t,{mode:this.mode,action:i})}}onLeftClick(e){this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0);let t=this.snapCoordinate(e)||[e.lng,e.lat];if(this.currentCoordinate===0){let{id:e,geometry:n}=this.mutateFeature.createPolygon({coordinates:[t,t,t,t],properties:{mode:this.mode,[u.CURRENTLY_DRAWING]:!0,[u.COMMITTED_COORDINATE_COUNT]:this.currentCoordinate+1,[u.PROVISIONAL_COORDINATE_COUNT]:this.currentCoordinate+1}});this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:e,featureCoordinates:n.coordinates}),this.currentId=e,this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.setDrawing()}else if(this.currentCoordinate===1&&this.currentId){if(this.readFeature.coordinateAtIndexIsIdentical({featureId:this.currentId,newCoordinate:t,index:0}))return;let e=this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:[{type:A,index:1,coordinate:t},{type:A,index:2,coordinate:t}],propertyMutations:{[u.COMMITTED_COORDINATE_COUNT]:this.currentCoordinate+1},context:{updateType:s.Commit}});if(!e)return;this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:e.geometry.coordinates}),this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate)}else if(this.currentCoordinate===2&&this.currentId){if(this.readFeature.coordinateAtIndexIsIdentical({featureId:this.currentId,newCoordinate:t,index:1}))return;let e=this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:[{type:A,index:2,coordinate:t},{type:k,index:2,coordinate:t}],propertyMutations:{[u.COMMITTED_COORDINATE_COUNT]:this.currentCoordinate+1},context:{updateType:s.Commit}});if(!e)return;this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:e.geometry.coordinates}),this.currentCoordinate===2&&this.closingPoints.create(e.geometry.coordinates),this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate)}else if(this.currentId){let{isClosing:n,isPreviousClosing:r}=this.closingPoints.isPolygonClosingPoints(e);if(r||n)this.close();else{if(this.readFeature.coordinateAtIndexIsIdentical({featureId:this.currentId,newCoordinate:t,index:this.currentCoordinate-1}))return;let e=this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:[{type:_e,index:-1,coordinate:t}],propertyMutations:{[u.COMMITTED_COORDINATE_COUNT]:this.currentCoordinate+1},context:{updateType:s.Commit}});if(!e)return;this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:this.currentId,featureCoordinates:e.geometry.coordinates}),this.currentCoordinate++,this.pushHistorySnapshot(this.currentId,this.currentCoordinate),this.closingPoints.ids.length&&this.closingPoints.update(e.geometry.coordinates)}}}onClick(e){this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(e),this.mouseMove=!1,e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e)?this.onRightClick(e):e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)&&this.onLeftClick(e)}onKeyUp(e){e.key===this.keyEvents.cancel?this.cleanUp():e.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,e)||!this.editable)return;let n;if(this.state===`started`){let t=this.lineSnapping.getSnappable(e,e=>this.polygonFilter(e));t.coordinate&&(this.editedSnapType=`line`,this.editedFeatureCoordinateIndex=t.featureCoordinateIndex,this.editedFeatureId=t.featureId,n=t.coordinate);let r=this.coordinateSnapping.getSnappable(e,e=>this.polygonFilter(e));r.coordinate&&(this.editedSnapType=`coordinate`,this.editedFeatureCoordinateIndex=r.featureCoordinateIndex,this.editedFeatureId=r.featureId,n=r.coordinate)}this.editedFeatureId&&n&&(this.editedPointId||=this.mutateFeature.createGuidancePoint({coordinate:n,type:u.EDITED}),this.setCursor(this.cursors.dragStart),t(!1))}onDrag(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDrag,e)||this.editedFeatureId===void 0||this.editedFeatureCoordinateIndex===void 0)return;let n=this.readFeature.getGeometry(this.editedFeatureId),r=[e.lng,e.lat],i=[];if(this.editedSnapType===`coordinate`||this.editedSnapType===`line`&&this.editedInsertIndex!==void 0?i=this.editedFeatureCoordinateIndex===0||this.editedFeatureCoordinateIndex===n.coordinates[0].length-1?[{type:A,index:0,coordinate:r},{type:A,index:-1,coordinate:r}]:[{type:A,index:this.editedFeatureCoordinateIndex,coordinate:r}]:this.editedSnapType===`line`&&this.editedInsertIndex===void 0&&(this.editedInsertIndex=this.editedFeatureCoordinateIndex+1,i=[{type:_e,index:this.editedInsertIndex,coordinate:r}],this.editedFeatureCoordinateIndex++),i.length===0)return;let a=this.mutateFeature.updatePolygon({featureId:this.editedFeatureId,coordinateMutations:i,propertyMutations:{[u.EDITED]:!0},context:{updateType:s.Provisional}});a&&(this.showCoordinatePoints&&(this.editedInsertIndex?this.coordinatePoints.createOrUpdate({featureId:this.editedFeatureId,featureCoordinates:a.geometry.coordinates}):this.coordinatePoints.updateOneAtIndex(this.editedFeatureId,this.editedFeatureCoordinateIndex,a.geometry.coordinates[0][this.editedFeatureCoordinateIndex])),this.snapping&&this.snappedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),this.snappedPointId=void 0),this.editedPointId&&this.mutateFeature.updateGuidancePoints([{featureId:this.editedPointId,coordinate:r}]))}onDragEnd(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragEnd,e)||this.editedFeatureId===void 0||(this.setCursor(this.cursors.dragEnd),!this.mutateFeature.updatePolygon({featureId:this.editedFeatureId,propertyMutations:{[u.EDITED]:!1},context:{updateType:s.Finish,action:i}})))return;let n=this.editedFeatureId;this.editedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),void 0),this.snappedPointId&&=(this.mutateFeature.deleteFeatureIfPresent(this.snappedPointId),void 0),this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0,t(!0),this.onFinish(n,{mode:this.mode,action:i})}cleanUp(){let e=this.currentId,t=this.snappedPointId,n=this.editedPointId;this.currentId=void 0,this.snappedPointId=void 0,this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedInsertIndex=void 0,this.editedSnapType=void 0,this.currentCoordinate=0,this.undoRedo.clear(),this.state===`drawing`&&this.setStarted(),e&&this.coordinatePoints.deletePointsByFeatureIds([e]),this.mutateFeature.deleteFeatureIfPresent(e),this.mutateFeature.deleteFeatureIfPresent(n),this.mutateFeature.deleteFeatureIfPresent(t),this.closingPoints.ids.length&&this.closingPoints.delete()}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});if(e.properties.mode===this.mode){if(e.geometry.type===`Polygon`)return t.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,t.polygonFillColor,e),t.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,t.polygonOutlineColor,e),t.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,t.polygonOutlineWidth,e),t.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,t.polygonFillOpacity,e),t.polygonOutlineOpacity=this.getNumericStylingValue(this.styles.outlineOpacity,1,e),t.zIndex=d,t;if(e.geometry.type===`Point`){let n=e.properties[u.EDITED],r=e.properties[u.COORDINATE_POINT],i=n?`editedPoint`:e.properties[u.CLOSING_POINT]?`closingPoint`:e.properties[u.SNAPPING_POINT]?`snappingPoint`:r?`coordinatePoint`:void 0;if(!i)return t;let a={editedPoint:{width:this.styles.editedPointOutlineWidth,color:this.styles.editedPointColor,opacity:this.styles.editedPointOpacity,outlineColor:this.styles.editedPointOutlineColor,outlineWidth:this.styles.editedPointOutlineWidth,outlineOpacity:this.styles.editedPointOutlineOpacity},closingPoint:{width:this.styles.closingPointWidth,color:this.styles.closingPointColor,opacity:this.styles.closingPointOpacity,outlineColor:this.styles.closingPointOutlineColor,outlineWidth:this.styles.closingPointOutlineWidth,outlineOpacity:this.styles.closingPointOutlineOpacity},snappingPoint:{width:this.styles.snappingPointWidth,color:this.styles.snappingPointColor,opacity:this.styles.snappingPointOpacity,outlineColor:this.styles.snappingPointOutlineColor,outlineWidth:this.styles.snappingPointOutlineWidth,outlineOpacity:this.styles.snappingPointOutlineOpacity},coordinatePoint:{width:this.styles.coordinatePointWidth,color:this.styles.coordinatePointColor,opacity:this.styles.coordinatePointOpacity,outlineColor:this.styles.coordinatePointOutlineColor,outlineWidth:this.styles.coordinatePointOutlineWidth,outlineOpacity:this.styles.coordinatePointOutlineOpacity}};return t.pointWidth=this.getNumericStylingValue(a[i].width,t.pointWidth,e),t.pointOpacity=this.getNumericStylingValue(a[i].opacity,1,e),t.pointColor=this.getHexColorStylingValue(a[i].color,t.pointColor,e),t.pointOutlineColor=this.getHexColorStylingValue(a[i].outlineColor,t.pointOutlineColor,e),t.pointOutlineOpacity=this.getNumericStylingValue(a[i].outlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(a[i].outlineWidth,2,e),t.zIndex=n?40:r?20:30,t}}return t}afterFeatureAdded(e){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates})}afterFeatureUpdated(e){this.showCoordinatePoints&&this.coordinatePoints.createOrUpdate({featureId:e.id,featureCoordinates:e.geometry.coordinates}),this.editedFeatureId===e.id&&this.editedPointId&&(this.mutateFeature.deleteFeatureIfPresent(this.editedPointId),this.editedPointId=void 0,this.editedFeatureId=void 0,this.editedFeatureCoordinateIndex=void 0,this.editedSnapType=void 0),this.snappedPointId&&this.lastMouseMoveEvent&&this.updateSnappedCoordinate(this.lastMouseMoveEvent),this.currentId===e.id&&(this.currentCoordinate=0,this.currentId=void 0,this.undoRedo.clear(),this.closingPoints.delete(),this.state===`drawing`&&this.setStarted())}validateFeature(e){return this.validateModeFeature(e,e=>me(e,this.coordinatePrecision))}},ot={cancel:`Escape`,finish:`Enter`},st={start:`crosshair`},ct=class extends v{constructor(e){super(e,!0),this.mode=`rectangle`,this.startPosition=void 0,this.endPosition=void 0,this.currentRectangleId=void 0,this.keyEvents=ot,this.cursors=st,this.drawInteraction=`click-move`,this.drawType=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors)),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=n({},this.keyEvents,e.keyEvents)),e!=null&&e.drawInteraction&&(this.drawInteraction=e.drawInteraction)}updateRectangle(e,t){if(!this.startPosition||!this.currentRectangleId)return;let n=t===s.Finish;return this.mutateFeature.updatePolygon({featureId:this.currentRectangleId,coordinateMutations:[{type:A,index:1,coordinate:[e[0],this.startPosition[1]]},{type:A,index:2,coordinate:e},{type:A,index:3,coordinate:[this.startPosition[0],e[1]]}],propertyMutations:n?{[u.CURRENTLY_DRAWING]:void 0}:{},context:n?{updateType:t,action:r}:{updateType:t}})}close(){if(!this.currentRectangleId||!this.endPosition||!this.updateRectangle(this.endPosition,s.Finish))return;let e=this.currentRectangleId;this.startPosition=void 0,this.currentRectangleId=void 0,this.drawType=void 0,this.state===`drawing`&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:r})}beginDrawing(e,t=`click`){this.startPosition=[e.lng,e.lat],this.endPosition=[e.lng,e.lat];let n=this.mutateFeature.createPolygon({coordinates:[[e.lng,e.lat],[e.lng,e.lat],[e.lng,e.lat],[e.lng,e.lat],[e.lng,e.lat]],properties:{mode:this.mode,[u.CURRENTLY_DRAWING]:!0}});this.currentRectangleId=n.id,this.drawType=t,this.setDrawing()}moveDrawAllowed(){return this.drawInteraction===`click-move`||this.drawInteraction===`click-move-or-drag`}dragDrawAllowed(){return this.drawInteraction===`click-drag`||this.drawInteraction===`click-move-or-drag`}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onClick(e){this.moveDrawAllowed()&&(e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e))&&(this.startPosition?(this.endPosition=[e.lng,e.lat],this.close()):this.beginDrawing(e))}onMouseMove(e){this.endPosition=[e.lng,e.lat],this.updateRectangle(this.endPosition,s.Provisional)}onKeyDown(){}onKeyUp(e){e.key===this.keyEvents.cancel?this.cleanUp():e.key===this.keyEvents.finish&&this.close()}onDragStart(e,t){this.state!==`drawing`&&this.allowPointerEvent(this.pointerEvents.onDragStart,e)&&this.dragDrawAllowed()&&(this.beginDrawing(e,`drag`),t(!1))}onDrag(e,t){this.allowPointerEvent(this.pointerEvents.onDrag,e)&&this.dragDrawAllowed()&&this.drawType===`drag`&&(this.endPosition=[e.lng,e.lat],this.updateRectangle(this.endPosition,s.Provisional))}onDragEnd(e,t){this.allowPointerEvent(this.pointerEvents.onDragEnd,e)&&this.dragDrawAllowed()&&this.drawType===`drag`&&(this.endPosition=[e.lng,e.lat],this.close(),t(!0))}cleanUp(){let e=this.currentRectangleId;this.startPosition=void 0,this.currentRectangleId=void 0,this.drawType=void 0,this.state===`drawing`&&this.setStarted(),this.mutateFeature.deleteFeatureIfPresent(e)}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});return e.type===`Feature`&&e.geometry.type===`Polygon`&&e.properties.mode===this.mode?(t.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,t.polygonFillColor,e),t.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,t.polygonOutlineColor,e),t.polygonOutlineOpacity=this.getNumericStylingValue(this.styles.outlineOpacity,1,e),t.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,t.polygonOutlineWidth,e),t.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,t.polygonFillOpacity,e),t.zIndex=d,t):t}validateFeature(e){return this.validateModeFeature(e,e=>he(e,this.coordinatePrecision))}afterFeatureUpdated(e){this.currentRectangleId===e.id&&(this.startPosition=void 0,this.currentRectangleId=void 0,this.drawType=void 0,this.state===`drawing`&&this.setStarted())}registerBehaviors(e){this.readFeature=new F(e),this.mutateFeature=new N(e,{validate:this.validate})}},V=class extends v{constructor(e){if(!e.modeName)throw Error(`Mode name is required for TerraDrawRenderMode`);super(e,!0),this.type=g.Render,this.mode=`render`,this.updateOptions(e)}updateOptions(e){super.updateOptions(e)}registerBehaviors(e){this.mode=e.mode}start(){this.setStarted()}stop(){this.setStopped()}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(e){return{pointColor:this.getHexColorStylingValue(this.styles.pointColor,`#3f97e0`,e),pointWidth:this.getNumericStylingValue(this.styles.pointWidth,6,e),pointOpacity:this.getNumericStylingValue(this.styles.pointOpacity,1,e),pointOutlineColor:this.getHexColorStylingValue(this.styles.pointOutlineColor,`#ffffff`,e),pointOutlineWidth:this.getNumericStylingValue(this.styles.pointOutlineWidth,0,e),pointOutlineOpacity:this.getNumericStylingValue(this.styles.pointOutlineOpacity,1,e),polygonFillColor:this.getHexColorStylingValue(this.styles.polygonFillColor,`#3f97e0`,e),polygonFillOpacity:this.getNumericStylingValue(this.styles.polygonFillOpacity,.3,e),polygonOutlineColor:this.getHexColorStylingValue(this.styles.polygonOutlineColor,`#3f97e0`,e),polygonOutlineWidth:this.getNumericStylingValue(this.styles.polygonOutlineWidth,4,e),lineStringWidth:this.getNumericStylingValue(this.styles.lineStringWidth,4,e),lineStringColor:this.getHexColorStylingValue(this.styles.lineStringColor,`#3f97e0`,e),lineStringOpacity:this.getNumericStylingValue(this.styles.lineStringOpacity,1,e),zIndex:this.getNumericStylingValue(this.styles.zIndex,0,e),lineStringDash:void 0}}validateFeature(e){let t=super.validateFeature(e);if(t.valid){let t=e,n=$e(t,this.coordinatePrecision).valid||me(t,this.coordinatePrecision).valid||Fe(t,this.coordinatePrecision).valid;return n?{valid:!0}:{valid:n,reason:`Feature is not a valid Point, Polygon or LineString feature`}}return t}};function lt(e,t){let n=e,r=t,i=S(n[1]),a=S(r[1]),o=S(r[0]-n[0]);o>Math.PI&&(o-=2*Math.PI),o<-Math.PI&&(o+=2*Math.PI);let s=Math.log(Math.tan(a/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),c=(C(Math.atan2(o,s))+360)%360;return c>180?-(360-c):c}function ut(e,t,n){let r=t;t<0&&(r=-Math.abs(r));let i=r/x,a=e[0]*Math.PI/180,o=S(e[1]),s=S(n),c=i*Math.cos(s),l=o+c;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);let u=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(o/2+Math.PI/4)),d=Math.abs(u)>1e-11?c/u:Math.cos(o),f=[(180*(a+i*Math.sin(s)/d)/Math.PI+540)%360-180,180*l/Math.PI];return f[0]+=f[0]-e[0]>180?-360:e[0]-f[0]>180?360:0,f}function dt(e,t,n,r,i){let a=r(e[0],e[1]),o=r(t[0],t[1]),{lng:s,lat:c}=i((a.x+o.x)/2,(a.y+o.y)/2);return[w(s,n),w(c,n)]}function ft(e,t,n){let r=ut(e,1e3*b(e,t)/2,lt(e,t));return[w(r[0],n),w(r[1],n)]}function pt({featureCoords:e,precision:t,unproject:n,project:r,projection:i}){let a=[];for(let o=0;o<e.length-1;o++){let s;if(i===`web-mercator`)s=dt(e[o],e[o+1],t,r,n);else{if(i!==`globe`)throw Error(`Invalid projection`);s=ft(e[o],e[o+1],t)}a.push(s)}return a}var mt=class extends O{constructor(e,t,n,r,i,a){super(e),this.config=void 0,this.selectionPointBehavior=void 0,this.coordinatePointBehavior=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.pixelDistance=void 0,this._midPoints=[],this.config=e,this.selectionPointBehavior=t,this.coordinatePointBehavior=n,this.mutateFeature=r,this.readFeature=i,this.pixelDistance=a}getMidpointConfig(e){return{featureCoords:e,precision:this.coordinatePrecision,project:this.config.project,unproject:this.config.unproject,projection:this.config.projection}}get ids(){return this._midPoints.concat()}set ids(e){}getNearestMidPoint(e){let t,n=1/0;return this.ids.forEach(r=>{let i=this.readFeature.getGeometry(r),a=this.pixelDistance.measure(e,i.coordinates);a<this.pointerDistance&&a<n&&(n=a,t=r)}),t}insert({featureId:e,midPointId:t}){let n=this.readFeature.getGeometry(t),{midPointFeatureId:r,midPointSegment:i}=this.readFeature.getProperties(t),a=this.readFeature.getGeometry(r),o={featureId:r,coordinateMutations:[{type:k,index:i,coordinate:n.coordinates}],context:{updateType:s.Commit}},c=null;if(a.type===`Polygon`)c=this.mutateFeature.updatePolygon(o);else{if(a.type!==`LineString`)throw Error(`Midpoints can only be added to polygons or linestrings`);c=this.mutateFeature.updateLineString(o)}if(!c)throw Error(`Failed to insert midpoint coordinate`);let l=c.geometry.coordinates;this.readFeature.getProperties(e)[u.COORDINATE_POINT_IDS]&&this.coordinatePointBehavior.createOrUpdate({featureId:e,featureCoordinates:l}),this.mutateFeature.deleteFeaturesIfPresent([...this.selectionPointBehavior.ids,...this._midPoints]),this.create({featureCoordinates:l,featureId:r}),this.selectionPointBehavior.create({featureCoordinates:l,featureId:e})}create({featureCoordinates:e,featureId:t}){if(!this.readFeature.hasFeature(t))throw Error(`Store does not have feature with this id`);let n=Ue(e),r=pt(this.getMidpointConfig(n));this._midPoints=this.mutateFeature.createGuidancePoints({additionalProperties:e=>({mode:this.mode,midPointSegment:e,midPointFeatureId:t,[l.MID_POINT]:!0}),coordinates:r,type:l.MID_POINT})}delete(){this._midPoints.length&&(this.mutateFeature.deleteFeaturesIfPresent(this._midPoints),this._midPoints=[])}updateAllInPlace({featureCoordinates:e}){if(this._midPoints.length===0)return;let t=Ue(e),n=pt(this.getMidpointConfig(t));this.mutateFeature.updateGuidancePoints(this._midPoints.map((e,t)=>({featureId:e,coordinate:n[t]})))}updateOneAtIndex(e,t){if(e<0&&(e=this._midPoints.length+e),this._midPoints[e]===void 0)return;let n=Ue(t),r=pt(this.getMidpointConfig(n));this.mutateFeature.updateGuidancePoints([{featureId:this._midPoints[e],coordinate:r[e]}])}},ht=class extends O{constructor(e,t){super(e),this.mutateFeature=void 0,this._selectionPoints=[],this.mutateFeature=t}get ids(){return this._selectionPoints.concat()}set ids(e){}create({featureId:e,featureCoordinates:t}){let n=He(t);this._selectionPoints=this.mutateFeature.createGuidancePoints({coordinates:n,type:l.SELECTION_POINT,additionalProperties:t=>({[l.SELECTION_POINT_FEATURE_ID]:e,index:t})})}delete(){this.ids.length&&(this.mutateFeature.deleteFeaturesIfPresent(this.ids),this._selectionPoints=[])}updateAllInPlace({featureCoordinates:e}){if(this._selectionPoints.length===0)return;let t=He(e);t.length===this._selectionPoints.length&&this.mutateFeature.updateGuidancePoints(this._selectionPoints.map((e,n)=>({featureId:e,coordinate:t[n]})))}updateOneAtIndex(e,t){this._selectionPoints[e]!==void 0&&this.mutateFeature.updateGuidancePoints([{featureId:this._selectionPoints[e],coordinate:t}])}};function gt(e,t){let n=!1;for(let o=0,s=t.length;o<s;o++){let s=t[o];for(let t=0,o=s.length,c=o-1;t<o;c=t++)(i=s[t])[1]>(r=e)[1]!=(a=s[c])[1]>r[1]&&r[0]<(a[0]-i[0])*(r[1]-i[1])/(a[1]-i[1])+i[0]&&(n=!n)}var r,i,a;return n}var _t=(e,t,n)=>{let r=e=>e*e,i=(e,t)=>r(e.x-t.x)+r(e.y-t.y);return Math.sqrt(((e,t,n)=>{let r=i(t,n);if(r===0)return i(e,t);let a=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/r;return a=Math.max(0,Math.min(1,a)),i(e,{x:t.x+a*(n.x-t.x),y:t.y+a*(n.y-t.y)})})(e,t,n))},vt=class extends O{constructor(e,t,n){super(e),this.config=void 0,this.createClickBoundingBox=void 0,this.pixelDistance=void 0,this.config=e,this.createClickBoundingBox=t,this.pixelDistance=n}find(e,t){let n,r,i,a=1/0,o=1/0,s=this.createClickBoundingBox.create(e),c=this.store.search(s);for(let s=0;s<c.length;s++){let u=c[s],d=u.geometry;if(d.type===`Point`){if(u.properties.selectionPoint||u.properties.coordinatePoint||!t&&u.properties[l.MID_POINT])continue;let r=this.pixelDistance.measure(e,d.coordinates);!u.properties[l.MID_POINT]&&r<this.pointerDistance&&r<a&&(a=r,n=u)}else if(d.type===`LineString`){if(n)continue;for(let t=0;t<d.coordinates.length-1;t++){let n=d.coordinates[t],i=d.coordinates[t+1],a=_t({x:e.containerX,y:e.containerY},this.project(n[0],n[1]),this.project(i[0],i[1]));a<this.pointerDistance&&a<o&&(o=a,r=u)}}else if(d.type===`Polygon`){if(n||r)continue;gt([e.lng,e.lat],d.coordinates)&&(i=u)}}return{clickedFeature:n||r||i}}},yt=class extends O{constructor(e,t,n,r,i,a,o){super(e),this.config=void 0,this.featuresAtCursorEvent=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.draggedFeatureId=null,this.dragPosition=void 0,this.config=e,this.featuresAtCursorEvent=t,this.selectionPoints=n,this.midPoints=r,this.coordinatePoints=i,this.readFeature=a,this.mutateFeature=o}startDragging(e,t){this.draggedFeatureId=t,this.dragPosition=[e.lng,e.lat]}stopDragging(){this.draggedFeatureId=null,this.dragPosition=void 0}isDragging(){return this.draggedFeatureId!==null}canDrag(e,t){let{clickedFeature:n}=this.featuresAtCursorEvent.find(e,!0);return!(!n||n.id!==t)}drag(e){if(!this.draggedFeatureId)return;let t=this.readFeature.getGeometry(this.draggedFeatureId),n=[e.lng,e.lat];if(t.type===`Polygon`||t.type===`LineString`){let r,i;if(t.type===`Polygon`?(r=t.coordinates[0],i=r.length-1):(r=t.coordinates,i=r.length),!this.dragPosition)return!1;for(let e=0;e<i;e++){let t=r[e],i,a;if(this.config.projection===`web-mercator`){let e=E(this.dragPosition[0],this.dragPosition[1]),r=E(n[0],n[1]),o=E(t[0],t[1]),s={x:e.x-r.x,y:e.y-r.y},{lng:c,lat:l}=D(o.x-s.x,o.y-s.y);i=c,a=l}else{let e=[this.dragPosition[0]-n[0],this.dragPosition[1]-n[1]];i=t[0]-e[0],a=t[1]-e[1]}if(i=w(i,this.config.coordinatePrecision),a=w(a,this.config.coordinatePrecision),i>180||i<-180||a>90||a<-90)return!1;r[e]=[i,a]}t.type===`Polygon`&&(r[r.length-1]=[r[0][0],r[0][1]]);let a=this.draggedFeatureId,o=null;if(t.type===`Polygon`)o=this.mutateFeature.updatePolygon({featureId:a,coordinateMutations:{type:M,coordinates:[r]},context:{updateType:s.Provisional}});else{if(t.type!==`LineString`)return;o=this.mutateFeature.updateLineString({featureId:a,coordinateMutations:{type:M,coordinates:r},context:{updateType:s.Provisional}})}if(!o)return!1;let c=o.geometry.coordinates;this.midPoints.updateAllInPlace({featureCoordinates:c}),this.selectionPoints.updateAllInPlace({featureCoordinates:c}),this.coordinatePoints.updateAllInPlace({featureId:a,featureCoordinates:c}),this.dragPosition=[e.lng,e.lat]}else t.type===`Point`&&(this.mutateFeature.updatePoint({featureId:this.draggedFeatureId,coordinateMutations:{type:M,coordinates:n},context:{updateType:s.Provisional}}),this.dragPosition=[e.lng,e.lat])}},bt=class extends O{constructor(e,t,n,r,i,a,o,s,c){super(e),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.coordinateSnapping=void 0,this.lineSnapping=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.draggedCoordinate={id:null,index:-1},this.config=e,this.pixelDistance=t,this.selectionPoints=n,this.midPoints=r,this.coordinatePoints=i,this.coordinateSnapping=a,this.lineSnapping=o,this.readFeature=s,this.mutateFeature=c}getClosestCoordinate(e,t){let n={dist:1/0,index:-1,isFirstOrLastPolygonCoord:!1},r;if(t.type===`LineString`)r=t.coordinates;else{if(t.type!==`Polygon`)return n;r=t.coordinates[0]}for(let i=0;i<r.length;i++){let a=this.pixelDistance.measure(e,r[i]);if(a<this.pointerDistance&&a<n.dist){let e=t.type===`Polygon`&&(i===r.length-1||i===0);n.dist=a,n.index=e?0:i,n.isFirstOrLastPolygonCoord=e}}return n}getDraggable(e,t){let n=this.readFeature.getGeometry(t);return this.getClosestCoordinate(e,n)}getDraggableIndex(e,t){let n=this.readFeature.getGeometry(t),r=this.getClosestCoordinate(e,n);return r.index===-1?-1:r.index}snapCoordinate(e,t,n){let r=[e.lng,e.lat],i=e=>!!(e.properties&&e.properties.mode===n.properties.mode&&e.id!==this.draggedCoordinate.id);if(t!=null&&t.toLine){let t;t=this.lineSnapping.getSnappable(e,i).coordinate,t&&(r=t)}if(t.toCoordinate){let t;t=this.coordinateSnapping.getSnappable(e,i).coordinate,t&&(r=t)}if(t!=null&&t.toCustom){let i;i=t.toCustom(e,{currentCoordinate:this.draggedCoordinate.index,currentId:n.id,getCurrentGeometrySnapshot:n.id?()=>this.readFeature.getGeometry(n.id):()=>null,project:this.project,unproject:this.unproject}),i&&(r=i)}return r}drag(e,t,n){let r=this.draggedCoordinate.id;if(r===null)return!1;let i=this.draggedCoordinate.index,a=this.readFeature.getGeometry(r),o=this.readFeature.getProperties(r),c=a.type===`LineString`?a.coordinates:a.coordinates[0],l=a.type===`Polygon`&&(i===c.length-1||i===0),u=this.snapCoordinate(e,n,{type:`Feature`,id:r,geometry:a,properties:o});if(e.lng>180||e.lng<-180||e.lat>90||e.lat<-90)return!1;if(l){let e=c.length-1;c[0]=u,c[e]=u}else c[i]=u;if(a.type!==`Point`&&!t&&ae({type:`Feature`,geometry:a,properties:{}}))return!1;let d=r,f=null;return a.type===`Polygon`?f=this.mutateFeature.updatePolygon({featureId:d,coordinateMutations:{type:M,coordinates:[c]},context:{updateType:s.Provisional}}):a.type===`LineString`&&(f=this.mutateFeature.updateLineString({featureId:d,coordinateMutations:{type:M,coordinates:c},context:{updateType:s.Provisional}})),!!f&&(this.midPoints.updateOneAtIndex(i>0?i-1:-1,c),this.midPoints.updateOneAtIndex(i,c),this.selectionPoints.updateOneAtIndex(i,u),this.coordinatePoints.updateOneAtIndex(d,i,u),!0)}isDragging(){return this.draggedCoordinate.id!==null}startDragging(e,t){this.draggedCoordinate={id:e,index:t}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}};function xt(e){let t=0,n=0,r=0;return(e.geometry.type===`Polygon`?e.geometry.coordinates[0].slice(0,-1):e.geometry.coordinates).forEach(e=>{t+=e[0],n+=e[1],r++},!0),[t/r,n/r]}var St=(e,t)=>{if(t===0||t===360||t===-360)return e;let n=.017453292519943295*t,r=(e.geometry.type===`Polygon`?e.geometry.coordinates[0]:e.geometry.coordinates).map(([e,t])=>E(e,t)),i=r.reduce((e,t)=>({x:e.x+t.x,y:e.y+t.y}),{x:0,y:0});i.x/=r.length,i.y/=r.length;let a=r.map(e=>({x:i.x+(e.x-i.x)*Math.cos(n)-(e.y-i.y)*Math.sin(n),y:i.y+(e.x-i.x)*Math.sin(n)+(e.y-i.y)*Math.cos(n)})).map(({x:e,y:t})=>[D(e,t).lng,D(e,t).lat]);return e.geometry.type===`Polygon`?e.geometry.coordinates[0]=a:e.geometry.coordinates=a,e};function Ct(e){let t=(e.geometry.type===`Polygon`?e.geometry.coordinates[0]:e.geometry.coordinates).map(e=>{let{x:t,y:n}=E(e[0],e[1]);return[t,n]});return e.geometry.type===`Polygon`?function(e){let t=0,n=0,r=0,i=e.length;for(let a=0;a<i-1;a++){let[i,o]=e[a],[s,c]=e[a+1],l=i*c-s*o;t+=l,n+=(i+s)*l,r+=(o+c)*l}return t/=2,n/=6*t,r/=6*t,{x:n,y:r}}(t):function(e){let t=e.length,n=0,r=0;for(let i=0;i<t;i++){let[t,a]=e[i];n+=t,r+=a}return{x:n/t,y:r/t}}(t)}var wt=class extends O{constructor(e,t,n,r,i,a){super(e),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.readFeature=void 0,this.mutateFeature=void 0,this.lastBearing=void 0,this.selectedGeometry=void 0,this.selectedGeometryCentroid=void 0,this.selectedGeometryWebMercatorCentroid=void 0,this.config=e,this.selectionPoints=t,this.midPoints=n,this.coordinatePoints=r,this.readFeature=i,this.mutateFeature=a}reset(){this.lastBearing=void 0,this.selectedGeometry=void 0,this.selectedGeometryWebMercatorCentroid=void 0,this.selectedGeometryCentroid=void 0}rotate(e,t){this.selectedGeometry||=this.readFeature.getGeometry(t);let n=this.selectedGeometry;if(n.type!==`Polygon`&&n.type!==`LineString`)return;let r=[e.lng,e.lat],i,a={type:`Feature`,geometry:n,properties:{}};if(this.config.projection===`web-mercator`){this.selectedGeometryWebMercatorCentroid||=Ct(a);let t=E(e.lng,e.lat);if(i=L(this.selectedGeometryWebMercatorCentroid,t),i===0)return;if(!this.lastBearing)return void(this.lastBearing=i);St(a,-(this.lastBearing-i))}else{if(this.config.projection!==`globe`)throw Error(`Unsupported projection`);if(this.selectedGeometryCentroid||=xt({type:`Feature`,geometry:n,properties:{}}),i=lt(this.selectedGeometryCentroid,r),!this.lastBearing)return void(this.lastBearing=i+180);(function(e,t){if(t===0||t===360||t===-360)return e;let n=xt(e);(e.geometry.type===`Polygon`?e.geometry.coordinates[0]:e.geometry.coordinates).forEach(e=>{let r=lt(n,e)+t,i=ut(n,function(e,t){e[0]+=e[0]-t[0]>180?-360:t[0]-e[0]>180?360:0;let n=x,r=t[1]*Math.PI/180,i=e[1]*Math.PI/180,a=i-r,o=Math.abs(e[0]-t[0])*Math.PI/180;o>Math.PI&&(o-=2*Math.PI);let s=Math.log(Math.tan(i/2+Math.PI/4)/Math.tan(r/2+Math.PI/4)),c=Math.abs(s)>1e-11?a/s:Math.cos(r);return Math.sqrt(a*a+c*c*o*o)*n}(n,e),r);e[0]=i[0],e[1]=i[1]})})(a,-(this.lastBearing-(i+180)))}let o=n.type===`Polygon`?n.coordinates[0]:n.coordinates;o.forEach(e=>{e[0]=w(e[0],this.coordinatePrecision),e[1]=w(e[1],this.coordinatePrecision)});let c={featureId:t,coordinateMutations:{type:M,coordinates:n.type===`Polygon`?[o]:o},context:{updateType:s.Provisional}},l=null;if(a.geometry.type===`Polygon`)l=this.mutateFeature.updatePolygon(c);else{if(a.geometry.type!==`LineString`)return;l=this.mutateFeature.updateLineString(c)}if(!l)return!1;let u=l.geometry.coordinates;this.midPoints.updateAllInPlace({featureCoordinates:u}),this.selectionPoints.updateAllInPlace({featureCoordinates:u}),this.coordinatePoints.updateAllInPlace({featureId:t,featureCoordinates:u}),this.projection===`web-mercator`?this.lastBearing=i:this.projection===`globe`&&(this.lastBearing=i+180)}},Tt=class extends O{constructor(e,t){super(e),this.config=void 0,this.dragCoordinateResizeBehavior=void 0,this.config=e,this.dragCoordinateResizeBehavior=t}scale(e,t){if(!this.dragCoordinateResizeBehavior.isDragging()){let n=this.dragCoordinateResizeBehavior.getDraggableIndex(e,t);this.dragCoordinateResizeBehavior.startDragging(t,n)}this.dragCoordinateResizeBehavior.drag(e,`center-fixed`)}reset(){this.dragCoordinateResizeBehavior.stopDragging()}};function Et({coordinates:e,originX:t,originY:n,xScale:r,yScale:i}){r===1&&i===1||e.forEach(e=>{let{x:a,y:o}=E(e[0],e[1]),{lng:s,lat:c}=D(t+(a-t)*r,n+(o-n)*i);e[0]=s,e[1]=c})}var Dt=class extends O{constructor(e,t,n,r,i,a,o){super(e),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.coordinatePoints=void 0,this.readFeature=void 0,this.mutateFeature=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=e,this.pixelDistance=t,this.selectionPoints=n,this.midPoints=r,this.coordinatePoints=i,this.readFeature=a,this.mutateFeature=o}getClosestCoordinate(e,t){let n={dist:1/0,index:-1,isFirstOrLastPolygonCoord:!1},r;if(t.type===`LineString`)r=t.coordinates;else{if(t.type!==`Polygon`)return n;r=t.coordinates[0]}for(let i=0;i<r.length;i++){let a=this.pixelDistance.measure(e,r[i]);if(a<this.pointerDistance&&a<n.dist){let e=t.type===`Polygon`&&(i===r.length-1||i===0);n.dist=a,n.index=e?0:i,n.isFirstOrLastPolygonCoord=e}}return n}isValidDragWebMercator(e,t,n){switch(e){case 0:if(t<=0||n>=0)return!1;break;case 1:if(n>=0)return!1;break;case 2:if(t>=0||n>=0)return!1;break;case 3:if(t>=0)return!1;break;case 4:if(t>=0||n<=0)return!1;break;case 5:if(n<=0)return!1;break;case 6:if(t<=0||n<=0)return!1;break;case 7:if(t<=0)return!1}return!0}getSelectedFeatureDataWebMercator(){if(!this.draggedCoordinate.id||this.draggedCoordinate.index===-1)return null;let e=this.getFeature(this.draggedCoordinate.id);if(!e)return null;let t=this.getNormalisedCoordinates(e.geometry);return{boundingBox:this.getBBoxWebMercator(t),feature:e,updatedCoords:t,selectedCoordinate:t[this.draggedCoordinate.index]}}centerWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{feature:n,boundingBox:r,updatedCoords:i,selectedCoordinate:a}=t,o=Ct(n);if(!o)return null;let s=E(a[0],a[1]),{closestBBoxIndex:c}=this.getIndexesWebMercator(r,s),l=E(e.lng,e.lat);return this.scaleWebMercator({closestBBoxIndex:c,updatedCoords:i,webMercatorCursor:l,webMercatorSelected:s,webMercatorOrigin:o}),i}centerFixedWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{feature:n,boundingBox:r,updatedCoords:i,selectedCoordinate:a}=t,o=Ct(n);if(!o)return null;let s=E(a[0],a[1]),{closestBBoxIndex:c}=this.getIndexesWebMercator(r,s),l=E(e.lng,e.lat);return this.scaleFixedWebMercator({closestBBoxIndex:c,updatedCoords:i,webMercatorCursor:l,webMercatorSelected:s,webMercatorOrigin:o}),i}scaleFixedWebMercator({closestBBoxIndex:e,webMercatorOrigin:t,webMercatorSelected:n,webMercatorCursor:r,updatedCoords:i}){if(!this.isValidDragWebMercator(e,t.x-r.x,t.y-r.y))return null;let a=P(t,r)/P(t,n);return a<0&&(a=this.minimumScale),Et({coordinates:i,originX:t.x,originY:t.y,xScale:a,yScale:a}),i}oppositeFixedWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{boundingBox:n,updatedCoords:r,selectedCoordinate:i}=t,a=E(i[0],i[1]),{oppositeBboxIndex:o,closestBBoxIndex:s}=this.getIndexesWebMercator(n,a),c={x:n[o][0],y:n[o][1]},l=E(e.lng,e.lat);return this.scaleFixedWebMercator({closestBBoxIndex:s,updatedCoords:r,webMercatorCursor:l,webMercatorSelected:a,webMercatorOrigin:c}),r}oppositeWebMercatorDrag(e){let t=this.getSelectedFeatureDataWebMercator();if(!t)return null;let{boundingBox:n,updatedCoords:r,selectedCoordinate:i}=t,a=E(i[0],i[1]),{oppositeBboxIndex:o,closestBBoxIndex:s}=this.getIndexesWebMercator(n,a),c={x:n[o][0],y:n[o][1]},l=E(e.lng,e.lat);return this.scaleWebMercator({closestBBoxIndex:s,updatedCoords:r,webMercatorCursor:l,webMercatorSelected:a,webMercatorOrigin:c}),r}scaleWebMercator({closestBBoxIndex:e,webMercatorOrigin:t,webMercatorSelected:n,webMercatorCursor:r,updatedCoords:i}){let a=t.x-r.x,o=t.y-r.y;if(!this.isValidDragWebMercator(e,a,o))return null;let s=1;a!==0&&e!==1&&e!==5&&(s=1-(t.x-n.x-a)/a);let c=1;return o!==0&&e!==3&&e!==7&&(c=1-(t.y-n.y-o)/o),this.validateScale(s,c)?(s<0&&(s=this.minimumScale),c<0&&(c=this.minimumScale),this.performWebMercatorScale(i,t.x,t.y,s,c),i):null}getFeature(e){if(this.draggedCoordinate.id===null)return null;let t=this.readFeature.getGeometry(e);return t.type!==`Polygon`&&t.type!==`LineString`?null:{id:e,type:`Feature`,geometry:t,properties:{}}}getNormalisedCoordinates(e){return e.type===`Polygon`?e.coordinates[0]:e.coordinates}validateScale(e,t){return!isNaN(e)&&t<2**53-1&&!isNaN(t)&&t<2**53-1}performWebMercatorScale(e,t,n,r,i){e.forEach(e=>{let{x:a,y:o}=E(e[0],e[1]),{lng:s,lat:c}=D(t+(a-t)*r,n+(o-n)*i);e[0]=s,e[1]=c})}getBBoxWebMercator(e){let t=[1/0,1/0,-1/0,-1/0];(e=e.map(e=>{let{x:t,y:n}=E(e[0],e[1]);return[t,n]})).forEach(([e,n])=>{e<t[0]&&(t[0]=e),n<t[1]&&(t[1]=n),e>t[2]&&(t[2]=e),n>t[3]&&(t[3]=n)});let[n,r,i,a]=t;return[[n,a],[(n+i)/2,a],[i,a],[i,a+(r-a)/2],[i,r],[(n+i)/2,r],[n,r],[n,a+(r-a)/2]]}getIndexesWebMercator(e,t){let n,r=1/0;for(let i=0;i<e.length;i++){let a=P({x:t.x,y:t.y},{x:e[i][0],y:e[i][1]});a<r&&(n=i,r=a)}if(n===void 0)throw Error(`No closest coordinate found`);return{oppositeBboxIndex:this.boundingBoxMaps.opposite[n],closestBBoxIndex:n}}isDragging(){return this.draggedCoordinate.id!==null}startDragging(e,t){this.draggedCoordinate={id:e,index:t}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}getDraggableIndex(e,t){let n=this.readFeature.getGeometry(t),r=this.getClosestCoordinate(e,n);return r.index===-1?-1:r.index}drag(e,t){if(!this.draggedCoordinate.id)return!1;let n=this.getFeature(this.draggedCoordinate.id);if(!n)return!1;let r=null;if(t===`center`?r=this.centerWebMercatorDrag(e):t===`opposite`?r=this.oppositeWebMercatorDrag(e):t===`center-fixed`?r=this.centerFixedWebMercatorDrag(e):t===`opposite-fixed`&&(r=this.oppositeFixedWebMercatorDrag(e)),!r)return!1;for(let e=0;e<r.length;e++){let t=r[e];if(t[0]=w(t[0],this.coordinatePrecision),t[1]=w(t[1],this.coordinatePrecision),!se(t,this.coordinatePrecision))return!1}let i=n.id,a=null;if(n.geometry.type===`Polygon`?a=this.mutateFeature.updatePolygon({featureId:i,coordinateMutations:{type:M,coordinates:[r]},context:{updateType:s.Provisional}}):n.geometry.type===`LineString`&&(a=this.mutateFeature.updateLineString({featureId:i,coordinateMutations:{type:M,coordinates:r},context:{updateType:s.Provisional}})),!a)return!1;let o=a.geometry.coordinates;return this.midPoints.updateAllInPlace({featureCoordinates:o}),this.selectionPoints.updateAllInPlace({featureCoordinates:o}),this.coordinatePoints.updateAllInPlace({featureId:i,featureCoordinates:o}),!0}},Ot={deselect:`Escape`,delete:`Delete`,rotate:[`Control`,`r`],scale:[`Control`,`s`]},kt={pointerOver:`move`,dragStart:`move`,dragEnd:`move`,insertMidpoint:`crosshair`},At=class extends y{getPointerOverFeatureCursor(){return this.cursors.pointerOverFeature??this.cursors.pointerOver}getPointerOverCoordinateCursor(){return this.cursors.pointerOverCoordinate??this.cursors.pointerOver}getPointerOverResizeHandleCursor(){return this.cursors.pointerOverResizeHandle??this.cursors.pointerOver}constructor(e){super(e,!0),this.mode=`select`,this.allowManualDeselection=!0,this.allowManualSelection=!0,this.dragEventThrottle=5,this.dragEventCount=0,this.selected=[],this.flags={},this.keyEvents=Ot,this.cursors=kt,this.validations={},this.dragTarget={type:`none`},this.selectionPoints=void 0,this.midPoints=void 0,this.coordinateSnap=void 0,this.featuresAtMouseEvent=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.dragFeature=void 0,this.dragCoordinate=void 0,this.rotateFeature=void 0,this.scaleFeature=void 0,this.dragCoordinateResizeFeature=void 0,this.coordinatePoints=void 0,this.lineSnap=void 0,this.mutateFeature=void 0,this.readFeature=void 0,this.updateOptions(e)}updateOptions(e){if(super.updateOptions(e),this.cursors=e&&e.cursors?n({},this.cursors,e.cursors):kt,e?.keyEvents===null?this.keyEvents={deselect:null,delete:null,rotate:null,scale:null}:e!=null&&e.keyEvents&&(this.keyEvents=n({},this.keyEvents,e.keyEvents)),e?.dragEventThrottle!==void 0&&(this.dragEventThrottle=e.dragEventThrottle),e?.allowManualDeselection!==void 0&&(this.allowManualDeselection=e.allowManualDeselection),e?.allowManualSelection!==void 0&&(this.allowManualSelection=e.allowManualSelection),e!=null&&e.flags){this.flags=n({},this.flags,e.flags),this.validations={};for(let e in this.flags){let t=this.flags[e].feature;t&&t.validation&&(this.validations[e]=t.validation)}}}selectFeature(e){this.select(e,!1)}setSelecting(){if(this._state!==`started`)throw Error(`Mode must be started to move to selecting state`);this._state=`selecting`}registerBehaviors(e){this.readFeature=new F(e),this.mutateFeature=new N(e,{validate:(e,t)=>{let n=e.properties.mode;return this.validations&&this.validations[n]?this.validations[n](e,t):{valid:!0}}}),this.pixelDistance=new I(e),this.clickBoundingBox=new Ee(e),this.featuresAtMouseEvent=new vt(e,this.clickBoundingBox,this.pixelDistance),this.selectionPoints=new ht(e,this.mutateFeature),this.coordinatePoints=new Ge(e,this.readFeature,this.mutateFeature),this.midPoints=new mt(e,this.selectionPoints,this.coordinatePoints,this.mutateFeature,this.readFeature,this.pixelDistance),this.coordinateSnap=new De(e,this.pixelDistance,this.clickBoundingBox),this.lineSnap=new Be(e,this.pixelDistance,this.clickBoundingBox),this.rotateFeature=new wt(e,this.selectionPoints,this.midPoints,this.coordinatePoints,this.readFeature,this.mutateFeature),this.dragFeature=new yt(e,this.featuresAtMouseEvent,this.selectionPoints,this.midPoints,this.coordinatePoints,this.readFeature,this.mutateFeature),this.dragCoordinate=new bt(e,this.pixelDistance,this.selectionPoints,this.midPoints,this.coordinatePoints,this.coordinateSnap,this.lineSnap,this.readFeature,this.mutateFeature),this.dragCoordinateResizeFeature=new Dt(e,this.pixelDistance,this.selectionPoints,this.midPoints,this.coordinatePoints,this.readFeature,this.mutateFeature),this.scaleFeature=new Tt(e,this.dragCoordinateResizeFeature)}deselectFeature(e){this.deselect(e)}deselect(e){this.selected.includes(e)&&(this.mutateFeature.setDeselected(this.selected),this.onDeselect(this.selected[0]),this.selected=[],this.selectionPoints.delete(),this.midPoints.delete(),this.dragTarget={type:`none`})}deleteSelected(){this.selected.length&&this.mutateFeature.deleteFeaturesIfPresent(this.selected),this.selected=[],this.dragTarget={type:`none`}}clearDragTargetAndCursor(){this.dragTarget={type:`none`},this.setCursor(`unset`)}getSelectedFlags(e){let t=this.readFeature.getProperties(e),n=this.flags[t.mode]?.feature,r=n?.coordinates;return{featureFlags:n,coordinatesFlags:r,hasDraggableFlags:n&&(n.draggable||r?.draggable||r?.resizable||typeof r?.midpoints==`object`&&r.midpoints.draggable)}}onRightClick(e){if(!this.selectionPoints.ids.length)return;let t,n=1/0;if(this.selectionPoints.ids.forEach(r=>{let i=this.readFeature.getGeometry(r),a=this.pixelDistance.measure(e,i.coordinates);a<this.pointerDistance&&a<n&&(n=a,t=this.readFeature.getProperties(r))}),!t)return;let r=t.selectionPointFeatureId,i=t.index,o=this.readFeature.getProperties(r),c=this.flags[o.mode];if(!(c&&c.feature&&c.feature.coordinates&&c.feature.coordinates.deletable))return;let l=this.readFeature.getGeometry(r),u;if(l.type===`Polygon`){if(u=l.coordinates[0],u.length<=4)return}else if(l.type!==`LineString`||(u=l.coordinates,u.length<=2))return;l.type!==`Polygon`||i!==0&&i!==u.length-1?u.splice(i,1):(u.shift(),u.pop(),u.push([u[0][0],u[0][1]]));let d=null;if(l.type===`Polygon`?d=this.mutateFeature.updatePolygon({featureId:r,coordinateMutations:{type:M,coordinates:[u]},context:{updateType:s.Commit}}):l.type===`LineString`&&(d=this.mutateFeature.updateLineString({featureId:r,coordinateMutations:{type:M,coordinates:u},context:{updateType:s.Commit}})),!d)return;let f=d.geometry.coordinates;this.mutateFeature.deleteFeaturesIfPresent([...this.midPoints.ids,...this.selectionPoints.ids]),o.coordinatePointIds&&this.coordinatePoints.createOrUpdate({featureId:r,featureCoordinates:f}),this.selectionPoints.create({featureCoordinates:f,featureId:r}),c&&c.feature&&c.feature.coordinates&&c.feature.coordinates.midpoints&&this.midPoints.create({featureCoordinates:f,featureId:r}),this.onFinish(r,{action:a,mode:this.mode})}select(e,t=!0){if(this.selected[0]===e)return;let{mode:n}=this.readFeature.getProperties(e),r=this.flags[n];if(!r||!r.feature)return;let i=this.selected[0];if(i){if(i===e)return;this.deselect(i)}t&&this.setCursor(this.getPointerOverFeatureCursor()),this.selected=[e],this.mutateFeature.setSelected(e),this.onSelect(e);let{type:a,coordinates:o}=this.readFeature.getGeometry(e);a!==`LineString`&&a!==`Polygon`||o&&r&&r.feature.coordinates&&(this.selectionPoints.create({featureCoordinates:o,featureId:e}),r.feature.coordinates.midpoints&&this.midPoints.create({featureCoordinates:o,featureId:e}))}onLeftClick(e){let{clickedFeature:t}=this.featuresAtMouseEvent.find(e,this.selected.length>0),n=this.midPoints.getNearestMidPoint(e),r=this.selected[0];if(r){var i;let{featureFlags:t}=this.getSelectedFlags(r);if(t!=null&&(i=t.coordinates)!=null&&i.midpoints&&n){if(t.coordinates.draggable){let t=this.pixelDistance.measure(e,this.readFeature.getGeometry(n).coordinates),{dist:i}=this.dragCoordinate.getDraggable(e,r);if(i!==void 0&&t>i)return}this.midPoints.insert({featureId:r,midPointId:n}),this.onFinish(this.selected[0],{action:o,mode:this.mode});return}}if(t!=null&&t.id)this.allowManualSelection&&this.select(t.id,!0);else if(this.selected.length&&this.allowManualDeselection)return void this.deselect(this.selected[0])}start(){this.setStarted(),this.setSelecting()}stop(){this.cleanUp(),this.setStarted(),this.setStopped()}onClick(e){e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e)?this.onRightClick(e):e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)&&this.onLeftClick(e)}canScale(e){return this.keyEvents.scale&&this.keyEvents.scale.every(t=>e.heldKeys.includes(t))}canRotate(e){return this.keyEvents.rotate&&this.keyEvents.rotate.every(t=>e.heldKeys.includes(t))}preventDefaultKeyEvent(e){let t=this.canRotate(e),n=this.canScale(e);(t||n)&&e.preventDefault()}onKeyDown(e){this.preventDefaultKeyEvent(e)}onKeyUp(e){if(this.preventDefaultKeyEvent(e),this.keyEvents.delete&&e.key===this.keyEvents.delete){if(!this.selected.length)return;let e=this.selected[0];this.onDeselect(this.selected[0]),this.coordinatePoints.deletePointsByFeatureIds([e]),this.deleteSelected(),this.selectionPoints.delete(),this.midPoints.delete()}else this.keyEvents.deselect&&e.key===this.keyEvents.deselect&&this.cleanUp()}cleanUp(){this.selected.length&&this.deselect(this.selected[0])}onDragStart(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragStart,e))return;let n=this.selected[0];if(!n)return;let{featureFlags:r,coordinatesFlags:i,hasDraggableFlags:a}=this.getSelectedFlags(n);if(!a)return;this.dragEventCount=0;let s=this.dragTarget.type!==`none`&&this.dragTarget.featureId===n?this.dragTarget:{type:`none`},c=s.type===`coordinate`?s.coordinateIndex:this.dragCoordinate.getDraggableIndex(e,n),l=s.type===`resize`?s.coordinateIndex:this.dragCoordinateResizeFeature.getDraggableIndex(e,n),u=i?.resizable&&l!==-1,d=i?.draggable&&c!==-1,f=i&&typeof i.midpoints==`object`&&i.midpoints.draggable,p=r?.draggable&&(s.type===`feature`||this.dragFeature.canDrag(e,n));if(u)return this.setCursor(this.cursors.dragStart),this.dragCoordinateResizeFeature.startDragging(n,l),void t(!1);if(d)return this.setCursor(this.cursors.dragStart),this.dragCoordinate.startDragging(n,c),void t(!1);if(f){let r=s.type===`midpoint`?s.midPointId:this.midPoints.getNearestMidPoint(e);if(this.selected.length&&r){this.midPoints.insert({featureId:n,midPointId:r}),this.onFinish(this.selected[0],{action:o,mode:this.mode});let i=this.dragCoordinate.getDraggableIndex(e,n);this.dragCoordinate.startDragging(n,i),t(!1);return}}if(p)return this.setCursor(this.cursors.dragStart),this.dragFeature.startDragging(e,n),void t(!1);this.setCursor(`unset`)}onDrag(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDrag,e))return;let n=this.selected[0];if(!n)return;let r=this.readFeature.getProperties(n),i=this.flags[r.mode],a=!0===(i&&i.feature&&i.feature.selfIntersectable);if(this.dragEventCount++,this.dragEventCount%this.dragEventThrottle!=0){if(i&&i.feature&&i.feature.rotateable&&this.canRotate(e))return t(!1),void this.rotateFeature.rotate(e,n);if(i&&i.feature&&i.feature.scaleable&&this.canScale(e))return t(!1),void this.scaleFeature.scale(e,n);if(this.dragCoordinateResizeFeature.isDragging()&&i.feature&&i.feature.coordinates&&i.feature.coordinates.resizable){if(this.projection===`globe`)throw Error(`Globe is currently unsupported projection for resizable`);t(!1),this.dragCoordinateResizeFeature.drag(e,i.feature.coordinates.resizable);return}if(this.dragCoordinate.isDragging()){var o;let t=(o=i.feature)==null||(o=o.coordinates)==null?void 0:o.snappable,n={toCoordinate:!1};!0===t?n={toCoordinate:!0}:typeof t==`object`&&(n=t),this.dragCoordinate.drag(e,a,n);return}this.dragFeature.isDragging()?this.dragFeature.drag(e):t(!0)}}onDragEnd(e,t){this.allowPointerEvent(this.pointerEvents.onDragEnd,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(),t(!0))}onMouseMove(e){let t=this.selected[0];if(!t)return void this.clearDragTargetAndCursor();if(this.dragFeature.isDragging()||this.dragCoordinate.isDragging()||this.dragCoordinateResizeFeature.isDragging())return;let{featureFlags:n}=this.getSelectedFlags(t);if(!n)return void this.clearDragTargetAndCursor();let r,i=n.coordinates;if(i!=null&&i.midpoints&&(r=this.midPoints.getNearestMidPoint(e),r&&(this.dragTarget={type:`midpoint`,featureId:t,midPointId:r},this.setCursor(this.cursors.insertMidpoint))),i&&i.draggable){let{index:n,dist:i}=this.dragCoordinate.getDraggable(e,t);if(n>-1){if(r&&this.pixelDistance.measure(e,this.readFeature.getGeometry(r).coordinates)<i)return;this.dragTarget={type:`coordinate`,featureId:t,coordinateIndex:n},this.setCursor(this.getPointerOverCoordinateCursor());return}}if(i&&i.resizable){let n=this.dragCoordinateResizeFeature.getDraggableIndex(e,t);if(n>-1)return this.dragTarget={type:`resize`,featureId:t,coordinateIndex:n},void this.setCursor(this.getPointerOverResizeHandleCursor())}if(n.draggable&&this.dragFeature.canDrag(e,t)){if(r)return;this.dragTarget={type:`feature`,featureId:t},this.setCursor(this.getPointerOverFeatureCursor());return}r||this.clearDragTargetAndCursor()}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});if(e.properties.mode===this.mode&&e.geometry.type===`Point`){if(e.properties[l.SELECTION_POINT])return t.pointColor=this.getHexColorStylingValue(this.styles.selectionPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.selectionPointOpacity,1,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectionPointOutlineColor,t.pointOutlineColor,e),t.pointWidth=this.getNumericStylingValue(this.styles.selectionPointWidth,t.pointWidth,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.selectionPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectionPointOutlineWidth,2,e),t.zIndex=30,t;if(e.properties[l.MID_POINT])return t.pointColor=this.getHexColorStylingValue(this.styles.midPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.midPointOpacity,1,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.midPointOutlineColor,t.pointOutlineColor,e),t.pointWidth=this.getNumericStylingValue(this.styles.midPointWidth,4,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.midPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.midPointOutlineWidth,2,e),t.zIndex=50,t}else if(e.properties[l.SELECTED]){if(e.geometry.type===`Point`&&e.properties[u.MARKER])return t.markerUrl=this.getUrlStylingValue(this.styles.selectedMarkerUrl,c,e),t.markerHeight=this.getNumericStylingValue(this.styles.selectedMarkerHeight,40,e),t.markerWidth=this.getNumericStylingValue(this.styles.selectedMarkerWidth,32,e),t;if(e.geometry.type===`Polygon`)return t.polygonFillColor=this.getHexColorStylingValue(this.styles.selectedPolygonColor,t.polygonFillColor,e),t.polygonOutlineWidth=this.getNumericStylingValue(this.styles.selectedPolygonOutlineWidth,t.polygonOutlineWidth,e),t.polygonOutlineColor=this.getHexColorStylingValue(this.styles.selectedPolygonOutlineColor,t.polygonOutlineColor,e),t.polygonOutlineOpacity=this.getNumericStylingValue(this.styles.selectedPolygonOutlineOpacity,1,e),t.polygonFillOpacity=this.getNumericStylingValue(this.styles.selectedPolygonFillOpacity,t.polygonFillOpacity,e),t.zIndex=d,t;if(e.geometry.type===`LineString`)return t.lineStringColor=this.getHexColorStylingValue(this.styles.selectedLineStringColor,t.lineStringColor,e),t.lineStringWidth=this.getNumericStylingValue(this.styles.selectedLineStringWidth,t.lineStringWidth,e),t.zIndex=d,t;if(e.geometry.type===`Point`)return t.pointWidth=this.getNumericStylingValue(this.styles.selectedPointWidth,t.pointWidth,e),t.pointColor=this.getHexColorStylingValue(this.styles.selectedPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.selectedPointOpacity,1,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectedPointOutlineColor,t.pointOutlineColor,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.selectedPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectedPointOutlineWidth,t.pointOutlineWidth,e),t.zIndex=d,t}return t}afterFeatureUpdated(e){if(this.selected.length&&e.id===this.selected[0]){var t,n;let r=this.flags[e.properties.mode];if(r==null||(t=r.feature)==null||!t.coordinates)return;let i=e.geometry.type,a=e.id;if(this.selectionPoints.delete(),this.midPoints.delete(),i!==`LineString`&&i!==`Polygon`)return;let o=e.geometry.coordinates;this.selectionPoints.create({featureCoordinates:o,featureId:a}),r!=null&&(n=r.feature)!=null&&(n=n.coordinates)!=null&&n.midpoints&&this.midPoints.create({featureCoordinates:o,featureId:a})}}},jt=class extends v{constructor(...e){super(...e),this.type=g.Static,this.mode=`static`}start(){}stop(){}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(){return n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0})}};function Mt(e,t,n,r,i){for(;r>n;){if(r-n>600){let a=r-n+1,o=t-n+1,s=Math.log(a),c=.5*Math.exp(2*s/3),l=.5*Math.sqrt(s*c*(a-c)/a)*(o-a/2<0?-1:1);Mt(e,t,Math.max(n,Math.floor(t-o*c/a+l)),Math.min(r,Math.floor(t+(a-o)*c/a+l)),i)}let a=e[t],o=n,s=r;for(Nt(e,n,t),i(e[r],a)>0&&Nt(e,n,r);o<s;){for(Nt(e,o,s),o++,s--;i(e[o],a)<0;)o++;for(;i(e[s],a)>0;)s--}i(e[n],a)===0?Nt(e,n,s):(s++,Nt(e,s,r)),s<=t&&(n=s+1),t<=s&&(r=s-1)}}function Nt(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function H(e,t){Pt(e,0,e.children.length,t,e)}function Pt(e,t,n,r,i){i||=U([]),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let a=t;a<n;a++){let t=e.children[a];Ft(i,e.leaf?r(t):t)}return i}function Ft(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function It(e,t){return e.minX-t.minX}function Lt(e,t){return e.minY-t.minY}function Rt(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function zt(e){return e.maxX-e.minX+(e.maxY-e.minY)}function Bt(e,t){let n=Math.max(e.minX,t.minX),r=Math.max(e.minY,t.minY),i=Math.min(e.maxX,t.maxX),a=Math.min(e.maxY,t.maxY);return Math.max(0,i-n)*Math.max(0,a-r)}function Vt(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function Ht(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function U(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Ut(e,t,n,r,i){let a=[t,n];for(;a.length;){if((n=a.pop())-(t=a.pop())<=r)continue;let o=t+Math.ceil((n-t)/r/2)*r;Mt(e,o,t,n,i),a.push(t,o,o,n)}}var Wt=class{constructor(e){this._maxEntries=void 0,this._minEntries=void 0,this.data=void 0,this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}search(e){let t=this.data,n=[];if(!Ht(e,t))return n;let r=this.toBBox,i=[];for(;t;){for(let a=0;a<t.children.length;a++){let o=t.children[a],s=t.leaf?r(o):o;Ht(e,s)&&(t.leaf?n.push(o):Vt(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n}collides(e){let t=this.data;if(Ht(e,t)){let n=[];for(;t;){for(let r=0;r<t.children.length;r++){let i=t.children[r],a=t.leaf?this.toBBox(i):i;if(Ht(e,a)){if(t.leaf||Vt(e,a))return!0;n.push(i)}}t=n.pop()}}return!1}load(e){if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){let e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t}insert(e){this._insert(e,this.data.height-1)}clear(){this.data=U([])}remove(e){let t=this.data,n=this.toBBox(e),r=[],i=[],a,o,s=!1;for(;t||r.length;){if(t||(t=r.pop(),o=r[r.length-1],a=i.pop(),s=!0),t.leaf){let n=t.children.indexOf(e);n!==-1&&(t.children.splice(n,1),r.push(t),this._condense(r))}s||t.leaf||!Vt(t,n)?o?(a++,t=o.children[a],s=!1):t=null:(r.push(t),i.push(a),a=0,o=t,t=t.children[0])}}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}_all(e,t){let n=[];for(;e;)e.leaf?t.push(...e.children):n.push(...e.children),e=n.pop();return t}_build(e,t,n,r){let i=n-t+1,a,o=this._maxEntries;if(i<=o)return a=U(e.slice(t,n+1)),H(a,this.toBBox),a;r||(r=Math.ceil(Math.log(i)/Math.log(o)),o=Math.ceil(i/o**(r-1))),a=U([]),a.leaf=!1,a.height=r;let s=Math.ceil(i/o),c=s*Math.ceil(Math.sqrt(o));Ut(e,t,n,c,this.compareMinX);for(let i=t;i<=n;i+=c){let t=Math.min(i+c-1,n);Ut(e,i,t,s,this.compareMinY);for(let n=i;n<=t;n+=s){let i=Math.min(n+s-1,t);a.children.push(this._build(e,n,i,r-1))}}return H(a,this.toBBox),a}_chooseSubtree(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){let n,r=1/0,o=1/0;for(let s=0;s<t.children.length;s++){let c=t.children[s],l=Rt(c),u=(i=e,a=c,(Math.max(a.maxX,i.maxX)-Math.min(a.minX,i.minX))*(Math.max(a.maxY,i.maxY)-Math.min(a.minY,i.minY))-l);u<o?(o=u,r=l<r?l:r,n=c):u===o&&l<r&&(r=l,n=c)}t=n||t.children[0]}var i,a;return t}_insert(e,t,n){let r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),Ft(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)}_split(e,t){let n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);let a=this._chooseSplitIndex(n,i,r),o=U(n.children.splice(a,n.children.length-a));o.height=n.height,o.leaf=n.leaf,H(n,this.toBBox),H(o,this.toBBox),t?e[t-1].children.push(o):this._splitRoot(n,o)}_splitRoot(e,t){this.data=U([e,t]),this.data.height=e.height+1,this.data.leaf=!1,H(this.data,this.toBBox)}_chooseSplitIndex(e,t,n){let r,i=1/0,a=1/0;for(let o=t;o<=n-t;o++){let t=Pt(e,0,o,this.toBBox),s=Pt(e,o,n,this.toBBox),c=Bt(t,s),l=Rt(t)+Rt(s);c<i?(i=c,r=o,a=l<a?l:a):c===i&&l<a&&(a=l,r=o)}return r||n-t}_chooseSplitAxis(e,t,n){let r=e.leaf?this.compareMinX:It,i=e.leaf?this.compareMinY:Lt;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)}_allDistMargin(e,t,n,r){e.children.sort(r);let i=this.toBBox,a=Pt(e,0,t,i),o=Pt(e,n-t,n,i),s=zt(a)+zt(o);for(let r=t;r<n-t;r++){let t=e.children[r];Ft(a,e.leaf?i(t):t),s+=zt(a)}for(let r=n-t-1;r>=t;r--){let t=e.children[r];Ft(o,e.leaf?i(t):t),s+=zt(o)}return s}_adjustParentBBoxes(e,t,n){for(let r=n;r>=0;r--)Ft(t[r],e)}_condense(e){for(let t,n=e.length-1;n>=0;n--)e[n].children.length===0?n>0?(t=e[n-1].children,t.splice(t.indexOf(e[n]),1)):this.clear():H(e[n],this.toBBox)}},Gt=class{constructor(e){this.tree=void 0,this.idToNode=void 0,this.nodeToId=void 0,this.tree=new Wt(e&&e.maxEntries?e.maxEntries:9),this.idToNode=new Map,this.nodeToId=new Map}setMaps(e,t){this.idToNode.set(e.id,t),this.nodeToId.set(t,e.id)}toBBox(e){let t=[],n=[],r;if(e.geometry.type===`Polygon`)r=e.geometry.coordinates[0];else if(e.geometry.type===`LineString`)r=e.geometry.coordinates;else{if(e.geometry.type!==`Point`)throw Error(`Not a valid feature to turn into a bounding box`);r=[e.geometry.coordinates]}for(let e=0;e<r.length;e++)n.push(r[e][1]),t.push(r[e][0]);let i=Math.min(...n),a=Math.max(...n);return{minX:Math.min(...t),minY:i,maxX:Math.max(...t),maxY:a}}insert(e){if(this.idToNode.get(String(e.id)))throw Error(`Feature already exists`);let t=this.toBBox(e);this.setMaps(e,t),this.tree.insert(t)}load(e){let t=[],n=new Set;e.forEach(e=>{let r=this.toBBox(e);if(this.setMaps(e,r),n.has(String(e.id)))throw Error(`Duplicate feature ID found ${e.id}`);n.add(String(e.id)),t.push(r)}),this.tree.load(t)}update(e){this.remove(e.id);let t=this.toBBox(e);this.setMaps(e,t),this.tree.insert(t)}remove(e){let t=this.idToNode.get(e);if(!t)throw Error(`${e} not inserted into the spatial index`);this.tree.remove(t)}clear(){this.tree.clear()}search(e){return this.tree.search(this.toBBox(e)).map(e=>this.nodeToId.get(e))}collides(e){return this.tree.collides(this.toBBox(e))}},Kt={getId:()=>`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=16*Math.random()|0;return(e==`x`?t:3&t|8).toString(16)}),isValidId:e=>typeof e==`string`&&e.length===36},qt={target:`geometry`},Jt={target:`properties`},Yt=class{constructor(e){this.idStrategy=void 0,this.tracked=void 0,this.spatialIndex=void 0,this.store=void 0,this._onChange=()=>{},this.store={},this.spatialIndex=new Gt,this.tracked=!e||!1!==e.tracked,this.idStrategy=e&&e.idStrategy?e.idStrategy:Kt}clone(e){return JSON.parse(JSON.stringify(e))}getId(){return this.idStrategy.getId()}has(e){return!!this.store[e]}load(e,t,n,r){if(e.length===0)return[];let i=this.clone(e),a=[],o=[];i=i.filter(e=>{e.id??=this.idStrategy.getId();let n=e.id;if(t){let r=t(e);if(!r.valid)return a.push({id:n,valid:!1,reason:r.reason}),!1}if(this.tracked){if(e.properties.createdAt){if(!m(e.properties.createdAt))return a.push({id:e.id,valid:!1,reason:`createdAt is not a valid numeric timestamp`}),!1}else e.properties.createdAt=+new Date;if(e.properties.updatedAt){if(!m(e.properties.updatedAt))return a.push({id:e.id,valid:!1,reason:`updatedAt is not a valid numeric timestamp`}),!1}else e.properties.updatedAt=+new Date}return this.has(n)?(a.push({id:n,valid:!1,reason:`Feature already exists with this id: ${n}`}),!1):(this.store[n]=e,o.push(e),a.push({id:n,valid:!0}),!0)}),this.spatialIndex.load(i);let s=o.map(({id:e})=>e);return s.length>0&&(this._onChange(s,`create`,r),n&&o.forEach(e=>{n(e)})),a}search(e,t){let n=this.spatialIndex.search(e).map(e=>this.store[e]);return this.clone(t?n.filter(t):n)}registerOnChange(e){this._onChange=(t,n,r)=>{e(t,n,r)}}getGeometryCopy(e){let t=this.store[e];if(!t)throw Error(`No feature with this id (${e}), can not get geometry copy`);return this.clone(t.geometry)}getPropertiesCopy(e){let t=this.store[e];if(!t)throw Error(`No feature with this id (${e}), can not get properties copy`);return this.clone(t.properties)}updateProperty(e,t){let r=new Set;e.forEach(({id:e,property:t,value:n})=>{let i=this.store[e];if(!i)throw Error(`No feature with this (${e}), can not update geometry`);i.properties[t]!==n&&(r.add(e),n===void 0?delete i.properties[t]:i.properties[t]=n,this.tracked&&(i.properties.updatedAt=+new Date))}),this._onChange&&r.size>0&&this._onChange(Array.from(r),`update`,t?n({},t,Jt):Jt)}updateGeometry(e,t){let r=new Set;e.forEach(({id:e,geometry:t})=>{r.add(e);let n=this.store[e];if(!n)throw Error(`No feature with this (${e}), can not update geometry`);n.geometry=this.clone(t),this.spatialIndex.update(n),this.tracked&&(n.properties.updatedAt=+new Date)}),this._onChange&&r.size>0&&this._onChange(Array.from(r),`update`,t?n({},t,qt):qt)}create(e,t){let r=[];return e.forEach(({geometry:e,properties:t})=>{let i,a=n({},t);this.tracked&&(i=+new Date,t?(a.createdAt=typeof t.createdAt==`number`?t.createdAt:i,a.updatedAt=typeof t.updatedAt==`number`?t.updatedAt:i):a={createdAt:i,updatedAt:i});let o=this.getId(),s={id:o,type:`Feature`,geometry:e,properties:a};this.store[o]=s,this.spatialIndex.insert(s),r.push(o)}),this._onChange&&this._onChange([...r],`create`,t),r}delete(e,t){e.forEach(e=>{if(!this.store[e])throw Error(`No feature with id ${e}, can not delete`);delete this.store[e],this.spatialIndex.remove(e)}),this._onChange&&this._onChange([...e],`delete`,t)}copy(e){return this.clone(this.store[e])}copyAll(){return this.clone(Object.keys(this.store).map(e=>this.store[e]))}copyAllWhere(e){return this.clone(Object.keys(this.store).map(e=>this.store[e]).filter(t=>t.properties&&e(t.properties)))}clear(e){let t=Object.keys(this.store);this.store={},this.spatialIndex.clear(),this._onChange(t,`delete`,e)}size(){return Object.keys(this.store).length}};Math.PI/180;var Xt=`Feature is not a Polygon or LineString`,Zt=`Feature intersects itself`,Qt=e=>e.geometry.type!==`Polygon`&&e.geometry.type!==`LineString`?{valid:!1,reason:Xt}:ae(e)?{valid:!1,reason:Zt}:{valid:!0};function $t(e,t,n){let r=L(e,t),i=L(t,n)-r;return i<0&&(i+=360),180-Math.abs(i-90-90)}var en={cancel:`Escape`,finish:`Enter`},tn={start:`crosshair`,close:`pointer`},nn=class extends v{constructor(e){super(e,!0),this.mode=`angled-rectangle`,this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=en,this.cursors=tn,this.mouseMove=!1,this.mutateFeature=void 0,this.readFeature=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors)),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=n({},this.keyEvents,e.keyEvents))}close(){if(this.currentId===void 0||!this.mutateFeature.updatePolygon({featureId:this.currentId,propertyMutations:{[u.CURRENTLY_DRAWING]:void 0},context:{updateType:s.Finish,action:r}}))return;let e=this.currentId;this.currentCoordinate=0,this.currentId=void 0,this.state===`drawing`&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:r})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onMouseMove(e){if(this.mouseMove=!0,this.setCursor(this.cursors.start),this.currentId===void 0||this.currentCoordinate===0)return;let t=[];if(this.currentCoordinate===1)t=this.getUpdateForSecondCoordinate(e);else{if(this.currentCoordinate!==2)return;t=this.getNewSecondAndThirdCoordinates(e)}this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:t,context:{updateType:s.Provisional}})}getUpdateForSecondCoordinate(e){return[{type:A,index:1,coordinate:[e.lng,e.lat]},{type:A,index:2,coordinate:[e.lng,e.lat]}]}getNewSecondAndThirdCoordinates(e){if(!this.currentId)throw Error(`No current feature being drawn`);let t=this.readFeature.getCoordinate(this.currentId,0),n=this.readFeature.getCoordinate(this.currentId,1),r=dt(t,n,this.coordinatePrecision,this.project,this.unproject),i=E(t[0],t[1]),a=E(r[0],r[1]),o=E(n[0],n[1]),s=E(e.lng,e.lat),c=P(s,i)<P(s,o),l=$t(i,a,s),u=c?90-l:$t(i,a,s)-90,d=P(a,s),f=Math.cos(S(u))*d,p=L(i,o)+(function(e,t,n){let r=(n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x);return r>1e-10?`left`:r<-1e-10?`right`:`left`}(i,o,s)===`right`?-90:90),m=ke(i,f,p),h=ke(o,f,p),g=D(m.x,m.y),_=D(h.x,h.y);return[{type:A,index:2,coordinate:[w(_.lng,this.coordinatePrecision),w(_.lat,this.coordinatePrecision)]},{type:A,index:3,coordinate:[w(g.lng,this.coordinatePrecision),w(g.lat,this.coordinatePrecision)]}]}onClick(e){if(e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e))if(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(e),this.mouseMove=!1,this.currentCoordinate===0){let{id:t}=this.mutateFeature.createPolygon({coordinates:[[e.lng,e.lat],[e.lng,e.lat],[e.lng,e.lat],[e.lng,e.lat]],properties:{mode:this.mode,[u.CURRENTLY_DRAWING]:!0}});this.currentId=t,this.currentCoordinate++,this.setDrawing()}else if(this.currentCoordinate===1&&this.currentId){let t=this.readFeature.getCoordinate(this.currentId,0);if(xe([e.lng,e.lat],t)||!this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:[{type:A,index:1,coordinate:[e.lng,e.lat]},{type:k,index:1,coordinate:[e.lng,e.lat]}],context:{updateType:s.Commit}}))return;this.currentCoordinate++}else this.currentCoordinate===2&&this.currentId&&this.close()}onKeyUp(e){if(e.key===this.keyEvents.cancel)this.cleanUp();else if(e.key===this.keyEvents.finish){if(this.currentCoordinate<2)return void this.cleanUp();this.close()}}onKeyDown(){}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){let e=this.currentId;this.currentId=void 0,this.currentCoordinate=0,this.state===`drawing`&&this.setStarted(),this.mutateFeature.deleteFeatureIfPresent(e)}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});return e.properties.mode===this.mode&&e.geometry.type===`Polygon`&&(t.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,t.polygonFillColor,e),t.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,t.polygonOutlineColor,e),t.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,t.polygonOutlineWidth,e),t.polygonOutlineOpacity=this.getNumericStylingValue(this.styles.outlineOpacity,1,e),t.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,t.polygonFillOpacity,e),t.zIndex=d),t}validateFeature(e){return this.validateModeFeature(e,e=>he(e,this.coordinatePrecision))}afterFeatureUpdated(e){this.currentId===e.id&&(this.currentId=void 0,this.currentCoordinate=0,this.state===`drawing`&&this.setStarted())}registerBehaviors(e){this.readFeature=new F(e),this.mutateFeature=new N(e,{validate:this.validate})}};function rn(e,t,n){return(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x)<=0}var an={cancel:`Escape`,finish:`Enter`},on={start:`crosshair`,close:`pointer`},sn=class extends v{constructor(e){super(e,!0),this.mode=`sector`,this.currentCoordinate=0,this.currentId=void 0,this.keyEvents=an,this.direction=void 0,this.arcPoints=64,this.cursors=on,this.mouseMove=!1,this.readFeature=void 0,this.mutateFeature=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors)),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=n({},this.keyEvents,e.keyEvents)),e!=null&&e.arcPoints&&(this.arcPoints=e.arcPoints)}close(){if(this.currentId===void 0||!this.mutateFeature.updatePolygon({featureId:this.currentId,propertyMutations:{[u.CURRENTLY_DRAWING]:void 0},coordinateMutations:{coordinates:this.readFeature.getGeometry(this.currentId).coordinates,type:M},context:{updateType:s.Finish,action:r}}))return;let e=this.currentId;this.currentCoordinate=0,this.currentId=void 0,this.direction=void 0,this.state===`drawing`&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:r})}getSectorCoordinates(e){let t=this.readFeature.getCoordinates(this.currentId),n=t[0],r=t[1],i=[e.lng,e.lat],a=E(n[0],n[1]),o=E(r[0],r[1]),s=E(i[0],i[1]);if(this.direction===void 0){let e=rn(a,o,s);this.direction=e?`clockwise`:`anticlockwise`}let c=P(a,o),l=L(a,o),u=L(a,s),d=this.arcPoints,f=[n],p=R(l),m=R(u),h;this.direction===`anticlockwise`?(h=m-p,h<0&&(h+=360)):(h=p-m,h<0&&(h+=360));let g=(this.direction===`anticlockwise`?1:-1)*h/d;f.push(r);for(let e=0;e<=d;e++){let t=ke(a,c,p+e*g),{lng:n,lat:r}=D(t.x,t.y),i=[w(n,this.coordinatePrecision),w(r,this.coordinatePrecision)];i[0]!==f[f.length-1][0]&&i[1]!==f[f.length-1][1]&&f.push(i)}return f.push(n),f}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onMouseMove(e){if(this.mouseMove=!0,this.setCursor(this.cursors.start),this.currentId===void 0||this.currentCoordinate===0)return;let t;if(this.currentCoordinate===1)t=[{type:A,index:1,coordinate:[e.lng,e.lat]},{type:A,index:2,coordinate:[e.lng,e.lat]}];else{if(this.currentCoordinate!==2)return;{let n=this.getSectorCoordinates(e);if(!n)return;t={type:M,coordinates:[n]}}}this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:t,context:{updateType:s.Provisional}})}onClick(e){if(e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e))if(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(e),this.mouseMove=!1,this.currentCoordinate===0){let t=this.mutateFeature.createPolygon({coordinates:[[e.lng,e.lat],[e.lng,e.lat],[e.lng,e.lat],[e.lng,e.lat]],properties:{mode:this.mode,[u.CURRENTLY_DRAWING]:!0}});this.currentId=t?.id,this.currentCoordinate++,this.setDrawing()}else if(this.currentCoordinate===1&&this.currentId){if(this.readFeature.coordinateAtIndexIsIdentical({featureId:this.currentId,index:0,newCoordinate:[e.lng,e.lat]})||!this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:[{type:A,index:1,coordinate:[e.lng,e.lat]},{type:A,index:2,coordinate:[e.lng,e.lat]}],context:{updateType:s.Provisional}}))return;this.currentCoordinate++}else this.currentCoordinate===2&&this.currentId&&this.close()}onKeyUp(e){e.key===this.keyEvents.cancel?this.cleanUp():e.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){let e=this.currentId;this.currentId=void 0,this.direction=void 0,this.currentCoordinate=0,this.state===`drawing`&&this.setStarted(),this.mutateFeature.deleteFeatureIfPresent(e)}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});return e.properties.mode===this.mode&&e.geometry.type===`Polygon`&&(t.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,t.polygonFillColor,e),t.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,t.polygonOutlineColor,e),t.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,t.polygonOutlineWidth,e),t.polygonOutlineOpacity=this.getNumericStylingValue(this.styles.outlineOpacity,1,e),t.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,t.polygonFillOpacity,e),t.zIndex=d),t}validateFeature(e){return this.validateModeFeature(e,e=>he(e,this.coordinatePrecision))}afterFeatureUpdated(e){this.currentId===e.id&&(this.currentId=void 0,this.direction=void 0,this.currentCoordinate=0,this.state===`drawing`&&this.setStarted())}registerBehaviors(e){this.readFeature=new F(e),this.mutateFeature=new N(e,{validate:this.validate})}},cn={cancel:`Escape`,finish:`Enter`},ln={start:`crosshair`,close:`pointer`},un=class extends v{constructor(e){super(e,!0),this.mode=`sensor`,this.currentCoordinate=0,this.currentId=void 0,this.currentInitialArcId=void 0,this.currentStartingPointId=void 0,this.keyEvents=cn,this.direction=void 0,this.arcPoints=64,this.cursors=ln,this.mouseMove=!1,this.readFeature=void 0,this.mutateFeature=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors)),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=n({},this.keyEvents,e.keyEvents)),e!=null&&e.arcPoints&&(this.arcPoints=e.arcPoints)}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onMouseMove(e){if(this.mouseMove=!0,this.setCursor(this.cursors.start),this.currentInitialArcId!==void 0&&this.currentStartingPointId!==void 0&&this.currentCoordinate!==0){if(this.currentCoordinate===2){let t=this.getUpdatedLineStringCoordinates(e);if(!t)return;this.mutateFeature.updateLineString({featureId:this.currentInitialArcId,coordinateMutations:{type:M,coordinates:t},context:{updateType:s.Provisional}})}else if(this.currentCoordinate===3){let t=this.getUpdatedPolygonCoordinates(e);if(!t)return;if(this.currentId)this.mutateFeature.updatePolygon({featureId:this.currentId,coordinateMutations:{type:M,coordinates:[t]},context:{updateType:s.Provisional}});else{let e=this.mutateFeature.createPolygon({coordinates:t,properties:{mode:this.mode,[u.CURRENTLY_DRAWING]:!0}});if(!e)return;this.currentId=e.id}}}}onClick(e){if(e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e))if(this.currentCoordinate>0&&!this.mouseMove&&this.onMouseMove(e),this.mouseMove=!1,this.currentCoordinate===0){let t=this.mutateFeature.createPoint({coordinates:[e.lng,e.lat],properties:{mode:this.mode}});if(!t)return;this.currentStartingPointId=t.id,this.currentCoordinate++,this.setDrawing()}else if(this.currentCoordinate===1&&this.currentStartingPointId){let t=this.mutateFeature.createLineString({coordinates:[[e.lng,e.lat],[e.lng,e.lat]],properties:{mode:this.mode}});if(!t)return;this.currentInitialArcId=t.id,this.currentCoordinate++}else this.currentCoordinate===2&&this.currentStartingPointId?this.currentCoordinate++:this.currentCoordinate===3&&this.currentStartingPointId&&this.close()}onKeyUp(e){e.key===this.keyEvents.cancel?this.cleanUp():e.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){this.mutateFeature.deleteFeatureIfPresent(this.currentStartingPointId),this.mutateFeature.deleteFeatureIfPresent(this.currentInitialArcId),this.mutateFeature.deleteFeatureIfPresent(this.currentId),this.currentStartingPointId=void 0,this.direction=void 0,this.currentId=void 0,this.currentCoordinate=0,this.state===`drawing`&&this.setStarted()}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});return e.properties.mode===this.mode&&(e.geometry.type===`Polygon`?(t.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,t.polygonFillColor,e),t.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,t.polygonOutlineColor,e),t.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,t.polygonOutlineWidth,e),t.polygonOutlineOpacity=this.getNumericStylingValue(this.styles.outlineOpacity,1,e),t.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,t.polygonFillOpacity,e),t.zIndex=d):e.geometry.type===`LineString`?(t.lineStringColor=this.getHexColorStylingValue(this.styles.outlineColor,t.polygonOutlineColor,e),t.lineStringWidth=this.getNumericStylingValue(this.styles.outlineWidth,t.polygonOutlineWidth,e),t.zIndex=d):e.geometry.type===`Point`&&(t.pointColor=this.getHexColorStylingValue(this.styles.centerPointColor,t.pointColor,e),t.pointOpacity=this.getNumericStylingValue(this.styles.centerPointOpacity,1,e),t.pointWidth=this.getNumericStylingValue(this.styles.centerPointWidth,t.pointWidth,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.centerPointOutlineColor,t.pointOutlineColor,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.centerPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.centerPointOutlineWidth,t.pointOutlineWidth,e),t.zIndex=20)),t}validateFeature(e){return this.validateModeFeature(e,e=>he(e,this.coordinatePrecision))}afterFeatureUpdated(e){this.currentId===e.id&&(this.mutateFeature.deleteFeatureIfPresent(this.currentStartingPointId),this.mutateFeature.deleteFeatureIfPresent(this.currentInitialArcId),this.currentStartingPointId=void 0,this.direction=void 0,this.currentId=void 0,this.currentCoordinate=0,this.state===`drawing`&&this.setStarted())}registerBehaviors(e){this.readFeature=new F(e),this.mutateFeature=new N(e,{validate:this.validate})}close(){if(this.currentStartingPointId===void 0)return;let e=this.currentStartingPointId,t=this.currentInitialArcId;if(this.currentId&&!this.mutateFeature.updatePolygon({featureId:this.currentId,propertyMutations:{[u.CURRENTLY_DRAWING]:void 0},coordinateMutations:{coordinates:this.readFeature.getGeometry(this.currentId).coordinates,type:M},context:{updateType:s.Finish,action:r}}))return;let n=this.currentId;this.mutateFeature.deleteFeatureIfPresent(e),this.mutateFeature.deleteFeatureIfPresent(t),this.currentCoordinate=0,this.currentStartingPointId=void 0,this.currentInitialArcId=void 0,this.currentId=void 0,this.direction=void 0,this.state===`drawing`&&this.setStarted(),n&&this.onFinish(n,{mode:this.mode,action:r})}getUpdatedPolygonCoordinates(e){if(this.currentInitialArcId===void 0||this.currentStartingPointId===void 0||this.currentCoordinate<3)return;let t=this.readFeature.getCoordinates(this.currentInitialArcId);if(t.length<2||!this.direction)return;let n=this.readFeature.getGeometry(this.currentStartingPointId).coordinates,r=t[0],i=t[t.length-1],a=E(e.lng,e.lat),o=E(r[0],r[1]),s=E(i[0],i[1]),c=E(n[0],n[1]),l=P(c,o),u=P(c,a)<l?o:a,d=L(c,a),f=L(c,o),p=L(c,s),m=R(f),h=R(p),g=R(d);if(this.notInSector({normalizedCursor:g,normalizedStart:m,normalizedEnd:h,direction:this.direction}))return;let _=this.getDeltaBearing(this.direction,m,h),v=this.arcPoints,y=(this.direction===`anticlockwise`?1:-1)*_/v,b=P(c,u),x=[];for(let e=0;e<=v;e++){let n=ke(c,b,m+e*y),{lng:r,lat:i}=D(n.x,n.y),a=[w(r,this.coordinatePrecision),w(i,this.coordinatePrecision)];a[0]!==t[t.length-1][0]&&a[1]!==t[t.length-1][1]&&x.unshift(a)}return t.push(...x),t.push(t[0]),t}getUpdatedLineStringCoordinates(e){if(this.currentInitialArcId===void 0||this.currentStartingPointId===void 0||this.currentCoordinate<2)return;let t=this.readFeature.getGeometry(this.currentInitialArcId).coordinates,n=this.readFeature.getGeometry(this.currentStartingPointId).coordinates,r=t[0],i=[e.lng,e.lat],a=E(r[0],r[1]),o=E(i[0],i[1]),s=E(n[0],n[1]),c=P(s,a);if(this.direction===void 0){let e=rn(s,a,o);this.direction=e?`clockwise`:`anticlockwise`}let l=L(s,a),u=L(s,o),d=this.arcPoints,f=[r],p=R(l),m=R(u),h;this.direction===`anticlockwise`?(h=m-p,h<0&&(h+=360)):(h=p-m,h<0&&(h+=360));let g=(this.direction===`anticlockwise`?1:-1)*h/d;for(let e=0;e<=d;e++){let t=ke(s,c,p+e*g),{lng:n,lat:r}=D(t.x,t.y),i=[w(n,this.coordinatePrecision),w(r,this.coordinatePrecision)];i[0]!==f[f.length-1][0]&&i[1]!==f[f.length-1][1]&&f.push(i)}return f}getDeltaBearing(e,t,n){let r;return e===`anticlockwise`?(r=n-t,r<0&&(r+=360)):(r=t-n,r<0&&(r+=360)),r}notInSector({normalizedCursor:e,normalizedStart:t,normalizedEnd:n,direction:r}){return r===`clockwise`?t<=n?e>=t&&e<=n:e>=t||e<=n:t>=n?e<=t&&e>=n:e<=t||e>=n}},W=class{constructor({name:e,callback:t,unregister:n,register:r}){this.name=void 0,this.callback=void 0,this.registered=!1,this.register=void 0,this.unregister=void 0,this.name=e,this.register=()=>{this.registered||(this.registered=!0,r(t))},this.unregister=()=>{this.register&&(this.registered=!1,n(t))},this.callback=t}},dn={__proto__:null,GeoJSONStore:Yt,TerraDrawBaseDrawMode:v,TerraDrawBaseSelectMode:y,TerraDrawBaseAdapter:class{constructor(e){this._nextKeyUpIsContextMenu=!1,this._lastPointerDownEventTarget=void 0,this._ignoreMismatchedPointerEvents=!1,this._minPixelDragDistance=void 0,this._minPixelDragDistanceDrawing=void 0,this._minPixelDragDistanceSelecting=void 0,this._lastDrawEvent=void 0,this._coordinatePrecision=void 0,this._heldKeys=new Set,this._listeners=[],this._dragState=`not-dragging`,this._currentModeCallbacks=void 0,this._ignoreMismatchedPointerEvents=typeof e.ignoreMismatchedPointerEvents==`boolean`&&e.ignoreMismatchedPointerEvents,this._minPixelDragDistance=typeof e.minPixelDragDistance==`number`?e.minPixelDragDistance:1,this._minPixelDragDistanceSelecting=typeof e.minPixelDragDistanceSelecting==`number`?e.minPixelDragDistanceSelecting:1,this._minPixelDragDistanceDrawing=typeof e.minPixelDragDistanceDrawing==`number`?e.minPixelDragDistanceDrawing:8,this._coordinatePrecision=typeof e.coordinatePrecision==`number`?e.coordinatePrecision:9}getButton(e){return e.button===-1?`neither`:e.button===0?`left`:e.button===1?`middle`:e.button===2?`right`:`neither`}getMapElementXYPosition(e){let{left:t,top:n}=this.getMapEventElement(e.type).getBoundingClientRect();return{containerX:e.clientX-t,containerY:e.clientY-n}}getDrawEventFromEvent(e,t=!1){let n=this.getLngLatFromEvent(e);if(!n)return null;let{lng:r,lat:i}=n,{containerX:a,containerY:o}=this.getMapElementXYPosition(e),s=this.getButton(e),c=Array.from(this._heldKeys);return{lng:w(r,this._coordinatePrecision),lat:w(i,this._coordinatePrecision),containerX:a,containerY:o,button:s,heldKeys:c,isContextMenu:t}}register(e){this._currentModeCallbacks=e,this._listeners=this.getAdapterListeners(),this._listeners.forEach(e=>{e.register()})}getCoordinatePrecision(){return this._coordinatePrecision}getAdapterListeners(){return[new W({name:`pointerdown`,callback:e=>{if(!this._currentModeCallbacks||!e.isPrimary)return;let t=this.getDrawEventFromEvent(e);t&&(this._dragState=`pre-dragging`,this._lastDrawEvent=t,this._lastPointerDownEventTarget=e.target?e.target:void 0)},register:e=>{this.getMapEventElement(`pointerdown`).addEventListener(`pointerdown`,e)},unregister:e=>{this.getMapEventElement(`pointerdown`).removeEventListener(`pointerdown`,e)}}),new W({name:`pointermove`,callback:e=>{if(!this._currentModeCallbacks||!e.isPrimary)return;e.preventDefault();let t=this.getDrawEventFromEvent(e);if(t)if(this._dragState===`not-dragging`)this._currentModeCallbacks.onMouseMove(t),this._lastDrawEvent=t;else if(this._dragState===`pre-dragging`){if(!this._lastDrawEvent)return;let e={x:this._lastDrawEvent.containerX,y:this._lastDrawEvent.containerY},n={x:t.containerX,y:t.containerY},r=this._currentModeCallbacks.getState(),i=P(e,n),a=!1;if(a=r===`drawing`?i<this._minPixelDragDistanceDrawing:r===`selecting`?i<this._minPixelDragDistanceSelecting:i<this._minPixelDragDistance,a)return;this._nextKeyUpIsContextMenu=!1,this._dragState=`dragging`,this._currentModeCallbacks.onDragStart(t,e=>{this.setDraggability.bind(this)(e)})}else this._dragState===`dragging`&&this._currentModeCallbacks.onDrag(t,e=>{this.setDraggability.bind(this)(e)})},register:e=>{this.getMapEventElement(`pointermove`).addEventListener(`pointermove`,e)},unregister:e=>{this.getMapEventElement(`pointermove`).removeEventListener(`pointermove`,e)}}),new W({name:`contextmenu`,callback:e=>{this._currentModeCallbacks&&(e.preventDefault(),this._nextKeyUpIsContextMenu=!0)},register:e=>{this.getMapEventElement(`contextmenu`).addEventListener(`contextmenu`,e)},unregister:e=>{this.getMapEventElement(`contextmenu`).removeEventListener(`contextmenu`,e)}}),new W({name:`pointerup`,callback:e=>{if(!this._currentModeCallbacks||e.target!==this.getMapEventElement(`pointerup`)||this._ignoreMismatchedPointerEvents&&this._lastPointerDownEventTarget!==e.target||(this._lastPointerDownEventTarget=void 0,!e.isPrimary))return;let t=this.getDrawEventFromEvent(e);t&&(this._dragState===`dragging`?this._currentModeCallbacks.onDragEnd(t,e=>{this.setDraggability.bind(this)(e)}):this._dragState!==`not-dragging`&&this._dragState!==`pre-dragging`||(this._nextKeyUpIsContextMenu&&=(t.isContextMenu=!0,!1),this._currentModeCallbacks.onClick(t)),this._dragState=`not-dragging`,this.setDraggability(!0))},register:e=>{this.getMapEventElement(`pointerup`).addEventListener(`pointerup`,e)},unregister:e=>{this.getMapEventElement(`pointerup`).removeEventListener(`pointerup`,e)}}),new W({name:`keyup`,callback:e=>{this._currentModeCallbacks&&(this._heldKeys.delete(e.key),this._currentModeCallbacks.onKeyUp({key:e.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>e.preventDefault()}))},register:e=>{this.getMapEventElement(`keyup`).addEventListener(`keyup`,e)},unregister:e=>{this.getMapEventElement(`keyup`).removeEventListener(`keyup`,e)}}),new W({name:`keydown`,callback:e=>{this._currentModeCallbacks&&(this._heldKeys.add(e.key),this._currentModeCallbacks.onKeyDown({key:e.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>e.preventDefault()}))},register:e=>{this.getMapEventElement(`keydown`).addEventListener(`keydown`,e)},unregister:e=>{this.getMapEventElement(`keydown`).removeEventListener(`keydown`,e)}})]}unregister(){this._listeners.forEach(e=>{e.unregister()}),this.clear(),this._currentModeCallbacks=void 0,this._lastDrawEvent=void 0,this._lastPointerDownEventTarget=void 0,this._nextKeyUpIsContextMenu=!1}},getDefaultStyling:()=>({polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0}),SELECT_PROPERTIES:l},fn={cancel:`Escape`,finish:`Enter`},pn={start:`crosshair`,close:`pointer`},mn=class extends v{constructor(e){super(e,!0),this.mode=`freehand-linestring`,this.canClose=!1,this.currentId=void 0,this.minDistance=20,this.keyEvents=fn,this.cursors=pn,this.preventNewFeature=!1,this.mutateFeature=void 0,this.readFeature=void 0,this.pixelDistance=void 0,this.closingPoints=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.minDistance&&(this.minDistance=e.minDistance),e?.keyEvents===null?this.keyEvents={cancel:null,finish:null}:e!=null&&e.keyEvents&&(this.keyEvents=n({},this.keyEvents,e.keyEvents)),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors))}close(){if(this.currentId===void 0||!this.mutateFeature.updateLineString({featureId:this.currentId,propertyMutations:{[u.CURRENTLY_DRAWING]:void 0},context:{updateType:s.Finish,action:r}}))return;let e=this.currentId;this.closingPoints.delete(),this.canClose=!1,this.currentId=void 0,this.state===`drawing`&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:r})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onMouseMove(e){if(this.currentId===void 0||!1===this.canClose)return void this.setCursor(this.cursors.start);let[t,n]=this.readFeature.getCoordinate(this.currentId,-2),{x:r,y:i}=this.project(t,n),a=P({x:r,y:i},{x:e.containerX,y:e.containerY}),[o,c]=this.readFeature.getCoordinate(this.currentId,-1),{x:l,y:u}=this.project(o,c),d=P({x:l,y:u},{x:e.containerX,y:e.containerY});if(this.setCursor(d<this.pointerDistance?this.cursors.close:this.cursors.start),a<this.minDistance)return;let f=this.mutateFeature.updateLineString({featureId:this.currentId,coordinateMutations:[{type:k,index:-1,coordinate:[e.lng,e.lat]}],context:{updateType:s.Provisional}});f&&this.closingPoints.update(f.geometry.coordinates)}onClick(e){if(e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e)){if(this.preventNewFeature)return;if(!1===this.canClose){let{id:t,geometry:n}=this.mutateFeature.createLineString({coordinates:[[e.lng,e.lat],[e.lng,e.lat]],properties:{mode:this.mode,[u.CURRENTLY_DRAWING]:!0}});this.closingPoints.create(n.coordinates),this.currentId=t,this.canClose=!0,this.state!==`drawing`&&this.setDrawing();return}this.close()}}onKeyDown(){}onKeyUp(e){e.key===this.keyEvents.cancel?this.cleanUp():e.key===this.keyEvents.finish&&!0===this.canClose&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){let e=this.currentId;this.currentId=void 0,this.canClose=!1,this.state===`drawing`&&this.setStarted(),this.mutateFeature.deleteFeatureIfPresent(e),this.closingPoints.delete()}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});return e.type===`Feature`&&e.geometry.type===`LineString`&&e.properties.mode===this.mode?(t.lineStringDash=this.styles.lineStringDash,t.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,t.lineStringColor,e),t.lineStringOpacity=this.getNumericStylingValue(this.styles.lineStringOpacity,t.lineStringOpacity===void 0?1:t.lineStringOpacity,e),t.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,t.lineStringWidth,e),t.zIndex=d,t):e.type===`Feature`&&e.geometry.type===`Point`&&e.properties.mode===this.mode?(t.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,t.pointWidth,e),t.pointOpacity=this.getNumericStylingValue(this.styles.closingPointOpacity,1,e),t.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,t.pointColor,e),t.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,t.pointOutlineColor,e),t.pointOutlineOpacity=this.getNumericStylingValue(this.styles.closingPointOutlineOpacity,1,e),t.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),t.zIndex=50,t):t}validateFeature(e){return this.validateModeFeature(e,e=>Fe(e,this.coordinatePrecision))}afterFeatureUpdated(e){this.currentId===e.id&&(this.closingPoints.delete(),this.canClose=!1,this.currentId=void 0)}registerBehaviors(e){this.readFeature=new F(e),this.mutateFeature=new N(e,{validate:this.validate}),this.pixelDistance=new I(e),this.closingPoints=new We(e,this.pixelDistance,this.mutateFeature,this.readFeature)}};function hn(e){if(e===null||typeof e==`boolean`||typeof e==`string`)return!0;if(e===void 0)return!1;if(typeof e==`number`)return Number.isFinite(e);if(typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof Date)return!1;if(typeof e==`object`&&e&&!Array.isArray(e)){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return!1}if(ArrayBuffer.isView(e)&&!(e instanceof DataView))return!1;if(Array.isArray(e)){for(let t of e)if(!hn(t))return!1}return typeof e==`object`&&Object.keys(e).every(t=>typeof t==`string`&&hn(e[t]))}var gn={create:`crosshair`,dragStart:`grabbing`,dragEnd:`crosshair`},_n=class extends v{constructor(e){super(e,!0),this.mode=`marker`,this.cursors=gn,this.editable=!1,this.editedFeatureId=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.pointSearch=void 0,this.mutateFeature=void 0,this.updateOptions(e)}updateOptions(e){super.updateOptions(e),e!=null&&e.cursors&&(this.cursors=n({},this.cursors,e.cursors)),e!=null&&e.editable&&(this.editable=e.editable)}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor(`unset`)}onClick(e){e.button===`right`&&this.allowPointerEvent(this.pointerEvents.rightClick,e)||e.isContextMenu&&this.allowPointerEvent(this.pointerEvents.contextMenu,e)?this.onRightClick(e):e.button===`left`&&this.allowPointerEvent(this.pointerEvents.leftClick,e)&&this.onLeftClick(e)}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){this.editedFeatureId=void 0}onDragStart(e,t){if(this.allowPointerEvent(this.pointerEvents.onDragStart,e)){if(this.editable){let t=this.pointSearch.getNearestPointFeature(e);this.editedFeatureId=t?.id}this.editedFeatureId&&(this.setCursor(this.cursors.dragStart),t(!1))}}onDrag(e,t){this.allowPointerEvent(this.pointerEvents.onDrag,e)&&this.editedFeatureId!==void 0&&this.mutateFeature.updatePoint({featureId:this.editedFeatureId,coordinateMutations:{type:M,coordinates:[e.lng,e.lat]},propertyMutations:{[u.EDITED]:!0},context:{updateType:s.Provisional}})}onDragEnd(e,t){if(!this.allowPointerEvent(this.pointerEvents.onDragEnd,e)||this.editedFeatureId===void 0||!this.mutateFeature.updatePoint({featureId:this.editedFeatureId,propertyMutations:{mode:this.mode,[u.EDITED]:!1},context:{updateType:s.Finish,action:`edit`}}))return;let n=this.editedFeatureId;this.setCursor(this.cursors.dragEnd),this.editedFeatureId=void 0,t(!0),this.onFinish(n,{mode:this.mode,action:r})}registerBehaviors(e){this.pixelDistance=new I(e),this.clickBoundingBox=new Ee(e),this.pointSearch=new et(e,this.pixelDistance,this.clickBoundingBox),this.mutateFeature=new N(e,{validate:this.validate})}styleFeature(e){let t=n({},{polygonFillColor:`#3f97e0`,polygonOutlineColor:`#3f97e0`,polygonOutlineWidth:4,polygonOutlineOpacity:1,polygonFillOpacity:.3,pointColor:`#3f97e0`,pointOpacity:1,pointOutlineColor:`#ffffff`,pointOutlineOpacity:1,pointOutlineWidth:0,pointWidth:6,lineStringColor:`#3f97e0`,lineStringWidth:4,lineStringOpacity:1,zIndex:0,markerUrl:void 0,markerHeight:void 0,markerWidth:void 0,lineStringDash:void 0});return e.type===`Feature`&&e.geometry.type===`Point`&&e.properties.mode===this.mode&&(t.zIndex=30,t.markerHeight=this.getNumericStylingValue(this.styles?.markerHeight,40,e),t.markerWidth=this.getNumericStylingValue(this.styles?.markerWidth,32,e),t.markerUrl=this.getUrlStylingValue(this.styles?.markerUrl,c,e)),t}validateFeature(e){return this.validateModeFeature(e,e=>$e(e,this.coordinatePrecision))}onLeftClick(e){let t=this.mutateFeature.createPoint({coordinates:[e.lng,e.lat],properties:{mode:this.mode,[u.MARKER]:!0},context:{updateType:s.Finish,action:r}});t&&this.onFinish(t.id,{mode:this.mode,action:r})}onRightClick(e){if(!this.editable)return;let t=this.pointSearch.getNearestPointFeature(e);t&&this.mutateFeature.deleteFeatureIfPresent(t.id)}afterFeatureUpdated(e){this.editedFeatureId===e.id&&(this.editedFeatureId=void 0,this.setCursor(this.cursors.create))}},vn=[{key:`z`,heldKeys:[`meta`]},{key:`z`,heldKeys:[`control`]}],yn=[{key:`z`,heldKeys:[`meta`,`shift`]},{key:`z`,heldKeys:[`control`,`shift`]},{key:`y`,heldKeys:[`control`]}],bn=(e,t)=>{let n=e.key.toLowerCase(),r=new Set(e.heldKeys.map(e=>e.toLowerCase()).filter(e=>e!==n));if(t.key.toLowerCase()!==n)return!1;let i=new Set(t.heldKeys.map(e=>e.toLowerCase()));if(r.size!==i.size)return!1;for(let e of i)if(!r.has(e))return!1;return!0},xn=class{constructor(e){this.undoKeyboardShortcuts=void 0,this.redoKeyboardShortcuts=void 0,this.undoKeyboardShortcuts=e?.undo??vn,this.redoKeyboardShortcuts=e?.redo??yn}isUndoKeyboardShortcut(e){return this.undoKeyboardShortcuts.some(t=>bn(e,t))}isRedoKeyboardShortcut(e){return this.redoKeyboardShortcuts.some(t=>bn(e,t))}};function Sn(e){return e!==void 0&&Number.isFinite(e)?Math.max(0,Math.floor(e)):1/0}var G=`undo`,K=`redo`,q=`push`,J=`mode`,Cn=`session`,wn=class{constructor(e){this.getModeState=void 0,this.getModeHistorySizes=void 0,this.undoMode=void 0,this.redoMode=void 0,this.clearModeHistory=void 0,this.onHistoryChange=void 0,this.maxStackSize=void 0,this.lastHistorySizes={undoSize:0,redoSize:0},this.maxStackSize=Sn(e?.maxStackSize)}getMaxStackSize(){return this.maxStackSize}register(e){this.getModeState=e.getModeState,this.getModeHistorySizes=e.getModeHistorySizes,this.undoMode=e.undoMode,this.redoMode=e.redoMode,this.clearModeHistory=e.clearModeHistory,this.onHistoryChange=e.onHistoryChange}inDrawingState(){return!!this.getModeState&&this.getModeState()===`drawing`}canUndo(){if(!this.inDrawingState())return!1;let{undoSize:e}=this.getHistorySizes();return e>0}canRedo(){if(!this.inDrawingState())return!1;let{redoSize:e}=this.getHistorySizes();return e>0}undo(){return!(!this.canUndo()||!this.undoMode||(this.undoMode(),this.emitHistoryChange(G),0))}redo(){return!(!this.canRedo()||!this.redoMode||(this.redoMode(),this.emitHistoryChange(K),0))}clearHistory(){this.clearModeHistory&&this.clearModeHistory(),this.lastHistorySizes={undoSize:0,redoSize:0}}getHistorySizes(){return this.getModeHistorySizes?this.getModeHistorySizes():{undoSize:0,redoSize:0}}undoSize(){return this.getHistorySizes().undoSize}redoSize(){return this.getHistorySizes().redoSize}emitPushIfHistoryChangedFromLastSnapshot(){if(!this.inDrawingState())return;let e=this.getHistorySizes();e.undoSize===this.lastHistorySizes.undoSize&&e.redoSize===this.lastHistorySizes.redoSize||this.emitHistoryChange(q)}emitPushIfHistoryChanged(e){if(!this.inDrawingState())return;let t=this.getHistorySizes();t.undoSize===e.undoSize&&t.redoSize===e.redoSize||this.emitHistoryChange(q)}emitHistoryChange(e){if(!this.onHistoryChange)return;let{undoSize:t,redoSize:n}=this.getHistorySizes();this.lastHistorySizes={undoSize:t,redoSize:n},this.onHistoryChange({cause:e,stack:J,undoStackSize:t,redoStackSize:n})}},Tn=class{constructor(e){this.draw=void 0,this.onHistoryChange=void 0,this.maxStackSize=void 0,this.historyById={},this.undoStack=[],this.ignoreProgrammaticCreate={},this.ignoreProgrammaticDelete={},this.deletedFeatureIds={},this.redoStack=[],this.isReplayingHistory=!1,this.emitStackChange=e=>{this.onHistoryChange&&this.onHistoryChange({cause:e,stack:Cn,undoStackSize:this.undoStack.length,redoStackSize:this.redoStack.length})},this.handleChange=(e,t,n)=>{if(!this.draw||this.isDrawing()||this.maxStackSize===0)return;if(t===`update`){if(n===void 0||!(`origin`in n)||n.origin!==`api`||this.isReplayingHistory)return;let t=Array.isArray(e)?e:[e],r=!1;for(let e of t){if(e==null)continue;let t=String(e),n=this.draw.getSnapshotFeature(e);n&&(this.historyById[t]||(this.historyById[t]=[]),this.historyById[t].push(n),this.pushUndoStackEntry({id:e,toIndex:this.historyById[t].length-1,action:`single`}),r=!0)}r&&(this.redoStack.length=0,this.emitStackChange(q));return}if(t!==`delete`&&t!==`create`)return;if(t===`create`){if(n===void 0||!(`origin`in n)||n.origin!==`api`)return;let t=!1,r=Array.isArray(e)?e:[e],i=[];for(let e of r){if(this.ignoreProgrammaticCreate[e]){delete this.ignoreProgrammaticCreate[e],delete this.deletedFeatureIds[e];continue}let n=String(e),r=this.draw.getSnapshotFeature(e);r&&(this.deletedFeatureIds[e]&&(this.historyById[n]=[],delete this.deletedFeatureIds[e]),this.historyById[n]||(this.historyById[n]=[]),this.historyById[n].push(r),i.push({id:e,toIndex:this.historyById[n].length-1,snapshot:r}),t=!0)}if(i.length>1)this.pushUndoStackEntry({id:i[0].id,toIndex:i[0].toIndex,action:`batch-create`,metadata:{entries:i}});else if(i.length===1){let e=i[0];this.pushUndoStackEntry({id:e.id,toIndex:e.toIndex,action:`single`})}t&&(this.redoStack.length=0,this.emitStackChange(q));return}let r=!1,i=Array.isArray(e)?e:[e],a=[];for(let e of i){let t=String(e);if(this.ignoreProgrammaticDelete[e]){delete this.ignoreProgrammaticDelete[e];continue}if(!this.historyById[t])continue;let n=this.historyById[t].length-1;if(n>=0){let i=this.historyById[t][n];if(!i)continue;a.push({id:e,toIndex:n,snapshot:i}),this.deletedFeatureIds[e]=!0,r=!0}}if(a.length>1)this.pushUndoStackEntry({id:a[0].id,toIndex:a[0].toIndex,action:`batch-delete`,metadata:{entries:a}});else if(a.length===1){let e=a[0];this.pushUndoStackEntry({id:e.id,toIndex:e.toIndex,action:`single`})}r&&(this.redoStack.length=0,this.emitStackChange(q))},this.handleFinish=e=>{if(!this.draw||this.maxStackSize===0||this.isReplayingHistory)return;let t=Array.isArray(e)?e:[e],n=!1;for(let e of t){if(e==null)continue;let t=String(e),r=this.draw.getSnapshotFeature(e);r&&(this.historyById[t]||(this.historyById[t]=[]),this.historyById[t].push(r),n||=(this.redoStack.length=0,!0),this.pushUndoStackEntry({id:e,toIndex:this.historyById[t].length-1,action:`single`}),this.emitStackChange(q))}},this.maxStackSize=Sn(e?.maxStackSize)}register(e){this.draw===e.draw?this.onHistoryChange=e.onHistoryChange:(this.draw&&(this.draw.off(`change`,this.handleChange),this.draw.off(`finish`,this.handleFinish)),this.draw=e.draw,this.draw.on(`change`,this.handleChange),this.draw.on(`finish`,this.handleFinish),this.onHistoryChange=e.onHistoryChange)}pushUndoStackEntry(e){this.maxStackSize!==0&&(this.undoStack.push(e),this.undoStack.length>this.maxStackSize&&this.undoStack.shift())}pushRedoStackEntry(e){this.maxStackSize!==0&&(this.redoStack.push(e),this.redoStack.length>this.maxStackSize&&this.redoStack.shift())}isDrawing(){return!!this.draw&&this.draw.getModeState()===`drawing`}applySnapshotDuringReplay(e,t){if(this.draw){this.isReplayingHistory=!0;try{this.draw.hasFeature(e)&&(this.ignoreProgrammaticDelete[e]=!0,this.draw.removeFeatures([e])),this.ignoreProgrammaticCreate[e]=!0,delete this.deletedFeatureIds[e],this.draw.addFeatures([t])}finally{this.isReplayingHistory=!1}}}canUndo(){return!(!this.draw||this.isDrawing())&&this.undoStack.length>0}canRedo(){return!(!this.draw||this.isDrawing())&&this.redoStack.length>0}undo(){if(!this.canUndo()||!this.draw)return!1;let e=this.undoStack.pop();if(!e)return this.emitStackChange(G),!1;if(e.action===`batch-create`){let t=e.metadata?.entries||[];if(t.length===0)return this.emitStackChange(G),!1;let n=t.map(e=>e.id);return n.forEach(e=>{this.ignoreProgrammaticDelete[e]=!0,this.deletedFeatureIds[e]=!0}),this.draw.removeFeatures(n),this.pushRedoStackEntry({id:t[0].id,toIndex:t[0].toIndex,action:`batch-create`,metadata:{entries:t}}),this.emitStackChange(G),!0}if(e.action===`batch-delete`){let t=e.metadata?.entries||[];if(t.length===0)return this.emitStackChange(G),!1;let n=t.map(e=>e.snapshot).filter(e=>e!==void 0);return n.length>0&&(t.forEach(e=>{this.ignoreProgrammaticCreate[e.id]=!0,delete this.deletedFeatureIds[e.id]}),this.draw.addFeatures(n)),this.pushRedoStackEntry({id:t[0].id,toIndex:t[0].toIndex,action:`batch-delete`,metadata:{entries:t}}),this.emitStackChange(G),!0}let t=e.id,n=e.toIndex,r=String(t),i=this.historyById[r];if(!i||i.length===0)return this.emitStackChange(G),!1;let a=Math.min(n,i.length-1);if(!this.draw.hasFeature(t)){let e=i[a];return e?(this.ignoreProgrammaticCreate[t]=!0,delete this.deletedFeatureIds[t],this.draw.addFeatures([e]),this.pushRedoStackEntry({id:t,toIndex:a,action:`delete`,snapshot:e}),this.emitStackChange(G),!0):(this.emitStackChange(G),!1)}if(a<=0)return this.pushRedoStackEntry({id:t,toIndex:0,action:`create`}),this.ignoreProgrammaticDelete[t]=!0,this.deletedFeatureIds[t]=!0,this.draw.removeFeatures([t]),this.undoStack=this.undoStack.filter(e=>e.id!==t),this.emitStackChange(G),!0;let o=i[a],s=i[a-1];return o&&this.pushRedoStackEntry({id:t,toIndex:a,snapshot:o,action:`update`}),this.applySnapshotDuringReplay(t,s),i.length=a,this.emitStackChange(G),!0}redo(){if(!this.canRedo()||!this.draw)return!1;let{id:e,toIndex:t,snapshot:n,action:r,metadata:i}=this.redoStack.pop();if(r===`batch-create`){let e=i?.entries||[];if(e.length===0)return this.emitStackChange(K),!1;let t=e.map(e=>e.snapshot).filter(e=>e!==void 0);return t.length>0&&(e.forEach(e=>{this.ignoreProgrammaticCreate[e.id]=!0}),this.draw.addFeatures(t)),this.pushUndoStackEntry({id:e[0].id,toIndex:e[0].toIndex,action:`batch-create`,metadata:{entries:e}}),this.emitStackChange(K),!0}if(r===`batch-delete`){let e=i?.entries||[];if(e.length===0)return this.emitStackChange(K),!1;let t=e.map(e=>e.id);return t.forEach(e=>{this.ignoreProgrammaticDelete[e]=!0,this.deletedFeatureIds[e]=!0}),this.draw.removeFeatures(t),this.pushUndoStackEntry({id:e[0].id,toIndex:e[0].toIndex,action:`batch-delete`,metadata:{entries:e}}),this.emitStackChange(K),!0}let a=String(e),o=this.historyById[a]||(this.historyById[a]=[]);if(r===`delete`)return this.ignoreProgrammaticDelete[e]=!0,this.deletedFeatureIds[e]=!0,this.draw.removeFeatures([e]),this.pushUndoStackEntry({id:e,toIndex:t,action:`single`}),this.emitStackChange(K),!0;if(t<=0){let t=o[0];return!!t&&(this.ignoreProgrammaticCreate[e]=!0,this.draw.addFeatures([t]),this.pushUndoStackEntry({id:e,toIndex:0,action:`single`}),this.emitStackChange(K),!0)}let s=n||o[t];return!!s&&(o.length===t?o.push(s):(o[t]=s,o.length=t+1),this.applySnapshotDuringReplay(e,s),this.pushUndoStackEntry({id:e,toIndex:t,action:`single`}),this.emitStackChange(K),!0)}clearHistory(){let e={};if(this.draw&&!this.isDrawing()){let t=this.draw.getSnapshot();for(let n of t)e[String(n.id)]=[n]}this.historyById=e,this.undoStack=[],this.ignoreProgrammaticCreate={},this.ignoreProgrammaticDelete={},this.deletedFeatureIds={},this.redoStack=[]}undoSize(){return this.undoStack.length}redoSize(){return this.redoStack.length}},En=class{constructor(e){this.modeLevel=void 0,this.sessionLevel=void 0,this.shouldPreferMode=void 0,this.onHistoryChange=void 0,this.shouldEmitHistoryChange=void 0,this.modeLevel=e.modeLevel,this.sessionLevel=e.sessionLevel,this.shouldPreferMode=e.shouldPreferMode,this.onHistoryChange=e.onHistoryChange,this.shouldEmitHistoryChange=e.shouldEmitHistoryChange??(()=>!0)}emitStackHistoryChange(e){this.shouldEmitHistoryChange()&&this.onHistoryChange&&this.onHistoryChange({cause:e.cause,stack:e.stack,undoSize:e.undoStackSize,redoSize:e.redoStackSize})}hasSessionUndo(){return!!(this.sessionLevel&&this.sessionLevel.canUndo())}hasSessionRedo(){return!!(this.sessionLevel&&this.sessionLevel.canRedo())}activeStackForUndo(){var e,t;return this.shouldPreferMode()&&(e=this.modeLevel)!=null&&e.canUndo()?J:this.hasSessionUndo()?Cn:(t=this.modeLevel)!=null&&t.canUndo()?J:void 0}activeStackForRedo(){var e,t;return this.shouldPreferMode()&&(e=this.modeLevel)!=null&&e.canRedo()?J:this.hasSessionRedo()?Cn:(t=this.modeLevel)!=null&&t.canRedo()?J:void 0}canUndo(){return this.activeStackForUndo()!==void 0}canRedo(){return this.activeStackForRedo()!==void 0}undo(){let e=this.activeStackForUndo();return!!e&&(e===J?!!this.modeLevel&&this.modeLevel.undo():!(!this.sessionLevel||!this.sessionLevel.canUndo())&&this.sessionLevel.undo())}redo(){let e=this.activeStackForRedo();return!!e&&(e===J?!!this.modeLevel&&this.modeLevel.redo():!(!this.sessionLevel||!this.sessionLevel.canRedo())&&this.sessionLevel.redo())}clearHistory(){this.modeLevel&&this.modeLevel.clearHistory(),this.sessionLevel&&this.sessionLevel.clearHistory()}emitHistoryPushForCompletedAction(){this.sessionLevel?this.emitStackHistoryChange({cause:q,undoStackSize:this.sessionLevel.undoSize(),redoStackSize:this.sessionLevel.redoSize(),stack:Cn}):this.modeLevel&&this.emitStackHistoryChange({cause:q,undoStackSize:this.modeLevel.undoSize(),redoStackSize:this.modeLevel.redoSize(),stack:J})}},Dn=class{constructor(e){var t,r,i,a;this._modes=void 0,this._mode=void 0,this._adapter=void 0,this._enabled=!1,this._store=void 0,this._eventListeners=void 0,this._instanceSelectModes=void 0,this.sessionUndoRedoEnabled=!1,this.keyboardShortcutsMatcher=void 0,this.drawingUndoRedo=void 0,this.sessionUndoRedo=void 0,this.undoRedoCoordinator=void 0,this._adapter=e.adapter,this._instanceSelectModes=[];let o=e==null||(t=e.undoRedo)==null?void 0:t.modeLevel;o&&(this.drawingUndoRedo=o);let s=e==null||(r=e.undoRedo)==null?void 0:r.keyboardShortcuts;s&&(this.keyboardShortcutsMatcher=s),this.sessionUndoRedoEnabled=!!(!(e==null||(i=e.undoRedo)==null)&&i.sessionLevel);let c=e==null||(a=e.undoRedo)==null?void 0:a.sessionLevel;this._mode=new jt;let l=new Set,u=e.modes.reduce((e,t)=>{if(l.has(t.mode))throw Error(`There is already a ${t.mode} mode provided`);return l.add(t.mode),e[t.mode]=t,e},{}),d=Object.keys(u);if(d.length===0)throw Error(`No modes provided`);d.forEach(e=>{u[e].type===g.Select&&this._instanceSelectModes.push(e)}),this._modes=n({},u,{static:this._mode}),this._eventListeners={change:[],select:[],deselect:[],finish:[],ready:[],history:[]},this._store=new Yt({tracked:!!e.tracked,idStrategy:e.idStrategy?e.idStrategy:void 0});let f=e=>{let t=[];return{changed:t,unchanged:this._store.copyAll().filter(n=>!e.includes(n.id)||(t.push(n),!1))}},p=(e,t)=>{var n;this._enabled&&(this._eventListeners.finish.forEach(n=>{n(e,t)}),(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction())},m=(e,t,n)=>{if(!this._enabled)return;this._eventListeners.change.forEach(r=>{r(e,t,n)}),this.emitDrawingPushIfHistoryChangedFromLastSnapshot();let{changed:r,unchanged:i}=f(e);t===`create`?this._adapter.render({created:r,deletedIds:[],unchanged:i,updated:[]},this.getModeStyles()):t===`update`?this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:r},this.getModeStyles()):t===`delete`?this._adapter.render({created:[],deletedIds:e,unchanged:i,updated:[]},this.getModeStyles()):t===`styling`&&this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:[]},this.getModeStyles())},h=e=>{if(!this._enabled)return;this._eventListeners.select.forEach(t=>{t(e)});let{changed:t,unchanged:n}=f([e]);this._adapter.render({created:[],deletedIds:[],unchanged:n,updated:t},this.getModeStyles())},_=e=>{if(!this._enabled)return;this._eventListeners.deselect.forEach(t=>{t(e)});let{changed:t,unchanged:n}=f([e]);t&&this._adapter.render({created:[],deletedIds:[],unchanged:n,updated:t},this.getModeStyles())};Object.keys(this._modes).forEach(e=>{var t;this._modes[e].register({mode:e,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:m,onSelect:h,onDeselect:_,onFinish:p,coordinatePrecision:this._adapter.getCoordinatePrecision(),undoRedoMaxStackSize:(t=this.drawingUndoRedo)==null||t.getMaxStackSize==null?void 0:t.getMaxStackSize()})}),this.sessionUndoRedoEnabled&&c&&(this.sessionUndoRedo=c,c.register({draw:this,onHistoryChange:e=>{var t;(t=this.undoRedoCoordinator)==null||t.emitStackHistoryChange(e)}})),this.drawingUndoRedo&&this.drawingUndoRedo.register({getModeState:()=>this.getModeState(),getModeHistorySizes:()=>this.getDrawingHistorySizes(),undoMode:()=>{this._mode.undo&&this._mode.undo()},redoMode:()=>{this._mode.redo&&this._mode.redo()},clearModeHistory:()=>{let e=this._mode;e.clearHistory&&e.clearHistory()},onHistoryChange:e=>{var t;(t=this.undoRedoCoordinator)==null||t.emitStackHistoryChange(e)}}),this.undoRedoCoordinator=new En({modeLevel:this.drawingUndoRedo,sessionLevel:this.sessionUndoRedo,shouldPreferMode:()=>this.getModeState()===`drawing`,onHistoryChange:e=>{this._eventListeners.history.forEach(t=>{t(e)})},shouldEmitHistoryChange:()=>this._enabled})}checkEnabled(){if(!this._enabled)throw Error(`Terra Draw is not enabled`)}handleUndoRedoKeyboardShortcut(e){if(!this.drawingUndoRedo&&!this.sessionUndoRedoEnabled||!this.keyboardShortcutsMatcher)return!1;let t=this.keyboardShortcutsMatcher.isUndoKeyboardShortcut(e),n=this.keyboardShortcutsMatcher.isRedoKeyboardShortcut(e);if(t){if(!this.canUndo())return!1;let t=this.undo();return t&&e.preventDefault(),t}if(n){if(!this.canRedo())return!1;let t=this.redo();return t&&e.preventDefault(),t}return!1}getDrawingHistorySizes(){return{undoSize:this._mode.undoSize&&typeof this._mode.undoSize==`function`?this._mode.undoSize():0,redoSize:this._mode.redoSize&&typeof this._mode.redoSize==`function`?this._mode.redoSize():0}}emitDrawingPushIfHistoryChangedFromLastSnapshot(){this.drawingUndoRedo&&this.drawingUndoRedo.emitPushIfHistoryChangedFromLastSnapshot()}emitDrawingPushIfHistoryChanged(e){this.drawingUndoRedo&&this.drawingUndoRedo.emitPushIfHistoryChanged(e)}getModeStyles(){let e={},t=this._instanceSelectModes.includes(this._mode.mode)?this._mode.mode:void 0;return Object.keys(this._modes).forEach(n=>{e[n]=e=>t&&e.properties[l.SELECTED]?this._modes[t].styleFeature.bind(this._modes[t])(e):this._modes[n].styleFeature.bind(this._modes[n])(e)}),e}featuresAtLocation({lng:e,lat:t},n){let r=n&&n.pointerDistance!==void 0?n.pointerDistance:30,i=!n||n.ignoreSelectFeatures===void 0||n.ignoreSelectFeatures,a=!(!n||n.ignoreCoordinatePoints===void 0)&&n.ignoreCoordinatePoints,o=!(!n||n.ignoreCurrentlyDrawing===void 0)&&n.ignoreCurrentlyDrawing,s=!(!n||n.ignoreClosingPoints===void 0)&&n.ignoreClosingPoints,c=!(!n||n.ignoreSnappingPoints===void 0)&&n.ignoreSnappingPoints,d=this._adapter.unproject.bind(this._adapter),f=this._adapter.project.bind(this._adapter),p=f(e,t),m=Te({unproject:d,point:p,pointerDistance:r});return this._store.search(m).filter(d=>{if(i&&(d.properties[l.MID_POINT]||d.properties[l.SELECTION_POINT])||a&&d.properties[u.COORDINATE_POINT]||s&&d.properties[u.CLOSING_POINT]||o&&d.properties[u.CURRENTLY_DRAWING]||c&&d.properties[u.SNAPPING_POINT])return!1;if(d.geometry.type===`Point`){let e=d.geometry.coordinates;return P(p,f(e[0],e[1]))<r}if(d.geometry.type===`LineString`){let e=d.geometry.coordinates;for(let t=0;t<e.length-1;t++){let n=e[t],i=e[t+1];if(_t(p,f(n[0],n[1]),f(i[0],i[1]))<r)return!0}return!1}if(gt([e,t],d.geometry.coordinates))return!0;if(n!=null&&n.includePolygonsWithinPointerDistance){let e=d.geometry.coordinates;for(let t of e)for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];if(_t(p,f(n[0],n[1]),f(i[0],i[1]))<r)return!0}}return!1}).map(r=>{if(n==null||!n.addClosestCoordinateInfoToProperties)return r;let i;if(r.geometry.type===`Polygon`)i=r.geometry.coordinates[0].slice(0,-1);else{if(r.geometry.type!==`LineString`)return r;i=r.geometry.coordinates}let a,o=-1,s=1/0;for(let e=0;e<i.length;e++){let t=i[e],n=P(f(t[0],t[1]),p);n<s&&(o=e,s=n,a=t)}return r.properties.closestCoordinateIndexToEvent=o,r.properties.closestCoordinatePixelDistanceToEvent=s,r.properties.closestCoordinateDistanceKmToEvent=b(a,[e,t]),r})}getSelectModeOrThrow(e=void 0){let t=this.getSelectMode({switchToSelectMode:!0,selectMode:e});if(!t)throw Error(`No select mode defined in instance`);return t}getSelectMode({switchToSelectMode:e,selectMode:t}){this.checkEnabled();let n=this.getMode();if(this._instanceSelectModes.length===0)return null;if(t!==void 0&&!this._instanceSelectModes.includes(t))throw Error(`No select mode with this name present: ${t}`);let r;return r=t===void 0?this._instanceSelectModes.includes(n)?n:this._instanceSelectModes[0]:t,e&&n!==r&&this.setMode(r),this._modes[r]}isGuidanceFeature(e){return!!(e.properties[l.MID_POINT]||e.properties[l.SELECTION_POINT]||e.properties[u.COORDINATE_POINT]||e.properties[u.SNAPPING_POINT])}setModeStyles(e,t){if(this.checkEnabled(),!this._modes[e])throw Error(`No mode with this name present`);this._modes[e].styles=t}updateModeOptions(e,t){if(this.checkEnabled(),!this._modes[e])throw Error(`No mode with this name present`);this._modes[e].updateOptions(t)}getSnapshot(){return this._store.copyAll()}getSnapshotFeature(e){if(this._store.has(e))return this._store.copy(e)}clear(){this.checkEnabled(),this._adapter.clear()}get enabled(){return this._enabled}set enabled(e){throw Error(`Enabled is read only`)}getMode(){return this._mode.mode}getModeState(){return this._mode.state}setMode(e){if(this.checkEnabled(),!this._modes[e])throw Error(`No mode with this name present`);this._mode.stop(),this._mode=this._modes[e],this._mode.start()}removeFeatures(e){this.checkEnabled();let t=[],n=[],r;e.forEach(e=>{if(!this._store.has(e))throw Error(`No feature with id ${e}, can not delete`);let i=this._store.getPropertiesCopy(e);i[l.SELECTED]&&this.deselectFeature(e),i[u.CURRENTLY_DRAWING]&&this._modes[i.mode]?r=i.mode:(i[u.COORDINATE_POINT_IDS]&&t.push(...i[u.COORDINATE_POINT_IDS]),n.push(e))}),this._store.delete([...n,...t],{origin:`api`}),r&&this._modes[r]&&this._modes[r].cleanUp()&&this._modes[r].cleanUp()}selectFeature(e,t){this.getSelectModeOrThrow(t).selectFeature(e)}deselectFeature(e){this.getSelectModeOrThrow().deselectFeature(e)}getFeatureId(){return this._store.getId()}hasFeature(e){return this._store.has(e)}checkIsReservedProperty(e){return![...Object.values(l),...Object.values(u)].includes(e)}updateFeatureProperties(e,t){var n;if(!this._store.has(e))throw Error(`No feature with id ${e} present in store`);let r=this._store.copy(e);if(this.isGuidanceFeature(r))throw Error(`Guidance features are not allowed to be updated directly.`);let i=r.properties.mode;if(!this._modes[i])throw Error(`No mode with name ${i} present in instance`);let a=Object.entries(t);a.forEach(([e,t])=>{if(!this.checkIsReservedProperty(e))throw Error(`You are trying to update a reserved property name: ${e}. Please choose another name.`);if(t!==void 0&&!hn(t))throw Error(`Invalid JSON value provided for property ${e}`)}),this._store.updateProperty(a.map(([e,t])=>({id:r.id,property:e,value:t})),{origin:`api`}),(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction()}updateFeatureGeometry(e,t){var r;if(!this._store.has(e))throw Error(`No feature with id ${e} present in store`);let i=this._store.copy(e);if(this.isGuidanceFeature(i))throw Error(`Guidance features are not allowed to be updated directly.`);if(!(i&&t&&t.type&&t.coordinates))throw Error(`Invalid geometry provided`);if(t.type!==i.geometry.type)throw Error(`Geometry type mismatch: expected ${i.geometry.type}, got ${t.type}`);let a=i.properties.mode,o=this._modes[a];if(!o)throw Error(`No mode with name ${a} present in instance`);let s=n({},i,{geometry:t}),c=o.validateFeature(s);if(!c.valid)throw Error(`Feature validation failed: ${c.reason||`Unknown reason`}`);if(this._store.updateGeometry([{id:i.id,geometry:t}],{origin:`api`}),o.afterFeatureUpdated){o.afterFeatureUpdated(s);let e=s.properties[l.SELECTED],t=this.getSelectMode({switchToSelectMode:!1});t&&e&&t.afterFeatureUpdated(s)}(r=this.undoRedoCoordinator)==null||r.emitHistoryPushForCompletedAction()}transformFeatureGeometry(e,t){var n;if(!this._store.has(e))throw Error(`No feature with id ${e} present in store`);let r=this._store.copy(e);if(this.isGuidanceFeature(r))throw Error(`Guidance features are not allowed to be updated directly.`);let i=r.properties.mode,a=this._modes[i];if(!a)throw Error(`No mode with name ${i} present in instance`);let o;if(r.geometry.type===`Polygon`)o=r.geometry.coordinates[0];else{if(r.geometry.type!==`LineString`)throw Error(`Feature geometry type ${r.geometry.type} is not supported for transformation`);o=r.geometry.coordinates}if(t.projection!=`web-mercator`)throw Error(`Projection ${t.projection} is not currently supported for transformation`);if(t.type===`scale`){let{x:e,y:n}=E(t.origin[0],t.origin[1]);Et({coordinates:o,originX:e,originY:n,xScale:t.options.xScale||1,yScale:t.options.yScale||1})}else t.type===`rotate`&&(r=St(r,t.options.angle||0),o=r.geometry.type===`Polygon`?r.geometry.coordinates[0]:r.geometry.coordinates);if(o=o.map(e=>[w(e[0],this._adapter.getCoordinatePrecision()),w(e[1],this._adapter.getCoordinatePrecision())]),r.geometry.coordinates=r.geometry.type===`Polygon`?[o]:o,this._store.updateGeometry([{id:r.id,geometry:r.geometry}],{origin:`api`}),a.afterFeatureUpdated){a.afterFeatureUpdated(r);let e=r.properties[l.SELECTED],t=this.getSelectMode({switchToSelectMode:!1});t&&e&&t.afterFeatureUpdated(r)}(n=this.undoRedoCoordinator)==null||n.emitHistoryPushForCompletedAction()}undo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.undo()}canUndo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.canUndo()}canRedo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.canRedo()}redo(){return this.checkEnabled(),!!this.undoRedoCoordinator&&this.undoRedoCoordinator.redo()}clearUndoRedoHistory(){this.checkEnabled(),this.undoRedoCoordinator&&this.undoRedoCoordinator.clearHistory()}addFeatures(e){return this.checkEnabled(),e.length===0?[]:this._store.load(e,e=>{if(p(e)){let t=e.properties.mode,n=this._modes[t];if(!n)return{id:e.id,valid:!1,reason:`${t} mode is not in the list of instantiated modes`};let r=n.validateFeature.bind(n)(e);return{id:e.id,valid:r.valid,reason:r.reason?r.reason:r.valid?void 0:`Feature is invalid`}}return{id:e.id,valid:!1,reason:`Mode property does not exist`}},e=>{if(p(e)){let t=this._modes[e.properties.mode];t&&t.afterFeatureAdded&&t.afterFeatureAdded(e)}},{origin:`api`})}start(){this._enabled||(this._enabled=!0,this._adapter.register({onReady:()=>{this._eventListeners.ready.forEach(e=>{e()})},getState:()=>this._mode.state,onClick:e=>{let t=this.drawingUndoRedo?this.drawingUndoRedo.getHistorySizes():{undoSize:0,redoSize:0};this._mode.onClick(e),this.emitDrawingPushIfHistoryChanged(t)},onMouseMove:e=>{this._mode.onMouseMove(e)},onKeyDown:e=>{this.handleUndoRedoKeyboardShortcut(e)||this._mode.onKeyDown(e)},onKeyUp:e=>{let t=this.drawingUndoRedo?this.drawingUndoRedo.getHistorySizes():{undoSize:0,redoSize:0};this._mode.onKeyUp(e),this.emitDrawingPushIfHistoryChanged(t)},onDragStart:(e,t)=>{this._mode.onDragStart(e,t)},onDrag:(e,t)=>{this._mode.onDrag(e,t)},onDragEnd:(e,t)=>{this._mode.onDragEnd(e,t)},onClear:()=>{this._mode.cleanUp(),this._store.clear({origin:`api`})}}))}getFeaturesAtLngLat(e,t){let{lng:n,lat:r}=e;return this.featuresAtLocation({lng:n,lat:r},t)}getFeaturesAtPointerEvent(e,t){let n=this._adapter.getLngLatFromEvent.bind(this._adapter)(e);return n===null?[]:this.featuresAtLocation(n,t)}stop(){this._enabled&&(this._enabled=!1,this._adapter.unregister())}on(e,t){let n=this._eventListeners[e];n.includes(t)||n.push(t)}off(e,t){let n=this._eventListeners[e];n.includes(t)&&n.splice(n.indexOf(t),1)}};function On(){return On=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},On.apply(null,arguments)}var kn=class extends dn.TerraDrawBaseAdapter{constructor(e){super(e),this._renderBeforeLayerId=void 0,this._prefixId=void 0,this._initialDragPan=void 0,this._initialDragRotate=void 0,this._nextRender=void 0,this._map=void 0,this._container=void 0,this.changedIds={deletion:!1,points:!1,linestrings:!1,polygons:!1,styling:!1},this._map=e.map,this._container=this._map.getContainer(),this._initialDragRotate=this._map.dragRotate.isEnabled(),this._initialDragPan=this._map.dragPan.isEnabled(),this._renderBeforeLayerId=e.renderBelowLayerId,this._prefixId=e.prefixId||`td`}hashCode(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)}resizeImage(e,t,n,r){let i=new Image;i.crossOrigin=`anonymous`,i.onload=()=>{let e=document.createElement(`canvas`);e.width=t,e.height=n;let a=e.getContext(`2d`);if(!a)throw Error(`Could not get canvas context`);a.drawImage(i,0,0,t,n),r(e.toDataURL())},i.src=e}toGlDashArrayFromPixels(e,t){if(!e)return null;let[n,r]=e;if(!Number.isFinite(n)||!Number.isFinite(r)||n<0||r<0)return null;let i=Math.max(1e-4,t);return[n/i,r/i]}isMapLibreAtLeast(e){let t=this._map.version;if(!t)return!1;let n=e=>{let t=e.match(/(\d+)\.(\d+)\.(\d+)/);return t?[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)]:null},r=n(t),i=n(e);if(!r||!i)return!0;let[a,o,s]=r,[c,l,u]=i;return a===c?o===l?s>=u:o>l:a>c}_addGeoJSONSource(e,t){this._map.addSource(e,{type:`geojson`,data:{type:`FeatureCollection`,features:t},tolerance:0})}_addFillLayer(e){return this._map.addLayer({id:e,source:e,type:`fill`,layout:{"fill-sort-key":[`get`,`zIndex`]},paint:{"fill-color":[`get`,`polygonFillColor`],"fill-opacity":[`get`,`polygonFillOpacity`]}})}_addFillOutlineLayer(e){return this._map.addLayer({id:e+`-outline`,source:e,type:`line`,layout:{"line-sort-key":[`get`,`zIndex`]},paint:{"line-width":[`get`,`polygonOutlineWidth`],"line-color":[`get`,`polygonOutlineColor`],"line-opacity":[`get`,`polygonOutlineOpacity`]}})}_addLineLayer(e){let t={};return this.isMapLibreAtLeast(`5.8.0`)&&(t[`line-dasharray`]=[`coalesce`,[`get`,`lineStringDash`],[`literal`,[1,0]]]),this._map.addLayer({id:e,source:e,type:`line`,layout:{"line-sort-key":[`get`,`zIndex`]},paint:On({},t,{"line-width":[`get`,`lineStringWidth`],"line-color":[`get`,`lineStringColor`],"line-opacity":[`get`,`lineStringOpacity`]})})}_addPointLayer(e){return this._map.addLayer({id:e,source:e,type:`circle`,layout:{"circle-sort-key":[`get`,`zIndex`]},paint:{"circle-stroke-color":[`get`,`pointOutlineColor`],"circle-stroke-width":[`get`,`pointOutlineWidth`],"circle-stroke-opacity":[`get`,`pointOutlineOpacity`],"circle-radius":[`get`,`pointWidth`],"circle-color":[`get`,`pointColor`],"circle-opacity":[`get`,`pointOpacity`]}})}_addMarkerLayer(e){return this._map.addLayer({id:e+`-marker`,source:e,type:`symbol`,filter:[`has`,`markerId`],layout:{"icon-image":[`image`,[`get`,`markerId`]],"icon-anchor":`bottom`,"icon-allow-overlap":!0}})}_addLayer(e,t){t===`Point`&&(this._addPointLayer(e),this._addMarkerLayer(e)),t===`LineString`&&this._addLineLayer(e),t===`Polygon`&&(this._addFillLayer(e),this._addFillOutlineLayer(e))}_addGeoJSONLayer(e,t){let n=`${this._prefixId}-${e.toLowerCase()}`;return this._addGeoJSONSource(n,t),this._addLayer(n,e),n}_setGeoJSONLayerData(e,t){let n=`${this._prefixId}-${e.toLowerCase()}`;return this._map.getSource(n).setData({type:`FeatureCollection`,features:t}),n}updateChangedIds(e){[...e.updated,...e.created].forEach(e=>{e.geometry.type===`Point`?this.changedIds.points=!0:e.geometry.type===`LineString`?this.changedIds.linestrings=!0:e.geometry.type===`Polygon`&&(this.changedIds.polygons=!0)}),e.deletedIds.length>0&&(this.changedIds.deletion=!0),e.created.length===0&&e.updated.length===0&&e.deletedIds.length===0&&(this.changedIds.styling=!0)}getLngLatFromEvent(e){let{left:t,top:n}=this._container.getBoundingClientRect();return this.unproject(e.clientX-t,e.clientY-n)}getMapEventElement(){return this._map.getCanvas()}setDraggability(e){e?(this._initialDragRotate&&this._map.dragRotate.enable(),this._initialDragPan&&this._map.dragPan.enable()):(this._initialDragRotate&&this._map.dragRotate.disable(),this._initialDragPan&&this._map.dragPan.disable())}project(e,t){let{x:n,y:r}=this._map.project({lng:e,lat:t});return{x:n,y:r}}unproject(e,t){let{lng:n,lat:r}=this._map.unproject({x:e,y:t});return{lng:n,lat:r}}setCursor(e){let t=this._map.getCanvas();e===`unset`?t.style.removeProperty(`cursor`):t.style.cursor=e}setDoubleClickToZoom(e){e?this._map.doubleClickZoom.enable():this._map.doubleClickZoom.disable()}render(e,t){this.updateChangedIds(e),this._nextRender&&cancelAnimationFrame(this._nextRender),this._nextRender=requestAnimationFrame(()=>{if(!this._currentModeCallbacks)return;let n=[...e.created,...e.updated,...e.unchanged],r=[],i=[],a=[];for(let e=0;e<n.length;e++){let o=n[e],{properties:s}=o,c=t[s.mode](o);if(s.zIndex=c.zIndex,s.zIndex=c.zIndex,o.geometry.type===`Point`){s.pointColor=c.pointColor,s.pointOutlineColor=c.pointOutlineColor,s.pointOutlineWidth=c.pointOutlineWidth;let e=c.pointOutlineOpacity;s.pointOutlineOpacity=e===void 0?1:e,s.pointWidth=c.pointWidth;let t=c.pointOpacity;if(s.pointOpacity=t===void 0?1:t,c.markerUrl&&c.markerWidth&&c.markerHeight){let e=`marker-${this.hashCode(c.markerUrl)}`;this._map.hasImage(e)||this.resizeImage(c.markerUrl,c.markerWidth,c.markerHeight,t=>{this._map.loadImage(t).then(t=>{this._map.hasImage(e)||this._map.addImage(e,t.data)})}),s.markerId=e,s.pointWidth=0}r.push(o)}else if(o.geometry.type===`LineString`){s.lineStringDash=this.toGlDashArrayFromPixels(c.lineStringDash,c.lineStringWidth),s.lineStringColor=c.lineStringColor,s.lineStringWidth=c.lineStringWidth;let e=c.lineStringOpacity;s.lineStringOpacity=e===void 0?1:e,i.push(o)}else if(o.geometry.type===`Polygon`){let e=c.polygonOutlineOpacity;s.polygonFillColor=c.polygonFillColor,s.polygonFillOpacity=c.polygonFillOpacity,s.polygonOutlineOpacity=e===void 0?1:e,s.polygonOutlineColor=c.polygonOutlineColor,s.polygonOutlineWidth=c.polygonOutlineWidth,a.push(o)}}let o=this.changedIds.deletion||this.changedIds.styling,s=o||this.changedIds.linestrings,c=o||this.changedIds.polygons;(o||this.changedIds.points)&&this._setGeoJSONLayerData(`Point`,r),s&&this._setGeoJSONLayerData(`LineString`,i),c&&this._setGeoJSONLayerData(`Polygon`,a),this.changedIds={points:!1,linestrings:!1,polygons:!1,deletion:!1,styling:!1}})}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this._nextRender&&=(cancelAnimationFrame(this._nextRender),void 0),this._setGeoJSONLayerData(`Point`,[]),this._setGeoJSONLayerData(`LineString`,[]),this._setGeoJSONLayerData(`Polygon`,[]))}getCoordinatePrecision(){return super.getCoordinatePrecision()}unregister(){super.unregister(),this.changedIds={points:!1,linestrings:!1,polygons:!1,deletion:!1,styling:!1},this._map.removeLayer(`${this._prefixId}-point`),this._map.removeLayer(`${this._prefixId}-point-marker`),this._map.removeSource(`${this._prefixId}-point`),this._map.removeLayer(`${this._prefixId}-linestring`),this._map.removeSource(`${this._prefixId}-linestring`),this._map.removeLayer(`${this._prefixId}-polygon`),this._map.removeLayer(`${this._prefixId}-polygon-outline`),this._map.removeSource(`${this._prefixId}-polygon`)}register(e){var t;super.register(e);let n=this._addGeoJSONLayer(`Polygon`,[]),r=this._addGeoJSONLayer(`LineString`,[]),i=this._addGeoJSONLayer(`Point`,[]);var a;this._renderBeforeLayerId&&(this._map.moveLayer(i,this._renderBeforeLayerId),this._map.moveLayer(r,i),this._map.moveLayer(`${n}-outline`,r),this._map.moveLayer(n,`${n}-outline`)),(t=this._currentModeCallbacks)!=null&&t.onReady&&((a=this._currentModeCallbacks)==null||a.onReady())}},An=[`render`,`point`,`marker`,`linestring`,`polygon`,`rectangle`,`circle`,`freehand`,`freehand-linestring`,`angled-rectangle`,`sensor`,`sector`,`select`,`delete-selection`,`delete`,`undo`,`redo`,`download`],jn=[`render`,`routing`,`time-isochrone`,`distance-isochrone`,`select`,`delete-selection`,`delete`,`download`,`settings`],Mn={modes:[`render`,`point`,`marker`,`linestring`,`polygon`,`rectangle`,`angled-rectangle`,`sensor`,`sector`,`circle`,`freehand`,`freehand-linestring`,`select`,`delete-selection`,`delete`,`undo`,`redo`,`download`],open:!1},Y={kilometer:`km`,meter:`m`,centimeter:`cm`,mile:`mi`,foot:`ft`,inch:`in`,"square meters":`m²`,"square kilometers":`km²`,ares:`a`,hectares:`ha`,"square feet":`ft²`,"square yards":`yd²`,acres:`acres`,"square miles":`mi²`},Nn=`data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3csvg%20xmlns:dc='http://purl.org/dc/elements/1.1/'%20xmlns:cc='http://creativecommons.org/ns%23'%20xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns%23'%20xmlns:svg='http://www.w3.org/2000/svg'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd'%20xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape'%20inkscape:version='1.0%20(4035a4fb49,%202020-05-01)'%20sodipodi:docname='poi.svg'%20id='svg4460'%20height='100'%20width='100'%20version='1.1'%3e%3csodipodi:namedview%20inkscape:document-rotation='0'%20inkscape:current-layer='svg4460'%20inkscape:window-maximized='1'%20inkscape:window-y='-8'%20inkscape:window-x='-8'%20inkscape:cy='70.031285'%20inkscape:cx='-78.460726'%20inkscape:zoom='2.02'%20showgrid='false'%20id='namedview11'%20inkscape:window-height='1017'%20inkscape:window-width='1920'%20inkscape:pageshadow='2'%20inkscape:pageopacity='0'%20guidetolerance='10'%20gridtolerance='10'%20objecttolerance='10'%20borderopacity='1'%20bordercolor='%23666666'%20pagecolor='%23ffffff'%20/%3e%3cdefs%20id='defs4462'%20/%3e%3cmetadata%20id='metadata4465'%3e%3crdf:RDF%3e%3ccc:Work%20rdf:about=''%3e%3cdc:format%3eimage/svg+xml%3c/dc:format%3e%3cdc:type%20rdf:resource='http://purl.org/dc/dcmitype/StillImage'%20/%3e%3cdc:title%3e%3c/dc:title%3e%3c/cc:Work%3e%3c/rdf:RDF%3e%3c/metadata%3e%3cpath%20d='M%2050.001528,3.3861402e-7%20C%2030.763177,3.3861402e-7%2015,15.718144%2015,34.901534%20c%200,7.432782%202.373565,14.339962%206.391689,20.019029%20l%2024.338528,42.073163%20c%203.40849,4.452814%205.674917,3.607154%208.509014,-0.23458%20L%2081.083105,51.075788%20C%2081.625418,50.0948%2082.050328,49.050173%2082.421327,47.983517%2084.078241,43.936622%2085.000002,39.521943%2085,34.901534%2085,15.718144%2069.23988,3.3861402e-7%2050.001528,3.3861402e-7%20Z%20m%200,16.35400066138598%20c%2010.359296,0%2018.597616,8.21783%2018.597618,18.547533%200,10.329703%20-8.238322,18.544487%20-18.597618,18.544487%20-10.359299,0%20-18.600672,-8.214784%20-18.600672,-18.544487%200,-10.329703%208.241373,-18.547533%2018.600672,-18.547533%20z'%20style='fill:rgb(95,%2099,%20104);stroke-width:4.26019'%20id='path4135'%20/%3e%3c/svg%3e`,Pn={url:`https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png`,encoding:`terrarium`,tileSize:256,minzoom:5,maxzoom:15,tms:!1},Fn={url:`https://tiles.mapterhorn.com/{z}/{x}/{y}.webp`,encoding:`terrarium`,tileSize:512,minzoom:0,maxzoom:12,tms:!1},In={modes:[`render`,`point`,`marker`,`linestring`,`polygon`,`rectangle`,`angled-rectangle`,`sensor`,`sector`,`circle`,`freehand`,`freehand-linestring`,`select`,`delete-selection`,`delete`,`undo`,`redo`,`download`],open:!1,modeOptions:{point:new nt({editable:!0,styles:{pointColor:`#FFFFFF`,pointWidth:5,pointOutlineColor:`#666666`,pointOutlineWidth:1}}),marker:new _n({editable:!0,styles:{markerUrl:Nn,markerWidth:27,markerHeight:27}}),linestring:new Ye({editable:!0,styles:{lineStringColor:`#666666`,lineStringWidth:2,closingPointColor:`#FFFFFF`,closingPointWidth:3,closingPointOutlineColor:`#666666`,closingPointOutlineWidth:1}}),polygon:new at({editable:!0,styles:{fillColor:`#EDEFF0`,fillOpacity:.7,outlineColor:`#666666`,outlineWidth:2,closingPointColor:`#FAFAFA`,closingPointWidth:3,closingPointOutlineColor:`#666666`,closingPointOutlineWidth:1}}),rectangle:new ct({styles:{fillColor:`#EDEFF0`,fillOpacity:.7,outlineColor:`#666666`,outlineWidth:2}}),"angled-rectangle":new nn({styles:{fillColor:`#EDEFF0`,fillOpacity:.7,outlineColor:`#666666`,outlineWidth:2}}),circle:new be({styles:{fillColor:`#EDEFF0`,fillOpacity:.7,outlineColor:`#666666`,outlineWidth:2}}),freehand:new we({styles:{fillColor:`#EDEFF0`,fillOpacity:.7,outlineColor:`#666666`,outlineWidth:2,closingPointColor:`#FAFAFA`,closingPointWidth:3,closingPointOutlineColor:`#666666`,closingPointOutlineWidth:1}}),"freehand-linestring":new mn({styles:{lineStringColor:`#666666`,lineStringWidth:2,closingPointColor:`#FFFFFF`,closingPointWidth:3,closingPointOutlineColor:`#666666`,closingPointOutlineWidth:1}}),sensor:new un({styles:{fillColor:`#EDEFF0`,fillOpacity:.7,outlineColor:`#666666`,outlineWidth:2,centerPointColor:`#FAFAFA`,centerPointWidth:3,centerPointOutlineColor:`#666666`,centerPointOutlineWidth:1}}),sector:new sn({styles:{fillColor:`#EDEFF0`,fillOpacity:.7,outlineColor:`#666666`,outlineWidth:2}}),select:new At({flags:{point:{feature:{draggable:!1}},marker:{feature:{draggable:!1}},polygon:{feature:{draggable:!0,rotateable:!0,scaleable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}},linestring:{feature:{draggable:!0,rotateable:!0,scaleable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}},freehand:{feature:{draggable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}},"freehand-linestring":{feature:{draggable:!0,rotateable:!0,scaleable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}},circle:{feature:{draggable:!0,coordinates:{resizable:`center`,deletable:!1,midpoints:!1}}},rectangle:{feature:{draggable:!0,rotateable:!0,coordinates:{resizable:`opposite`,deletable:!1,midpoints:!1}}},"angled-rectangle":{feature:{draggable:!0,rotateable:!0,coordinates:{resizable:`opposite`,deletable:!1,midpoints:!1}}},sensor:{feature:{draggable:!0,rotateable:!0,scaleable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}},sector:{feature:{draggable:!0,rotateable:!0,scaleable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}}}})},pointLayerLabelSpec:{id:`{prefix}-point-label`,type:`symbol`,source:`{prefix}-point`,filter:[`all`,[`==`,`$type`,`Point`],[`any`,[`==`,`mode`,`point`],[`==`,`mode`,`marker`]]],layout:{"text-field":[`case`,[`all`,[`has`,`elevation`],[`>`,[`get`,`elevation`],0]],[`concat`,`Alt. `,[`to-string`,[`floor`,[`get`,`elevation`]]],` `,[`get`,`elevationUnit`]],``],"symbol-placement":`point`,"text-size":[`interpolate`,[`linear`],[`zoom`],5,10,10,12,13,14,14,16,18,18],"text-overlap":`always`,"text-variable-anchor":[`left`,`right`,`top`,`bottom`],"text-radial-offset":.5,"text-justify":`center`,"text-letter-spacing":.05},paint:{"text-halo-color":`#F7F7F7`,"text-halo-width":2,"text-color":`#232E3D`}},lineLayerLabelSpec:{id:`{prefix}-line-label`,type:`symbol`,source:`{prefix}-line-source`,filter:[`==`,`$type`,`Point`],layout:{"text-field":[`concat`,[`to-string`,[`get`,`distance`]],` `,[`get`,`unit`],[`case`,[`==`,[`get`,`total`],0],``,[`concat`,`
(`,[`to-string`,[`get`,`total`]],` `,[`get`,`totalUnit`],`)`]],[`case`,[`all`,[`has`,`elevation`],[`>`,[`get`,`elevation`],0]],[`concat`,`
Alt. `,[`to-string`,[`floor`,[`get`,`elevation`]]],` `,[`get`,`elevationUnit`]],``]],"symbol-placement":`point`,"text-size":[`interpolate`,[`linear`],[`zoom`],5,10,10,12,13,14,14,16,18,18],"text-overlap":`always`,"text-variable-anchor":[`left`,`right`,`top`,`bottom`],"text-radial-offset":.5,"text-justify":`center`,"text-letter-spacing":.05},paint:{"text-halo-color":`#F7F7F7`,"text-halo-width":2,"text-color":`#232E3D`}},routingLineLayerNodeSpec:{id:`{prefix}-line-node`,type:`circle`,source:`{prefix}-line-source`,filter:[`==`,`$type`,`Point`],layout:{},paint:{"circle-radius":3,"circle-color":`#FFFFFF`,"circle-stroke-color":`#000000`,"circle-stroke-width":1}},polygonLayerSpec:{id:`{prefix}-polygon-label`,type:`symbol`,source:`{prefix}-polygon-source`,filter:[`==`,`$type`,`Point`],layout:{"text-field":[`concat`,[`to-string`,[`get`,`area`]],` `,[`get`,`unit`]],"symbol-placement":`point`,"text-size":[`interpolate`,[`linear`],[`zoom`],5,10,10,12,13,14,14,16,18,18],"text-overlap":`always`,"text-letter-spacing":.05},paint:{"text-halo-color":`#F7F7F7`,"text-halo-width":2,"text-color":`#232E3D`}},computeElevation:!1,terrainSource:Fn,measureUnitType:`metric`,distancePrecision:2,distanceUnit:void 0,areaPrecision:2,areaUnit:void 0,measureUnitSymbols:JSON.parse(JSON.stringify(Y)),elevationCacheConfig:{enabled:!0,maxSize:1e3,ttl:3600*1e3,precision:9},adapterOptions:{prefixId:`td-measure`}},X={modes:[`render`,`routing`,`time-isochrone`,`distance-isochrone`,`select`,`delete-selection`,`delete`,`download`,`settings`],open:!1,modeOptions:{"time-isochrone":new nt({modeName:`time-isochrone`,editable:!1,styles:{pointColor:`#FFFFFF`,pointWidth:5,pointOutlineColor:`#666666`,pointOutlineWidth:1}}),"distance-isochrone":new nt({modeName:`distance-isochrone`,editable:!1,styles:{pointColor:`#FFFFFF`,pointWidth:5,pointOutlineColor:`#666666`,pointOutlineWidth:1}}),routing:new Ye({modeName:`routing`,editable:!1,styles:{lineStringColor:`#FF0000`,lineStringWidth:2,closingPointColor:`#FF0000`,closingPointWidth:3,closingPointOutlineColor:`#666666`,closingPointOutlineWidth:1}}),select:new At({flags:{"time-isochrone":{feature:{draggable:!1}},"distance-isochrone":{feature:{draggable:!1}},routing:{feature:{draggable:!1,rotateable:!1,scaleable:!1,coordinates:{midpoints:!1,draggable:!1,deletable:!1}}}}}),settings:new V({modeName:`settings`,styles:{}})},valhallaOptions:{url:``,routingOptions:{costingModel:`auto`,distanceUnit:`kilometers`},isochroneOptions:{timeCostingModel:`auto`,distanceCostingModel:`auto`,contours:[{time:3,distance:1,color:`#ff0000`},{time:5,distance:2,color:`#ffff00`},{time:10,distance:3,color:`#0000ff`},{time:15,distance:4,color:`#ff00ff`}]}},adapterOptions:{prefixId:`td-valhalla`},routingLineLayerNodeLabelSpec:{id:`{prefix}-routing-node-label`,type:`symbol`,source:`{prefix}-routing-source`,filter:[`==`,`$type`,`Point`],layout:{"text-field":[`case`,[`all`,[`has`,`distance`],[`has`,`distance_unit`],[`has`,`time`]],[`concat`,[`to-string`,[`get`,`text`]],`
`,[`to-string`,[`/`,[`round`,[`*`,[`get`,`distance`],10]],10]],[`to-string`,[`get`,`distance_unit`]],`
`,[`to-string`,[`get`,`time`]],`min`],[`all`,[`has`,`costingModel`]],[`concat`,[`to-string`,[`get`,`text`]],`
(`,[`to-string`,[`get`,`costingModel`]],`)`],[`concat`,[`to-string`,[`get`,`text`]]]],"symbol-placement":`point`,"text-size":[`interpolate`,[`linear`],[`zoom`],5,10,10,12,13,14,14,16,18,18],"text-overlap":`always`,"text-variable-anchor":[`left`,`right`,`top`,`bottom`],"text-radial-offset":.5,"text-justify":`left`,"text-letter-spacing":.05},paint:{"text-halo-color":`#F7F7F7`,"text-halo-width":2,"text-color":`#232E3D`}},routingLineLayerNodeSpec:{id:`{prefix}-routing-node`,type:`circle`,source:`{prefix}-routing-source`,filter:[`==`,`$type`,`Point`],layout:{},paint:{"circle-radius":3,"circle-color":[`case`,[`==`,[`get`,`text`],`Start`],`#0000FF`,[`==`,[`get`,`text`],`Goal`],`#FFFF00`,`#FFFFFF`],"circle-stroke-color":`#000000`,"circle-stroke-width":1}},timeIsochronePolygonLayerSpec:{id:`{prefix}-time-isochrone-polygon`,type:`fill`,source:`{prefix}-time-isochrone-source`,layout:{},paint:{"fill-color":[`get`,`fillColor`],"fill-opacity":[`get`,`fillOpacity`]}},timeIsochroneLineLayerSpec:{id:`{prefix}-time-isochrone-line`,type:`line`,source:`{prefix}-time-isochrone-source`,layout:{"line-join":`round`,"line-cap":`round`},paint:{"line-color":[`get`,`fillColor`],"line-width":3}},timeIsochroneLabelLayerSpec:{id:`{prefix}-time-isochrone-label`,type:`symbol`,source:`{prefix}-time-isochrone-source`,layout:{"symbol-placement":`line`,"text-pitch-alignment":`viewport`,"text-field":[`concat`,[`get`,`contour`],` `,`min`],"text-size":12,"symbol-spacing":100,"text-max-angle":45},paint:{"text-color":`rgb(0, 0, 0)`,"text-halo-width":1,"text-halo-color":`rgb(255, 255, 255)`}},distanceIsochronePolygonLayerSpec:{id:`{prefix}-distance-isochrone-polygon`,type:`fill`,source:`{prefix}-distance-isochrone-source`,layout:{},paint:{"fill-color":[`get`,`fillColor`],"fill-opacity":[`get`,`fillOpacity`]}},distanceIsochroneLineLayerSpec:{id:`{prefix}-distance-isochrone-line`,type:`line`,source:`{prefix}-distance-isochrone-source`,layout:{"line-join":`round`,"line-cap":`round`},paint:{"line-color":[`get`,`fillColor`],"line-width":3}},distanceIsochroneLabelLayerSpec:{id:`{prefix}-distance-isochrone-label`,type:`symbol`,source:`{prefix}-distance-isochrone-source`,layout:{"symbol-placement":`line`,"text-pitch-alignment":`viewport`,"text-field":[`concat`,[`get`,`contour`],` `,`km`],"text-size":12,"symbol-spacing":100,"text-max-angle":45},paint:{"text-color":`rgb(0, 0, 0)`,"text-halo-width":1,"text-halo-color":`rgb(255, 255, 255)`}}},Ln=`data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3csvg%20xmlns:dc='http://purl.org/dc/elements/1.1/'%20xmlns:cc='http://creativecommons.org/ns%23'%20xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns%23'%20xmlns:svg='http://www.w3.org/2000/svg'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd'%20xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape'%20inkscape:version='1.0%20(4035a4fb49,%202020-05-01)'%20sodipodi:docname='poi.svg'%20id='svg4460'%20height='100'%20width='100'%20version='1.1'%3e%3csodipodi:namedview%20inkscape:document-rotation='0'%20inkscape:current-layer='svg4460'%20inkscape:window-maximized='1'%20inkscape:window-y='-8'%20inkscape:window-x='-8'%20inkscape:cy='70.031285'%20inkscape:cx='-78.460726'%20inkscape:zoom='2.02'%20showgrid='false'%20id='namedview11'%20inkscape:window-height='1017'%20inkscape:window-width='1920'%20inkscape:pageshadow='2'%20inkscape:pageopacity='0'%20guidetolerance='10'%20gridtolerance='10'%20objecttolerance='10'%20borderopacity='1'%20bordercolor='%23666666'%20pagecolor='%23ffffff'%20/%3e%3cdefs%20id='defs4462'%20/%3e%3cmetadata%20id='metadata4465'%3e%3crdf:RDF%3e%3ccc:Work%20rdf:about=''%3e%3cdc:format%3eimage/svg+xml%3c/dc:format%3e%3cdc:type%20rdf:resource='http://purl.org/dc/dcmitype/StillImage'%20/%3e%3cdc:title%3e%3c/dc:title%3e%3c/cc:Work%3e%3c/rdf:RDF%3e%3c/metadata%3e%3cpath%20d='M%2050.001528,3.3861402e-7%20C%2030.763177,3.3861402e-7%2015,15.718144%2015,34.901534%20c%200,7.432782%202.373565,14.339962%206.391689,20.019029%20l%2024.338528,42.073163%20c%203.40849,4.452814%205.674917,3.607154%208.509014,-0.23458%20L%2081.083105,51.075788%20C%2081.625418,50.0948%2082.050328,49.050173%2082.421327,47.983517%2084.078241,43.936622%2085.000002,39.521943%2085,34.901534%2085,15.718144%2069.23988,3.3861402e-7%2050.001528,3.3861402e-7%20Z%20m%200,16.35400066138598%20c%2010.359296,0%2018.597616,8.21783%2018.597618,18.547533%200,10.329703%20-8.238322,18.544487%20-18.597618,18.544487%20-10.359299,0%20-18.600672,-8.214784%20-18.600672,-18.544487%200,-10.329703%208.241373,-18.547533%2018.600672,-18.547533%20z'%20style='fill:%233FB1CE;stroke-width:4.26019'%20id='path4135'%20/%3e%3c/svg%3e`,Rn=(e,t)=>{let n=t.updateType;return n===`finish`||n===`commit`?Qt(e):{valid:!0}},zn=()=>({render:new V({modeName:`render`,styles:{}}),point:new nt({editable:!0}),marker:new _n({editable:!0,styles:{markerUrl:Ln,markerWidth:27,markerHeight:27}}),linestring:new Ye({editable:!0}),polygon:new at({editable:!0,validation:Rn}),rectangle:new ct,"angled-rectangle":new nn,circle:new be,freehand:new we,"freehand-linestring":new mn,sensor:new un,sector:new sn,select:new At({flags:{point:{feature:{draggable:!0}},marker:{feature:{draggable:!0}},polygon:{feature:{draggable:!0,rotateable:!0,scaleable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}},linestring:{feature:{draggable:!0,rotateable:!0,scaleable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}},freehand:{feature:{draggable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}},"freehand-linestring":{feature:{draggable:!0,rotateable:!0,scaleable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}},circle:{feature:{draggable:!0,coordinates:{resizable:`center`,deletable:!1,midpoints:!1}}},rectangle:{feature:{draggable:!0,rotateable:!0,coordinates:{resizable:`opposite`,deletable:!1,midpoints:!1}}},"angled-rectangle":{feature:{draggable:!0,rotateable:!0,coordinates:{resizable:`opposite`,deletable:!1,midpoints:!1}}},sensor:{feature:{draggable:!0,rotateable:!0,scaleable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}},sector:{feature:{draggable:!0,rotateable:!0,scaleable:!0,coordinates:{midpoints:!0,draggable:!0,deletable:!0}}}}}),delete:new V({modeName:`delete`,styles:{}}),"delete-selection":new V({modeName:`delete-selection`,styles:{}}),download:new V({modeName:`download`,styles:{}}),undo:new V({modeName:`undo`,styles:{}}),redo:new V({modeName:`redo`,styles:{}})}),Z=6371008.8,Bn={centimeters:Z*100,centimetres:Z*100,degrees:360/(2*Math.PI),feet:Z*3.28084,inches:Z*39.37,kilometers:Z/1e3,kilometres:Z/1e3,meters:Z,metres:Z,miles:Z/1609.344,millimeters:Z*1e3,millimetres:Z*1e3,nauticalmiles:Z/1852,radians:1,yards:Z*1.0936};function Vn(e,t,n={}){let r={type:`Feature`};return(n.id===0||n.id)&&(r.id=n.id),n.bbox&&(r.bbox=n.bbox),r.properties=t||{},r.geometry=e,r}function Hn(e,t,n={}){if(!e)throw Error(`coordinates is required`);if(!Array.isArray(e))throw Error(`coordinates must be an Array`);if(e.length<2)throw Error(`coordinates must be at least 2 numbers long`);if(!Gn(e[0])||!Gn(e[1]))throw Error(`coordinates must contain numbers`);return Vn({type:`Point`,coordinates:e},t,n)}function Un(e,t=`kilometers`){let n=Bn[t];if(!n)throw Error(t+` units is invalid`);return e*n}function Wn(e){return e%360*Math.PI/180}function Gn(e){return!isNaN(e)&&e!==null&&!Array.isArray(e)}function Kn(e,t,n){if(e!==null)for(var r,i,a,o,s,c,l,u=0,d=0,f,p=e.type,m=p===`FeatureCollection`,h=p===`Feature`,g=m?e.features.length:1,_=0;_<g;_++){l=m?e.features[_].geometry:h?e.geometry:e,f=l?l.type===`GeometryCollection`:!1,s=f?l.geometries.length:1;for(var v=0;v<s;v++){var y=0,b=0;if(o=f?l.geometries[v]:l,o!==null){c=o.coordinates;var x=o.type;switch(u=n&&(x===`Polygon`||x===`MultiPolygon`)?1:0,x){case null:break;case`Point`:if(t(c,d,_,y,b)===!1)return!1;d++,y++;break;case`LineString`:case`MultiPoint`:for(r=0;r<c.length;r++){if(t(c[r],d,_,y,b)===!1)return!1;d++,x===`MultiPoint`&&y++}x===`LineString`&&y++;break;case`Polygon`:case`MultiLineString`:for(r=0;r<c.length;r++){for(i=0;i<c[r].length-u;i++){if(t(c[r][i],d,_,y,b)===!1)return!1;d++}x===`MultiLineString`&&y++,x===`Polygon`&&b++}x===`Polygon`&&y++;break;case`MultiPolygon`:for(r=0;r<c.length;r++){for(b=0,i=0;i<c[r].length;i++){for(a=0;a<c[r][i].length-u;a++){if(t(c[r][i][a],d,_,y,b)===!1)return!1;d++}b++}y++}break;case`GeometryCollection`:for(r=0;r<o.geometries.length;r++)if(Kn(o.geometries[r],t,n)===!1)return!1;break;default:throw Error(`Unknown Geometry Type`)}}}}}function qn(e,t){var n,r,i,a,o,s,c,l,u,d,f=0,p=e.type===`FeatureCollection`,m=e.type===`Feature`,h=p?e.features.length:1;for(n=0;n<h;n++){for(s=p?e.features[n].geometry:m?e.geometry:e,l=p?e.features[n].properties:m?e.properties:{},u=p?e.features[n].bbox:m?e.bbox:void 0,d=p?e.features[n].id:m?e.id:void 0,c=s?s.type===`GeometryCollection`:!1,o=c?s.geometries.length:1,i=0;i<o;i++){if(a=c?s.geometries[i]:s,a===null){if(t(null,f,l,u,d)===!1)return!1;continue}switch(a.type){case`Point`:case`LineString`:case`MultiPoint`:case`Polygon`:case`MultiLineString`:case`MultiPolygon`:if(t(a,f,l,u,d)===!1)return!1;break;case`GeometryCollection`:for(r=0;r<a.geometries.length;r++)if(t(a.geometries[r],f,l,u,d)===!1)return!1;break;default:throw Error(`Unknown Geometry Type`)}}f++}}function Jn(e,t,n){var r=n;return qn(e,function(e,i,a,o,s){r=i===0&&n===void 0?e:t(r,e,i,a,o,s)}),r}function Yn(e){return Jn(e,(e,t)=>e+Xn(t),0)}function Xn(e){let t=0,n;switch(e.type){case`Polygon`:return Zn(e.coordinates);case`MultiPolygon`:for(n=0;n<e.coordinates.length;n++)t+=Zn(e.coordinates[n]);return t;case`Point`:case`MultiPoint`:case`LineString`:case`MultiLineString`:return 0}return 0}function Zn(e){let t=0;if(e&&e.length>0){t+=Math.abs(er(e[0]));for(let n=1;n<e.length;n++)t-=Math.abs(er(e[n]))}return t}var Qn=Z*Z/2,$n=Math.PI/180;function er(e){let t=e.length-1;if(t<=2)return 0;let n=0,r=0;for(;r<t;){let i=e[r],a=e[r+1===t?0:r+1],o=e[r+2>=t?(r+2)%t:r+2],s=i[0]*$n,c=a[1]*$n,l=o[0]*$n;n+=(l-s)*Math.sin(c),r++}return n*Qn}var tr=Yn,nr=(e,t,n=void 0,r=Y)=>{let i=[`square meters`,`square kilometers`,`ares`,`hectares`],a=[`square feet`,`square yards`,`acres`,`square miles`];if(n&&typeof n!=`function`){let t=i.includes(n),o=a.includes(n);if(t)return ir(e,n,r);if(o)return ar(e,n,r)}return n&&typeof n==`function`?n(e):rr(e,t,r)},rr=(e,t,n)=>t===`metric`?e>=1e6?ir(e,`square kilometers`,n):e>=1e4?ir(e,`hectares`,n):e>=100?ir(e,`ares`,n):ir(e,`square meters`,n):e>=2589988.11?ar(e,`square miles`,n):e>=4046.856?ar(e,`acres`,n):e>=.83612736?ar(e,`square yards`,n):ar(e,`square feet`,n),ir=(e,t,n)=>{let r=e,i=n[`square meters`];switch(t){case`square meters`:r=e,i=n[`square meters`];break;case`ares`:r=e/100,i=n.ares;break;case`hectares`:r=e/1e4,i=n.hectares;break;case`square kilometers`:r=e/1e6,i=n[`square kilometers`];break}return{area:r,unit:i}},ar=(e,t,n)=>{let r=e/2589988.11,i=n[`square meters`];switch(t){case`square feet`:r=e/.09290304,i=n[`square feet`];break;case`square yards`:r=e/.83612736,i=n[`square yards`];break;case`acres`:r=e/4046.856,i=n.acres;break;case`square miles`:r=e/2589988.11,i=n[`square miles`];break}return{area:r,unit:i}},or=(e,t,n,r,i)=>{if(e.geometry.type!==`Polygon`)return e;let a=nr(tr(e.geometry),t,r,i);return a.area=parseFloat(a.area.toFixed(n)),e.properties.area=a.area,e.properties.unit=a.unit,e};function sr(e){if(!e)throw Error(`coord is required`);if(!Array.isArray(e)){if(e.type===`Feature`&&e.geometry!==null&&e.geometry.type===`Point`)return[...e.geometry.coordinates];if(e.type===`Point`)return[...e.coordinates]}if(Array.isArray(e)&&e.length>=2&&!Array.isArray(e[0])&&!Array.isArray(e[1]))return[...e];throw Error(`coord must be GeoJSON Point or an Array of numbers`)}function cr(e,t,n={}){var r=sr(e),i=sr(t),a=Wn(i[1]-r[1]),o=Wn(i[0]-r[0]),s=Wn(r[1]),c=Wn(i[1]),l=Math.sin(a/2)**2+Math.sin(o/2)**2*Math.cos(s)*Math.cos(c);return Un(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),n.units)}var lr=cr,ur=(e,t=`metric`,n=void 0,r=Y)=>{let i=[`centimeter`,`meter`,`kilometer`],a=[`inch`,`foot`,`mile`],o={distance:e,unit:r.meter};if(n&&typeof n!=`function`){let t=i.includes(n),s=a.includes(n);t?o=fr(e,n,r):s&&(o=pr(e,n,r))}else o=n&&typeof n==`function`?n(e):dr(e,t,r);return o},dr=(e,t,n)=>{let r={distance:e,unit:n.meter};if(t===`metric`)r=e>=1e3?fr(e,`kilometer`,n):e>=1?fr(e,`meter`,n):fr(e,`centimeter`,n);else if(t===`imperial`){let t=Math.round(e*3.28084*10)/10;r=t>=5280?pr(e,`mile`,n):t>=1?pr(e,`foot`,n):pr(e,`inch`,n)}return r},fr=(e,t,n)=>{let r={distance:e,unit:n.meter};switch(t){case`meter`:r.distance=e,r.unit=n[t];break;case`centimeter`:r.distance=e*100,r.unit=n[t];break;case`kilometer`:r.distance=e/1e3,r.unit=n[t];break;default:r.distance=e,r.unit=n.meter;break}return r},pr=(e,t,n)=>{let r=Math.round(e*3.28084*10)/10,i={distance:r/5280,unit:n.mile};switch(t){case`foot`:i.distance=r,i.unit=n[t];break;case`inch`:i.distance=r*12,i.unit=n[t];break;default:i.distance=r/5280,i.unit=n.mile;break}return i},mr=(e,t,n,r,i,a,o,s)=>{if(e.geometry.type!==`LineString`)return e;let c=e.geometry.coordinates,l=0,u=[];for(let t=0;t<c.length-1;t++){let n=c[t],r=c[t+1],i=lr(n,r,{units:`meters`});l+=i;let d=JSON.parse(JSON.stringify(e));if(d.id=`${d.id}-${t}`,d.geometry.coordinates=[n,r],d.properties.originalId=e.id,d.properties.distance=i,d.properties.total=l,o===!0&&s===void 0){let e=a?.queryTerrainElevation(n);e&&(d.properties.elevation_start=e);let t=a?.queryTerrainElevation(r);t&&(d.properties.elevation_end=t)}u.push(d)}e.properties.distance=u[u.length-1].properties.total,e.properties.segments=u;let d=ur(e.properties.distance,t,r,i);return e.properties.distance=d.distance,e.properties.unit=d.unit,e.properties.segments.forEach(e=>{let n=ur(e.properties.distance,t,r,i);e.properties.distance=n.distance,e.properties.unit=n.unit;let a=ur(e.properties.total,t,r,i);e.properties.total=a.distance,e.properties.totalUnit=a.unit}),e.properties.distance=parseFloat(e.properties.distance.toFixed(n)),e.properties.segments.forEach(e=>{e.properties.distance=parseFloat(e.properties.distance.toFixed(n)),e.properties.total=parseFloat(e.properties.total.toFixed(n))}),e},Q=(e,t=`metric`,n=Y)=>t===`imperial`?{elevation:e*3.28084,unit:n.foot}:{elevation:e,unit:n.meter},hr=e=>e.charAt(0).toUpperCase()+e.slice(1),$=[`{prefix}-point`,`{prefix}-point-lower`,`{prefix}-linestring`,`{prefix}-polygon`,`{prefix}-polygon-outline`],gr=[...$,In.polygonLayerSpec?.source,In.lineLayerLabelSpec?.source],_r=[...$,X.routingLineLayerNodeLabelSpec?.source,X.routingLineLayerNodeSpec?.source,X.timeIsochronePolygonLayerSpec?.source,X.timeIsochroneLineLayerSpec?.source,X.timeIsochroneLabelLayerSpec?.source,X.distanceIsochronePolygonLayerSpec?.source,X.distanceIsochroneLineLayerSpec?.source,X.distanceIsochroneLabelLayerSpec?.source],vr=(e,t,n=$,r=`td`)=>{n=n.map(e=>e.replace(`{prefix}`,r));let i=JSON.parse(JSON.stringify(e));return t&&(t.onlyTerraDrawLayers===!0?(i.layers=i.layers.filter(e=>`source`in e&&n.includes(e.source)),Object.keys(i.sources).forEach(e=>{n.includes(e)||delete i.sources[e]})):t.excludeTerraDrawLayers===!0&&(i.layers=i.layers.filter(e=>`source`in e&&!n.includes(e.source)||e.type===`background`),Object.keys(i.sources).forEach(e=>{n.includes(e)&&delete i.sources[e]}))),i},yr=(e,t=250)=>{let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}},br=class{cache=new Map;maxSize;ttl;constructor(e=1e3,t){this.maxSize=e,this.ttl=t}get(e){let t=this.cache.get(e);if(t){if(t.expiry&&Date.now()>t.expiry){this.cache.delete(e);return}return t.value}}set(e,t){if(this.maxSize===0)return;if(this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}let n=this.ttl?Date.now()+this.ttl:void 0;this.cache.set(e,{value:t,expiry:n})}has(e){return this.get(e)!==void 0}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}cleanupExpired(){if(!this.ttl)return;let e=Date.now();for(let[t,n]of this.cache.entries())n.expiry&&e>n.expiry&&this.cache.delete(t)}getStats(){return{size:this.size,maxSize:this.maxSize,ttl:this.ttl}}},xr=class{className;dialog;title;constructor(e,t){this.className=e,this.title=t}create(e,t){let n=document.getElementsByClassName(this.className);n.length>0&&Array.from(n).forEach(e=>{e.remove()}),this.dialog=document.createElement(`dialog`),this.dialog.classList.add(this.className);let r=document.createElement(`div`);r.classList.add(`dialog-header`);let i=document.createElement(`h3`);i.textContent=this.title,i.classList.add(`dialog-title`),r.appendChild(i);let a=document.createElement(`button`);a.type=`button`,a.classList.add(`close-button`),a.innerHTML=`×`,a.setAttribute(`aria-label`,`Close dialog`),a.addEventListener(`click`,()=>{this.close()}),r.appendChild(a),this.dialog.appendChild(r);let o=document.createElement(`div`);o.classList.add(`content`),this.dialog.appendChild(t(o)),this.dialog.addEventListener(`click`,e=>{let t=e.target?.getBoundingClientRect();t&&(t.left>e.clientX||t.right<e.clientX||t.top>e.clientY||t.bottom<e.clientY)&&this.close()}),e.appendChild(this.dialog)}open(){this.dialog?.showModal()}close(){this.dialog?.close()}createSegmentButtons(e,t,n=()=>{}){let r=document.createElement(`div`);return r.classList.add(`segment-buttons`),e.forEach(e=>{let i=document.createElement(`button`);i.type=`button`,i.classList.add(`segment-button`),i.value=e.value,i.textContent=e.label,e.value===t&&i.classList.add(`active`),i.addEventListener(`click`,()=>{r.querySelectorAll(`.segment-button`).forEach(e=>e.classList.remove(`active`)),i.classList.add(`active`),n(i.value)}),r.appendChild(i)}),r}},Sr=(e,t,n,r,i=`metric`,a=Y)=>{if(e.geometry.type!==`Point`)return e;let o=e.geometry.coordinates;if(n===!0){if(r===void 0){let n=t?.queryTerrainElevation(o);if(n){let{elevation:t,unit:r}=Q(n,i,a);e.properties.elevation=t,e.properties.elevationUnit=r}}else if(e.properties.elevation!==void 0&&typeof e.properties.elevation==`number`){let t=e.properties.elevation,n=e.properties.elevationUnit;(n===`ft`||n===`foot`)&&(t/=3.28084);let{elevation:r,unit:o}=Q(t,i,a);e.properties.elevation=r,e.properties.elevationUnit=o}}return e},Cr=Object.defineProperty,wr=(e,t,n)=>t in e?Cr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Tr=(e,t,n)=>wr(e,typeof t==`symbol`?t:t+``,n),Er=2*Math.PI*6378137/2;function Dr(e){return e||=256,2*Math.PI*6378137/e}function Or(e,t,n={enable:!0,decimal:1}){e=Lr(e);var r=e[0],i=e[1],a=r*Er/180,o=Math.log(Math.tan((90+i)*Math.PI/360))/(Math.PI/180);return o=o*Er/180,n.enable&&(a=Number(a.toFixed(n.decimal)),o=Number(o.toFixed(n.decimal))),[a,o]}function kr(e,t,n){var r=e[0],i=e[1],a=Rr(t,n);return[(r+Er)/a,(i+Er)/a,t]}function Ar(e,t,n){return e=Lr(e),Mr(kr(Or(e),t))}function jr(e,t,n){return e=Lr(e),t===0?[0,0,0]:Nr(Ar(e,t))}function Mr(e,t,n){t||=256;var r=e[0],i=e[1],a=e[2];if(a===0)return[0,0,0];Ir(a);var o=Math.ceil(r/t)-1,s=Math.ceil(i/t)-1;return o<0&&(o=0),s<0&&(s=0),[o,s,a]}function Nr(e,t){Pr(e);var n=e[0],r=e[1],i=e[2];return i===0?[0,0,0]:[n,2**i-1-r,i]}function Pr(e,t){var n=e[0],r=e[1],i=e[2];if(i==null)throw Error(`<zoom> is required`);if(n==null)throw Error(`<x> is required`);if(r==null)throw Error(`<y> is required`);return i=Ir(i),e=Fr(e),e}function Fr(e){var t=e[0],n=e[1],r=e[2],i=2**r;return t%=i,t<0&&(t+=i),[t,n,r]}function Ir(e){if(e===!1)return e;if(e==null)throw Error(`<zoom> is required`);if(e<0)throw Error(`<zoom> cannot be less than 0`);if(e>32)throw Error(`<zoom> cannot be greater than 32`);return e}function Lr(e,t){var n=Br(e[0]),r=zr(e[1]);return r>85&&(r=85),r<-85&&(r=-85),[n,r]}function Rr(e,t){return Dr(t)/2**e}function zr(e){if(e==null)throw Error(`lat is required`);return(e>90||e<-90)&&(e%=180,e>90&&(e=-180+e),e<-90&&(e=180+e),e===0&&(e=0)),e}function Br(e){if(e==null)throw Error(`lng is required`);return(e>180||e<-180)&&(e%=360,e>180&&(e=-360+e),e<-180&&(e=360+e),e===0&&(e=0)),e}var Vr=class{constructor(e,t,n,r,i){Tr(this,`url`),Tr(this,`tileSize`),Tr(this,`tms`),Tr(this,`minzoom`),Tr(this,`maxzoom`),this.url=e,this.tileSize=t,this.tms=i,this.minzoom=n,this.maxzoom=r,this.tms=i}getValue(e,t){return new Promise((n,r)=>{let i=e[0],a=e[1],o=t;t>this.maxzoom?o=this.maxzoom:t<this.minzoom&&(o=this.minzoom);let s=this.tms?Ar([i,a],o):jr([i,a],o),c=this.url.replace(/{x}/g,s[0].toString()).replace(/{y}/g,s[1].toString()).replace(/{z}/g,s[2].toString()),l=this.getUrlExtension(c);switch(l||=`png`,l){case`png`:case`webp`:this.getValueFromRaster(c,s,i,a).then(e=>{n(e)});break;default:r(Error(`Invalid file extension: ${l}`));break}})}async getValueFromRaster(e,t,n,r){let i=await fetch(e);if(!i.ok){if(i.status===404)return;throw Error(`Failed to fetch tile: ${i.statusText}`)}let a=await i.blob();return new Promise((e,i)=>{let o=new Image;o.onload=()=>{let a=document.createElement(`canvas`);a.width=o.width,a.height=o.height;let s=a.getContext(`2d`);if(!s)return i(Error(`Failed to create canvas context`));s.drawImage(o,0,0);let c=s.getImageData(0,0,o.width,o.height).data,l=this.pixels2rgba(new Uint8Array(c),t,n,r);e(this.calc(l[0],l[1],l[2],l[3]))},o.onerror=()=>e(void 0),o.src=URL.createObjectURL(a)})}pixels2rgba(e,t,n,r){let i=[];for(let t=0;t<e.length;t+=4){let n=[e[t],e[t+1],e[t+2],e[t+3]];i.push(n)}let a=this.tileToBBOX(t),o=this.getPixelPosition(n,r,a);return i[o[0]+o[1]*this.tileSize]}getPixelPosition(e,t,n){let r=this.tileSize,i=this.tileSize,a=n[2]-n[0],o=n[3]-n[1],s=(e-n[0])/a,c=(t-n[1])/o;return[Math.floor(r*s),Math.floor(i*(1-c))]}getUrlExtension(e){let t=e.split(/[#?]/)[0].split(`.`).pop();return t&&=t.trim(),t}tileToBBOX(e){let t=this.tile2lon(e[0]+1,e[2]);return[this.tile2lon(e[0],e[2]),this.tile2lat(e[1]+1,e[2]),t,this.tile2lat(e[1],e[2])]}tile2lon(e,t){return e/2**t*360-180}tile2lat(e,t){let n=180/Math.PI,r=Math.PI-2*Math.PI*e/2**t;return n*Math.atan(.5*(Math.exp(r)-Math.exp(-r)))}},Hr=class extends Vr{constructor(e,t,n=5,r=15,i=!1){super(e,t,n,r,i)}async getElevation(e,t){return await this.getValue(e,t)}calc(e,t,n){return-1e4+(e*256*256+t*256+n)*.1}},Ur=class extends Vr{constructor(e,t,n=5,r=15,i=!1){super(e,t,n,r,i)}async getElevation(e,t){return await this.getValue(e,t)}calc(e,t,n){let r=e*256+t+n/256-32768;return parseInt(r.toFixed(0))}},Wr=(e,t=8)=>{let[n,r]=e,i=10**t;return`${Math.round(n*i)/i},${Math.round(r*i)/i}`},Gr=async(e,t,n,r,i=`metric`,a=Y)=>{let o=[],s={enabled:!0,maxSize:1e3,ttl:3600*1e3,precision:6,...n},c;s.enabled&&(c=r||new br(s.maxSize,s.ttl));let l,u=15;if(t){let e=t.url,n=t.encoding??`mapbox`,r=t.tileSize??512,i=t.minzoom??5;u=t.maxzoom??15;let a=t.tms??!1;l=n===`mapbox`?new Hr(e,r,i,u,a):new Ur(e,r,i,u,a)}for(let t of e)o.push(new Promise(e=>{t.geometry.type!==`Point`&&e(t);let n=t.geometry.coordinates,r=Wr(n,s.precision);if(c){let n=c.get(r);if(n!==void 0){if(!isNaN(n)){let{elevation:e,unit:r}=Q(n,i,a);t.properties.elevation=e,t.properties.elevationUnit=r}e(t);return}}l?l.getElevation(t.geometry.coordinates,u).then(n=>{if(n!=null&&typeof n==`number`){c&&c.set(r,n);let{elevation:e,unit:o}=Q(n,i,a);t.properties.elevation=e,t.properties.elevationUnit=o}e(t)}).catch(()=>{c&&c.has(r)&&c.delete(r),e(t)}):e(t)}));return await Promise.all(o)},Kr=(e,t=9)=>{function n(e){return[Number(e[0].toFixed(t)),Number(e[1].toFixed(t))]}function r(e){let t=e.type,r=e.coordinates;switch(t){case`Point`:r=n(r);break;case`LineString`:case`MultiPoint`:r=r.map(n);break;case`Polygon`:case`MultiLineString`:r=r.map(e=>e.map(n));break;case`MultiPolygon`:r=r.map(e=>e.map(e=>e.map(n)));break;default:break}return{...e,coordinates:r}}return e.map(e=>({...e,geometry:r(e.geometry)}))},qr=[{value:`time`,label:`Time`},{value:`distance`,label:`Distance`}],Jr=class{url;constructor(e){this.url=e}async calcIsochrone(e,t,n,r,i){let a=JSON.parse(JSON.stringify(i));a.forEach(e=>{n===`time`?delete e.distance:delete e.time});let o={locations:[{lat:t,lon:e}],costing:r,contours:a.map(e=>(e.color=e.color.replace(`#`,``),e)),polygons:!0},s=`${this.url}/isochrone?json=${JSON.stringify(o)}`;return await(await fetch(s)).json()}},Yr=[{value:`pedestrian`,label:`Pedestrian`},{value:`bicycle`,label:`Bicycle`},{value:`auto`,label:`Car`}],Xr=[{value:`kilometers`,label:`km`},{value:`miles`,label:`mile`}],Zr=class{tripData=[];getTripData(){return this.tripData}url;tripSummary;getTripSummary(){return this.tripSummary}constructor(e){this.url=e}clearFeatures(){this.tripData=[],this.tripSummary=void 0}async calcRoute(e,t,n){if(this.tripData=e,!this.tripData||this.tripData&&this.tripData.length<2){this.tripSummary=void 0;return}let r=`${this.url}/route`,i={locations:this.tripData.map(e=>({lon:e.lng,lat:e.lat})),costing:t,costing_options:{auto:{country_crossing_penalty:2e3}},units:n,id:`my_work_route`},a=`${r}?json=${JSON.stringify(i)}`,o=await(await fetch(a)).json();if(`error`in o)throw this.tripData.pop(),Error(`${o.status} (${o.status_code}): ${o.error} (${o.error_code})`);let s=o.trip.legs.map(e=>this.decodeShape(e.shape)),c=[];s.forEach(e=>{c=[...c,...e]}),this.tripSummary=o.trip.summary,this.tripSummary.length=Number(this.tripSummary.length.toFixed(2)),this.tripSummary.time=Number((this.tripSummary.time/60).toFixed());let l=[],u=0,d=0,f=[],p=this.geoPoint(this.tripData.map(e=>[e.lng,e.lat]));o.trip.legs.forEach((e,t)=>{let r=this.decodeShape(e.shape);l.push(...r),u+=Number(e.summary.length.toFixed(2)),d+=Number((e.summary.time/60).toFixed()),f.push(...e.maneuvers);let i=p.features[t+1];i.properties={...i.properties,distance:u,distance_unit:n===`kilometers`?`km`:`mi`,time:d,maneuvers:e.maneuvers}});let m=Yr.find(e=>e.value===t)?.label,h=this.geoLineString(l,{costingModel:m,distance:u,distance_unit:n===`kilometers`?`km`:`mi`,time:d,maneuvers:f}),g=p.features[0];return g.properties={...g.properties,costingModel:m},{feature:h,pointFeatures:p}}geoLineString(e=[],t={}){return{type:`Feature`,properties:t,geometry:{type:`LineString`,coordinates:e}}}geoPoint(e=[]){return{type:`FeatureCollection`,features:e.map((t,n)=>{let r=(n+1).toString();return r=n===0?`Start`:n===e.length-1?`Goal`:`No.${r}`,{type:`Feature`,id:`node-${n}`,properties:{sequence:n,text:r},geometry:{type:`Point`,coordinates:t}}})}}decodeShape(e,t=6){let n=0,r=0,i=0,a=[],o,s,c=10**(t||6);for(;n<e.length;){let t,l=0,u=0;do t=e.charCodeAt(n++)-63,u|=(t&31)<<l,l+=5;while(t>=32);o=u&1?~(u>>1):u>>1,l=u=0;do t=e.charCodeAt(n++)-63,u|=(t&31)<<l,l+=5;while(t>=32);s=u&1?~(u>>1):u>>1,r+=o,i+=s,a.push([i/c,r/c])}return a}},Qr=class{controlContainer;map;modeButtons={};_isExpanded=!1;_cssPrefix=``;get isExpanded(){return this._isExpanded}get cssPrefix(){return this._cssPrefix}set isExpanded(e){this._isExpanded=e;let t=document.getElementsByClassName(`maplibregl-terradraw-${this.cssPrefix}add-control`);for(let e=0;e<t.length;e++){let n=t.item(e);n&&(this.isExpanded?n.classList.remove(`hidden`):n.classList.add(`hidden`))}let n=document.getElementsByClassName(`maplibregl-terradraw-${this.cssPrefix}render-button`);n&&n.length>0&&(this.isExpanded?n.item(0)?.classList.add(`enabled`):(n.item(0)?.classList.remove(`enabled`),this.resetActiveMode())),this.toggleDeleteSelectionButton(),this.toggleButtonsWhenNoFeature(),this.isExpanded?this.dispatchEvent(`expanded`):this.dispatchEvent(`collapsed`)}get showDeleteConfirmation(){return this.options.showDeleteConfirmation===!0}set showDeleteConfirmation(e){this.options.showDeleteConfirmation=e}terradraw;options;events={};defaultMode=`render`;constructor(e){this.modeButtons={},this.options={...Mn,modes:[...Mn.modes??[]],...e};let t=this.options.adapterOptions?.prefixId??`td`;this.options.adapterOptions||(this.options.adapterOptions={}),this.options.adapterOptions?.prefixId||(this.options.adapterOptions.prefixId=t),this.options.undoRedo||(this.options.undoRedo={modeLevel:new wn({maxStackSize:100}),sessionLevel:new Tn({maxStackSize:100}),keyboardShortcuts:new xn})}getDefaultPosition(){return`top-right`}onAdd(e){if(this.options&&this.options.modes&&this.options.modes.length===0)throw Error(`At least a mode must be enabled.`);this.map=e;let t=zn(),n=[];return this.options?.modes?.forEach(e=>{if(this.options.modeOptions&&this.options.modeOptions[e]){let r=this.options.modeOptions[e];if(e===`select`){let n=t[e];if(n){let e=n.flags;Object.keys(e).forEach(t=>{r.flags[t]||(r.flags[t]=e[t])})}}n.push(r)}else t[e]&&n.push(t[e])}),n.forEach(e=>{e.state!==`unregistered`&&(e._state=`unregistered`)}),this.options?.modes?.includes(`render`)||(n.push(new V({modeName:`default`,styles:{}})),this.defaultMode=`default`),this.isExpanded=this.options.open===!0,this.terradraw=new Dn({adapter:new kn({map:e,...this.options.adapterOptions}),modes:n,undoRedo:this.options.undoRedo}),this.map?.loaded()?this.terradraw.start():this.map?.once(`load`,()=>{this.terradraw?.start()}),this.controlContainer=document.createElement(`div`),this.controlContainer.classList.add(`maplibregl-ctrl`),this.controlContainer.classList.add(`maplibregl-ctrl-group`),n.forEach(e=>{e.mode!==`default`&&this.addTerradrawButton(e.mode)}),Object.values(this.modeButtons).forEach(e=>{this.controlContainer?.appendChild(e)}),this.toggleButtonsWhenNoFeature(),this.terradraw?.on(`finish`,this.toggleButtonsWhenNoFeature.bind(this)),this.terradraw?.on(`history`,this.handleHistoryChange.bind(this)),this.map.once(`idle`,()=>{this.toggleButtonsWhenNoFeature()}),this.controlContainer}onRemove(){!this.controlContainer||!this.controlContainer.parentNode||!this.map||(this.deactivate(),this.modeButtons={},this.terradraw=void 0,this.map=void 0,this.controlContainer.parentNode.removeChild(this.controlContainer))}on(e,t){this.events[e]?this.events[e].push(t):this.events[e]=[t]}off(e,t){if(!this.events[e])return;let n=this.events[e].findIndex(e=>e===t);n!==-1&&this.events[e].splice(n,1)}dispatchEvent(e,t){this.events[e]&&this.events[e].forEach(e=>{let n=(this.terradraw?.getSnapshot())?.filter(e=>e.properties.selected===!0);e({feature:n,mode:this.terradraw?.getMode(),...t})})}activate(){this.terradraw&&(this.terradraw.enabled||this.terradraw.start())}deactivate(){this.terradraw&&this.terradraw.enabled&&(this.resetActiveMode(),this.dispatchEvent(`mode-changed`),this.terradraw.stop())}handleModeChange(e,t){let n=t.setMode(e);return this.syncButtonStates(e),e!==this.defaultMode&&this.activate(),this.dispatchEvent(`mode-changed`),n}syncButtonStates(e){if(!this.controlContainer)return;let t=this.controlContainer.getElementsByClassName(`maplibregl-terradraw-${this.cssPrefix}add-control`);for(let e=0;e<t.length;e++){let n=t.item(e);n&&n.classList.remove(`active`)}if(e!==this.defaultMode&&e!==`render`){let t=this.controlContainer.getElementsByClassName(`maplibregl-terradraw-${this.cssPrefix}add-${e}-button`);t&&t.length>0&&t[0].classList.add(`active`)}this.toggleDeleteSelectionButton(),this.toggleButtonsWhenNoFeature()}getTerraDrawInstance(){return this.terradraw?new Proxy(this.terradraw,{get:(e,t,n)=>t===`setMode`?t=>this.handleModeChange(t,e):t===`clearUndoRedoHistory`?()=>{e.clearUndoRedoHistory(),this.handleHistoryChange({undoSize:0,redoSize:0})}:Reflect.get(e,t,n)}):this.terradraw}handleHistoryChange(e){if(!this.controlContainer)return;let t=this.controlContainer.getElementsByClassName(`maplibregl-terradraw-${this.cssPrefix}undo-button`);for(let n=0;n<t.length;n++){let r=t.item(n);r&&(r.disabled=e.undoSize===0)}let n=this.controlContainer.getElementsByClassName(`maplibregl-terradraw-${this.cssPrefix}redo-button`);for(let t=0;t<n.length;t++){let r=n.item(t);r&&(r.disabled=e.redoSize===0)}}toggleEditor(){this.terradraw&&(this.isExpanded=!this.isExpanded)}resetActiveMode(){this.terradraw&&(this.terradraw.enabled||this.terradraw.start(),this.terradraw?.setMode(this.defaultMode),this.syncButtonStates(this.defaultMode))}addTerradrawButton(e){let t=document.createElement(`button`);t.type=`button`,this.modeButtons[e]=t,e===`render`?(t.classList.add(`maplibregl-terradraw-${this.cssPrefix}${e}-button`),this.isExpanded&&t.classList.add(`enabled`),t.type=`button`,t.title=hr(`expand or collapse drawing tool`),t.addEventListener(`click`,this.toggleEditor.bind(this))):(t.classList.add(`maplibregl-terradraw-${this.cssPrefix}add-control`),this.isExpanded||t.classList.add(`hidden`),t.title=hr(e.replace(/-/g,` `)),e===`delete`?(t.classList.add(`maplibregl-terradraw-${this.cssPrefix}${e}-button`),t.addEventListener(`click`,this.handleDeleteAllFeatures.bind(this))):e===`delete-selection`?(t.classList.add(`maplibregl-terradraw-${this.cssPrefix}${e}-button`),t.classList.add(`hidden-delete-selection`),t.addEventListener(`click`,this.handleDeleteSelectedFeatures.bind(this))):e===`download`?(t.classList.add(`maplibregl-terradraw-${this.cssPrefix}${e}-button`),t.addEventListener(`click`,this.handleDownload.bind(this))):[`undo`,`redo`].includes(e)?(t.classList.add(`maplibregl-terradraw-${this.cssPrefix}${e}-button`),t.disabled=!0,t.addEventListener(`click`,()=>{this.terradraw&&(e===`undo`?this.terradraw.undo():this.terradraw.redo())})):(t.classList.add(`maplibregl-terradraw-${this.cssPrefix}add-${e}-button`),t.addEventListener(`click`,()=>{if(!this.terradraw)return;let n=t.classList.contains(`active`);this.activate(),this.resetActiveMode(),n||(this.terradraw.setMode(e),this.syncButtonStates(e)),this.dispatchEvent(`mode-changed`)})))}getFeatures(e=!1){if(!this.terradraw)return;let t={type:`FeatureCollection`,features:(this.terradraw?.getSnapshot()).filter(e=>e.properties.mode!==`select`)};return e===!0&&(t.features=t.features.filter(e=>e.properties.selected===!0)),t}cleanStyle(e,t){return vr(e,t,$,this.options.adapterOptions?.prefixId)}showDeleteConfirmationDialog(e){let t=new xr(`maplibre-terradraw-delete-confirmation-dialog`,`Delete All Features`);t.create(document.body,n=>{let r=document.createElement(`p`);r.textContent=`Are you sure you want to delete all features?`,n.appendChild(r);let i=document.createElement(`div`);i.classList.add(`dialog-buttons`);let a=document.createElement(`button`);a.type=`button`,a.textContent=`Cancel`,a.classList.add(`dialog-button-cancel`),a.addEventListener(`click`,()=>{t.close()});let o=document.createElement(`button`);return o.type=`button`,o.textContent=`Delete`,o.classList.add(`dialog-button-delete`),o.addEventListener(`click`,()=>{e(),t.close()}),i.appendChild(a),i.appendChild(o),n.appendChild(i),n}),t.open()}handleDeleteAllFeatures(){if(!this.terradraw||!this.terradraw.enabled)return;let e=()=>{this.terradraw?.clear(),this.resetActiveMode(),this.toggleDeleteSelectionButton(),this.toggleButtonsWhenNoFeature(),this.dispatchEvent(`feature-deleted`)};this.options.showDeleteConfirmation===!0?this.showDeleteConfirmationDialog(e):e()}handleDeleteSelectedFeatures(){if(!this.terradraw||!this.terradraw.enabled)return;let e=(this.terradraw?.getSnapshot()).filter(e=>e.properties.selected===!0);if(e.length>0){let t=e.map(e=>e.id);this.terradraw.removeFeatures(t);for(let e of t)this.terradraw.deselectFeature(e);this.dispatchEvent(`feature-deleted`,{deletedIds:t})}this.toggleDeleteSelectionButton(),this.toggleButtonsWhenNoFeature()}handleDownload(){let e=this.getFeatures(!1),t=`data:application/json;charset=utf-8,`+encodeURIComponent(JSON.stringify(e)),n=document.createElement(`a`);n.setAttribute(`href`,t),n.setAttribute(`download`,`data.geojson`),document.body.appendChild(n),n.click(),n.remove()}toggleButtonsWhenNoFeature(){if(!this.controlContainer)return;let e=(this.terradraw?.getSnapshot())?.filter(e=>e.properties.mode!==`select`),t=!!(e&&e.length>0),n=[`maplibregl-terradraw-${this.cssPrefix}add-select-button`,`maplibregl-terradraw-${this.cssPrefix}download-button`,`maplibregl-terradraw-${this.cssPrefix}delete-button`];for(let e of n){let n=this.controlContainer.getElementsByClassName(e);for(let e=0;e<n.length;e++){let r=n.item(e);r&&(r.disabled=!t)}}}toggleDeleteSelectionButton(){let e=this.terradraw?.enabled||!1,t=this.terradraw?.getMode(),n=this.getFeatures(!1),r=n&&n.features.length>0,i=r&&e&&t===`select`,a=document.getElementsByClassName(`maplibregl-terradraw-${this.cssPrefix}delete-selection-button`);for(let e=0;e<a.length;e++){let t=a.item(e);t&&(i?t.classList.remove(`hidden-delete-selection`):t.classList.add(`hidden-delete-selection`))}if(!r){let e=document.getElementsByClassName(`maplibregl-terradraw-${this.cssPrefix}add-select-button`);for(let t=0;t<e.length;t++){let n=e.item(t);n&&n.classList.remove(`active`)}}}clearExtendedFeatures(e,t=void 0){if(this.map)for(let n of e){let e=this.map.getStyle().sources[n];e&&typeof e.data!=`string`&&e.data.type===`FeatureCollection`&&(t===void 0?e.data.features=[]:e.data.features=e.data.features.filter(e=>e.properties?.originalId?!t.includes(e.properties.originalId):!t.includes(e.id)),this.map.getSource(n)?.setData(e.data))}}};function $r(e,t={}){let n=0,r=0,i=0;return Kn(e,function(e){n+=e[0],r+=e[1],i++},!0),Hn([n/i,r/i],t.properties)}var ei=class extends Qr{measureOptions;elevationCache;get measureUnitType(){return this.measureOptions.measureUnitType??`metric`}set measureUnitType(e){let t=this.measureOptions.measureUnitType===e;this.measureOptions.measureUnitType=e,t||(this.computeElevation&&this.recalculateElevationUnits(),this.recalc())}get distancePrecision(){return this.measureOptions.distancePrecision??2}set distancePrecision(e){let t=this.measureOptions.distancePrecision===e;this.measureOptions.distancePrecision=e,t||this.recalc()}get distanceUnit(){return this.measureOptions.distanceUnit}set distanceUnit(e){let t=this.measureOptions.distanceUnit===e;this.measureOptions.distanceUnit=e,t||this.recalc()}get areaPrecision(){return this.measureOptions.areaPrecision??2}set areaPrecision(e){let t=this.measureOptions.areaPrecision===e;this.measureOptions.areaPrecision=e,t||this.recalc()}get areaUnit(){return this.measureOptions.areaUnit}set areaUnit(e){let t=this.measureOptions.areaUnit===e;this.measureOptions.areaUnit=e,t||this.recalc()}get measureUnitSymbols(){return this.measureOptions.measureUnitSymbols??JSON.parse(JSON.stringify(Y))}set measureUnitSymbols(e){let t=JSON.stringify(this.measureOptions.measureUnitSymbols)===JSON.stringify(e);this.measureOptions.measureUnitSymbols=e,t||this.recalc()}get computeElevation(){return this.measureOptions.computeElevation??!1}set computeElevation(e){let t=this.measureOptions.computeElevation===e;this.measureOptions.computeElevation=e,t||this.recalc()}get fontGlyphs(){let e=[this.measureOptions.pointLayerLabelSpec,this.measureOptions.lineLayerLabelSpec,this.measureOptions.polygonLayerSpec][0];return e&&e.layout&&e.layout[`text-font`]}set fontGlyphs(e){let t=[this.measureOptions.pointLayerLabelSpec,this.measureOptions.lineLayerLabelSpec,this.measureOptions.polygonLayerSpec];for(let n of t)n&&n.layout&&(n.layout[`text-font`]=e),this.map&&n&&this.map.getLayer(n.id)&&this.map.setLayoutProperty(n.id,`text-font`,e)}constructor(e){let{modeOptions:t,...n}=In,r={...JSON.parse(JSON.stringify(n)),modeOptions:{...t}};e&&(r=Object.assign(r,e));let i=r.adapterOptions?.prefixId??`td-measure`;r.adapterOptions&&!r.adapterOptions?.prefixId&&(r.adapterOptions.prefixId=i),r.pointLayerLabelSpec.id=r.pointLayerLabelSpec?.id.replace(`{prefix}`,i),r.pointLayerLabelSpec.source=r.pointLayerLabelSpec?.source.replace(`{prefix}`,i),r.routingLineLayerNodeSpec.id=r.routingLineLayerNodeSpec?.id.replace(`{prefix}`,i),r.routingLineLayerNodeSpec.source=r.routingLineLayerNodeSpec?.source.replace(`{prefix}`,i),r.lineLayerLabelSpec.id=r.lineLayerLabelSpec?.id.replace(`{prefix}`,i),r.lineLayerLabelSpec.source=r.lineLayerLabelSpec?.source.replace(`{prefix}`,i),r.polygonLayerSpec.id=r.polygonLayerSpec?.id.replace(`{prefix}`,i),r.polygonLayerSpec.source=r.polygonLayerSpec?.source.replace(`{prefix}`,i),super({modes:r.modes,open:r.open,modeOptions:r.modeOptions,adapterOptions:r.adapterOptions,undoRedo:r.undoRedo}),this._cssPrefix=`measure-`,this.measureOptions=r,this.measureOptions.elevationCacheConfig&&this.measureOptions.elevationCacheConfig?.enabled&&(this.elevationCache=new br(this.measureOptions.elevationCacheConfig.maxSize,this.measureOptions.elevationCacheConfig.ttl))}onAdd(e){return this.controlContainer=super.onAdd(e),this.controlContainer}onRemove(){this.unregisterMesureControl(),super.onRemove()}activate(){super.activate(),this.registerMesureControl()}recalc(){let e=this.getTerraDrawInstance();if(e){this.registerMesureControl();let t=e.getSnapshot();for(let e of t){let t=e.id,n=e.geometry.type,r=e.properties.mode;[`linestring`,`freehand-linestring`].includes(r)&&n===`LineString`?this.measureLine(t,!1):[`point`,`marker`].includes(r)&&n===`Point`?this.measurePoint(t,!1):![`point`,`marker`,`linestring`,`freehand-linestring`,`select`,`render`].includes(r)&&n===`Polygon`&&this.measurePolygon(t,!1)}}}cleanStyle(e,t){let n=$,r=this.measureOptions.polygonLayerSpec?.source;r&&n.push(r);let i=this.measureOptions.lineLayerLabelSpec?.source;return i&&n.push(i),vr(e,t,n,this.measureOptions.adapterOptions?.prefixId)}registerMesureControl(){if(!this.map)return;let e=this.options.modes?.filter(e=>[`linestring`,`freehand-linestring`].includes(e));this.options.modes?.find(e=>[`point`,`marker`].includes(e))&&(this.map.getLayer(this.measureOptions.pointLayerLabelSpec.id)||this.map.addLayer(this.measureOptions.pointLayerLabelSpec)),e&&e.length>0&&(this.map.getSource(this.measureOptions.lineLayerLabelSpec.source)||this.map.addSource(this.measureOptions.lineLayerLabelSpec.source,{type:`geojson`,data:{type:`FeatureCollection`,features:[]}}),this.map.getLayer(this.measureOptions.routingLineLayerNodeSpec.id)||this.map.addLayer(this.measureOptions.routingLineLayerNodeSpec),this.map.getLayer(this.measureOptions.lineLayerLabelSpec.id)||this.map.addLayer(this.measureOptions.lineLayerLabelSpec));let t=this.options.modes?.filter(e=>[`polygon`,`rectangle`,`angled-rectangle`,`circle`,`sector`,`sensor`,`freehand`].includes(e));if(t&&t.length>0&&(this.map.getSource(this.measureOptions.polygonLayerSpec.source)||this.map.addSource(this.measureOptions.polygonLayerSpec.source,{type:`geojson`,data:{type:`FeatureCollection`,features:[]}}),this.map.getLayer(this.measureOptions.polygonLayerSpec.id)||this.map.addLayer(this.measureOptions.polygonLayerSpec)),e&&e.length>0||t&&t.length>0){let e=this.getTerraDrawInstance();e&&(e.on(`change`,this.handleTerradrawFeatureChanged.bind(this)),e.on(`finish`,this.handleTerradrawFeatureReady.bind(this)),e.on(`deselect`,this.handleTerradrawDeselect.bind(this)),this.on(`feature-deleted`,this.onFeatureDeleted.bind(this)))}}handleTerradrawDeselect=()=>{if(this.map&&this.computeElevation===!0&&this.measureOptions.terrainSource!==void 0){let e=this.getTerraDrawInstance();if(!e)return;let t=e.getSnapshot(),n=t.filter(e=>e.properties.mode&&[`linestring`,`freehand-linestring`].includes(e.properties.mode)&&e.geometry.type===`LineString`);if(n.length>0)for(let e of n)this.computeElevationByLineFeatureID(e.id);let r=t.filter(e=>[`point`,`marker`].includes(e.properties.mode)&&e.geometry.type===`Point`);if(r.length>0)for(let e of r)this.measurePoint(e.id)}};handleTerradrawFeatureReady=yr(e=>{if(!this.map||!this.terradraw)return;let t=this.terradraw.getSnapshotFeature(e);if(!t)return;let n=t.geometry.type,r=t.properties.mode;[`linestring`,`freehand-linestring`].includes(r)&&n===`LineString`?this.measureLine(e,!1):[`point`,`marker`].includes(r)&&n===`Point`?this.measurePoint(e,!1):![`point`,`marker`,`linestring`,`freehand-linestring`,`select`,`render`].includes(r)&&n===`Polygon`&&this.measurePolygon(e,!1)},300);handleTerradrawFeatureChanged(e,t){if(!this.map||t===`styling`)return;let n=[this.measureOptions.lineLayerLabelSpec,this.measureOptions.routingLineLayerNodeSpec,this.measureOptions.polygonLayerSpec].map(e=>e.source);if(t===`delete`){this.clearExtendedFeatures(n,e);return}let r=this.getTerraDrawInstance();if(r)for(let t of e){let e=r.getSnapshotFeature(t);if(e){let n=e.geometry.type,r=e.properties.mode;[`linestring`,`freehand-linestring`].includes(r)&&n===`LineString`?this.measureLine(t,!0):[`point`,`marker`].includes(r)&&n===`Point`?this.measurePoint(t,!0):![`point`,`marker`,`linestring`,`freehand-linestring`,`select`,`render`].includes(r)&&n===`Polygon`&&this.measurePolygon(t,!0)}else this.clearExtendedFeatures(n,[t])}}unregisterMesureControl(){this.off(`feature-deleted`,this.onFeatureDeleted.bind(this)),this.map&&(this.map.getLayer(this.measureOptions.pointLayerLabelSpec.id)&&this.map.removeLayer(this.measureOptions.pointLayerLabelSpec.id),this.map.getLayer(this.measureOptions.lineLayerLabelSpec.id)&&this.map.removeLayer(this.measureOptions.lineLayerLabelSpec.id),this.map.getLayer(this.measureOptions.routingLineLayerNodeSpec.id)&&this.map.removeLayer(this.measureOptions.routingLineLayerNodeSpec.id),this.map.getLayer(this.measureOptions.polygonLayerSpec.id)&&this.map.removeLayer(this.measureOptions.polygonLayerSpec.id),this.map.getSource(this.measureOptions.lineLayerLabelSpec.source)&&this.map.removeSource(this.measureOptions.lineLayerLabelSpec.source),this.map.getSource(this.measureOptions.polygonLayerSpec.source)&&this.map.removeSource(this.measureOptions.polygonLayerSpec.source))}replaceGeoJSONSource(e,t,n){if(!this.map)return;let r=this.map.getStyle().sources[t];if(r&&typeof r.data!=`string`&&r.data.type===`FeatureCollection`){let i=[];for(let t of e)(this.terradraw?.getSnapshotFeature(t.id)||this.terradraw?.getSnapshotFeature(t.properties.originalId))&&i.push(t);let a=i.map(e=>e.id);if(typeof r.data!=`string`&&r.data.type===`FeatureCollection`){n===`linestring`?r.data.features=[...r.data.features=r.data.features.filter(e=>!(a.includes(e.properties?.originalId)&&e.geometry.type===`Point`)),...i]:n===`point`&&(r.data.features=[...r.data.features=r.data.features.filter(e=>!(a.includes(e.id)&&e.geometry.type===`Point`)),...i]);let e={};r.data.features.forEach(t=>{let n=t.id;e[n]?!e[n].properties.elevation&&t.properties?.elevation&&(e[n]=t):e[n]=t}),r.data.features=Array.from(Object.values(e)),this.map.getSource(t)?.setData(r.data)}}}computeElevationByLineFeatureID=async e=>{if(this.map&&this.computeElevation===!0){let t=this.map.getStyle().sources[this.measureOptions.lineLayerLabelSpec.source];if(t&&typeof t.data!=`string`&&t.data.type===`FeatureCollection`){let n=t.data.features.filter(t=>t.properties?.originalId===e&&t.geometry.type===`Point`);if(n&&n.length>0){let e=await Gr(n,this.measureOptions.terrainSource,this.measureOptions.elevationCacheConfig,this.elevationCache,this.measureUnitType,this.measureUnitSymbols);this.replaceGeoJSONSource(e,this.measureOptions.lineLayerLabelSpec.source,`linestring`)}}}};recalculateElevationUnits(){if(!this.map)return;let e=this.measureOptions.pointLayerLabelSpec.source;this.updateElevationUnitsInSource(e);let t=this.measureOptions.lineLayerLabelSpec.source;this.updateElevationUnitsInSource(t)}updateElevationUnitsInSource(e){if(!this.map)return;let t=this.map.getStyle().sources[e];if(t&&typeof t.data!=`string`&&t.data.type===`FeatureCollection`){let n=!1;for(let e of t.data.features)if(e.properties?.elevation!==void 0){let t=e.properties.elevationUnit,r=e.properties.elevation;(t===`ft`||t===`foot`)&&(r/=3.28084);let{elevation:i,unit:a}=Q(r,this.measureUnitType,this.measureUnitSymbols);e.properties.elevation=i,e.properties.elevationUnit=a,n=!0}n&&this.map.getSource(e).setData(t.data)}}async measurePolygon(e,t=!1){if(!this.map)return;let n=this.getTerraDrawInstance();if(!n)return;let r=n.getSnapshot()?.find(t=>t.id===e&&t.geometry.type===`Polygon`);if(r){let n=this.map.getStyle().sources[this.measureOptions.polygonLayerSpec.source];if(n){typeof n.data!=`string`&&n.data.type===`FeatureCollection`&&(n.data.features=n.data.features.filter(t=>t.properties?.originalId!==e));let i=JSON.parse(JSON.stringify(r));i.id+=`-area-label`,i.geometry=$r(r.geometry).geometry,i.properties.originalId=r.id,r=or(r,this.measureUnitType,this.areaPrecision,this.areaUnit,this.measureUnitSymbols),i.properties.area=r.properties.area,i.properties.unit=r.properties.unit,t||this.terradraw?.updateFeatureProperties(e,{area:i.properties.area,unit:i.properties.unit}),typeof n.data!=`string`&&n.data.type===`FeatureCollection`&&n.data.features.push(i),this.map.getSource(this.measureOptions.polygonLayerSpec.source)?.setData(n.data),this.map.moveLayer(this.measureOptions.polygonLayerSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.getLayer(this.measureOptions.lineLayerLabelSpec.id)&&this.map.moveLayer(this.measureOptions.lineLayerLabelSpec.id),this.map.getLayer(this.measureOptions.routingLineLayerNodeSpec.id)&&this.map.moveLayer(this.measureOptions.routingLineLayerNodeSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.getLayer(this.measureOptions.pointLayerLabelSpec.id)&&this.map.moveLayer(this.measureOptions.pointLayerLabelSpec.id,this.options.adapterOptions?.renderBelowLayerId)}}}measureLine(e,t=!1){if(!this.map)return;let n=this.getTerraDrawInstance();if(!n)return;let r=n.getSnapshotFeature(e);if(r){let n=this.map.getStyle().sources[this.measureOptions.lineLayerLabelSpec.source];if(n){typeof n.data!=`string`&&n.data.type===`FeatureCollection`&&(n.data.features=n.data.features.filter(t=>t.properties?.originalId!==e)),r=mr(r,this.measureUnitType,this.distancePrecision,this.distanceUnit,this.measureUnitSymbols,this.map,this.computeElevation,this.measureOptions.terrainSource);let i=r.properties.segments;for(let e=0;e<i.length;e++){let t=i[e],r=t.geometry.coordinates,a=r[0],o=r[1];if(e===0){let r=JSON.parse(JSON.stringify(t));r.id=`${t.id}-node-${e}`,r.geometry={type:`Point`,coordinates:a},r.properties.distance=0,r.properties.total=0,t.properties.elevation_start&&(r.properties.elevation=t.properties.elevation_start),typeof n.data!=`string`&&n.data.type===`FeatureCollection`&&n.data.features.push(r)}let s=JSON.parse(JSON.stringify(t));s.id=`${t.id}-node-${e+1}`,s.geometry={type:`Point`,coordinates:o},t.properties.elevation_end&&(s.properties.elevation=t.properties.elevation_end),typeof n.data!=`string`&&n.data.type===`FeatureCollection`&&n.data.features.push(s)}if(!t){this.computeElevation===!0&&this.measureOptions.terrainSource!==void 0&&this.computeElevationByLineFeatureID(e);let t=i[i.length-1].properties.totalUnit;this.terradraw?.updateFeatureProperties(e,{distance:r.properties.distance,distanceUnit:t,segments:r.properties.segments})}this.map.getSource(this.measureOptions.lineLayerLabelSpec.source)?.setData(n.data),this.map.getLayer(this.measureOptions.polygonLayerSpec.id)&&this.map.moveLayer(this.measureOptions.polygonLayerSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.moveLayer(this.measureOptions.lineLayerLabelSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.moveLayer(this.measureOptions.routingLineLayerNodeSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.getLayer(this.measureOptions.pointLayerLabelSpec.id)&&this.map.moveLayer(this.measureOptions.pointLayerLabelSpec.id,this.options.adapterOptions?.renderBelowLayerId)}}}async measurePoint(e,t=!1){if(!this.map)return;let n=this.getTerraDrawInstance();if(!n)return;let r=n.getSnapshotFeature(e);if(r){let n={elevation:void 0,elevationUnit:void 0};this.computeElevation&&(r=this.measureOptions.terrainSource===void 0?Sr(r,this.map,this.computeElevation,this.measureOptions.terrainSource,this.measureUnitType,this.measureUnitSymbols):(await Gr([r],this.measureOptions.terrainSource,this.measureOptions.elevationCacheConfig,this.elevationCache,this.measureUnitType,this.measureUnitSymbols))[0],n={elevation:r.properties.elevation,elevationUnit:r.properties.elevationUnit}),t||this.terradraw?.updateFeatureProperties(e,n)}}onFeatureDeleted(e){if(this.map&&this.getTerraDrawInstance()){let t=[];typeof e==`object`&&e&&`deletedIds`in e&&(t=e.deletedIds);let n=[this.measureOptions.lineLayerLabelSpec,this.measureOptions.routingLineLayerNodeSpec,this.measureOptions.polygonLayerSpec].map(e=>e.source);t&&t.length>0?this.clearExtendedFeatures(n,t):this.clearExtendedFeatures(n,void 0)}}},ti=class extends Qr{controlOptions;valhallaOptions;_modalDialog;get valhallaUrl(){return this.valhallaOptions.url}set valhallaUrl(e){this.valhallaOptions.url=e}get routingCostingModel(){return this.valhallaOptions.routingOptions?.costingModel}set routingCostingModel(e){this.valhallaOptions.routingOptions||(this.valhallaOptions.routingOptions={}),this.valhallaOptions.routingOptions.costingModel=e,this.createSettingsDialog()}get routingDistanceUnit(){return this.valhallaOptions.routingOptions?.distanceUnit}set routingDistanceUnit(e){this.valhallaOptions.routingOptions||(this.valhallaOptions.routingOptions={}),this.valhallaOptions.routingOptions.distanceUnit=e,this.createSettingsDialog()}get timeIsochroneCostingModel(){return this.valhallaOptions.isochroneOptions?.timeCostingModel}set timeIsochroneCostingModel(e){this.valhallaOptions.isochroneOptions||(this.valhallaOptions.isochroneOptions={}),this.valhallaOptions.isochroneOptions.timeCostingModel=e,this.createSettingsDialog()}get distanceIsochroneCostingModel(){return this.valhallaOptions.isochroneOptions?.distanceCostingModel}set distanceIsochroneCostingModel(e){this.valhallaOptions.isochroneOptions||(this.valhallaOptions.isochroneOptions={}),this.valhallaOptions.isochroneOptions.distanceCostingModel=e,this.createSettingsDialog()}get isochroneContours(){return this.valhallaOptions.isochroneOptions?.contours}set isochroneContours(e){this.valhallaOptions.isochroneOptions||(this.valhallaOptions.isochroneOptions={}),this.valhallaOptions.isochroneOptions.contours=e,this.createSettingsDialog()}get fontGlyphs(){let e=[this.controlOptions.routingLineLayerNodeLabelSpec][0];return e&&e.layout&&e.layout[`text-font`]}set fontGlyphs(e){let t=[this.controlOptions.routingLineLayerNodeLabelSpec];for(let n of t)n&&n.layout&&(n.layout[`text-font`]=e),this.map&&n&&this.map.getLayer(n.id)&&this.map.setLayoutProperty(n.id,`text-font`,e)}get settingDialog(){return this._modalDialog}set settingDialog(e){this._modalDialog=e}constructor(e){let t={...JSON.parse(JSON.stringify(X)),modeOptions:{...X.modeOptions}};e&&(t=Object.assign(t,e),t.valhallaOptions=Object.assign(JSON.parse(JSON.stringify(X.valhallaOptions)),t.valhallaOptions)),t.adapterOptions||={},t.adapterOptions.prefixId=t.adapterOptions?.prefixId??`td-valhalla`;let n=t.adapterOptions?.prefixId??`td-valhalla`;if(t.routingLineLayerNodeLabelSpec.id=t.routingLineLayerNodeLabelSpec?.id.replace(`{prefix}`,n),t.routingLineLayerNodeLabelSpec.source=t.routingLineLayerNodeLabelSpec?.source.replace(`{prefix}`,n),t.routingLineLayerNodeSpec.id=t.routingLineLayerNodeSpec?.id.replace(`{prefix}`,n),t.routingLineLayerNodeSpec.source=t.routingLineLayerNodeSpec?.source.replace(`{prefix}`,n),t.timeIsochronePolygonLayerSpec.id=t.timeIsochronePolygonLayerSpec?.id.replace(`{prefix}`,n),t.timeIsochronePolygonLayerSpec.source=t.timeIsochronePolygonLayerSpec?.source.replace(`{prefix}`,n),t.timeIsochroneLineLayerSpec.id=t.timeIsochroneLineLayerSpec?.id.replace(`{prefix}`,n),t.timeIsochroneLineLayerSpec.source=t.timeIsochroneLineLayerSpec?.source.replace(`{prefix}`,n),t.timeIsochroneLabelLayerSpec.id=t.timeIsochroneLabelLayerSpec?.id.replace(`{prefix}`,n),t.timeIsochroneLabelLayerSpec.source=t.timeIsochroneLabelLayerSpec?.source.replace(`{prefix}`,n),t.distanceIsochronePolygonLayerSpec.id=t.distanceIsochronePolygonLayerSpec?.id.replace(`{prefix}`,n),t.distanceIsochronePolygonLayerSpec.source=t.distanceIsochronePolygonLayerSpec?.source.replace(`{prefix}`,n),t.distanceIsochroneLineLayerSpec.id=t.distanceIsochroneLineLayerSpec?.id.replace(`{prefix}`,n),t.distanceIsochroneLineLayerSpec.source=t.distanceIsochroneLineLayerSpec?.source.replace(`{prefix}`,n),t.distanceIsochroneLabelLayerSpec.id=t.distanceIsochroneLabelLayerSpec?.id.replace(`{prefix}`,n),t.distanceIsochroneLabelLayerSpec.source=t.distanceIsochroneLabelLayerSpec?.source.replace(`{prefix}`,n),super({modes:t.modes,open:t.open,modeOptions:t.modeOptions,adapterOptions:t.adapterOptions}),this.valhallaOptions=t.valhallaOptions,!this.valhallaOptions.url)throw Error(`Valhalla URL is required for this control. Please set valhallaOptions.url in options.`);this._cssPrefix=`valhalla-`,this.controlOptions=t}onAdd(e){return this.controlContainer=super.onAdd(e),this.createSettingsDialog(),this.controlContainer}onRemove(){this.unregisterValhallaControl(),super.onRemove()}activate(){super.activate(),this.registerValhallaControl()}cleanStyle(e,t){let n=$,r=this.controlOptions.routingLineLayerNodeSpec?.source;r&&n.push(r);let i=this.controlOptions.timeIsochronePolygonLayerSpec?.source;i&&n.push(i);let a=this.controlOptions.distanceIsochronePolygonLayerSpec?.source;return a&&n.push(a),vr(e,t,n,this.options.adapterOptions?.prefixId)}createSettingsDialog(){this.settingDialog=new xr(`maplibregl-terradraw-${this.cssPrefix}settings-dialog`,`Settings`),this.settingDialog.create(this.map?.getContainer().parentElement,e=>{let t=document.createElement(`div`);t.classList.add(`tab-container`);let n=document.createElement(`div`);n.classList.add(`tab-buttons`);let r=document.createElement(`button`);r.type=`button`,r.classList.add(`tab-button`,`active`),r.textContent=`Routing`,r.addEventListener(`click`,e=>{e.stopPropagation(),this.switchTab(`routing`,n,a)}),n.appendChild(r);let i=document.createElement(`button`);i.type=`button`,i.classList.add(`tab-button`),i.textContent=`Isochrone`,i.addEventListener(`click`,e=>{e.stopPropagation(),this.switchTab(`isochrone`,n,a)}),n.appendChild(i),t.appendChild(n);let a=document.createElement(`div`);a.classList.add(`tab-contents`);let o=this.createRoutingContent();o.classList.add(`tab-content`,`active`),o.setAttribute(`data-tab`,`routing`),a.appendChild(o);let s=this.createIsochroneContent();return s.classList.add(`tab-content`),s.setAttribute(`data-tab`,`isochrone`),a.appendChild(s),t.appendChild(a),e.appendChild(t),e})}switchTab(e,t,n){t.querySelectorAll(`.tab-button`).forEach(e=>e.classList.remove(`active`)),t.querySelector(`[data-tab="${e}"], :nth-child(${e===`routing`?`1`:`2`})`)?.classList.add(`active`),n.querySelectorAll(`.tab-content`).forEach(e=>e.classList.remove(`active`)),n.querySelector(`[data-tab="${e}"]`)?.classList.add(`active`)}createRoutingContent(){let e=document.createElement(`div`),t=document.createElement(`div`);t.classList.add(`setting-section`);let n=document.createElement(`label`);n.textContent=`Means of Transport`,n.classList.add(`setting-label`),t.appendChild(n),t.appendChild(this.settingDialog.createSegmentButtons(Yr,this.routingCostingModel,e=>{this.valhallaOptions.routingOptions||(this.valhallaOptions.routingOptions={}),this.valhallaOptions.routingOptions.costingModel=e,this.dispatchEvent(`setting-changed`)})),e.appendChild(t);let r=document.createElement(`div`);r.classList.add(`setting-section`);let i=document.createElement(`label`);return i.textContent=`Distance Unit`,i.classList.add(`setting-label`),r.appendChild(i),r.appendChild(this.settingDialog.createSegmentButtons(Xr,this.routingDistanceUnit,e=>{this.valhallaOptions.routingOptions||(this.valhallaOptions.routingOptions={}),this.valhallaOptions.routingOptions.distanceUnit=e,this.dispatchEvent(`setting-changed`)})),e.appendChild(r),e}createIsochroneContent(){let e=document.createElement(`div`),t=document.createElement(`div`);t.classList.add(`setting-section`);let n=document.createElement(`label`);n.textContent=`Means of Transport (Time)`,n.classList.add(`setting-label`),t.appendChild(n),t.appendChild(this.settingDialog.createSegmentButtons(Yr,this.controlOptions.valhallaOptions?.isochroneOptions?.timeCostingModel||`auto`,e=>{this.valhallaOptions.isochroneOptions||(this.valhallaOptions.isochroneOptions={}),this.valhallaOptions.isochroneOptions.timeCostingModel=e,this.dispatchEvent(`setting-changed`)})),e.appendChild(t);let r=document.createElement(`div`);r.classList.add(`setting-section`);let i=document.createElement(`label`);i.textContent=`Means of Transport (Distance)`,i.classList.add(`setting-label`),r.appendChild(i),r.appendChild(this.settingDialog.createSegmentButtons(Yr,this.controlOptions.valhallaOptions?.isochroneOptions?.distanceCostingModel||`auto`,e=>{this.valhallaOptions.isochroneOptions||(this.valhallaOptions.isochroneOptions={}),this.valhallaOptions.isochroneOptions.distanceCostingModel=e,this.dispatchEvent(`setting-changed`)})),e.appendChild(r);let a=document.createElement(`div`);a.classList.add(`setting-section`);let o=document.createElement(`label`);o.textContent=`Contours`,o.classList.add(`setting-label`),a.appendChild(o);let s=this.createContoursTable();return a.appendChild(s),e.appendChild(a),e}createContoursTable(){let e=document.createElement(`div`);e.classList.add(`contours-table`);let t=document.createElement(`table`);t.classList.add(`contours-table-element`);let n=document.createElement(`thead`),r=document.createElement(`tr`),i=document.createElement(`th`);i.textContent=`Color`,r.appendChild(i);let a=document.createElement(`th`);a.textContent=`Time (min)`,r.appendChild(a);let o=document.createElement(`th`);o.textContent=`Distance (km)`,r.appendChild(o);let s=document.createElement(`th`);r.appendChild(s),n.appendChild(r),t.appendChild(n);let c=document.createElement(`tbody`),l=this.controlOptions.valhallaOptions?.isochroneOptions?.contours;l.forEach((e,t)=>{let n=this.createContourRow(e,t);c.appendChild(n)}),t.appendChild(c),e.appendChild(t);let u=document.createElement(`button`);return u.type=`button`,u.classList.add(`add-row-button`),u.textContent=`Add Contour`,u.hidden=l.length>=4,u.addEventListener(`click`,e=>{e.stopPropagation();let t=this.valhallaOptions.isochroneOptions?.contours,n=JSON.parse(JSON.stringify(t[t.length-1])),r=c.children.length,i=this.createContourRow(n,r);c.appendChild(i),t.push(n),this.updateAddRowButtonState(),this.dispatchEvent(`setting-changed`)}),e.appendChild(u),e}createContourRow(e,t){let n=document.createElement(`tr`);n.setAttribute(`data-index`,t.toString());let r=document.createElement(`td`),i=document.createElement(`input`);i.type=`color`,i.value=e.color,i.classList.add(`color-picker`),i.addEventListener(`change`,e=>{e.stopPropagation(),this.valhallaOptions.isochroneOptions?.contours&&(this.valhallaOptions.isochroneOptions.contours[t].color=e.target.value,this.dispatchEvent(`setting-changed`))}),r.appendChild(i),n.appendChild(r);let a=document.createElement(`td`),o=document.createElement(`input`);o.type=`number`,o.value=e.time.toString(),o.min=`1`,o.classList.add(`number-input`),o.addEventListener(`change`,e=>{e.stopPropagation(),this.valhallaOptions.isochroneOptions?.contours&&(this.valhallaOptions.isochroneOptions.contours[t].time=parseFloat(e.target.value),this.dispatchEvent(`setting-changed`))}),a.appendChild(o),n.appendChild(a);let s=document.createElement(`td`),c=document.createElement(`input`);c.type=`number`,c.value=e.distance.toString(),c.min=`0.1`,c.step=`0.1`,c.classList.add(`number-input`),c.addEventListener(`change`,e=>{e.stopPropagation(),this.valhallaOptions.isochroneOptions?.contours&&(this.valhallaOptions.isochroneOptions.contours[t].distance=parseFloat(e.target.value),this.dispatchEvent(`setting-changed`))}),s.appendChild(c),n.appendChild(s);let l=document.createElement(`td`);if(t>0){let e=document.createElement(`button`);e.type=`button`,e.textContent=`×`,e.classList.add(`delete-button`),e.addEventListener(`click`,e=>{e.stopPropagation();let t=parseInt(n.getAttribute(`data-index`)||`0`);n.remove(),this.valhallaOptions.isochroneOptions?.contours&&this.valhallaOptions.isochroneOptions.contours.splice(t,1);let r=n.parentElement;r&&Array.from(r.children).forEach((e,t)=>{e.setAttribute(`data-index`,t.toString())}),this.updateAddRowButtonState(),this.dispatchEvent(`setting-changed`)}),l.appendChild(e)}return n.appendChild(l),n}updateAddRowButtonState=()=>{let e=document.getElementsByClassName(`add-row-button`);if(e&&e.length>0){let t=e.item(0);t&&(t.hidden=(this.controlOptions.valhallaOptions?.isochroneOptions?.contours).length>=4)}};addTerradrawButton(e){let t=document.createElement(`button`);t.type=`button`,this.modeButtons[e]=t,e===`settings`?(t.classList.add(`maplibregl-terradraw-${this.cssPrefix}add-control`),t.classList.add(`maplibregl-terradraw-${this.cssPrefix}${e}-button`),t.addEventListener(`click`,this.handleSettingDialog.bind(this))):super.addTerradrawButton(e)}handleSettingDialog(){this.settingDialog?.open()}registerValhallaControl(){if(!this.map)return;let e=this.options.modes?.filter(e=>[`routing`].includes(e));e&&e.length>0&&(this.map.getSource(this.controlOptions.routingLineLayerNodeSpec.source)||this.map.addSource(this.controlOptions.routingLineLayerNodeSpec.source,{type:`geojson`,data:{type:`FeatureCollection`,features:[]}}),this.map.getLayer(this.controlOptions.routingLineLayerNodeSpec.id)||this.map.addLayer(this.controlOptions.routingLineLayerNodeSpec),this.map.getLayer(this.controlOptions.routingLineLayerNodeLabelSpec.id)||this.map.addLayer(this.controlOptions.routingLineLayerNodeLabelSpec));let t=this.options.modes?.filter(e=>[`time-isochrone`,`distance-isochrone`].includes(e));if(t&&t.length>0&&(this.map.getSource(this.controlOptions.timeIsochronePolygonLayerSpec.source)||this.map.addSource(this.controlOptions.timeIsochronePolygonLayerSpec.source,{type:`geojson`,data:{type:`FeatureCollection`,features:[]}}),this.map.getLayer(this.controlOptions.timeIsochronePolygonLayerSpec.id)||this.map.addLayer(this.controlOptions.timeIsochronePolygonLayerSpec),this.map.getLayer(this.controlOptions.timeIsochroneLineLayerSpec.id)||this.map.addLayer(this.controlOptions.timeIsochroneLineLayerSpec),this.map.getLayer(this.controlOptions.timeIsochroneLabelLayerSpec.id)||this.map.addLayer(this.controlOptions.timeIsochroneLabelLayerSpec),this.map.getSource(this.controlOptions.distanceIsochronePolygonLayerSpec.source)||this.map.addSource(this.controlOptions.distanceIsochronePolygonLayerSpec.source,{type:`geojson`,data:{type:`FeatureCollection`,features:[]}}),this.map.getLayer(this.controlOptions.distanceIsochronePolygonLayerSpec.id)||this.map.addLayer(this.controlOptions.distanceIsochronePolygonLayerSpec),this.map.getLayer(this.controlOptions.distanceIsochroneLineLayerSpec.id)||this.map.addLayer(this.controlOptions.distanceIsochroneLineLayerSpec),this.map.getLayer(this.controlOptions.distanceIsochroneLabelLayerSpec.id)||this.map.addLayer(this.controlOptions.distanceIsochroneLabelLayerSpec)),(e&&e.length>0||t&&t.length>0)&&this.map){let e=this.getTerraDrawInstance();e&&(e.on(`finish`,this.handleTerradrawFeatureReady.bind(this)),this.on(`feature-deleted`,this.onFeatureDeleted.bind(this)))}}unregisterValhallaControl(){if(this.off(`feature-deleted`,this.onFeatureDeleted.bind(this)),!this.map)return;this.map.getLayer(this.controlOptions.routingLineLayerNodeSpec.id)&&this.map.removeLayer(this.controlOptions.routingLineLayerNodeSpec.id),this.map.getLayer(this.controlOptions.routingLineLayerNodeLabelSpec.id)&&this.map.removeLayer(this.controlOptions.routingLineLayerNodeLabelSpec.id),this.map.getSource(this.controlOptions.routingLineLayerNodeSpec.source)&&this.map.removeSource(this.controlOptions.routingLineLayerNodeSpec.source),this.map.getLayer(this.controlOptions.timeIsochronePolygonLayerSpec.id)&&this.map.removeLayer(this.controlOptions.timeIsochronePolygonLayerSpec.id),this.map.getLayer(this.controlOptions.timeIsochroneLineLayerSpec.id)&&this.map.removeLayer(this.controlOptions.timeIsochroneLineLayerSpec.id),this.map.getLayer(this.controlOptions.timeIsochroneLabelLayerSpec.id)&&this.map.removeLayer(this.controlOptions.timeIsochroneLabelLayerSpec.id),this.map.getSource(this.controlOptions.timeIsochronePolygonLayerSpec.source)&&this.map.removeSource(this.controlOptions.timeIsochronePolygonLayerSpec.source),this.map.getLayer(this.controlOptions.distanceIsochronePolygonLayerSpec.id)&&this.map.removeLayer(this.controlOptions.distanceIsochronePolygonLayerSpec.id),this.map.getLayer(this.controlOptions.distanceIsochroneLineLayerSpec.id)&&this.map.removeLayer(this.controlOptions.distanceIsochroneLineLayerSpec.id),this.map.getLayer(this.controlOptions.distanceIsochroneLabelLayerSpec.id)&&this.map.removeLayer(this.controlOptions.distanceIsochroneLabelLayerSpec.id),this.map.getSource(this.controlOptions.distanceIsochronePolygonLayerSpec.source)&&this.map.removeSource(this.controlOptions.distanceIsochronePolygonLayerSpec.source);let e=this.getTerraDrawInstance();e&&e.off(`finish`,this.handleTerradrawFeatureReady.bind(this))}handleTerradrawFeatureReady=yr(e=>{this.map&&(this.computeRouteByLineFeatureID(e),this.computeIsochroneByPointFeatureID(e))},300);computeIsochroneByPointFeatureID=async e=>{if(!this.map||!this.valhallaOptions.url)return;let t=this.terradraw?.getSnapshotFeature(e);if(!t||t&&t.geometry.type!==`Point`)return;let n=t.geometry.coordinates,r=t.properties.mode===`time-isochrone`?`time`:`distance`,i=r===`time`?this.valhallaOptions.isochroneOptions?.timeCostingModel||`auto`:this.valhallaOptions.isochroneOptions?.distanceCostingModel||`auto`,a=(await new Jr(this.valhallaUrl).calcIsochrone(n[0],n[1],r,i,this.isochroneContours)).features.map(n=>(n.id=`${e}-${n.properties.contour}`,n.properties.originalId=e,n.properties.mode=t.properties.mode,n)),o={contourType:r,costingModel:i,result:a};if(t.properties={...t.properties,...o},this.terradraw?.updateFeatureProperties(e,o),r===`time`){let t=this.map.getStyle().sources[this.controlOptions.timeIsochronePolygonLayerSpec.source];t&&(typeof t.data!=`string`&&t.data.type===`FeatureCollection`&&(t.data.features=t.data.features.filter(t=>t.properties?.originalId!==e)),typeof t.data!=`string`&&t.data.type===`FeatureCollection`&&t.data.features.push(...a),this.map.getSource(this.controlOptions.timeIsochronePolygonLayerSpec.source)?.setData(t.data))}else{let t=this.map.getStyle().sources[this.controlOptions.distanceIsochronePolygonLayerSpec.source];t&&(typeof t.data!=`string`&&t.data.type===`FeatureCollection`&&(t.data.features=t.data.features.filter(t=>t.properties?.originalId!==e)),typeof t.data!=`string`&&t.data.type===`FeatureCollection`&&t.data.features.push(...a),this.map.getSource(this.controlOptions.distanceIsochronePolygonLayerSpec.source)?.setData(t.data)),this.map.moveLayer(this.controlOptions.timeIsochronePolygonLayerSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.moveLayer(this.controlOptions.distanceIsochronePolygonLayerSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.moveLayer(this.controlOptions.timeIsochroneLineLayerSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.moveLayer(this.controlOptions.distanceIsochroneLineLayerSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.moveLayer(this.controlOptions.timeIsochroneLabelLayerSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.moveLayer(this.controlOptions.distanceIsochroneLabelLayerSpec.id,this.options.adapterOptions?.renderBelowLayerId)}};computeRouteByLineFeatureID=async e=>{if(!this.map||!this.valhallaOptions.url)return;let n=this.terradraw?.getSnapshotFeature(e);if(!n||n&&n.geometry.type!==`LineString`)return;let r=new Zr(this.valhallaUrl),i=n.geometry.coordinates.map(e=>{let n=e;return new t.LngLat(n[0],n[1])});if(!i||i&&i.length<2)return;let a=await r.calcRoute(i,this.routingCostingModel,this.routingDistanceUnit);if(!a||!a.feature)return;let o=a?.feature.geometry;this.terradraw?.updateFeatureGeometry(e,o),n.geometry=o,n.properties={...n.properties,...a?.feature.properties},this.terradraw?.updateFeatureProperties(e,a?.feature.properties);let s=(a?.pointFeatures).features.map(t=>(t.id=`${e}-${t.id}`,t.properties.originalId=e,t)),c=this.map.getStyle().sources[this.controlOptions.routingLineLayerNodeSpec.source];c&&(typeof c.data!=`string`&&c.data.type===`FeatureCollection`&&(c.data.features=c.data.features.filter(t=>t.properties?.originalId!==e)),typeof c.data!=`string`&&c.data.type===`FeatureCollection`&&c.data.features.push(...s),this.map.getSource(this.controlOptions.routingLineLayerNodeSpec.source)?.setData(c.data),this.map.moveLayer(this.controlOptions.routingLineLayerNodeSpec.id,this.options.adapterOptions?.renderBelowLayerId),this.map.moveLayer(this.controlOptions.routingLineLayerNodeLabelSpec.id,this.options.adapterOptions?.renderBelowLayerId))};onFeatureDeleted(e){if(this.map&&this.getTerraDrawInstance()){let t=[];typeof e==`object`&&e&&`deletedIds`in e&&(t=e.deletedIds);let n=[this.controlOptions.routingLineLayerNodeSpec,this.controlOptions.timeIsochronePolygonLayerSpec,this.controlOptions.distanceIsochronePolygonLayerSpec].map(e=>e.source);t&&t.length>0?this.clearExtendedFeatures(n,t):this.clearExtendedFeatures(n,void 0)}}getFeatures(e=!1){let t=super.getFeatures(e);if(!t||!this.terradraw||!this.map)return t;let n=this.map.getStyle();if(!n||!n.sources)return t;let r=this.controlOptions.timeIsochronePolygonLayerSpec.source;if(!r||!n.sources[r])return t;let i=this.controlOptions.distanceIsochronePolygonLayerSpec.source;if(!i||!n.sources[i])return t;let a=n.sources[r],o=n.sources[i],s=[];for(let e=0;e<t.features.length;e++){let n=t.features[e];if(n.geometry.type===`Point`){let e=n.id;if(a&&typeof a.data!=`string`&&a.data.type===`FeatureCollection`){let t=a.data.features.filter(t=>t.properties?.originalId===e);s.push(n),t.length>0&&s.push(...t)}if(o&&typeof o.data!=`string`&&o.data.type===`FeatureCollection`){let t=o.data.features.filter(t=>t.properties?.originalId===e);s.push(n),t.length>0&&s.push(...t)}}else s.push(n)}return{type:`FeatureCollection`,features:s}}};e.AWS_ELEVATION_TILES=Pn,e.AvailableModes=An,e.AvailableValhallaModes=jn,e.MAPTERHORN_TILES=Fn,e.MaplibreMeasureControl=ei,e.MaplibreTerradrawControl=Qr,e.MaplibreValhallaControl=ti,e.MemoryCache=br,e.ModalDialog=xr,e.TERRADRAW_MEASURE_SOURCE_IDS=gr,e.TERRADRAW_SOURCE_IDS=$,e.TERRADRAW_VALHALLA_SOURCE_IDS=_r,e.ValhallaIsochrone=Jr,e.ValhallaRouting=Zr,e.calcArea=or,e.calcDistance=mr,e.capitalize=hr,e.cleanMaplibreStyle=vr,e.contourTypeOptions=qr,e.convertArea=nr,e.convertDistance=ur,e.convertElevation=Q,e.costingModelOptions=Yr,e.debounce=yr,e.defaultControlOptions=Mn,e.defaultMeasureControlOptions=In,e.defaultMeasureUnitSymbols=Y,e.defaultValhallaControlOptions=X,e.getDefaultModeOptions=zn,e.polygonValidation=Rn,e.queryElevationByPoint=Sr,e.queryElevationFromRasterDEM=Gr,e.roundFeatureCoordinates=Kr,e.routingDistanceUnitOptions=Xr});
//# sourceMappingURL=maplibre-gl-terradraw.umd.js.map