@arcgis/core 4.34.0-next.29 → 4.34.0-next.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/Map.js +1 -1
  2. package/assets/esri/core/workers/RemoteClient.js +1 -1
  3. package/assets/esri/core/workers/chunks/0260b33daf48fc207880.js +1 -0
  4. package/assets/esri/core/workers/chunks/{f469224c6e4804fd835a.js → 140efe4735605258ecc9.js} +1 -1
  5. package/assets/esri/core/workers/chunks/173c5b8fa1ac7aa6e072.js +1 -0
  6. package/assets/esri/core/workers/chunks/1aa6719be3afbdc7c880.js +1 -0
  7. package/assets/esri/core/workers/chunks/{8552fdb3230f4dd082c6.js → 20a96c17d1a117dfdf77.js} +1 -1
  8. package/assets/esri/core/workers/chunks/28e04ef3575f164f611a.js +1 -0
  9. package/assets/esri/core/workers/chunks/{2173012af606ac4cdf87.js → 2a695b50a384c45ace9a.js} +1 -1
  10. package/assets/esri/core/workers/chunks/{cf635f7ca998dd33d947.js → 439ce953a25b2776cb7f.js} +1 -1
  11. package/assets/esri/core/workers/chunks/{ecdbbfebca1fcef567bb.js → 4e267a813e8b10d10b3b.js} +9 -9
  12. package/assets/esri/core/workers/chunks/7099ff8dc699fedea931.js +1 -0
  13. package/assets/esri/core/workers/chunks/{e89698fc404379627349.js → 949dc266ac6f3505d357.js} +1 -1
  14. package/assets/esri/core/workers/chunks/{0aba41e0ee0a591b254b.js → 971b16677b66c16fb6b9.js} +1 -1
  15. package/assets/esri/core/workers/chunks/a809042fdce7ced2a415.js +1 -0
  16. package/assets/esri/core/workers/chunks/{16d82cbec34bc434efcd.js → a82d7e2eecfe654a65de.js} +1 -1
  17. package/assets/esri/core/workers/chunks/{27e089acb1cc76758b0a.js → ac30cf2f9a94597f7665.js} +8 -8
  18. package/assets/esri/core/workers/chunks/{ec4428250dbd807df0bd.js → c50c2f014e8567870686.js} +1 -1
  19. package/assets/esri/core/workers/chunks/{ce3a1ac43e8579db65cd.js → c854c3bb4440fd942c12.js} +1 -1
  20. package/assets/esri/core/workers/chunks/{9cbed3b43d7aadc7e627.js → ca88859fc69fcb4568c0.js} +1 -1
  21. package/assets/esri/core/workers/chunks/e7209654ecdfde926272.js +1 -0
  22. package/assets/esri/core/workers/chunks/e82b1f91465d569012c4.js +1 -0
  23. package/assets/esri/core/workers/chunks/e9311386f58f3cb95c22.js +1 -0
  24. package/assets/esri/core/workers/chunks/{45485d8f0b0e0e0a6365.js → efec0f496491a0647051.js} +1 -1
  25. package/chunks/RealisticTree.glsl.js +6 -6
  26. package/colorUtils.js +1 -1
  27. package/config.js +1 -1
  28. package/core/Evented.js +1 -1
  29. package/interfaces.d.ts +2 -2
  30. package/kernel.js +1 -1
  31. package/layers/CatalogLayer.js +1 -1
  32. package/layers/FeatureLayer.js +1 -1
  33. package/layers/GeoJSONLayer.js +1 -1
  34. package/layers/GraphicsLayer.js +1 -1
  35. package/layers/OGCFeatureLayer.js +1 -1
  36. package/layers/SceneLayer.js +1 -1
  37. package/layers/SubtypeGroupLayer.js +1 -1
  38. package/layers/graphics/data/FeatureStore.js +1 -1
  39. package/layers/graphics/dehydratedPoint.js +1 -1
  40. package/layers/knowledgeGraph/KnowledgeGraphSublayer.js +1 -1
  41. package/layers/mixins/SublayersOwner.js +1 -1
  42. package/layers/support/LayerContingentValuesCache.js +1 -1
  43. package/networks/UtilityNetwork.js +1 -1
  44. package/package.json +1 -1
  45. package/portal/support/layersLoader.js +1 -1
  46. package/rest/networks/support/CircuitTraceResult.js +1 -1
  47. package/support/revision.js +1 -1
  48. package/views/2d/engine/ManagedCanvas.js +1 -1
  49. package/views/2d/engine/imagery/RasterTileContainer.js +1 -1
  50. package/views/2d/engine/webgl/Profiler.js +1 -1
  51. package/views/2d/engine/webgl/shaderGraph/techniques/raster/RasterColorizerTechnique.js +1 -1
  52. package/views/2d/engine/webgl/shaderGraph/techniques/raster/processor/ReprojectTechnique.js +1 -1
  53. package/views/2d/engine/webgl/shaderGraph/techniques/shaders/raster/BaseRasterColorizerShader.js +1 -1
  54. package/views/2d/engine/webgl/shaderGraph/techniques/shaders/raster/processor/math.js +1 -1
  55. package/views/2d/layers/ImageryTileLayerView2D.js +1 -1
  56. package/views/2d/layers/features/FeatureSourceEventLog.js +1 -1
  57. package/views/2d/layers/features/processor/AAggregateStrategy.js +1 -1
  58. package/views/2d/layers/features/sources/strategies/StreamLoadStrategy.js +1 -1
  59. package/views/2d/layers/features/sources/strategies/chunks/SourceChunkStore.js +1 -1
  60. package/views/2d/layers/imagery/ImageryTileView2D.js +1 -1
  61. package/views/2d/support/hitTestUtils.js +1 -1
  62. package/views/3d/analysis/LineOfSight/LineOfSightController.js +1 -1
  63. package/views/3d/analysis/VolumeMeasurement/CutFillVolumeMeasurementController.js +1 -1
  64. package/views/3d/analysis/VolumeMeasurement/CutFillVolumeMeasurementVisualization.js +5 -0
  65. package/views/3d/analysis/VolumeMeasurement/VolumeMeasurementConfiguration.js +5 -0
  66. package/views/3d/analysis/VolumeMeasurementAnalysisView3D.js +1 -1
  67. package/views/3d/interactive/editingTools/manipulations/MoveXYAxisManipulation.js +1 -1
  68. package/views/3d/interactive/editingTools/manipulations/MoveZManipulation.js +1 -1
  69. package/views/3d/interactive/editingTools/move/MoveTool3D.js +1 -1
  70. package/views/3d/interactive/editingTools/reshape/ReshapeOperation.js +1 -1
  71. package/views/3d/interactive/editingTools/reshape/ReshapeTool3D.js +1 -1
  72. package/views/3d/interactive/editingTools/transform/ExtentTransformTool.js +1 -1
  73. package/views/3d/interactive/editingTools/transform/ScaleRotateTransform.js +1 -1
  74. package/views/3d/interactive/editingTools/transform/TransformTool3D.js +1 -1
  75. package/views/3d/interactive/visualElements/OutlineVisualElement.js +1 -1
  76. package/views/3d/layers/SceneLayerGraphicsView3D.js +1 -1
  77. package/views/3d/layers/graphics/Graphics3DCore.js +1 -1
  78. package/views/3d/layers/graphics/Graphics3DElevationAlignment.js +1 -1
  79. package/views/3d/layers/graphics/Graphics3DFeatureStore.js +1 -1
  80. package/views/3d/layers/graphics/Graphics3DSymbol.js +1 -1
  81. package/views/3d/layers/graphics/Graphics3DSymbolLayer.js +1 -1
  82. package/views/3d/layers/graphics/pipeline/featureSet/TiledFeatureStore.js +1 -1
  83. package/views/3d/layers/i3s/I3SIndex.js +1 -1
  84. package/views/3d/layers/i3s/I3SQueryFeatureStore.js +1 -1
  85. package/views/3d/layers/i3s/LayerElevationProvider.js +1 -1
  86. package/views/3d/layers/support/HeatmapFeatureProcessor.js +1 -1
  87. package/views/3d/layers/support/StageLayerElevationProvider.js +1 -1
  88. package/views/3d/state/ViewState.js +1 -1
  89. package/views/3d/support/CombinedElevationProvider.js +1 -1
  90. package/views/3d/support/pointsOfInterest/ContentGeometryUpdates.js +1 -1
  91. package/views/3d/support/pointsOfInterest/SurfaceGeometryUpdates.js +1 -1
  92. package/views/3d/terrain/OverlayRenderer.js +1 -1
  93. package/views/3d/terrain/TerrainSurface.js +1 -1
  94. package/views/3d/webgl-engine/lib/BoundingInfo.js +1 -1
  95. package/views/3d/webgl-engine/lib/ChangeSet.js +1 -1
  96. package/views/3d/webgl-engine/lib/Geometry.js +1 -1
  97. package/views/3d/webgl-engine/lib/RenderGeometry.js +1 -1
  98. package/views/3d/webgl-engine/lib/SortedRenderGeometryRenderer.js +1 -1
  99. package/views/3d/webgl-engine/lib/TextTextureAtlas.js +1 -1
  100. package/views/3d/webgl-engine/lib/Texture.js +1 -1
  101. package/views/3d/webgl-engine/lib/TextureRepository.js +1 -1
  102. package/views/3d/webgl-engine/lib/WebGLLayer.js +1 -1
  103. package/views/3d/webgl-engine/lib/lodRendering/InstanceData.js +1 -1
  104. package/views/3d/webgl-engine/lib/rendererUtils.js +1 -1
  105. package/views/3d/webgl-engine/materials/renderers/MergedRenderer.js +1 -1
  106. package/views/DOMContainer.js +1 -1
  107. package/views/Viewport2DMixin.js +1 -1
  108. package/views/draw/DrawManipulator.js +1 -1
  109. package/views/draw/DrawOperation.js +1 -1
  110. package/views/interactive/snapping/SnappingManager.js +1 -1
  111. package/views/interactive/snapping/featureSources/FeatureCollectionSnappingSource.js +1 -1
  112. package/views/layers/FeatureLayerView.js +1 -1
  113. package/views/layers/support/editableLayerViews.js +1 -1
  114. package/views/support/Scheduler.js +1 -1
  115. package/widgets/Editor/EditorViewModel.js +1 -1
  116. package/widgets/Editor/workflowUtils.js +1 -1
  117. package/widgets/Feature/support/arcadeFeatureUtils.js +1 -1
  118. package/widgets/FeatureForm/FeatureFormViewModel.js +1 -1
  119. package/widgets/Search/SearchViewModel.js +1 -1
  120. package/widgets/support/GeolocationPositioning.js +1 -1
  121. package/widgets/support/UtilityNetworkAssociations/FeatureUtilityNetworkAssociationsViewModel.js +1 -1
  122. package/assets/esri/core/workers/chunks/230e7b817ae16505ccf0.js +0 -1
  123. package/assets/esri/core/workers/chunks/450a7ebe2535a55c5193.js +0 -1
  124. package/assets/esri/core/workers/chunks/4599f5cebbafddb6720e.js +0 -1
  125. package/assets/esri/core/workers/chunks/676fec273f2f660a614d.js +0 -1
  126. package/assets/esri/core/workers/chunks/6aced8e446beceefaf2c.js +0 -1
  127. package/assets/esri/core/workers/chunks/9f459805a6698708830a.js +0 -1
  128. package/assets/esri/core/workers/chunks/a4104b21f2b282dfb14f.js +0 -1
  129. package/assets/esri/core/workers/chunks/cab3199d37411c8ed074.js +0 -1
  130. package/assets/esri/core/workers/chunks/fbfe2195ba87d18bc37a.js +0 -1
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import{unique as t,isSome as i}from"../../core/arrayUtils.js";import{createTask as r}from"../../core/asyncUtils.js";import a from"../../core/Collection.js";import{deprecatedFunction as o}from"../../core/deprecate.js";import s from"../../core/Error.js";import n from"../../core/Evented.js";import{makeHandle as l}from"../../core/handleUtils.js";import d from"../../core/Logger.js";import{destroyMaybe as p,abortMaybe as c,removeMaybe as u}from"../../core/maybe.js";import{throwIfAborted as h,createResolver as f}from"../../core/promiseUtils.js";import{watch as w,on as m,when as y,syncAndInitial as g,initial as k,sync as v,whenOnce as _}from"../../core/reactiveUtils.js";import{property as M}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import{subclass as W}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as F}from"../../core/support/UpdatingHandles.js";import{getTemplatesForLayers as E}from"../../editing/templateUtils.js";import b from"../../layers/GraphicsLayer.js";import{isEditableLayer as T}from"../../layers/support/editableLayers.js";import{isFeatureLayer as V,isSubtypeGroupLayer as S,getOwningPortalUrl as L}from"../../layers/support/layerUtils.js";import{parseKnownArcGISOnlineDomain as I}from"../../portal/support/urlUtils.js";import A from"../../views/SelectionManager.js";import U from"../../views/interactive/sketch/SketchOptions.js";import{SnappingManager as C}from"../../views/interactive/snapping/SnappingManager.js";import O from"../../views/interactive/snapping/SnappingOptions.js";import{isSelectableLayer as j}from"../../views/support/selectionUtils.js";import P from"../Attachments/AttachmentsViewModel.js";import R from"./CreateFeaturesWorkflow.js";import H from"./UpdateFeaturesWorkflow.js";import q from"./UpdateWorkflow.js";import{getLayersFromWorkflow as G,isCreateFeaturesWorkflow as x,isUpdateRecordWorkflow as D,isUpdateFeaturesWorkflow as B,isUpdateWorkflow as N,makeMultipleSourceLayersError as Q,whenEditorLayerView as z}from"./workflowUtils.js";import Z from"./support/EditorItem.js";import{makeTemplateGroupInfoForLayer as $}from"../FeatureTemplates/featureTemplatesUtils.js";import J from"../FeatureTemplates/FeatureTemplatesViewModel.js";import K from"../Sketch/SketchViewModel.js";import X from"../Spinner/SpinnerViewModel.js";import{goTo as Y}from"../support/goToUtils.js";import{isFeatureItem as ee,isLayerItem as te}from"../support/SelectionList/selectionListUtils.js";import ie from"../support/SelectionList/SelectionListViewModel.js";import re from"../support/SelectionToolbar/SelectionToolbarViewModel.js";function ae(e,t){return e?.find(e=>e.layer===t)}let oe=class extends n.EventedAccessor{constructor(e){super(e),this._queuedSelectionTool=null,this._sketchEventListenerHandle=null,this._sketchGraphicsLayer=new b({listMode:"hide",internal:!0}),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 a,this.editorItems=new a,this.failures=[],this.hideTemplatesForInactiveLayers=!1,this.attachmentsViewModel=new P({capabilities:{editing:!0}}),this.featureTemplatesViewModel=new J({disabledItemFunction:({layer:e})=>this._itemIsSuspended(e)}),this.layerInfos=null,this.ownSketchViewModel=new K({layer:this._sketchGraphicsLayer}),this.selectionListViewModel=new ie,this.selectionManager=new A,this.selectionToolbarViewModel=new re({continuousSelectionEnabled:!0,defaultOperationType:"replace",persistSelection:!1,returnGeometry:!1}),this.sketchOptions=new U,this.snappingOptions=new O({attributeRulesEnabled:!0}),this.spinnerViewModel=new X,this.pageStack=[],this.showDiscardEditsPrompt=()=>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.selectFeature=(e,t=!1)=>{const i=this.activeWorkflow;this._candidateCommitted||"update"!==i?.type||(i.data.rootFeature=e,t&&(i.next(),this._candidateCommitted=!0))}}initialize(){this.addHandles([w(()=>{const e=this.view,t=e?.map?.editableLayers.toArray(),i=e?.allLayerViews,r=i?.filter(e=>!!t?.includes(e.layer));return[t,r,this.layerInfos]},()=>this._updateEditorItems(),g),w(()=>this.hideTemplatesForInactiveLayers,()=>this.syncFeatureTemplates()),w(()=>this._selectionSources,()=>this._syncSelectionSources(),k),m(()=>this.activeWorkflow,"cancel",()=>this.emit("workflow-cancel")),m(()=>this.activeWorkflow,"commit",()=>this.emit("workflow-commit")),m(()=>this.activeWorkflow,"complete",()=>{this.emit("workflow-commit"),this._set("activeWorkflow",null)}),y(()=>!this.activeWorkflow&&this._queuedSelectionTool,()=>this._queuedSelectionTool&&this.selectionToolbarViewModel.activateTool(this._queuedSelectionTool)),w(()=>this.activeWorkflow,e=>this.selectionManager.showHighlight=!e),y(()=>this.view?.map,e=>e.add(this._sketchGraphicsLayer),k),m(()=>this.editorItems,"change",()=>this._afterEditorItemsChange()),w(()=>[this.canCreate,this.canUpdateVisible],()=>this._afterEditorItemsChange()),w(()=>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},g),y(()=>"awaiting-update-feature-candidate"===this.state,()=>this._candidateCommitted=!1),m(()=>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 r={layer:e.layer,template:e.template};if(e.supportsUpload)return this.featureTemplatesViewModel.select(t,{emit:!1}),this.startCreateFeaturesWorkflow(r);this.startCreateFeaturesWorkflowAtFeatureCreation(r)}),w(()=>[this.view,this.featureTemplatesViewModel],([e,t])=>{t.view=e},g),m(()=>this.view,"key-down",e=>{"Escape"===e.key&&this.activeWorkflow?.keyboardCancellationEnabled&&(e.stopPropagation(),this.back())}),m(()=>this.sketchViewModel,["create","delete","update"],e=>{const{activeWorkflow:t}=this,i="update"===t?.type,r=G(t),a=i?t?.activeWorkflow?.parentLayer:void 0,o=`sketch-${e.type}`;this.emit(o,{type:o,detail:e,layer:r[0],layers:r,parentLayer:a})},v),w(()=>this.view,e=>{if(this._snappingManager=p(this._snappingManager),!e)return;const t=this.snappingOptions;this._snappingManager=new C({view:e,options:t}),this.ownSketchViewModel.snappingManager=this._snappingManager},g),w(()=>this.snappingOptions,e=>{this._snappingManager&&(this._snappingManager.options=e)},g),m(()=>this.selectionToolbarViewModel,"complete",e=>this._onSelectionComplete(e)),w(()=>({view:this.view,selectionManager:this.effectiveSelectionManager,selectionListViewModel:this.selectionListViewModel,selectionToolbarViewModel:this.selectionToolbarViewModel}),({view:e,selectionManager:t,selectionListViewModel:i,selectionToolbarViewModel:r})=>{t.view=e,i.view=e,r.view=e},g),w(()=>this.effectiveSelectionManager,e=>{this.selectionListViewModel.selectionManager=e,this.selectionToolbarViewModel.selectionManager=e},g)])}destroy(){this._cancelWorkflow({warnIfNoWorkflow:!1}).then(()=>{this.view?.map?.remove(this._sketchGraphicsLayer),this.view=null}),this._updateItemsTask=c(this._updateItemsTask),this._updatingHandles.destroy(),this._sketchEventListenerHandle=u(this._sketchEventListenerHandle),this.selectionListViewModel?.destroy(),this.selectionToolbarViewModel?.destroy(),this.selectionManager.destroy()}get _featureTemplatesLayersAndTables(){const e=new a;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 a;for(const t of this.editorItems)j(t.layer)&&t.supportsUpdateWorkflow&&t.visible&&e.push(t.layer);return e}get activeFeatureCount(){const e=this.activeLeafWorkflow;return x(e)?e.pendingFeatures.length:D(e)&&e.data.edits.feature?1:B(e)?e.data.features.length:0}get activeLeafWorkflow(){const e=this.activeWorkflow;return e&&N(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(){return this.selectionManager}get featureFormViewModel(){const{activeWorkflow:e}=this;return"update"===e?.type?e.activeFeatureFormViewModel:"create-features"===e?.type?e.featureFormViewModel:null}get formViewModel(){const{activeWorkflow:e}=this;return"update"===e?.type?e.activeFeatureFormViewModel:"create-features"===e?.type?e.featureFormViewModel:"update-features"===e?.type?e.formViewModel:null}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 sketchViewModel(){const{activeWorkflow:e}=this;return"update"===e?.type?e.activeSketchViewModel:"create-features"===e?.type||"update-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(){const e=this.sketchViewModel,t=e?.createGraphic?.geometry?.type;return!(!e?.updateGraphics?.length&&"multipoint"!==t)}get page(){const{activeWorkflow:e,state:t}=this;if("update"===e?.type&&null!=e?.activeWorkflow?.featureFormViewModel?.associatedLayer)return"viewing-associated-features";if("update"===e?.type&&null!=e?.activeWorkflow?.featureFormViewModel?.associationId)return"viewing-associated-layers";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(D(e))return!1===e.data.editorItem?.capabilities.update.attributes||!0===e.featureFormViewModel.disabled;if(B(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(D(e)){const{data:t}=e;return t.editorItem?.capabilities.delete.enabled&&!t.readOnly}return!!B(e)&&e.data.editorItems.every(e=>e.capabilities.delete.enabled)}get hasPendingEdits(){return this.activeWorkflow?.hasPendingEdits??!1}get snappingManager(){return this._snappingManager}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 _(()=>!this.updating),!this.canCreate)throw new s("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(r){this._logErrorAndCancelWorkflow(r)}finally{i.resolve()}}async startCreateFeaturesWorkflowAtFeatureEdit(e){await _(()=>!this.updating);const t=this._createUpdatingResolver();try{const{initialFeature:t}=e,i=t.sourceLayer=t.layer,r=i?this.findEditorItemForLayer(i):void 0;if(!r?.supportsCreateFeaturesWorkflow)throw new s("editing:unsupported-workflow","Creating features is unsupported or disabled for this layer.");await this._cancelWorkflow();const a=this._createCreateFeaturesWorkflow({initialFeature:t,layer:r.layer,maxFeatures:1},"creating-features");this._set("activeWorkflow",a),await a.start()}catch(i){this._logErrorAndCancelWorkflow(i)}finally{t.resolve()}}async startUpdateFeaturesWorkflow(e){if(await _(()=>!this.updating),!this.canUpdate)return void this._logError("editing:unsupported-workflow","Update features workflow is unsupported or disabled.");if(t(e.map(e=>e.sourceLayer??e.layer)).length>1)throw Q();const i=this._createUpdatingResolver();try{await this._cancelWorkflow();const t=this._createUpdateFeaturesWorkflow(e);this._set("activeWorkflow",t),await t.start()}catch(r){this._logErrorAndCancelWorkflow(r)}finally{i.resolve()}}async startUpdateWorkflowAtFeatureSelection(){if(await _(()=>!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 _(()=>!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 _(()=>!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("editing-existing-feature");t.data.rootFeature=e,t.addHandles(m(()=>t,"commit",()=>{t.destroy(),this.activeWorkflow===t&&this._set("activeWorkflow",null)})),this._set("activeWorkflow",t),await t.start()}catch(i){this._logErrorAndCancelWorkflow(i)}finally{t.resolve()}}async startUpdateWorkflowWithActiveSelection(){const{selectionListViewModel:e}=this;if(!e.visibleFeatureCount)throw new s("editing:missing-selection","Unable to determine visible selection.");if(e.visibleLayerCount>1)throw new s("editing:features-different-layers","Cannot start workflow with features from different layers.");const t=e.visibleFeatureItems.map(e=>e.graphic);1===t.length?this.startUpdateWorkflowAtFeatureEdit(t[0]):this.startUpdateFeaturesWorkflow(t)}async deleteFeatureFromWorkflow(){o(d.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;return N(e)?e.deleteActiveFeature():B(e)?e.deleteAndCommit():void 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})}findEditorItemForLayer(e){return this.editorItems.find(t=>t.layer===e)}itemHasInvalidFormTemplate(e){return null!=e&&!0===this.findEditorItemForLayer(e.layer)?.hasInvalidFormTemplate}syncFeatureTemplates(){this._featureTemplatesViewModelIsRestricted||this._updateTemplates()}zoomTo(e){const{view:t,sketchViewModel:r}=this;if(!t)return;const a=e??r?.createGraphic;if(a)"mesh"===a.geometry?.type?Y(t,a.geometry):Y(t,a);else{const e=r?.updateGraphics?.toArray();"3d"===t.type&&e?.some(e=>"mesh"===e.geometry?.type)?Y(t,e.map(e=>e.geometry).filter(i)):e&&Y(t,e)}}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){ee(e)&&this.startUpdateWorkflowAtFeatureEdit(e.graphic)}async onSelectionListMenuItemSelect(e){if(ee(e))this.startUpdateWorkflowAtFeatureEdit(e.graphic);else if(te(e)){const t=e.featureItems.filter(e=>e.visible).map(e=>e.graphic);1===t.length?this.startUpdateWorkflowAtFeatureEdit(t[0]):this.startUpdateFeaturesWorkflow(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,r=i.editableLayers.toArray(),a=i.allTables.toArray().filter(e=>V(e)||S(e));return await Promise.allSettled([...r.flatMap(e=>this._getLayerLoadPromise(e)),...a.flatMap(e=>this._getLayerLoadPromise(e))]),h(e),[...r.reverse(),...a.reverse()].filter(e=>T(e)&&("mesh"!==e.geometryType||"3d"===t.type)).flatMap(e=>"subtype-group"===e.type?e.sublayers.toArray():e)}_getLayerLoadPromise(e){return S(e)?e.loadAll():e.load()}_drainEditorItems(){this.editorItems.drain(e=>e.destroy())}_updateEditorItems(){c(this._updateItemsTask);const{view:e}=this,t=r(async t=>{if(!e?.map||!e?.allLayerViews)return;const i=await this._getEditorItemCandidates(t);if(!i.length)return void this._drainEditorItems();const r=[],a=[],o=[],{layerInfos:s}=this;for(const l of i){const t=ae(s,l),i=await z(e,l).catch(()=>null);(t?r:i?a:o).push(new Z({layer:l,layerInfo:t,layerView:i}))}s?.length&&r.sort((e,t)=>s.findIndex(({layer:t})=>t===e.layer)-s.findIndex(({layer:e})=>e===t.layer));const n=[...r,...a,...o];t.aborted||(this._drainEditorItems(),this.editorItems.addMany(n))});this._updatingHandles.addPromise(t.promise),this._updateItemsTask=t}_updateTemplates(){c(this._updateTemplatesTask);const e=r(async e=>{const t=this._templatesByLayer,i=this._featureTemplatesLayersAndTables.filter(e=>!t.has(e));if(i.length>0){const r=await E(i.toArray(),this.view,e);for(const{layer:e,templates:i}of r)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 r of e){const e=t.get(r);e&&e.length>0&&i.push($(r,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 R.create({viewModel:this,creationInfo:e,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:t,applyEditsCallback:(e,t,i)=>this._applyEdits(e,t,i),applyEditsFeatureServiceCallback:(e,t,i)=>this._applyEditsFeatureService(e,t,i),addAttachmentsCallback:(e,t)=>this._addAttachments(e,t)})}_createUpdateFeaturesWorkflow(e){const t=H.create({viewModel:this,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,features:e,applyEdits:(e,t,i)=>this._applyEdits(e,t,i),applyEditsFeatureService:(e,t,i)=>this._applyEditsFeatureService(e,t,i)});return t.addHandles(m(()=>t,"commit",()=>{t.destroy(),this.activeWorkflow===t&&this._set("activeWorkflow",null)})),t}_createUpdateWorkflow(e){return q.create({viewModel:this,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:e,applyEditsCallback:(e,t,i)=>this._applyEdits(e,t,i),applyEditsFeatureServiceCallback:(e,t,i)=>this._applyEditsFeatureService(e,t,i),addAttachmentsCallback:(e,t)=>this._addAttachments(e,t)})}_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 r=null;if(!("addAttachment"in e)||null==e.capabilities?.attachment)throw new s("editor:attachments-not-supported","Adding attachments is not supported for this layer type");return await this._queueOperation(async()=>(r=await(e.addAttachment?.(t,i).catch(e=>{throw e?.error||e}))??null,r)),r}async _applyEdits(e,t,i){let r=null;const a=e.url?await L(e.url):null,o={returnServiceEditsOption:(!a||!I(a))&&!RegExp("/hosted/","i").test(e.url)?"original-and-current-features":void 0,...i};return await this._queueOperation(async()=>{const{view:i}=this;if(!i)return null;const a=await z(i,e).catch(()=>null);return r=await e.applyEdits(t,o),a&&await _(()=>!a.updating),r}),r}async _applyEditsFeatureService(e,t,i){let r=null;return await this._queueOperation(async()=>r=await e.applyEdits(t,i)),r}_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 r={error:i,retry:()=>(t(r,this.failures),this._queueOperation(e)),cancel:()=>{t(r,this.failures)}};this._set("failures",[...this.failures,r])}).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:r}=e,a=t.find(e=>!!e.error)||r.find(e=>!!e.error)||i.find(e=>!!e.error);if(a)throw a.error}}_createUpdatingResolver(){const e=f();return this._updatingHandles.addPromise(e.promise),e}_logErrorAndCancelWorkflow(e){const{name:t,message:i,details:r}=e;this._logError(t??"editing:workflow-start-failed",i??void 0,r??e),this._cancelWorkflow({force:!0})}_itemIsSuspended(e){const t=this.findEditorItemForLayer(e);return null!=t&&(!t.visible||t.disabled)}_logError(e,t,i){d.getLogger(this).error(new s(e,t,i))}_syncSelectionSources(){this.selectionManager.sources.items=this._selectionSources.toArray()}async _onSelectionComplete(e){if(e.aborted)return;const{operationType:t,selection:i}=e,{effectiveSelectionManager:r}=this,a="ready"===this.state,o=1===i.length;if(this._queuedSelectionTool=void 0,a&&o&&(0===r.count&&"add"===t||"replace"===t))return this._queuedSelectionTool=e.toolName,this.startUpdateWorkflowAtFeatureEdit(i[0]);switch(t){case"remove":r.updateSelection({current:[],added:[],removed:i});break;case"replace":r.clear(),r.updateSelection({current:i,added:[],removed:[]});break;case"add":r.updateSelection({current:i,added:[],removed:[]})}}};e([M()],oe.prototype,"_featureTemplatesLayersAndTables",null),e([M()],oe.prototype,"_queuedSelectionTool",void 0),e([M()],oe.prototype,"_snappingManager",void 0),e([M()],oe.prototype,"_selectionSources",null),e([M()],oe.prototype,"activeFeatureCount",null),e([M({readOnly:!0})],oe.prototype,"activeWorkflow",void 0),e([M()],oe.prototype,"activeLeafWorkflow",null),e([M({readOnly:!0})],oe.prototype,"_activityQueue",void 0),e([M({readOnly:!0})],oe.prototype,"canCreate",null),e([M()],oe.prototype,"canCreateVisible",null),e([M({readOnly:!0})],oe.prototype,"canUpdate",null),e([M()],oe.prototype,"canUpdateVisible",null),e([M()],oe.prototype,"featureTemplatesLayers",null),e([M()],oe.prototype,"editorItems",void 0),e([M()],oe.prototype,"effectiveSelectionManager",null),e([M({readOnly:!0})],oe.prototype,"failures",void 0),e([M()],oe.prototype,"hideTemplatesForInactiveLayers",void 0),e([M({type:P})],oe.prototype,"attachmentsViewModel",void 0),e([M()],oe.prototype,"featureFormViewModel",null),e([M()],oe.prototype,"formViewModel",null),e([M()],oe.prototype,"utilityNetworkAssociationAddAssociationViewModel",null),e([M({type:J})],oe.prototype,"featureTemplatesViewModel",void 0),e([M()],oe.prototype,"labelOptions",null),e([M()],oe.prototype,"layerInfos",void 0),e([M()],oe.prototype,"ownSketchViewModel",void 0),e([M()],oe.prototype,"selectionListViewModel",void 0),e([M()],oe.prototype,"selectionManager",void 0),e([M()],oe.prototype,"selectionToolbarViewModel",void 0),e([M()],oe.prototype,"sketchOptions",void 0),e([M()],oe.prototype,"sketchViewModel",null),e([M({type:O,nonNullable:!0})],oe.prototype,"snappingOptions",void 0),e([M()],oe.prototype,"spinnerViewModel",void 0),e([M()],oe.prototype,"state",null),e([M({readOnly:!0})],oe.prototype,"syncing",null),e([M()],oe.prototype,"updating",null),e([M()],oe.prototype,"tooltipOptions",null),e([M()],oe.prototype,"valueOptions",null),e([M()],oe.prototype,"view",null),e([M()],oe.prototype,"canZoomTo",null),e([M()],oe.prototype,"pageStack",void 0),e([M()],oe.prototype,"showDiscardEditsPrompt",void 0),e([M()],oe.prototype,"_candidateCommitted",void 0),e([M()],oe.prototype,"page",null),e([M()],oe.prototype,"featureFormDisabled",null),e([M()],oe.prototype,"featureFormHasAssociation",null),e([M()],oe.prototype,"canGoBack",null),e([M()],oe.prototype,"shouldShowDeleteButton",null),e([M()],oe.prototype,"hasPendingEdits",null),e([M()],oe.prototype,"snappingManager",null),oe=e([W("esri.widgets.Editor.EditorViewModel")],oe);const se=oe;export{se as default};
5
+ import{__decorate as e}from"tslib";import{unique as t,isSome as i}from"../../core/arrayUtils.js";import{createTask as r}from"../../core/asyncUtils.js";import a from"../../core/Collection.js";import{deprecatedFunction as o}from"../../core/deprecate.js";import s from"../../core/Error.js";import n from"../../core/Evented.js";import{makeHandle as l}from"../../core/handleUtils.js";import d from"../../core/Logger.js";import{destroyMaybe as p,abortMaybe as c,removeMaybe as u}from"../../core/maybe.js";import{throwIfAborted as h,createResolver as f}from"../../core/promiseUtils.js";import{watch as w,on as m,when as y,syncAndInitial as g,initial as v,sync as k,whenOnce as _}from"../../core/reactiveUtils.js";import{property as M}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import{subclass as W}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as F}from"../../core/support/UpdatingHandles.js";import{getTemplatesForLayers as E}from"../../editing/templateUtils.js";import b from"../../layers/GraphicsLayer.js";import{isEditableLayer as T}from"../../layers/support/editableLayers.js";import{isFeatureLayer as V,isSubtypeGroupLayer as S,getOwningPortalUrl as L}from"../../layers/support/layerUtils.js";import{parseKnownArcGISOnlineDomain as I}from"../../portal/support/urlUtils.js";import A from"../../views/SelectionManager.js";import U from"../../views/interactive/sketch/SketchOptions.js";import{SnappingManager as C}from"../../views/interactive/snapping/SnappingManager.js";import O from"../../views/interactive/snapping/SnappingOptions.js";import{isSelectableLayer as j}from"../../views/support/selectionUtils.js";import P from"../Attachments/AttachmentsViewModel.js";import R from"./CreateFeaturesWorkflow.js";import H from"./UpdateFeaturesWorkflow.js";import q from"./UpdateWorkflow.js";import{getLayersFromWorkflow as G,isCreateFeaturesWorkflow as x,isUpdateRecordWorkflow as D,isUpdateFeaturesWorkflow as B,isUpdateWorkflow as N,makeMultipleSourceLayersError as Q,whenEditorLayerView as z}from"./workflowUtils.js";import Z from"./support/EditorItem.js";import{makeTemplateGroupInfoForLayer as $}from"../FeatureTemplates/featureTemplatesUtils.js";import J from"../FeatureTemplates/FeatureTemplatesViewModel.js";import K from"../Sketch/SketchViewModel.js";import X from"../Spinner/SpinnerViewModel.js";import{goTo as Y}from"../support/goToUtils.js";import{isFeatureItem as ee,isLayerItem as te}from"../support/SelectionList/selectionListUtils.js";import ie from"../support/SelectionList/SelectionListViewModel.js";import re from"../support/SelectionToolbar/SelectionToolbarViewModel.js";function ae(e,t){return e?.find(e=>e.layer===t)}let oe=class extends n.EventedAccessor{constructor(e){super(e),this._queuedSelectionTool=null,this._sketchEventListenerHandle=null,this._sketchGraphicsLayer=new b({listMode:"hide",internal:!0}),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 a,this.editorItems=new a,this.failures=[],this.hideTemplatesForInactiveLayers=!1,this.attachmentsViewModel=new P({capabilities:{editing:!0}}),this.featureTemplatesViewModel=new J({disabledItemFunction:({layer:e})=>this._itemIsSuspended(e)}),this.layerInfos=null,this.ownSketchViewModel=new K({layer:this._sketchGraphicsLayer}),this.selectionListViewModel=new ie,this.selectionManager=new A,this.selectionToolbarViewModel=new re({continuousSelectionEnabled:!0,defaultOperationType:"replace",persistSelection:!1,returnGeometry:!1}),this.sketchOptions=new U,this.snappingOptions=new O({attributeRulesEnabled:!0}),this.spinnerViewModel=new X,this.pageStack=[],this.showDiscardEditsPrompt=()=>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.selectFeature=(e,t=!1)=>{const i=this.activeWorkflow;this._candidateCommitted||"update"!==i?.type||(i.data.rootFeature=e,t&&(i.next(),this._candidateCommitted=!0))}}initialize(){this.addHandles([w(()=>{const e=this.view,t=e?.map?.editableLayers.toArray(),i=e?.allLayerViews,r=i?.filter(e=>!!t?.includes(e.layer));return[t,r,this.layerInfos]},()=>this._updateEditorItems(),g),w(()=>this.hideTemplatesForInactiveLayers,()=>this.syncFeatureTemplates()),w(()=>this._selectionSources,()=>this._syncSelectionSources(),v),m(()=>this.activeWorkflow,"cancel",()=>this.emit("workflow-cancel")),m(()=>this.activeWorkflow,"commit",()=>this.emit("workflow-commit")),m(()=>this.activeWorkflow,"complete",()=>{this.emit("workflow-commit"),this._set("activeWorkflow",null)}),y(()=>!this.activeWorkflow&&this._queuedSelectionTool,()=>this._queuedSelectionTool&&this.selectionToolbarViewModel.activateTool(this._queuedSelectionTool)),w(()=>this.activeWorkflow,e=>this.selectionManager.showHighlight=!e),y(()=>this.view?.map,e=>e.add(this._sketchGraphicsLayer),v),m(()=>this.editorItems,"change",()=>this._afterEditorItemsChange()),w(()=>[this.canCreate,this.canUpdateVisible],()=>this._afterEditorItemsChange()),w(()=>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},g),y(()=>"awaiting-update-feature-candidate"===this.state,()=>this._candidateCommitted=!1),m(()=>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 r={layer:e.layer,template:e.template};if(e.supportsUpload)return this.featureTemplatesViewModel.select(t,{emit:!1}),this.startCreateFeaturesWorkflow(r);this.startCreateFeaturesWorkflowAtFeatureCreation(r)}),w(()=>[this.view,this.featureTemplatesViewModel],([e,t])=>{t.view=e},g),m(()=>this.view,"key-down",e=>{"Escape"===e.key&&this.activeWorkflow?.keyboardCancellationEnabled&&(e.stopPropagation(),this.back())}),m(()=>this.sketchViewModel,["create","delete","update"],e=>{const{activeWorkflow:t}=this,i="update"===t?.type,r=G(t),a=i?t?.activeWorkflow?.parentLayer??void 0:void 0,o=`sketch-${e.type}`;this.emit(o,{type:o,detail:e,layer:r[0],layers:r,parentLayer:a})},k),w(()=>this.view,e=>{if(this._snappingManager=p(this._snappingManager),!e)return;const t=this.snappingOptions;this._snappingManager=new C({view:e,options:t}),this.ownSketchViewModel.snappingManager=this._snappingManager},g),w(()=>this.snappingOptions,e=>{this._snappingManager&&(this._snappingManager.options=e)},g),m(()=>this.selectionToolbarViewModel,"complete",e=>this._onSelectionComplete(e)),w(()=>({view:this.view,selectionManager:this.effectiveSelectionManager,selectionListViewModel:this.selectionListViewModel,selectionToolbarViewModel:this.selectionToolbarViewModel}),({view:e,selectionManager:t,selectionListViewModel:i,selectionToolbarViewModel:r})=>{t.view=e,i.view=e,r.view=e},g),w(()=>this.effectiveSelectionManager,e=>{this.selectionListViewModel.selectionManager=e,this.selectionToolbarViewModel.selectionManager=e},g)])}destroy(){this._cancelWorkflow({warnIfNoWorkflow:!1}).then(()=>{this.view?.map?.remove(this._sketchGraphicsLayer),this.view=null}),this._updateItemsTask=c(this._updateItemsTask),this._updatingHandles.destroy(),this._sketchEventListenerHandle=u(this._sketchEventListenerHandle),this.selectionListViewModel?.destroy(),this.selectionToolbarViewModel?.destroy(),this.selectionManager.destroy()}get _featureTemplatesLayersAndTables(){const e=new a;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 a;for(const t of this.editorItems)j(t.layer)&&t.supportsUpdateWorkflow&&t.visible&&e.push(t.layer);return e}get activeFeatureCount(){const e=this.activeLeafWorkflow;return x(e)?e.pendingFeatures.length:D(e)&&e.data.edits.feature?1:B(e)?e.data.features.length:0}get activeLeafWorkflow(){const e=this.activeWorkflow;return e&&N(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(){return this.selectionManager}get featureFormViewModel(){const{activeWorkflow:e}=this;return"update"===e?.type?e.activeFeatureFormViewModel:"create-features"===e?.type?e.featureFormViewModel:null}get formViewModel(){const{activeWorkflow:e}=this;return"update"===e?.type?e.activeFeatureFormViewModel:"create-features"===e?.type?e.featureFormViewModel:"update-features"===e?.type?e.formViewModel:null}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 sketchViewModel(){const{activeWorkflow:e}=this;return"update"===e?.type?e.activeSketchViewModel:"create-features"===e?.type||"update-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(){const e=this.sketchViewModel,t=e?.createGraphic?.geometry?.type;return!(!e?.updateGraphics?.length&&"multipoint"!==t)}get page(){const{activeWorkflow:e,state:t}=this;if("update"===e?.type&&null!=e?.activeWorkflow?.featureFormViewModel?.associatedLayer)return"viewing-associated-features";if("update"===e?.type&&null!=e?.activeWorkflow?.featureFormViewModel?.associationId)return"viewing-associated-layers";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(D(e))return!1===e.data.editorItem?.capabilities.update.attributes||!0===e.featureFormViewModel.disabled;if(B(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(D(e)){const{data:t}=e;return t.editorItem?.capabilities.delete.enabled&&!t.readOnly}return!!B(e)&&e.data.editorItems.every(e=>e.capabilities.delete.enabled)}get hasPendingEdits(){return this.activeWorkflow?.hasPendingEdits??!1}get snappingManager(){return this._snappingManager}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 _(()=>!this.updating),!this.canCreate)throw new s("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(r){this._logErrorAndCancelWorkflow(r)}finally{i.resolve()}}async startCreateFeaturesWorkflowAtFeatureEdit(e){await _(()=>!this.updating);const t=this._createUpdatingResolver();try{const{initialFeature:t}=e,i=t.sourceLayer=t.layer,r=i?this.findEditorItemForLayer(i):void 0;if(!r?.supportsCreateFeaturesWorkflow)throw new s("editing:unsupported-workflow","Creating features is unsupported or disabled for this layer.");await this._cancelWorkflow();const a=this._createCreateFeaturesWorkflow({initialFeature:t,layer:r.layer,maxFeatures:1},"creating-features");this._set("activeWorkflow",a),await a.start()}catch(i){this._logErrorAndCancelWorkflow(i)}finally{t.resolve()}}async startUpdateFeaturesWorkflow(e){if(await _(()=>!this.updating),!this.canUpdate)return void this._logError("editing:unsupported-workflow","Update features workflow is unsupported or disabled.");if(t(e.map(e=>e.sourceLayer??e.layer)).length>1)throw Q();const i=this._createUpdatingResolver();try{await this._cancelWorkflow();const t=this._createUpdateFeaturesWorkflow(e);this._set("activeWorkflow",t),await t.start()}catch(r){this._logErrorAndCancelWorkflow(r)}finally{i.resolve()}}async startUpdateWorkflowAtFeatureSelection(){if(await _(()=>!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 _(()=>!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 _(()=>!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("editing-existing-feature");t.data.rootFeature=e,t.addHandles(m(()=>t,"commit",()=>{t.destroy(),this.activeWorkflow===t&&this._set("activeWorkflow",null)})),this._set("activeWorkflow",t),await t.start()}catch(i){this._logErrorAndCancelWorkflow(i)}finally{t.resolve()}}async startUpdateWorkflowWithActiveSelection(){const{selectionListViewModel:e}=this;if(!e.visibleFeatureCount)throw new s("editing:missing-selection","Unable to determine visible selection.");if(e.visibleLayerCount>1)throw new s("editing:features-different-layers","Cannot start workflow with features from different layers.");const t=e.visibleFeatureItems.map(e=>e.graphic);1===t.length?this.startUpdateWorkflowAtFeatureEdit(t[0]):this.startUpdateFeaturesWorkflow(t)}async deleteFeatureFromWorkflow(){o(d.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;return N(e)?e.deleteActiveFeature():B(e)?e.deleteAndCommit():void 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})}findEditorItemForLayer(e){return this.editorItems.find(t=>t.layer===e)}itemHasInvalidFormTemplate(e){return null!=e&&!0===this.findEditorItemForLayer(e.layer)?.hasInvalidFormTemplate}syncFeatureTemplates(){this._featureTemplatesViewModelIsRestricted||this._updateTemplates()}zoomTo(e){const{view:t,sketchViewModel:r}=this;if(!t)return;const a=e??r?.createGraphic;if(a)"mesh"===a.geometry?.type?Y(t,a.geometry):Y(t,a);else{const e=r?.updateGraphics?.toArray();"3d"===t.type&&e?.some(e=>"mesh"===e.geometry?.type)?Y(t,e.map(e=>e.geometry).filter(i)):e&&Y(t,e)}}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){ee(e)&&this.startUpdateWorkflowAtFeatureEdit(e.graphic)}async onSelectionListMenuItemSelect(e){if(ee(e))this.startUpdateWorkflowAtFeatureEdit(e.graphic);else if(te(e)){const t=e.featureItems.filter(e=>e.visible).map(e=>e.graphic);1===t.length?this.startUpdateWorkflowAtFeatureEdit(t[0]):this.startUpdateFeaturesWorkflow(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,r=i.editableLayers.toArray(),a=i.allTables.toArray().filter(e=>V(e)||S(e));return await Promise.allSettled([...r.flatMap(e=>this._getLayerLoadPromise(e)),...a.flatMap(e=>this._getLayerLoadPromise(e))]),h(e),[...r.reverse(),...a.reverse()].filter(e=>T(e)&&("mesh"!==e.geometryType||"3d"===t.type)).flatMap(e=>"subtype-group"===e.type?e.sublayers.toArray():e)}_getLayerLoadPromise(e){return S(e)?e.loadAll():e.load()}_drainEditorItems(){this.editorItems.drain(e=>e.destroy())}_updateEditorItems(){c(this._updateItemsTask);const{view:e}=this,t=r(async t=>{if(!e?.map||!e?.allLayerViews)return;const i=await this._getEditorItemCandidates(t);if(!i.length)return void this._drainEditorItems();const r=[],a=[],o=[],{layerInfos:s}=this;for(const l of i){const t=ae(s,l),i=await z(e,l).catch(()=>null);(t?r:i?a:o).push(new Z({layer:l,layerInfo:t,layerView:i}))}s?.length&&r.sort((e,t)=>s.findIndex(({layer:t})=>t===e.layer)-s.findIndex(({layer:e})=>e===t.layer));const n=[...r,...a,...o];t.aborted||(this._drainEditorItems(),this.editorItems.addMany(n))});this._updatingHandles.addPromise(t.promise),this._updateItemsTask=t}_updateTemplates(){c(this._updateTemplatesTask);const e=r(async e=>{const t=this._templatesByLayer,i=this._featureTemplatesLayersAndTables.filter(e=>!t.has(e));if(i.length>0){const r=await E(i.toArray(),this.view,e);for(const{layer:e,templates:i}of r)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 r of e){const e=t.get(r);e&&e.length>0&&i.push($(r,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 R.create({viewModel:this,creationInfo:e,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:t,applyEditsCallback:(e,t,i)=>this._applyEdits(e,t,i),applyEditsFeatureServiceCallback:(e,t,i)=>this._applyEditsFeatureService(e,t,i),addAttachmentsCallback:(e,t)=>this._addAttachments(e,t)})}_createUpdateFeaturesWorkflow(e){const t=H.create({viewModel:this,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,features:e,applyEdits:(e,t,i)=>this._applyEdits(e,t,i),applyEditsFeatureService:(e,t,i)=>this._applyEditsFeatureService(e,t,i)});return t.addHandles(m(()=>t,"commit",()=>{t.destroy(),this.activeWorkflow===t&&this._set("activeWorkflow",null)})),t}_createUpdateWorkflow(e){return q.create({viewModel:this,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:e,applyEditsCallback:(e,t,i)=>this._applyEdits(e,t,i),applyEditsFeatureServiceCallback:(e,t,i)=>this._applyEditsFeatureService(e,t,i),addAttachmentsCallback:(e,t)=>this._addAttachments(e,t)})}_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 r=null;if(!("addAttachment"in e)||null==e.capabilities?.attachment)throw new s("editor:attachments-not-supported","Adding attachments is not supported for this layer type");return await this._queueOperation(async()=>(r=await(e.addAttachment?.(t,i).catch(e=>{throw e?.error||e}))??null,r)),r}async _applyEdits(e,t,i){let r=null;const a=e.url?await L(e.url):null,o={returnServiceEditsOption:(!a||!I(a))&&!RegExp("/hosted/","i").test(e.url)?"original-and-current-features":void 0,...i};return await this._queueOperation(async()=>{const{view:i}=this;if(!i)return null;const a=await z(i,e).catch(()=>null);return r=await e.applyEdits(t,o),a&&await _(()=>!a.updating),r}),r}async _applyEditsFeatureService(e,t,i){let r=null;return await this._queueOperation(async()=>r=await e.applyEdits(t,i)),r}_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 r={error:i,retry:()=>(t(r,this.failures),this._queueOperation(e)),cancel:()=>{t(r,this.failures)}};this._set("failures",[...this.failures,r])}).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:r}=e,a=t.find(e=>!!e.error)||r.find(e=>!!e.error)||i.find(e=>!!e.error);if(a)throw a.error}}_createUpdatingResolver(){const e=f();return this._updatingHandles.addPromise(e.promise),e}_logErrorAndCancelWorkflow(e){const{name:t,message:i,details:r}=e;this._logError(t??"editing:workflow-start-failed",i??void 0,r??e),this._cancelWorkflow({force:!0})}_itemIsSuspended(e){const t=this.findEditorItemForLayer(e);return null!=t&&(!t.visible||t.disabled)}_logError(e,t,i){d.getLogger(this).error(new s(e,t,i))}_syncSelectionSources(){this.selectionManager.sources.items=this._selectionSources.toArray()}async _onSelectionComplete(e){if(e.aborted)return;const{operationType:t,selection:i}=e,{effectiveSelectionManager:r}=this,a="ready"===this.state,o=1===i.length;if(this._queuedSelectionTool=void 0,a&&o&&(0===r.count&&"add"===t||"replace"===t))return this._queuedSelectionTool=e.toolName,this.startUpdateWorkflowAtFeatureEdit(i[0]);switch(t){case"remove":r.updateSelection({current:[],added:[],removed:i});break;case"replace":r.clear(),r.updateSelection({current:i,added:[],removed:[]});break;case"add":r.updateSelection({current:i,added:[],removed:[]})}}};e([M()],oe.prototype,"_featureTemplatesLayersAndTables",null),e([M()],oe.prototype,"_queuedSelectionTool",void 0),e([M()],oe.prototype,"_snappingManager",void 0),e([M()],oe.prototype,"_selectionSources",null),e([M()],oe.prototype,"activeFeatureCount",null),e([M({readOnly:!0})],oe.prototype,"activeWorkflow",void 0),e([M()],oe.prototype,"activeLeafWorkflow",null),e([M({readOnly:!0})],oe.prototype,"_activityQueue",void 0),e([M({readOnly:!0})],oe.prototype,"canCreate",null),e([M()],oe.prototype,"canCreateVisible",null),e([M({readOnly:!0})],oe.prototype,"canUpdate",null),e([M()],oe.prototype,"canUpdateVisible",null),e([M()],oe.prototype,"featureTemplatesLayers",null),e([M()],oe.prototype,"editorItems",void 0),e([M()],oe.prototype,"effectiveSelectionManager",null),e([M({readOnly:!0})],oe.prototype,"failures",void 0),e([M()],oe.prototype,"hideTemplatesForInactiveLayers",void 0),e([M({type:P})],oe.prototype,"attachmentsViewModel",void 0),e([M()],oe.prototype,"featureFormViewModel",null),e([M()],oe.prototype,"formViewModel",null),e([M()],oe.prototype,"utilityNetworkAssociationAddAssociationViewModel",null),e([M({type:J})],oe.prototype,"featureTemplatesViewModel",void 0),e([M()],oe.prototype,"labelOptions",null),e([M()],oe.prototype,"layerInfos",void 0),e([M()],oe.prototype,"ownSketchViewModel",void 0),e([M()],oe.prototype,"selectionListViewModel",void 0),e([M()],oe.prototype,"selectionManager",void 0),e([M()],oe.prototype,"selectionToolbarViewModel",void 0),e([M()],oe.prototype,"sketchOptions",void 0),e([M()],oe.prototype,"sketchViewModel",null),e([M({type:O,nonNullable:!0})],oe.prototype,"snappingOptions",void 0),e([M()],oe.prototype,"spinnerViewModel",void 0),e([M()],oe.prototype,"state",null),e([M({readOnly:!0})],oe.prototype,"syncing",null),e([M()],oe.prototype,"updating",null),e([M()],oe.prototype,"tooltipOptions",null),e([M()],oe.prototype,"valueOptions",null),e([M()],oe.prototype,"view",null),e([M()],oe.prototype,"canZoomTo",null),e([M()],oe.prototype,"pageStack",void 0),e([M()],oe.prototype,"showDiscardEditsPrompt",void 0),e([M()],oe.prototype,"_candidateCommitted",void 0),e([M()],oe.prototype,"page",null),e([M()],oe.prototype,"featureFormDisabled",null),e([M()],oe.prototype,"featureFormHasAssociation",null),e([M()],oe.prototype,"canGoBack",null),e([M()],oe.prototype,"shouldShowDeleteButton",null),e([M()],oe.prototype,"hasPendingEdits",null),e([M()],oe.prototype,"snappingManager",null),oe=e([W("esri.widgets.Editor.EditorViewModel")],oe);const se=oe;export{se as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../Color.js";import t from"../../Graphic.js";import{isSome as r,equals as n,addMany as a}from"../../core/arrayUtils.js";import{createTask as o}from"../../core/asyncUtils.js";import"../../core/has.js";import i from"../../core/Error.js";import{handlesGroup as s,makeHandle as l,abortHandle as c}from"../../core/handleUtils.js";import{clone as u}from"../../core/lang.js";import p from"../../core/Logger.js";import{getOrCreateMapValue as d}from"../../core/MapUtils.js";import{debounce as f,isPromiseLike as y,throwIfAborted as m,whenOrAbort as h}from"../../core/promiseUtils.js";import{watch as g,on as b,whenOnce as w}from"../../core/reactiveUtils.js";import{px2pt as v}from"../../core/screenUtils.js";import{diff as I}from"../../core/accessorSupport/diffUtils.js";import{isSharedTemplateOrMetadata as T,isSharedGroupTemplate as S,isSharedTemplate as j,isSharedPresetTemplate as F,isStandardFeatureTemplate as k,isSharedFeatureTemplate as A}from"../../editing/templateUtils.js";import{getSharedTemplateProvider as U}from"../../editing/sharedTemplates/SharedTemplateProvider.js";import V from"../../layers/GraphicsLayer.js";import{featureHasFields as L,fixFields as M,getDisplayFieldName as O}from"../../layers/support/fieldUtils.js";import{isSubtypeSublayer as x}from"../../layers/support/layerUtils.js";import{calculateTolerance as z}from"../../renderers/support/clickToleranceUtils.js";import{meterIn as q}from"../../renderers/support/lengthUtils.js";import{isRenderer as P}from"../../renderers/support/typeUtils.js";import{getTransformationType as E}from"../../renderers/visualVariables/support/sizeVariableUtils.js";import C from"../../symbols/SimpleFillSymbol.js";import R from"../../symbols/SimpleLineSymbol.js";import D from"../../symbols/SimpleMarkerSymbol.js";import{to3D as G}from"../../symbols/support/symbolConversion.js";import{getDisplayedSymbol as B}from"../../symbols/support/symbolUtils.js";import{getServices as N}from"../../undoredo/support/Services.js";import{GraphicState as Z}from"../../views/3d/layers/graphics/GraphicState.js";import{defaultDrawingMode as W}from"../../views/draw/DrawingMode.js";import{createQueryGeometry as Q}from"../../views/support/drapedUtils.js";import{filterGraphicHits as $,hitTestSelectSimilarDistance as J}from"../../views/support/hitTestSelectUtils.js";import{dependencySort as H}from"./support/dependencySort.js";import{isDrawGraphicTool as K}from"../Sketch/support/sketchUtils.js";const X=()=>p.getLogger("esri.widgets.Editor.workflowUtils");function Y(e){return!!e&&"features"in e}function _(e){return null!=e&&"create-features"===e.type}function ee(e){return null!=e&&"update-features"===e.type}function te(e){return null!=e&&/update-/.test(e.type)&&"fullFeature"in e}function re(e){return null!=e&&"update"===e.type}function ne(e){if(!(e&&"renderer"in e&&ue(e.renderer)))return{rotation:null,size:null};const t=e.renderer.getVisualVariablesForType("rotation").filter(e=>(!e.axis||"heading"===e.axis)&&e.field&&!e.valueExpression),r=e.renderer.getVisualVariablesForType("size").filter(e=>e.field&&!e.useSymbolValue&&!e.valueExpression&&"real-world-size"===E(e));return{rotation:1===t.length?t[0]:null,size:1===r.length?r[0]:null}}function ae(e){const t=e.sourceLayer;if(!(t&&"renderer"in t&&ue(t.renderer)))return{rotation:null,size:null};const{rotation:r,size:n}=ne(t);let a=null,o=null;if(r){const e=t.fields?.filter(e=>e.name===r.field),n=1===e?.length?e[0]:null;a=oe(r,n)}if(n){const e=t.fields?.filter(e=>e.name===n.field),r=1===e?.length?e[0]:null;o=le(n,r)}return{rotation:a,size:o}}function oe(e,t){const r="heading"===(e.axis||"heading")&&"arithmetic"===e.rotationType?-1:1,n=t?.type??"double",a={initial:0,current:0};return{field:e.field,fieldType:n,getDefaultValue:()=>Promise.resolve(0),getValue:e=>(a.current=a.initial-r*e,ce((a.current+360)%360,n)),setInitialValue:e=>{a.initial=e,a.current=0},isUpdatingInteractively:!1,rotationType:e.rotationType??"geographic"}}function ie(e,t){switch(t){case"width":return e[0];case"depth":return e[1];case"height":return e[2];default:return e[2]||e[1]||e[0]}}async function se(e,t,r){if(null==t)return 0;const{symbol:n}=G(t);if(null==n||"web-style"===n.type||"cim"===n.type)return 0;const a=n.symbolLayers.at(0);if(!a)return 0;switch(a.type){case"icon":{const{computeIconLayerResourceSize:e}=await import("../../symbols/support/symbolLayerUtils.js");return Math.min(Ke.icon,(await e(a,Ke.icon))[0])||Ke.icon}case"text":return Ke.text;case"line":return Ke.line;case"object":{const{computeObjectLayerResourceSize:t}=await import("../../symbols/support/symbolLayerUtils.js");return ie(await t(a,e.scale/Ke.viewScaleSizeFactor),r)}case"path":case"extrude":return e.scale/Ke.viewScaleSizeFactor;default:return 0}}function le(e,t){const r=e.axis,n=t?.type??"double",a={initial:0,current:0},o=q[e.valueUnit]??1;let i;return i="area"===e.valueRepresentation?e=>(e*o/2)**2*Math.PI:"radius"===e.valueRepresentation||"distance"===e.valueRepresentation?e=>e*o/2:e=>e*o,{field:e.field,fieldType:n,getDefaultValue:async(e,t)=>ce(i(await se(t,e,r)),n),getValue:(e,t)=>(a.initial||(a.initial=t.pixelSizeAt(t.center)),a.current=a.initial*e,ce(a.current,n)),setInitialValue:e=>{a.initial=e,a.current=0},isUpdatingInteractively:!1,displayUnit:_e(e.valueUnit),axis:e.axis}}function ce(e,t){switch(t){case"small-integer":case"integer":case"long":return Math.round(e);case"double":case"single":return e;default:return 0}}function ue(e){if(!P(e))return!1;switch(e?.type){case"class-breaks":case"simple":case"unique-value":case"dot-density":case"dictionary":case"pie-chart":return!0;default:return!1}}async function pe(e,t,r){const n=await B(e,{useSourceLayer:!0,ignoreGraphicSymbol:!0,webStyleCache:t,scale:r});null!=I(e.symbol,n)&&(e.symbol=n)}function de(e,t){if(!e||!t)throw new Error("no geometry type");if("multipatch"===e)return{tool:"mesh",createOptions:{mode:"hybrid"}};const r=new Map;r.set("circle",{mode:"freehand"}),r.set("rectangle",{mode:"freehand"});const n={mode:W,optionsPerTool:r};if(T(t)){const a=t.defaultTool,o=S(t)?t.definition?.inputGeometryType??e:e;switch(a){case"freehand":case"stream-line":return{tool:"polyline"===o?"freehandPolyline":"freehandPolygon",createOptions:n};case"autocomplete-freehand-polygons":case"stream-polygon":return{tool:"freehandPolygon",createOptions:n};case"autocomplete-polygons":case"difference-polygon":case"create-structures":case"polygon":case"trace":return{tool:"polygon"===o?"polygon":"polyline",createOptions:n};case"circle":return r.get("circle").preserveAspectRatio=!0,{tool:"circle",createOptions:n};case"ellipse":return r.get("circle").preserveAspectRatio=!1,{tool:"circle",createOptions:n};case"create-points-along-line":case"multipoint":return{tool:"multipoint",createOptions:n};case"line":case"radial-line":case"right-angle-line":case"split":case"two-point-line":return{tool:"polyline",createOptions:n};case"rectangle":case"regular-polygon":case"right-angle-polygon":return{tool:"rectangle",createOptions:n};case"elevation-point-from-contour":case"elevation-point-from-dem":case"parcel-seed":case"point":case"point-and-rotation":case"point-at-end-of-line":return{tool:"point",createOptions:n}}}else{const a=t.drawingTool;if("circle"===a||"ellipse"===a)return r.get("circle").preserveAspectRatio="circle"===a,{tool:"circle",createOptions:n};if("rectangle"===a)return{tool:"rectangle",createOptions:n};if("freehand"===a)return{tool:"polygon"===e?"freehandPolygon":"freehandPolyline",createOptions:n}}return{tool:e,createOptions:n}}async function fe(e,t,r){const{creationInfo:n,fullTemplate:a}=t;if(!n)throw new i("featureworkflow","No creation info provided.");const o=n.layer,s=Me(a,n.attributeOverrides),{view:l}=e,c="2d"===l?.type;S(a)||F(a)||await Oe(e,o,s,r,c?l.scale:null);const{capabilities:u}=o;e.layer.elevationInfo=o.elevationInfo;const p=de(o.geometryType,a);e.defaultCreateOptions={graphicProperties:{attributes:s,sourceLayer:o},mode:p.createOptions.mode,optionsPerTool:p.createOptions.optionsPerTool,preserveAspectRatio:p.createOptions.preserveAspectRatio,hasZ:u.data.supportsZ,defaultZ:(c?u.editing.zDefault:null)??e.defaultCreateOptions.defaultZ},null==n.geometryToPlace?await e.create(p.tool):await e.place(n.geometryToPlace,{graphicProperties:{attributes:s,sourceLayer:o}})}async function ye(e){return s([await me(e),await he(e)])}async function me({creationAttributes:e,data:t,sketchViewModel:r,view:n,webStyleCache:a}){const{creationInfo:o}=t,{fullTemplate:i}=t;if(!o||"2d"!==n?.type||S(i)||F(i))return null;const s=f(t=>Oe(r,o.layer,e,a,t));return g(()=>n.scale,e=>s(e))}async function he({data:t,sketchViewModel:r,view:n}){const{templateExecutorInfo:a}=t;if(!a)return null;const o=r.activeComponent;if(!n||!K(o))return X().error(new i("featureworkflow","Failed to set up template feedback.")),null;const c=new V({effect:"saturate(0.6) opacity(0.8)",listMode:"hide",title:"Shared Template Feedback Graphics"});n.map?.add(c);const{executor:u,serviceLayersById:p}=a,d=n.theme?.accentColor??new e([255,165,0,1]);return s([b(()=>o,["cursor-update","vertex-add"],()=>{c.removeAll();const e=o.graphic?.geometry;if(!e||!ge(e))return;const t=u(e,"digitizing");if(!y(t))for(const r of t.edits){const e=p.get(r.id);if(e&&r.addFeatures&&0!==r.addFeatures.length)for(const t of e)if(!t.isTable)for(const e of r.addFeatures){const t=be(e,d);t&&c.add(t)}}}),l(()=>{n.map.remove(c),c.destroy()})])}function ge(e){switch(e.type){case"point":case"multipoint":return!0;case"polyline":return e.paths[0].length>1;case"polygon":{const t=e.rings[0];return n(t.at(0),t.at(-1))?t.length>2:t.length>1}default:return!1}}function be(e,r){let n=null;switch(e.geometry?.type){case"point":case"multipoint":n=new D({angle:0,color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:1}),path:"undefined",size:8,style:"circle",xoffset:0,yoffset:0});break;case"polygon":n=new C({color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:3}),style:"none"});break;case"polyline":n=new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:2});break;default:return null}return new t({geometry:e.geometry,symbol:n,attributes:{...e.attributes}})}async function we(e,t){const r=await N(t).load(),n=x(e)?e.parent:e;return r.tablesAndLayersLookup.get(n)}async function ve(e,t){const r=await we(e,t);if(!r)return new Map;const n=new Map;for(const a of r.layersAndTables)d(n,a.layerId,()=>[]).push(a);return n}function Ie(e){const t=e.objectIdField,r=e.globalIdField??"";return{id:e.layerId,identifierFields:{objectIdField:t,globalIdField:r},addFeatures:[],deleteAttachments:[],addAttachments:[],deleteFeatures:[],updateFeatures:[]}}function Te(e){const{edits:t,serviceInfo:n,view:a,findOriginalFeature:o}=e,i=Se(n.layersAndTables),s=n.layersAndTables.toArray(),{allEditData:l,editDataByLayerIdMap:c,editDataByIdMap:u}=Fe(t,i,o),p=ke(l,je(s,c),c);if(a&&Ve(l,p,a),0===p.length)return t;const d=H(p,{continueOnCircularDependency:!0}).map(e=>u.get(e)).filter(r),f=new Map;for(const r of d)f.set(r.uniqueId,r);const y=[];for(const r of l)f.has(r.uniqueId)||y.push(r);const m=[];let h=null;for(const r of d){const{layer:e}=r;switch(null==h?h=Ie(e):h.id!==e.layerId&&(m.push(h),h=Ie(e)),r.operationType){case"add":case"modify":h.addFeatures.push(r.after);break;case"delete":h.deleteFeatures.push(r.before)}}null!==h&&m.push(h);for(const r of y){const e=r.layer.layerId,t=m.find(t=>t.id===e)??Ie(r.layer);switch(m.includes(t)||m.push(t),r.operationType){case"add":t.addFeatures.push(r.after);break;case"modify":t.updateFeatures.push(r.after);break;case"delete":t.deleteFeatures.push(r.before);break;case"deleteAttachment":t.deleteAttachments.push(r.attachmentId);break;case"addAttachment":t.addAttachments.push(r.attachment)}}for(const r of m)void 0!==r.deleteAttachments&&0===r.deleteAttachments.length&&delete r.deleteAttachments,void 0!==r.addAttachments&&0===r.addAttachments.length&&delete r.addAttachments;return m}function Se(e){const t=new Map;for(const r of e)t.set(r.layerId,r);return t}function je(e,t){const r=new Map;for(const n of e)for(const e of n.relationships??[])if(r.set(Ae(n,e),""),t.has(e.relatedTableId)){const a=t.get(e.relatedTableId);if(a.length>0)for(const t of a[0].layer.relationships??[])if(t.id===e.id){r.set(Ae(n,e),t.keyField);break}}return r}function Fe(e,t,r){const n=new Map,a=[],o=new Map;let s=1;for(const l of e){const e=[],c=t.get(l.id);if(!c)throw new i("featureworkflow",`Failed to prepare applyEdits payload. Layer with id ${l.id} not found.`);for(const t of l.addFeatures??[])e.push({uniqueId:"T"+s++,operationType:"add",layer:c,after:t});for(const t of l.deleteFeatures??[])e.push({uniqueId:"T"+s++,operationType:"delete",before:t,layer:c});for(const t of l.deleteAttachments??[])e.push({uniqueId:"T"+s++,operationType:"deleteAttachment",attachmentId:t,layer:c});for(const t of l.addAttachments??[])e.push({uniqueId:"T"+s++,operationType:"addAttachment",attachment:t,layer:c});for(const t of l.updateFeatures??[])e.push({uniqueId:"T"+s++,operationType:"modify",before:r(t),after:t,layer:c});n.set(c.layerId,e);for(const t of e)a.push(t),o.set(t.uniqueId,t)}return{allEditData:a,editDataByIdMap:o,editDataByLayerIdMap:n}}function ke(e,t,r){const n=[];for(const a of e){const e=a.layer.relationships??[],{uniqueId:o}=a;for(const i of e){const e=i.keyField;if("origin"===i.role){const s=r.get(i.relatedTableId);if(!s||0===s.length)continue;const l=Ae(a.layer,i),c=t.get(l);if(void 0===c||""===c)continue;switch(a.operationType){case"add":for(const t of s)t!==a&&("add"!==t.operationType&&"modify"!==t.operationType||t.after.attributes[c]===a.after.attributes[e]&&n.push([o,t.uniqueId]));break;case"modify":if(a.before.attributes[e]!==a.after.attributes[e])for(const t of s){const r=t.uniqueId;t!==a&&("delete"===t.operationType?t.before.attributes[c]===a.before.attributes[e]?n.push([r,o]):t.before.attributes[c]===a.after.attributes[e]&&n.push([o,r]):"add"===t.operationType?t.after.attributes[c]===a.after.attributes[e]?n.push([o,r]):t.after.attributes[c]===a.before.attributes[e]&&n.push([r,o]):"modify"===t.operationType&&(t.before.attributes[c]!==t.after.attributes[c]?t.after.attributes[c]===a.after.attributes[e]?n.push([o,r]):n.push([r,o]):n.push([o,r])))}break;case"delete":for(const t of s)t!==a&&("delete"!==t.operationType&&"modify"!==t.operationType||t.before.attributes[c]===a.before.attributes[e]&&n.push([t.uniqueId,o]))}}}}return n}function Ae(e,t){return`${e.layerId}:${t.id}`}function Ue(e,t){return!!(t?.map&&"utilityNetworks"in t.map&&t.map.utilityNetworks?.length&&t.map.utilityNetworks.some(t=>!(!t.loaded||!e.url?.startsWith(t.featureServiceUrl)||e.layerId!==t.networkSystemLayers.associationsTableId)))}function Ve(e,t,r){const n=[];for(const o of e)Ue(o.layer,r)&&n.push(o);if(0===n.length)return;let a=[];for(const o of n){const r=o.layer;switch(o.operationType){case"delete":a=[...Le(o.before.attributes[r.fieldsIndex.get("fromglobalid").name],e),...Le(o.before.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of a)t.push([o.uniqueId,e.uniqueId]);break;case"add":a=[...Le(o.after.attributes[r.fieldsIndex.get("fromglobalid").name],e),...Le(o.after.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of a)t.push([e.uniqueId,o.uniqueId])}}}function Le(e,t){const r=[],n=t.filter(({layer:e})=>""!==e.globalIdField&&null!=e.globalIdField);for(const a of n){const t=a.layer.globalIdField;("before"in a&&a.before?.attributes[t]===e||"after"in a&&a.after?.attributes[t]===e)&&r.push(a)}return r}function Me(e,t={}){return S(e)||F(e)?{}:k(e)?{...e.prototype.attributes,...t}:A(e)?{...e.definition?.defaultValues,...t}:{...t}}async function Oe(e,r,n,a,o){const i=new t({sourceLayer:r,attributes:n}),{rotation:s,size:l}=ae(i);let c=await B(i,{useSourceLayer:!0,webStyleCache:a,scale:o}),u=!1;for(const t of[l,s]){if(null==t)continue;null==n[t.field]&&(n[t.field]=await t.getDefaultValue(c,e.view),u=!0)}switch(u&&(c=await B(i,{useSourceLayer:!0,webStyleCache:a,scale:o})),c?.type){case"simple-fill":case"polygon-3d":e.polygonSymbol=c;break;case"simple-line":case"line-3d":e.polylineSymbol=c;break;case"simple-marker":case"picture-marker":case"point-3d":case"cim":e.pointSymbol=c;break;case"mesh-3d":e.meshSymbol=c}xe(e.tooltipOptions,l,s)}function xe(e,t,r){e.visualVariables=null!=t||null!=r?{size:null!=t?{unit:t.displayUnit,axis:t.axis,valueType:t.fieldType}:null,rotation:null!=r?{valueType:r.fieldType,rotationType:r.rotationType??"geographic"}:null}:null}function ze(e,t){return e?.find(e=>e.layer===t)}async function qe(e,t,r,n){switch(t.type){case"3d":return Pe(e,t,r,n);case"2d":return Ee(e,t,r,n)}}async function Pe(e,t,r,n){if(0===e.length)return[];const{updatable:o,graphicsByLayer:i}=await r.defer(async()=>{const{results:a}=await h(J(t,r),n),o=new Map,i=e=>{const t=e.layer,r=o.get(t);if(!r){const e=new Array;return o.set(t,e),e}return r};$(a).forEach(({graphic:e})=>i(e).push(e));const s=e.filter(({capabilities:e,layer:t})=>e.update.enabled&&o.has(t));return 0!==s.length&&r.stopPropagation(),{updatable:s,graphicsByLayer:o}});return h(Promise.allSettled(o.map(async({layer:e})=>{const t=i.get(e),r=Ce(e);if(t.every(e=>L(e,r)))return t;const o=[];for(const n of t){o.push(n.getObjectId());const e=Object.keys(n.attributes);a(r,e)}const s=e.createQuery();return s.returnGeometry=!1,s.objectIds=o,s.outFields=M(e.fieldsIndex,r),e.queryFeatures(s,{signal:n}).then(({features:e})=>e)})),n)}async function Ee(e,t,r,n){if(0===e.length)return[];const{mapPoint:a}=r;if(null==a)return[];let o=null;const i=await r.defer(async()=>{const{results:a}=await h(t.hitTest(r),n);if(0===a.length)return[];const i=new Set;o=$(a),o.forEach(({graphic:e})=>e&&i.add(e.layer));const s=e.filter(e=>i.has(e.layer)&&e.supportsUpdateWorkflow);return s.length>0&&r.stopPropagation(),s});return h(Promise.allSettled(i.map(async({layer:e})=>{const i=e.createQuery();i.returnGeometry=!0,i.outFields=Ce(e);const s="renderer"in e?z({renderer:e.renderer,pointerType:r.pointerType}):0;i.geometry=Q(a,s,t),i.outSpatialReference=t.spatialReference;const{features:l}=await e.queryFeatures(i,{signal:n});return o?.forEach(({graphic:t})=>{t.layer!==e||l.some(e=>e.getObjectId()===t.getObjectId())||l.push(t)}),l})),n)}function Ce(e){return M(e.fieldsIndex,[e.objectIdField,O({displayField:"displayField"in e?e.displayField:null,fields:e.fields})])}async function Re(e,t,n,a){const o=t.createQuery();o.objectIds=e.map(e=>e.getObjectId()).filter(r),o.outFields=["*"],o.returnM=t.capabilities.data.supportsM,o.returnZ=t.capabilities.data.supportsZ,"scene"===t.type&&null!=t.infoFor3D||(o.outSpatialReference=n);const i=await t.queryFeatures(o,{signal:a});return m(a),i.features}function De(e){const t=new Map;for(const r of e){const e=r.sourceLayer,n=x(e)?e.parent:e;d(t,n,()=>[]).push(r)}return t}async function Ge(e){const{graphic:t,sketchViewModel:r,sourceLayer:n,visualVariables:a}=e;await Be(e);const o={multipleSelectionEnabled:!1};return"point"===n.geometryType&&(o.enableRotation=null!=a.rotation,o.enableScaling=null!=a.size),r.update(t,o)}async function Be(e){const{graphic:t,sketchViewModel:r,sourceLayer:n,visualVariables:a,webStyleCache:o}=e;let i=!1;const{rotation:s,size:l}=a;for(const c of[s,l]){if(null==c)continue;const e=t.getAttribute(c.field);if(null!=e)c.setInitialValue(e);else{const e=await c.getDefaultValue(t.symbol,r.view);c.setInitialValue(e),t.setAttribute(c.field,e),i=!0}}if(i){const e="2d"===r.view?.type?r.view.scale:null;await pe(t,o,e)}xe(r.tooltipOptions,l,s),r.layer.elevationInfo=n.elevationInfo}function Ne(e){return null==e||"rotate-start"!==e.type&&"rotate"!==e.type&&"rotate-stop"!==e.type?null:e}function Ze(e){return null==e||"scale-start"!==e.type&&"scale"!==e.type&&"scale-stop"!==e.type?null:e}function We(e,t,r,n){if(null==t.geometry||"point"!==t.geometry?.type)return!1;const a=t.attributes;let o=!1;const i=n.rotation,s=Ne(r.toolEventInfo);if(null!=i&&null!=s){const{field:r,getValue:n}=i;if("rotate-stop"===s.type)i.isUpdatingInteractively=!1,i.setInitialValue(t.getAttribute(r));else{i.isUpdatingInteractively=!0;const l=n(s.angle,e);l!==a[r]&&t.setAttribute(r,l),o=!0}}const l=n.size,c=Ze(r.toolEventInfo);if(null!=l&&null!=c){const{field:r,getValue:n}=l;if("scale-stop"===c.type)l.isUpdatingInteractively=!1,l.setInitialValue(t.getAttribute(r));else{l.isUpdatingInteractively=!0;const i=n(c.xScale,e);i!==a[r]&&t.setAttribute(r,i),o=!0}}return o}async function Qe({feature:e,featureClone:t,visualVariableAttributes:r,sketchViewModel:n,view:a,onUpdate:o,webStyleCache:i,addUpdatingPromise:u,addHandle:p}){await pe(t,i,"2d"===a.type?a.scale:null);let d=null;if("2d"===n?.view?.type){const e=f(e=>pe(t,i,e));d=g(()=>n?.view?.scale,t=>e(t))}const y=t.sourceLayer,m=rt(a,y);await Ge({graphic:t,sketchViewModel:n,sourceLayer:y,visualVariables:r,webStyleCache:i});let h=null;m.then(e=>h=e).catch(()=>{});const b=r.size,v=r.rotation,I=g(()=>e.attributes,async e=>{let r=!1;for(const n in e){const a=e[n];a!==t.getAttribute(n)&&(t.setAttribute(n,a),null==b||b.isUpdatingInteractively||b.field!==n||b.setInitialValue(a),null==v||v.isUpdatingInteractively||v.field!==n||v.setInitialValue(a),(null==h||h.requiredFields.includes(n))&&(r=!0))}r&&await pe(t,i,"2d"===a.type?a.scale:null)}),T=n.on("update",async e=>{const t=e.graphics[0],s={graphic:t,sketchViewModel:n,sourceLayer:y,visualVariables:r,webStyleCache:i};if("complete"===e.state){if(null===a.activeTool)return Ge(s);const e=new AbortController,t=c(e);return p(t),u(w(()=>null===a.activeTool,e.signal).then(async()=>{if(!e.signal.aborted)return e.abort(),Ge(s)}))}We(a,t,e,r)&&await pe(t,i,"2d"===a.type?a.scale:null),o(at(t),e)}),S=n.on(["undo","redo"],async e=>{o(at(e.graphics[0]),e)});return s([S,T,l(()=>n.cancel()),I,d])}async function $e(e,t,r){const n=e.view;e.layer.add(r);const a=t.sourceLayer,i=t.layer,c=t.getAttribute(i.objectIdField);let u=null;function p(e){u?.abort(),u=o(async t=>{const r=await rt(n,a);m(t),r.setVisibility?.(c,e)})}return await He(n,r),p(!1),s([Je(n,r,e=>p(!e)),l(async()=>{p(!0);try{if(!n.destroyed){const e=await rt(n,a).catch(()=>{});e&&!e.destroyed&&await w(()=>!e.updating)}}finally{e.layer.remove(r)}})])}function Je(e,t,r){if("3d"===e.type){const n=new Z({graphic:t});return s([e.trackGraphicState(n),g(()=>n.displaying,r)])}return g(()=>t.visible,r)}async function He(e,t){if("3d"===e.type){const r=new Z({graphic:t}),n=e.trackGraphicState(r);await w(()=>r.displaying||r.error),n.remove()}else await w(()=>t.visible)}const Ke={icon:v(24),text:v(12),line:v(1),viewScaleSizeFactor:100};function Xe(e,t,r){let n=!1;return e.filter(e=>!!n||(n=e===t,n)).map(e=>r[e]())}function Ye(e,t){e.viewModel.syncFeatureTemplates();const r=e.creationInfo;if("awaiting-feature-creation-info"===t[0].id&&r){const n=r.layer,a=e.viewModel.getTemplatesForLayer(n);1===a.length&&"scene"!==n.type&&(r.template=a[0],t.shift())}return t}function _e(e){return"unknown"===e?null:e}function et(e){e.filesEnabled=!0,e.mode="view",e.capabilities={editing:!0,operations:{add:!0,update:!0,delete:!0}}}const tt=e=>/-stop/.test(e)||/vertex-/.test(e),rt=(e,t)=>{const r="subtype-sublayer"===t.type?t.parent:t;return e.whenLayerView(r)};function nt(e){return"createInteractiveEditSession"in e}function at(e){const t=e.geometry;if("mesh"===t?.type){const r=e.cloneShallow();return r.attributes=u(e.attributes),r.geometry=t.cloneShallow(),r.geometry.transform=t.transform?.clone()??null,r}return e.clone()}function ot(e){const t=e.cursor;return e.cursor="progress",l(()=>e.cursor=t)}async function it(e,t){const{template:r}=e;if(null==r)return null;if(j(r))return r.load();if(T(r)){const e=(await import("../../editing/sharedTemplates/SharedTemplate.js")).default,n=U(t,{makeSharedTemplateFromJSON:t=>e.fromJSON(t)}),a=await n.getTemplates({templateIds:[r.templateId],featureService:r.featureService});if(0===a.length)throw new i("editor:failed-to-load-template","Unable to load the provided template");return a[0].load()}return r}function st(e){for(const t of e){const{destinationGraphic:e,destinationField:r,sourceGraphic:n,sourceField:a}=t;e.setAttribute(r,n.getAttribute(a))}}function lt(e){const t=e.templateExecutorInfo?.completionResults;return t?.length?(t.forEach(e=>st(e.relationships)),t.flatMap(e=>e.edits)):null}function ct(e){if(null==e)return[];if(ee(e))return e.data.layers;const t=re(e)?e.activeWorkflow:e,r=t?.layer;return r?[r]:[]}function ut(){return new i("editing:multiple-layers-not-supported","UpdateFeaturesWorkflow does not support updating features from multiple layers.")}export{Ve as appendAllUtilityNetworkAssociationRelationships,Ye as avoidFeatureTemplateSelectionWithOnlyOneItem,nt as canCreateInteractiveEditSession,at as cloneGraphicExceptMesh,Se as createLayerIdMap,je as createRelationshipKeyMap,de as createToolFromGeometryType,Xe as createWorkflowSteps,qe as fetchCandidates,Re as fetchFullFeatures,ke as findAllDependencies,Le as findChangesByGlobalId,ze as findLayerInfo,Ae as generateHashForRelationship,Me as getCreationAttributes,it as getFullTemplateForCreationInfo,ct as getLayersFromWorkflow,oe as getRotationVariableAttribute,lt as getServiceEditsFromWorkflowData,we as getServiceInfoForLayer,ve as getServiceLayersById,le as getSizeVariableAttribute,ae as getVisualVariableAttributes,ne as getVisualVariablesForLayer,De as groupFeaturesByLayer,Y as isBatchAttributeFormViewModel,_ as isCreateFeaturesWorkflow,tt as isTerminalUpdateEventType,ee as isUpdateFeaturesWorkflow,te as isUpdateRecordWorkflow,re as isUpdateWorkflow,Ue as isUtilityNetworkAssociationsTable,ut as makeMultipleSourceLayersError,Te as orderEditsByRelationshipDependencies,et as prepareAttachmentsForCreateFeaturesWorkflow,st as setRelationshipFields,Qe as setUpGeometryUpdate,ye as setUpSketchCreateWatchers,Be as setVisualVariablesAndElevationInfoForUpdate,ot as showProgressCursor,Ke as sizeDefaults,_e as sizeVariableUnitToLengthUnit,fe as startCreatingNewFeature,Ge as startUpdatingFeatureGeometry,$e as swapForEditingSession,pe as updateGraphicSymbolWhenRequired,We as visualVariableInteractiveUpdate,rt as whenEditorLayerView,He as whenGraphicDisplayed};
5
+ import e from"../../Color.js";import t from"../../Graphic.js";import{isSome as r,equals as n,addMany as a}from"../../core/arrayUtils.js";import{createTask as o}from"../../core/asyncUtils.js";import"../../core/has.js";import i from"../../core/Error.js";import{handlesGroup as s,makeHandle as l,abortHandle as c}from"../../core/handleUtils.js";import{clone as u}from"../../core/lang.js";import p from"../../core/Logger.js";import{getOrCreateMapValue as d}from"../../core/MapUtils.js";import{debounce as f,isPromiseLike as y,throwIfAborted as m,whenOrAbort as h}from"../../core/promiseUtils.js";import{watch as g,on as b,whenOnce as w}from"../../core/reactiveUtils.js";import{px2pt as v}from"../../core/screenUtils.js";import{diff as I}from"../../core/accessorSupport/diffUtils.js";import{isSharedTemplateOrMetadata as T,isSharedGroupTemplate as S,isSharedTemplate as j,isSharedPresetTemplate as F,isStandardFeatureTemplate as k,isSharedFeatureTemplate as A}from"../../editing/templateUtils.js";import{getSharedTemplateProvider as U}from"../../editing/sharedTemplates/SharedTemplateProvider.js";import V from"../../layers/GraphicsLayer.js";import{featureHasFields as L,fixFields as M,getDisplayFieldName as O}from"../../layers/support/fieldUtils.js";import{isSubtypeSublayer as x}from"../../layers/support/layerUtils.js";import{calculateTolerance as z}from"../../renderers/support/clickToleranceUtils.js";import{meterIn as q}from"../../renderers/support/lengthUtils.js";import{isRenderer as P}from"../../renderers/support/typeUtils.js";import{getTransformationType as E}from"../../renderers/visualVariables/support/sizeVariableUtils.js";import C from"../../symbols/SimpleFillSymbol.js";import R from"../../symbols/SimpleLineSymbol.js";import D from"../../symbols/SimpleMarkerSymbol.js";import{to3D as G}from"../../symbols/support/symbolConversion.js";import{getDisplayedSymbol as B}from"../../symbols/support/symbolUtils.js";import{getServices as N}from"../../undoredo/support/Services.js";import{GraphicState as Z}from"../../views/3d/layers/graphics/GraphicState.js";import{defaultDrawingMode as W}from"../../views/draw/DrawingMode.js";import{createQueryGeometry as Q}from"../../views/support/drapedUtils.js";import{filterGraphicHits as $,hitTestSelectSimilarDistance as J}from"../../views/support/hitTestSelectUtils.js";import{dependencySort as H}from"./support/dependencySort.js";import{isDrawGraphicTool as K}from"../Sketch/support/sketchUtils.js";const X=()=>p.getLogger("esri.widgets.Editor.workflowUtils");function Y(e){return!!e&&"features"in e}function _(e){return null!=e&&"create-features"===e.type}function ee(e){return null!=e&&"update-features"===e.type}function te(e){return null!=e&&/update-/.test(e.type)&&"fullFeature"in e}function re(e){return null!=e&&"update"===e.type}function ne(e){const t=e&&"renderer"in e?e.renderer:null;if(!ue(t))return{rotation:null,size:null};const r=t.getVisualVariablesForType("rotation").filter(e=>(!e.axis||"heading"===e.axis)&&e.field&&!e.valueExpression),n=t.getVisualVariablesForType("size").filter(e=>e.field&&!e.useSymbolValue&&!e.valueExpression&&"real-world-size"===E(e));return{rotation:1===r.length?r[0]:null,size:1===n.length?n[0]:null}}function ae(e){const t=e.sourceLayer;if(!(t&&"renderer"in t&&ue(t.renderer)))return{rotation:null,size:null};const{rotation:r,size:n}=ne(t);let a=null,o=null;if(r){const e=t.fields?.filter(e=>e.name===r.field),n=1===e?.length?e[0]:null;a=oe(r,n)}if(n){const e=t.fields?.filter(e=>e.name===n.field),r=1===e?.length?e[0]:null;o=le(n,r)}return{rotation:a,size:o}}function oe(e,t){const r="heading"===(e.axis||"heading")&&"arithmetic"===e.rotationType?-1:1,n=t?.type??"double",a={initial:0,current:0};return{field:e.field,fieldType:n,getDefaultValue:()=>Promise.resolve(0),getValue:e=>(a.current=a.initial-r*e,ce((a.current+360)%360,n)),setInitialValue:e=>{a.initial=e,a.current=0},isUpdatingInteractively:!1,rotationType:e.rotationType??"geographic"}}function ie(e,t){switch(t){case"width":return e[0];case"depth":return e[1];case"height":return e[2];default:return e[2]||e[1]||e[0]}}async function se(e,t,r){if(null==t)return 0;const{symbol:n}=G(t);if(null==n||"web-style"===n.type||"cim"===n.type)return 0;const a=n.symbolLayers.at(0);if(!a)return 0;switch(a.type){case"icon":{const{computeIconLayerResourceSize:e}=await import("../../symbols/support/symbolLayerUtils.js");return Math.min(Ke.icon,(await e(a,Ke.icon))[0])||Ke.icon}case"text":return Ke.text;case"line":return Ke.line;case"object":{const{computeObjectLayerResourceSize:t}=await import("../../symbols/support/symbolLayerUtils.js");return ie(await t(a,e.scale/Ke.viewScaleSizeFactor),r)}case"path":case"extrude":return e.scale/Ke.viewScaleSizeFactor;default:return 0}}function le(e,t){const r=e.axis,n=t?.type??"double",a={initial:0,current:0},o=q[e.valueUnit]??1;let i;return i="area"===e.valueRepresentation?e=>(e*o/2)**2*Math.PI:"radius"===e.valueRepresentation||"distance"===e.valueRepresentation?e=>e*o/2:e=>e*o,{field:e.field,fieldType:n,getDefaultValue:async(e,t)=>ce(i(await se(t,e,r)),n),getValue:(e,t)=>(a.initial||(a.initial=t.pixelSizeAt(t.center)),a.current=a.initial*e,ce(a.current,n)),setInitialValue:e=>{a.initial=e,a.current=0},isUpdatingInteractively:!1,displayUnit:_e(e.valueUnit),axis:e.axis}}function ce(e,t){switch(t){case"small-integer":case"integer":case"long":return Math.round(e);case"double":case"single":return e;default:return 0}}function ue(e){if(!P(e))return!1;switch(e?.type){case"class-breaks":case"simple":case"unique-value":case"dot-density":case"dictionary":case"pie-chart":return!0;default:return!1}}async function pe(e,t,r){const n=await B(e,{useSourceLayer:!0,ignoreGraphicSymbol:!0,webStyleCache:t,scale:r});null!=I(e.symbol,n)&&(e.symbol=n)}function de(e,t){if(!e||!t)throw new Error("no geometry type");if("multipatch"===e)return{tool:"mesh",createOptions:{mode:"hybrid"}};const r=new Map;r.set("circle",{mode:"freehand"}),r.set("rectangle",{mode:"freehand"});const n={mode:W,optionsPerTool:r};if(T(t)){const a=t.defaultTool,o=S(t)?t.definition?.inputGeometryType??e:e;switch(a){case"freehand":case"stream-line":return{tool:"polyline"===o?"freehandPolyline":"freehandPolygon",createOptions:n};case"autocomplete-freehand-polygons":case"stream-polygon":return{tool:"freehandPolygon",createOptions:n};case"autocomplete-polygons":case"difference-polygon":case"create-structures":case"polygon":case"trace":return{tool:"polygon"===o?"polygon":"polyline",createOptions:n};case"circle":return r.get("circle").preserveAspectRatio=!0,{tool:"circle",createOptions:n};case"ellipse":return r.get("circle").preserveAspectRatio=!1,{tool:"circle",createOptions:n};case"create-points-along-line":case"multipoint":return{tool:"multipoint",createOptions:n};case"line":case"radial-line":case"right-angle-line":case"split":case"two-point-line":return{tool:"polyline",createOptions:n};case"rectangle":case"regular-polygon":case"right-angle-polygon":return{tool:"rectangle",createOptions:n};case"elevation-point-from-contour":case"elevation-point-from-dem":case"parcel-seed":case"point":case"point-and-rotation":case"point-at-end-of-line":return{tool:"point",createOptions:n}}}else{const a=t.drawingTool;if("circle"===a||"ellipse"===a)return r.get("circle").preserveAspectRatio="circle"===a,{tool:"circle",createOptions:n};if("rectangle"===a)return{tool:"rectangle",createOptions:n};if("freehand"===a)return{tool:"polygon"===e?"freehandPolygon":"freehandPolyline",createOptions:n}}return{tool:e,createOptions:n}}async function fe(e,t,r){const{creationInfo:n,fullTemplate:a}=t;if(!n)throw new i("featureworkflow","No creation info provided.");const o=n.layer,s=Me(a,n.attributeOverrides),{view:l}=e,c="2d"===l?.type;S(a)||F(a)||await Oe(e,o,s,r,c?l.scale:null);const{capabilities:u}=o;e.layer.elevationInfo=o.elevationInfo;const p=de(o.geometryType,a);e.defaultCreateOptions={graphicProperties:{attributes:s,sourceLayer:o},mode:p.createOptions.mode,optionsPerTool:p.createOptions.optionsPerTool,preserveAspectRatio:p.createOptions.preserveAspectRatio,hasZ:u.data.supportsZ,defaultZ:(c?u.editing.zDefault:null)??e.defaultCreateOptions.defaultZ},null==n.geometryToPlace?await e.create(p.tool):await e.place(n.geometryToPlace,{graphicProperties:{attributes:s,sourceLayer:o}})}async function ye(e){return s([await me(e),await he(e)])}async function me({creationAttributes:e,data:t,sketchViewModel:r,view:n,webStyleCache:a}){const{creationInfo:o}=t,{fullTemplate:i}=t;if(!o||"2d"!==n?.type||S(i)||F(i))return null;const s=f(t=>Oe(r,o.layer,e,a,t));return g(()=>n.scale,e=>s(e))}async function he({data:t,sketchViewModel:r,view:n}){const{templateExecutorInfo:a}=t;if(!a)return null;const o=r.activeComponent;if(!n||!K(o))return X().error(new i("featureworkflow","Failed to set up template feedback.")),null;const c=new V({effect:"saturate(0.6) opacity(0.8)",listMode:"hide",title:"Shared Template Feedback Graphics"});n.map?.add(c);const{executor:u,serviceLayersById:p}=a,d=n.theme?.accentColor??new e([255,165,0,1]);return s([b(()=>o,["cursor-update","vertex-add"],()=>{c.removeAll();const e=o.graphic?.geometry;if(!e||!ge(e))return;const t=u(e,"digitizing");if(!y(t))for(const r of t.edits){const e=p.get(r.id);if(e&&r.addFeatures&&0!==r.addFeatures.length)for(const t of e)if(!t.isTable)for(const e of r.addFeatures){const t=be(e,d);t&&c.add(t)}}}),l(()=>{n.map.remove(c),c.destroy()})])}function ge(e){switch(e.type){case"point":case"multipoint":return!0;case"polyline":return e.paths[0].length>1;case"polygon":{const t=e.rings[0];return n(t.at(0),t.at(-1))?t.length>2:t.length>1}default:return!1}}function be(e,r){let n=null;switch(e.geometry?.type){case"point":case"multipoint":n=new D({angle:0,color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:1}),path:"undefined",size:8,style:"circle",xoffset:0,yoffset:0});break;case"polygon":n=new C({color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:3}),style:"none"});break;case"polyline":n=new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:2});break;default:return null}return new t({geometry:e.geometry,symbol:n,attributes:{...e.attributes}})}async function we(e,t){const r=await N(t).load(),n=x(e)?e.parent:e;return r.tablesAndLayersLookup.get(n)}async function ve(e,t){const r=await we(e,t);if(!r)return new Map;const n=new Map;for(const a of r.layersAndTables)d(n,a.layerId,()=>[]).push(a);return n}function Ie(e){const t=e.objectIdField,r=e.globalIdField??"";return{id:e.layerId,identifierFields:{objectIdField:t,globalIdField:r},addFeatures:[],deleteAttachments:[],addAttachments:[],deleteFeatures:[],updateFeatures:[]}}function Te(e){const{edits:t,serviceInfo:n,view:a,findOriginalFeature:o}=e,i=Se(n.layersAndTables),s=n.layersAndTables.toArray(),{allEditData:l,editDataByLayerIdMap:c,editDataByIdMap:u}=Fe(t,i,o),p=ke(l,je(s,c),c);if(a&&Ve(l,p,a),0===p.length)return t;const d=H(p,{continueOnCircularDependency:!0}).map(e=>u.get(e)).filter(r),f=new Map;for(const r of d)f.set(r.uniqueId,r);const y=[];for(const r of l)f.has(r.uniqueId)||y.push(r);const m=[];let h=null;for(const r of d){const{layer:e}=r;switch(null==h?h=Ie(e):h.id!==e.layerId&&(m.push(h),h=Ie(e)),r.operationType){case"add":case"modify":h.addFeatures.push(r.after);break;case"delete":h.deleteFeatures.push(r.before)}}null!==h&&m.push(h);for(const r of y){const e=r.layer.layerId,t=m.find(t=>t.id===e)??Ie(r.layer);switch(m.includes(t)||m.push(t),r.operationType){case"add":t.addFeatures.push(r.after);break;case"modify":t.updateFeatures.push(r.after);break;case"delete":t.deleteFeatures.push(r.before);break;case"deleteAttachment":t.deleteAttachments.push(r.attachmentId);break;case"addAttachment":t.addAttachments.push(r.attachment)}}for(const r of m)void 0!==r.deleteAttachments&&0===r.deleteAttachments.length&&delete r.deleteAttachments,void 0!==r.addAttachments&&0===r.addAttachments.length&&delete r.addAttachments;return m}function Se(e){const t=new Map;for(const r of e)t.set(r.layerId,r);return t}function je(e,t){const r=new Map;for(const n of e)for(const e of n.relationships??[])if(r.set(Ae(n,e),""),t.has(e.relatedTableId)){const a=t.get(e.relatedTableId);if(a.length>0)for(const t of a[0].layer.relationships??[])if(t.id===e.id){r.set(Ae(n,e),t.keyField);break}}return r}function Fe(e,t,r){const n=new Map,a=[],o=new Map;let s=1;for(const l of e){const e=[],c=t.get(l.id);if(!c)throw new i("featureworkflow",`Failed to prepare applyEdits payload. Layer with id ${l.id} not found.`);for(const t of l.addFeatures??[])e.push({uniqueId:"T"+s++,operationType:"add",layer:c,after:t});for(const t of l.deleteFeatures??[])e.push({uniqueId:"T"+s++,operationType:"delete",before:t,layer:c});for(const t of l.deleteAttachments??[])e.push({uniqueId:"T"+s++,operationType:"deleteAttachment",attachmentId:t,layer:c});for(const t of l.addAttachments??[])e.push({uniqueId:"T"+s++,operationType:"addAttachment",attachment:t,layer:c});for(const t of l.updateFeatures??[])e.push({uniqueId:"T"+s++,operationType:"modify",before:r(t),after:t,layer:c});n.set(c.layerId,e);for(const t of e)a.push(t),o.set(t.uniqueId,t)}return{allEditData:a,editDataByIdMap:o,editDataByLayerIdMap:n}}function ke(e,t,r){const n=[];for(const a of e){const e=a.layer.relationships??[],{uniqueId:o}=a;for(const i of e){const e=i.keyField;if("origin"===i.role){const s=r.get(i.relatedTableId);if(!s||0===s.length)continue;const l=Ae(a.layer,i),c=t.get(l);if(void 0===c||""===c)continue;switch(a.operationType){case"add":for(const t of s)t!==a&&("add"!==t.operationType&&"modify"!==t.operationType||t.after.attributes[c]===a.after.attributes[e]&&n.push([o,t.uniqueId]));break;case"modify":if(a.before.attributes[e]!==a.after.attributes[e])for(const t of s){const r=t.uniqueId;t!==a&&("delete"===t.operationType?t.before.attributes[c]===a.before.attributes[e]?n.push([r,o]):t.before.attributes[c]===a.after.attributes[e]&&n.push([o,r]):"add"===t.operationType?t.after.attributes[c]===a.after.attributes[e]?n.push([o,r]):t.after.attributes[c]===a.before.attributes[e]&&n.push([r,o]):"modify"===t.operationType&&(t.before.attributes[c]!==t.after.attributes[c]?t.after.attributes[c]===a.after.attributes[e]?n.push([o,r]):n.push([r,o]):n.push([o,r])))}break;case"delete":for(const t of s)t!==a&&("delete"!==t.operationType&&"modify"!==t.operationType||t.before.attributes[c]===a.before.attributes[e]&&n.push([t.uniqueId,o]))}}}}return n}function Ae(e,t){return`${e.layerId}:${t.id}`}function Ue(e,t){return!!(t?.map&&"utilityNetworks"in t.map&&t.map.utilityNetworks?.length&&t.map.utilityNetworks.some(t=>!(!t.loaded||!e.url?.startsWith(t.featureServiceUrl)||e.layerId!==t.networkSystemLayers.associationsTableId)))}function Ve(e,t,r){const n=[];for(const o of e)Ue(o.layer,r)&&n.push(o);if(0===n.length)return;let a=[];for(const o of n){const r=o.layer;switch(o.operationType){case"delete":a=[...Le(o.before.attributes[r.fieldsIndex.get("fromglobalid").name],e),...Le(o.before.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of a)t.push([o.uniqueId,e.uniqueId]);break;case"add":a=[...Le(o.after.attributes[r.fieldsIndex.get("fromglobalid").name],e),...Le(o.after.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of a)t.push([e.uniqueId,o.uniqueId])}}}function Le(e,t){const r=[],n=t.filter(({layer:e})=>""!==e.globalIdField&&null!=e.globalIdField);for(const a of n){const t=a.layer.globalIdField;("before"in a&&a.before?.attributes[t]===e||"after"in a&&a.after?.attributes[t]===e)&&r.push(a)}return r}function Me(e,t={}){return S(e)||F(e)?{}:k(e)?{...e.prototype.attributes,...t}:A(e)?{...e.definition?.defaultValues,...t}:{...t}}async function Oe(e,r,n,a,o){const i=new t({sourceLayer:r,attributes:n}),{rotation:s,size:l}=ae(i);let c=await B(i,{useSourceLayer:!0,webStyleCache:a,scale:o}),u=!1;for(const t of[l,s]){if(null==t)continue;null==n[t.field]&&(n[t.field]=await t.getDefaultValue(c,e.view),u=!0)}switch(u&&(c=await B(i,{useSourceLayer:!0,webStyleCache:a,scale:o})),c?.type){case"simple-fill":case"polygon-3d":e.polygonSymbol=c;break;case"simple-line":case"line-3d":e.polylineSymbol=c;break;case"simple-marker":case"picture-marker":case"point-3d":case"cim":e.pointSymbol=c;break;case"mesh-3d":e.meshSymbol=c}xe(e.tooltipOptions,l,s)}function xe(e,t,r){e.visualVariables=null!=t||null!=r?{size:null!=t?{unit:t.displayUnit,axis:t.axis,valueType:t.fieldType}:null,rotation:null!=r?{valueType:r.fieldType,rotationType:r.rotationType??"geographic"}:null}:null}function ze(e,t){return e?.find(e=>e.layer===t)}async function qe(e,t,r,n){switch(t.type){case"3d":return Pe(e,t,r,n);case"2d":return Ee(e,t,r,n)}}async function Pe(e,t,r,n){if(0===e.length)return[];const{updatable:o,graphicsByLayer:i}=await r.defer(async()=>{const{results:a}=await h(J(t,r),n),o=new Map,i=e=>{const t=e.layer,r=o.get(t);if(!r){const e=new Array;return o.set(t,e),e}return r};$(a).forEach(({graphic:e})=>i(e).push(e));const s=e.filter(({capabilities:e,layer:t})=>e.update.enabled&&o.has(t));return 0!==s.length&&r.stopPropagation(),{updatable:s,graphicsByLayer:o}});return h(Promise.allSettled(o.map(async({layer:e})=>{const t=i.get(e),r=Ce(e);if(t.every(e=>L(e,r)))return t;const o=[];for(const n of t){o.push(n.getObjectId());const e=Object.keys(n.attributes);a(r,e)}const s=e.createQuery();return s.returnGeometry=!1,s.objectIds=o,s.outFields=M(e.fieldsIndex,r),e.queryFeatures(s,{signal:n}).then(({features:e})=>e)})),n)}async function Ee(e,t,r,n){if(0===e.length)return[];const{mapPoint:a}=r;if(null==a)return[];let o=null;const i=await r.defer(async()=>{const{results:a}=await h(t.hitTest(r),n);if(0===a.length)return[];const i=new Set;o=$(a),o.forEach(({graphic:e})=>e&&i.add(e.layer));const s=e.filter(e=>i.has(e.layer)&&e.supportsUpdateWorkflow);return s.length>0&&r.stopPropagation(),s});return h(Promise.allSettled(i.map(async({layer:e})=>{const i=e.createQuery();i.returnGeometry=!0,i.outFields=Ce(e);const s="renderer"in e?z({renderer:e.renderer,pointerType:r.pointerType}):0;i.geometry=Q(a,s,t),i.outSpatialReference=t.spatialReference;const{features:l}=await e.queryFeatures(i,{signal:n});return o?.forEach(({graphic:t})=>{t.layer!==e||l.some(e=>e.getObjectId()===t.getObjectId())||l.push(t)}),l})),n)}function Ce(e){return M(e.fieldsIndex,[e.objectIdField,O({displayField:"displayField"in e?e.displayField:null,fields:e.fields})])}async function Re(e,t,n,a){const o=t.createQuery();o.objectIds=e.map(e=>e.getObjectId()).filter(r),o.outFields=["*"],o.returnM=t.capabilities.data.supportsM,o.returnZ=t.capabilities.data.supportsZ,"scene"===t.type&&null!=t.infoFor3D||(o.outSpatialReference=n);const i=await t.queryFeatures(o,{signal:a});return m(a),i.features}function De(e){const t=new Map;for(const r of e){const e=r.sourceLayer,n=x(e)?e.parent:e;d(t,n,()=>[]).push(r)}return t}async function Ge(e){const{graphic:t,sketchViewModel:r,sourceLayer:n,visualVariables:a}=e;await Be(e);const o={multipleSelectionEnabled:!1};return"point"===n.geometryType&&(o.enableRotation=null!=a.rotation,o.enableScaling=null!=a.size),r.update(t,o)}async function Be(e){const{graphic:t,sketchViewModel:r,sourceLayer:n,visualVariables:a,webStyleCache:o}=e;let i=!1;const{rotation:s,size:l}=a;for(const c of[s,l]){if(null==c)continue;const e=t.getAttribute(c.field);if(null!=e)c.setInitialValue(e);else{const e=await c.getDefaultValue(t.symbol,r.view);c.setInitialValue(e),t.setAttribute(c.field,e),i=!0}}if(i){const e="2d"===r.view?.type?r.view.scale:null;await pe(t,o,e)}xe(r.tooltipOptions,l,s),r.layer.elevationInfo=n.elevationInfo}function Ne(e){return null==e||"rotate-start"!==e.type&&"rotate"!==e.type&&"rotate-stop"!==e.type?null:e}function Ze(e){return null==e||"scale-start"!==e.type&&"scale"!==e.type&&"scale-stop"!==e.type?null:e}function We(e,t,r,n){if(null==t.geometry||"point"!==t.geometry?.type)return!1;const a=t.attributes;let o=!1;const i=n.rotation,s=Ne(r.toolEventInfo);if(null!=i&&null!=s){const{field:r,getValue:n}=i;if("rotate-stop"===s.type)i.isUpdatingInteractively=!1,i.setInitialValue(t.getAttribute(r));else{i.isUpdatingInteractively=!0;const l=n(s.angle,e);l!==a[r]&&t.setAttribute(r,l),o=!0}}const l=n.size,c=Ze(r.toolEventInfo);if(null!=l&&null!=c){const{field:r,getValue:n}=l;if("scale-stop"===c.type)l.isUpdatingInteractively=!1,l.setInitialValue(t.getAttribute(r));else{l.isUpdatingInteractively=!0;const i=n(c.xScale,e);i!==a[r]&&t.setAttribute(r,i),o=!0}}return o}async function Qe({feature:e,featureClone:t,visualVariableAttributes:r,sketchViewModel:n,view:a,onUpdate:o,webStyleCache:i,addUpdatingPromise:u,addHandle:p}){await pe(t,i,"2d"===a.type?a.scale:null);let d=null;if("2d"===n?.view?.type){const e=f(e=>pe(t,i,e));d=g(()=>n?.view?.scale,t=>e(t))}const y=t.sourceLayer,m=rt(a,y);await Ge({graphic:t,sketchViewModel:n,sourceLayer:y,visualVariables:r,webStyleCache:i});let h=null;m.then(e=>h=e).catch(()=>{});const b=r.size,v=r.rotation,I=g(()=>e.attributes,async e=>{let r=!1;for(const n in e){const a=e[n];a!==t.getAttribute(n)&&(t.setAttribute(n,a),null==b||b.isUpdatingInteractively||b.field!==n||b.setInitialValue(a),null==v||v.isUpdatingInteractively||v.field!==n||v.setInitialValue(a),(null==h||h.requiredFields.includes(n))&&(r=!0))}r&&await pe(t,i,"2d"===a.type?a.scale:null)}),T=n.on("update",async e=>{const t=e.graphics[0],s={graphic:t,sketchViewModel:n,sourceLayer:y,visualVariables:r,webStyleCache:i};if("complete"===e.state){if(null===a.activeTool)return Ge(s);const e=new AbortController,t=c(e);return p(t),u(w(()=>null===a.activeTool,e.signal).then(async()=>{if(!e.signal.aborted)return e.abort(),Ge(s)}))}We(a,t,e,r)&&await pe(t,i,"2d"===a.type?a.scale:null),o(at(t),e)}),S=n.on(["undo","redo"],async e=>{o(at(e.graphics[0]),e)});return s([S,T,l(()=>n.cancel()),I,d])}async function $e(e,t,r){const n=e.view;e.layer.add(r);const a=t.sourceLayer,i=t.layer,c=t.getAttribute(i.objectIdField);let u=null;function p(e){u?.abort(),u=o(async t=>{const r=await rt(n,a);m(t),r.setVisibility?.(c,e)})}return await He(n,r),p(!1),s([Je(n,r,e=>p(!e)),l(async()=>{p(!0);try{if(!n.destroyed){const e=await rt(n,a).catch(()=>{});e&&!e.destroyed&&await w(()=>!e.updating)}}finally{e.layer.remove(r)}})])}function Je(e,t,r){if("3d"===e.type){const n=new Z({graphic:t});return s([e.trackGraphicState(n),g(()=>n.displaying,r)])}return g(()=>t.visible,r)}async function He(e,t){if("3d"===e.type){const r=new Z({graphic:t}),n=e.trackGraphicState(r);await w(()=>r.displaying||r.error),n.remove()}else await w(()=>t.visible)}const Ke={icon:v(24),text:v(12),line:v(1),viewScaleSizeFactor:100};function Xe(e,t,r){let n=!1;return e.filter(e=>!!n||(n=e===t,n)).map(e=>r[e]())}function Ye(e,t){e.viewModel.syncFeatureTemplates();const r=e.creationInfo;if("awaiting-feature-creation-info"===t[0].id&&r){const n=r.layer,a=e.viewModel.getTemplatesForLayer(n);1===a.length&&"scene"!==n.type&&(r.template=a[0],t.shift())}return t}function _e(e){return"unknown"===e?null:e}function et(e){e.filesEnabled=!0,e.mode="view",e.capabilities={editing:!0,operations:{add:!0,update:!0,delete:!0}}}const tt=e=>/-stop/.test(e)||/vertex-/.test(e),rt=(e,t)=>{const r="subtype-sublayer"===t.type?t.parent:t;return e.whenLayerView(r)};function nt(e){return"createInteractiveEditSession"in e}function at(e){const t=e.geometry;if("mesh"===t?.type){const r=e.cloneShallow();return r.attributes=u(e.attributes),r.geometry=t.cloneShallow(),r.geometry.transform=t.transform?.clone()??null,r}return e.clone()}function ot(e){const t=e.cursor;return e.cursor="progress",l(()=>e.cursor=t)}async function it(e,t){const{template:r}=e;if(null==r)return null;if(j(r))return r.load();if(T(r)){const e=(await import("../../editing/sharedTemplates/SharedTemplate.js")).default,n=U(t,{makeSharedTemplateFromJSON:t=>e.fromJSON(t)}),a=await n.getTemplates({templateIds:[r.templateId],featureService:r.featureService});if(0===a.length)throw new i("editor:failed-to-load-template","Unable to load the provided template");return a[0].load()}return r}function st(e){for(const t of e){const{destinationGraphic:e,destinationField:r,sourceGraphic:n,sourceField:a}=t;e.setAttribute(r,n.getAttribute(a))}}function lt(e){const t=e.templateExecutorInfo?.completionResults;return t?.length?(t.forEach(e=>st(e.relationships)),t.flatMap(e=>e.edits)):null}function ct(e){if(null==e)return[];if(ee(e))return e.data.layers;const t=re(e)?e.activeWorkflow:e,r=t?.layer;return r?[r]:[]}function ut(){return new i("editing:multiple-layers-not-supported","UpdateFeaturesWorkflow does not support updating features from multiple layers.")}export{Ve as appendAllUtilityNetworkAssociationRelationships,Ye as avoidFeatureTemplateSelectionWithOnlyOneItem,nt as canCreateInteractiveEditSession,at as cloneGraphicExceptMesh,Se as createLayerIdMap,je as createRelationshipKeyMap,de as createToolFromGeometryType,Xe as createWorkflowSteps,qe as fetchCandidates,Re as fetchFullFeatures,ke as findAllDependencies,Le as findChangesByGlobalId,ze as findLayerInfo,Ae as generateHashForRelationship,Me as getCreationAttributes,it as getFullTemplateForCreationInfo,ct as getLayersFromWorkflow,oe as getRotationVariableAttribute,lt as getServiceEditsFromWorkflowData,we as getServiceInfoForLayer,ve as getServiceLayersById,le as getSizeVariableAttribute,ae as getVisualVariableAttributes,ne as getVisualVariablesForLayer,De as groupFeaturesByLayer,Y as isBatchAttributeFormViewModel,_ as isCreateFeaturesWorkflow,tt as isTerminalUpdateEventType,ee as isUpdateFeaturesWorkflow,te as isUpdateRecordWorkflow,re as isUpdateWorkflow,Ue as isUtilityNetworkAssociationsTable,ut as makeMultipleSourceLayersError,Te as orderEditsByRelationshipDependencies,et as prepareAttachmentsForCreateFeaturesWorkflow,st as setRelationshipFields,Qe as setUpGeometryUpdate,ye as setUpSketchCreateWatchers,Be as setVisualVariablesAndElevationInfoForUpdate,ot as showProgressCursor,Ke as sizeDefaults,_e as sizeVariableUnitToLengthUnit,fe as startCreatingNewFeature,Ge as startUpdatingFeatureGeometry,$e as swapForEditingSession,pe as updateGraphicSymbolWhenRequired,We as visualVariableInteractiveUpdate,rt as whenEditorLayerView,He as whenGraphicDisplayed};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__addDisposableResource as e,__disposeResources as r}from"tslib";import{isSupportedLayer as t}from"../../../arcade/featureset/support/shared.js";import a from"../../../core/Logger.js";import{sqlAnd as n}from"../../../core/sql.js";import i from"../../../layers/FeatureLayer.js";import{internalTimeReceivedField as s}from"../../../layers/support/streamLayerUtils.js";import{isDate as o}from"../../../support/guards.js";import{applyTextFormattingHTML as c,htmlEntities as u}from"./featureUtils.js";const l="esri.widgets.Feature.support.arcadeFeatureUtils",p=()=>a.getLogger(l);function d(e){return c(u(e))}function f(e){return"createQuery"in e&&"queryFeatures"in e}async function y({graphic:e,view:r,options:t}){const{isAggregate:a}=e,n=e.layer??e.sourceLayer;if(!a||!n||"2d"!==r?.type)return[];const i=await r.whenLayerView(n);if(!f(i))return[];const s=i.createQuery(),o=e.getObjectId();s.aggregateIds=null!=o?[o]:[];const{features:c}=await i.queryFeatures(s,t);return c}function m({layer:e,aggregatedFeatures:r,interceptor:t}){const{fields:a,objectIdField:n,geometryType:s,spatialReference:o,displayField:c}=e;return new i({fields:a,objectIdField:n,geometryType:s,spatialReference:o,displayField:c,interceptor:t,..."feature"===e.type?{templates:e.templates,typeIdField:e.typeIdField,types:e.types}:null,source:r})}function w(e){const r="esri.views.3d.layers.VoxelGraphic"===e.declaredClass;return e.isAggregate?"popup-feature-reduction":r?"popup-voxel":"popup"}function g(e){return{scale:e?.scale,timeProperties:{currentStart:e?.timeExtent?.start,currentEnd:e?.timeExtent?.end,startIncluded:!0,endIncluded:!0}}}function v(e){return{$voxel:e}}async function x(e,r,t,a,n,i,s){let o=null;if(i.has("$aggregatedfeatures")){const e=await y({graphic:r,view:t,options:a}),i=r.sourceLayer||r.layer;o=m({layer:i,aggregatedFeatures:e,interceptor:n})}return{vars:{$feature:r,$aggregatedFeatures:o,$view:g(t)},track:s?await F(e,r,t):null,[Symbol.dispose]:()=>o?.[Symbol.dispose]()}}function h(e){if(o(e))return e.getTime();if("number"==typeof e)return e;if("string"==typeof e)return new Date(e).getTime();throw new Error(`Unexpected time value: ${e}`)}async function F(e,r,t){const a=r.sourceLayer||r.layer;if(null==a||!("timeInfo"in a))return null;const i=a.timeInfo?.trackIdField;if(null==i)return null;const o=r.getAttribute(i);if(null==o)return null;let c,u;if("string"==typeof o)c=`"${i.replaceAll('"','""')}" = '${o.replaceAll("'","''")}'`;else{if("number"!=typeof o)return p().warn("Expected track id to be a string or number"),null;c=`"${i.replaceAll('"','""')}" = ${o}`}if("stream"===a.type&&null!=t){const e=await t.whenLayerView(a),r=e.createQuery();r.returnGeometry=!0,r.where=n(r.where,c),u=(await e.queryFeatures(r)).features}else{if(!("queryFeatures"in a))return null;{const e=a.createQuery();e.returnGeometry=!0,e.where=n(e.where,c),u=(await a.queryFeatures(e)).features}}const l=a.fieldsIndex.normalizeFieldName(a.timeInfo.startField)??s,d=a.timeInfo.endField?a.fieldsIndex.normalizeFieldName(a.timeInfo.endField):null,f=u.map(r=>{const a=r.getObjectId();if(null==a)throw new Error("Cannot identify observation");const n=e.ArcadeFeature.createFromGraphic(r,t?.timeZone),i=h(r.getAttribute(l));return{id:a,feature:n,startTime:i,endTime:null!=d?h(r.getAttribute(d)):i,stats:{totalDistance:void 0,distance:void 0,speed:void 0,acceleration:void 0}}}).sort((e,r)=>e.startTime-r.startTime),y="esri.TrackGraphic"===r.declaredClass?f.length-1:f.findIndex(e=>r.getObjectId()===e.id);if(y<0)throw new Error("Couldn't locate feature in observations");return{observations:f,currentObservationIndex:y}}async function b(e,r,a,n,i,s){const o=(r.sourceLayer||r.layer)??void 0;return{vars:{$feature:r,$layer:null!=o&&t(o)?o:"scene"===o?.type&&null!=o.associatedLayer?o.associatedLayer:void 0,$map:a,$datastore:o?.url,$userInput:n,$graph:"knowledge-graph-sublayer"===o?.type?o.parentCompositeLayer?.knowledgeGraph:void 0,$view:g(i)},track:s?await F(e,r,i):null}}async function I(e,{arcade:r,graphic:t,map:a,location:n,view:i,options:s,interceptor:o,arcadeExecutor:c,usesTrack:u}){switch(e){case"popup":return{...await b(r,t,a,n,i,u),[Symbol.dispose](){}};case"popup-feature-reduction":{const e=new Set(c.variablesUsed);return await x(r,t,i,s,o,e,u)}case"popup-voxel":return{vars:v(t),track:null,[Symbol.dispose](){}};default:throw new Error(`Unexpected profile name ${e}`)}}async function $(){const[e,r,{default:t}]=await Promise.all([import("../../../arcade.js"),import("../../../arcade/arcade.js"),import("../../../arcade/Feature.js")]);return{executor:e,syntaxUtils:r,ArcadeFeature:t}}async function j(t,a,n){const{executor:{createArcadeProfile:i,createArcadeExecutor:s},syntaxUtils:o}=n,c=w(a),u=i(c);let l;try{l=await s(t,u)}catch(y){return p().error("arcade-executor-error",{error:y,expression:t}),null}const d=new Set;l.variablesUsed.includes("$view")&&(o.scriptUsesViewProperties(l.syntaxTree,["scale"])&&d.add("view-scale"),o.scriptUsesViewProperties(l.syntaxTree,["timeProperties"])&&d.add("view-time-extent"));const f=o.scriptUsesTrack(l.syntaxTree);return{dependencies:d,async evaluate({graphic:a,interceptor:i,location:s,map:o,options:u,spatialReference:d,view:m}){const w={stack:[],error:void 0,hasError:!1};try{const r=e(w,await I(c,{arcade:n,graphic:a,map:o,location:s,view:m,options:u,interceptor:i,arcadeExecutor:l,usesTrack:f}),!1),g={abortSignal:u?.signal??void 0,interceptor:i??void 0,rawOutput:!0,spatialReference:d??void 0,timeZone:m?.timeZone,track:r.track,console(...e){p().info(...e)}};try{return await l.executeAsync(r.vars,g)}catch(y){if(u?.signal?.aborted)return;return void p().error("arcade-execution-error",{error:y,graphic:a,expression:t})}}catch(g){w.error=g,w.hasError=!0}finally{r(w)}}}}async function T({expression:e,graphic:r}){return e?j(e,r,await $()):null}async function k(e,r){if(!e?.length)return{dependencies:new Set,expressions:new Map};const t=await $(),a=new Set,n=new Map;for(const i of e){const e=await j(i.expression,r,t);n.set(`expression/${i.name}`,e),e?.dependencies.forEach(e=>a.add(e))}return{dependencies:a,expressions:n}}export{T as compileExpression,k as compileExpressionInfos,d as formatArcadeValue};
5
+ import{__addDisposableResource as e,__disposeResources as r}from"tslib";import{isSupportedLayer as t}from"../../../arcade/featureset/support/shared.js";import a from"../../../core/Logger.js";import{sqlAnd as n}from"../../../core/sql.js";import i from"../../../layers/FeatureLayer.js";import{internalTimeReceivedField as s}from"../../../layers/support/streamLayerUtils.js";import{isDate as o}from"../../../support/guards.js";import{applyTextFormattingHTML as c,htmlEntities as u}from"./featureUtils.js";const l="esri.widgets.Feature.support.arcadeFeatureUtils",p=()=>a.getLogger(l);function d(e){return c(u(e))}function f(e){return"createQuery"in e&&"queryFeatures"in e}async function y({graphic:e,view:r,options:t}){const{isAggregate:a}=e,n=e.layer??e.sourceLayer;if(!a||!n||"2d"!==r?.type)return[];const i=await r.whenLayerView(n);if(!f(i))return[];const s=i.createQuery(),o=e.getObjectId();s.aggregateIds=null!=o?[o]:[];const{features:c}=await i.queryFeatures(s,t);return c}function m({layer:e,aggregatedFeatures:r,interceptor:t}){const{fields:a,objectIdField:n,geometryType:s,spatialReference:o,displayField:c}=e;return new i({fields:a,objectIdField:n,geometryType:s,spatialReference:o,displayField:c,interceptor:t,..."feature"===e.type?{templates:e.templates,typeIdField:e.typeIdField,types:e.types}:null,source:r})}function w(e){const r="esri.views.3d.layers.VoxelGraphic"===e.declaredClass;return e.isAggregate?"popup-feature-reduction":r?"popup-voxel":"popup"}function g(e){return{scale:e?.scale,timeProperties:{currentStart:e?.timeExtent?.start,currentEnd:e?.timeExtent?.end,startIncluded:!0,endIncluded:!0}}}function v(e){return{$voxel:e}}async function x(e,r,t,a,n,i,s){let o=null;if(i.has("$aggregatedfeatures")){const e=await y({graphic:r,view:t,options:a}),i=r.sourceLayer||r.layer;o=m({layer:i,aggregatedFeatures:e,interceptor:n})}return{vars:{$feature:r,$aggregatedFeatures:o,$view:g(t)},track:s?await F(e,r,t):null,[Symbol.dispose]:()=>o?.[Symbol.dispose]()}}function h(e){if(o(e))return e.getTime();if("number"==typeof e)return e;if("string"==typeof e)return new Date(e).getTime();throw new Error(`Unexpected time value: ${e}`)}async function F(e,r,t){const a=r.sourceLayer||r.layer;if(null==a||!("timeInfo"in a))return null;const i=a.timeInfo?.trackIdField;if(null==i)return null;const o=r.getAttribute(i);if(null==o)return null;let c,u;if("string"==typeof o)c=`"${i.replaceAll('"','""')}" = '${o.replaceAll("'","''")}'`;else{if("number"!=typeof o)return p().warn("Expected track id to be a string or number"),null;c=`"${i.replaceAll('"','""')}" = ${o}`}if("stream"===a.type&&null!=t){const e=await t.whenLayerView(a),r=e.createQuery();r.returnGeometry=!0,r.where=n(r.where,c),u=(await e.queryFeatures(r)).features}else{if(!("queryFeatures"in a))return null;{const e=a.createQuery();e.returnGeometry=!0,e.where=n(e.where,c),u=(await a.queryFeatures(e)).features}}const l=a.fieldsIndex.normalizeFieldName(a.timeInfo.startField)??s,d=a.timeInfo.endField?a.fieldsIndex.normalizeFieldName(a.timeInfo.endField):null,f=u.map(r=>{const a=r.getObjectId();if(null==a)throw new Error("Cannot identify observation");const n=e.ArcadeFeature.createFromGraphic(r,t?.timeZone),i=h(r.getAttribute(l));return{id:a,feature:n,startTime:i,endTime:null!=d?h(r.getAttribute(d)):i,stats:{totalDistance:void 0,distance:void 0,speed:void 0,acceleration:void 0}}}).sort((e,r)=>e.startTime-r.startTime),y="esri.TrackGraphic"===r.declaredClass?f.length-1:f.findIndex(e=>r.getObjectId()===e.id);if(y<0)throw new Error("Couldn't locate feature in observations");return{observations:f,currentObservationIndex:y}}async function b(e,r,a,n,i,s){const o=(r.sourceLayer||r.layer)??void 0;return{vars:{$feature:r,$layer:null!=o&&t(o)?o:"scene"===o?.type&&null!=o.associatedLayer?o.associatedLayer:void 0,$map:a,$datastore:o&&"url"in o?o.url:void 0,$userInput:n,$graph:"knowledge-graph-sublayer"===o?.type?o.parentCompositeLayer?.knowledgeGraph:void 0,$view:g(i)},track:s?await F(e,r,i):null}}async function I(e,{arcade:r,graphic:t,map:a,location:n,view:i,options:s,interceptor:o,arcadeExecutor:c,usesTrack:u}){switch(e){case"popup":return{...await b(r,t,a,n,i,u),[Symbol.dispose](){}};case"popup-feature-reduction":{const e=new Set(c.variablesUsed);return await x(r,t,i,s,o,e,u)}case"popup-voxel":return{vars:v(t),track:null,[Symbol.dispose](){}};default:throw new Error(`Unexpected profile name ${e}`)}}async function $(){const[e,r,{default:t}]=await Promise.all([import("../../../arcade.js"),import("../../../arcade/arcade.js"),import("../../../arcade/Feature.js")]);return{executor:e,syntaxUtils:r,ArcadeFeature:t}}async function j(t,a,n){const{executor:{createArcadeProfile:i,createArcadeExecutor:s},syntaxUtils:o}=n,c=w(a),u=i(c);let l;try{l=await s(t,u)}catch(y){return p().error("arcade-executor-error",{error:y,expression:t}),null}const d=new Set;l.variablesUsed.includes("$view")&&(o.scriptUsesViewProperties(l.syntaxTree,["scale"])&&d.add("view-scale"),o.scriptUsesViewProperties(l.syntaxTree,["timeProperties"])&&d.add("view-time-extent"));const f=o.scriptUsesTrack(l.syntaxTree);return{dependencies:d,async evaluate({graphic:a,interceptor:i,location:s,map:o,options:u,spatialReference:d,view:m}){const w={stack:[],error:void 0,hasError:!1};try{const r=e(w,await I(c,{arcade:n,graphic:a,map:o,location:s,view:m,options:u,interceptor:i,arcadeExecutor:l,usesTrack:f}),!1),g={abortSignal:u?.signal??void 0,interceptor:i??void 0,rawOutput:!0,spatialReference:d??void 0,timeZone:m?.timeZone,track:r.track,console(...e){p().info(...e)}};try{return await l.executeAsync(r.vars,g)}catch(y){if(u?.signal?.aborted)return;return void p().error("arcade-execution-error",{error:y,graphic:a,expression:t})}}catch(g){w.error=g,w.hasError=!0}finally{r(w)}}}}async function T({expression:e,graphic:r}){return e?j(e,r,await $()):null}async function k(e,r){if(!e?.length)return{dependencies:new Set,expressions:new Map};const t=await $(),a=new Set,n=new Map;for(const i of e){const e=await j(i.expression,r,t);n.set(`expression/${i.name}`,e),e?.dependencies.forEach(e=>a.add(e))}return{dependencies:a,expressions:n}}export{T as compileExpression,k as compileExpressionInfos,d as formatArcadeValue};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import t from"../../Graphic.js";import{neverReached as n}from"../../core/compilerUtils.js";import s from"../../core/Evented.js";import i from"../../core/Logger.js";import{destroyMaybe as o}from"../../core/maybe.js";import r from"../../core/Promise.js";import{debounce as a}from"../../core/promiseUtils.js";import{watch as l,syncAndInitial as u,whenOnce as p,on as c}from"../../core/reactiveUtils.js";import{templateHasKey as h}from"../../core/string.js";import{property as d}from"../../core/accessorSupport/decorators/property.js";import"../../core/RandomLCG.js";import{subclass as f}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as m}from"../../core/support/UpdatingHandles.js";import y from"../../form/FormTemplate.js";import{isUtilityNetworkAssociationsElement as g,isGroupElement as _,isFieldElement as v,isRelationshipElement as I,isTextElement as x}from"../../form/support/formUtils.js";import E from"../../layers/support/ContingentValue.js";import{isEditableLayer as C}from"../../layers/support/editableLayers.js";import F from"../../layers/support/LayerContingentValuesCache.js";import{utc as b,unknown as V,system as w}from"../../time/constants.js";import{flattenAssociationInputs as A,flattenFieldInputs as j,isGroupInput as T,flattenRelationshipInputs as M,parseFormTemplateString as N,isRelationshipInput as S,isFieldInput as k,isTextElementInput as L,getNormalizedFeatureTypeInfo as R,valueIsValidContingentValue as U}from"./featureFormUtils.js";import Z from"./FieldInput.js";import{FormExpressionsManager as H}from"./FormExpressionsManager.js";import P from"./GroupInput.js";import O from"./RelationshipInput.js";import G from"./TextElementInput.js";import{createFormExpressionArcadeExecutor as W}from"../support/forms/expressions/FormExpressionArcadeExecutor.js";const $=new t({attributes:{}}),D={field:["editableExpression","requiredExpression","valueExpression","visibilityExpression"],group:["visibilityExpression"],relationship:["editableExpression","visibilityExpression"],text:["visibilityExpression"],utilityNetworkAssociations:["editableExpression","visibilityExpression"]},z="#JSAPI_CONTINGENT_VALUE_EMPTY_HASH",J="#JSAPI_CONTINGENT_VALUE_ANY_HASH",B="#JSAPI_CONTINGENT_VALUE_NULL_HASH";let K=class extends(r.EsriPromiseMixin(s.EventedAccessor)){constructor(e){super(e),this._expressionExecutorsInUse=new Set,this._expressionExecutorLookup=new Map,this._expressionsManager=null,this._contingentValuesCache=null,this._featureClone=$.clone(),this._initialFeature=$.clone(),this._timeZone=null,this._updatingHandles=new m,this.activeAssociation=null,this.editType="NA",this.contingencyConstraintViolations=new Map,this.disabled=!1,this.highlightHelper=null,this.inputs=[],this.map=null,this.callbacks=null,this.strict=!1,this.pendingSubtypeChoice=null,this._updateInputs=a(async()=>{this._stopExpressions();const{_featureClone:e,_initialFeature:t,editType:n,formTemplate:s,inputs:i,layer:o,timeZone:r}=this;if(!o)return;const a={editType:n,feature:e,initialFeature:t,layer:o,timeZone:r},l=i.slice(),u=s?.elements&&s.elements.length>0?await this._updateInputsUsingFormElements(l,s.elements,a):this._updateInputsUsingLayerFields(l,o?.fields,a);this.inputs=u,await this._startExpressions()})}initialize(){const e=l(()=>[this.layer,!!this.layer?.loaded,this.formTemplate,this.feature,this.timeZone,this.editType],([e,t])=>{null!=e&&(t?this._updatingHandles.addPromise(this._updateInputs()):e.load().catch(()=>{}))},u),t=l(()=>this._arcadeContextInfo,e=>{null!=this._expressionsManager&&(this._expressionsManager.arcadeContextInfo=e,this._evaluateExpressions(e=>e.evaluateAll()))}),n=l(()=>this.layer,e=>{const t="subtype-sublayer"===e?.type?e.parent:"feature"===e?.type?e:null;t&&this.addResolvingPromise(F.createLoadedLayerContingentValuesCache(t).then(e=>{this._contingentValuesCache=e,this.notifyChange("fieldsWithContingentValues")}))},{initial:!0});this.addHandles([e,t,n])}destroy(){this.feature=null,this.layer=null,this._contingentValuesCache=o(this._contingentValuesCache),this.highlightHelper?.removeAll(),this._updatingHandles.destroy()}get _expressionInfosLookup(){return new Map(this.formTemplate?.expressionInfos?.map(e=>[e.name,e]))}get activeAssociationInput(){return this.allAssociationInputs.find(e=>e.uid===this.associationId)}get activeRelationshipInput(){return this.allRelationshipInputs.find(e=>e.relationshipId===this.relationshipId||e.activeCategory||e.showAllEnabled)}get _arcadeContextInfo(){const{_initialFeature:e,editType:t,layer:n,map:s,spatialReference:i,timeZone:o}=this;return{layer:C(n)?n:null,originalFeature:e,editType:t,map:s,spatialReference:i,timeZone:o}}get associationId(){return this._get("associationId")}set associationId(e){null==e&&this.activeAssociationInput?.viewModel&&(this.activeAssociationInput.associatedLayer=null,this.activeAssociationInput.viewModel.activeAssociationType=null),this._set("associationId",e)}get associatedLayer(){return this.activeAssociationInput?.associatedLayer}set associatedLayer(e){this.activeAssociationInput&&(this.activeAssociationInput.associatedLayer=e)}get allAssociationInputs(){return A(this.inputs)}get allFieldInputs(){return j(this.inputs)}get allGroupInputs(){return this.inputs.filter(T)}get allRelationshipInputs(){return M(this.inputs)}get _layerFieldsByName(){return new Map(this.layer?.fields.map(e=>[e.name,e]))}get feature(){return this._get("feature")}set feature(e){const t=this._get("feature");this._featureClone=e?e.clone():$.clone(),this._initialFeature=this._featureClone.clone(),this._expressionsManager&&(this._expressionsManager.feature=this._featureClone),e?(this._resetFieldInputValues(this._featureClone),this.allRelationshipInputs.forEach(t=>t.feature=e)):(this.inputs.forEach(e=>e.destroy()),this.inputs.length=0),t!==e&&(this.pendingSubtypeChoice=null),this.contingencyConstraintViolations.clear(),this._set("feature",e)}get fieldsWithContingentValues(){if(null==this._contingentValuesCache)return new Set;const e=this._contingentValuesCache.fieldGroups.flatMap(e=>e.fields);return new Set(e)}get formTemplate(){return this.layer&&"formTemplate"in this.layer?this.layer.formTemplate:null}set formTemplate(e){void 0===e?this._clearOverride("formTemplate"):this._override("formTemplate",e)}get formDescription(){const{formTemplate:e,layer:t}=this;return e?.description&&t?N({label:e.description,attributes:this.getValues(),fieldsIndex:t.fieldsIndex,timeZone:this.timeZone}):null}get formTitle(){const{formTemplate:e,layer:t}=this;return e?.title&&t?N({label:e.title,attributes:this.getValues(),fieldsIndex:t.fieldsIndex,timeZone:this.timeZone}):null}get formHeaderVisible(){const{activeRelationshipInput:e,activeAssociationInput:t,formDescription:n,formTitle:s}=this;return!(e||t||!n&&!s)}get joinedContingentValues(){return this._joinContingentValues()}get layer(){return this.feature?.sourceLayer&&"applyEdits"in this.feature.sourceLayer?this.feature.sourceLayer:null}set layer(e){this._override("layer",e)}get relationshipId(){return this._get("relationshipId")}set relationshipId(e){const t=this.allRelationshipInputs;if(null!=e&&e===this.relationshipId||t.forEach(e=>{e.showAllEnabled=!1,e.activeCategory=null}),null!=e){const n=t.find(t=>t.relationshipId===e);n&&(n.showAllEnabled=!0)}this._set("relationshipId",e)}get spatialReference(){return this.layer?.spatialReference??null}set spatialReference(e){this._override("spatialReference",e)}get state(){return this.layer?.loaded?"ready":"disabled"}get submittable(){return!!this.valid||this.allFieldInputs.filter(e=>!e.valid).every(({submittable:e})=>e)}get timeZone(){const{layer:e}=this;if(e&&"datesInUnknownTimezone"in e&&e.datesInUnknownTimezone)return b;const t=e&&"preferredTimeZone"in e&&e.preferredTimeZone;return this._timeZone===V?t||b:this._timeZone||w}set timeZone(e){this._timeZone=e}get updating(){return this._updatingHandles.updating}get valid(){const e=this.allFieldInputs;return e.length>0&&e.every(({valid:e})=>e)}findField(e){return this.allFieldInputs.find(t=>t.name===e)}findGroup(e){return this.allGroupInputs.find(t=>t.id===e)}getFieldValueOptionsForField(e,t){const n=this.findField(e);if(!n)return[[],[],[]];const s="coded-value"===n.domain?.type?n.domain.codedValues.map(({name:e,code:t})=>({name:e,value:t})):[],i=null==n.value||s.some(e=>e.value===n.value)?[]:[{name:`${n.value}`,value:n.value}],o=this.fieldsWithContingentValues.has(e)?this._getContingentValueOptionsForField(e,t):[];if(o.length>0){const e=new Set(o.map(e=>e.value));return[o,s.filter(t=>!e.has(t.value)),i]}return[s,[],i]}getValue(e){const t=this.layer?.getField(e);if(null!=t)return this._featureClone.getAttribute(t.name)??null}setValue(e,t){const{_featureClone:n,strict:s}=this,i=this.findField(e);t=""===t?null:t,i&&n.getAttribute(e)!==t&&(i.value=t,s&&!i.valid||(this._afterValueChange(i),this._evaluateExpressions(t=>t.evaluateInvalidated([e]))))}getValues(){return{...this._featureClone.attributes}}overrideInitialFeature(e){this._initialFeature=e}submit(){const e=this.allFieldInputs,t=new Set(e.filter(e=>e.valid).map(({name:e})=>e)),n=e.filter(e=>!e.valid).map(({name:e})=>e),s=this.getValues();if(this.validateContingencyConstraints(s,{includeIncompleteViolations:!0}).length>0)for(const[i,o]of this.contingencyConstraintViolations.entries())"error"===o.type&&(t.delete(i),n.push(i));this.notifyChange("submittable"),this.notifyChange("valid"),this.emit("submit",{valid:[...t],invalid:n,values:s})}validateContingencyConstraints(e,t){const{_contingentValuesCache:n}=this,s=new Map;if(this.contingencyConstraintViolations=s,null==n)return[];const{invalid:i,incomplete:o}=n.validateContingencyConstraints(e),r=[...i,...t?.includeIncompleteViolations?o:[]];for(const a of r)for(const e of a.fieldGroup.fields)s.set(e,a);return r}notifyFeatureGeometryChanged(){const{feature:e,_featureClone:t}=this;e&&(t.geometry=e.geometry,this._evaluateExpressions(e=>e.evaluateInvalidatedByGeometry()))}applySubtypeDefaults(e){const{defaultValues:t}=e,{allFieldInputs:n}=this;for(const{name:s}of n){const e=t[s];null!=e&&this.setValue(s,e)}}_emitChangeEvent({name:e,valid:t,value:n}){this.emit("value-change",{layer:this.layer,feature:this.feature,fieldName:e,value:n,valid:t})}async _evaluateExpressions(e){const t=this._expressionsManager;null!=t&&await this._updatingHandles.addPromise(e(t).finally(()=>this._afterExpressionsEvaluated()))}async _updateInputsUsingFormElements(e,t,n){const s=new Map;for(const r of e)if(T(r)){s.set(r.element,r);for(const e of r.inputs)e.element&&s.set(e.element,e)}else r.element&&s.set(r.element,r);const i=new Map,o=await this._updateInputsUsingFormElementsRecursive({existingInputsByElement:s,updatedElements:t.filter(e=>this._isSupportedElement(e)),sharedInitializationProperties:n,group:null,newExpressionExecutorPromises:i});for(const[r,a]of s.entries())s.delete(r),a.destroy();return await Promise.all(Array.from(i.values())),o}async _updateInputsUsingFormElementsRecursive(e){const{existingInputsByElement:t,updatedElements:n,sharedInitializationProperties:s,group:i,newExpressionExecutorPromises:o}=e,r=[];for(const a of n){const e=t.has(a),n=e?t.get(a):g(a)?await this._makeUtilityNetworkAssociationInputFromElement(a,s,i):this._makeInputFromElement(a,s,i);if(n){if(r.push(n),await p(()=>!n.updating),this._assignExpressionExecutors(n,a,o),e)if(t.delete(a),T(n)){const{feature:e,timeZone:t}=s;n.set({feature:e,timeZone:t})}else if(S(n)){const e=this.relationshipId===a.relationshipId;n.set(s),n.set({map:this.map,showAllEnabled:e})}else g(n)?(n.set(s),n.set({map:this.map})):n.set(s);if(_(a)){const e=a.elements.filter(e=>this._isSupportedElement(e));n.inputs=await this._updateInputsUsingFormElementsRecursive({existingInputsByElement:t,updatedElements:e,sharedInitializationProperties:s,group:n,newExpressionExecutorPromises:o})}}}return r}_updateInputsUsingLayerFields(e,t,n){if(!Array.isArray(t))return i.getLogger(this).warn(this.declaredClass,"No attribute fields found."),[];const s=new Map;for(const i of e)if(T(i)){for(const e of i.inputs)e.destroy();i.inputs.length=0,i.destroy()}else S(i)?i.destroy():k(i)&&(null!==i.element?i.destroy():s.set(i.field,i));const o=[];for(const i of t){const e=n.feature?.getAttribute(i.name)??null,t=s.get(i)??new Z({field:i,preservesValueWhenHidden:this.formTemplate?.preserveFieldValuesWhenHidden});o.push(t.set({...n,value:e})),s.delete(i)}for(const[i,r]of s.entries())s.delete(i),r.destroy();return o}_resetFieldInputValues(e){for(const t of this.allFieldInputs)t.value=e.getAttribute(t.name)}_makeInputFromElement(e,t,s){return _(e)?Y(e,t):v(e)?this._makeFieldInputFromElement(e,t,s):I(e)?this._makeRelationshipInputFromElement(e,t,s):g(e)?this._makeUtilityNetworkAssociationInputFromElement(e,t,s):x(e)?q(e,t):g(e)?this._makeUtilityNetworkAssociationInputFromElement(e,t,s):n()}_makeFieldInputFromElement(e,t,n){const{editType:s,feature:i,initialFeature:o,layer:r,timeZone:a}=t,{fieldName:l}=e,u=l&&this._layerFieldsByName.get(l);return u?new Z({editType:s,element:e,field:u,value:i?.getAttribute(e.fieldName)??null,feature:i,initialFeature:o,layer:r,group:n,preservesValueWhenHidden:this.formTemplate?.preserveFieldValuesWhenHidden,timeZone:a}):null}_makeRelationshipInputFromElement(e,t,n=null){const{map:s}=this,{feature:i,layer:o,timeZone:r}=t,a=new O({element:e,feature:i,group:n,layer:o,map:s,timeZone:r});return a.addHandles(c(()=>a.relatedLayer,"edits",()=>this._evaluateExpressions(e=>e.evaluateAsyncExpressions()))),a}async _makeUtilityNetworkAssociationInputFromElement(e,t,n=null){const{map:s}=this,{feature:i,layer:o,timeZone:r}=t;return new(0,(await import("./UtilityNetworkAssociationInput.js")).default)({element:e,feature:i,group:n,layer:o,map:s,timeZone:r})}_assignExpressionExecutors(e,t,n){const s=D[t.type],i=[];for(const o of s){const s=`${o}Executor`;if(e[s]){this._useExecutor(e[s]);continue}const r=t[o];if(null!=r&&""!==r){const t=this._expressionInfosLookup.get(r)?.expression??r;i.push(this._getOrCreateExecutorForExpression(t,n).then(t=>{e[s]=this._useExecutor(t)}))}}return L(e)&&i.push(...this._assignTextElementExpressionExecutors(e,n)),i}_assignTextElementExpressionExecutors(e,t){const{_expressionInfosLookup:n}=this,s=[];for(const o of e.expressionsUsed){const r=n.get(o);null!=r?s.push(this._getOrCreateExecutorForExpression(r.expression,t).then(t=>e.setExpressionExecutor(o,this._useExecutor(t)))):i.getLogger(this).error("feature-form:expression-not-found",`Could not find expressionInfo object with name '${o}'`)}for(const i of e.fieldsUsed){const n=`return $feature['${i}'];`;s.push(this._getOrCreateExecutorForExpression(n,t).then(t=>e.setFieldExecutor(i,this._useExecutor(t))))}return s}async _getOrCreateExecutorForExpression(e,t){const{_expressionExecutorLookup:n}=this;if(n.has(e))return n.get(e);if(t.has(e))return t.get(e);const s=W(e,this.layer);t.set(e,s);const i=await s;return n.set(e,i),i}_createExpressionsManager(e){const{_arcadeContextInfo:t,_featureClone:n,allFieldInputs:s,formTemplate:i}=this;this._expressionsManager=new H({executors:e,feature:n,arcadeContextInfo:t,fieldInputs:s,preserveFieldValuesWhenHidden:!0===i?.preserveFieldValuesWhenHidden})}async _startExpressions(){if(0===this._expressionExecutorsInUse.size)return;const e=Array.from(this._expressionExecutorsInUse);this._createExpressionsManager(e),this._evaluateExpressions(e=>e.evaluateAll())}_stopExpressions(){this._expressionsManager=o(this._expressionsManager),this._expressionExecutorsInUse.clear()}_useExecutor(e){return this._expressionExecutorsInUse.add(e),e}_afterValueChange(e){const{name:t,value:n}=e,{_featureClone:s,formTemplate:i,layer:o}=this;if(!o)return;const r=s.getAttribute(t);s.setAttribute(t,n);const{typeFieldName:a,types:l}=R(o);if((e.isSubtypeField||t===a)&&n!==r){if("subtype-sublayer"===o.type){const e=o.parent?.findSublayerForFeature(s);e&&(this.feature&&(this.feature.sourceLayer=e),s.sourceLayer=e)}const e=new Set;for(const t of l)if(t.domains&&"object"==typeof t.domains)for(const n of Object.keys(t.domains))e.add(n);for(const t of e){const e=this.findField(t);e&&e.notifyChange("domain")}this.notifyChange("joinedContingentValues")}if(null!=i){const{description:e,title:n}=i;n&&h(n,t)&&this.notifyChange("formTitle"),e&&h(e,t)&&this.notifyChange("formDescription")}this._emitChangeEvent(e)}_afterExpressionsEvaluated(){const{_featureClone:e}=this;for(const t of this.allFieldInputs)t.value!==e.getAttribute(t.name)&&this._afterValueChange(t)}_joinContingentValues(){const e=this._contingentValuesCache;if(null==e)return[];const{typeFieldName:t}=R(this.layer),n=t?this.getValue(t):null,s=[];for(const r of e.fieldGroups){const{contingencies:e,fields:t,name:i}=r,o=[];for(const s of e)s.isRetired||null!=s.subtype&&s.subtype.code!==n||o.push({values:s.values});o.length>0&&s.push({name:i,fields:t,contingencies:o})}const[i,o]=this._generateJoinPlan(s);return[...i.flatMap(e=>this._joinFieldGroupContingencies(e)),...o.flatMap(e=>e.contingencies)]}_generateJoinPlan(e){const t=new Map,n=[],s=new Set;for(const l of e)for(const e of l.fields)if(t.has(e)){const i=t.get(e),o=l,r=[i.name,o.name].sort().join("|");if(s.has(r))continue;n.push([i,o]),s.add(r),t.set(e,o)}else t.set(e,l);const i=new Set(n.flat()),o=new Set(e);for(const l of i)o.delete(l);const r=new Map,a=new Map;for(const l of new Set(n.flat())){const e=Symbol(l.name);r.set(e,new Set([l])),a.set(l,e)}for(const[l,u]of n){const e=a.get(l),t=a.get(u);if(e===t)continue;const n=r.get(e),s=r.get(t);for(const i of s)n.add(i),a.set(i,e);r.delete(t)}return[[...r.values()].map(e=>[...e]),[...o]]}_joinFieldGroupContingencies(e){const t=e.slice(),n=t.shift();let s=t.shift(),i=this._generateJoinKey(n.fields,s.fields),o=new Set([...n.fields,...s.fields]),r=new Map;for(const l of n.contingencies){const[e]=this._hashContingency(l,i.codedValueFields,!0);r.has(e)?r.get(e)?.push(l):r.set(e,[l])}for(;t.length>0;){const e=new Map,n=t.shift(),a=this._generateJoinKey(o,n.fields);for(const t of s.contingencies){const[n,s]=this._hashContingency(t,i.codedValueFields),o=s?this._findMatchingContingenciesWithAnyHashMask(r,n):r.get(n);if(r.has(J)&&o?.push(...this._findMatchingContingenciesContainingAny(t,r.get(J),i.codedValueFields)),null!=o)for(const r of o){const n=i.rangeFields.length>0?this._joinContingenciesWithRangeDomains(r,t,i.rangeFields):this._joinContingencies(r,t);if(null==n)break;const[s]=this._hashContingency(n,a.codedValueFields,!0);e.has(s)?e.get(s)?.push(n):e.set(s,[n])}}r=e,s=n,i=a,o=new Set([...o,...s.fields])}const a=[];for(const l of s.contingencies){const[e,t]=this._hashContingency(l,i.codedValueFields),n=t?this._findMatchingContingenciesWithAnyHashMask(r,e):r.get(e);if(r.has(J)&&n.push(...this._findMatchingContingenciesContainingAny(l,r.get(J),i.codedValueFields)),null!=n)for(const s of n){const e=i.rangeFields.length>0?this._joinContingenciesWithRangeDomains(s,l,i.rangeFields):this._joinContingencies(s,l);null!=e&&a.push(e)}}return a}_joinContingencies(e,t){const n={values:{...e.values,...t.values}};for(const[s,i]of Object.entries(n.values))"any"===i.objectType&&null!=e.values[s]&&(n.values[s]=e.values[s]);return n}_joinContingenciesWithRangeDomains(e,t,n){const s=this._joinContingencies(e,t);for(const i of n){const n=e.values[i],o=t.values[i],{leftIsNull:r,rightIsNull:a,bothAreNull:l,leftIsAny:u,rightIsAny:p,bothAreAny:c,leftIsRange:h,rightIsRange:d}=this._compareObjectTypes(n.objectType,o.objectType);if(l||c)continue;if(r&&p||a&&u){s.values[i]=new E({objectType:"null"});continue}if(r&&d||a&&h)return null;u?(n.minValue=-1/0,n.maxValue=1/0):p&&(o.minValue=-1/0,o.maxValue=1/0);const f=Math.max(n.minValue,o.minValue),m=Math.min(n.maxValue,o.maxValue);if(f>m)return null;s.values[i]=new E({objectType:"range",minValue:f,maxValue:m})}return s}_findMatchingContingenciesContainingAny(e,t,n){return t.filter(t=>n.every(n=>{const s=t.values[n],i=e.values[n];return"any"===s.objectType||"any"===i.objectType||s.codedValue?.code===i.codedValue?.code}))}_findMatchingContingenciesWithAnyHashMask(e,t){const n=RegExp(`${t}$`),s=[];for(const[i,o]of e){if(i===J)break;n.test(i)&&s.push(...o)}return s}_generateJoinKey(e,t){const n=Array.isArray(e)?new Set(e):e,s=Array.isArray(t)?new Set(t):t,i=n.size<s.size?n:s,o=i===n?s:n,{feature:r}=this,a=new Set,l=new Set;for(const u of i)if(o.has(u)){const e=this.layer?.getFieldDomain(u,{feature:r??void 0,excludeImpliedDomains:!0});if(null==e)continue;switch(e.type){case"coded-value":a.add(u);break;case"range":l.add(u)}}return{codedValueFields:[...a],rangeFields:[...l]}}_contingencyIsValid(e,t){const n={};for(const{name:s,value:i}of this.allFieldInputs)this.fieldsWithContingentValues.has(s)&&null!=i&&s!==e&&(n[s]=i);return Object.entries(n).every(([e,n])=>!t.values.hasOwnProperty(e)||U(n,t.values[e]))}_getContingentValueOptionsForField(e,t){const n=this.joinedContingentValues.slice(),s=new Map,i={code:"",name:t??"No value"};for(const o of n){const t=o.values[e];if("code"===t?.objectType||"null"===t?.objectType){const{code:n,name:r}=t.codedValue&&"null"!==t.objectType?t.codedValue:i;!s.has(n)&&this._contingencyIsValid(e,o)&&s.set(n,{name:r,value:n})}}return[...s.values()]}_hashContingency(e,t,n=!1){if(t.length<1)return[z,!1];const s=[];let i=!1;for(const o of t){const t=e.values[o];if("any"===t.objectType){if(n)return[J,!0];i=!0,s.push(`${o}:.*`)}else"null"===t.objectType?s.push(`${o}:${B}`):s.push(`${o}:${t.codedValue?.code}`)}return[s.sort().join("&"),i]}_compareObjectTypes(e,t){return{leftIsNull:"null"===e,rightIsNull:"null"===t,bothAreNull:"null"===e&&"null"===t,leftIsAny:"any"===e,rightIsAny:"any"===t,bothAreAny:"any"===e&&"any"===t,leftIsRange:"range"===e,rightIsRange:"range"===t}}_isSupportedElement(e){return"field"===e.type||"group"===e.type||"relationship"===e.type||"text"===e.type||"utilityNetworkAssociations"===e.type||(i.getLogger(this).warn("form-info::unsupported-element-type","Only element types 'field', 'group' and 'relationship' are supported",`Element ${e.label} has unsupported type '${e.type}'`),!1)}get test(){return{featureClone:this._featureClone}}};function Y(e,t){const{feature:n,layer:s}=t;return new P({element:e,inputs:[],feature:n,layer:s})}function q(e,t,n=null){const{feature:s,layer:i,timeZone:o}=t;return new G({element:e,feature:s,group:n,layer:i,timeZone:o})}e([d()],K.prototype,"_expressionInfosLookup",null),e([d()],K.prototype,"_featureClone",void 0),e([d()],K.prototype,"_timeZone",void 0),e([d()],K.prototype,"activeAssociation",void 0),e([d()],K.prototype,"activeAssociationInput",null),e([d()],K.prototype,"activeRelationshipInput",null),e([d()],K.prototype,"_arcadeContextInfo",null),e([d()],K.prototype,"associationId",null),e([d()],K.prototype,"associatedLayer",null),e([d()],K.prototype,"allAssociationInputs",null),e([d()],K.prototype,"allFieldInputs",null),e([d()],K.prototype,"allGroupInputs",null),e([d()],K.prototype,"allRelationshipInputs",null),e([d()],K.prototype,"_layerFieldsByName",null),e([d()],K.prototype,"editType",void 0),e([d()],K.prototype,"contingencyConstraintViolations",void 0),e([d()],K.prototype,"disabled",void 0),e([d()],K.prototype,"feature",null),e([d()],K.prototype,"fieldsWithContingentValues",null),e([d({type:y})],K.prototype,"formTemplate",null),e([d()],K.prototype,"formDescription",null),e([d()],K.prototype,"formTitle",null),e([d()],K.prototype,"formHeaderVisible",null),e([d()],K.prototype,"highlightHelper",void 0),e([d()],K.prototype,"inputs",void 0),e([d()],K.prototype,"joinedContingentValues",null),e([d()],K.prototype,"layer",null),e([d()],K.prototype,"map",void 0),e([d()],K.prototype,"callbacks",void 0),e([d()],K.prototype,"relationshipId",null),e([d()],K.prototype,"spatialReference",null),e([d()],K.prototype,"state",null),e([d()],K.prototype,"strict",void 0),e([d()],K.prototype,"submittable",null),e([d()],K.prototype,"timeZone",null),e([d()],K.prototype,"updating",null),e([d()],K.prototype,"valid",null),e([d()],K.prototype,"pendingSubtypeChoice",void 0),e([d()],K.prototype,"getValues",null),e([d()],K.prototype,"submit",null),e([d()],K.prototype,"test",null),K=e([f("esri.widgets.FeatureForm.FeatureFormViewModel")],K);const Q=K;export{Q as default};
5
+ import{__decorate as e}from"tslib";import t from"../../Graphic.js";import{neverReached as n}from"../../core/compilerUtils.js";import s from"../../core/Evented.js";import i from"../../core/Logger.js";import{destroyMaybe as o}from"../../core/maybe.js";import r from"../../core/Promise.js";import{debounce as a}from"../../core/promiseUtils.js";import{watch as l,syncAndInitial as u,whenOnce as p,on as c}from"../../core/reactiveUtils.js";import{templateHasKey as h}from"../../core/string.js";import{property as d}from"../../core/accessorSupport/decorators/property.js";import"../../core/RandomLCG.js";import{subclass as f}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as m}from"../../core/support/UpdatingHandles.js";import y from"../../form/FormTemplate.js";import{isUtilityNetworkAssociationsElement as g,isGroupElement as _,isFieldElement as v,isRelationshipElement as I,isTextElement as x}from"../../form/support/formUtils.js";import E from"../../layers/support/ContingentValue.js";import{isEditableLayer as C}from"../../layers/support/editableLayers.js";import F from"../../layers/support/LayerContingentValuesCache.js";import{utc as b,unknown as V,system as w}from"../../time/constants.js";import{flattenAssociationInputs as A,flattenFieldInputs as j,isGroupInput as T,flattenRelationshipInputs as M,parseFormTemplateString as N,isRelationshipInput as S,isFieldInput as k,isTextElementInput as L,getNormalizedFeatureTypeInfo as R,valueIsValidContingentValue as U}from"./featureFormUtils.js";import Z from"./FieldInput.js";import{FormExpressionsManager as H}from"./FormExpressionsManager.js";import P from"./GroupInput.js";import O from"./RelationshipInput.js";import G from"./TextElementInput.js";import{createFormExpressionArcadeExecutor as W}from"../support/forms/expressions/FormExpressionArcadeExecutor.js";const $=new t({attributes:{}}),D={field:["editableExpression","requiredExpression","valueExpression","visibilityExpression"],group:["visibilityExpression"],relationship:["editableExpression","visibilityExpression"],text:["visibilityExpression"],utilityNetworkAssociations:["editableExpression","visibilityExpression"]},z="#JSAPI_CONTINGENT_VALUE_EMPTY_HASH",J="#JSAPI_CONTINGENT_VALUE_ANY_HASH",B="#JSAPI_CONTINGENT_VALUE_NULL_HASH";let K=class extends(r.EsriPromiseMixin(s.EventedAccessor)){constructor(e){super(e),this._expressionExecutorsInUse=new Set,this._expressionExecutorLookup=new Map,this._expressionsManager=null,this._contingentValuesCache=null,this._featureClone=$.clone(),this._initialFeature=$.clone(),this._timeZone=null,this._updatingHandles=new m,this.activeAssociation=null,this.editType="NA",this.contingencyConstraintViolations=new Map,this.disabled=!1,this.highlightHelper=null,this.inputs=[],this.map=null,this.callbacks=null,this.strict=!1,this.pendingSubtypeChoice=null,this._updateInputs=a(async()=>{this._stopExpressions();const{_featureClone:e,_initialFeature:t,editType:n,formTemplate:s,inputs:i,layer:o,timeZone:r}=this;if(!o)return;const a={editType:n,feature:e,initialFeature:t,layer:o,timeZone:r},l=i.slice(),u=s?.elements&&s.elements.length>0?await this._updateInputsUsingFormElements(l,s.elements,a):this._updateInputsUsingLayerFields(l,o?.fields,a);this.inputs=u,await this._startExpressions()})}initialize(){const e=l(()=>[this.layer,!!this.layer?.loaded,this.formTemplate,this.feature,this.timeZone,this.editType],([e,t])=>{null!=e&&(t?this._updatingHandles.addPromise(this._updateInputs()):e.load().catch(()=>{}))},u),t=l(()=>this._arcadeContextInfo,e=>{null!=this._expressionsManager&&(this._expressionsManager.arcadeContextInfo=e,this._evaluateExpressions(e=>e.evaluateAll()))}),n=l(()=>this.layer,e=>{const t="subtype-sublayer"===e?.type?e.parent:"feature"===e?.type?e:null;t&&this.addResolvingPromise(F.createLoadedLayerContingentValuesCache(t).then(e=>{this._contingentValuesCache=e,this.notifyChange("fieldsWithContingentValues")}))},{initial:!0});this.addHandles([e,t,n])}destroy(){this.feature=null,this.layer=null,this._contingentValuesCache=o(this._contingentValuesCache),this.highlightHelper?.removeAll(),this._updatingHandles.destroy()}get _expressionInfosLookup(){return new Map(this.formTemplate?.expressionInfos?.map(e=>[e.name,e]))}get activeAssociationInput(){return this.allAssociationInputs.find(e=>e.uid===this.associationId)}get activeRelationshipInput(){return this.allRelationshipInputs.find(e=>e.relationshipId===this.relationshipId||e.activeCategory||e.showAllEnabled)}get _arcadeContextInfo(){const{_initialFeature:e,editType:t,layer:n,map:s,spatialReference:i,timeZone:o}=this;return{layer:C(n)?n:null,originalFeature:e,editType:t,map:s,spatialReference:i,timeZone:o}}get associationId(){return this._get("associationId")}set associationId(e){null==e&&this.activeAssociationInput?.viewModel&&(this.activeAssociationInput.associatedLayer=null,this.activeAssociationInput.viewModel.activeAssociationType=null),this._set("associationId",e)}get associatedLayer(){return this.activeAssociationInput?.associatedLayer}set associatedLayer(e){this.activeAssociationInput&&(this.activeAssociationInput.associatedLayer=e)}get allAssociationInputs(){return A(this.inputs)}get allFieldInputs(){return j(this.inputs)}get allGroupInputs(){return this.inputs.filter(T)}get allRelationshipInputs(){return M(this.inputs)}get _layerFieldsByName(){return new Map(this.layer?.fields.map(e=>[e.name,e]))}get feature(){return this._get("feature")}set feature(e){const t=this._get("feature");this._featureClone=e?e.clone():$.clone(),this._initialFeature=this._featureClone.clone(),this._expressionsManager&&(this._expressionsManager.feature=this._featureClone),e?(this._resetFieldInputValues(this._featureClone),this.allRelationshipInputs.forEach(t=>t.feature=e)):(this.inputs.forEach(e=>e.destroy()),this.inputs.length=0),t!==e&&(this.pendingSubtypeChoice=null),this.contingencyConstraintViolations.clear(),this._set("feature",e)}get fieldsWithContingentValues(){if(null==this._contingentValuesCache)return new Set;const e=this._contingentValuesCache.fieldGroups.flatMap(e=>e.fields);return new Set(e)}get formTemplate(){return this.layer&&"formTemplate"in this.layer?this.layer.formTemplate:null}set formTemplate(e){void 0===e?this._clearOverride("formTemplate"):this._override("formTemplate",e)}get formDescription(){const{formTemplate:e,layer:t}=this;return e?.description&&t?N({label:e.description,attributes:this.getValues(),fieldsIndex:t.fieldsIndex,timeZone:this.timeZone}):null}get formTitle(){const{formTemplate:e,layer:t}=this;return e?.title&&t?N({label:e.title,attributes:this.getValues(),fieldsIndex:t.fieldsIndex,timeZone:this.timeZone}):null}get formHeaderVisible(){const{activeRelationshipInput:e,activeAssociationInput:t,formDescription:n,formTitle:s}=this;return!(e||t||!n&&!s)}get joinedContingentValues(){return this._joinContingentValues()}get layer(){return this.feature?.sourceLayer&&"applyEdits"in this.feature.sourceLayer?this.feature.sourceLayer:null}set layer(e){this._override("layer",e)}get relationshipId(){return this._get("relationshipId")}set relationshipId(e){const t=this.allRelationshipInputs;if(null!=e&&e===this.relationshipId||t.forEach(e=>{e.showAllEnabled=!1,e.activeCategory=null}),null!=e){const n=t.find(t=>t.relationshipId===e);n&&(n.showAllEnabled=!0)}this._set("relationshipId",e)}get spatialReference(){return this.layer?.spatialReference??null}set spatialReference(e){this._override("spatialReference",e)}get state(){return this.layer?.loaded?"ready":"disabled"}get submittable(){return!!this.valid||this.allFieldInputs.filter(e=>!e.valid).every(({submittable:e})=>e)}get timeZone(){const{layer:e}=this;if(e&&"datesInUnknownTimezone"in e&&e.datesInUnknownTimezone)return b;const t=e&&"preferredTimeZone"in e&&e.preferredTimeZone;return this._timeZone===V?t||b:this._timeZone||w}set timeZone(e){this._timeZone=e}get updating(){return this._updatingHandles.updating}get valid(){const e=this.allFieldInputs;return e.length>0&&e.every(({valid:e})=>e)}findField(e){return this.allFieldInputs.find(t=>t.name===e)}findGroup(e){return this.allGroupInputs.find(t=>t.id===e)}getFieldValueOptionsForField(e,t){const n=this.findField(e);if(!n)return[[],[],[]];const s="coded-value"===n.domain?.type?n.domain.codedValues.map(({name:e,code:t})=>({name:e,value:t})):[],i=null==n.value||s.some(e=>e.value===n.value)?[]:[{name:`${n.value}`,value:n.value}],o=this.fieldsWithContingentValues.has(e)?this._getContingentValueOptionsForField(e,t):[];if(o.length>0){const e=new Set(o.map(e=>e.value));return[o,s.filter(t=>!e.has(t.value)),i]}return[s,[],i]}getValue(e){const t=this.layer?.getField(e);if(null!=t)return this._featureClone.getAttribute(t.name)??null}setValue(e,t){const{_featureClone:n,strict:s}=this,i=this.findField(e);t=""===t?null:t,i&&n.getAttribute(e)!==t&&(i.value=t,s&&!i.valid||(this._afterValueChange(i),this._evaluateExpressions(t=>t.evaluateInvalidated([e]))))}getValues(){return{...this._featureClone.attributes}}overrideInitialFeature(e){this._initialFeature=e}submit(){const e=this.allFieldInputs,t=new Set(e.filter(e=>e.valid).map(({name:e})=>e)),n=e.filter(e=>!e.valid).map(({name:e})=>e),s=this.getValues();if(this.validateContingencyConstraints(s,{includeIncompleteViolations:!0}).length>0)for(const[i,o]of this.contingencyConstraintViolations.entries())"error"===o.type&&(t.delete(i),n.push(i));this.notifyChange("submittable"),this.notifyChange("valid"),this.emit("submit",{valid:[...t],invalid:n,values:s})}validateContingencyConstraints(e,t){const{_contingentValuesCache:n}=this,s=new Map;if(this.contingencyConstraintViolations=s,null==n)return[];const{invalid:i,incomplete:o}=n.validateContingencyConstraints(e),r=[...i,...t?.includeIncompleteViolations?o:[]];for(const a of r)for(const e of a.fieldGroup.fields)s.set(e,a);return r}notifyFeatureGeometryChanged(){const{feature:e,_featureClone:t}=this;e&&(t.geometry=e.geometry,this._evaluateExpressions(e=>e.evaluateInvalidatedByGeometry()))}applySubtypeDefaults(e){const{defaultValues:t}=e,{allFieldInputs:n}=this;for(const{name:s}of n){const e=t[s];null!=e&&this.setValue(s,e)}}_emitChangeEvent({name:e,valid:t,value:n}){this.emit("value-change",{layer:this.layer,feature:this.feature,fieldName:e,value:n,valid:t})}async _evaluateExpressions(e){const t=this._expressionsManager;null!=t&&await this._updatingHandles.addPromise(e(t).finally(()=>this._afterExpressionsEvaluated()))}async _updateInputsUsingFormElements(e,t,n){const s=new Map;for(const r of e)if(T(r)){s.set(r.element,r);for(const e of r.inputs)e.element&&s.set(e.element,e)}else r.element&&s.set(r.element,r);const i=new Map,o=await this._updateInputsUsingFormElementsRecursive({existingInputsByElement:s,updatedElements:t.filter(e=>this._isSupportedElement(e)),sharedInitializationProperties:n,group:null,newExpressionExecutorPromises:i});for(const[r,a]of s.entries())s.delete(r),a.destroy();return await Promise.all(Array.from(i.values())),o}async _updateInputsUsingFormElementsRecursive(e){const{existingInputsByElement:t,updatedElements:n,sharedInitializationProperties:s,group:i,newExpressionExecutorPromises:o}=e,r=[];for(const a of n){const e=t.has(a),n=e?t.get(a):g(a)?await this._makeUtilityNetworkAssociationInputFromElement(a,s,i):this._makeInputFromElement(a,s,i);if(n){if(r.push(n),await p(()=>!n.updating),this._assignExpressionExecutors(n,a,o),e)if(t.delete(a),T(n)){const{feature:e,timeZone:t}=s;n.set({feature:e,timeZone:t})}else if(S(n)){const e=this.relationshipId===a.relationshipId;n.set(s),n.set({map:this.map,showAllEnabled:e})}else g(n)?(n.set(s),n.set({map:this.map})):n.set(s);if(_(a)){const e=a.elements.filter(e=>this._isSupportedElement(e));n.inputs=await this._updateInputsUsingFormElementsRecursive({existingInputsByElement:t,updatedElements:e,sharedInitializationProperties:s,group:n,newExpressionExecutorPromises:o})}}}return r}_updateInputsUsingLayerFields(e,t,n){if(!Array.isArray(t))return i.getLogger(this).warn(this.declaredClass,"No attribute fields found."),[];const s=new Map;for(const i of e)if(T(i)){for(const e of i.inputs)e.destroy();i.inputs.length=0,i.destroy()}else S(i)?i.destroy():k(i)&&(null!==i.element?i.destroy():s.set(i.field,i));const o=[];for(const i of t){const e=n.feature?.getAttribute(i.name)??null,t=s.get(i)??new Z({field:i,preservesValueWhenHidden:this.formTemplate?.preserveFieldValuesWhenHidden});o.push(t.set({...n,value:e})),s.delete(i)}for(const[i,r]of s.entries())s.delete(i),r.destroy();return o}_resetFieldInputValues(e){for(const t of this.allFieldInputs)t.value=e.getAttribute(t.name)??null}_makeInputFromElement(e,t,s){return _(e)?Y(e,t):v(e)?this._makeFieldInputFromElement(e,t,s):I(e)?this._makeRelationshipInputFromElement(e,t,s):g(e)?this._makeUtilityNetworkAssociationInputFromElement(e,t,s):x(e)?q(e,t):g(e)?this._makeUtilityNetworkAssociationInputFromElement(e,t,s):n()}_makeFieldInputFromElement(e,t,n){const{editType:s,feature:i,initialFeature:o,layer:r,timeZone:a}=t,{fieldName:l}=e,u=l&&this._layerFieldsByName.get(l);return u?new Z({editType:s,element:e,field:u,value:i?.getAttribute(e.fieldName)??null,feature:i,initialFeature:o,layer:r,group:n,preservesValueWhenHidden:this.formTemplate?.preserveFieldValuesWhenHidden,timeZone:a}):null}_makeRelationshipInputFromElement(e,t,n=null){const{map:s}=this,{feature:i,layer:o,timeZone:r}=t,a=new O({element:e,feature:i,group:n,layer:o,map:s,timeZone:r});return a.addHandles(c(()=>a.relatedLayer,"edits",()=>this._evaluateExpressions(e=>e.evaluateAsyncExpressions()))),a}async _makeUtilityNetworkAssociationInputFromElement(e,t,n=null){const{map:s}=this,{feature:i,layer:o,timeZone:r}=t;return new(0,(await import("./UtilityNetworkAssociationInput.js")).default)({element:e,feature:i,group:n,layer:o,map:s,timeZone:r})}_assignExpressionExecutors(e,t,n){const s=D[t.type],i=[];for(const o of s){const s=`${o}Executor`;if(e[s]){this._useExecutor(e[s]);continue}const r=t[o];if(null!=r&&""!==r){const t=this._expressionInfosLookup.get(r)?.expression??r;i.push(this._getOrCreateExecutorForExpression(t,n).then(t=>{e[s]=this._useExecutor(t)}))}}return L(e)&&i.push(...this._assignTextElementExpressionExecutors(e,n)),i}_assignTextElementExpressionExecutors(e,t){const{_expressionInfosLookup:n}=this,s=[];for(const o of e.expressionsUsed){const r=n.get(o);null!=r?s.push(this._getOrCreateExecutorForExpression(r.expression,t).then(t=>e.setExpressionExecutor(o,this._useExecutor(t)))):i.getLogger(this).error("feature-form:expression-not-found",`Could not find expressionInfo object with name '${o}'`)}for(const i of e.fieldsUsed){const n=`return $feature['${i}'];`;s.push(this._getOrCreateExecutorForExpression(n,t).then(t=>e.setFieldExecutor(i,this._useExecutor(t))))}return s}async _getOrCreateExecutorForExpression(e,t){const{_expressionExecutorLookup:n}=this;if(n.has(e))return n.get(e);if(t.has(e))return t.get(e);const s=W(e,this.layer);t.set(e,s);const i=await s;return n.set(e,i),i}_createExpressionsManager(e){const{_arcadeContextInfo:t,_featureClone:n,allFieldInputs:s,formTemplate:i}=this;this._expressionsManager=new H({executors:e,feature:n,arcadeContextInfo:t,fieldInputs:s,preserveFieldValuesWhenHidden:!0===i?.preserveFieldValuesWhenHidden})}async _startExpressions(){if(0===this._expressionExecutorsInUse.size)return;const e=Array.from(this._expressionExecutorsInUse);this._createExpressionsManager(e),this._evaluateExpressions(e=>e.evaluateAll())}_stopExpressions(){this._expressionsManager=o(this._expressionsManager),this._expressionExecutorsInUse.clear()}_useExecutor(e){return this._expressionExecutorsInUse.add(e),e}_afterValueChange(e){const{name:t,value:n}=e,{_featureClone:s,formTemplate:i,layer:o}=this;if(!o)return;const r=s.getAttribute(t);s.setAttribute(t,n);const{typeFieldName:a,types:l}=R(o);if((e.isSubtypeField||t===a)&&n!==r){if("subtype-sublayer"===o.type){const e=o.parent?.findSublayerForFeature(s);e&&(this.feature&&(this.feature.sourceLayer=e),s.sourceLayer=e)}const e=new Set;for(const t of l)if(t.domains&&"object"==typeof t.domains)for(const n of Object.keys(t.domains))e.add(n);for(const t of e){const e=this.findField(t);e&&e.notifyChange("domain")}this.notifyChange("joinedContingentValues")}if(null!=i){const{description:e,title:n}=i;n&&h(n,t)&&this.notifyChange("formTitle"),e&&h(e,t)&&this.notifyChange("formDescription")}this._emitChangeEvent(e)}_afterExpressionsEvaluated(){const{_featureClone:e}=this;for(const t of this.allFieldInputs)t.value!==e.getAttribute(t.name)&&this._afterValueChange(t)}_joinContingentValues(){const e=this._contingentValuesCache;if(null==e)return[];const{typeFieldName:t}=R(this.layer),n=t?this.getValue(t):null,s=[];for(const r of e.fieldGroups){const{contingencies:e,fields:t,name:i}=r,o=[];for(const s of e)s.isRetired||null!=s.subtype&&s.subtype.code!==n||o.push({values:s.values});o.length>0&&s.push({name:i,fields:t,contingencies:o})}const[i,o]=this._generateJoinPlan(s);return[...i.flatMap(e=>this._joinFieldGroupContingencies(e)),...o.flatMap(e=>e.contingencies)]}_generateJoinPlan(e){const t=new Map,n=[],s=new Set;for(const l of e)for(const e of l.fields)if(t.has(e)){const i=t.get(e),o=l,r=[i.name,o.name].sort().join("|");if(s.has(r))continue;n.push([i,o]),s.add(r),t.set(e,o)}else t.set(e,l);const i=new Set(n.flat()),o=new Set(e);for(const l of i)o.delete(l);const r=new Map,a=new Map;for(const l of new Set(n.flat())){const e=Symbol(l.name);r.set(e,new Set([l])),a.set(l,e)}for(const[l,u]of n){const e=a.get(l),t=a.get(u);if(e===t)continue;const n=r.get(e),s=r.get(t);for(const i of s)n.add(i),a.set(i,e);r.delete(t)}return[[...r.values()].map(e=>[...e]),[...o]]}_joinFieldGroupContingencies(e){const t=e.slice(),n=t.shift();let s=t.shift(),i=this._generateJoinKey(n.fields,s.fields),o=new Set([...n.fields,...s.fields]),r=new Map;for(const l of n.contingencies){const[e]=this._hashContingency(l,i.codedValueFields,!0);r.has(e)?r.get(e)?.push(l):r.set(e,[l])}for(;t.length>0;){const e=new Map,n=t.shift(),a=this._generateJoinKey(o,n.fields);for(const t of s.contingencies){const[n,s]=this._hashContingency(t,i.codedValueFields),o=s?this._findMatchingContingenciesWithAnyHashMask(r,n):r.get(n);if(r.has(J)&&o?.push(...this._findMatchingContingenciesContainingAny(t,r.get(J),i.codedValueFields)),null!=o)for(const r of o){const n=i.rangeFields.length>0?this._joinContingenciesWithRangeDomains(r,t,i.rangeFields):this._joinContingencies(r,t);if(null==n)break;const[s]=this._hashContingency(n,a.codedValueFields,!0);e.has(s)?e.get(s)?.push(n):e.set(s,[n])}}r=e,s=n,i=a,o=new Set([...o,...s.fields])}const a=[];for(const l of s.contingencies){const[e,t]=this._hashContingency(l,i.codedValueFields),n=t?this._findMatchingContingenciesWithAnyHashMask(r,e):r.get(e);if(r.has(J)&&n.push(...this._findMatchingContingenciesContainingAny(l,r.get(J),i.codedValueFields)),null!=n)for(const s of n){const e=i.rangeFields.length>0?this._joinContingenciesWithRangeDomains(s,l,i.rangeFields):this._joinContingencies(s,l);null!=e&&a.push(e)}}return a}_joinContingencies(e,t){const n={values:{...e.values,...t.values}};for(const[s,i]of Object.entries(n.values))"any"===i.objectType&&null!=e.values[s]&&(n.values[s]=e.values[s]);return n}_joinContingenciesWithRangeDomains(e,t,n){const s=this._joinContingencies(e,t);for(const i of n){const n=e.values[i],o=t.values[i],{leftIsNull:r,rightIsNull:a,bothAreNull:l,leftIsAny:u,rightIsAny:p,bothAreAny:c,leftIsRange:h,rightIsRange:d}=this._compareObjectTypes(n.objectType,o.objectType);if(l||c)continue;if(r&&p||a&&u){s.values[i]=new E({objectType:"null"});continue}if(r&&d||a&&h)return null;u?(n.minValue=-1/0,n.maxValue=1/0):p&&(o.minValue=-1/0,o.maxValue=1/0);const f=Math.max(n.minValue,o.minValue),m=Math.min(n.maxValue,o.maxValue);if(f>m)return null;s.values[i]=new E({objectType:"range",minValue:f,maxValue:m})}return s}_findMatchingContingenciesContainingAny(e,t,n){return t.filter(t=>n.every(n=>{const s=t.values[n],i=e.values[n];return"any"===s.objectType||"any"===i.objectType||s.codedValue?.code===i.codedValue?.code}))}_findMatchingContingenciesWithAnyHashMask(e,t){const n=RegExp(`${t}$`),s=[];for(const[i,o]of e){if(i===J)break;n.test(i)&&s.push(...o)}return s}_generateJoinKey(e,t){const n=Array.isArray(e)?new Set(e):e,s=Array.isArray(t)?new Set(t):t,i=n.size<s.size?n:s,o=i===n?s:n,{feature:r}=this,a=new Set,l=new Set;for(const u of i)if(o.has(u)){const e=this.layer?.getFieldDomain(u,{feature:r??void 0,excludeImpliedDomains:!0});if(null==e)continue;switch(e.type){case"coded-value":a.add(u);break;case"range":l.add(u)}}return{codedValueFields:[...a],rangeFields:[...l]}}_contingencyIsValid(e,t){const n={};for(const{name:s,value:i}of this.allFieldInputs)this.fieldsWithContingentValues.has(s)&&null!=i&&s!==e&&(n[s]=i);return Object.entries(n).every(([e,n])=>!t.values.hasOwnProperty(e)||U(n,t.values[e]))}_getContingentValueOptionsForField(e,t){const n=this.joinedContingentValues.slice(),s=new Map,i={code:"",name:t??"No value"};for(const o of n){const t=o.values[e];if("code"===t?.objectType||"null"===t?.objectType){const{code:n,name:r}=t.codedValue&&"null"!==t.objectType?t.codedValue:i;!s.has(n)&&this._contingencyIsValid(e,o)&&s.set(n,{name:r,value:n})}}return[...s.values()]}_hashContingency(e,t,n=!1){if(t.length<1)return[z,!1];const s=[];let i=!1;for(const o of t){const t=e.values[o];if("any"===t.objectType){if(n)return[J,!0];i=!0,s.push(`${o}:.*`)}else"null"===t.objectType?s.push(`${o}:${B}`):s.push(`${o}:${t.codedValue?.code}`)}return[s.sort().join("&"),i]}_compareObjectTypes(e,t){return{leftIsNull:"null"===e,rightIsNull:"null"===t,bothAreNull:"null"===e&&"null"===t,leftIsAny:"any"===e,rightIsAny:"any"===t,bothAreAny:"any"===e&&"any"===t,leftIsRange:"range"===e,rightIsRange:"range"===t}}_isSupportedElement(e){return"field"===e.type||"group"===e.type||"relationship"===e.type||"text"===e.type||"utilityNetworkAssociations"===e.type||(i.getLogger(this).warn("form-info::unsupported-element-type","Only element types 'field', 'group' and 'relationship' are supported",`Element ${e.label} has unsupported type '${e.type}'`),!1)}get test(){return{featureClone:this._featureClone}}};function Y(e,t){const{feature:n,layer:s}=t;return new P({element:e,inputs:[],feature:n,layer:s})}function q(e,t,n=null){const{feature:s,layer:i,timeZone:o}=t;return new G({element:e,feature:s,group:n,layer:i,timeZone:o})}e([d()],K.prototype,"_expressionInfosLookup",null),e([d()],K.prototype,"_featureClone",void 0),e([d()],K.prototype,"_timeZone",void 0),e([d()],K.prototype,"activeAssociation",void 0),e([d()],K.prototype,"activeAssociationInput",null),e([d()],K.prototype,"activeRelationshipInput",null),e([d()],K.prototype,"_arcadeContextInfo",null),e([d()],K.prototype,"associationId",null),e([d()],K.prototype,"associatedLayer",null),e([d()],K.prototype,"allAssociationInputs",null),e([d()],K.prototype,"allFieldInputs",null),e([d()],K.prototype,"allGroupInputs",null),e([d()],K.prototype,"allRelationshipInputs",null),e([d()],K.prototype,"_layerFieldsByName",null),e([d()],K.prototype,"editType",void 0),e([d()],K.prototype,"contingencyConstraintViolations",void 0),e([d()],K.prototype,"disabled",void 0),e([d()],K.prototype,"feature",null),e([d()],K.prototype,"fieldsWithContingentValues",null),e([d({type:y})],K.prototype,"formTemplate",null),e([d()],K.prototype,"formDescription",null),e([d()],K.prototype,"formTitle",null),e([d()],K.prototype,"formHeaderVisible",null),e([d()],K.prototype,"highlightHelper",void 0),e([d()],K.prototype,"inputs",void 0),e([d()],K.prototype,"joinedContingentValues",null),e([d()],K.prototype,"layer",null),e([d()],K.prototype,"map",void 0),e([d()],K.prototype,"callbacks",void 0),e([d()],K.prototype,"relationshipId",null),e([d()],K.prototype,"spatialReference",null),e([d()],K.prototype,"state",null),e([d()],K.prototype,"strict",void 0),e([d()],K.prototype,"submittable",null),e([d()],K.prototype,"timeZone",null),e([d()],K.prototype,"updating",null),e([d()],K.prototype,"valid",null),e([d()],K.prototype,"pendingSubtypeChoice",void 0),e([d()],K.prototype,"getValues",null),e([d()],K.prototype,"submit",null),e([d()],K.prototype,"test",null),K=e([f("esri.widgets.FeatureForm.FeatureFormViewModel")],K);const Q=K;export{Q as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import{getAssetUrl as t}from"../../assets.js";import r from"../../Graphic.js";import s from"../../PopupTemplate.js";import o from"../../core/Accessor.js";import{isSome as i}from"../../core/arrayUtils.js";import l from"../../core/Collection.js";import a from"../../core/Error.js";import n from"../../core/Evented.js";import u from"../../core/Logger.js";import{mappedFind as c}from"../../core/maybe.js";import{eachAlways as h,after as p}from"../../core/promiseUtils.js";import{watch as g,initial as d,whenOnce as m}from"../../core/reactiveUtils.js";import{property as y}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import{subclass as f}from"../../core/accessorSupport/decorators/subclass.js";import S from"../../geometry/Point.js";import _ from"../../geometry/SpatialReference.js";import{getPointFromGeometry as v,getPointWithElevation as w}from"../../geometry/support/geometryUtils.js";import{onLocaleChange as b}from"../../intl/locale.js";import{fetchMessageBundle as x}from"../../intl/messages.js";import L from"../../portal/Portal.js";import{isApiKeyApplicable as I}from"../../support/apiKeyUtils.js";import T from"../../symbols/PictureMarkerSymbol.js";import R from"../../symbols/SimpleFillSymbol.js";import E from"../../symbols/SimpleLineSymbol.js";import F from"../../symbols/TextSymbol.js";import{highlightsSupported as j}from"../../views/support/layerViewUtils.js";import P from"./LayerSearchSource.js";import C from"./LocatorSearchSource.js";import G from"./SearchSource.js";import{isArcGISWorldGeocoder as O,meteredArcGISLocatorUrl as A,isProxiedArcGISWorldGeocoder as N,isMeteredArcGISWorldGeocoder as D}from"./support/locatorUtils.js";import{supported as M,getCurrentPosition as V,positionToPoint as J}from"../support/geolocationUtils.js";import U from"../support/GoTo.js";function k(e,t){return e.hasOwnProperty(t)&&null!=e[t]&&""!==e[t]}const H=()=>x("esri/widgets/Search/t9n/Search"),B="highlight",Q=l.ofType({key:e=>e.layer?"layer":"locator",base:G,typeMap:{layer:P,locator:C}}),Z=_.WGS84,q="esri/images/search/search-symbol-32.png",z=/<[\s\S]*?>/g,K=-1;let W=class extends(U(n.EventedMixin(o))){constructor(e){super(e),this._gotoController=null,this._searching=null,this._updatingPromise=null,this._createdFeatureLayers=[],this.autoNavigate=!0,this.autoSelect=!0,this.defaultPopupTemplate=null,this.defaultSources=new Q,this.defaultSymbols={point:new T({url:t(q),size:24,width:24,height:24}),polyline:new E({color:[130,130,130,1],width:2}),polygon:new R({color:[235,235,235,.4],outline:{color:[130,130,130,1],width:2}})},this.includeDefaultSources=!0,this.maxInputLength=128,this.maxResults=6,this.maxSuggestions=6,this.messages=null,this.minSuggestCharacters=3,this.popupEnabled=!0,this.popupTemplate=null,this.portal=L.getDefault(),this.resultCount=null,this.resultGraphicEnabled=!0,this.resultGraphic=null,this.results=null,this.selectedSuggestion=null,this.searchAllEnabled=!0,this.selectedResult=null,this.sources=new Q,this.suggestionDelay=350,this.suggestionCount=null,this.suggestions=null,this.suggestionsEnabled=!0,this.view=null}initialize(){const e=async()=>{const e=await H();this.messages=e,this.defaultPopupTemplate=new s({title:e.searchResult,content:"{Match_addr}"})};e(),this.addHandles([g(()=>[this.includeDefaultSources,this.view,this.portal],()=>this._update(),d),b(e)])}destroy(){this._destroyFeatureLayers(),this._abortGoTo(),this.clearGraphics()}static{this.ALL_INDEX=K}get activeSource(){return this.allSources.at(this.activeSourceIndex)??null}get activeSourceIndex(){return 1===this.allSources.length||!this.searchAllEnabled?0:K}set activeSourceIndex(e){this._overrideIfSome("activeSourceIndex",e)}get allPlaceholder(){return this.messages?.allPlaceholder}set allPlaceholder(e){this._overrideIfSome("allPlaceholder",e)}get allSources(){const{sources:e,defaultSources:t,includeDefaultSources:r}=this,s="function"==typeof r?r.call(null,{sources:e,defaultSources:t}):r?t.concat(e):e,o=this._get("allSources")||new Q;return o.removeAll(),o.addMany(s.filter(Boolean)),o}get locationEnabled(){return this._get("locationEnabled")||M()}set locationEnabled(e){if(void 0===e)return void this._clearOverride("locationEnabled");const t=M();if(e&&!t){const e=new a("locationEnabled:geolocation-unsupported","Geolocation API is unsupported.",{geolocation:navigator.geolocation});u.getLogger(this).error(e)}this._override("locationEnabled",!!e&&t)}get placeholder(){const{allSources:e,activeSourceIndex:t,allPlaceholder:r}=this;if(t===K)return r??"";const s=e.at(t);return s?.placeholder??""}set searchTerm(e){this._set("searchTerm",e||""),this.clearGraphics(),this.selectedSuggestion&&this.selectedSuggestion.text!==e&&this._set("selectedSuggestion",null),""===e&&this._clear()}get searchTerm(){return this._get("searchTerm")||""}get state(){return this._searching?"searching":this.updating?"loading":0===this.allSources.length?"disabled":"ready"}get updating(){return null!=this._updatingPromise}clear(){this.searchTerm=""}clearGraphics(){this._removeHighlight(),this._closePopup();const{view:e,resultGraphic:t}=this;e&&t&&e.graphics.remove(t),this._set("resultGraphic",null)}search(e,t){this.emit("search-start"),this.clearGraphics();const r=this._createSuggestionForSearch(e),s=(async()=>{try{await this.when();const e=await this._getResultsFromSources(r,t);if(t?.signal?.aborted)return null;const s={activeSourceIndex:this.activeSourceIndex,searchTerm:r.text??"",numResults:0,numErrors:0,errors:[],results:[]};this._formatResponse(s,e,r);const o=this._getFirstResult(s.results),i=r.location&&o?o.name:r.text,l=i?.replace(z,"");return this._set("searchTerm",l),(r.key&&"number"==typeof r.sourceIndex||r.location)&&this._set("selectedSuggestion",r),this._set("results",s.results),this._set("resultCount",s.results.reduce((e,t)=>e+(t.results?.length??0),0)),this.emit("search-complete",s),await this._selectFirstResult(o),s}finally{this._clearSearching()}})();return this._searching=s,s}async searchNearby(e){if(!this.locationEnabled){const e=new a("searchNearby:geolocation-unsupported","Geolocation API is unsupported.",{geolocation:navigator.geolocation});throw u.getLogger(this).error(e),e}const t=(async()=>{try{const t=await V(),r=await J({position:t,view:this.view},e);return await this.search(r,e)}finally{this._clearSearching()}})();return this._searching=t,t}async select(e){if(this.clearGraphics(),!e){const t=new a("select:missing-parameter","Cannot select without a searchResult.",{searchResult:e});throw u.getLogger(this).error(t),t}const{view:t}=this,s=k(e,"sourceIndex")?e.sourceIndex:this._getSourceIndexOfResult(e),o=null!=s?this.allSources.at(s):null;if(!o){const e=new a("select:missing-source","Cannot select without a source.",{source:o});throw u.getLogger(this).error(e),e}const i=o instanceof P?this._getLayerSourcePopupTemplate(o):o.popupTemplate,l=o.resultSymbol||this._getDefaultSymbol(e),n=k(o,"resultGraphicEnabled")?o.resultGraphicEnabled:this.resultGraphicEnabled,c=k(o,"autoNavigate")?o.autoNavigate:this.autoNavigate,p=k(o,"popupEnabled")?o.popupEnabled:this.popupEnabled,g=p?i||this.popupTemplate||this.defaultPopupTemplate:null,{feature:d}=e;if(!d){const e=new a("select:missing-feature","Cannot select without a feature.",{feature:d});throw u.getLogger(this).error(e),e}const{attributes:m,geometry:y,layer:f,sourceLayer:S}=d,_=y?v(y):null,b={layerViewQuery:this._getLayerView(d),elevationQuery:t&&null!=_?w(_,t):Promise.resolve(_)},x=await h(b),L=x.layerViewQuery.value,I=x.elevationQuery.value;l instanceof F&&(l.text=e.name);const T=t&&c?e.target||e.extent:null,R=null!=T?this._goToSearchResult(T):Promise.resolve();await R;const E=L?d:new r({geometry:y,symbol:l,attributes:m,layer:f,sourceLayer:S,popupTemplate:g}),C=t?.popup,G=C&&p&&E.getEffectivePopupTemplate(C.defaultPopupTemplateEnabled);return G&&await t.openPopup({features:[E],location:I}),L&&j(L)&&!G&&this._highlightFeature({graphic:E,layerView:L}),!L&&n&&t&&t.graphics.push(E),this._setResultFloor(e),this._set("selectedResult",e),this._set("resultGraphic",E),this.emit("select-result",{result:e,source:o,sourceIndex:s}),e}async suggest(e,t,r){const s=e||this.searchTerm;this.emit("suggest-start",{searchTerm:s}),await this._suggestTimer(t,r);const o=await this._suggestImmediate(s,r);return this._set("suggestions",o?.results),this._set("suggestionCount",o?.results.reduce((e,t)=>e+(t.results?.length??0),0)??null),this.emit("suggest-complete",o),o}async when(){await m(()=>!this.updating)}async _update(){const{portal:e,view:t}=this;if(this.includeDefaultSources){const r=this._updatingPromise=h([e?.load(),t?.when()]);if(this.destroyed)return;if(await r,r!==this._updatingPromise)return}await m(()=>this.messages),this.destroyed||this._updateDefaultSources(),this._updatingPromise=null}_clearSearching(){this._searching=null}_convertHelperServices(){const e=this.portal?.helperServices?.geocode;if(!e)return[];return e.map(e=>{if(!1===e.placefinding)return;const t=O(e.url)&&I(e.url)?{url:A}:null,r=C.fromJSON({...e,...t}),s=r.url;if(O(s)||N(s)||D(s)){const e=r.outFields??["Addr_type","Match_addr","StAddr","City"],t=(r.placeholder||this.messages?.placeholder)??"",s="number"==typeof r.defaultZoomScale?r.defaultZoomScale:2500;r.singleLineFieldName="SingleLine",r.outFields=e,r.placeholder=t,r.defaultZoomScale=s}return r.singleLineFieldName?r:void 0}).filter(i)}_destroyFeatureLayers(){this._createdFeatureLayers.forEach(e=>e?.destroy()),this._createdFeatureLayers=[]}_getLayerSources(e,t){const r=this.view?.map;return e.map(e=>{const s=r.findLayerById(e.id);if(!s)return;const o=this._getLayerJSON(e),i=P.fromJSON(o);return i.placeholder=t,this._getLayer(s,o).then(e=>{i.layer=e}),i}).filter(i).toArray()}_getTableSources(e,t){const r=this.view?.map;return e.map(e=>{if(!e.id)return;const s=r.findTableById(e.id);if(!s)return;const o=this._getLayerJSON(e),i=P.fromJSON(o);return i.placeholder=t,this._getLayer(s,o).then(e=>{i.layer=e}),i}).filter(i).toArray()}_convertApplicationProperties(){const e=this.view?.map,t=e?.applicationProperties?.viewing?.search;if(!t)return[];const{enabled:r,hintText:s,layers:o,tables:i}=t;if(!r)return[];return[...this._getLayerSources(o,s),...this._getTableSources(i,s)]}async _getSubLayer(e,t){if(await e.load(),!e.allSublayers)throw new Error;const r=e.allSublayers.find(e=>e.id===t.subLayer);if(!r)throw new Error;const s=await(r.createFeatureLayer?.());if(!s)throw new Error;return this._createdFeatureLayers.push(s),s}async _getBuildingSubLayer(e,t){await e.load();const r=e.allSublayers.find(e=>e.id===t.subLayer);if("building-component"!==r?.type)throw new Error;if(await r.load(),null==r.associatedLayer)throw new Error;return await r.associatedLayer.load(),r}async _getLayer(e,t){if("feature"===e.type||"scene"===e.type||"csv"===e.type||"geojson"===e.type||"ogc-feature"===e.type)return e;if("map-image"===e.type)try{return await this._getSubLayer(e,t)}catch(r){const t=new a("search:create-featurelayer","Could not create a FeatureLayer from the MapImageLayer",{layer:e});return u.getLogger(this).error(t),null}return"building-scene"===e.type?this._getBuildingSubLayer(e,t):null}_getLayerJSON(e){return"function"==typeof e.toJSON?e.toJSON():e}_updateDefaultSources(){const{defaultSources:e,includeDefaultSources:t}=this;this._destroyFeatureLayers(),e.removeAll(),t&&e.addMany([...this._convertApplicationProperties(),...this._convertHelperServices()])}_abortGoTo(){this._gotoController&&this._gotoController.abort(),this._gotoController=null}_clear(){this._abortGoTo(),this._set("resultCount",null),this._set("results",null),this._set("suggestions",null),this._set("suggestionCount",null),this._set("selectedResult",null),this._set("selectedSuggestion",null),this.emit("search-clear")}_closePopup(){const e=this.view?.popup,{resultGraphic:t}=this;if(!e||!t)return;const r="selectedFeature"in e,s=r?e.selectedFeature:null;r&&(s&&s===t)&&e.close()}_suggestTimer(e,t){const r=null!=e?e:this.suggestionDelay;return p(r,null,t?.signal)}_createLocationForSearch(e){return e instanceof r&&e.geometry?v(e.geometry):e instanceof S?e:Array.isArray(e)&&2===e.length?new S({longitude:e[0],latitude:e[1]}):null}_createSuggestionForSearch(e){if(e&&k(e,"key")&&k(e,"text")&&k(e,"sourceIndex"))return e;const t=this._createLocationForSearch(e),r="string"==typeof e?e:this.searchTerm,{selectedSuggestion:s,selectedResult:o}=this,i=!e&&s&&o,l=i&&s.key===o.key&&s.sourceIndex===o.sourceIndex,a=i&&s.location;return l||a?s:{location:t,text:t?"":r,sourceIndex:null,key:null}}_getFirstResult(e){return c(e,({results:e})=>e?.[0])??null}async _selectFirstResult(e){return this.autoSelect&&e?this.select(e):null}async _suggestImmediate(e,t){await this.when();const r=await this._getSuggestionsFromSources(e,t);if(t?.signal?.aborted)return null;const s={activeSourceIndex:this.activeSourceIndex,searchTerm:e??"",numResults:0,numErrors:0,errors:[],results:[]};return this._formatResponse(s,r),s}_formatSourceResponse(e,t,r){const s=t?.value||[],o=t?.error,i=this.allSources.at(r);if(o){const t={sourceIndex:r,source:i,error:o};e.errors.push(t),u.getLogger(this).error(o),e.numErrors++}else{const t={sourceIndex:r,source:i,results:s};e.results.push(t),e.numResults+=s.length}}_formatResponse(e,t,r){if(t)if(e.activeSourceIndex===K){const s=r&&k(r,"sourceIndex")&&-1!==r.sourceIndex?r.sourceIndex:void 0;t.forEach((t,r)=>{const o=void 0!==s?s:r;this._formatSourceResponse(e,t,o)})}else this._formatSourceResponse(e,t[0],e.activeSourceIndex)}async _getResultsFromSources(e,t){const{allSources:r}=this,s=!e.location&&k(e,"sourceIndex")?e.sourceIndex:this.activeSourceIndex,o=[];if(!r.length){const e=new a("search:no-sources-defined","At least one source is required.",{allSources:r});throw u.getLogger(this).error(e),e}return s===K?r.forEach((r,s)=>{o.push(this._getResultsFromSource(e,s,t))}):o.push(this._getResultsFromSource(e,s,t)),h(o)}async _getSuggestionsFromSources(e,t){const{allSources:r,activeSourceIndex:s}=this,o=[];if(!r.length){const e=new a("suggest:no-sources-defined","At least one source is required.",{allSources:r});throw u.getLogger(this).error(e),e}return s===K?r.forEach((r,s)=>{o.push(this._getSuggestionsFromSource(e,s,t))}):o.push(this._getSuggestionsFromSource(e,s,t)),h(o)}async _getResultsFromSource(e,t,r){const s=null!=t?this.allSources.at(t):null;if(!s)return null;const{location:o=null}=e,i=this.view?.spatialReference??Z,l=k(s,"maxResults")?s.maxResults:this.maxResults,a=!!(s instanceof P&&k(s,"exactMatch"))&&s.exactMatch,{view:n}=this;return s.getResults?.({exactMatch:a,location:o,maxResults:l,sourceIndex:t,spatialReference:i,suggestResult:e,view:n},r)}async _getSuggestionsFromSource(e,t,r){const s=this.allSources.at(t);if(!s)return null;e??="";const o=k(s,"suggestionsEnabled")?s.suggestionsEnabled:this.suggestionsEnabled,i=e?.length,l=k(s,"minSuggestCharacters")?s.minSuggestCharacters:this.minSuggestCharacters;if(o&&e.trim()&&i>=l){const o=this.view?.spatialReference||Z,i=k(s,"maxSuggestions")?s.maxSuggestions:this.maxSuggestions,{view:l}=this,a=!!(s instanceof P&&k(s,"exactMatch"))&&s.exactMatch;return s.getSuggestions?.({view:l,sourceIndex:t,suggestTerm:e,spatialReference:o,maxSuggestions:i,exactMatch:a},r)}return null}_getLayerSourcePopupTemplate(e){const{layer:t}=e;if(t)return k(e,"popupTemplate")?e.popupTemplate:t.popupTemplate}_getSourceIndexOfResult(e){return c(this.results??[],({results:t,sourceIndex:r})=>{const s=t?.includes(e);return s?r:null})??null}async _goToSearchResult(e){this._abortGoTo();const t=new AbortController;this._gotoController=t;const r={target:{target:e},options:{signal:t.signal}};e||(r.options.animate=!1),await this.callGoTo(r),this._gotoController=null}_getDefaultSymbol(e){const{defaultSymbols:t}=this,r=e.feature?.geometry;if(null==r)return null;switch(r.type){case"point":case"multipoint":return t.point;case"polyline":return t.polyline;case"extent":case"polygon":return t.polygon;default:return null}}_removeHighlight(){this.removeHandles(B)}async _getLayerView(e){const{view:t}=this;if(!e||!t)return null;const{layer:r,sourceLayer:s}=e,o=r??s;return o&&"building-component"!==o.type&&"subtype-sublayer"!==o.type?(await t.when(),t.whenLayerView(o)):null}_highlightFeature(e){const{graphic:t,layerView:r}=e,{attributes:s,layer:o,sourceLayer:i}=t,l=o??i,{objectIdField:a}=l,n=(a&&s?.[a])??null,u=r.highlight(n??t);this.addHandles(u,B)}_setResultFloor(e){const{view:t}=this,r=e.feature?.attributes,s=e.feature?.sourceLayer;if(s&&"floorInfo"in s&&s?.floorInfo?.floorField&&r){const e=r[s.floorInfo.floorField];t?.emit("select-result-floor",e)}}};e([y()],W.prototype,"_searching",void 0),e([y()],W.prototype,"_updatingPromise",void 0),e([y({readOnly:!0,value:null})],W.prototype,"activeSource",null),e([y()],W.prototype,"activeSourceIndex",null),e([y()],W.prototype,"allPlaceholder",null),e([y({readOnly:!0})],W.prototype,"allSources",null),e([y()],W.prototype,"autoNavigate",void 0),e([y()],W.prototype,"autoSelect",void 0),e([y({type:s})],W.prototype,"defaultPopupTemplate",void 0),e([y({readOnly:!0})],W.prototype,"defaultSources",void 0),e([y()],W.prototype,"defaultSymbols",void 0),e([y()],W.prototype,"includeDefaultSources",void 0),e([y()],W.prototype,"locationEnabled",null),e([y()],W.prototype,"maxInputLength",void 0),e([y()],W.prototype,"maxResults",void 0),e([y()],W.prototype,"maxSuggestions",void 0),e([y()],W.prototype,"messages",void 0),e([y()],W.prototype,"minSuggestCharacters",void 0),e([y({readOnly:!0})],W.prototype,"placeholder",null),e([y()],W.prototype,"popupEnabled",void 0),e([y({type:s})],W.prototype,"popupTemplate",void 0),e([y({type:L})],W.prototype,"portal",void 0),e([y()],W.prototype,"resultCount",void 0),e([y()],W.prototype,"resultGraphicEnabled",void 0),e([y({readOnly:!0})],W.prototype,"resultGraphic",void 0),e([y({readOnly:!0})],W.prototype,"results",void 0),e([y({readOnly:!0})],W.prototype,"selectedSuggestion",void 0),e([y()],W.prototype,"searchAllEnabled",void 0),e([y({readOnly:!0})],W.prototype,"selectedResult",void 0),e([y()],W.prototype,"searchTerm",null),e([y({type:Q})],W.prototype,"sources",void 0),e([y({readOnly:!0})],W.prototype,"state",null),e([y()],W.prototype,"suggestionDelay",void 0),e([y()],W.prototype,"suggestionCount",void 0),e([y({readOnly:!0})],W.prototype,"suggestions",void 0),e([y()],W.prototype,"suggestionsEnabled",void 0),e([y({readOnly:!0})],W.prototype,"updating",null),e([y()],W.prototype,"view",void 0),e([y()],W.prototype,"clear",null),W=e([f("esri.widgets.Search.SearchViewModel")],W);const X=W;export{X as default};
5
+ import{__decorate as e}from"tslib";import{getAssetUrl as t}from"../../assets.js";import r from"../../Graphic.js";import s from"../../PopupTemplate.js";import{isSome as o}from"../../core/arrayUtils.js";import i from"../../core/Collection.js";import l from"../../core/Error.js";import a from"../../core/Evented.js";import n from"../../core/Logger.js";import{mappedFind as u}from"../../core/maybe.js";import{eachAlways as c,after as h}from"../../core/promiseUtils.js";import{watch as p,initial as g,whenOnce as d}from"../../core/reactiveUtils.js";import{property as m}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import{subclass as y}from"../../core/accessorSupport/decorators/subclass.js";import f from"../../geometry/Point.js";import S from"../../geometry/SpatialReference.js";import{getPointFromGeometry as _,getPointWithElevation as v}from"../../geometry/support/geometryUtils.js";import{onLocaleChange as w}from"../../intl/locale.js";import{fetchMessageBundle as b}from"../../intl/messages.js";import x from"../../portal/Portal.js";import{isApiKeyApplicable as L}from"../../support/apiKeyUtils.js";import I from"../../symbols/PictureMarkerSymbol.js";import T from"../../symbols/SimpleFillSymbol.js";import R from"../../symbols/SimpleLineSymbol.js";import E from"../../symbols/TextSymbol.js";import{highlightsSupported as F}from"../../views/support/layerViewUtils.js";import P from"./LayerSearchSource.js";import j from"./LocatorSearchSource.js";import C from"./SearchSource.js";import{isArcGISWorldGeocoder as G,meteredArcGISLocatorUrl as O,isProxiedArcGISWorldGeocoder as A,isMeteredArcGISWorldGeocoder as N}from"./support/locatorUtils.js";import{supported as D,getCurrentPosition as M,positionToPoint as V}from"../support/geolocationUtils.js";import J from"../support/GoTo.js";function U(e,t){return e.hasOwnProperty(t)&&null!=e[t]&&""!==e[t]}const k=()=>b("esri/widgets/Search/t9n/Search"),H="highlight",B=i.ofType({key:e=>e.layer?"layer":"locator",base:C,typeMap:{layer:P,locator:j}}),Q=S.WGS84,Z="esri/images/search/search-symbol-32.png",q=/<[\s\S]*?>/g,z=-1;let K=class extends(J(a.EventedAccessor)){constructor(e){super(e),this._gotoController=null,this._searching=null,this._updatingPromise=null,this._createdFeatureLayers=[],this.autoNavigate=!0,this.autoSelect=!0,this.defaultPopupTemplate=null,this.defaultSources=new B,this.defaultSymbols={point:new I({url:t(Z),size:24,width:24,height:24}),polyline:new R({color:[130,130,130,1],width:2}),polygon:new T({color:[235,235,235,.4],outline:{color:[130,130,130,1],width:2}})},this.includeDefaultSources=!0,this.maxInputLength=128,this.maxResults=6,this.maxSuggestions=6,this.messages=null,this.minSuggestCharacters=3,this.popupEnabled=!0,this.popupTemplate=null,this.portal=x.getDefault(),this.resultCount=null,this.resultGraphicEnabled=!0,this.resultGraphic=null,this.results=null,this.selectedSuggestion=null,this.searchAllEnabled=!0,this.selectedResult=null,this.sources=new B,this.suggestionDelay=350,this.suggestionCount=null,this.suggestions=null,this.suggestionsEnabled=!0,this.view=null}initialize(){const e=async()=>{const e=await k();this.messages=e,this.defaultPopupTemplate=new s({title:e.searchResult,content:"{Match_addr}"})};e(),this.addHandles([p(()=>[this.includeDefaultSources,this.view,this.portal],()=>this._update(),g),w(e)])}destroy(){this._destroyFeatureLayers(),this._abortGoTo(),this.clearGraphics()}static{this.ALL_INDEX=z}get activeSource(){return this.allSources.at(this.activeSourceIndex)??null}get activeSourceIndex(){return 1===this.allSources.length||!this.searchAllEnabled?0:z}set activeSourceIndex(e){this._overrideIfSome("activeSourceIndex",e)}get allPlaceholder(){return this.messages?.allPlaceholder}set allPlaceholder(e){this._overrideIfSome("allPlaceholder",e)}get allSources(){const{sources:e,defaultSources:t,includeDefaultSources:r}=this,s="function"==typeof r?r.call(null,{sources:e,defaultSources:t}):r?t.concat(e):e,o=this._get("allSources")||new B;return o.removeAll(),o.addMany(s.filter(Boolean)),o}get locationEnabled(){return this._get("locationEnabled")||D()}set locationEnabled(e){if(void 0===e)return void this._clearOverride("locationEnabled");const t=D();if(e&&!t){const e=new l("locationEnabled:geolocation-unsupported","Geolocation API is unsupported.",{geolocation:navigator.geolocation});n.getLogger(this).error(e)}this._override("locationEnabled",!!e&&t)}get placeholder(){const{allSources:e,activeSourceIndex:t,allPlaceholder:r}=this;if(t===z)return r??"";const s=e.at(t);return s?.placeholder??""}set searchTerm(e){this._set("searchTerm",e||""),this.clearGraphics(),this.selectedSuggestion&&this.selectedSuggestion.text!==e&&this._set("selectedSuggestion",null),""===e&&this._clear()}get searchTerm(){return this._get("searchTerm")||""}get state(){return this._searching?"searching":this.updating?"loading":0===this.allSources.length?"disabled":"ready"}get updating(){return null!=this._updatingPromise}clear(){this.searchTerm=""}clearGraphics(){this._removeHighlight(),this._closePopup();const{view:e,resultGraphic:t}=this;e&&t&&e.graphics.remove(t),this._set("resultGraphic",null)}search(e,t){this.emit("search-start"),this.clearGraphics();const r=this._createSuggestionForSearch(e),s=(async()=>{try{await this.when();const e=await this._getResultsFromSources(r,t);if(t?.signal?.aborted)return null;const s={activeSourceIndex:this.activeSourceIndex,searchTerm:r.text??"",numResults:0,numErrors:0,errors:[],results:[]};this._formatResponse(s,e,r);const o=this._getFirstResult(s.results),i=r.location&&o?o.name:r.text,l=i?.replace(q,"");return this._set("searchTerm",l),(r.key&&"number"==typeof r.sourceIndex||r.location)&&this._set("selectedSuggestion",r),this._set("results",s.results),this._set("resultCount",s.results.reduce((e,t)=>e+(t.results?.length??0),0)),this.emit("search-complete",s),await this._selectFirstResult(o),s}finally{this._clearSearching()}})();return this._searching=s,s}async searchNearby(e){if(!this.locationEnabled){const e=new l("searchNearby:geolocation-unsupported","Geolocation API is unsupported.",{geolocation:navigator.geolocation});throw n.getLogger(this).error(e),e}const t=(async()=>{try{const t=await M(),r=await V({position:t,view:this.view},e);return await this.search(r,e)}finally{this._clearSearching()}})();return this._searching=t,t}async select(e){if(this.clearGraphics(),!e){const t=new l("select:missing-parameter","Cannot select without a searchResult.",{searchResult:e});throw n.getLogger(this).error(t),t}const{view:t}=this,s=U(e,"sourceIndex")?e.sourceIndex:this._getSourceIndexOfResult(e),o=null!=s?this.allSources.at(s):null;if(!o){const e=new l("select:missing-source","Cannot select without a source.",{source:o});throw n.getLogger(this).error(e),e}const i=o instanceof P?this._getLayerSourcePopupTemplate(o):o.popupTemplate,a=o.resultSymbol||this._getDefaultSymbol(e),u=U(o,"resultGraphicEnabled")?o.resultGraphicEnabled:this.resultGraphicEnabled,h=U(o,"autoNavigate")?o.autoNavigate:this.autoNavigate,p=U(o,"popupEnabled")?o.popupEnabled:this.popupEnabled,g=p?i||this.popupTemplate||this.defaultPopupTemplate:null,{feature:d}=e;if(!d){const e=new l("select:missing-feature","Cannot select without a feature.",{feature:d});throw n.getLogger(this).error(e),e}const{attributes:m,geometry:y,layer:f,sourceLayer:S}=d,w=y?_(y):null,b={layerViewQuery:this._getLayerView(d),elevationQuery:t&&null!=w?v(w,t):Promise.resolve(w)},x=await c(b),L=x.layerViewQuery.value,I=x.elevationQuery.value;a instanceof E&&(a.text=e.name);const T=t&&h?e.target||e.extent:null,R=null!=T?this._goToSearchResult(T):Promise.resolve();await R;const j=L?d:new r({geometry:y,symbol:a,attributes:m,layer:f,sourceLayer:S,popupTemplate:g}),C=t?.popup,G=C&&p&&j.getEffectivePopupTemplate(C.defaultPopupTemplateEnabled);return G&&await t.openPopup({features:[j],location:I}),L&&F(L)&&!G&&this._highlightFeature({graphic:j,layerView:L}),!L&&u&&t&&t.graphics.push(j),this._setResultFloor(e),this._set("selectedResult",e),this._set("resultGraphic",j),this.emit("select-result",{result:e,source:o,sourceIndex:s}),e}async suggest(e,t,r){const s=e||this.searchTerm;this.emit("suggest-start",{searchTerm:s}),await this._suggestTimer(t,r);const o=await this._suggestImmediate(s,r);return this._set("suggestions",o?.results),this._set("suggestionCount",o?.results.reduce((e,t)=>e+(t.results?.length??0),0)??null),this.emit("suggest-complete",o),o}async when(){await d(()=>!this.updating)}async _update(){const{portal:e,view:t}=this;if(this.includeDefaultSources){const r=this._updatingPromise=c([e?.load(),t?.when()]);if(this.destroyed)return;if(await r,r!==this._updatingPromise)return}await d(()=>this.messages),this.destroyed||this._updateDefaultSources(),this._updatingPromise=null}_clearSearching(){this._searching=null}_convertHelperServices(){const e=this.portal?.helperServices?.geocode;if(!e)return[];return e.map(e=>{if(!1===e.placefinding)return;const t=G(e.url)&&L(e.url)?{url:O}:null,r=j.fromJSON({...e,...t}),s=r.url;if(G(s)||A(s)||N(s)){const e=r.outFields??["Addr_type","Match_addr","StAddr","City"],t=(r.placeholder||this.messages?.placeholder)??"",s="number"==typeof r.defaultZoomScale?r.defaultZoomScale:2500;r.singleLineFieldName="SingleLine",r.outFields=e,r.placeholder=t,r.defaultZoomScale=s}return r.singleLineFieldName?r:void 0}).filter(o)}_destroyFeatureLayers(){this._createdFeatureLayers.forEach(e=>e?.destroy()),this._createdFeatureLayers=[]}_getLayerSources(e,t){const r=this.view?.map;return e.map(e=>{const s=r.findLayerById(e.id);if(!s)return;const o=this._getLayerJSON(e),i=P.fromJSON(o);return i.placeholder=t,this._getLayer(s,o).then(e=>{i.layer=e}),i}).filter(o).toArray()}_getTableSources(e,t){const r=this.view?.map;return e.map(e=>{if(!e.id)return;const s=r.findTableById(e.id);if(!s)return;const o=this._getLayerJSON(e),i=P.fromJSON(o);return i.placeholder=t,this._getLayer(s,o).then(e=>{i.layer=e}),i}).filter(o).toArray()}_convertApplicationProperties(){const e=this.view?.map,t=e?.applicationProperties?.viewing?.search;if(!t)return[];const{enabled:r,hintText:s,layers:o,tables:i}=t;if(!r)return[];return[...this._getLayerSources(o,s),...this._getTableSources(i,s)]}async _getSubLayer(e,t){if(await e.load(),!e.allSublayers)throw new Error;const r=e.allSublayers.find(e=>e.id===t.subLayer);if(!r)throw new Error;const s=await(r.createFeatureLayer?.());if(!s)throw new Error;return this._createdFeatureLayers.push(s),s}async _getBuildingSubLayer(e,t){await e.load();const r=e.allSublayers.find(e=>e.id===t.subLayer);if("building-component"!==r?.type)throw new Error;if(await r.load(),null==r.associatedLayer)throw new Error;return await r.associatedLayer.load(),r}async _getLayer(e,t){if("feature"===e.type||"scene"===e.type||"csv"===e.type||"geojson"===e.type||"ogc-feature"===e.type)return e;if("map-image"===e.type)try{return await this._getSubLayer(e,t)}catch(r){const t=new l("search:create-featurelayer","Could not create a FeatureLayer from the MapImageLayer",{layer:e});return n.getLogger(this).error(t),null}return"building-scene"===e.type?this._getBuildingSubLayer(e,t):null}_getLayerJSON(e){return"function"==typeof e.toJSON?e.toJSON():e}_updateDefaultSources(){const{defaultSources:e,includeDefaultSources:t}=this;this._destroyFeatureLayers(),e.removeAll(),t&&e.addMany([...this._convertApplicationProperties(),...this._convertHelperServices()])}_abortGoTo(){this._gotoController&&this._gotoController.abort(),this._gotoController=null}_clear(){this._abortGoTo(),this._set("resultCount",null),this._set("results",null),this._set("suggestions",null),this._set("suggestionCount",null),this._set("selectedResult",null),this._set("selectedSuggestion",null),this.emit("search-clear")}_closePopup(){const e=this.view?.popup,{resultGraphic:t}=this;if(!e||!t)return;const r="selectedFeature"in e,s=r?e.selectedFeature:null;r&&(s&&s===t)&&e.close()}_suggestTimer(e,t){const r=null!=e?e:this.suggestionDelay;return h(r,null,t?.signal)}_createLocationForSearch(e){return e instanceof r&&e.geometry?_(e.geometry):e instanceof f?e:Array.isArray(e)&&2===e.length?new f({longitude:e[0],latitude:e[1]}):null}_createSuggestionForSearch(e){if(e&&U(e,"key")&&U(e,"text")&&U(e,"sourceIndex"))return e;const t=this._createLocationForSearch(e),r="string"==typeof e?e:this.searchTerm,{selectedSuggestion:s,selectedResult:o}=this,i=!e&&s&&o,l=i&&s.key===o.key&&s.sourceIndex===o.sourceIndex,a=i&&s.location;return l||a?s:{location:t,text:t?"":r,sourceIndex:null,key:null}}_getFirstResult(e){return u(e,({results:e})=>e?.[0])??null}async _selectFirstResult(e){return this.autoSelect&&e?this.select(e):null}async _suggestImmediate(e,t){await this.when();const r=await this._getSuggestionsFromSources(e,t);if(t?.signal?.aborted)return null;const s={activeSourceIndex:this.activeSourceIndex,searchTerm:e??"",numResults:0,numErrors:0,errors:[],results:[]};return this._formatResponse(s,r),s}_formatSourceResponse(e,t,r){const s=t?.value||[],o=t?.error,i=this.allSources.at(r);if(o){const t={sourceIndex:r,source:i,error:o};e.errors.push(t),n.getLogger(this).error(o),e.numErrors++}else{const t={sourceIndex:r,source:i,results:s};e.results.push(t),e.numResults+=s.length}}_formatResponse(e,t,r){if(t)if(e.activeSourceIndex===z){const s=r&&U(r,"sourceIndex")&&-1!==r.sourceIndex?r.sourceIndex:void 0;t.forEach((t,r)=>{const o=void 0!==s?s:r;this._formatSourceResponse(e,t,o)})}else this._formatSourceResponse(e,t[0],e.activeSourceIndex)}async _getResultsFromSources(e,t){const{allSources:r}=this,s=!e.location&&U(e,"sourceIndex")?e.sourceIndex:this.activeSourceIndex,o=[];if(!r.length){const e=new l("search:no-sources-defined","At least one source is required.",{allSources:r});throw n.getLogger(this).error(e),e}return s===z?r.forEach((r,s)=>{o.push(this._getResultsFromSource(e,s,t))}):o.push(this._getResultsFromSource(e,s,t)),c(o)}async _getSuggestionsFromSources(e,t){const{allSources:r,activeSourceIndex:s}=this,o=[];if(!r.length){const e=new l("suggest:no-sources-defined","At least one source is required.",{allSources:r});throw n.getLogger(this).error(e),e}return s===z?r.forEach((r,s)=>{o.push(this._getSuggestionsFromSource(e,s,t))}):o.push(this._getSuggestionsFromSource(e,s,t)),c(o)}async _getResultsFromSource(e,t,r){const s=null!=t?this.allSources.at(t):null;if(!s)return null;const{location:o=null}=e,i=this.view?.spatialReference??Q,l=U(s,"maxResults")?s.maxResults:this.maxResults,a=!!(s instanceof P&&U(s,"exactMatch"))&&s.exactMatch,{view:n}=this;return s.getResults?.({exactMatch:a,location:o,maxResults:l,sourceIndex:t,spatialReference:i,suggestResult:e,view:n},r)}async _getSuggestionsFromSource(e,t,r){const s=this.allSources.at(t);if(!s)return null;e??="";const o=U(s,"suggestionsEnabled")?s.suggestionsEnabled:this.suggestionsEnabled,i=e?.length,l=U(s,"minSuggestCharacters")?s.minSuggestCharacters:this.minSuggestCharacters;if(o&&e.trim()&&i>=l){const o=this.view?.spatialReference||Q,i=U(s,"maxSuggestions")?s.maxSuggestions:this.maxSuggestions,{view:l}=this,a=!!(s instanceof P&&U(s,"exactMatch"))&&s.exactMatch;return s.getSuggestions?.({view:l,sourceIndex:t,suggestTerm:e,spatialReference:o,maxSuggestions:i,exactMatch:a},r)}return null}_getLayerSourcePopupTemplate(e){const{layer:t}=e;if(t)return U(e,"popupTemplate")?e.popupTemplate:t.popupTemplate}_getSourceIndexOfResult(e){return u(this.results??[],({results:t,sourceIndex:r})=>{const s=t?.includes(e);return s?r:null})??null}async _goToSearchResult(e){this._abortGoTo();const t=new AbortController;this._gotoController=t;const r={target:{target:e},options:{signal:t.signal}};e||(r.options.animate=!1),await this.callGoTo(r),this._gotoController=null}_getDefaultSymbol(e){const{defaultSymbols:t}=this,r=e.feature?.geometry;if(null==r)return null;switch(r.type){case"point":case"multipoint":return t.point;case"polyline":return t.polyline;case"extent":case"polygon":return t.polygon;default:return null}}_removeHighlight(){this.removeHandles(H)}async _getLayerView(e){const{view:t}=this;if(!e||!t)return null;const{layer:r,sourceLayer:s}=e,o=r??s;return o&&"building-component"!==o.type&&"subtype-sublayer"!==o.type?(await t.when(),t.whenLayerView(o)):null}_highlightFeature(e){const{graphic:t,layerView:r}=e,{attributes:s,layer:o,sourceLayer:i}=t,l=o??i,{objectIdField:a}=l,n=(a&&s?.[a])??null,u=r.highlight(n??t);this.addHandles(u,H)}_setResultFloor(e){const{view:t}=this,r=e.feature?.attributes,s=e.feature?.sourceLayer;if(s&&"floorInfo"in s&&s?.floorInfo?.floorField&&r){const e=r[s.floorInfo.floorField];t?.emit("select-result-floor",e)}}};e([m()],K.prototype,"_searching",void 0),e([m()],K.prototype,"_updatingPromise",void 0),e([m({readOnly:!0,value:null})],K.prototype,"activeSource",null),e([m()],K.prototype,"activeSourceIndex",null),e([m()],K.prototype,"allPlaceholder",null),e([m({readOnly:!0})],K.prototype,"allSources",null),e([m()],K.prototype,"autoNavigate",void 0),e([m()],K.prototype,"autoSelect",void 0),e([m({type:s})],K.prototype,"defaultPopupTemplate",void 0),e([m({readOnly:!0})],K.prototype,"defaultSources",void 0),e([m()],K.prototype,"defaultSymbols",void 0),e([m()],K.prototype,"includeDefaultSources",void 0),e([m()],K.prototype,"locationEnabled",null),e([m()],K.prototype,"maxInputLength",void 0),e([m()],K.prototype,"maxResults",void 0),e([m()],K.prototype,"maxSuggestions",void 0),e([m()],K.prototype,"messages",void 0),e([m()],K.prototype,"minSuggestCharacters",void 0),e([m({readOnly:!0})],K.prototype,"placeholder",null),e([m()],K.prototype,"popupEnabled",void 0),e([m({type:s})],K.prototype,"popupTemplate",void 0),e([m({type:x})],K.prototype,"portal",void 0),e([m()],K.prototype,"resultCount",void 0),e([m()],K.prototype,"resultGraphicEnabled",void 0),e([m({readOnly:!0})],K.prototype,"resultGraphic",void 0),e([m({readOnly:!0})],K.prototype,"results",void 0),e([m({readOnly:!0})],K.prototype,"selectedSuggestion",void 0),e([m()],K.prototype,"searchAllEnabled",void 0),e([m({readOnly:!0})],K.prototype,"selectedResult",void 0),e([m()],K.prototype,"searchTerm",null),e([m({type:B})],K.prototype,"sources",void 0),e([m({readOnly:!0})],K.prototype,"state",null),e([m()],K.prototype,"suggestionDelay",void 0),e([m()],K.prototype,"suggestionCount",void 0),e([m({readOnly:!0})],K.prototype,"suggestions",void 0),e([m()],K.prototype,"suggestionsEnabled",void 0),e([m({readOnly:!0})],K.prototype,"updating",null),e([m()],K.prototype,"view",void 0),e([m()],K.prototype,"clear",null),K=e([y("esri.widgets.Search.SearchViewModel")],K);const W=K;export{W as default};