UNPKG

@arcgis/core

Version:

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

3 lines (2 loc) • 30.9 kB
/* COPYRIGHT Esri - https://js.arcgis.com/5.0.8/LICENSE.txt */ import{__decorate as e}from"tslib";import{isSome as t}from"../../core/arrayUtils.js";import{createTask as i}from"../../core/asyncUtils.js";import o from"../../core/Collection.js";import{deprecatedFunction as r}from"../../core/deprecate.js";import a from"../../core/Error.js";import{EventedAccessor as s}from"../../core/Evented.js";import{abortHandle as n,makeHandle as l}from"../../core/handleUtils.js";import"../../core/has.js";import c from"../../core/Logger.js";import{destroyMaybe as d,abortMaybe as p,removeMaybe as h}from"../../core/maybe.js";import{throwIfAborted as u,createResolver as w}from"../../core/promiseUtils.js";import f from"../../core/ReactiveMap.js";import{watch as m,syncAndInitial as y,initial as g,on as k,when as v,sync as _,whenOnce as W}from"../../core/reactiveUtils.js";import{property as M,subclass as T}from"../../core/accessorSupport/decorators.js";import{UpdatingHandles as F}from"../../core/support/UpdatingHandles.js";import{getTemplatesForLayers as b}from"../../editing/templateUtils.js";import{getGraphicLayer as V}from"../../graphic/graphicOriginUtils.js";import S from"../../layers/GraphicsLayer.js";import{isEditableLayer as I}from"../../layers/support/editableLayers.js";import{isFeatureLayer as L,isSubtypeGroupLayer as E,getOwningPortalUrl as C}from"../../layers/support/layerUtils.js";import{parseKnownArcGISOnlineDomain as A}from"../../portal/support/urlUtils.js";import U from"../../views/SelectionManager.js";import O from"../../views/interactive/sketch/SketchLabelOptions.js";import j from"../../views/interactive/sketch/SketchOptions.js";import P from"../../views/interactive/sketch/SketchTooltipOptions.js";import R from"../../views/interactive/sketch/SketchValueOptions.js";import{SnappingManager as H}from"../../views/interactive/snapping/SnappingManager.js";import q from"../../views/interactive/snapping/SnappingOptions.js";import{isISelectableLayer as x}from"../../views/support/selectionUtils.js";import G from"../Attachments/AttachmentsViewModel.js";import D from"./CreateFeaturesWorkflow.js";import B from"./UpdateWorkflow.js";import{getLayersFromWorkflow as N,isCreateFeaturesWorkflow as Q,isUpdateRecordWorkflow as z,isUpdateFeaturesWorkflow as Z,isMergeFeaturesWorkflow as $,isSplitFeatureWorkflow as J,isUpdateWorkflow as K,isFeatureFormViewModel as X,findEditorItemForLayerOrThrow as Y,toFeatureInfos as ee,fetchFullFeaturesByObjectId as te,fetchFullFeatures as ie,findEditorItemForLayer as oe,whenEditorLayerView as re,isBatchAttributeFormViewModel as ae}from"./workflowUtils.js";import se from"./support/EditorItem.js";import{assertViewNot3D as ne,MultipleSourceLayersError as le,InsufficientFeatureCountError as ce,MissingOriginLayerError as de,assertMergeWorkflowCapabilities as pe,FetchFullFeatureError as he,assertSplitWorkflowCapabilities as ue}from"./support/errors.js";import{makeTemplateGroupInfoForLayer as we}from"../FeatureTemplates/featureTemplatesUtils.js";import fe from"../FeatureTemplates/FeatureTemplatesViewModel.js";import me from"../Sketch/SketchViewModel.js";import ye from"../Spinner/SpinnerViewModel.js";import{goTo as ge}from"../support/goToUtils.js";import{isFeatureItem as ke,isLayerItem as ve}from"../support/SelectionList/selectionListUtils.js";import _e from"../support/SelectionList/SelectionListViewModel.js";import We from"../support/SelectionToolbar/SelectionToolbarViewModel.js";function Me(e,t){return e?.find(e=>e.layer===t)}let Te=class extends s{constructor(e){super(e),this._defaultSelectionManager=new U,this._queuedSelectionTool=null,this._sketchEventListenerHandle=null,this._sketchGraphicsLayer=new S({listMode:"hide",internal:!0,title:"Editor sketch layer"}),this._snappingManager=null,this._templatesByLayer=new Map,this._updateItemsTask=null,this._updateTemplatesTask=null,this._updatingHandles=new F,this._featureTemplatesViewModelIsRestricted=!1,this.activeWorkflow=null,this._activityQueue=new o,this.editorItems=new o,this.editorItemsLayerMap=new f,this.failures=[],this.hideTemplatesForInactiveLayers=!1,this.attachmentsViewModel=new G({capabilities:{editing:!0}}),this.featureTemplatesViewModel=new fe({disabledItemFunction:({layer:e})=>this._itemIsSuspended(e)}),this.layerInfos=null,this.ownSketchViewModel=new me({layer:this._sketchGraphicsLayer,useLegacyCreateTools:this._get("useLegacyCreateTools")??!0}),this.selectionListViewModel=new _e,this.selectionManager=null,this.selectionToolbarViewModel=new We({continuousSelectionEnabled:!0,defaultOperationType:"replace",persistSelection:!1,returnGeometry:!1}),this.sketchOptions=new j,this.snappingOptions=new q({attributeRulesEnabled:!0}),this.spinnerViewModel=new ye,this.syncViewSelection=!1,this.pageStack=[],this.showDiscardEditsPrompt=()=>Promise.resolve(!0),this.showConfirmationPrompt=()=>Promise.resolve(!0),this._candidateCommitted=!1,this.back=async()=>{if("viewing-selection-list"===this.state)return this.selectionListViewModel.filterText=void 0,void this.effectiveSelectionManager.clear();this.canGoBack&&(this.activeWorkflow?.hasPreviousStep?await this.activeWorkflow.back(this.showDiscardEditsPrompt):await this._cancelWorkflow({force:!this.hasPendingEdits}))},this.saveWorkflow=async()=>await(this.activeWorkflow?.save(this.showConfirmationPrompt)),this.selectFeature=(e,t=!1)=>{const i=this.activeWorkflow;if(this._candidateCommitted||"update"!==i?.type)return;const{rootFeatures:o}=i.data;o.removeAll(),e&&o.add(e),t&&(i.next(),this._candidateCommitted=!0)}}initialize(){this.addHandles([m(()=>{const e=this.view,t=e?.map?.editableLayers.toArray(),i=e?.allLayerViews,o=i?.filter(e=>!!t?.includes(e.layer));return[t,o,this.layerInfos]},()=>this._updateEditorItems(),y),m(()=>this.hideTemplatesForInactiveLayers,()=>this.syncFeatureTemplates()),m(()=>this._selectionSources,()=>this._syncSelectionSources(),g),k(()=>this.activeWorkflow,"cancel",()=>this.emit("workflow-cancel")),k(()=>this.activeWorkflow,"commit",()=>this.emit("workflow-commit")),k(()=>this.activeWorkflow,"complete",()=>{this.emit("workflow-commit"),this._set("activeWorkflow",null)}),v(()=>!this.activeWorkflow&&this._queuedSelectionTool,()=>this._queuedSelectionTool&&this.selectionToolbarViewModel.activateTool(this._queuedSelectionTool)),m(()=>this.activeWorkflow,e=>this._defaultSelectionManager.highlightEnabled=!e),v(()=>this.view?.map,e=>e.add(this._sketchGraphicsLayer),g),k(()=>this.editorItems,"change",()=>this._afterEditorItemsChange()),m(()=>[this.canCreate,this.canUpdateVisible],()=>this._afterEditorItemsChange()),m(()=>this.page,(e,t)=>{const i=[...this.pageStack];if(-1===i.indexOf(e))i.push(e);else for(;i.length&&i.at(-1)!==e;)i.pop();this.pageStack=i},y),v(()=>"awaiting-update-feature-candidate"===this.state,()=>this._candidateCommitted=!1),k(()=>this.featureTemplatesViewModel,"select",async({item:e,oldItem:t})=>{const{activeWorkflow:i}=this;if(i){if("update"===i.type&&"awaiting-feature-creation-info"===i.activeWorkflow?.stepId)return;try{await this.cancelWorkflow({force:!this.hasPendingEdits})}catch{return void this.featureTemplatesViewModel.select(t,{emit:!1})}}if(!e)return;const o={layer:e.layer,template:e.template};if(e.supportsUpload)return this.featureTemplatesViewModel.select(t,{emit:!1}),this.startCreateFeaturesWorkflow(o);await this.startCreateFeaturesWorkflowAtFeatureCreation(o)}),m(()=>[this.view,this.featureTemplatesViewModel],([e,t])=>{t.view=e},y),k(()=>this.view,"key-down",e=>{"Escape"===e.key&&this.activeWorkflow?.keyboardCancellationEnabled&&(e.stopPropagation(),this.back())}),k(()=>this.sketchViewModel,["create","delete","update"],e=>{const{activeWorkflow:t}=this,i=N(t),o=`sketch-${e.type}`;this.emit(o,{type:o,detail:e,layer:i[0],layers:i})},_),m(()=>this.view,e=>{if(this._snappingManager=d(this._snappingManager),!e)return;const t=this.snappingOptions;this._snappingManager=new H({view:e,options:t}),this.ownSketchViewModel.snappingManager=this._snappingManager},y),m(()=>this.snappingOptions,e=>{this._snappingManager&&(this._snappingManager.options=e)},y),k(()=>this.selectionToolbarViewModel,"complete",e=>this._onSelectionComplete(e)),m(()=>({view:this.view,selectionManager:this.effectiveSelectionManager,selectionListViewModel:this.selectionListViewModel,selectionToolbarViewModel:this.selectionToolbarViewModel}),({view:e,selectionManager:t,selectionListViewModel:i,selectionToolbarViewModel:o})=>{t.view=e,i.view=e,o.view=e},y),m(()=>this.effectiveSelectionManager,e=>{this.selectionListViewModel.selectionManager=e,this.selectionToolbarViewModel.selectionManager=e},y)])}destroy(){this._cancelWorkflow({warnIfNoWorkflow:!1}).then(()=>{this.view?.map?.remove(this._sketchGraphicsLayer),this.view=null}),this._updateItemsTask=p(this._updateItemsTask),this._updatingHandles.destroy(),this._sketchEventListenerHandle=h(this._sketchEventListenerHandle),this.selectionListViewModel?.destroy(),this.selectionToolbarViewModel?.destroy(),this._defaultSelectionManager.destroy()}get _featureTemplatesLayersAndTables(){const e=new o;for(const t of this.editorItems){const i=this.hideTemplatesForInactiveLayers&&!t.visible;t.supportsCreateFeaturesWorkflow&&!i&&e.push(t.layer)}return e}get _selectionSources(){const e=new o;if(this.syncViewSelection||this.selectionManager)return e;for(const t of this.editorItems)x(t.layer)&&t.supportsUpdateWorkflow&&e.push(t.layer);return e}get activeFeatureCount(){const e=this.activeLeafWorkflow;return Q(e)?e.pendingFeatures.length:z(e)&&e.data.edits.feature?1:Z(e)?e.data.fullFeatures.length:$(e)?e.data.features.length:J(e)?2:0}get activeLeafWorkflow(){const e=this.activeWorkflow;return e&&K(e)?e.activeWorkflow??e:e}get canCreate(){return this.editorItems.some(e=>e.supportsCreateFeaturesWorkflow)}get canCreateVisible(){return!!this.featureTemplatesLayers.length}get canUpdate(){return this.editorItems.some(e=>e.supportsUpdateWorkflow)}get canUpdateVisible(){return this.editorItems.some(e=>e.supportsUpdateWorkflow&&e.visible)}get featureTemplatesLayers(){return this._featureTemplatesLayersAndTables.filter(e=>"scene"===e.type||!e.isTable)}get effectiveSelectionManager(){const e=this.view;return e&&this.syncViewSelection?e.selectionManager:this.selectionManager??this._defaultSelectionManager}get featureFormViewModel(){const e=this.activeWorkflow?.formViewModel;return X(e)?e:null}get formViewModel(){return this.activeWorkflow?.formViewModel}get utilityNetworkAssociationAddAssociationViewModel(){const{activeWorkflow:e}=this;return"update"===e?.type?e.activeUtilityNetworkAssociationAddAssociationViewModel:null}get labelOptions(){return this.sketchOptions.labels}set labelOptions(e){this.sketchOptions.labels=e}get useLegacyCreateTools(){return this.ownSketchViewModel.useLegacyCreateTools}set useLegacyCreateTools(e){this.ownSketchViewModel.useLegacyCreateTools=e}get isUsingLegacyCreateTools(){return this.useLegacyCreateTools||"2d"!==this.view?.type}get sketchViewModel(){const{activeWorkflow:e}=this;return"update"===e?.type?e.activeSketchViewModel:"create-features"===e?.type?e.sketchViewModel:this.ownSketchViewModel}get state(){if(!this.view?.ready)return"disabled";const e=this.attachmentsViewModel.mode;if("add"===e)return"adding-attachment";if("edit"===e)return"editing-attachment";const{activeWorkflow:t}=this,i=!t?.stepId;return this.effectiveSelectionManager.count&&i?"viewing-selection-list":i?"ready":"update"===t.type&&t.activeWorkflow?.stepId?t.activeWorkflow.stepId:t.stepId}get syncing(){return this._activityQueue.length>0}get updating(){return this._updatingHandles.updating||!0===this.activeWorkflow?.updating}get tooltipOptions(){return this.sketchOptions.tooltips}set tooltipOptions(e){this.sketchOptions.tooltips=e}get valueOptions(){return this.sketchOptions.values}set valueOptions(e){this.sketchOptions.values=e}set view(e){this.ownSketchViewModel.view=e,this.spinnerViewModel.view=e,this._set("view",e)}get canZoomTo(){return this._getWorkingFeatures().some(e=>e.geometry)}get page(){const{activeWorkflow:e,state:t}=this;if("update"===e?.type&&X(e.formViewModel)){const{associatedLayer:t,associationId:i}=e.formViewModel;if(t||null!=i)return"viewing-associated-features"}if("update"===e?.type&&"awaiting-feature-to-update"===e.stepId)return"ready";if("create-features"===e?.type&&0===e.numPendingFeatures){const t=e.data.upload;if(t)return"default"===t.state?"ready":"creating-features-upload-details"}return t??"disabled"}get featureFormDisabled(){const{activeLeafWorkflow:e}=this;if(z(e))return!1===e.data.editorItem?.capabilities.update.attributes||!0===e.formViewModel.disabled;if(Z(e)){const{formViewModel:t}=e;return t.disabled||t.readOnly}return!1}get featureFormHasAssociation(){return!!this.featureFormViewModel?.activeAssociation}get canGoBack(){return null!=this.activeWorkflow&&!this.syncing}get shouldShowDeleteButton(){const{activeLeafWorkflow:e}=this;if(z(e)){const{data:t}=e;return t.editorItem?.capabilities.delete.enabled&&!t.readOnly}return!!Z(e)&&e.data.editorItems.every(e=>e.capabilities.delete.enabled)}get hasPendingEdits(){return this.activeWorkflow?.hasPendingEdits??!1}get snappingManager(){return this._snappingManager}activateSelectionTool(e){return this.selectionToolbarViewModel.activateTool(e)}cancelSelectionTool(){this.selectionToolbarViewModel.cancel()}getTemplatesForLayer(e){return this._templatesByLayer.get(e)??[]}async startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.startCreateFeaturesWorkflow()}async startCreateFeaturesWorkflowAtFeatureCreation(e){return this.startCreateFeaturesWorkflow(e,"creating-features")}async startCreateFeaturesWorkflow(e,t="awaiting-feature-creation-info"){if(await W(()=>!this.updating),!this.canCreate)throw new a("editing:unsupported-workflow","Creating features is unsupported or disabled.");const i=this._createUpdatingResolver();try{await this._cancelWorkflow();const i=this._createCreateFeaturesWorkflow(e,t);this._set("activeWorkflow",i),await i.start()}catch(o){this._logErrorAndCancelWorkflow(o)}finally{i.resolve()}}async startCreateFeaturesWorkflowAtFeatureEdit(e){await W(()=>!this.updating);const t=this._createUpdatingResolver();try{const{initialFeature:t}=e,i=t.sourceLayer=t.layer,o=i?Y(this.editorItems,i):void 0;if(!o?.supportsCreateFeaturesWorkflow)throw new a("editing:unsupported-workflow","Creating features is unsupported or disabled for this layer.");await this._cancelWorkflow();const r=this._createCreateFeaturesWorkflow({initialFeature:t,layer:o.layer,maxFeatures:1},"creating-features");this._set("activeWorkflow",r),await r.start()}catch(i){this._logErrorAndCancelWorkflow(i)}finally{t.resolve()}}async startMergeFeaturesWorkflow(e,t={}){await W(()=>!this.updating),ne(this,"merge-features");const i=Array.isArray(e)?ee(e):[e];if(i.length>1)throw new le;if(0===i.length||i[0].objectIds.length<2)throw new ce(2);const r=i[0],a=r.layer;if(!a)throw new de;const s=Y(this.editorItems,a);pe(s);const l=this._createUpdatingResolver(),c=new AbortController;this.addHandles(n(c));try{await this._cancelWorkflow(),this.cancelSelectionTool();const e=await te(r.objectIds,a,this.view?.spatialReference,c.signal);if(e.length!==r.objectIds.length)throw new he;let i;if(t.keyFeature){const o=t.keyFeature.getObjectId();i=e.find(e=>e.getObjectId()===o)??t.keyFeature}const s=this._createUpdateWorkflow("editing-existing-feature",{rootFeatures:new o(e),rootWorkflowOptions:{type:"merge",props:{...t,keyFeature:i}}});this._set("activeWorkflow",s),this.addHandles(this._destroyWorkflowOnCommit(s)),await s.start()}catch(d){this._logErrorAndCancelWorkflow(d)}finally{l.resolve()}}async startSplitFeatureWorkflow(e,t={}){await W(()=>!this.updating),ne(this,"split-feature");const i=V(e);if(!i)throw new de;const r=Y(this.editorItems,i);ue(r);const a=this._createUpdatingResolver(),s=new AbortController;this.addHandles(n(s));try{await this._cancelWorkflow(),this.cancelSelectionTool();const r=await ie([e],i,this.view?.spatialReference,s.signal);if(1!==r.length)throw new he;const a=this._createUpdateWorkflow("editing-existing-feature",{rootFeatures:new o(r),rootWorkflowOptions:{type:"split",props:t}});this._set("activeWorkflow",a),this.addHandles(this._destroyWorkflowOnCommit(a)),await a.start()}catch(l){this._logErrorAndCancelWorkflow(l)}finally{a.resolve()}}async startUpdateFeaturesWorkflow(e){if(await W(()=>!this.updating),!this.canUpdate)return void this._logError("editing:unsupported-workflow","Update features workflow is unsupported or disabled.");const t=Array.isArray(e)?ee(e):[e];if(t.length>1)throw new le;const i=this._createUpdatingResolver();try{await this._cancelWorkflow(),this.cancelSelectionTool();const e=this._createUpdateWorkflow("editing-existing-feature",{rootFeatureInfos:t,rootWorkflowOptions:{type:"update-multiple"}});e.addHandles(this._destroyWorkflowOnCommit(e)),this._set("activeWorkflow",e),await e.start()}catch(o){this._logErrorAndCancelWorkflow(o)}finally{i.resolve()}}async startUpdateWorkflowAtFeatureSelection(){if(await W(()=>!this.updating),!this.canUpdate)return void this._logError("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const e=this._createUpdatingResolver();try{await this._cancelWorkflow();const e=this._createUpdateWorkflow();this._set("activeWorkflow",e),await e.start()}catch(t){this._logErrorAndCancelWorkflow(t)}finally{e.resolve()}}async startUpdateWorkflowAtMultipleFeatureSelection(e){if(await W(()=>!this.updating),!this.canUpdate)return void this._logError("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const t=this._createUpdatingResolver();try{await this._cancelWorkflow();const t=this._createUpdateWorkflow("awaiting-update-feature-candidate");t.data.candidates=e,this._set("activeWorkflow",t),await t.start()}catch(i){this._logErrorAndCancelWorkflow(i)}finally{t.resolve()}}async startUpdateWorkflowAtFeatureEdit(e){if(await W(()=>!this.updating),!this.canUpdate)return void this._logError("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const t=this._createUpdatingResolver();try{await this._cancelWorkflow(),this.cancelSelectionTool();const t=this._createUpdateWorkflow("editing-existing-feature",{rootFeatures:new o([e])});t.addHandles(this._destroyWorkflowOnCommit(t)),this._set("activeWorkflow",t),await t.start()}catch(i){this._logErrorAndCancelWorkflow(i)}finally{t.resolve()}}async startUpdateWorkflowWithActiveSelection(){const{selectionListViewModel:e}=this;if(!e.visibleFeatureCount||!e.visibleLayerCount)throw new a("editing:missing-selection","Unable to determine visible selection.");if(e.visibleLayerCount>1)throw new a("editing:features-different-layers","Cannot start workflow with features from different layers.");const t=e.layerItems.find(e=>e.visible);t&&await this._startUpdateWorkflowWithLayerItem(t,"update")}async deleteFeatureFromWorkflow(){r(c.getLogger(this),"EditorViewModel.deleteFeatureFromWorkflow is deprecated. Use EditorViewModel.deleteFeatures instead.",{version:"4.33",replacement:"EditorViewModel.deleteFeatures",warnOnce:!0}),await this.deleteFeatures()}async deleteFeatures(){const e=this.activeWorkflow;if(K(e))return e.deleteActiveFeatures();this._logError("editing:unsupported-workflow","Deleting features requires an active update workflow.")}async deleteAssociationFromWorkflow(){const{activeWorkflow:e}=this;e&&"update"===e.type?await e.deleteActiveAssociation():this._logError("editing:unsupported-workflow","Deleting an association requires an active update workflow.")}async cancelWorkflow(e){return this._cancelWorkflow({warnIfNoWorkflow:!0,...e})}itemHasInvalidFormTemplate(e){return null!=e&&!0===oe(this.editorItems,e.layer)?.hasInvalidFormTemplate}syncFeatureTemplates(){this._featureTemplatesViewModelIsRestricted||this._updateTemplates()}zoomTo(e){const{view:i,sketchViewModel:o}=this;if(!i)return;const r=void 0,a=e??o?.createGraphic;if(a)"mesh"===a.geometry?.type?ge(i,a.geometry,r):ge(i,a,r);else{const e=this._getWorkingFeatures();"3d"===i.type&&e?.some(e=>"mesh"===e.geometry?.type)?ge(i,e.map(e=>e.geometry).filter(t),r):e&&ge(i,e,r)}}async toggleUpdateWorkflow(){this.canUpdate&&(this.hasPendingEdits&&!await this.showDiscardEditsPrompt()||(this.activeWorkflow&&"awaiting-feature-to-update"===this.state?await this.cancelWorkflow({force:!0}):await this.startUpdateWorkflowAtFeatureSelection()))}async onSelectionListItemSelect(e){ke(e)&&await this.startUpdateWorkflowAtFeatureEdit(e.graphic)}async onSelectionListMenuItemSelect(e,t){ke(e)?await this.startUpdateWorkflowAtFeatureEdit(e.graphic):ve(e)&&await this._startUpdateWorkflowWithLayerItem(e,t)}restrictFeatureTemplatesViewModelToLayer(e){return this._featureTemplatesViewModelIsRestricted=!0,this._setFeatureTemplatesViewModelLayers([e]),l(()=>{this._featureTemplatesViewModelIsRestricted=!1,this._setFeatureTemplatesViewModelLayers(this.featureTemplatesLayers)})}async _getEditorItemCandidates(e){const{view:t}=this;if(!t?.map)return[];const{map:i}=t,o=i.editableLayers.toArray(),r=i.allTables.toArray().filter(e=>L(e)||E(e));return await Promise.allSettled([...o.flatMap(e=>this._getLayerLoadPromise(e)),...r.flatMap(e=>this._getLayerLoadPromise(e))]),u(e),[...o.reverse(),...r.reverse()].filter(e=>I(e)&&("mesh"!==e.geometryType||"3d"===t.type)).flatMap(e=>"subtype-group"===e.type?e.sublayers.toArray():e)}_getLayerLoadPromise(e){return E(e)?e.loadAll():e.load()}_drainEditorItems(){this.editorItems.drain(e=>e.destroy())}_updateEditorItems(){p(this._updateItemsTask);const{view:e}=this,t=i(async t=>{if(!e?.map||!e?.allLayerViews)return;const i=await this._getEditorItemCandidates(t);if(!i.length)return this._drainEditorItems(),void this.editorItemsLayerMap.clear();const o=[],r=[],a=[],{editorItemsLayerMap:s,layerInfos:n}=this;for(const c of i){const t=Me(n,c),i=await re(e,c).catch(()=>null),l=t?o:i?r:a,d=new se({layer:c,layerInfo:t,layerView:i});l.push(d),s.set(c,d)}n?.length&&o.sort((e,t)=>n.findIndex(({layer:t})=>t===e.layer)-n.findIndex(({layer:e})=>e===t.layer));const l=[...o,...r,...a];t.aborted||(this._drainEditorItems(),this.editorItems.addMany(l))});this._updatingHandles.addPromise(t.promise),this._updateItemsTask=t}_updateTemplates(){p(this._updateTemplatesTask);const e=i(async e=>{const t=this._templatesByLayer,i=this._featureTemplatesLayersAndTables.filter(e=>!t.has(e));if(i.length>0){const o=await b({layers:i.toArray(),view:this.view,signal:e,queryOptions:{returnVisibleTemplatesOnly:!0}});for(const{layer:e,templates:i}of o)t.set(e,i)}this._setFeatureTemplatesViewModelLayers(this.featureTemplatesLayers)});this._updatingHandles.addPromise(e.promise),this._updateTemplatesTask=e}_setFeatureTemplatesViewModelLayers(e){const t=this._templatesByLayer,i=[];for(const o of e){const e=t.get(o);e&&e.length>0&&i.push(we(o,e))}this.featureTemplatesViewModel.templateInfos=i}_afterEditorItemsChange(){const{activeWorkflow:e}=this;if(this.syncFeatureTemplates(),!e)return;const{stepId:t}=e;"create-features"!==e.type?"update"===e.type&&("awaiting-feature-to-update"===t&&!this.canUpdateVisible||"awaiting-update-feature-candidate"===t&&!e.hasUpdatableCandidates)&&this._cancelWorkflow():"awaiting-feature-creation-info"!==t||this.canCreate||this._cancelWorkflow()}async _cancelWorkflow(e){const t=this.activeWorkflow;if(!t)return void(e?.warnIfNoWorkflow&&this._logError("editing:no-active-workflow","There is no active workflow to cancel."));if(!e||!1!==e.force){this.emit("workflow-cancel"),this._set("activeWorkflow",null);try{await t.cancel(e)}finally{t.destroy()}}else try{await t.cancel(e),this._set("activeWorkflow",null),t.destroy()}catch(i){}}_createCreateFeaturesWorkflow(e,t){return D.create({viewModel:this,creationInfo:e,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:t,applyEdits:(e,t,i)=>this._applyEdits(e,t,i),applyEditsFeatureService:(e,t,i)=>this._applyEditsFeatureService(e,t,i),addAttachmentsCallback:(e,t)=>this._addAttachments(e,t)})}_createUpdateWorkflow(e,t){const i=B.create({viewModel:this,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:e,...t,applyEdits:(e,t,i)=>this._applyEdits(e,t,i),applyEditsFeatureService:(e,t,i)=>this._applyEditsFeatureService(e,t,i),addAttachmentsCallback:(e,t)=>this._addAttachments(e,t)});return i}_addAttachments(e,t){const i=t.map(t=>this._addAttachment(e,t.feature,t.attachment))??[];return Promise.all(i)}async _addAttachment(e,t,i){let o=null;if(!("addAttachment"in e)||null==e.capabilities?.attachment)throw new a("editor:attachments-not-supported","Adding attachments is not supported for this layer type");return await this._queueOperation(async()=>(o=await(e.addAttachment?.(t,i).catch(e=>{throw e?.error||e}))??null,o)),o}async _applyEdits(e,t,i){let o=null;const r=e.url?await C(e.url):null,a={returnServiceEditsOption:(!r||!A(r))&&!/\/hosted\//i.test(e.url)?"original-and-current-features":void 0,editsRespectTrueCurves:!0,...i};return await this._queueOperation(async()=>{const{view:i}=this;if(!i)return null;const r=await re(i,e).catch(()=>null);return o=await e.applyEdits(t,a),r&&await W(()=>!r.updating),o}),o}async _applyEditsFeatureService(e,t,i){let o=null;return await this._queueOperation(async()=>o=await e.applyEdits(t,i)),o}_destroyWorkflowOnCommit(e){return k(()=>e,"commit",()=>{e.destroy(),this.activeWorkflow===e&&this._set("activeWorkflow",null)})}_queueOperation(e){this._activityQueue.push(e);const t=(e,t)=>{const i=t.indexOf(e);i>-1&&t.splice(i,1)};return e().then(e=>(Array.isArray(e)?e.forEach(e=>this._handleEditsResultError(e)):this._handleEditsResultError(e),e)).catch(i=>{this._logError("editing:operation-error","An error occurred.",{error:i});const o={error:i,retry:()=>(t(o,this.failures),this._queueOperation(e)),cancel:()=>{t(o,this.failures)}};this._set("failures",[...this.failures,o])}).then(()=>{t(e,this._activityQueue)})}_handleEditsResultError(e){if(null!=e&&"error"in e&&null!=e.error)throw e.error;if(null!=e&&"addFeatureResults"in e){const{addFeatureResults:t,deleteFeatureResults:i,updateFeatureResults:o}=e,r=t.find(e=>!!e.error)||o.find(e=>!!e.error)||i.find(e=>!!e.error);if(r)throw r.error}}_createUpdatingResolver(){const e=w();return this._updatingHandles.addPromise(e.promise),e}_logErrorAndCancelWorkflow(e){const{name:t,message:i,details:o}=e;this._logError(t??"editing:workflow-start-failed",i??void 0,o??e),this._cancelWorkflow({force:!0})}_itemIsSuspended(e){const t=Y(this.editorItems,e);return null!=t&&(!t.visible||t.disabled)}_logError(e,t,i){c.getLogger(this).error(new a(e,t,i))}_syncSelectionSources(){this._defaultSelectionManager.sources.items=this._selectionSources.toArray()}async _onSelectionComplete(e){if(e.aborted)return;const{operationType:t,selection:i}=e,{effectiveSelectionManager:o}=this;this._queuedSelectionTool=void 0;const r=[],a=[];i.forEach(e=>{const t=V(e),i=this.editorItemsLayerMap.get(t);i?.editable&&a.push(e),!1!==i?.visible&&r.push(e)});const s=1===a.length;if("ready"===this.state&&s&&"replace"===t)return this._queuedSelectionTool=e.toolName,this.startUpdateWorkflowAtFeatureEdit(a[0]);switch(t){case"remove":o.updateSelection({current:[],added:[],removed:r});break;case"replace":o.clear(),o.updateSelection({current:r,added:[],removed:[]});break;case"add":o.updateSelection({current:r,added:[],removed:[]})}}async _startUpdateWorkflowWithLayerItem(e,t){if(!e.objectIds?.length)return;const i=e.featureItems.filter(e=>e.visible).map(e=>e.graphic),o=this.selectionListViewModel.filterText;if(1===i.length)return await this.startUpdateWorkflowAtFeatureEdit(i[0]);let r;if(null!=o&&""!==o){const e=ee(i);if(e.length>1)throw new le;if(r=e[0],!r)throw new ce("merge"===t?2:1)}else r={layer:e.layer,objectIds:e.objectIds};"update"===t?await this.startUpdateFeaturesWorkflow(r):"merge"===t&&await this.startMergeFeaturesWorkflow(r)}_getWorkingFeatures(){const{sketchViewModel:e}=this;if(e?.createGraphic)return[e.createGraphic];if(e?.updateGraphics?.length)return e.updateGraphics.toArray();const{formViewModel:t}=this;if(X(t)&&t.feature)return[t.feature];if(ae(t)){if(t.activeFeature)return[t.activeFeature];if(t.features.length)return t.features.toArray()}return[]}};e([M()],Te.prototype,"_defaultSelectionManager",void 0),e([M()],Te.prototype,"_featureTemplatesLayersAndTables",null),e([M()],Te.prototype,"_queuedSelectionTool",void 0),e([M()],Te.prototype,"_snappingManager",void 0),e([M()],Te.prototype,"_selectionSources",null),e([M()],Te.prototype,"activeFeatureCount",null),e([M({readOnly:!0})],Te.prototype,"activeWorkflow",void 0),e([M()],Te.prototype,"activeLeafWorkflow",null),e([M({readOnly:!0})],Te.prototype,"_activityQueue",void 0),e([M({readOnly:!0})],Te.prototype,"canCreate",null),e([M()],Te.prototype,"canCreateVisible",null),e([M({readOnly:!0})],Te.prototype,"canUpdate",null),e([M()],Te.prototype,"canUpdateVisible",null),e([M()],Te.prototype,"featureTemplatesLayers",null),e([M()],Te.prototype,"editorItems",void 0),e([M()],Te.prototype,"editorItemsLayerMap",void 0),e([M()],Te.prototype,"effectiveSelectionManager",null),e([M({readOnly:!0})],Te.prototype,"failures",void 0),e([M()],Te.prototype,"hideTemplatesForInactiveLayers",void 0),e([M({type:G})],Te.prototype,"attachmentsViewModel",void 0),e([M()],Te.prototype,"featureFormViewModel",null),e([M()],Te.prototype,"formViewModel",null),e([M()],Te.prototype,"utilityNetworkAssociationAddAssociationViewModel",null),e([M({type:fe})],Te.prototype,"featureTemplatesViewModel",void 0),e([M({type:O})],Te.prototype,"labelOptions",null),e([M()],Te.prototype,"layerInfos",void 0),e([M()],Te.prototype,"useLegacyCreateTools",null),e([M()],Te.prototype,"isUsingLegacyCreateTools",null),e([M()],Te.prototype,"ownSketchViewModel",void 0),e([M()],Te.prototype,"selectionListViewModel",void 0),e([M()],Te.prototype,"selectionManager",void 0),e([M()],Te.prototype,"selectionToolbarViewModel",void 0),e([M()],Te.prototype,"sketchOptions",void 0),e([M()],Te.prototype,"sketchViewModel",null),e([M({type:q,nonNullable:!0})],Te.prototype,"snappingOptions",void 0),e([M()],Te.prototype,"spinnerViewModel",void 0),e([M()],Te.prototype,"state",null),e([M({readOnly:!0})],Te.prototype,"syncing",null),e([M()],Te.prototype,"syncViewSelection",void 0),e([M()],Te.prototype,"updating",null),e([M({type:P})],Te.prototype,"tooltipOptions",null),e([M({type:R})],Te.prototype,"valueOptions",null),e([M()],Te.prototype,"view",null),e([M()],Te.prototype,"canZoomTo",null),e([M()],Te.prototype,"pageStack",void 0),e([M()],Te.prototype,"showDiscardEditsPrompt",void 0),e([M()],Te.prototype,"showConfirmationPrompt",void 0),e([M()],Te.prototype,"_candidateCommitted",void 0),e([M()],Te.prototype,"page",null),e([M()],Te.prototype,"featureFormDisabled",null),e([M()],Te.prototype,"featureFormHasAssociation",null),e([M()],Te.prototype,"canGoBack",null),e([M()],Te.prototype,"shouldShowDeleteButton",null),e([M()],Te.prototype,"hasPendingEdits",null),e([M()],Te.prototype,"snappingManager",null),Te=e([T("esri.widgets.Editor.EditorViewModel")],Te);const Fe=Te;export{Fe as default};