UNPKG

@arcgis/core

Version:

ArcGIS Maps SDK for JavaScript: A complete 2D and 3D mapping and data visualization API

3 lines (2 loc) • 20.7 kB
/* COPYRIGHT Esri - https://js.arcgis.com/5.0.8/LICENSE.txt */ import{__addDisposableResource as e,__disposeResources as t,__decorate as i}from"tslib";import{disposable as a}from"../../core/handleUtils.js";import n from"../../core/Logger.js";import{getOrCreateMapValue as r}from"../../core/MapUtils.js";import{destroyMaybe as o}from"../../core/maybe.js";import{when as s,initial as d,on as l,sync as p,watch as c}from"../../core/reactiveUtils.js";import{screenPointEqual as u,createScreenPoint as h}from"../../core/screenUtils.js";import{diff as g}from"../../core/accessorSupport/diffUtils.js";import{property as m}from"../../core/accessorSupport/decorators/property.js";import{subclass as v}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as y}from"../../core/support/UpdatingHandles.js";import f from"../../geometry/Polygon.js";import{i as M,e as _}from"../../chunks/simplifyOperator.js";import{isExtent as w}from"../../geometry/support/jsonTypeUtils.js";import{isPolygon as b}from"../../geometry/support/typeUtils.js";import{isCurvedGeometry as C}from"../../geometry/support/curves/curveUtils.js";import{densifyCurvedGeometry as H}from"../../geometry/support/curves/densifyCurvedGeometry.js";import{getMaxDeviationInPixels as P,getMinSegmentsPerCurve as S}from"../2d/layers/graphics/densificationConstants.js";import{createSnappingVisualizer as x}from"./support/createSnappingVisualizer.js";import{multipointFromGeometry as k,markHandled as j,getPointerType as E}from"./support/drawToolUtils.js";import{PluginContext as T}from"./support/PluginContext.js";import{viewEventToCommand as G}from"./support/input/drawToolInput.js";import{EditSessionManager as O}from"./support/managers/EditSessionManager.js";import{GlobalStateManager as V}from"./support/managers/GlobalStateManager.js";import{InteractiveHandleManager as I}from"./support/managers/InteractiveHandleManager.js";import{MeasurementManager as A}from"./support/managers/MeasurementManager.js";import{PluginLifecycleManager as U}from"./support/managers/PluginLifecycleManager.js";import{SurfaceManager as R}from"./support/managers/SurfaceManager.js";import{TooltipManager as F}from"./support/managers/TooltipManager.js";import{ViewEventPriorities as D}from"../input/InputManager.js";import{createCoordinateHelper as L}from"../interactive/coordinateHelper.js";import{InteractiveToolBase as Z}from"../interactive/InteractiveToolBase.js";import{KeyBindings as q,mediaKeys as B,sketchKeys as z,advancedSketchKeys as K,tooltipKeys as Q}from"../interactive/keybindings.js";import{isInputModeAvailable as N}from"../interactive/tooltip/tooltipCommonUtils.js";const W=Symbol();let $=class extends Z{constructor(e){super(e),this._shapeVisualId=Symbol(),this._vertexVisualId=Symbol(),this._pluginContexts=new Map,this._queuedFeedbackEvents=[],this._flushingQueuedFeedbackEvents=!1,this._snappingVisualizer=null,this._updatingHandles=new y,this._keybindings=this._makeKeyBindings(),this._pendingBeginRequest=null,this.type="draw-2.0",this.automaticManipulatorSelection=!0,this.snappingManager=null,this.sketchOptions=null,this.elevationInfo=null,this.hasZ=!1,this.defaultZ=0,this.lastScreenPosition=null,this.measurementManager=new A,this.globalStateManager=new V({getPluginStack:()=>this.pluginStack}),this.editSessionManager=new O({getContext:()=>this._editSessionManagerContext}),this.lifecycleManager=new U({getContext:this._getContextForPlugin.bind(this),editSessionManager:this.editSessionManager,afterAttach:this._afterAttach.bind(this),afterDetach:this._afterDetach.bind(this),beforeResume:this._beforeResume.bind(this)}),this.surfaceManager=null,this.interactiveHandleManager=null,this.renderer=null,this.enableVertexVisuals=!0}initialize(){const{view:e}=this;this.interactiveHandleManager=new I({view:e,renderer:this.renderer}),this._override("manipulators",this.interactiveHandleManager.manipulators),this.tooltipManager=new F({getDependencies:()=>this._tooltipDependencies,getLastScreenPosition:()=>this.lastScreenPosition}),this.addHandles(s(()=>this.renderer,t=>{t.addOrUpdateVisual(this._shapeVisualId,{role:"outputGeometry"}),t.addOrUpdateVisual(this._vertexVisualId,{role:"vertex"}),this._updatingHandles.addPromise(x(e,t).then(e=>this._snappingVisualizer=e))},d)),this.addHandles([s(()=>this.view,e=>{this.surfaceManager?.destroy(),this.surfaceManager=new R({spatialReference:this.coordinateHelper.spatialReference,excludedGraphicsLayer:null,defaultZ:this.defaultZ,hasZ:this.hasZ,view:e,elevationInfo:this.elevationInfo,getContext:()=>({drawAtFixedElevation:this.globalStateManager.drawAtFixedElevation,elevationConstraint:this.tooltipManager?.elevationConstraint,constraintsEnabled:this.tooltipManager?.constraintsEnabled??!1})})},d),s(()=>this.sketchOptions?.tooltips.effectiveEnabled,()=>this.measurementManager.preloadMeasurementUtils(),{once:!0,initial:!0}),l(()=>this.editSessionManager,"cancelPlugin",({plugin:e})=>{this._suspendPlugin(e)},p),l(()=>this.editSessionManager,"restartPlugin",({restartInfo:e})=>{this._resumePlugin(e)},p),c(()=>this.lifecycleManager.updating,e=>{e||this._emitQueuedFeedbackEvents()},p),l(()=>this.editGeometryOperations,["vertex-add","vertex-update","vertex-remove"],e=>{const t=e.vertices.map(e=>({componentIndex:0,vertexIndex:e.index,coordinates:this.coordinateHelper.vectorToArray(e.pos)})),i=t.map(e=>e.coordinates);switch(e.type){case"vertex-add":this._emitWhenReady(e.type,{...e,added:i,vertices:t});break;case"vertex-update":this._emitWhenReady(e.type,{...e,updated:i,vertices:t});break;case"vertex-remove":this._emitWhenReady(e.type,{...e,removed:i,vertices:t})}})])}destroy(){this.active&&this.onDeactivate(),this.editSessionManager.destroy(),this.lifecycleManager.destroy(),this.measurementManager.destroy(),this.globalStateManager.destroy();for(const e of this._pluginContexts.values())e.destroy();this._pluginContexts.clear(),this.surfaceManager=o(this.surfaceManager),this.interactiveHandleManager=o(this.interactiveHandleManager),this.tooltipManager=o(this.tooltipManager)}get _tooltipDependencies(){const{defaultZ:e,editGeometryOperations:t,sketchOptions:i,directionOptions:a,view:n}=this;return t&&i&&n?{defaultZ:e,directionOptions:a,editGeometryOperations:t,sketchOptions:i,view:n,getActiveHandle:()=>this.interactiveHandleManager?.focusedHandle,getAllHandles:()=>this.interactiveHandleManager?.allhandles,getHelpMessageKey:()=>this.helpMessageKey,notifyTooltipsChanged:()=>{const{interactiveHandleManager:e,movementCommandContext:t}=this;e&&t&&e.reapplyPositions(t)}}:null}get _editSessionManagerContext(){const{coordinateHelper:e,view:t}=this;if(!t)return null;return{coordinateHelper:e,viewingMode:"3d"===t.type&&"global"===t.viewingMode?1:2}}get _densificationParameters(){const{view:e,coordinateHelper:t}=this,i=t.spatialReference,a=e?.spatialReference,n=e.resolution;if(!(i&&a&&n&&Number.isFinite(n)))return null;const r=a.metersPerUnit/i.metersPerUnit;return{maxDeviation:2**Math.round(Math.log2(n))*P()*r,minSegmentsPerCurve:S()}}get test(){return{densificationParameters:this._densificationParameters}}get updating(){return this._updatingHandles.updating||this.lifecycleManager.updating}get coordinateHelper(){return L(this.hasZ,!1,this.view.spatialReference)}get editGeometry(){return this.editGeometryOperations?.data}get editGeometryOperations(){return this.editSessionManager.editGeometryOperations}get unprocessedGeometry(){return this.editSessionManager.outputGeometry}get simplifiedGeometryPreview(){const e=this.editSessionManager.outputGeometry;if(e&&b(e))try{const t=this._densificationParameters,i=C(e)&&t?new f({...H(e,t)}):e;if(!M(i))return _(i)}catch(t){return e}return e}get canUndo(){return this.editSessionManager.canUndo}get canRedo(){return this.editSessionManager.canRedo}get pluginStack(){return this.lifecycleManager.pluginStack}get mostDownstreamPlugin(){return this.pluginStack.at(-1)}get mostUpstreamPlugin(){return this.pluginStack.at(0)}get positionOfLastUserInput(){return this.lastScreenPosition?this.view.toMap(this.lastScreenPosition):this.view.center}get movementCommandContext(){const{editGeometryOperations:e,tooltipManager:t,surfaceManager:i,snappingManager:a,interactiveHandleManager:n,_snappingVisualizer:r,defaultZ:o,hasZ:s,globalStateManager:{drawAtFixedElevation:d},view:l}=this;return{tooltipManager:t,editGeometryOperations:e,surfaceManager:i,interactiveHandleManager:n,snappingManager:a,snappingVisualizer:r,pointerType:"mouse",hasZ:s,defaultZ:o,view:l,drawAtFixedElevation:d}}get tooltip(){return this.tooltipManager?.tooltip}get activeTooltipInfo(){return this.tooltipManager?.tooltipInfo}get helpMessageKey(){return this.pluginStack.items.findLast(e=>e.helpMessageKey)?.helpMessageKey??"noTool"}begin(e){this.active?(this.lifecycleManager.begin(e),this._pendingBeginRequest=null):this._pendingBeginRequest=e}complete(e){const t=this.lifecycleManager;e&&t.complete(e),0===t.pluginStack.length&&(this._finalizeAndSimplifyGeometryResult(),this.emit("complete",{geometry:this.finalGeometry,aborted:!1,type:"complete",vertices:[]}),this.view?.activeTool===this&&(this.view.activeTool=null))}cancelFirstUserLeafPlugin(){const e=this.pluginStack.toArray().findLast(e=>!0!==e.configuration?.hidden);e&&this.lifecycleManager.cancel(e)}replaceLeaf(e){const t=this.lifecycleManager;t.updating?n.getLogger(this).info("Ignoring command; arrived while updating:","replaceLeaf"):t.replaceLeaf(e)}finishPart(){const e=this.mostUpstreamPlugin,t=e?.configuration;if(this.editGeometryOperations&&t&&t.kind?.includes("multipart")){const e=this.pluginStack.at(1);e&&this.complete(e)}}undo(){this._guardCommand({action:"undo"},()=>this.editSessionManager.undo())}redo(){this._guardCommand({action:"redo"},()=>this.editSessionManager.redo())}executeCommand(e){return this._handleCommand(e)}addPromise(e){return this._updatingHandles.addPromise(e)}getGeometryIfCompleted(){const e=this.lifecycleManager.gatherCompletablePlugins();return this.editSessionManager?.generatePreviewGeometryForPlugins(e)}onActivate(){super.onActivate();const{view:e}=this;this.lastScreenPosition=e?.inputManager.latestPointerInfo?.location,this.renderer?.activate(),this._pendingBeginRequest&&(this.begin(this._pendingBeginRequest),this._pendingBeginRequest=null),this.enableVertexVisuals&&this.addHandles(c(()=>this.unprocessedGeometry,e=>{this.renderer?.addOrUpdateVisual(this._vertexVisualId,{geometry:e?k(e):null})},d)),this.addHandles([c(()=>this.simplifiedGeometryPreview,e=>{this.renderer?.addOrUpdateVisual(this._shapeVisualId,{geometry:e})},d),s(()=>this.interactiveHandleManager?.capturingHandle?.screenPosition,e=>this.lastScreenPosition=e,{initial:!0,equals:u}),c(()=>this.interactiveHandleManager?.capturingHandle?.outputMapPosition,(e,t)=>{const i=this.interactiveHandleManager?.capturingHandle?.editSession?.endVertex;e&&t&&i&&this._emitWhenReady("cursor-update",{updated:i.pos,type:"vertex-update",operation:"apply",vertices:[{componentIndex:i.part.index,vertexIndex:i.index,coordinates:i.pos}]})},p),this._keybindings.register(e,D.TOOL),c(()=>e.viewpoint,(e,t)=>{e&&t&&g(e,t)&&this._handleCommand({action:"viewpoint-moved"})})],W)}onDeactivate(){super.onDeactivate(),this.removeHandles(W),this.renderer?.deactivate(),this.snappingManager?.doneSnapping(),this.lifecycleManager.cancelAll(),this._pendingBeginRequest=null}onInputEvent(e){const t=G(e);t&&this._handleCommand(t)}_emitWhenReady(e,t){if(this.destroyed)return;const i=()=>{this.emit(e,t)};this.lifecycleManager.updating||this._flushingQueuedFeedbackEvents?this._queuedFeedbackEvents.push(i):i()}_emitQueuedFeedbackEvents(){if(!(this.destroyed||this._flushingQueuedFeedbackEvents||this.lifecycleManager.updating||0===this._queuedFeedbackEvents.length)){this._flushingQueuedFeedbackEvents=!0;try{for(;!this.destroyed&&!this.lifecycleManager.updating&&this._queuedFeedbackEvents.length>0;)this._queuedFeedbackEvents.shift()?.()}finally{this._flushingQueuedFeedbackEvents=!1}}}async _handleCommand(e){if(this.lifecycleManager.updating)n.getLogger(this).info("Ignoring command; arrived while updating:",e.action);else switch(e.action){case"view-drag":return await this._handleViewDragCommand(e);case"vertex-add":return this._guardCommand(e,()=>{j(e),this._commitNext()});case"vertex-add-and-finish-part":return this._handleVertexAddAndFinishPartCommand(e);case"cancel":return this._guardCommand(e,()=>this.cancel());case"complete":return this._guardCommand(e,()=>{this.mostUpstreamPlugin&&(j(e),this.complete(this.mostUpstreamPlugin))});case"finish-part":return this._guardCommand(e,()=>this.finishPart());case"undo":return this._guardCommand(e,()=>this.editSessionManager.undo());case"redo":return this._guardCommand(e,()=>this.editSessionManager.redo());case"next-manipulator":return this._guardCommand(e,()=>this.interactiveHandleManager?.cycleManipulator("forward"));case"previous-manipulator":return this._guardCommand(e,()=>this.interactiveHandleManager?.cycleManipulator("backward"));case"toggle-manipulator-follow":this.interactiveHandleManager?.toggleFollow()&&j(e);break;case"viewpoint-moved":return await this._handleViewpointMovedCommand(e);case"manipulator-move-to":return await this._handleManipulatorMoveToCommand(e);case"manipulator-drag-to":return await this._handleManipulatorDragToCommand(e);case"vertex-add-at-point":return await this._handleVertexAddAtPointCommand(e);case"show-tooltip":return this._guardCommand(e,async()=>{const t=this.tooltipManager?.tooltip;t&&N(t.info)&&(await t.enterInputMode(),j(e))});case"constraint-center":this.globalStateManager.setCentered(e.enabled);break;case"constraint-aspect":this.globalStateManager.setPreserveAspectRatio(e.enabled)}}async _handleViewDragCommand(e){if(!this.editable)return;const t=e.originalEvent,i=this.interactiveHandleManager?.capturingHandle;(!t||!("pointerType"in t)||"touch"!==t.pointerType||"capture-always"!==i?.captureMode&&"capture-when-engaged"!==i?.captureMode)&&"capture-when-engaged"!==this.interactiveHandleManager?.capturingHandle?.captureMode?this._before(e)&&j(e):j(e)}_handleVertexAddAndFinishPartCommand(e){this._before(e)||(j(e),this._commitNext(),this.finishPart())}async _handleViewpointMovedCommand(e){this.editable&&(await this._updatingHandles.addPromise(this.interactiveHandleManager?.capturingHandle?.moveTo(null,{...this.movementCommandContext,pointerType:E(e.originalEvent)})),this.interactiveHandleManager?.updateAllScreenPositions())}async _handleManipulatorMoveToCommand(e){if(!this.editable)return;const t=this._updateLastScreenPosition(e);this.interactiveHandleManager?.capturingHandle&&j(e),await this._updatingHandles.addPromise(this.interactiveHandleManager?.capturingHandle?.moveTo(t,{...this.movementCommandContext,pointerType:E(e.originalEvent)}))}async _handleManipulatorDragToCommand(e){if(!this.editable)return;const t=E(e.originalEvent),i=this._updateLastScreenPosition(e),a=this.interactiveHandleManager?.findHandleByManipulator(i);"touch"===t&&a&&"start"===e.state&&this.interactiveHandleManager?.releaseHandle();const n=this.interactiveHandleManager?.findHandleDragging(),r=this.interactiveHandleManager?.capturingHandle,o=n??r??a;o&&!a&&j(e),"capture-when-engaged"===o?.captureMode||"capture-always"===o?.captureMode&&"touch"===t?"end"===e.state?await this._updatingHandles.addPromise(o.noteDragEnd(i,{...this.movementCommandContext,pointerType:t}).then(()=>{o&&"touch"===E(e.originalEvent)&&"grabbable-object"!==o.captureMode&&"capture-when-engaged"!==o.defaultCaptureMode&&"primary"===o.role&&(1===this.interactiveHandleManager?.handleCount?this._handleCommand({action:"vertex-add"}):this.interactiveHandleManager?.releaseHandle())})):"start"===e.state?await this._updatingHandles.addPromise(o.noteDragStart(i,{...this.movementCommandContext,pointerType:t}).then(()=>{o&&"touch"===E(e.originalEvent)&&"grabbable-object"!==o.captureMode&&"capture-when-engaged"!==o.defaultCaptureMode&&!o.editSession?.lastPointAddedBySession&&this._handleCommand({action:"vertex-add"})})):await this._updatingHandles.addPromise(o?.moveTo(i,{...this.movementCommandContext,pointerType:E(e.originalEvent)})):"grabbable-object"===o?.captureMode&&(this.interactiveHandleManager?.releaseHandle(r),await this._updatingHandles.addPromise(o.moveTo(i,{...this.movementCommandContext,pointerType:t})))}async _handleVertexAddAtPointCommand(e){const t=this._updateLastScreenPosition(e),i=this.interactiveHandleManager?.capturingHandle??this.interactiveHandleManager?.findHandleByManipulator(t);this.editable&&i&&(this._before(e)||(j(e),await this._updatingHandles.addPromise(i.moveTo(t,{...this.movementCommandContext,skipSnapping:!0,pointerType:E(e.originalEvent)}).finally(()=>this._commitNext()))))}_makeKeyBindings(){const e=new q,t=(t,i)=>{e.addToggle(t,e=>this._handleCommand({action:i,originalEvent:e,enabled:"key-down"===e.type}))},i=(t,i)=>{e.add(t,e=>this._handleCommand({action:i,originalEvent:e}))};return t(B.preserveAspectRatio,"constraint-aspect"),t(z.center,"constraint-center"),i(K.toggleFollowManipulator,"toggle-manipulator-follow"),i(z.undo,"undo"),i(z.redo,"redo"),i(z.complete,"complete"),i(z.vertexAdd,"vertex-add"),i({key:Q.enterInputMode,continuePropagation:!0,repeats:!0},"show-tooltip"),e}_afterAttach(){}_afterDetach(e){this.interactiveHandleManager?.unregisterCustomConstraint(e),this.interactiveHandleManager?.unregisterHandle(e),this.tooltipManager?.unregisterPluginFields(e),this.globalStateManager.clearPluginOverrides(e);const t=this._pluginContexts.get(e);t&&(t.destroy(),this._pluginContexts.delete(e))}_beforeResume(e,t){this.interactiveHandleManager?.replaceEditSessions(e,t)}_commitNext(){const i={stack:[],error:void 0,hasError:!1};try{const t=this.mostDownstreamPlugin;if(!t)return;this.tooltipManager?.storeConstraintSnapshot();let n=!1;const r=this.editGeometryOperations;e(i,r?a(r.on("vertex-add",()=>n=!0)):null,!1);t.completeStep?t.completeStep():this.complete(t),n&&this.tooltipManager?.unlockOnVertexPlacement()}catch(n){i.error=n,i.hasError=!0}finally{t(i)}}_suspendPlugin(e){this.lifecycleManager.suspend(e),this.measurementManager.suspendPlugin(e)}_resumePlugin(e){this.lifecycleManager.resume(e)}_updateLastScreenPosition(e){const t=h(e.x,e.y);return this.lastScreenPosition=t,t}_getContextForPlugin(e,t){const i=r(this._pluginContexts,e,()=>new T({drawTool:this,plugin:e,session:t}));return i.session=t,i}_finalizeAndSimplifyGeometryResult(){const e=this.unprocessedGeometry;try{const t=e?_(e):e;t&&!w(t)?this.finalGeometry=t:this.finalGeometry=e}catch(t){n.getLogger(this).error("draw-tool:complete","geometry simplification failed",t)}}_before(e){if(!this.hasEventListener(`before-${e.action}`))return!1;const t=new CustomEvent(`before-${e.action}`,{detail:e,cancelable:!0});return this.emit(`before-${e.action}`,t),t.defaultPrevented}_guardCommand(e,t,i){return this._before(e)?i?.():t()}};i([m()],$.prototype,"_snappingVisualizer",void 0),i([m()],$.prototype,"_tooltipDependencies",null),i([m()],$.prototype,"_editSessionManagerContext",null),i([m()],$.prototype,"_densificationParameters",null),i([m({constructOnly:!0,nonNullable:!0})],$.prototype,"view",void 0),i([m()],$.prototype,"automaticManipulatorSelection",void 0),i([m()],$.prototype,"updating",null),i([m()],$.prototype,"coordinateHelper",null),i([m()],$.prototype,"editGeometry",null),i([m()],$.prototype,"editGeometryOperations",null),i([m()],$.prototype,"unprocessedGeometry",null),i([m()],$.prototype,"finalGeometry",void 0),i([m()],$.prototype,"simplifiedGeometryPreview",null),i([m()],$.prototype,"snappingManager",void 0),i([m()],$.prototype,"sketchOptions",void 0),i([m()],$.prototype,"elevationInfo",void 0),i([m()],$.prototype,"hasZ",void 0),i([m()],$.prototype,"defaultZ",void 0),i([m()],$.prototype,"directionOptions",void 0),i([m()],$.prototype,"canUndo",null),i([m()],$.prototype,"canRedo",null),i([m()],$.prototype,"pluginStack",null),i([m()],$.prototype,"mostDownstreamPlugin",null),i([m()],$.prototype,"mostUpstreamPlugin",null),i([m()],$.prototype,"lastScreenPosition",void 0),i([m()],$.prototype,"positionOfLastUserInput",null),i([m()],$.prototype,"tooltipManager",void 0),i([m()],$.prototype,"measurementManager",void 0),i([m()],$.prototype,"globalStateManager",void 0),i([m()],$.prototype,"editSessionManager",void 0),i([m()],$.prototype,"lifecycleManager",void 0),i([m()],$.prototype,"surfaceManager",void 0),i([m()],$.prototype,"interactiveHandleManager",void 0),i([m()],$.prototype,"renderer",void 0),i([m()],$.prototype,"movementCommandContext",null),i([m()],$.prototype,"tooltip",null),i([m()],$.prototype,"activeTooltipInfo",null),i([m()],$.prototype,"helpMessageKey",null),i([m({constructOnly:!0})],$.prototype,"enableVertexVisuals",void 0),$=i([v("esri.views.draw.DrawTool")],$);export{$ as DrawTool};