@arcgis/core 4.33.0-next.20250219 → 4.33.0-next.20250221

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 (211) hide show
  1. package/applications/ExperienceBuilder/sketchUtils.d.ts +1 -0
  2. package/applications/ExperienceBuilder/sketchUtils.js +1 -1
  3. package/arcade/featureSetUtils.js +1 -1
  4. package/arcade/functions/featuresetbase.js +1 -1
  5. package/arcade/treeAnalysis.js +1 -1
  6. package/assets/esri/core/workers/RemoteClient.js +1 -1
  7. package/assets/esri/core/workers/chunks/0c3930e40fc9f8a84599.js +2 -0
  8. package/assets/esri/core/workers/chunks/{ccee343fb8c415b59ce3.js.LICENSE.txt → 0c3930e40fc9f8a84599.js.LICENSE.txt} +1 -1
  9. package/assets/esri/core/workers/chunks/333bb93a28209c997d8b.js +314 -0
  10. package/assets/esri/core/workers/chunks/469c50c49447f0d602c0.js +1 -0
  11. package/assets/esri/core/workers/chunks/486df1e042204b90b0dd.js.LICENSE.txt +1 -1
  12. package/assets/esri/core/workers/chunks/4f764b952c6463fc7c88.js +1 -0
  13. package/assets/esri/core/workers/chunks/{c2d539359f321bba3432.js → 52c13b3c074c9f6dadde.js} +2 -2
  14. package/assets/esri/core/workers/chunks/{c2d539359f321bba3432.js.LICENSE.txt → 52c13b3c074c9f6dadde.js.LICENSE.txt} +1 -1
  15. package/assets/esri/core/workers/chunks/5693d9ce4472a4c5959f.js.LICENSE.txt +1 -1
  16. package/assets/esri/core/workers/chunks/5b56b271afb0fadf48b4.js.LICENSE.txt +1 -1
  17. package/assets/esri/core/workers/chunks/63d8d507f073a8ed42d2.js +1 -0
  18. package/assets/esri/core/workers/chunks/6518954889df2e781c47.js.LICENSE.txt +1 -1
  19. package/assets/esri/core/workers/chunks/68322a63ec92d33701ea.js +1 -0
  20. package/assets/esri/core/workers/chunks/70574e0e3de729187d98.js +1 -0
  21. package/assets/esri/core/workers/chunks/78c066e8fe167d4ab817.js +1 -0
  22. package/assets/esri/core/workers/chunks/875a200f215e472d147e.js +1 -0
  23. package/assets/esri/core/workers/chunks/{f976233ad5e5b718ba83.js → 8d1f49927738ad3601d2.js} +1 -1
  24. package/assets/esri/core/workers/chunks/9050dad7e4f093568026.js +1 -0
  25. package/assets/esri/core/workers/chunks/930544d3b2c1d9c035c7.js +1 -0
  26. package/assets/esri/core/workers/chunks/{962cad03be1b7aa52ebe.js → 95835a62712fe4f24205.js} +1 -1
  27. package/assets/esri/core/workers/chunks/{030384851fa745908a6e.js → 9dbdb88cdac993104740.js} +2 -2
  28. package/assets/esri/core/workers/chunks/aacebda644be06ad1a61.js +1 -0
  29. package/assets/esri/core/workers/chunks/b0952b81d5be214262dd.js.LICENSE.txt +1 -1
  30. package/assets/esri/core/workers/chunks/b7c6d0ff4c085c8d0596.js +1 -0
  31. package/assets/esri/core/workers/chunks/e0cd4815149d1ff4d31e.js +1 -0
  32. package/assets/esri/core/workers/chunks/e2df18662cc4d6e47715.js +1 -0
  33. package/assets/esri/core/workers/chunks/{0a82c13828ffd4780419.js → f51fc2370fb486233499.js} +1 -1
  34. package/assets/esri/core/workers/chunks/fcbe65256a71b34ac9cf.js +1 -0
  35. package/assets/esri/themes/base/widgets/_Editor.scss +7 -0
  36. package/assets/esri/themes/base/widgets/_ResponsiveToolbar.scss +9 -3
  37. package/assets/esri/themes/base/widgets/_Sketch.scss +32 -24
  38. package/assets/esri/themes/dark/main.css +1 -1
  39. package/assets/esri/themes/light/main.css +1 -1
  40. package/assets/esri/themes/light/view.css +1 -1
  41. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ar.json +1 -1
  42. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_bg.json +1 -1
  43. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_bs.json +1 -1
  44. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ca.json +1 -1
  45. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_cs.json +1 -1
  46. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_da.json +1 -1
  47. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_de.json +1 -1
  48. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_el.json +1 -1
  49. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_es.json +1 -1
  50. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_et.json +1 -1
  51. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_fi.json +1 -1
  52. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_fr.json +1 -1
  53. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_he.json +1 -1
  54. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_hr.json +1 -1
  55. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_hu.json +1 -1
  56. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_id.json +1 -1
  57. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_it.json +1 -1
  58. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ja.json +1 -1
  59. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ko.json +1 -1
  60. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_lt.json +1 -1
  61. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_lv.json +1 -1
  62. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_nl.json +1 -1
  63. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_no.json +1 -1
  64. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_pl.json +1 -1
  65. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_pt-BR.json +1 -1
  66. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_pt-PT.json +1 -1
  67. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ro.json +1 -1
  68. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ru.json +1 -1
  69. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_sk.json +1 -1
  70. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_sl.json +1 -1
  71. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_sr.json +1 -1
  72. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_sv.json +1 -1
  73. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_th.json +1 -1
  74. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_tr.json +1 -1
  75. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_uk.json +1 -1
  76. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_vi.json +1 -1
  77. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_zh-CN.json +1 -1
  78. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_zh-HK.json +1 -1
  79. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_zh-TW.json +1 -1
  80. package/chunks/ColorMaterial.glsl.js +1 -1
  81. package/chunks/DefaultMaterial.glsl.js +1 -1
  82. package/chunks/ImageMaterial.glsl.js +3 -3
  83. package/chunks/LineMarker.glsl.js +11 -11
  84. package/chunks/NativeLine.glsl.js +1 -1
  85. package/chunks/Path.glsl.js +11 -11
  86. package/chunks/Pattern.glsl.js +2 -2
  87. package/chunks/RealisticTree.glsl.js +1 -1
  88. package/chunks/RibbonLine.glsl.js +1 -1
  89. package/chunks/Terrain.glsl.js +1 -1
  90. package/chunks/WaterSurface.glsl.js +9 -9
  91. package/copyright.txt +20 -0
  92. package/editing/sharedTemplates/SharedTemplate.js +1 -1
  93. package/editing/sharedTemplates/SharedTemplateMetadata.js +1 -1
  94. package/editing/sharedTemplates/SharedTemplateProvider.js +1 -1
  95. package/editing/sharedTemplates/executor/support/createServiceEdit.js +1 -1
  96. package/editing/sharedTemplates/support/sharedTemplateErrors.js +1 -1
  97. package/editing/sharedTemplates/templateDefinitions/FeatureTemplateDefinition.js +1 -1
  98. package/editing/sharedTemplates/templateDefinitions/GroupTemplateDefinition.js +1 -1
  99. package/editing/sharedTemplates/templateDefinitions/PresetTemplateDefinition.js +1 -1
  100. package/editing/sharedTemplates/templateDefinitions/TemplateDefinitionBase.js +1 -1
  101. package/editing/sharedTemplates/templateDefinitions/parts/FeatureTemplateRelationshipPart.js +1 -1
  102. package/editing/sharedTemplates/templateDefinitions/parts/GroupTemplatePart.js +1 -1
  103. package/editing/sharedTemplates/templateDefinitions/parts/TemplatePartBase.js +1 -1
  104. package/interfaces.d.ts +427 -93
  105. package/layers/ImageryLayer.js +1 -1
  106. package/layers/ImageryTileLayer.js +1 -1
  107. package/layers/RouteLayer.js +1 -1
  108. package/layers/WCSLayer.js +1 -1
  109. package/layers/mixins/ArcGISImageService.js +1 -1
  110. package/layers/mixins/ImageryTileMixin.js +1 -1
  111. package/layers/mixins/RasterJobHandlerMixin.js +5 -0
  112. package/layers/orientedImagery/transformations/utils.js +1 -1
  113. package/layers/orientedImagery/transformations/worldToImage.js +1 -1
  114. package/layers/support/Relationship.js +1 -1
  115. package/layers/support/rasterFunctionUtils.d.ts +11 -0
  116. package/networks/UtilityNetwork.js +1 -1
  117. package/package.json +2 -2
  118. package/rest/route.js +1 -1
  119. package/rest/support/RouteParameters.js +1 -1
  120. package/rest/support/RouteSolveResult.js +1 -1
  121. package/support/revision.js +1 -1
  122. package/symbols/cim/CIMEffects.js +1 -1
  123. package/symbols/cim/effects/EffectAddControlPoints.js +1 -1
  124. package/symbols/cim/effects/EffectBuffer.js +1 -1
  125. package/symbols/cim/effects/EffectDonut.js +1 -1
  126. package/symbols/cim/effects/EffectOffset.js +1 -1
  127. package/undoredo/support/Services.js +1 -1
  128. package/views/2d/AnimationManager.js +1 -1
  129. package/views/2d/engine/webgl/TextureManager.js +1 -1
  130. package/views/2d/engine/webgl/Utils.js +1 -1
  131. package/views/2d/engine/webgl/shaderGraph/techniques/labels/LabelTechnique.js +1 -1
  132. package/views/2d/engine/webgl/shaderGraph/techniques/markers/MarkerMeshWriter.js +1 -1
  133. package/views/2d/engine/webgl/shaderGraph/techniques/text/TextShader.js +1 -1
  134. package/views/2d/layers/FeatureLayerView2D.js +1 -1
  135. package/views/2d/layers/features/FeaturePipelineWorker.js +1 -1
  136. package/views/2d/layers/features/sources/FeatureSource.js +1 -1
  137. package/views/2d/layers/features/sources/strategies/chunks/Overrides.js +1 -1
  138. package/views/2d/layers/imagery/VectorFieldTileView2D.js +1 -1
  139. package/views/2d/layers/imagery/VectorFieldView2D.js +1 -1
  140. package/views/3d/layers/I3SMeshView3D.js +1 -1
  141. package/views/3d/layers/graphics/pipeline/Feature3DPipelineWorker.js +1 -1
  142. package/views/3d/layers/graphics/pipeline/Tile.js +1 -1
  143. package/views/3d/layers/graphics/pipeline/Tile3DManager.js +1 -1
  144. package/views/3d/layers/graphics/pipeline/featureData/FeatureData.js +1 -1
  145. package/views/3d/layers/graphics/pipeline/featureData/FeatureDataSubset.js +5 -0
  146. package/views/3d/layers/graphics/pipeline/featureData/processingUtils.js +1 -1
  147. package/views/3d/layers/graphics/pipeline/featureSet/PBFPointFeatureSetView.js +1 -1
  148. package/views/3d/layers/graphics/pipeline/featureSet/TiledFeatureStore.js +1 -1
  149. package/views/3d/layers/graphics/pipeline/fetching/Tile3DFetcher.js +1 -1
  150. package/views/3d/layers/graphics/pipeline/symbolization/TestObjectSymbol.js +1 -1
  151. package/views/3d/layers/graphics/pipeline/symbolization/TestSymbol.js +1 -1
  152. package/views/3d/layers/graphics/pipeline/symbolization/UniqueValueFeatureRenderer.js +1 -1
  153. package/views/3d/webgl-engine/collections/Component/ComponentData.js +1 -1
  154. package/views/3d/webgl-engine/collections/Component/ComponentObjectCollection.js +1 -1
  155. package/views/3d/webgl-engine/collections/Component/ComponentObjectElevationAgnosticComponentBVH.js +1 -1
  156. package/views/3d/webgl-engine/collections/Component/IndexRange/ComponentRange.js +5 -0
  157. package/views/3d/webgl-engine/lib/ComponentUtils.js +1 -1
  158. package/views/View.js +1 -1
  159. package/views/animation/easing.js +1 -1
  160. package/views/webgl/ShaderBuilder.js +1 -1
  161. package/webmap/utils.js +1 -1
  162. package/widgets/BatchAttributeForm/BatchAttributeFormViewModel.js +1 -1
  163. package/widgets/BatchAttributeForm/inputs/FieldInput.js +1 -1
  164. package/widgets/BatchAttributeForm/templates/support/createBatchFormTemplate.js +1 -1
  165. package/widgets/BatchAttributeForm.js +1 -1
  166. package/widgets/Directions/DirectionsViewModel.js +1 -1
  167. package/widgets/Directions.js +1 -1
  168. package/widgets/Editor/CreateFeaturesWorkflow.js +1 -1
  169. package/widgets/Editor/components/Prompt.js +1 -1
  170. package/widgets/Editor/workflowUtils.js +1 -1
  171. package/widgets/Editor.js +1 -1
  172. package/widgets/ElevationProfile/components/LegendItem.js +1 -1
  173. package/widgets/ElevationProfile/components/SettingsButton.js +1 -1
  174. package/widgets/FeatureForm/FeatureFormUtilityNetworkAssociations/UtilityNetworkAssociationItemList.js +1 -1
  175. package/widgets/FeatureForm/UtilityNetworkAssociationAddAssociationViewModel.js +1 -1
  176. package/widgets/FeatureForm/featureFormUtils.js +1 -1
  177. package/widgets/FeatureTable/FeatureTableViewModel.js +1 -1
  178. package/widgets/FeatureTable/support/FeatureStore.js +1 -1
  179. package/widgets/Legend/styles/support/utils.js +1 -1
  180. package/widgets/OrientedImageryViewer/OrientedImageryViewerViewModel.js +1 -1
  181. package/widgets/OrientedImageryViewer/imageMeasurementUtils.js +1 -1
  182. package/widgets/OrientedImageryViewer/symbols.js +1 -1
  183. package/widgets/OrientedImageryViewer.js +1 -1
  184. package/widgets/Sketch/SketchViewModel.js +1 -1
  185. package/widgets/Sketch/support/ResponsiveToolbar/OverflowGroup.js +1 -1
  186. package/widgets/Sketch/support/ResponsiveToolbar/ResponsiveToolbar.js +1 -1
  187. package/widgets/Sketch/support/ResponsiveToolbar/SplitButton.js +1 -1
  188. package/widgets/Sketch/support/sketchUtils.js +1 -1
  189. package/widgets/Sketch.js +1 -1
  190. package/widgets/support/FilterCondition.js +1 -1
  191. package/widgets/support/GoTo.js +1 -1
  192. package/widgets/support/UtilityNetworkAssociations/utilityNetworkUtils.js +1 -1
  193. package/widgets/support/goToUtils.js +1 -1
  194. package/assets/esri/core/workers/chunks/0c85731e9bf3eaeb96a2.js +0 -1
  195. package/assets/esri/core/workers/chunks/1b36d4400ab841c978c8.js +0 -1
  196. package/assets/esri/core/workers/chunks/3c44b4bf7fe407ec1d70.js +0 -1
  197. package/assets/esri/core/workers/chunks/4e3e141b3fd8bb652798.js +0 -1
  198. package/assets/esri/core/workers/chunks/544ad8fa4777ba8ec177.js +0 -1
  199. package/assets/esri/core/workers/chunks/717d7e9912d948e44d8d.js +0 -1
  200. package/assets/esri/core/workers/chunks/7bf9ebff90bb02bec8e7.js +0 -1
  201. package/assets/esri/core/workers/chunks/905cf2bb280479cd4f80.js +0 -1
  202. package/assets/esri/core/workers/chunks/b8fae500c69ca2cff62a.js +0 -1
  203. package/assets/esri/core/workers/chunks/b90b7ffc1e9363ed18e0.js +0 -1
  204. package/assets/esri/core/workers/chunks/bdc9dec6a359d2e3705c.js +0 -1
  205. package/assets/esri/core/workers/chunks/bf127fe767174e2715b5.js +0 -1
  206. package/assets/esri/core/workers/chunks/ccee343fb8c415b59ce3.js +0 -2
  207. package/assets/esri/core/workers/chunks/dc68246df91af766593a.js +0 -1
  208. package/assets/esri/core/workers/chunks/e862f1b9ecafc6c92b86.js +0 -314
  209. package/assets/esri/core/workers/chunks/f06231c14c0c0e5525bd.js +0 -1
  210. package/views/3d/layers/graphics/pipeline/featureData/FeatureDataStore.js +0 -5
  211. package/views/3d/webgl-engine/collections/Component/IndexRange/ComponentRangeRunLengthEncoded.js +0 -5
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../core/Collection.js";import r from"../../core/Error.js";import i from"../../core/Evented.js";import o from"../../core/Logger.js";import{debounce as s,isAbortError as a}from"../../core/promiseUtils.js";import{watch as l,on as n,syncAndInitial as u,when as d}from"../../core/reactiveUtils.js";import{property as c}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as h}from"../../core/accessorSupport/decorators/subclass.js";import{resolveTimeZone as p,convertDateFormatToIntlOptions as m,formatTimestamp as v}from"../../intl/date.js";import{getLocale as y,getLocaleParts as g}from"../../intl/locale.js";import{fetchServiceDescription as f}from"../../rest/networkService.js";import w from"../../rest/support/RouteParameters.js";import _ from"../../rest/support/Stop.js";import T from"../../rest/support/TravelMode.js";import{defaultDatePattern as S,defaultTimePattern as D}from"../../support/dateUtils.js";import{system as C,shortTimeZoneName as b}from"../../time/timeZoneUtils.js";import{DepartureTimeOption as M}from"./support/directionsUtils.js";import{getDefaultLocaleOptions as A}from"../support/dateUtils.js";import I from"../support/GoTo.js";import{DateTime as L,FixedOffsetZone as j,IANAZone as R}from"luxon";function P(e){return e.map((e=>({locale:e,parts:g(e)}))).filter((({parts:e})=>!!e))}function E(e,t){return e.find((({parts:e})=>F(e.language,t.language)&&e.region===t.region))?.locale??e.find((({parts:e})=>F(e.language,t.language)))?.locale}function U(e){return"esri.Graphic"===e?.declaredClass}function N(e){return"no"===e||"nb"===e}function F(e,t){return e===t||N(e)&&N(t)}function O(e){return"esri.rest.support.Stop"===e?.declaredClass}var k;!function(e){e[e.Active=0]="Active",e[e.Complete=1]="Complete",e[e.Failed=2]="Failed",e[e.Idle=3]="Idle",e[e.Suspended=4]="Suspended"}(k||(k={}));let V=class extends(I(i.EventedAccessor)){constructor(e){super(e),this._debouncedSolveHandler=s((async e=>{switch(e.type){case"create":if("complete"!==e.state)return;break;case"delete":break;case"update":switch(e.state){case"start":return void(this._networkFeatureUpdated=!1);case"active":return void(this._networkFeatureUpdated=!0);case"complete":if(!this._networkFeatureUpdated)return}}if(!((this.layer?.stops.filter((({geometry:e})=>!!e)).length??0)<2)&&this.autoSolve)try{await this.getDirections({zoomToSolvedRoute:!1})}catch(t){o.getLogger(this).error(t)}})),this._highlight=null,this._loadController=null,this._loadPromise=null,this._networkFeatureUpdated=!1,this._layerView=null,this._routeController=null,this._serviceDescriptionStatus=k.Idle,this.apiKey=void 0,this.autoSolve=!0,this.defaultTravelMode=null,this.departureIsoDate=null,this.departureIsoTime=null,this.departureOption=M.NOW,this.departureTime="now",this.lastError=null,this.lastRoute=null,this.layer=null,this.maxStops=50,this.routeParameters=new w({directionsLengthUnits:"kilometers",findBestSequence:!1,preserveFirstStop:!0,preserveLastStop:!0,returnZ:!0,useTimeWindows:!1}),this.serviceDescription=null,this.view=null}initialize(){this.addHandles([l((()=>this.layer),(e=>{if(null!=e){for(;e.stops.length<2;)e.stops.add(new _);this._set("defaultTravelMode",null),this.addHandles(d((()=>this.serviceDescription?e.routeInfo?.analysisSettings?.travelMode:null),(e=>{this.defaultTravelMode=this._resolveDefaultTravelMode(e)}),{once:!0}))}}),u),l((()=>[this.layer,this.view]),(async()=>{this._layerView=await this._getRouteLayerView()}),u),n((()=>this._layerView),["create","delete","update"],(e=>{this._debouncedSolveHandler(e).catch((e=>{if(!a(e))throw e}))}))]);const e=p(this.view?.timeZone??C),t=L.fromMillis(Date.now());this.departureIsoDate=t.toFormat(S,A(e)),this.departureIsoTime=t.toFormat(D,A(e))}get _directionsLanguage(){const e=this.serviceDescription?.directionsSupportedLanguages;if(!e)return;const t=this.routeParameters.directionsLanguage??y(),r=g(t),i=r?.language,o=r?.region;if(!i)return;return E(P(e),{language:i,region:o})}get formattedEta(){const e=this.layer?.routeInfo?.endTime,t=this.layer?.routeInfo?.endTimeOffset;if(this.departureOption===M.UNSPECIFIED||!e||!t)return null;const r=L.fromJSDate(e,{zone:j.instance(t)}),i=L.fromJSDate(e,{zone:R.create(p(this.view?.timeZone??C))}),o=L.fromJSDate(new Date,{zone:R.create(p(this.view?.timeZone??C))}),s=o.year===i.year&&o.month===i.month&&o.day===i.day,a=i.offset===t?void 0:b,l=s?void 0:m("short-date"),n=m("short-time");return v(r.toISO(),{...l,...n,timeZoneName:a})}get impedanceAttribute(){const e=this.routeParameters.travelMode?.impedanceAttributeName??this.routeParameters.impedanceAttribute??this.serviceDescription?.impedance??null;return this.getCostAttribute(e)}get selectedNetworkFeatures(){return this._layerView?.selectedNetworkFeatures??null}get selectedTravelMode(){return this.serviceDescription?this.defaultTravelMode??this.serviceDescription.defaultTravelMode??this.serviceDescription.supportedTravelModes?.[0]??null:null}set selectedTravelMode(e){this._override("selectedTravelMode",e)}get state(){if(this._routeController)return"routing";if(this.lastError)return"error";switch(this._serviceDescriptionStatus){case k.Suspended:return"unauthenticated";case k.Idle:return"disabled";case k.Active:return"initializing";case k.Failed:return"error";default:return"ready"}}get timeAttribute(){const e=this.routeParameters.travelMode?.timeAttributeName??this.routeParameters.directionsTimeAttribute??this.serviceDescription?.directionsTimeAttribute??null;return this.getCostAttribute(e)}get travelModes(){const e=this.serviceDescription?.supportedTravelModes?.slice()??[];return null==this.defaultTravelMode||e.includes(this.defaultTravelMode)||e.unshift(this.defaultTravelMode),e}async load(){if(this._loadPromise)return this._loadPromise;this._loadPromise=this._load(),await this._loadPromise,this._loadPromise=null}async highlight(e){if(this.clearHighlights(),!this.view||!this.layer)return;const t=await this.view.whenLayerView(this.layer);this._highlight=t.highlight(e)}clearHighlights(){null!=this._highlight&&(this._highlight.remove(),this._highlight=null)}centerAt(e){if(!this.view)return;const t=O(e)||U(e)?e.geometry:e;t&&this.callGoTo({target:t})}clearResults(){this._set("lastRoute",null),this.layer?.removeResult()}async create(e){await(this._layerView?.create(e))}async getDirections(e={zoomToSolvedRoute:!0}){const{apiKey:t,layer:i,state:o}=this;if(!i)throw new r("directions-view-model:missing-route-layer","A route layer must be associated with the view model.");if("unauthenticated"===o||"initializing"===o||"disabled"===o||this._serviceDescriptionStatus===k.Failed)throw new r("directions-view-model:not-loaded","Cannot get directions until view model loads.");null!=this._routeController&&(this._routeController.abort(),this._routeController=null);const{startTime:s,startTimeIsUTC:l}=this._getStartTimeParameters(),n=this.view?.spatialReference??null,u=this.routeParameters.clone();u.set({apiKey:t,directionsLanguage:this._directionsLanguage,outSpatialReference:n,startTime:s,startTimeIsUTC:l}),this.selectedTravelMode&&(u.travelMode=this.selectedTravelMode);if(i.stops.filter((({geometry:e})=>null!=e)).length<2){const e=new r("directions-view-model:not-enough-stops","Not enough stops for routing");throw this._set("lastError",e),e}this._routeController=new AbortController;const{signal:d}=this._routeController;let c=null;try{c=await i.solve(u,{signal:d})}catch(h){if(!a(h)){const e=new r("directions-view-model:unable-to-route","Unable to route to these addresses",{error:h});throw this._set("lastError",e),this.clearResults(),e}}finally{this._routeController=null}this._set("lastError",null);for(const r of c.stops)null==r.geometry&&(r.name=null);return i.update(c),this._set("lastRoute",c),e.zoomToSolvedRoute&&this.zoomToRoute(),c}getCostAttribute(e){return(this.serviceDescription?.networkDataset?.networkAttributes??[]).find((({name:t,usageType:r})=>t===e&&"cost"===r))??null}remove(e){this._layerView?.remove(e)}reset(){this.clearHighlights(),this.clearResults(),null!=this.layer&&(this.layer.removeAll(),this.layer.stops=new t([new _,new _]))}save(){if(!this.layer)throw new r("directions-view-model:missing-layer","save() requires a layer");return this.layer.save()}saveAs(e,t={}){if(!this.layer)throw new r("directions-view-model:missing-layer","saveAs() requires a layer");return this.layer.saveAs(e,t)}async startEditing(){this._layerView&&(this._layerView.interactive=!0)}async stopEditing(){this._layerView&&(this._layerView.interactive=!1)}updateDepartureTime(){if(this.departureIsoDate&&this.departureIsoTime)switch(this.departureOption){case M.NOW:this.departureTime="now";break;case M.DEPART_AT:{const e=L.fromISO(`${this.departureIsoDate}T${this.departureIsoTime}`,{zone:j.instance(0)});this.departureTime=e.toJSDate();break}case M.UNSPECIFIED:this.departureTime=null}}zoomToRoute(){const{view:e,layer:t}=this,r=t?.routeInfo?.geometry?.extent;if(!e||!r)return;const i=r.width>r.height,o=r.clone().expand(i?2:1);this.callGoTo({target:o})}async _getRouteLayerView(){return this.view&&this.layer?this.view.whenLayerView(this.layer):null}_getStartTimeParameters(){if("now"===this.departureTime){return{startTime:this.serviceDescription?.capabilities.supportsNow??!1?"now":new Date,startTimeIsUTC:!0}}return null==this.departureTime?{startTime:void 0,startTimeIsUTC:void 0}:{startTime:this.departureTime,startTimeIsUTC:!1}}async _load(){if(null==this.layer)return;null!=this._loadController&&(this._loadController.abort(),this._loadController=null),this._loadController=new AbortController;const{signal:e}=this._loadController;try{this._serviceDescriptionStatus=k.Active;const t=await f(this.layer.url,this.apiKey,{signal:e});this._set("serviceDescription",t),this._serviceDescriptionStatus=k.Complete}catch(t){if(a(t))return void(this._serviceDescriptionStatus=k.Idle);if("identity-manager:user-aborted"===t.name)return void(this._serviceDescriptionStatus=k.Suspended);const e=new r("directions-view-model:service-metadata-unavailable","Cannot load route service metadata",{error:t});throw this._serviceDescriptionStatus=k.Failed,this._set("lastError",e),e}finally{this._loadController=null}}_resolveDefaultTravelMode(e){if(null==this.serviceDescription)return null;const{defaultTravelMode:t,supportedTravelModes:r}=this.serviceDescription,i=/^<(?<name>.*)>$/i.exec(e.name)?.groups?.name;if(i){const o=r?.find((({name:e})=>e.toLocaleLowerCase()===i.trim().toLocaleLowerCase())),s=o??t;return T.fromJSON({...s?.toJSON(),...e.toJSON()})}const o=r?.find((({name:t})=>t.toLocaleLowerCase()===e.name.toLocaleLowerCase()));return o??t}};e([c()],V.prototype,"_directionsLanguage",null),e([c()],V.prototype,"_layerView",void 0),e([c()],V.prototype,"_routeController",void 0),e([c()],V.prototype,"_serviceDescriptionStatus",void 0),e([c()],V.prototype,"apiKey",void 0),e([c()],V.prototype,"autoSolve",void 0),e([c()],V.prototype,"defaultTravelMode",void 0),e([c()],V.prototype,"departureTime",void 0),e([c()],V.prototype,"formattedEta",null),e([c({readOnly:!0})],V.prototype,"impedanceAttribute",null),e([c()],V.prototype,"lastError",void 0),e([c({readOnly:!0})],V.prototype,"lastRoute",void 0),e([c()],V.prototype,"layer",void 0),e([c({type:Number,range:{min:2,max:50},nonNullable:!0})],V.prototype,"maxStops",void 0),e([c({type:w,nonNullable:!0})],V.prototype,"routeParameters",void 0),e([c({readOnly:!0})],V.prototype,"selectedNetworkFeatures",null),e([c({type:T})],V.prototype,"selectedTravelMode",null),e([c({readOnly:!0})],V.prototype,"serviceDescription",void 0),e([c({readOnly:!0})],V.prototype,"state",null),e([c({readOnly:!0})],V.prototype,"timeAttribute",null),e([c()],V.prototype,"travelModes",null),e([c()],V.prototype,"view",void 0),e([c()],V.prototype,"zoomToRoute",null),V=e([h("esri.widgets.Directions.DirectionsViewModel")],V);const z=V;export{z as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../core/Collection.js";import r from"../../core/Error.js";import i from"../../core/Evented.js";import o from"../../core/Logger.js";import{debounce as s,isAbortError as a}from"../../core/promiseUtils.js";import{watch as l,on as n,syncAndInitial as u,when as d}from"../../core/reactiveUtils.js";import{property as c}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as h}from"../../core/accessorSupport/decorators/subclass.js";import{resolveTimeZone as p,convertDateFormatToIntlOptions as m,formatTimestamp as v}from"../../intl/date.js";import{getLocale as y,getLocaleParts as g}from"../../intl/locale.js";import{fetchServiceDescription as f}from"../../rest/networkService.js";import w from"../../rest/support/RouteParameters.js";import _ from"../../rest/support/Stop.js";import T from"../../rest/support/TravelMode.js";import{defaultDatePattern as S,defaultTimePattern as D}from"../../support/dateUtils.js";import{system as C,shortTimeZoneName as b}from"../../time/timeZoneUtils.js";import{DepartureTimeOption as M}from"./support/directionsUtils.js";import{getDefaultLocaleOptions as A}from"../support/dateUtils.js";import I from"../support/GoTo.js";import{DateTime as L,FixedOffsetZone as j,IANAZone as R}from"luxon";function P(e){return e.map((e=>({locale:e,parts:g(e)}))).filter((({parts:e})=>!!e))}function E(e,t){return e.find((({parts:e})=>F(e.language,t.language)&&e.region===t.region))?.locale??e.find((({parts:e})=>F(e.language,t.language)))?.locale}function U(e){return"esri.Graphic"===e?.declaredClass}function N(e){return"no"===e||"nb"===e}function F(e,t){return e===t||N(e)&&N(t)}function O(e){return"esri.rest.support.Stop"===e?.declaredClass}var k;!function(e){e[e.Active=0]="Active",e[e.Complete=1]="Complete",e[e.Failed=2]="Failed",e[e.Idle=3]="Idle",e[e.Suspended=4]="Suspended"}(k||(k={}));let V=class extends(I(i.EventedAccessor)){constructor(e){super(e),this._debouncedSolveHandler=s((async e=>{switch(e.type){case"create":if("complete"!==e.state)return;break;case"delete":break;case"update":switch(e.state){case"start":return void(this._networkFeatureUpdated=!1);case"active":return void(this._networkFeatureUpdated=!0);case"complete":if(!this._networkFeatureUpdated)return}}if(!((this.layer?.stops.filter((({geometry:e})=>!!e)).length??0)<2)&&this.autoSolve)try{await this.getDirections({zoomToSolvedRoute:!1})}catch(t){o.getLogger(this).error(t)}})),this._highlight=null,this._loadController=null,this._loadPromise=null,this._networkFeatureUpdated=!1,this._layerView=null,this._routeController=null,this._serviceDescriptionStatus=k.Idle,this.apiKey=void 0,this.autoSolve=!0,this.defaultTravelMode=null,this.departureIsoDate=void 0,this.departureIsoTime=void 0,this.departureOption=M.NOW,this.departureTime="now",this.lastError=null,this.lastRoute=null,this.layer=null,this.maxStops=50,this.routeParameters=new w({directionsLengthUnits:"kilometers",findBestSequence:!1,preserveFirstStop:!0,preserveLastStop:!0,returnZ:!0,useTimeWindows:!1}),this.serviceDescription=null,this.view=null}initialize(){this.addHandles([l((()=>this.layer),(e=>{if(null!=e){for(;e.stops.length<2;)e.stops.add(new _);this._set("defaultTravelMode",null),this.addHandles(d((()=>this.serviceDescription?e.routeInfo?.analysisSettings?.travelMode:null),(e=>{this.defaultTravelMode=this._resolveDefaultTravelMode(e)}),{once:!0}))}}),u),l((()=>[this.layer,this.view]),(async()=>{this._layerView=await this._getRouteLayerView()}),u),n((()=>this._layerView),["create","delete","update"],(e=>{this._debouncedSolveHandler(e).catch((e=>{if(!a(e))throw e}))}))]);const e=p(this.view?.timeZone??C),t=L.fromMillis(Date.now());this.departureIsoDate=t.toFormat(S,A(e)),this.departureIsoTime=t.toFormat(D,A(e))}get _directionsLanguage(){const e=this.serviceDescription?.directionsSupportedLanguages;if(!e)return;const t=this.routeParameters.directionsLanguage??y(),r=g(t),i=r?.language,o=r?.region;if(!i)return;return E(P(e),{language:i,region:o})}get formattedEta(){const e=this.layer?.routeInfo?.endTime,t=this.layer?.routeInfo?.endTimeOffset;if(this.departureOption===M.UNSPECIFIED||!e||!t)return null;const r=L.fromJSDate(e,{zone:j.instance(t)}),i=L.fromJSDate(e,{zone:R.create(p(this.view?.timeZone??C))}),o=L.fromJSDate(new Date,{zone:R.create(p(this.view?.timeZone??C))}),s=o.year===i.year&&o.month===i.month&&o.day===i.day,a=i.offset===t?void 0:b,l=s?void 0:m("short-date"),n=m("short-time");return v(r.toISO(),{...l,...n,timeZoneName:a})}get impedanceAttribute(){const e=this.routeParameters.travelMode?.impedanceAttributeName??this.routeParameters.impedanceAttribute??this.serviceDescription?.impedance??null;return this.getCostAttribute(e)}get selectedNetworkFeatures(){return this._layerView?.selectedNetworkFeatures??null}get selectedTravelMode(){return this.serviceDescription?this.defaultTravelMode??this.serviceDescription.defaultTravelMode??this.serviceDescription.supportedTravelModes?.[0]??null:null}set selectedTravelMode(e){this._override("selectedTravelMode",e)}get state(){if(this._routeController)return"routing";if(this.lastError)return"error";switch(this._serviceDescriptionStatus){case k.Suspended:return"unauthenticated";case k.Idle:return"disabled";case k.Active:return"initializing";case k.Failed:return"error";default:return"ready"}}get timeAttribute(){const e=this.routeParameters.travelMode?.timeAttributeName??this.routeParameters.directionsTimeAttribute??this.serviceDescription?.directionsTimeAttribute??null;return this.getCostAttribute(e)}get travelModes(){const e=this.serviceDescription?.supportedTravelModes?.slice()??[];return null==this.defaultTravelMode||e.includes(this.defaultTravelMode)||e.unshift(this.defaultTravelMode),e}async load(){if(this._loadPromise)return this._loadPromise;this._loadPromise=this._load(),await this._loadPromise,this._loadPromise=null}async highlight(e){if(this.clearHighlights(),!this.view||!this.layer)return;const t=await this.view.whenLayerView(this.layer);this._highlight=t.highlight(e)}clearHighlights(){null!=this._highlight&&(this._highlight.remove(),this._highlight=null)}centerAt(e){if(!this.view)return;const t=O(e)||U(e)?e.geometry:e;t&&this.callGoTo({target:t})}clearResults(){this._set("lastRoute",null),this.layer?.removeResult()}async create(e){await(this._layerView?.create(e))}async getDirections(e={zoomToSolvedRoute:!0}){const{apiKey:t,layer:i,state:o}=this;if(!i)throw new r("directions-view-model:missing-route-layer","A route layer must be associated with the view model.");if("unauthenticated"===o||"initializing"===o||"disabled"===o||this._serviceDescriptionStatus===k.Failed)throw new r("directions-view-model:not-loaded","Cannot get directions until view model loads.");null!=this._routeController&&(this._routeController.abort(),this._routeController=null);const{startTime:s,startTimeIsUTC:l}=this._getStartTimeParameters(),n=this.view?.spatialReference??null,u=this.routeParameters.clone();u.set({apiKey:t,directionsLanguage:this._directionsLanguage,outSpatialReference:n,startTime:s,startTimeIsUTC:l}),this.selectedTravelMode&&(u.travelMode=this.selectedTravelMode);if(i.stops.filter((({geometry:e})=>null!=e)).length<2){const e=new r("directions-view-model:not-enough-stops","Not enough stops for routing");throw this._set("lastError",e),e}this._routeController=new AbortController;const{signal:d}=this._routeController;let c=null;try{c=await i.solve(u,{signal:d})}catch(h){if(!a(h)){const e=new r("directions-view-model:unable-to-route","Unable to route to these addresses",{error:h});throw this._set("lastError",e),this.clearResults(),e}}finally{this._routeController=null}this._set("lastError",null);for(const r of c.stops)null==r.geometry&&(r.name=null);return i.update(c),this._set("lastRoute",c),e.zoomToSolvedRoute&&this.zoomToRoute(),c}getCostAttribute(e){return(this.serviceDescription?.networkDataset?.networkAttributes??[]).find((({name:t,usageType:r})=>t===e&&"cost"===r))??null}remove(e){this._layerView?.remove(e)}reset(){this.clearHighlights(),this.clearResults(),null!=this.layer&&(this.layer.removeAll(),this.layer.stops=new t([new _,new _]))}save(){if(!this.layer)throw new r("directions-view-model:missing-layer","save() requires a layer");return this.layer.save()}saveAs(e,t={}){if(!this.layer)throw new r("directions-view-model:missing-layer","saveAs() requires a layer");return this.layer.saveAs(e,t)}async startEditing(){this._layerView&&(this._layerView.interactive=!0)}async stopEditing(){this._layerView&&(this._layerView.interactive=!1)}updateDepartureTime(){if(this.departureIsoDate&&this.departureIsoTime)switch(this.departureOption){case M.NOW:this.departureTime="now";break;case M.DEPART_AT:{const e=L.fromISO(`${this.departureIsoDate}T${this.departureIsoTime}`,{zone:j.instance(0)});this.departureTime=e.toJSDate();break}case M.UNSPECIFIED:this.departureTime=null}}zoomToRoute(){const{view:e,layer:t}=this,r=t?.routeInfo?.geometry?.extent;if(!e||!r)return;const i=r.width>r.height,o=r.clone().expand(i?2:1);this.callGoTo({target:o})}async _getRouteLayerView(){return this.view&&this.layer?this.view.whenLayerView(this.layer):null}_getStartTimeParameters(){if("now"===this.departureTime){return{startTime:this.serviceDescription?.capabilities.supportsNow??!1?"now":new Date,startTimeIsUTC:!0}}return null==this.departureTime?{startTime:void 0,startTimeIsUTC:void 0}:{startTime:this.departureTime,startTimeIsUTC:!1}}async _load(){if(null==this.layer)return;null!=this._loadController&&(this._loadController.abort(),this._loadController=null),this._loadController=new AbortController;const{signal:e}=this._loadController;try{this._serviceDescriptionStatus=k.Active;const t=await f(this.layer.url,this.apiKey,{signal:e});this._set("serviceDescription",t),this._serviceDescriptionStatus=k.Complete}catch(t){if(a(t))return void(this._serviceDescriptionStatus=k.Idle);if("identity-manager:user-aborted"===t.name)return void(this._serviceDescriptionStatus=k.Suspended);const e=new r("directions-view-model:service-metadata-unavailable","Cannot load route service metadata",{error:t});throw this._serviceDescriptionStatus=k.Failed,this._set("lastError",e),e}finally{this._loadController=null}}_resolveDefaultTravelMode(e){if(null==this.serviceDescription)return null;const{defaultTravelMode:t,supportedTravelModes:r}=this.serviceDescription,i=/^<(?<name>.*)>$/i.exec(e.name)?.groups?.name;if(i){const o=r?.find((({name:e})=>e.toLocaleLowerCase()===i.trim().toLocaleLowerCase())),s=o??t;return T.fromJSON({...s?.toJSON(),...e.toJSON()})}const o=r?.find((({name:t})=>t.toLocaleLowerCase()===e.name.toLocaleLowerCase()));return o??t}};e([c()],V.prototype,"_directionsLanguage",null),e([c()],V.prototype,"_layerView",void 0),e([c()],V.prototype,"_routeController",void 0),e([c()],V.prototype,"_serviceDescriptionStatus",void 0),e([c()],V.prototype,"apiKey",void 0),e([c()],V.prototype,"autoSolve",void 0),e([c()],V.prototype,"defaultTravelMode",void 0),e([c()],V.prototype,"departureTime",void 0),e([c()],V.prototype,"formattedEta",null),e([c({readOnly:!0})],V.prototype,"impedanceAttribute",null),e([c()],V.prototype,"lastError",void 0),e([c({readOnly:!0})],V.prototype,"lastRoute",void 0),e([c()],V.prototype,"layer",void 0),e([c({type:Number,range:{min:2,max:50},nonNullable:!0})],V.prototype,"maxStops",void 0),e([c({type:w,nonNullable:!0})],V.prototype,"routeParameters",void 0),e([c({readOnly:!0})],V.prototype,"selectedNetworkFeatures",null),e([c({type:T})],V.prototype,"selectedTravelMode",null),e([c({readOnly:!0})],V.prototype,"serviceDescription",void 0),e([c({readOnly:!0})],V.prototype,"state",null),e([c({readOnly:!0})],V.prototype,"timeAttribute",null),e([c()],V.prototype,"travelModes",null),e([c()],V.prototype,"view",void 0),e([c()],V.prototype,"zoomToRoute",null),V=e([h("esri.widgets.Directions.DirectionsViewModel")],V);const z=V;export{z 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.33/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../chunks/tslib.es6.js";import{isSome as t}from"../core/arrayUtils.js";import i from"../core/Collection.js";import{makeHandle as s}from"../core/handleUtils.js";import{debounce as o,isAbortError as r}from"../core/promiseUtils.js";import{watch as a,initial as n,on as l}from"../core/reactiveUtils.js";import{escapeRegExpString as c}from"../core/string.js";import{property as d}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import{subclass as m}from"../core/accessorSupport/decorators/subclass.js";import p from"../portal/Portal.js";import{defaultUnitPropertyMetadata as h}from"../properties/defaultUnit.js";import u from"../rest/support/Stop.js";import v from"../symbols/SimpleMarkerSymbol.js";import _ from"./Search.js";import g from"./Widget.js";import{DirectionsSearchTool as w}from"./Directions/DirectionsSearchTool.js";import y from"./Directions/DirectionsViewModel.js";import b from"./Directions/DirectionsVisibleElements.js";import{formatDistance as f,formatDuration as S,DepartureTimeOption as M,getIconName as k}from"./Directions/support/directionsUtils.js";import{isArcGISWorldGeocoder as I,meteredArcGISLocatorUrl as F}from"./Search/support/locatorUtils.js";import{loadCalciteComponents as T}from"./support/componentsUtils.js";import{globalCss as D}from"./support/globalCss.js";import"./support/widgetUtils.js";import{messageBundle as x}from"./support/decorators/messageBundle.js";import{tsx as C}from"./support/jsxFactory.js";function E(e){const{branchName:i,displayText:s,exitName:o,intersectingName:r,name:a,towardName:n}=e;if(null==s)return null;const l=[i,o,r,a,n].filter(t).sort(((e,t)=>t.length-e.length)).map((e=>c(e)));if(!l.length)return s;const d=new RegExp(l.join("|"),"g"),m=s.matchAll(d);let p=0;const h=[];for(const{0:t,index:c}of m)h.push(s.slice(p,c),C("span",{class:R.labelEmphasize,key:`maneuver-${c}`},t)),p=c+t.length;return h.push(s.slice(p)),C("span",null,h)}function $(e){const t=new Date(e);return new Date(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())}const L="esri-directions",R={base:L,accordion:`${L}__accordion`,actionContainer:`${L}__action-container`,addStopButton:`${L}__add-stop-button`,departureTime:`${L}__departure-time`,departureTimeOptions:`${L}__departure-time-options`,directionsHeader:`${L}__directions-header`,directionsHeaderStopName:`${L}__directions-header-stop-name`,editFooter:`${L}__edit-footer`,editToolbar:`${L}__edit-toolbar`,editToolbarContainer:`${L}__edit-toolbar-container`,flexColumn:`${L}__flex-column`,flexRow:`${L}__flex-row`,headerStops:`${L}__header-stops`,labelEmphasize:`${L}__label-emphasize`,labelNoBottomMargin:`${L}__label-no-bottom-margin`,marginInlineMedium:`${L}__margin-inline-medium`,optimizeSection:`${L}__optimize-section`,optimizeSwitches:`${L}__optimize-switches`,paddingMedium:`${L}__padding-medium`,primaryFlowItem:`${L}__primary-flow-item`,primaryFooter:`${L}__primary-footer`,primaryFooterCentered:`${L}__primary-footer-centered`,primaryFooterLoader:`${L}__primary-footer-loader`,routeItem:`${L}__route-item`,routeItemButton:`${L}__route-item-button`,routeItemButtonContent:`${L}__route-item-button-content`,routeItemLabel:`${L}__route-item-label`,routeItemDescription:`${L}__route-item-description`,saveError:`${L}__save-error`,saveErrorIcon:`${L}__save-error-icon`,saveErrorLabel:`${L}__save-error-label`,saveProcessLoader:`${L}__save-process-loader`,selectedFeatureContainer:`${L}__selected-feature-container`,separator:`${L}__separator`,solveRoute:`${L}__solve-route`,stopContainer:`${L}__stop-container`,stopList:`${L}__stop-list`,stopItem:`${L}__stop-item`};let A=class extends g{constructor(e,t){super(e,t),this._activeManeuver=null,this._placeholderStops=new i([new u,new u]),this._portalFolderCombobox=null,this._portalFolders=null,this._portalItemNameInput=null,this._portalUserName=null,this._sections=null,this._stopsToSearches=new Map,this._currentFlowItem="primary",this._parentFlowItem="primary",this._saveState="initialized",this._searchTool=null,this.headingLevel=2,this.messages=null,this.messagesUnits=null,this.searchProperties=null,this.viewModel=new y,this.visibleElements=new b,this._solveRouteDebounced=o((()=>this._solveRoute()))}initialize(){this.addHandles([a((()=>this.viewModel.layer),(()=>{try{this.viewModel.load()}catch{}}),n),a((()=>this.viewModel.layer?.routeInfo),(()=>{this._sections=this._getStopSections()}),n),a((()=>this.viewModel.layer?.stops.toArray()),(e=>{e&&this.view?.activeTool&&this._searchTool&&this.view.activeTool===this._searchTool&&!e.includes(this._searchTool.stop)&&(this.view.tools.remove(this._searchTool),this._searchTool=null)}))])}loadDependencies(){return T({accordion:()=>import("@esri/calcite-components/dist/components/calcite-accordion"),"accordion-item":()=>import("@esri/calcite-components/dist/components/calcite-accordion-item"),action:()=>import("@esri/calcite-components/dist/components/calcite-action"),"block-section":()=>import("@esri/calcite-components/dist/components/calcite-block-section"),button:()=>import("@esri/calcite-components/dist/components/calcite-button"),combobox:()=>import("@esri/calcite-components/dist/components/calcite-combobox"),"combobox-item":()=>import("@esri/calcite-components/dist/components/calcite-combobox-item"),dropdown:()=>import("@esri/calcite-components/dist/components/calcite-dropdown"),flow:()=>import("@esri/calcite-components/dist/components/calcite-flow"),"flow-item":()=>import("@esri/calcite-components/dist/components/calcite-flow-item"),icon:()=>import("@esri/calcite-components/dist/components/calcite-icon"),input:()=>import("@esri/calcite-components/dist/components/calcite-input"),"input-date-picker":()=>import("@esri/calcite-components/dist/components/calcite-input-date-picker"),"input-time-picker":()=>import("@esri/calcite-components/dist/components/calcite-input-time-picker"),label:()=>import("@esri/calcite-components/dist/components/calcite-label"),list:()=>import("@esri/calcite-components/dist/components/calcite-list"),"list-item":()=>import("@esri/calcite-components/dist/components/calcite-list-item"),loader:()=>import("@esri/calcite-components/dist/components/calcite-loader"),notice:()=>import("@esri/calcite-components/dist/components/calcite-notice"),panel:()=>import("@esri/calcite-components/dist/components/calcite-panel"),switch:()=>import("@esri/calcite-components/dist/components/calcite-switch")})}get apiKey(){return this.viewModel.apiKey}set apiKey(e){this.viewModel.apiKey=e}get goToOverride(){return this.viewModel.goToOverride}set goToOverride(e){this.viewModel.goToOverride=e}get icon(){return"right"}set icon(e){this._overrideIfSome("icon",e)}get label(){return this.messages?.widgetLabel??""}set label(e){this._overrideIfSome("label",e)}get lastRoute(){return this.viewModel.lastRoute}get layer(){return this.viewModel.layer}set layer(e){this.viewModel.layer=e}get maxStops(){return this.viewModel.maxStops}set maxStops(e){this.viewModel.maxStops=e}get unit(){return this.defaultUnit}set unit(e){this._overrideIfSome("unit",e)}get view(){return this.viewModel.view}set view(e){this.viewModel.view=e}acquireSearch(e){const{view:t}=this.viewModel;if(this._stopsToSearches.has(e)){const i=this._stopsToSearches.get(e);return i.view=t,this._overrideDefaultSources(i),i}const i=new _({icon:!1,popupEnabled:!1,resultGraphicEnabled:!1,view:t,...this.searchProperties});return this._normalizeSearchSources(i),this.addHandles([l((()=>i.allSources),"change",(()=>this._normalizeSearchSources(i))),i.on("search-clear",(()=>{e.geometry=null,e.name=null,this.viewModel.layer?.removeResult()})),i.on("select-result",(()=>{const t=i.selectedResult;e.geometry=t?.feature.geometry,e.name=t?.name,this._solveRouteDebounced()})),a((()=>i.searchTerm),(t=>{e.name=t}))],i),this._stopsToSearches.set(e,i),i}getDirections(){return this.viewModel.getDirections()}render(){return C("div",{class:this.classes(R.base,D.widget,D.panel)},C("calcite-flow",null,this._renderPrimaryFlowItem(),this._renderDirectionsFlowItem(),this._renderEditFlowItem(),this._renderSaveFlowItem()))}save(){return this.viewModel.save()}saveAs(e,t={}){return this.viewModel.saveAs(e,t)}zoomToRoute(){return this.viewModel.zoomToRoute()}_applyLocatorSourceOverrides({allSources:e}){for(const t of e)"url"in t&&t.url&&(t.locationType??="street",I(t.url)&&this.apiKey&&null==t.apiKey&&(t.apiKey=this.apiKey,t.url=F))}_disposeSearch(e){if(!e||!this._stopsToSearches.has(e))return;const t=this._stopsToSearches.get(e);this.removeHandles(t),t.destroy(),this._stopsToSearches.delete(e)}_getEffectiveStops(){return this.viewModel.layer?.stops??this._placeholderStops}_getErrorDescription(){switch(this.viewModel.lastError?.name){case"directions-view-model:unable-to-route":return this.messages.errors.unableToRoute;case"directions-view-model:service-metadata-unavailable":return this.messages.errors.unableToLoadServiceMetadata;default:return this.messages.errors.unknownError}}_getNetworkFeatureName(e){switch(e.type){case"stop":switch(e.locationType){case"stop":default:return this.messages.networkFeatures.stops.stop;case"waypoint":return this.messages.networkFeatures.stops.waypoint;case"break":return this.messages.networkFeatures.stops.break}case"point-barrier":return this.messages.networkFeatures.pointBarrier;case"polyline-barrier":return this.messages.networkFeatures.polylineBarrier;case"polygon-barrier":return this.messages.networkFeatures.polygonBarrier}}_getRouteCostSummary(){const e=this.viewModel.layer?.routeInfo;if(!e)return null;const t=e.totalDistance??0,i=e.totalDuration??0,{messagesUnits:s,unit:o}=this;return{distance:f(s,t,o),duration:S(i)}}_getStopSections(){if(!this.viewModel.layer)return null;const{directionPoints:e,directionLines:t,stops:i}=this.viewModel.layer;if(!e||!t)return null;const s=[];let o=null;for(const r of e){const{objectId:e,stopId:a}=r;if(null!=a){const e=i.find((({objectId:e})=>e===a));o&&o.stop===e||(o={stop:e,directions:[]},s.push(o));continue}if(null==o)continue;const n=t.find((({directionPointId:t})=>t===e));null!=n&&o.directions.push({directionPoint:r,directionLine:n})}return s}_handleLocateStopAction(e){const{view:t}=this;if(!t)return;const i="directions-search-tool";this.removeHandles(i),this._searchTool=new w({stop:e,view:t}),this.addHandles([this._searchTool.on("click",(async t=>{if(t.mapPoint&&this._stopsToSearches.has(e)){const i=this._stopsToSearches.get(e),s=await i.search(t.mapPoint),o=s?.results?.[0].results?.[0];if(o){const{feature:t,name:s}=o;i.searchTerm=s,e.geometry=t.geometry}}this.removeHandles(i)})),s((()=>{this._searchTool&&(this.view?.tools.remove(this._searchTool),this._searchTool=null)}))],i),t.addAndActivateTool(this._searchTool)}_handleEditingDoneClick(){this.viewModel.stopEditing(),this._currentFlowItem="primary"}async _handleSaveLayerAsAction(){const e=p.getDefault();try{await e.signIn()}catch(t){if(r(t)||"identity-manager:user-aborted"===t.name)return;return this._parentFlowItem=this._currentFlowItem,this._currentFlowItem="save",void(this._saveState="connect-to-portal-error")}this._saveState="fetch-portal-information",this._parentFlowItem=this._currentFlowItem,this._currentFlowItem="save",this._portalUserName=e.user?.username;try{this._portalFolders=await(e.user?.fetchFolders())}catch{return void(this._saveState="fetch-portal-information-error")}this._saveState="save-layer"}_normalizeSearchSources(e){this._overrideDefaultSources(e),this._applyLocatorSourceOverrides(e)}_overrideDefaultSources(e){for(const t of e.viewModel.defaultSources)t.autoNavigate=!1}_renderClearRouteAction(e){return C("calcite-action",{icon:"trash",key:"clear-route",onclick:()=>{this._currentFlowItem="primary",this.viewModel.reset()},...e,text:this.messages.common.clear,textEnabled:!0})}_renderDeleteStopAction(e){const t=this._getEffectiveStops();return C("calcite-action",{icon:"trash",onclick:()=>{t.remove(e),this._disposeSearch(e),this._solveRouteDebounced()},scale:"s",slot:"actions-end",text:this.messages.deleteStop,title:this.messages.deleteStop})}_renderDepartureTime(){const{DEPART_AT:e,NOW:t,UNSPECIFIED:i}=M;return C("calcite-label",{class:R.departureTime,key:"departure-time"},this.messages.departureTime,C("calcite-combobox",{clearDisabled:!0,label:this.messages.departureTime,overlayPositioning:"fixed",selectionMode:"single",onCalciteComboboxChange:({currentTarget:e})=>{const{selectedItems:t}=e;t.length&&(this.viewModel.departureOption=t[0].value,this._solveRouteDebounced())}},C("calcite-combobox-item",{heading:this.messages.leaveNow,key:t,label:this.messages.leaveNow,selected:this.viewModel.departureOption===t,value:t}),C("calcite-combobox-item",{heading:this.messages.departAt,key:e,label:this.messages.departAt,selected:this.viewModel.departureOption===e,value:e}),C("calcite-combobox-item",{heading:this.messages.timeUnspecified,key:i,label:this.messages.timeUnspecified,selected:this.viewModel.departureOption===i,value:i})))}_renderDepartureTimeOptions(){return this.viewModel.departureOption!==M.DEPART_AT?null:C("div",{class:R.departureTimeOptions},C("calcite-input-date-picker",{scale:"s",valueAsDate:$(this.viewModel.departureIsoDate),onCalciteInputDatePickerChange:({currentTarget:{value:e}})=>{this.viewModel.departureIsoDate=e,this._solveRouteDebounced()}}),C("calcite-input-time-picker",{scale:"s",value:this.viewModel.departureIsoTime,onCalciteInputTimePickerChange:({currentTarget:{value:e}})=>{this.viewModel.departureIsoTime=e,this._solveRouteDebounced()}}))}_renderDirectionsFlowItem(){if("directions"!==this._currentFlowItem)return null;const e=this._getRouteCostSummary();if(!this._sections||!e)return null;const{distance:t,duration:i}=e,{formattedEta:s}=this.viewModel,o=this._sections.at(0)?.stop.name??"",r=this._sections.at(-1)?.stop.name??"";return C("calcite-flow-item",{key:"directions-flow-item",overlayPositioning:"fixed",selected:"directions"===this._currentFlowItem,onCalciteFlowItemBack:e=>{e.stopPropagation(),this._currentFlowItem="primary"}},C("div",{class:R.directionsHeader,slot:"header-content"},C("div",{class:R.headerStops},C("span",null,this.messages.from)," ",C("span",{class:R.directionsHeaderStopName},o),C("span",null,this.messages.to)," ",C("span",{class:R.directionsHeaderStopName},r)),C("div",{class:R.flexColumn},C("span",null,`${i} (${t})`),s?C("span",null,s):null)),this._renderRouteLayerActions({slot:"header-menu-actions"}),C("calcite-accordion",{class:R.accordion,iconPosition:"start",selectionMode:"single"},this._sections.map(((e,t)=>{const{stop:i,directions:s}=e,{name:o}=i;return C("calcite-accordion-item",{expanded:0===t,heading:o??"",key:`stop-${t}`},C("calcite-action",{icon:"zoom-to-object",onclick:()=>{this.viewModel.centerAt(i)},slot:"actions-end",text:this.messages.panToStop}),this._renderDirectionTurns(s))}))))}_renderDirectionTurns(e){return C("calcite-list",{label:this.messages.drivingDirections,selectionMode:"none"},e.map(((e,t)=>{const{directionPoint:i,directionLine:s}=e,{distance:o,duration:r}=s,a=f(this.messagesUnits,o??0,this.unit),n=S(r??0),l=a&&n?`${a} | ${n}`:`${a||n}`,c=E(i),d=k(i.directionPointType);return C("calcite-list-item",{class:R.labelNoBottomMargin,key:`driving-direction-${t}`,onpointerenter:()=>{this.viewModel.highlight(s)},onpointerleave:()=>{this.viewModel.clearHighlights()},onCalciteListItemSelect:()=>{this._activeManeuver===s?this.zoomToRoute():(this._activeManeuver=s,this.viewModel.centerAt(s.geometry))}},C("calcite-icon",{icon:d,slot:"content-start"}),C("div",{slot:"content"},C("calcite-label",{layout:"inline",scale:"s"},c),C("calcite-label",{layout:"inline",scale:"s"},l)))})))}_renderEditFlowItem(){return"edit"!==this._currentFlowItem?null:C("calcite-flow-item",{heading:this.messages.editRoute,headingLevel:this.headingLevel,key:"edit-flow-item",loading:"routing"===this.viewModel.state,selected:"edit"===this._currentFlowItem,onCalciteFlowItemBack:e=>{e.stopPropagation(),this.viewModel.stopEditing(),this._currentFlowItem="primary"}},C("div",{class:R.flexColumn,key:"edit-container"},C("div",{class:R.editToolbarContainer},C("calcite-label",{layout:"inline",scale:"s"},this.messages.automaticallySolve,C("calcite-switch",{checked:this.viewModel.autoSolve,scale:"s",onCalciteSwitchChange:e=>{this.viewModel.autoSolve=e.target.checked}})),C("div",{class:R.editToolbar},C("calcite-action",{icon:"flag",onclick:()=>{this.viewModel.create("stop")},scale:"s",text:this.messages.networkFeatures.stops.stop,textEnabled:!0}),C("calcite-action",{icon:"line",onclick:()=>{this.viewModel.create("polyline-barrier")},scale:"s",text:this.messages.barrier,textEnabled:!0}),C("calcite-action",{class:R.solveRoute,disabled:this.viewModel.autoSolve,icon:"refresh",onclick:()=>{this._solveRouteDebounced()},scale:"s",text:this.messages.solve,textEnabled:!0}))),C("div",{class:R.selectedFeatureContainer},C("calcite-list",{label:this.messages.selectedNetworkFeatures,scale:"s",selectionMode:"none"},this.viewModel.selectedNetworkFeatures?.toArray().map(((e,t)=>C("calcite-list-item",{description:this._getNetworkFeatureName(e),key:`network-feature-${t}`,label:e.name??e.objectId?.toString()??this.messages.unnamed},C("calcite-action",{icon:"trash",onclick:()=>{this.viewModel.remove(e)},scale:"s",slot:"actions-end",text:this.messages.common.delete})))))),C("div",{class:R.editFooter},this._renderEditFooterContent())))}_renderEditFooterContent(){return this.viewModel.lastError?this._renderErrorNotice():C("calcite-button",{appearance:"outline-fill",bind:this,onclick:this._handleEditingDoneClick,width:"full"},this.messages.common.done)}_renderErrorNotice(){return C("calcite-notice",{icon:"exclamation-mark-circle",kind:"danger",open:!0},C("calcite-label",{class:R.labelNoBottomMargin,slot:"message"},this._getErrorDescription()))}_renderFooter(){if(!this.viewModel.layer)return C("div",{class:R.primaryFooter,key:"footer-missing-layer"},C("calcite-notice",{icon:"information",open:!0},C("calcite-label",{class:R.labelNoBottomMargin,slot:"message"},this.messages.missingLayer)));if("unauthenticated"===this.viewModel.state)return C("div",{class:R.primaryFooterCentered,key:"footer-sign-in"},C("calcite-label",null,this.messages.signInRequired),C("calcite-button",{onclick:()=>{this.viewModel.load().catch((()=>{}))}},this.messages.common.auth.signIn));if("routing"===this.viewModel.state)return C("div",{class:this.classes(R.primaryFooter,R.primaryFooterLoader),key:"footer-routing"},C("calcite-loader",{label:this.messages.solve,scale:"s"}));if("error"===this.viewModel.state)return C("div",{class:R.primaryFooter,key:"footer-service-error"},this._renderErrorNotice());if(!this.viewModel.layer?.routeInfo)return C("div",{class:R.primaryFooter,key:"footer-unsolved-route"},C("calcite-notice",{icon:"information",open:!0},C("calcite-label",{class:R.labelNoBottomMargin,slot:"message"},this.messages.directionsPlaceholder)));const e=this._getRouteCostSummary();if(!e||!this.viewModel.layer?.directionPoints)return C("div",{class:R.primaryFooter,key:"footer-invalid-route"},C("calcite-notice",{icon:"exclamation-mark-triangle",kind:"danger",open:!0},C("calcite-label",{class:R.labelNoBottomMargin,slot:"message"},this.messages.invalidRoute)));const{distance:t,duration:i}=e,{formattedEta:s}=this.viewModel;return C("div",{class:R.routeItem,key:"footer-directions-summary"},C("button",{"aria-busy":"false","aria-label":this.messages.viewDrivingDirections,"aria-live":"polite",class:R.routeItemButton,onclick:()=>{this._currentFlowItem="directions"},type:"button"},C("div",{class:R.routeItemButtonContent},C("span",{class:R.routeItemLabel},`${i} (${t})`),C("span",{class:R.routeItemDescription},s)),C("calcite-icon",{icon:"chevron-right",scale:"s"})),C("calcite-dropdown",null,C("calcite-action",{icon:"ellipsis",slot:"trigger",text:"Route actions"}),this._renderRouteLayerActions()))}_renderInteractiveRouteActions(){return C("div",{class:R.actionContainer,key:"interactive-route-action-container"},C("calcite-button",{appearance:"outline",class:R.addStopButton,disabled:this._getEffectiveStops().length>=this.maxStops,iconStart:"plus",kind:"neutral",label:this.messages.addStop,onclick:()=>{const e=new v;this.viewModel.layer?.stops.add(new u({symbol:e}))},width:"half"},this.messages.addStop),C("calcite-button",{appearance:"outline",disabled:"2d"!==this.viewModel.view?.type,iconStart:"pencil",kind:"neutral",label:this.messages.editRoute,onclick:()=>{this._currentFlowItem="edit",this.viewModel.startEditing()},width:"half"},this.messages.editRoute))}_renderLocateStopAction(e){if(null!=e.name||null!=e.geometry)return null;const t=this._getEffectiveStops().indexOf(e),i=!!this.view?.activeTool&&this.view.activeTool===this._searchTool&&this._searchTool.stop===e;return C("calcite-action",{active:i,icon:"crosshair",key:`stop-location-action-${t}`,onclick:()=>this._handleLocateStopAction(e),scale:"s",slot:"actions-end",text:this.messages.pickALocationOnTheMap,title:this.messages.pickALocationOnTheMap})}_renderOptimizeStopOrder(){const{routeParameters:e}=this.viewModel,{findBestSequence:t,preserveFirstStop:i,preserveLastStop:s}=e;return C("calcite-block-section",{class:R.optimizeSection,text:this.messages.optimizeOrder,toggleDisplay:"switch",onCalciteBlockSectionToggle:({target:t})=>{e.findBestSequence=t.open,t.open||this._resetStopSequence(),this._solveRouteDebounced()}},t?[C("calcite-label",{class:R.optimizeSwitches,key:"preserve-first-stop",layout:"inline-space-between"},this.messages.preserveFirstStop,C("calcite-switch",{checked:i,scale:"s",onCalciteSwitchChange:({target:{checked:t}})=>{e.preserveFirstStop=t,this._resetStopSequence(),this._solveRouteDebounced()}})),C("calcite-label",{class:R.optimizeSwitches,key:"preserve-last-stop",layout:"inline-space-between"},this.messages.preserveLastStop,C("calcite-switch",{checked:s,scale:"s",onCalciteSwitchChange:({target:{checked:t}})=>{e.preserveLastStop=t,this._resetStopSequence(),this._solveRouteDebounced()}}))]:null)}_renderPrimaryFlowItem(){return C("calcite-flow-item",{key:"primary-flow-item",loading:"initializing"===this.viewModel.state,selected:"primary"===this._currentFlowItem},C("calcite-panel",{class:R.primaryFlowItem,disabled:!this.viewModel.layer||"unauthenticated"===this.viewModel.state||"error"===this.viewModel.state&&!this.viewModel.serviceDescription},this._renderStops(),this._renderInteractiveRouteActions(),this._renderSeparator(),this._renderRouteSolveOptions()),this._renderFooter())}_renderRouteLayerActions(e){return[this._renderClearRouteAction(e),this._renderSaveLayerAction(e),this._renderSaveLayerAsAction(e),this._renderViewItemDetailsAction(e)]}_renderRouteSolveOptions(){return C("div",{class:R.marginInlineMedium,key:"route-solve-options"},this._renderTravelModes(),this._renderDepartureTime(),this._renderDepartureTimeOptions(),this._renderOptimizeStopOrder())}_renderSaveContent(){switch(this._saveState){case"initialized":return this._renderSaveInitialized();case"connect-to-portal":return this._renderSaveProcessing(this.messages.identity.lblSigning);case"connect-to-portal-error":return this._renderSaveError(this.messages.errors.authenticating);case"fetch-portal-information":return this._renderSaveProcessing(this.messages.processing.fetching);case"fetch-portal-information-error":return this._renderSaveError(this.messages.errors.fetching);case"save-layer":return this._renderSaveLayerSettings();case"saving":return this._renderSaveProcessing(this.messages.processing.saving);case"saving-error":return this._renderSaveError(this.messages.errors.saving)}}_renderSaveError(e){return C("calcite-panel",{class:R.paddingMedium,key:"save-layer-error"},C("div",{class:R.saveError},C("calcite-icon",{class:R.saveErrorIcon,icon:"exclamation-mark-triangle",scale:"l",textLabel:this.messages.common.errorMessage}),C("calcite-label",{class:R.saveErrorLabel},e)),C("calcite-button",{appearance:"outline",onclick:()=>{this._currentFlowItem=this._parentFlowItem},slot:"footer-actions",width:"full"},this.messages.common.close))}_renderSaveInitialized(){return C("calcite-panel",{class:R.paddingMedium,key:"save-layer-initialized"})}_renderSaveFlowItem(){return"save"!==this._currentFlowItem?null:C("calcite-flow-item",{heading:this.messages.saveLayer,headingLevel:this.headingLevel,key:"save-layer-flow-item",selected:"save"===this._currentFlowItem,onCalciteFlowItemBack:e=>{e.stopPropagation(),this._currentFlowItem=this._parentFlowItem}},this._renderSaveContent())}_renderSaveLayerAction(e){if(!this.visibleElements.saveButton)return null;const t=this.viewModel.layer,i=t?.routeInfo,s=t?.portalItem?.itemControl;return C("calcite-action",{disabled:!(!!i&&("admin"===s||"update"===s)),icon:"save",key:"save-route",onclick:()=>{this.viewModel.layer?.save()},...e,text:this.messages.common.save,textEnabled:!0})}_renderSaveLayerAsAction(e){if(!this.visibleElements.saveAsButton)return null;const t=!this.viewModel.layer?.routeInfo;return C("calcite-action",{disabled:t,icon:"save-as",key:"save-as-route",onclick:()=>{this._handleSaveLayerAsAction()},...e,text:this.messages.common.saveAs,textEnabled:!0})}_renderSaveLayerSettings(){if(null==this.layer||null==this._portalFolders||null==this._portalUserName)return this._renderSaveInitialized();const{stops:e}=this.layer,t=`${e.at(0).name} - ${e.at(-1).name}`,i=this._portalFolders.map((e=>C("calcite-combobox-item",{heading:e.title??"",key:`${L}-folder-${e.id}`,value:e.id})));return i.unshift(C("calcite-combobox-item",{heading:`${this._portalUserName} (${this.messages.common.home})`,key:`${L}-folder-home`,selected:!0,value:null})),C("calcite-panel",{key:"save-layer-panel"},C("div",{class:R.paddingMedium},C("calcite-label",null,this.messages.laverName,C("calcite-input",{afterCreate:e=>{this._portalItemNameInput=e},label:this.messages.laverName,value:t})),C("calcite-label",null,this.messages.saveInFolder,C("calcite-combobox",{afterCreate:e=>{this._portalFolderCombobox=e},label:this.messages.saveInFolder,overlayPositioning:"fixed",selectionMode:"single"},i))),C("calcite-button",{onclick:()=>{if(this._saveState="saving",null==this.layer||null==this._portalFolders)return;const e=this._portalItemNameInput?.value,t=this._portalFolderCombobox?.value,i=this._portalFolders.find((({id:e})=>e===t));this.layer.saveAs({title:e},{folder:i}).then((()=>{this._currentFlowItem=this._parentFlowItem})).catch((()=>{this._saveState="saving-error"}))},slot:"footer-actions",width:"full"},this.messages.common.save),C("calcite-button",{appearance:"outline",onclick:()=>{this._currentFlowItem=this._parentFlowItem},slot:"footer-actions",width:"full"},this.messages.common.cancel))}_renderSaveProcessing(e){return C("calcite-panel",{class:R.marginInlineMedium,key:"save-layer-processing"},C("calcite-loader",{class:R.saveProcessLoader,label:e,text:e}))}_renderSeparator(){return C("div",{class:R.separator})}_renderStop(e){const t=this.acquireSearch(e);null!=e.name&&(t.searchTerm=e.name);const i=this._getEffectiveStops(),s=this._renderLocateStopAction(e),o=i.length>2&&this._renderDeleteStopAction(e);return C("calcite-list-item",{key:e,value:e},s,o,C("div",{class:R.stopItem,slot:"content"},t.render()))}_renderStops(){const e=this._getEffectiveStops();for(const t of this._stopsToSearches.keys())e.includes(t)||this._disposeSearch(t);return C("div",{class:R.stopContainer,key:R.stopContainer},C("calcite-list",{class:R.stopList,dragEnabled:!0,label:this.messages.widgetLabel,scale:"s",onCalciteListOrderChange:({detail:t})=>{e.reorder(t.dragEl.value,t.newIndex),this._resetStopSequence(),this._solveRouteDebounced()}},e.toArray().map((e=>this._renderStop(e)))),2===e.length&&C("calcite-action",{icon:"arrow-up-down",onclick:()=>{e.reverse(),this._resetStopSequence(),this._solveRouteDebounced()},scale:"s",text:this.messages.reverseStops}))}_renderTravelModes(){return this.viewModel.travelModes.length?C("calcite-label",{key:"travel-modes"},this.messages.mode,C("calcite-combobox",{clearDisabled:!0,label:this.messages.mode,overlayPositioning:"fixed",selectionMode:"single",onCalciteComboboxChange:({currentTarget:e})=>{const{selectedItems:t}=e;t.length&&(this.viewModel.selectedTravelMode=t[0].value,this._solveRouteDebounced())}},this.viewModel.travelModes.map((e=>C("calcite-combobox-item",{heading:e.name,key:e.id,label:e.name,selected:this.viewModel.selectedTravelMode?.id===e.id,value:e}))))):null}_renderViewItemDetailsAction(e){if(!this.visibleElements.layerDetails)return null;const t=this.viewModel.layer?.portalItem;return C("calcite-action",{disabled:!t,icon:"launch",key:"open-route-details-link",onclick:()=>{t&&window.open(`${t.portal.url}/home/item.html?id=${t.id}`,"_blank")},...e,text:this.messages.viewLayerDetails,textEnabled:!0})}_resetStopSequence(){this.viewModel.layer?.stops.forEach((e=>{e.sequence=null}))}async _solveRoute(){this.viewModel.updateDepartureTime();if(!((this.viewModel.layer?.stops.filter((({geometry:e})=>!!e)).length??0)<2))try{await this.viewModel.getDirections()}catch{}}};e([d()],A.prototype,"_currentFlowItem",void 0),e([d()],A.prototype,"_saveState",void 0),e([d()],A.prototype,"_searchTool",void 0),e([d()],A.prototype,"apiKey",null),e([d(h)],A.prototype,"defaultUnit",void 0),e([d()],A.prototype,"goToOverride",null),e([d()],A.prototype,"headingLevel",void 0),e([d()],A.prototype,"icon",null),e([d()],A.prototype,"label",null),e([d({readOnly:!0})],A.prototype,"lastRoute",null),e([d()],A.prototype,"layer",null),e([d()],A.prototype,"maxStops",null),e([d(),x("esri/widgets/Directions/t9n/Directions")],A.prototype,"messages",void 0),e([d(),x("esri/core/t9n/Units")],A.prototype,"messagesUnits",void 0),e([d()],A.prototype,"searchProperties",void 0),e([d()],A.prototype,"unit",null),e([d()],A.prototype,"view",null),e([d({type:y})],A.prototype,"viewModel",void 0),e([d({type:b,nonNullable:!0})],A.prototype,"visibleElements",void 0),A=e([m("esri.widgets.Directions")],A);const N=A;export{N as default};
5
+ import{_ as e}from"../chunks/tslib.es6.js";import{isSome as t}from"../core/arrayUtils.js";import i from"../core/Collection.js";import{makeHandle as s}from"../core/handleUtils.js";import{debounce as o,isAbortError as r}from"../core/promiseUtils.js";import{watch as a,initial as n,on as l}from"../core/reactiveUtils.js";import{escapeRegExpString as c}from"../core/string.js";import{property as d}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import{subclass as m}from"../core/accessorSupport/decorators/subclass.js";import p from"../portal/Portal.js";import{defaultUnitPropertyMetadata as h}from"../properties/defaultUnit.js";import u from"../rest/support/Stop.js";import v from"../symbols/SimpleMarkerSymbol.js";import _ from"./Search.js";import g from"./Widget.js";import{DirectionsSearchTool as w}from"./Directions/DirectionsSearchTool.js";import y from"./Directions/DirectionsViewModel.js";import b from"./Directions/DirectionsVisibleElements.js";import{formatDistance as f,formatDuration as S,DepartureTimeOption as M,getIconName as k}from"./Directions/support/directionsUtils.js";import{isArcGISWorldGeocoder as I,meteredArcGISLocatorUrl as F}from"./Search/support/locatorUtils.js";import{loadCalciteComponents as T}from"./support/componentsUtils.js";import{globalCss as D}from"./support/globalCss.js";import"./support/widgetUtils.js";import{messageBundle as x}from"./support/decorators/messageBundle.js";import{tsx as C}from"./support/jsxFactory.js";function E(e){const{branchName:i,displayText:s,exitName:o,intersectingName:r,name:a,towardName:n}=e;if(null==s)return null;const l=[i,o,r,a,n].filter(t).sort(((e,t)=>t.length-e.length)).map((e=>c(e)));if(!l.length)return s;const d=new RegExp(l.join("|"),"g"),m=s.matchAll(d);let p=0;const h=[];for(const{0:t,index:c}of m)h.push(s.slice(p,c),C("span",{class:A.labelEmphasize,key:`maneuver-${c}`},t)),p=c+t.length;return h.push(s.slice(p)),C("span",null,h)}function $(e){if(!e)return;const t=new Date(e);return new Date(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())}const L="esri-directions",A={base:L,accordion:`${L}__accordion`,actionContainer:`${L}__action-container`,addStopButton:`${L}__add-stop-button`,departureTime:`${L}__departure-time`,departureTimeOptions:`${L}__departure-time-options`,directionsHeader:`${L}__directions-header`,directionsHeaderStopName:`${L}__directions-header-stop-name`,editFooter:`${L}__edit-footer`,editToolbar:`${L}__edit-toolbar`,editToolbarContainer:`${L}__edit-toolbar-container`,flexColumn:`${L}__flex-column`,flexRow:`${L}__flex-row`,headerStops:`${L}__header-stops`,labelEmphasize:`${L}__label-emphasize`,labelNoBottomMargin:`${L}__label-no-bottom-margin`,marginInlineMedium:`${L}__margin-inline-medium`,optimizeSection:`${L}__optimize-section`,optimizeSwitches:`${L}__optimize-switches`,paddingMedium:`${L}__padding-medium`,primaryFlowItem:`${L}__primary-flow-item`,primaryFooter:`${L}__primary-footer`,primaryFooterCentered:`${L}__primary-footer-centered`,primaryFooterLoader:`${L}__primary-footer-loader`,routeItem:`${L}__route-item`,routeItemButton:`${L}__route-item-button`,routeItemButtonContent:`${L}__route-item-button-content`,routeItemLabel:`${L}__route-item-label`,routeItemDescription:`${L}__route-item-description`,saveError:`${L}__save-error`,saveErrorIcon:`${L}__save-error-icon`,saveErrorLabel:`${L}__save-error-label`,saveProcessLoader:`${L}__save-process-loader`,selectedFeatureContainer:`${L}__selected-feature-container`,separator:`${L}__separator`,solveRoute:`${L}__solve-route`,stopContainer:`${L}__stop-container`,stopList:`${L}__stop-list`,stopItem:`${L}__stop-item`};let R=class extends g{constructor(e,t){super(e,t),this._activeManeuver=null,this._placeholderStops=new i([new u,new u]),this._portalFolderCombobox=null,this._portalFolders=null,this._portalItemNameInput=null,this._portalUserName=null,this._sections=null,this._stopsToSearches=new Map,this._currentFlowItem="primary",this._parentFlowItem="primary",this._saveState="initialized",this._searchTool=null,this.headingLevel=2,this.messages=null,this.messagesUnits=null,this.searchProperties=null,this.viewModel=new y,this.visibleElements=new b,this._solveRouteDebounced=o((()=>this._solveRoute()))}initialize(){this.addHandles([a((()=>this.viewModel.layer),(()=>{try{this.viewModel.load()}catch{}}),n),a((()=>this.viewModel.layer?.routeInfo),(()=>{this._sections=this._getStopSections()}),n),a((()=>this.viewModel.layer?.stops.toArray()),(e=>{e&&this.view?.activeTool&&this._searchTool&&this.view.activeTool===this._searchTool&&!e.includes(this._searchTool.stop)&&(this.view.tools.remove(this._searchTool),this._searchTool=null)}))])}loadDependencies(){return T({accordion:()=>import("@esri/calcite-components/dist/components/calcite-accordion"),"accordion-item":()=>import("@esri/calcite-components/dist/components/calcite-accordion-item"),action:()=>import("@esri/calcite-components/dist/components/calcite-action"),"block-section":()=>import("@esri/calcite-components/dist/components/calcite-block-section"),button:()=>import("@esri/calcite-components/dist/components/calcite-button"),combobox:()=>import("@esri/calcite-components/dist/components/calcite-combobox"),"combobox-item":()=>import("@esri/calcite-components/dist/components/calcite-combobox-item"),dropdown:()=>import("@esri/calcite-components/dist/components/calcite-dropdown"),flow:()=>import("@esri/calcite-components/dist/components/calcite-flow"),"flow-item":()=>import("@esri/calcite-components/dist/components/calcite-flow-item"),icon:()=>import("@esri/calcite-components/dist/components/calcite-icon"),input:()=>import("@esri/calcite-components/dist/components/calcite-input"),"input-date-picker":()=>import("@esri/calcite-components/dist/components/calcite-input-date-picker"),"input-time-picker":()=>import("@esri/calcite-components/dist/components/calcite-input-time-picker"),label:()=>import("@esri/calcite-components/dist/components/calcite-label"),list:()=>import("@esri/calcite-components/dist/components/calcite-list"),"list-item":()=>import("@esri/calcite-components/dist/components/calcite-list-item"),loader:()=>import("@esri/calcite-components/dist/components/calcite-loader"),notice:()=>import("@esri/calcite-components/dist/components/calcite-notice"),panel:()=>import("@esri/calcite-components/dist/components/calcite-panel"),switch:()=>import("@esri/calcite-components/dist/components/calcite-switch")})}get apiKey(){return this.viewModel.apiKey}set apiKey(e){this.viewModel.apiKey=e}get goToOverride(){return this.viewModel.goToOverride}set goToOverride(e){this.viewModel.goToOverride=e}get icon(){return"right"}set icon(e){this._overrideIfSome("icon",e)}get label(){return this.messages?.widgetLabel??""}set label(e){this._overrideIfSome("label",e)}get lastRoute(){return this.viewModel.lastRoute}get layer(){return this.viewModel.layer}set layer(e){this.viewModel.layer=e}get maxStops(){return this.viewModel.maxStops}set maxStops(e){this.viewModel.maxStops=e}get unit(){return this.defaultUnit}set unit(e){this._overrideIfSome("unit",e)}get view(){return this.viewModel.view}set view(e){this.viewModel.view=e}acquireSearch(e){const{view:t}=this.viewModel;if(this._stopsToSearches.has(e)){const i=this._stopsToSearches.get(e);return i.view=t,this._overrideDefaultSources(i),i}const i=new _({icon:!1,popupEnabled:!1,resultGraphicEnabled:!1,view:t,...this.searchProperties});return this._normalizeSearchSources(i),this.addHandles([l((()=>i.allSources),"change",(()=>this._normalizeSearchSources(i))),i.on("search-clear",(()=>{e.geometry=null,e.name=null,this.viewModel.layer?.removeResult()})),i.on("select-result",(()=>{const t=i.selectedResult;e.geometry=t?.feature.geometry,e.name=t?.name,this._solveRouteDebounced()})),a((()=>i.searchTerm),(t=>{e.name=t}))],i),this._stopsToSearches.set(e,i),i}getDirections(){return this.viewModel.getDirections()}render(){return C("div",{class:this.classes(A.base,D.widget,D.panel)},C("calcite-flow",null,this._renderPrimaryFlowItem(),this._renderDirectionsFlowItem(),this._renderEditFlowItem(),this._renderSaveFlowItem()))}save(){return this.viewModel.save()}saveAs(e,t={}){return this.viewModel.saveAs(e,t)}zoomToRoute(){return this.viewModel.zoomToRoute()}_applyLocatorSourceOverrides({allSources:e}){for(const t of e)"url"in t&&t.url&&(t.locationType??="street",I(t.url)&&this.apiKey&&null==t.apiKey&&(t.apiKey=this.apiKey,t.url=F))}_disposeSearch(e){if(!e||!this._stopsToSearches.has(e))return;const t=this._stopsToSearches.get(e);this.removeHandles(t),t.destroy(),this._stopsToSearches.delete(e)}_getEffectiveStops(){return this.viewModel.layer?.stops??this._placeholderStops}_getErrorDescription(){switch(this.viewModel.lastError?.name){case"directions-view-model:unable-to-route":return this.messages.errors.unableToRoute;case"directions-view-model:service-metadata-unavailable":return this.messages.errors.unableToLoadServiceMetadata;default:return this.messages.errors.unknownError}}_getNetworkFeatureName(e){switch(e.type){case"stop":switch(e.locationType){case"stop":default:return this.messages.networkFeatures.stops.stop;case"waypoint":return this.messages.networkFeatures.stops.waypoint;case"break":return this.messages.networkFeatures.stops.break}case"point-barrier":return this.messages.networkFeatures.pointBarrier;case"polyline-barrier":return this.messages.networkFeatures.polylineBarrier;case"polygon-barrier":return this.messages.networkFeatures.polygonBarrier}}_getRouteCostSummary(){const e=this.viewModel.layer?.routeInfo;if(!e)return null;const t=e.totalDistance??0,i=e.totalDuration??0,{messagesUnits:s,unit:o}=this;return{distance:f(s,t,o),duration:S(i)}}_getStopSections(){if(!this.viewModel.layer)return null;const{directionPoints:e,directionLines:t,stops:i}=this.viewModel.layer;if(!e||!t)return null;const s=[];let o=null;for(const r of e){const{objectId:e,stopId:a}=r;if(null!=a){const e=i.find((({objectId:e})=>e===a));o&&o.stop===e||(o={stop:e,directions:[]},s.push(o));continue}if(null==o)continue;const n=t.find((({directionPointId:t})=>t===e));null!=n&&o.directions.push({directionPoint:r,directionLine:n})}return s}_handleLocateStopAction(e){const{view:t}=this;if(!t)return;const i="directions-search-tool";this.removeHandles(i),this._searchTool=new w({stop:e,view:t}),this.addHandles([this._searchTool.on("click",(async t=>{if(t.mapPoint&&this._stopsToSearches.has(e)){const i=this._stopsToSearches.get(e),s=await i.search(t.mapPoint),o=s?.results?.[0].results?.[0];if(o){const{feature:t,name:s}=o;i.searchTerm=s,e.geometry=t.geometry}}this.removeHandles(i)})),s((()=>{this._searchTool&&(this.view?.tools.remove(this._searchTool),this._searchTool=null)}))],i),t.addAndActivateTool(this._searchTool)}_handleEditingDoneClick(){this.viewModel.stopEditing(),this._currentFlowItem="primary"}async _handleSaveLayerAsAction(){const e=p.getDefault();try{await e.signIn()}catch(t){if(r(t)||"identity-manager:user-aborted"===t.name)return;return this._parentFlowItem=this._currentFlowItem,this._currentFlowItem="save",void(this._saveState="connect-to-portal-error")}this._saveState="fetch-portal-information",this._parentFlowItem=this._currentFlowItem,this._currentFlowItem="save",this._portalUserName=e.user?.username;try{this._portalFolders=await(e.user?.fetchFolders())}catch{return void(this._saveState="fetch-portal-information-error")}this._saveState="save-layer"}_normalizeSearchSources(e){this._overrideDefaultSources(e),this._applyLocatorSourceOverrides(e)}_overrideDefaultSources(e){for(const t of e.viewModel.defaultSources)t.autoNavigate=!1}_renderClearRouteAction(e){return C("calcite-action",{icon:"trash",key:"clear-route",onclick:()=>{this._currentFlowItem="primary",this.viewModel.reset()},...e,text:this.messages.common.clear,textEnabled:!0})}_renderDeleteStopAction(e){const t=this._getEffectiveStops();return C("calcite-action",{icon:"trash",onclick:()=>{t.remove(e),this._disposeSearch(e),this._solveRouteDebounced()},scale:"s",slot:"actions-end",text:this.messages.deleteStop,title:this.messages.deleteStop})}_renderDepartureTime(){const{DEPART_AT:e,NOW:t,UNSPECIFIED:i}=M;return C("calcite-label",{class:A.departureTime,key:"departure-time"},this.messages.departureTime,C("calcite-combobox",{clearDisabled:!0,label:this.messages.departureTime,overlayPositioning:"fixed",selectionMode:"single",onCalciteComboboxChange:({currentTarget:e})=>{const{selectedItems:t}=e;t.length&&(this.viewModel.departureOption=t[0].value,this._solveRouteDebounced())}},C("calcite-combobox-item",{heading:this.messages.leaveNow,key:t,label:this.messages.leaveNow,selected:this.viewModel.departureOption===t,value:t}),C("calcite-combobox-item",{heading:this.messages.departAt,key:e,label:this.messages.departAt,selected:this.viewModel.departureOption===e,value:e}),C("calcite-combobox-item",{heading:this.messages.timeUnspecified,key:i,label:this.messages.timeUnspecified,selected:this.viewModel.departureOption===i,value:i})))}_renderDepartureTimeOptions(){return this.viewModel.departureOption!==M.DEPART_AT?null:C("div",{class:A.departureTimeOptions},C("calcite-input-date-picker",{scale:"s",valueAsDate:$(this.viewModel.departureIsoDate),onCalciteInputDatePickerChange:({currentTarget:{value:e}})=>{Array.isArray(e)||(this.viewModel.departureIsoDate=e,this._solveRouteDebounced())}}),C("calcite-input-time-picker",{scale:"s",value:this.viewModel.departureIsoTime,onCalciteInputTimePickerClose:({currentTarget:{value:e}})=>{this.viewModel.departureIsoTime=e,this._solveRouteDebounced()}}))}_renderDirectionsFlowItem(){if("directions"!==this._currentFlowItem)return null;const e=this._getRouteCostSummary();if(!this._sections||!e)return null;const{distance:t,duration:i}=e,{formattedEta:s}=this.viewModel,o=this._sections.at(0)?.stop.name??"",r=this._sections.at(-1)?.stop.name??"";return C("calcite-flow-item",{key:"directions-flow-item",overlayPositioning:"fixed",selected:"directions"===this._currentFlowItem,onCalciteFlowItemBack:e=>{e.stopPropagation(),this._currentFlowItem="primary"}},C("div",{class:A.directionsHeader,slot:"header-content"},C("div",{class:A.headerStops},C("span",null,this.messages.from)," ",C("span",{class:A.directionsHeaderStopName},o),C("span",null,this.messages.to)," ",C("span",{class:A.directionsHeaderStopName},r)),C("div",{class:A.flexColumn},C("span",null,`${i} (${t})`),s?C("span",null,s):null)),this._renderRouteLayerActions({slot:"header-menu-actions"}),C("calcite-accordion",{class:A.accordion,iconPosition:"start",selectionMode:"single"},this._sections.map(((e,t)=>{const{stop:i,directions:s}=e,{name:o}=i;return C("calcite-accordion-item",{expanded:0===t,heading:o??"",key:`stop-${t}`},C("calcite-action",{icon:"zoom-to-object",onclick:()=>{this.viewModel.centerAt(i)},slot:"actions-end",text:this.messages.panToStop}),this._renderDirectionTurns(s))}))))}_renderDirectionTurns(e){return C("calcite-list",{label:this.messages.drivingDirections,selectionMode:"none"},e.map(((e,t)=>{const{directionPoint:i,directionLine:s}=e,{distance:o,duration:r}=s,a=f(this.messagesUnits,o??0,this.unit),n=S(r??0),l=a&&n?`${a} | ${n}`:`${a||n}`,c=E(i),d=k(i.directionPointType);return C("calcite-list-item",{class:A.labelNoBottomMargin,key:`driving-direction-${t}`,onpointerenter:()=>{this.viewModel.highlight(s)},onpointerleave:()=>{this.viewModel.clearHighlights()},onCalciteListItemSelect:()=>{this._activeManeuver===s?this.zoomToRoute():(this._activeManeuver=s,this.viewModel.centerAt(s.geometry))}},C("calcite-icon",{icon:d,slot:"content-start"}),C("div",{slot:"content"},C("calcite-label",{layout:"inline",scale:"s"},c),C("calcite-label",{layout:"inline",scale:"s"},l)))})))}_renderEditFlowItem(){return"edit"!==this._currentFlowItem?null:C("calcite-flow-item",{heading:this.messages.editRoute,headingLevel:this.headingLevel,key:"edit-flow-item",loading:"routing"===this.viewModel.state,selected:"edit"===this._currentFlowItem,onCalciteFlowItemBack:e=>{e.stopPropagation(),this.viewModel.stopEditing(),this._currentFlowItem="primary"}},C("div",{class:A.flexColumn,key:"edit-container"},C("div",{class:A.editToolbarContainer},C("calcite-label",{layout:"inline",scale:"s"},this.messages.automaticallySolve,C("calcite-switch",{checked:this.viewModel.autoSolve,scale:"s",onCalciteSwitchChange:e=>{this.viewModel.autoSolve=e.target.checked}})),C("div",{class:A.editToolbar},C("calcite-action",{icon:"flag",onclick:()=>{this.viewModel.create("stop")},scale:"s",text:this.messages.networkFeatures.stops.stop,textEnabled:!0}),C("calcite-action",{icon:"line",onclick:()=>{this.viewModel.create("polyline-barrier")},scale:"s",text:this.messages.barrier,textEnabled:!0}),C("calcite-action",{class:A.solveRoute,disabled:this.viewModel.autoSolve,icon:"refresh",onclick:()=>{this._solveRouteDebounced()},scale:"s",text:this.messages.solve,textEnabled:!0}))),C("div",{class:A.selectedFeatureContainer},C("calcite-list",{label:this.messages.selectedNetworkFeatures,scale:"s",selectionMode:"none"},this.viewModel.selectedNetworkFeatures?.toArray().map(((e,t)=>C("calcite-list-item",{description:this._getNetworkFeatureName(e),key:`network-feature-${t}`,label:e.name??e.objectId?.toString()??this.messages.unnamed},C("calcite-action",{icon:"trash",onclick:()=>{this.viewModel.remove(e)},scale:"s",slot:"actions-end",text:this.messages.common.delete})))))),C("div",{class:A.editFooter},this._renderEditFooterContent())))}_renderEditFooterContent(){return this.viewModel.lastError?this._renderErrorNotice():C("calcite-button",{appearance:"outline-fill",bind:this,onclick:this._handleEditingDoneClick,width:"full"},this.messages.common.done)}_renderErrorNotice(){return C("calcite-notice",{icon:"exclamation-mark-circle",kind:"danger",open:!0},C("calcite-label",{class:A.labelNoBottomMargin,slot:"message"},this._getErrorDescription()))}_renderFooter(){if(!this.viewModel.layer)return C("div",{class:A.primaryFooter,key:"footer-missing-layer"},C("calcite-notice",{icon:"information",open:!0},C("calcite-label",{class:A.labelNoBottomMargin,slot:"message"},this.messages.missingLayer)));if("unauthenticated"===this.viewModel.state)return C("div",{class:A.primaryFooterCentered,key:"footer-sign-in"},C("calcite-label",null,this.messages.signInRequired),C("calcite-button",{onclick:()=>{this.viewModel.load().catch((()=>{}))}},this.messages.common.auth.signIn));if("routing"===this.viewModel.state)return C("div",{class:this.classes(A.primaryFooter,A.primaryFooterLoader),key:"footer-routing"},C("calcite-loader",{label:this.messages.solve,scale:"s"}));if("error"===this.viewModel.state)return C("div",{class:A.primaryFooter,key:"footer-service-error"},this._renderErrorNotice());if(!this.viewModel.layer?.routeInfo)return C("div",{class:A.primaryFooter,key:"footer-unsolved-route"},C("calcite-notice",{icon:"information",open:!0},C("calcite-label",{class:A.labelNoBottomMargin,slot:"message"},this.messages.directionsPlaceholder)));const e=this._getRouteCostSummary();if(!e||!this.viewModel.layer?.directionPoints)return C("div",{class:A.primaryFooter,key:"footer-invalid-route"},C("calcite-notice",{icon:"exclamation-mark-triangle",kind:"danger",open:!0},C("calcite-label",{class:A.labelNoBottomMargin,slot:"message"},this.messages.invalidRoute)));const{distance:t,duration:i}=e,{formattedEta:s}=this.viewModel;return C("div",{class:A.routeItem,key:"footer-directions-summary"},C("button",{"aria-busy":"false","aria-label":this.messages.viewDrivingDirections,"aria-live":"polite",class:A.routeItemButton,onclick:()=>{this._currentFlowItem="directions"},type:"button"},C("div",{class:A.routeItemButtonContent},C("span",{class:A.routeItemLabel},`${i} (${t})`),C("span",{class:A.routeItemDescription},s)),C("calcite-icon",{flipRtl:!0,icon:"chevron-right",scale:"s"})),C("calcite-dropdown",null,C("calcite-action",{icon:"ellipsis",slot:"trigger",text:"Route actions"}),this._renderRouteLayerActions()))}_renderInteractiveRouteActions(){return C("div",{class:A.actionContainer,key:"interactive-route-action-container"},C("calcite-button",{appearance:"outline",class:A.addStopButton,disabled:this._getEffectiveStops().length>=this.maxStops,iconStart:"plus",kind:"neutral",label:this.messages.addStop,onclick:()=>{const e=new v;this.viewModel.layer?.stops.add(new u({symbol:e}))},width:"half"},this.messages.addStop),C("calcite-button",{appearance:"outline",disabled:"2d"!==this.viewModel.view?.type,iconStart:"pencil",kind:"neutral",label:this.messages.editRoute,onclick:()=>{this._currentFlowItem="edit",this.viewModel.startEditing()},width:"half"},this.messages.editRoute))}_renderLocateStopAction(e){if(null!=e.name||null!=e.geometry)return null;const t=this._getEffectiveStops().indexOf(e),i=!!this.view?.activeTool&&this.view.activeTool===this._searchTool&&this._searchTool.stop===e;return C("calcite-action",{active:i,icon:"crosshair",key:`stop-location-action-${t}`,onclick:()=>this._handleLocateStopAction(e),scale:"s",slot:"actions-end",text:this.messages.pickALocationOnTheMap,title:this.messages.pickALocationOnTheMap})}_renderOptimizeStopOrder(){const{routeParameters:e}=this.viewModel,{findBestSequence:t,preserveFirstStop:i,preserveLastStop:s}=e;return C("calcite-block-section",{class:A.optimizeSection,text:this.messages.optimizeOrder,toggleDisplay:"switch",onCalciteBlockSectionToggle:({target:t})=>{e.findBestSequence=t.open,t.open||this._resetStopSequence(),this._solveRouteDebounced()}},t?[C("calcite-label",{class:A.optimizeSwitches,key:"preserve-first-stop",layout:"inline-space-between"},this.messages.preserveFirstStop,C("calcite-switch",{checked:i,scale:"s",onCalciteSwitchChange:({target:{checked:t}})=>{e.preserveFirstStop=t,this._resetStopSequence(),this._solveRouteDebounced()}})),C("calcite-label",{class:A.optimizeSwitches,key:"preserve-last-stop",layout:"inline-space-between"},this.messages.preserveLastStop,C("calcite-switch",{checked:s,scale:"s",onCalciteSwitchChange:({target:{checked:t}})=>{e.preserveLastStop=t,this._resetStopSequence(),this._solveRouteDebounced()}}))]:null)}_renderPrimaryFlowItem(){return C("calcite-flow-item",{key:"primary-flow-item",loading:"initializing"===this.viewModel.state,selected:"primary"===this._currentFlowItem},C("calcite-panel",{class:A.primaryFlowItem,disabled:!this.viewModel.layer||"unauthenticated"===this.viewModel.state||"error"===this.viewModel.state&&!this.viewModel.serviceDescription},this._renderStops(),this._renderInteractiveRouteActions(),this._renderSeparator(),this._renderRouteSolveOptions()),this._renderFooter())}_renderRouteLayerActions(e){return[this._renderClearRouteAction(e),this._renderSaveLayerAction(e),this._renderSaveLayerAsAction(e),this._renderViewItemDetailsAction(e)]}_renderRouteSolveOptions(){return C("div",{class:A.marginInlineMedium,key:"route-solve-options"},this._renderTravelModes(),this._renderDepartureTime(),this._renderDepartureTimeOptions(),this._renderOptimizeStopOrder())}_renderSaveContent(){switch(this._saveState){case"initialized":return this._renderSaveInitialized();case"connect-to-portal":return this._renderSaveProcessing(this.messages.identity.lblSigning);case"connect-to-portal-error":return this._renderSaveError(this.messages.errors.authenticating);case"fetch-portal-information":return this._renderSaveProcessing(this.messages.processing.fetching);case"fetch-portal-information-error":return this._renderSaveError(this.messages.errors.fetching);case"save-layer":return this._renderSaveLayerSettings();case"saving":return this._renderSaveProcessing(this.messages.processing.saving);case"saving-error":return this._renderSaveError(this.messages.errors.saving)}}_renderSaveError(e){return C("calcite-panel",{class:A.paddingMedium,key:"save-layer-error"},C("div",{class:A.saveError},C("calcite-icon",{class:A.saveErrorIcon,icon:"exclamation-mark-triangle",scale:"l",textLabel:this.messages.common.errorMessage}),C("calcite-label",{class:A.saveErrorLabel},e)),C("calcite-button",{appearance:"outline",onclick:()=>{this._currentFlowItem=this._parentFlowItem},slot:"footer-actions",width:"full"},this.messages.common.close))}_renderSaveInitialized(){return C("calcite-panel",{class:A.paddingMedium,key:"save-layer-initialized"})}_renderSaveFlowItem(){return"save"!==this._currentFlowItem?null:C("calcite-flow-item",{heading:this.messages.saveLayer,headingLevel:this.headingLevel,key:"save-layer-flow-item",selected:"save"===this._currentFlowItem,onCalciteFlowItemBack:e=>{e.stopPropagation(),this._currentFlowItem=this._parentFlowItem}},this._renderSaveContent())}_renderSaveLayerAction(e){if(!this.visibleElements.saveButton)return null;const t=this.viewModel.layer,i=t?.routeInfo,s=t?.portalItem?.itemControl;return C("calcite-action",{disabled:!(!!i&&("admin"===s||"update"===s)),icon:"save",key:"save-route",onclick:()=>{this.viewModel.layer?.save()},...e,text:this.messages.common.save,textEnabled:!0})}_renderSaveLayerAsAction(e){if(!this.visibleElements.saveAsButton)return null;const t=!this.viewModel.layer?.routeInfo;return C("calcite-action",{disabled:t,icon:"save-as",key:"save-as-route",onclick:()=>{this._handleSaveLayerAsAction()},...e,text:this.messages.common.saveAs,textEnabled:!0})}_renderSaveLayerSettings(){if(null==this.layer||null==this._portalFolders||null==this._portalUserName)return this._renderSaveInitialized();const{stops:e}=this.layer,t=`${e.at(0).name} - ${e.at(-1).name}`,i=this._portalFolders.map((e=>C("calcite-combobox-item",{heading:e.title??"",key:`${L}-folder-${e.id}`,value:e.id})));return i.unshift(C("calcite-combobox-item",{heading:`${this._portalUserName} (${this.messages.common.home})`,key:`${L}-folder-home`,selected:!0,value:null})),C("calcite-panel",{key:"save-layer-panel"},C("div",{class:A.paddingMedium},C("calcite-label",null,this.messages.laverName,C("calcite-input",{afterCreate:e=>{this._portalItemNameInput=e},label:this.messages.laverName,value:t})),C("calcite-label",null,this.messages.saveInFolder,C("calcite-combobox",{afterCreate:e=>{this._portalFolderCombobox=e},label:this.messages.saveInFolder,overlayPositioning:"fixed",selectionMode:"single"},i))),C("calcite-button",{onclick:()=>{if(this._saveState="saving",null==this.layer||null==this._portalFolders)return;const e=this._portalItemNameInput?.value,t=this._portalFolderCombobox?.value,i=this._portalFolders.find((({id:e})=>e===t));this.layer.saveAs({title:e},{folder:i}).then((()=>{this._currentFlowItem=this._parentFlowItem})).catch((()=>{this._saveState="saving-error"}))},slot:"footer-actions",width:"full"},this.messages.common.save),C("calcite-button",{appearance:"outline",onclick:()=>{this._currentFlowItem=this._parentFlowItem},slot:"footer-actions",width:"full"},this.messages.common.cancel))}_renderSaveProcessing(e){return C("calcite-panel",{class:A.marginInlineMedium,key:"save-layer-processing"},C("calcite-loader",{class:A.saveProcessLoader,label:e,text:e}))}_renderSeparator(){return C("div",{class:A.separator})}_renderStop(e){const t=this.acquireSearch(e);null!=e.name&&(t.searchTerm=e.name);const i=this._getEffectiveStops(),s=this._renderLocateStopAction(e),o=i.length>2&&this._renderDeleteStopAction(e);return C("calcite-list-item",{key:e,value:e},s,o,C("div",{class:A.stopItem,slot:"content"},t.render()))}_renderStops(){const e=this._getEffectiveStops();for(const t of this._stopsToSearches.keys())e.includes(t)||this._disposeSearch(t);return C("div",{class:A.stopContainer,key:A.stopContainer},C("calcite-list",{class:A.stopList,dragEnabled:!0,label:this.messages.widgetLabel,scale:"s",onCalciteListOrderChange:({detail:t})=>{e.reorder(t.dragEl.value,t.newIndex),this._resetStopSequence(),this._solveRouteDebounced()}},e.toArray().map((e=>this._renderStop(e)))),2===e.length&&C("calcite-action",{icon:"arrow-up-down",onclick:()=>{e.reverse(),this._resetStopSequence(),this._solveRouteDebounced()},scale:"s",text:this.messages.reverseStops}))}_renderTravelModes(){return this.viewModel.travelModes.length?C("calcite-label",{key:"travel-modes"},this.messages.mode,C("calcite-combobox",{clearDisabled:!0,label:this.messages.mode,overlayPositioning:"fixed",selectionMode:"single",onCalciteComboboxChange:({currentTarget:e})=>{const{selectedItems:t}=e;t.length&&(this.viewModel.selectedTravelMode=t[0].value,this._solveRouteDebounced())}},this.viewModel.travelModes.map((e=>C("calcite-combobox-item",{heading:e.name,key:e.id,label:e.name,selected:this.viewModel.selectedTravelMode?.id===e.id,value:e}))))):null}_renderViewItemDetailsAction(e){if(!this.visibleElements.layerDetails)return null;const t=this.viewModel.layer?.portalItem;return C("calcite-action",{disabled:!t,icon:"launch",key:"open-route-details-link",onclick:()=>{t&&window.open(`${t.portal.url}/home/item.html?id=${t.id}`,"_blank")},...e,text:this.messages.viewLayerDetails,textEnabled:!0})}_resetStopSequence(){this.viewModel.layer?.stops.forEach((e=>{e.sequence=null}))}async _solveRoute(){this.viewModel.updateDepartureTime();if(!((this.viewModel.layer?.stops.filter((({geometry:e})=>!!e)).length??0)<2))try{await this.viewModel.getDirections()}catch{}}};e([d()],R.prototype,"_currentFlowItem",void 0),e([d()],R.prototype,"_saveState",void 0),e([d()],R.prototype,"_searchTool",void 0),e([d()],R.prototype,"apiKey",null),e([d(h)],R.prototype,"defaultUnit",void 0),e([d()],R.prototype,"goToOverride",null),e([d()],R.prototype,"headingLevel",void 0),e([d()],R.prototype,"icon",null),e([d()],R.prototype,"label",null),e([d({readOnly:!0})],R.prototype,"lastRoute",null),e([d()],R.prototype,"layer",null),e([d()],R.prototype,"maxStops",null),e([d(),x("esri/widgets/Directions/t9n/Directions")],R.prototype,"messages",void 0),e([d(),x("esri/core/t9n/Units")],R.prototype,"messagesUnits",void 0),e([d()],R.prototype,"searchProperties",void 0),e([d()],R.prototype,"unit",null),e([d()],R.prototype,"view",null),e([d({type:y})],R.prototype,"viewModel",void 0),e([d({type:b,nonNullable:!0})],R.prototype,"visibleElements",void 0),R=e([m("esri.widgets.Directions")],R);const N=R;export{N 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.33/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../Graphic.js";import a from"../../core/Error.js";import{makeHandle as i,handlesGroup as r,abortHandle as s}from"../../core/handleUtils.js";import"../../core/has.js";import{removeMaybe as o,destroyMaybe as n}from"../../core/maybe.js";import{isPromiseLike as l,debounce as d}from"../../core/promiseUtils.js";import{watch as c,when as u,initial as h,whenOnce as p,syncAndInitial as m}from"../../core/reactiveUtils.js";import{generateBracedUUID as f}from"../../core/uuid.js";import{property as w}from"../../core/accessorSupport/decorators/property.js";import"../../core/Logger.js";import"../../core/RandomLCG.js";import{subclass as g}from"../../core/accessorSupport/decorators/subclass.js";import{isSharedTemplate as y,isSharedTemplateOrMetadata as v}from"../../editing/templateUtils.js";import{createTemplateExecutor as F}from"../../editing/sharedTemplates/executor/createTemplateExecutor.js";import _ from"../../layers/GraphicsLayer.js";import{isTable as b}from"../../layers/support/layerUtils.js";import{getDisplayedSymbol as M}from"../../symbols/support/symbolUtils.js";import{getDrawHelpMessage as V}from"../../views/draw/support/helpMessageUtils.js";import I from"../../views/draw/support/HighlightHelper.js";import k from"../../views/interactive/sketch/SketchOptions.js";import S from"../../views/interactive/snapping/FeatureSnappingLayerSource.js";import{temporaryHighlightName as C}from"../../views/support/HighlightDefaults.js";import P from"./CreateFeaturesWorkflowData.js";import{isModelUpload as A,handleModelUpload as H}from"./modelUploadUtils.js";import E from"./Workflow.js";import{startCreatingNewFeature as T,findLayerInfo as j,updateGraphicSymbolWhenRequired as U,isTerminalUpdateEventType as L,getVisualVariableAttributes as x,startUpdatingFeatureGeometry as O,createWorkflowSteps as R,avoidFeatureTemplateSelectionWithOnlyOneItem as W,getCreationAttributes as D,getFullTemplateForCreationInfo as N,getServiceLayersById as G,prepareAttachmentsForCreateFeaturesWorkflow as z,showProgressCursor as Z,setUpSketchCreateWatchers as q,setVisualVariablesAndElevationInfoForUpdate as B,visualVariableInteractiveUpdate as K}from"./workflowUtils.js";import J from"../FeatureForm/FeatureFormViewModel.js";import Q from"../Sketch/SketchViewModel.js";var X;const Y=Symbol(),$=Symbol(),ee=Symbol(),te=Symbol(),ae={point:["point"],multipoint:["multipoint"],polygon:["polygon","freehandPolygon","rectangle","circle"],polyline:["polyline","freehandPolyline"],mesh:[],multipatch:[]};let ie=X=class extends E{constructor(e){super(e),this.type="create-features",this.createFeatureState="create-new",this.data=void 0,this.isNested=!1,this._getDrawMeshHelpMessage=void 0,this._webStyleCache=new Map,this._featureFormHandle=null,this._visualVariableAttributes={rotation:null,size:null},this._featureFormViewModel=new J,this._sketchViewModel=null,this._attachmentFileInfos=new Map,this._isActive=!0}initialize(){this.isNested&&(this._isActive=!1),this._initializeSketchViewModel()}destroy(){this._sketchViewModel.destroy()}get featureFormViewModel(){return this._featureFormViewModel}get hasPendingEdits(){if(this.pendingFeatures.some((e=>!!this.data.getEditsForPendingFeature(e)?.modified)))return!0;const{creationInfo:e,upload:t}=this.data,a=this._sketchViewModel,{activeComponent:i}=a,r=a.createGraphic?.geometry?.type;return!("polyline"!==r&&"polygon"!==r&&"multipoint"!==r||"draw-2d"!==i?.type&&"draw-3d"!==i?.type)&&i.drawOperation.committedVertices.length>0||(!(!t||"pending"!==t.state&&"success"!==t.state)||!!e?.geometryToPlace)}get hasPreviousStep(){return this._stepIndex>0||"update-pending"===this.createFeatureState&&!!this.data.selectedPendingFeature}get helpMessage(){const{creationInfo:e,viewModel:t}=this.data;if("creating-features"!==this.stepId||!e)return;const a=e.layer.geometryType,i=this._sketchViewModel.createGraphic;if("mesh"===a){this._getDrawMeshHelpMessage||import("../../views/draw/support/helpMessageUtils3d.js").then((e=>{this._getDrawMeshHelpMessage=e.getDrawMeshHelpMessage}));const{view:e}=t;return"3d"===e?.type?this._getDrawMeshHelpMessage?.(i,e):void 0}const r=this._sketchViewModel.activeCreateToolDrawMode,s=this._sketchViewModel.activeTool;return V("rectangle"===s?"rectangle":"circle"===s?"circle":a,i?.geometry,r)}get layer(){return this.data.creationInfo?.layer}get numPendingFeatures(){return this.pendingFeatures.length}get parent(){return this.data.parent}get parentLayer(){return this.parent?.data.editorItem.layer}get pendingFeatures(){return this.data.pendingFeatures}get keyboardCancellationEnabled(){return 0===this.numPendingFeatures}get reliesOnOwnerAdminPrivileges(){return this.data.editorItem?.capabilities.create.reliesOnOwnerAdminPrivileges??!1}get shouldShowAttachments(){return(this.data.selectedPendingFeature&&this.data.editorItem?.capabilities.create.attachments.enabled)??!1}get shouldAllowAttachmentEditing(){return this.shouldShowAttachments}get sketchViewModel(){return this._sketchViewModel}get test(){}get availableCreateTools(){const e=this.data.creationInfo?.layer.geometryType,t=this.data.viewModel.view;return e?this.data.creationInfo?.maxFeatures&&this.data.creationInfo.maxFeatures<=this.numPendingFeatures||"2d"!==t?.type&&"multipoint"===e?[]:[...ae[e]]:[]}get _attachmentsActive(){const e=this.data.viewModel.attachmentsViewModel.mode,t=this.stepId;return this.shouldShowAttachments&&("add"===e||"edit"===e||"adding-attachment"===t||"editing-attachment"===t)}async enter(){this._isActive=!0,"awaiting-feature-creation-info"!==this.stepId&&this._setUpCreatingFeaturesStep()}exit(){this._isActive=!1,this.removeHandles([ee])}async updatePendingFeature(e){if(e!==this.data.selectedPendingFeature)return this._sketchViewModel.cancel(),this._startUpdating({feature:e})}async start(){return await super.start(),b(this.data.creationInfo?.layer)?null:{enter:async()=>{},exit:async()=>{},viewModel:this._sketchViewModel}}async save(){const{featureFormViewModel:e}=this;if(e.pendingSubtypeChoice)return;e.submit(),this._stashValidationState();const t=this.data.selectedPendingFeature,a=this._hasValidationErrors(t)?t:this.data.pendingFeatures.find((e=>this._hasValidationErrors(e)));return a?(await this._startUpdating({feature:a}),void e?.submit()):super.save()}back(e){return"update-pending"!==this.createFeatureState||!this.data.selectedPendingFeature||A(this.data.creationInfo)||this._attachmentsActive?super.back(e):this._clearSelectedFeature()}previous(e){return"update-pending"!==this.createFeatureState||!this.data.selectedPendingFeature||A(this.data.creationInfo)||this._attachmentsActive?super.previous(e):this._clearSelectedFeature()}cancelFeature(e){this.data.removePendingFeature(e),this.sketchViewModel.layer.graphics.remove(e)}static create(e){const{addAttachmentsCallback:t,applyEditsCallback:a,applyEditsFeatureServiceCallback:i,isNested:r,creationInfo:s,parent:o,snappingManager:n,startAt:l,viewModel:d}=e,c=e.sketchOptions??new k,u=s?.layer,h=u?d.findEditorItemForLayer(u):void 0,p=new X({data:new P({creationInfo:s,editorItem:h,parent:o,sketchOptions:c,snappingManager:n,viewModel:d}),isNested:r,onCommit:async e=>{const{creationInfo:r}=e;if(!r)return;p._sketchViewModel.cancel();const s=e.pendingFeatures.toArray(),{layer:o}=r,n=o.capabilities?.editing.supportsGlobalId&&"globalIdField"in o,l=p._attachmentFileInfos,{fullTemplate:d,templateExecutorInfo:c}=e,u=d&&y(d)&&c?.completionResult;if(n){if(ne(s),u){const e=de(c.completionResult.edits,l);await i(d.featureService,e,{globalIdUsed:!0,gdbVersion:d.layer.gdbVersion??void 0})}else{const e=le(s,l);await a(o,e,{globalIdUsed:!0})}return}const h=u?await i(d.featureService,c.completionResult.edits,{gdbVersion:d.layer.gdbVersion??void 0}):[await a(o,{addFeatures:s})];h&&l.size>0&&await Promise.all(h.map((e=>{if(e?.addFeatureResults)return t(o,oe(s,e.addFeatureResults,o,l))})))}});return p._set("steps",this._createWorkflowSteps(p,l)),p}_fadeExistingFeatures(e){if("effect"in e){const t=e.effect;return e.effect="saturate(0.6) opacity(0.8)",i((()=>e.effect=t))}const t=e.opacity;return e.opacity=.7,i((()=>e.opacity=t))}async _startCreating(){this.removeHandles($);const{data:e}=this;if(!e.creationInfo)return;const t=this.data.creationInfo?.maxFeatures;if(t&&this.numPendingFeatures>=t)return this.sketchViewModel.cancel(),void(this.numPendingFeatures&&await this._startUpdating({feature:this.pendingFeatures.at(-1)}));this.createFeatureState="create-new";const a=await T(this._sketchViewModel,e,this._webStyleCache);this.addHandles(a,$)}async _clearSelectedFeature(){const e=this._featureFormViewModel.pendingSubtypeChoice;e&&(e.resolve("undo"),await e.promise),this._stashValidationState(),this.sketchViewModel.cancel(),this.data.selectedPendingFeature=null,this._featureFormHandle=o(this._featureFormHandle),this._featureFormViewModel.feature=null;const t=this.data.viewModel.attachmentsViewModel;"add"!==t.mode&&"edit"!==t.mode||this.data.viewModel.activeWorkflow?.previous()}_stashValidationState(){const e=this._featureFormViewModel.feature,t=e&&this.data.getEditsForPendingFeature(e);t&&(t.submittable=this._featureFormViewModel.submittable)}async _selectFeatureForUpdate({feature:e,initialFeature:t=e}){this._stashValidationState();const{data:a,pendingFeatures:i,_webStyleCache:s}=this;i.includes(e)||a.addPendingFeature(e,t),a.selectedPendingFeature=e;const{_featureFormViewModel:n,_sketchViewModel:l}=this,{creationInfo:d,viewModel:u}=a,{attachmentsViewModel:h,layerInfos:p,view:m}=u;if(!m||!d)return;o(this._featureFormHandle);const f=e.sourceLayer,w=j(p,f),g=w?.formTemplate,y=m.spatialReference;n.set({arcadeEditType:"INSERT",feature:e,formTemplate:g,spatialReference:y,map:m.map}),"add"!==h.mode&&"edit"!==h.mode||u.activeWorkflow?.previous(),h.graphic=e,h.fileInfos.removeAll(),h.mode="view";(this._attachmentFileInfos.get(e)||[]).forEach((({file:e,form:t})=>h.addFile(e,t))),await U(e,s,"2d"===m.type?m.scale:null);const v=a.getEditsForPendingFeature(e);this._featureFormHandle=r([n.on("value-change",(async()=>{v?.updateAttributes(n.getValues()),await U(e,s,"2d"===m.type?m.scale:null)})),l.on(["update","undo","redo"],(e=>{("undo"===e.type||"redo"===e.type||"update"===e.type&&null!=e.toolEventInfo&&L(e.toolEventInfo.type))&&n.notifyFeatureGeometryChanged()})),c((()=>n.feature?.sourceLayer),(t=>e.sourceLayer=t)),c((()=>[n.feature,n.submittable]),(()=>this._stashValidationState()))]),this.createFeatureState="update-pending"}async _startUpdating({feature:e,initialFeature:t=e}){await this._selectFeatureForUpdate({feature:e,initialFeature:t});const{_sketchViewModel:a,data:i}=this,{creationInfo:r,viewModel:s}=i,{view:o}=s;if(!o||!r)return;const n=e.sourceLayer??r.layer;return b(n)?void 0:(this._visualVariableAttributes=x(e),O({graphic:e,sketchViewModel:a,sourceLayer:n,visualVariables:this._visualVariableAttributes,webStyleCache:this._webStyleCache}))}static _createWorkflowSteps(e,t="awaiting-feature-creation-info"){const{data:a}=e,i=R(["awaiting-feature-creation-info","creating-features","adding-attachment","editing-attachment"],t,{"awaiting-feature-creation-info":()=>({id:"awaiting-feature-creation-info",async setUp(){const{creationInfo:t,viewModel:i}=a,{view:r}=i;r&&(A(t)?e.addHandles(await H({view:r,data:a,next:()=>e.next(),cancel:()=>i.cancelWorkflow({warnIfNoWorkflow:!1})}),this.id):(a.parent&&t&&e.addHandles(i.restrictFeatureTemplatesViewModelToLayer(t.layer),this.id),e.addHandles(i.featureTemplatesViewModel.on("select",(({item:t})=>{t&&(a.creationInfo={...a.creationInfo,layer:t.layer,template:t.template},e.next())})),this.id)))},async tearDown(){e.removeHandles(this.id)}}),"creating-features":()=>({id:"creating-features",async setUp(){e._isActive&&await e._setUpCreatingFeaturesStep()},async tearDown(t){const{viewModel:i}=a;t.canceled&&(e.removeHandles([ee,Y,$,te]),i.attachmentsViewModel.fileInfos.removeAll(),e._attachmentFileInfos.clear())}}),"adding-attachment":()=>({id:"adding-attachment",parent:"creating-features",async setUp(){},async tearDown(){const{attachmentsViewModel:t}=a.viewModel,{graphic:i,fileInfos:r}=t;e._attachmentFileInfos.set(i,r.toArray()),t.mode="view"}}),"editing-attachment":()=>({id:"editing-attachment",parent:"creating-features",async setUp(){},async tearDown(){const{attachmentsViewModel:t}=a.viewModel,{graphic:i,fileInfos:r}=t;e._attachmentFileInfos.set(i,r.toArray()),t.mode="view"}})});return W(a,i)}static _configureSketchViewModel(e){const{data:t}=e,a=e._webStyleCache,{creationInfo:s,viewModel:o}=t,{view:n}=o,l=e._sketchViewModel,h=[];if(!n)return i();if("2d"===n.type){s&&h.push(e._fadeExistingFeatures(s.layer));const t=d(((e,t)=>Promise.all(e.map((e=>U(e,a,t))))));h.push(c((()=>n.scale),(e=>t(l.layer.graphics,e))))}const p=D(t.fullTemplate,s?.attributeOverrides),m=async i=>{if("start"!==i.state||e.hasHandles($)||e.addHandles(await q({creationAttributes:p,data:t,sketchViewModel:l,view:n,webStyleCache:a}),$),"cancel"!==i.state&&"complete"!==i.state||e.removeHandles($),"cancel"===i.state&&null!==n.activeTool&&n.activeTool!==e.sketchViewModel.activeComponent&&(await e._waitForActiveToolCleared(),await e._startCreating()),"complete"===i.state&&i.graphic){const t=await e._processEdits(i.graphic,{scale:"2d"===n.type?n.scale:null,useSourceLayer:!0,webStyleCache:e._webStyleCache});t&&(await e._waitForActiveToolCleared(),await e._startUpdating({feature:t}))}},f=async a=>{const{attachmentsViewModel:i}=o,{_featureFormViewModel:r}=e;if(a.graphics.length>1)return void await e._clearSelectedFeature();const d=a.graphics[0];if("complete"===a.state){const{submittable:t}=r;if(e.numPendingFeatures!==s?.maxFeatures&&t||r.submit(),await e._clearSelectedFeature(),"add"!==i.mode&&"edit"!==i.mode||o.activeWorkflow?.previous(),!a.aborted&&n.activeTool===e.sketchViewModel.activeComponent&&(await e.sketchViewModel.wait(),"ready"===e.sketchViewModel.state&&"mesh"!==e.data.creationInfo?.layer.geometryType))return e._startCreating()}else{if("start"===a.state)return d.sourceLayer??=t.creationInfo?.layer,await B({sketchViewModel:l,graphic:d,visualVariables:e._visualVariableAttributes,webStyleCache:e._webStyleCache,sourceLayer:d.sourceLayer}),e._selectFeatureForUpdate({feature:d});if("active"===a.state){await e.updatePendingFeature(d);const t=e._visualVariableAttributes;await K(n,d,a,t,e._webStyleCache);const i=d.attributes,{rotation:s,size:o}=t;if(null!=s){const{field:e}=s;r.setValue(e,i[e])}if(null!=o){const{field:e}=o;r.setValue(e,i[e])}}}},w=async a=>{if(a.graphics.forEach((e=>{t.removePendingFeature(e)})),!A(t.creationInfo))return e._startCreating()},g=async()=>{if(A(t.creationInfo))try{await e.data.viewModel.back()}catch{}return e._startCreating()};h.push(l.on("create",(t=>e._updatingHandles.addPromise(m(t)))),l.on("update",(t=>e._updatingHandles.addPromise(f(t)))),l.on("delete",(t=>e._updatingHandles.addPromise(w(t)))),u((()=>!e.numPendingFeatures),(()=>e._updatingHandles.addPromise(g()))),i((()=>{l.cancel()})),re(l,t),...se(t));const y=r(h);return l.addHandles(y),y}_initializeSketchViewModel(){const{data:e}=this,{view:t}=e.viewModel,a=new _({elevationInfo:e.creationInfo?.layer.elevationInfo,internal:!0,listMode:"hide",title:"createFeaturesWorkflow-internal"}),r=new Q({layer:a,creationMode:"single",sketchOptions:e.sketchOptions,snappingManager:e.snappingManager,updateOnGraphicClick:!1,defaultUpdateOptions:{multipleSelectionEnabled:!1},view:t});this._sketchViewModel=r,t?.map.add(a),this.addHandles([i((()=>{t?.destroyed||t?.map.remove(a),a.destroy()})),c((()=>this.numPendingFeatures>0),(e=>this._sketchViewModel.updateOnGraphicClick=e),h)])}_hasValidationErrors(e){return!!e&&(!this.data.isSubmittable(e)||!!this._featureFormViewModel.validateContingencyConstraints(e.attributes,{includeIncompleteViolations:!0})?.length)}async _processEdits(e,t){const{data:a}=this,{layerInfos:i,view:r}=a.viewModel,s=this._featureFormViewModel,{templateExecutorInfo:o}=a;if(!o){const t=e.clone();return t.geometry=null,a.addPendingFeature(e,t),e}const n=this.sketchViewModel.layer;n.remove(e);const{executor:d}=o,c=d(e.geometry,"completion"),u=l(c)?await c:c;o.completionResult=u,s.arcadeEditType="INSERT",s.map=r?.map,s.spatialReference=r?.spatialReference;for(const l of u.edits){let e=null;if(l.addFeatures)for(const r of l.addFeatures){const o=r.clone();o.geometry=null,r.symbol=await M(r,t),n.add(r);const l=a.addPendingFeature(r,o);r.sourceLayer!==e?.layer&&(e=j(i,r.sourceLayer)),s.feature=r,s.formTemplate=e?.formTemplate,await p((()=>!s.updating)),l.submittable=s.submittable}}s.feature=null,await p((()=>!s.updating));return u.edits.reduce(((e,t)=>e+(t.addFeatures?.length??0)),0)>1?null:u.primary?.graphic}async _setUpCreatingFeaturesStep(){if(this.hasHandles(ee))return;const{data:e,sketchViewModel:s}=this,{creationInfo:n,viewModel:l}=e,{attachmentsViewModel:d,view:u}=l;if(!u||!n?.layer)throw new a("missing-parameters","CreateFeaturesWorkflow requires a view and creationInfo.");const{initialFeature:p,layer:m}=n,f=[];if(this._featureFormHandle=o(this._featureFormHandle),this._visualVariableAttributes={rotation:null,size:null},e.editorItem=l.findEditorItemForLayer(n.layer),null===e.fullTemplate&&n.template){const t=await N(n,u);e.fullTemplate=t,t&&y(t)&&(e.templateExecutorInfo={completionResult:null,executor:await F(t),serviceLayersById:await G(n.layer,u)})}z(d),f.push(c((()=>d.mode),(e=>{switch(e){case"add":this.go("adding-attachment");break;case"edit":this.go("editing-attachment")}})));const w=Z(u);f.push(w);const g=b(n.layer);try{if(g){const{template:e}=n;if(e&&v(e))throw new a("Shared templates are not yet supported");const i=p??new t({attributes:{...e?.prototype.attributes,...n.attributeOverrides},sourceLayer:m});await this._startUpdating({feature:i})}else f.push(X._configureSketchViewModel(this)),p?(s.layer.add(p),await this._startUpdating({feature:p})):await this._startCreating()}finally{w.remove()}const _=i((()=>{for(const t of e.pendingFeatures)s.layer.remove(t),e.removePendingFeature(t)})),M=c((()=>u?.timeZone),(e=>this._featureFormViewModel.timeZone=e),h),V=i((()=>{A(n)&&l.cancelWorkflow({warnIfNoWorkflow:!1})}));this._featureFormHandle&&f.push(this._featureFormHandle),this.addHandles(f,this._handleKeys.beforeCommit),this.addHandles([i((()=>d.fileInfos.removeAll())),r(f),V,_,M],ee)}async _waitForActiveToolCleared(){const e=this.data.viewModel.view;if(null==e?.activeTool)return;const t=new AbortController;this.addHandles(s(t),te),await p((()=>null==e?.activeTool),t.signal),t.abort()}};function re(e,t){let a=null;const s=()=>e.snappingOptions.featureSources,o=()=>(a=new S({layer:e.layer}),s().add(a),a),l=()=>{null!=a&&(s().remove(a),a=n(a))};return r([c((()=>{const e=t.creationInfo?.layer,a=s().find((t=>t.layer===e));return{hasFeatureLayerSource:!!a,enabled:a?.enabled??!1}}),(({hasFeatureLayerSource:e,enabled:t})=>{if(!e)return l();a??=o(),a.enabled=t}),m),i(l)])}function se(e){const t=e.viewModel.view;if(!t)return[];const a=[];if("3d"===t.type){const r=new I({view:t});a.push(c((()=>e.selectedPendingFeature),((e,t)=>{r.remove(e),r.add(t)})),i((()=>r.destroy())))}const r=new I({view:t,highlightName:C});return a.push(c((()=>e.temporaryHighlightFeature),(e=>{r.removeAll(),r.add(e)})),i((()=>r.destroy()))),a}function oe(e,t,a,i){const r=[];return t.forEach(((t,s)=>{if(!t.error){const o=e[s],n=i.get(o)||[];o.attributes[a.objectIdField]=t.objectId,n.forEach((({form:e})=>r.push({feature:o,attachment:e})))}})),r}function ne(e){for(const t of e){const{sourceLayer:e}=t;e&&"globalIdField"in e&&null!=e.globalIdField&&(t.attributes[e.globalIdField]??=f())}}function le(e,t){const a=[];if(!t||0===t.size)return{addFeatures:e};for(const[i,r]of t)for(const{file:e}of r)a.push({feature:i,attachment:{globalId:f(),data:e}});return a.length?{addFeatures:e,addAttachments:a}:{addFeatures:e}}function de(e,t){return e.map((e=>{const{addFeatures:a}=e;if(!a||0===a.length)return e;const i=[];for(const r of a){const e=t.get(r);if(e)for(const{file:t}of e)i.push({feature:r,attachment:{globalId:f(),data:t}})}return i.length?{...e,addAttachments:i}:e}))}e([w()],ie.prototype,"createFeatureState",void 0),e([w()],ie.prototype,"data",void 0),e([w({constructOnly:!0})],ie.prototype,"isNested",void 0),e([w()],ie.prototype,"featureFormViewModel",null),e([w()],ie.prototype,"hasPendingEdits",null),e([w()],ie.prototype,"hasPreviousStep",null),e([w()],ie.prototype,"_getDrawMeshHelpMessage",void 0),e([w()],ie.prototype,"helpMessage",null),e([w()],ie.prototype,"layer",null),e([w()],ie.prototype,"parent",null),e([w()],ie.prototype,"parentLayer",null),e([w()],ie.prototype,"keyboardCancellationEnabled",null),e([w()],ie.prototype,"reliesOnOwnerAdminPrivileges",null),e([w()],ie.prototype,"shouldShowAttachments",null),e([w()],ie.prototype,"shouldAllowAttachmentEditing",null),e([w()],ie.prototype,"sketchViewModel",null),e([w()],ie.prototype,"availableCreateTools",null),e([w()],ie.prototype,"_attachmentsActive",null),ie=X=e([g("esri.widgets.Editor.CreateFeaturesWorkflow")],ie);const ce=ie;export{ce as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../Graphic.js";import a from"../../core/Error.js";import{makeHandle as i,handlesGroup as r,abortHandle as s}from"../../core/handleUtils.js";import"../../core/has.js";import{removeMaybe as o,destroyMaybe as n}from"../../core/maybe.js";import{isPromiseLike as l,debounce as d}from"../../core/promiseUtils.js";import{watch as c,when as u,initial as h,whenOnce as p,syncAndInitial as m}from"../../core/reactiveUtils.js";import{generateBracedUUID as f}from"../../core/uuid.js";import{property as w}from"../../core/accessorSupport/decorators/property.js";import"../../core/Logger.js";import"../../core/RandomLCG.js";import{subclass as g}from"../../core/accessorSupport/decorators/subclass.js";import{isSharedTemplate as y,isSharedTemplateOrMetadata as v}from"../../editing/templateUtils.js";import{createTemplateExecutor as F}from"../../editing/sharedTemplates/executor/createTemplateExecutor.js";import _ from"../../layers/GraphicsLayer.js";import{isTable as b}from"../../layers/support/layerUtils.js";import{getDisplayedSymbol as M}from"../../symbols/support/symbolUtils.js";import{getDrawHelpMessage as V}from"../../views/draw/support/helpMessageUtils.js";import I from"../../views/draw/support/HighlightHelper.js";import k from"../../views/interactive/sketch/SketchOptions.js";import S from"../../views/interactive/snapping/FeatureSnappingLayerSource.js";import{temporaryHighlightName as C}from"../../views/support/HighlightDefaults.js";import P from"./CreateFeaturesWorkflowData.js";import{isModelUpload as A,handleModelUpload as H}from"./modelUploadUtils.js";import E from"./Workflow.js";import{setRelationshipFields as T,startCreatingNewFeature as j,findLayerInfo as U,updateGraphicSymbolWhenRequired as L,isTerminalUpdateEventType as x,getVisualVariableAttributes as O,startUpdatingFeatureGeometry as R,createWorkflowSteps as W,avoidFeatureTemplateSelectionWithOnlyOneItem as D,getCreationAttributes as N,getFullTemplateForCreationInfo as G,getServiceLayersById as z,prepareAttachmentsForCreateFeaturesWorkflow as Z,showProgressCursor as q,setUpSketchCreateWatchers as B,setVisualVariablesAndElevationInfoForUpdate as K,visualVariableInteractiveUpdate as J}from"./workflowUtils.js";import Q from"../FeatureForm/FeatureFormViewModel.js";import X from"../Sketch/SketchViewModel.js";var Y;const $=Symbol(),ee=Symbol(),te=Symbol(),ae=Symbol(),ie={point:["point"],multipoint:["multipoint"],polygon:["polygon","freehandPolygon","rectangle","circle"],polyline:["polyline","freehandPolyline"],mesh:[],multipatch:[]};let re=Y=class extends E{constructor(e){super(e),this.type="create-features",this.createFeatureState="create-new",this.data=void 0,this.isNested=!1,this._getDrawMeshHelpMessage=void 0,this._webStyleCache=new Map,this._featureFormHandle=null,this._visualVariableAttributes={rotation:null,size:null},this._featureFormViewModel=new Q,this._sketchViewModel=null,this._attachmentFileInfos=new Map,this._isActive=!0}initialize(){this.isNested&&(this._isActive=!1),this._initializeSketchViewModel()}destroy(){this._sketchViewModel.destroy()}get featureFormViewModel(){return this._featureFormViewModel}get hasPendingEdits(){if(this.pendingFeatures.some((e=>!!this.data.getEditsForPendingFeature(e)?.modified)))return!0;const{creationInfo:e,upload:t}=this.data,a=this._sketchViewModel,{activeComponent:i}=a,r=a.createGraphic?.geometry?.type;return!("polyline"!==r&&"polygon"!==r&&"multipoint"!==r||"draw-2d"!==i?.type&&"draw-3d"!==i?.type)&&i.drawOperation.committedVertices.length>0||(!(!t||"pending"!==t.state&&"success"!==t.state)||!!e?.geometryToPlace)}get hasPreviousStep(){return this._stepIndex>0||"update-pending"===this.createFeatureState&&!!this.data.selectedPendingFeature}get helpMessage(){const{creationInfo:e,viewModel:t}=this.data;if("creating-features"!==this.stepId||!e)return;const a=e.layer.geometryType,i=this._sketchViewModel.createGraphic;if("mesh"===a){this._getDrawMeshHelpMessage||import("../../views/draw/support/helpMessageUtils3d.js").then((e=>{this._getDrawMeshHelpMessage=e.getDrawMeshHelpMessage}));const{view:e}=t;return"3d"===e?.type?this._getDrawMeshHelpMessage?.(i,e):void 0}const r=this._sketchViewModel.activeCreateToolDrawMode,s=this._sketchViewModel.activeTool;return V("rectangle"===s?"rectangle":"circle"===s?"circle":a,i?.geometry,r)}get layer(){return this.data.creationInfo?.layer}get numPendingFeatures(){return this.pendingFeatures.length}get parent(){return this.data.parent}get parentLayer(){return this.parent?.data.editorItem.layer}get pendingFeatures(){return this.data.pendingFeatures}get keyboardCancellationEnabled(){return 0===this.numPendingFeatures}get reliesOnOwnerAdminPrivileges(){return this.data.editorItem?.capabilities.create.reliesOnOwnerAdminPrivileges??!1}get shouldShowAttachments(){return(this.data.selectedPendingFeature&&this.data.editorItem?.capabilities.create.attachments.enabled)??!1}get shouldAllowAttachmentEditing(){return this.shouldShowAttachments}get sketchViewModel(){return this._sketchViewModel}get test(){}get availableCreateTools(){const e=this.data.creationInfo?.layer.geometryType,t=this.data.viewModel.view;return e?this.data.creationInfo?.maxFeatures&&this.data.creationInfo.maxFeatures<=this.numPendingFeatures||"2d"!==t?.type&&"multipoint"===e?[]:[...ie[e]]:[]}get _attachmentsActive(){const e=this.data.viewModel.attachmentsViewModel.mode,t=this.stepId;return this.shouldShowAttachments&&("add"===e||"edit"===e||"adding-attachment"===t||"editing-attachment"===t)}async enter(){this._isActive=!0,"awaiting-feature-creation-info"!==this.stepId&&this._setUpCreatingFeaturesStep()}exit(){this._isActive=!1,this.removeHandles([te])}async updatePendingFeature(e){if(e!==this.data.selectedPendingFeature)return this._sketchViewModel.cancel(),this._startUpdating({feature:e})}async start(){return await super.start(),b(this.data.creationInfo?.layer)?null:{enter:async()=>{},exit:async()=>{},viewModel:this._sketchViewModel}}async save(){const{featureFormViewModel:e}=this;if(e.pendingSubtypeChoice)return;e.submit(),this._stashValidationState();const t=this.data.selectedPendingFeature,a=this._hasValidationErrors(t)?t:this.data.pendingFeatures.find((e=>this._hasValidationErrors(e)));return a?(await this._startUpdating({feature:a}),void e?.submit()):super.save()}back(e){return"update-pending"!==this.createFeatureState||!this.data.selectedPendingFeature||A(this.data.creationInfo)||this._attachmentsActive?super.back(e):this._clearSelectedFeature()}previous(e){return"update-pending"!==this.createFeatureState||!this.data.selectedPendingFeature||A(this.data.creationInfo)||this._attachmentsActive?super.previous(e):this._clearSelectedFeature()}cancelFeature(e){this.data.removePendingFeature(e),this.sketchViewModel.layer.graphics.remove(e)}static create(e){const{addAttachmentsCallback:t,applyEditsCallback:a,applyEditsFeatureServiceCallback:i,isNested:r,creationInfo:s,parent:o,snappingManager:n,startAt:l,viewModel:d}=e,c=e.sketchOptions??new k,u=s?.layer,h=u?d.findEditorItemForLayer(u):void 0,p=new Y({data:new P({creationInfo:s,editorItem:h,parent:o,sketchOptions:c,snappingManager:n,viewModel:d}),isNested:r,onCommit:async e=>{const{creationInfo:r}=e;if(!r)return;p._sketchViewModel.cancel();const s=e.pendingFeatures.toArray(),{layer:o}=r,n=o.capabilities?.editing.supportsGlobalId&&"globalIdField"in o,l=p._attachmentFileInfos,{fullTemplate:d,templateExecutorInfo:c}=e;c?.completionResult&&T(c.completionResult.relationships);const u=d&&y(d)&&c?.completionResult;if(n){if(le(s),u){const e=ce(c.completionResult.edits,l);await i(d.featureService,e,{globalIdUsed:!0,gdbVersion:d.layer.gdbVersion??void 0})}else{const e=de(s,l);await a(o,e,{globalIdUsed:!0})}return}const h=u?await i(d.featureService,c.completionResult.edits,{gdbVersion:d.layer.gdbVersion??void 0}):[await a(o,{addFeatures:s})];h&&l.size>0&&await Promise.all(h.map((e=>{if(e?.addFeatureResults)return t(o,ne(s,e.addFeatureResults,o,l))})))}});return p._set("steps",this._createWorkflowSteps(p,l)),p}_fadeExistingFeatures(e){if("effect"in e){const t=e.effect;return e.effect="saturate(0.6) opacity(0.8)",i((()=>e.effect=t))}const t=e.opacity;return e.opacity=.7,i((()=>e.opacity=t))}async _startCreating(){this.removeHandles(ee);const{data:e}=this;if(!e.creationInfo)return;const t=this.data.creationInfo?.maxFeatures;if(t&&this.numPendingFeatures>=t)return this.sketchViewModel.cancel(),void(this.numPendingFeatures&&await this._startUpdating({feature:this.pendingFeatures.at(-1)}));this.createFeatureState="create-new";const a=await j(this._sketchViewModel,e,this._webStyleCache);this.addHandles(a,ee)}async _clearSelectedFeature(){const e=this._featureFormViewModel.pendingSubtypeChoice;e&&(e.resolve("undo"),await e.promise),this._stashValidationState(),this.sketchViewModel.cancel(),this.data.selectedPendingFeature=null,this._featureFormHandle=o(this._featureFormHandle),this._featureFormViewModel.feature=null;const t=this.data.viewModel.attachmentsViewModel;"add"!==t.mode&&"edit"!==t.mode||this.data.viewModel.activeWorkflow?.previous()}_stashValidationState(){const e=this._featureFormViewModel.feature,t=e&&this.data.getEditsForPendingFeature(e);t&&(t.submittable=this._featureFormViewModel.submittable)}async _selectFeatureForUpdate({feature:e,initialFeature:t=e}){this._stashValidationState();const{data:a,pendingFeatures:i,_webStyleCache:s}=this;i.includes(e)||a.addPendingFeature(e,t),a.selectedPendingFeature=e;const{_featureFormViewModel:n,_sketchViewModel:l}=this,{creationInfo:d,viewModel:u}=a,{attachmentsViewModel:h,layerInfos:p,view:m}=u;if(!m||!d)return;o(this._featureFormHandle);const f=e.sourceLayer,w=U(p,f),g=w?.formTemplate,y=m.spatialReference;n.set({arcadeEditType:"INSERT",feature:e,formTemplate:g,spatialReference:y,map:m.map}),"add"!==h.mode&&"edit"!==h.mode||u.activeWorkflow?.previous(),h.graphic=e,h.fileInfos.removeAll(),h.mode="view";(this._attachmentFileInfos.get(e)||[]).forEach((({file:e,form:t})=>h.addFile(e,t))),await L(e,s,"2d"===m.type?m.scale:null);const v=a.getEditsForPendingFeature(e);this._featureFormHandle=r([n.on("value-change",(async()=>{v?.updateAttributes(n.getValues()),await L(e,s,"2d"===m.type?m.scale:null)})),l.on(["update","undo","redo"],(e=>{("undo"===e.type||"redo"===e.type||"update"===e.type&&null!=e.toolEventInfo&&x(e.toolEventInfo.type))&&n.notifyFeatureGeometryChanged()})),c((()=>n.feature?.sourceLayer),(t=>e.sourceLayer=t)),c((()=>[n.feature,n.submittable]),(()=>this._stashValidationState()))]),this.createFeatureState="update-pending"}async _startUpdating({feature:e,initialFeature:t=e}){await this._selectFeatureForUpdate({feature:e,initialFeature:t});const{_sketchViewModel:a,data:i}=this,{creationInfo:r,viewModel:s}=i,{view:o}=s;if(!o||!r)return;const n=e.sourceLayer??r.layer;return b(n)?void 0:(this._visualVariableAttributes=O(e),R({graphic:e,sketchViewModel:a,sourceLayer:n,visualVariables:this._visualVariableAttributes,webStyleCache:this._webStyleCache}))}static _createWorkflowSteps(e,t="awaiting-feature-creation-info"){const{data:a}=e,i=W(["awaiting-feature-creation-info","creating-features","adding-attachment","editing-attachment"],t,{"awaiting-feature-creation-info":()=>({id:"awaiting-feature-creation-info",async setUp(){const{creationInfo:t,viewModel:i}=a,{view:r}=i;r&&(A(t)?e.addHandles(await H({view:r,data:a,next:()=>e.next(),cancel:()=>i.cancelWorkflow({warnIfNoWorkflow:!1})}),this.id):(a.parent&&t&&e.addHandles(i.restrictFeatureTemplatesViewModelToLayer(t.layer),this.id),e.addHandles(i.featureTemplatesViewModel.on("select",(({item:t})=>{t&&(a.creationInfo={...a.creationInfo,layer:t.layer,template:t.template},e.next())})),this.id)))},async tearDown(){e.removeHandles(this.id)}}),"creating-features":()=>({id:"creating-features",async setUp(){e._isActive&&await e._setUpCreatingFeaturesStep()},async tearDown(t){const{viewModel:i}=a;t.canceled&&(e.removeHandles([te,$,ee,ae]),i.attachmentsViewModel.fileInfos.removeAll(),e._attachmentFileInfos.clear())}}),"adding-attachment":()=>({id:"adding-attachment",parent:"creating-features",async setUp(){},async tearDown(){const{attachmentsViewModel:t}=a.viewModel,{graphic:i,fileInfos:r}=t;e._attachmentFileInfos.set(i,r.toArray()),t.mode="view"}}),"editing-attachment":()=>({id:"editing-attachment",parent:"creating-features",async setUp(){},async tearDown(){const{attachmentsViewModel:t}=a.viewModel,{graphic:i,fileInfos:r}=t;e._attachmentFileInfos.set(i,r.toArray()),t.mode="view"}})});return D(a,i)}static _configureSketchViewModel(e){const{data:t}=e,a=e._webStyleCache,{creationInfo:s,viewModel:o}=t,{view:n}=o,l=e._sketchViewModel,h=[];if(!n)return i();if("2d"===n.type){s&&h.push(e._fadeExistingFeatures(s.layer));const t=d(((e,t)=>Promise.all(e.map((e=>L(e,a,t))))));h.push(c((()=>n.scale),(e=>t(l.layer.graphics,e))))}const p=N(t.fullTemplate,s?.attributeOverrides),m=async i=>{if("start"!==i.state||e.hasHandles(ee)||e.addHandles(await B({creationAttributes:p,data:t,sketchViewModel:l,view:n,webStyleCache:a}),ee),"cancel"!==i.state&&"complete"!==i.state||e.removeHandles(ee),"cancel"===i.state&&null!==n.activeTool&&n.activeTool!==e.sketchViewModel.activeComponent&&(await e._waitForActiveToolCleared(),await e._startCreating()),"complete"===i.state&&i.graphic){const t=await e._processEdits(i.graphic,{scale:"2d"===n.type?n.scale:null,useSourceLayer:!0,webStyleCache:e._webStyleCache});t&&(await e._waitForActiveToolCleared(),await e._startUpdating({feature:t}))}},f=async a=>{const{attachmentsViewModel:i}=o,{_featureFormViewModel:r}=e;if(a.graphics.length>1)return void await e._clearSelectedFeature();const d=a.graphics[0];if("complete"===a.state){const{submittable:t}=r;if(e.numPendingFeatures!==s?.maxFeatures&&t||r.submit(),await e._clearSelectedFeature(),"add"!==i.mode&&"edit"!==i.mode||o.activeWorkflow?.previous(),!a.aborted&&n.activeTool===e.sketchViewModel.activeComponent&&(await e.sketchViewModel.wait(),"ready"===e.sketchViewModel.state&&"mesh"!==e.data.creationInfo?.layer.geometryType))return e._startCreating()}else{if("start"===a.state)return d.sourceLayer??=t.creationInfo?.layer,await K({sketchViewModel:l,graphic:d,visualVariables:e._visualVariableAttributes,webStyleCache:e._webStyleCache,sourceLayer:d.sourceLayer}),e._selectFeatureForUpdate({feature:d});if("active"===a.state){await e.updatePendingFeature(d);const t=e._visualVariableAttributes;await J(n,d,a,t,e._webStyleCache);const i=d.attributes,{rotation:s,size:o}=t;if(null!=s){const{field:e}=s;r.setValue(e,i[e])}if(null!=o){const{field:e}=o;r.setValue(e,i[e])}}}},w=async a=>{if(a.graphics.forEach((e=>{t.removePendingFeature(e)})),!A(t.creationInfo))return e._startCreating()},g=async()=>{if(A(t.creationInfo))try{await e.data.viewModel.back()}catch{}return e._startCreating()};h.push(l.on("create",(t=>e._updatingHandles.addPromise(m(t)))),l.on("update",(t=>e._updatingHandles.addPromise(f(t)))),l.on("delete",(t=>e._updatingHandles.addPromise(w(t)))),u((()=>!e.numPendingFeatures),(()=>e._updatingHandles.addPromise(g()))),i((()=>{l.cancel()})),se(l,t),...oe(t));const y=r(h);return l.addHandles(y),y}_initializeSketchViewModel(){const{data:e}=this,{view:t}=e.viewModel,a=new _({elevationInfo:e.creationInfo?.layer.elevationInfo,internal:!0,listMode:"hide",title:"createFeaturesWorkflow-internal"}),r=new X({layer:a,creationMode:"single",sketchOptions:e.sketchOptions,snappingManager:e.snappingManager,updateOnGraphicClick:!1,defaultUpdateOptions:{multipleSelectionEnabled:!1},view:t});this._sketchViewModel=r,t?.map.add(a),this.addHandles([i((()=>{t?.destroyed||t?.map.remove(a),a.destroy()})),c((()=>this.numPendingFeatures>0),(e=>this._sketchViewModel.updateOnGraphicClick=e),h)])}_hasValidationErrors(e){return!!e&&(!this.data.isSubmittable(e)||!!this._featureFormViewModel.validateContingencyConstraints(e.attributes,{includeIncompleteViolations:!0})?.length)}async _processEdits(e,t){const{data:a}=this,{layerInfos:i,view:r}=a.viewModel,s=this._featureFormViewModel,{templateExecutorInfo:o}=a;if(!o){const t=e.clone();return t.geometry=null,a.addPendingFeature(e,t),e}const n=this.sketchViewModel.layer;n.remove(e);const{executor:d}=o,c=d(e.geometry,"completion"),u=l(c)?await c:c;o.completionResult=u,T(u.relationships),s.arcadeEditType="INSERT",s.map=r?.map,s.spatialReference=r?.spatialReference;for(const l of u.edits){let e=null;if(l.addFeatures)for(const r of l.addFeatures){const o=r.clone();o.geometry=null,r.symbol=await M(r,t),n.add(r);const l=a.addPendingFeature(r,o);r.sourceLayer!==e?.layer&&(e=U(i,r.sourceLayer)),s.feature=r,s.formTemplate=e?.formTemplate,await p((()=>!s.updating)),l.submittable=s.submittable}}s.feature=null,await p((()=>!s.updating));return u.edits.reduce(((e,t)=>e+(t.addFeatures?.length??0)),0)>1?null:u.primary?.graphic}async _setUpCreatingFeaturesStep(){if(this.hasHandles(te))return;const{data:e,sketchViewModel:s}=this,{creationInfo:n,viewModel:l}=e,{attachmentsViewModel:d,view:u}=l;if(!u||!n?.layer)throw new a("missing-parameters","CreateFeaturesWorkflow requires a view and creationInfo.");const{initialFeature:p,layer:m}=n,f=[];if(this._featureFormHandle=o(this._featureFormHandle),this._visualVariableAttributes={rotation:null,size:null},e.editorItem=l.findEditorItemForLayer(n.layer),null===e.fullTemplate&&n.template){const t=await G(n,u);e.fullTemplate=t,t&&y(t)&&(e.templateExecutorInfo={completionResult:null,executor:await F(t),serviceLayersById:await z(n.layer,u)})}Z(d),f.push(c((()=>d.mode),(e=>{switch(e){case"add":this.go("adding-attachment");break;case"edit":this.go("editing-attachment")}})));const w=q(u);f.push(w);const g=b(n.layer);try{if(g){const{template:e}=n;if(e&&v(e))throw new a("Shared templates are not yet supported");const i=p??new t({attributes:{...e?.prototype.attributes,...n.attributeOverrides},sourceLayer:m});await this._startUpdating({feature:i})}else f.push(Y._configureSketchViewModel(this)),p?(s.layer.add(p),await this._startUpdating({feature:p})):await this._startCreating()}finally{w.remove()}const _=i((()=>{for(const t of e.pendingFeatures)s.layer.remove(t),e.removePendingFeature(t)})),M=c((()=>u?.timeZone),(e=>this._featureFormViewModel.timeZone=e),h),V=i((()=>{A(n)&&l.cancelWorkflow({warnIfNoWorkflow:!1})}));this._featureFormHandle&&f.push(this._featureFormHandle),this.addHandles(f,this._handleKeys.beforeCommit),this.addHandles([i((()=>d.fileInfos.removeAll())),r(f),V,_,M],te)}async _waitForActiveToolCleared(){const e=this.data.viewModel.view;if(null==e?.activeTool)return;const t=new AbortController;this.addHandles(s(t),ae),await p((()=>null==e?.activeTool),t.signal),t.abort()}};function se(e,t){let a=null;const s=()=>e.snappingOptions.featureSources,o=()=>(a=new S({layer:e.layer}),s().add(a),a),l=()=>{null!=a&&(s().remove(a),a=n(a))};return r([c((()=>{const e=t.creationInfo?.layer,a=s().find((t=>t.layer===e));return{hasFeatureLayerSource:!!a,enabled:a?.enabled??!1}}),(({hasFeatureLayerSource:e,enabled:t})=>{if(!e)return l();a??=o(),a.enabled=t}),m),i(l)])}function oe(e){const t=e.viewModel.view;if(!t)return[];const a=[];if("3d"===t.type){const r=new I({view:t});a.push(c((()=>e.selectedPendingFeature),((e,t)=>{r.remove(e),r.add(t)})),i((()=>r.destroy())))}const r=new I({view:t,highlightName:C});return a.push(c((()=>e.temporaryHighlightFeature),(e=>{r.removeAll(),r.add(e)})),i((()=>r.destroy()))),a}function ne(e,t,a,i){const r=[];return t.forEach(((t,s)=>{if(!t.error){const o=e[s],n=i.get(o)||[];o.attributes[a.objectIdField]=t.objectId,n.forEach((({form:e})=>r.push({feature:o,attachment:e})))}})),r}function le(e){for(const t of e){const{sourceLayer:e}=t;e&&"globalIdField"in e&&null!=e.globalIdField&&(t.attributes[e.globalIdField]??=f())}}function de(e,t){const a=[];if(!t||0===t.size)return{addFeatures:e};for(const[i,r]of t)for(const{file:e}of r)a.push({feature:i,attachment:{globalId:f(),data:e}});return a.length?{addFeatures:e,addAttachments:a}:{addFeatures:e}}function ce(e,t){return e.map((e=>{const{addFeatures:a}=e;if(!a||0===a.length)return e;const i=[];for(const r of a){const e=t.get(r);if(e)for(const{file:t}of e)i.push({feature:r,attachment:{globalId:f(),data:t}})}return i.length?{...e,addAttachments:i}:e}))}e([w()],re.prototype,"createFeatureState",void 0),e([w()],re.prototype,"data",void 0),e([w({constructOnly:!0})],re.prototype,"isNested",void 0),e([w()],re.prototype,"featureFormViewModel",null),e([w()],re.prototype,"hasPendingEdits",null),e([w()],re.prototype,"hasPreviousStep",null),e([w()],re.prototype,"_getDrawMeshHelpMessage",void 0),e([w()],re.prototype,"helpMessage",null),e([w()],re.prototype,"layer",null),e([w()],re.prototype,"parent",null),e([w()],re.prototype,"parentLayer",null),e([w()],re.prototype,"keyboardCancellationEnabled",null),e([w()],re.prototype,"reliesOnOwnerAdminPrivileges",null),e([w()],re.prototype,"shouldShowAttachments",null),e([w()],re.prototype,"shouldAllowAttachmentEditing",null),e([w()],re.prototype,"sketchViewModel",null),e([w()],re.prototype,"availableCreateTools",null),e([w()],re.prototype,"_attachmentsActive",null),re=Y=e([g("esri.widgets.Editor.CreateFeaturesWorkflow")],re);const ue=re;export{ue 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.33/esri/copyright.txt for details.
4
4
  */
5
- import{loadCalciteComponents as t}from"../../support/componentsUtils.js";import{Heading as e}from"../../support/Heading.js";import{iconByKind as o}from"../../support/iconUtils.js";import{setFocus as i}from"../../support/widgetUtils.js";import{tsx as a}from"../../support/jsxFactory.js";const c="esri-editor__prompt",n={base:c,header:`${c}__header`,heading:`${c}__header__heading`,message:`${c}__message`,divider:`${c}__divider`,actions:`${c}__actions`},s=()=>t({button:()=>import("@esri/calcite-components/dist/components/calcite-button"),icon:()=>import("@esri/calcite-components/dist/components/calcite-icon"),scrim:()=>import("@esri/calcite-components/dist/components/calcite-scrim"),label:()=>import("@esri/calcite-components/dist/components/calcite-label"),"radio-button":()=>import("@esri/calcite-components/dist/components/calcite-radio-button"),"radio-button-group":()=>import("@esri/calcite-components/dist/components/calcite-radio-button-group")});function r({actions:t,context:c,headingLevel:s,message:r,title:p,...d}){const{primary:m,secondary:u}=t;let b;switch(c){case"danger":b="danger";break;case"info":b="brand";break;default:b="neutral"}const g=a("calcite-button",{afterCreate:t=>i(t),appearance:"solid","data-testid":"primary-prompt-button",key:"prompt-primary-button",kind:b,onclick:m.action,width:"full"},m.label),h=u&&a("calcite-button",{appearance:"outline","data-testid":"secondary-prompt-button",key:"prompt-secondary-button",kind:b,onclick:u.action,width:"full"},u.label);return a("calcite-scrim",{"data-testid":"prompt",key:"prompt"},a("div",{class:`${n.base}--${c}`},a("div",{class:n.header},a("calcite-icon",{icon:o.warning}),a(e,{class:n.heading,level:s},p)),a("div",{class:n.message},r),l(d)??a("div",{class:n.divider}),a("div",{class:n.actions},h,g)))}function l({radios:t,onRadioSelection:e,defaultRadioSelection:o}){return t?.length?a("calcite-radio-button-group",{name:"PromptChoiceList"},t.map((t=>a("calcite-label",{layout:"inline"},a("calcite-radio-button",{checked:t.value===o,value:t.value,onCalciteRadioButtonChange:()=>e?.(t.value)}),t.label)))):void 0}export{r as Prompt,n as css,s as loadPromptComponents};
5
+ import{loadCalciteComponents as t}from"../../support/componentsUtils.js";import{Heading as e}from"../../support/Heading.js";import{iconByKind as o}from"../../support/iconUtils.js";import{setFocus as i}from"../../support/widgetUtils.js";import{tsx as a}from"../../support/jsxFactory.js";const c="esri-editor__prompt",n={base:c,header:`${c}__header`,heading:`${c}__header__heading`,message:`${c}__message`,divider:`${c}__divider`,actions:`${c}__actions`,halfWidthButton:`${c}__half-width-button`},s=()=>t({button:()=>import("@esri/calcite-components/dist/components/calcite-button"),icon:()=>import("@esri/calcite-components/dist/components/calcite-icon"),scrim:()=>import("@esri/calcite-components/dist/components/calcite-scrim"),label:()=>import("@esri/calcite-components/dist/components/calcite-label"),"radio-button":()=>import("@esri/calcite-components/dist/components/calcite-radio-button"),"radio-button-group":()=>import("@esri/calcite-components/dist/components/calcite-radio-button-group")});function r({actions:t,context:c,headingLevel:s,message:r,title:d,...p}){const{primary:m,secondary:u}=t;let b;switch(c){case"danger":b="danger";break;case"info":b="brand";break;default:b="neutral"}const h=a("calcite-button",{afterCreate:t=>i(t),appearance:"solid",classes:{[n.halfWidthButton]:!!u},"data-testid":"primary-prompt-button",key:"prompt-primary-button",kind:b,onclick:m.action,width:"full"},m.label),g=u&&a("calcite-button",{appearance:"outline",class:n.halfWidthButton,"data-testid":"secondary-prompt-button",key:"prompt-secondary-button",kind:b,onclick:u.action,width:"full"},u.label);return a("calcite-scrim",{"data-testid":"prompt",key:"prompt"},a("div",{class:`${n.base}--${c}`},a("div",{class:n.header},a("calcite-icon",{icon:o.warning}),a(e,{class:n.heading,level:s},d)),a("div",{class:n.message},r),l(p)??a("div",{class:n.divider}),a("div",{class:n.actions},g,h)))}function l({radios:t,onRadioSelection:e,defaultRadioSelection:o}){return t?.length?a("calcite-radio-button-group",{name:"PromptChoiceList"},t.map((t=>a("calcite-label",{layout:"inline"},a("calcite-radio-button",{checked:t.value===o,value:t.value,onCalciteRadioButtonChange:()=>e?.(t.value)}),t.label)))):void 0}export{r as Prompt,n as css,s as loadPromptComponents};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../Color.js";import t from"../../Graphic.js";import{addMany as r,equals as i}from"../../core/arrayUtils.js";import{createTask as n}from"../../core/asyncUtils.js";import"../../core/has.js";import a from"../../core/Error.js";import{handlesGroup as o,makeHandle as s,abortHandle as l}from"../../core/handleUtils.js";import{clone as c}from"../../core/lang.js";import u from"../../core/Logger.js";import{getOrCreateMapValue as p}from"../../core/MapUtils.js";import{whenOrAbort as d,throwIfAborted as y,debounce as f,isPromiseLike as m}from"../../core/promiseUtils.js";import{watch as g,on as h,whenOnce as w}from"../../core/reactiveUtils.js";import{px2pt as b}from"../../core/screenUtils.js";import{diff as v}from"../../core/accessorSupport/diffUtils.js";import{isSharedGroupTemplate as S,isSharedPresetTemplate as j,isStandardFeatureTemplate as I,isSharedFeatureTemplate as T,getAllStandardFeatureTemplatesForLayer as U,isSharedTemplate as V,isSharedTemplateOrMetadata as L}from"../../editing/templateUtils.js";import k from"../../editing/sharedTemplates/SharedTemplate.js";import{getSharedTemplateProvider as O}from"../../editing/sharedTemplates/SharedTemplateProvider.js";import F from"../../layers/GraphicsLayer.js";import{featureHasFields as z,fixFields as x,getDisplayFieldName as A}from"../../layers/support/fieldUtils.js";import{isSubtypeSublayer as M}from"../../layers/support/layerUtils.js";import{calculateTolerance as P}from"../../renderers/support/clickToleranceUtils.js";import{meterIn as C}from"../../renderers/support/lengthUtils.js";import{getTransformationType as E,TransformationType as R}from"../../renderers/visualVariables/support/sizeVariableUtils.js";import{getRotationAngle as G,getSize as D}from"../../renderers/visualVariables/support/visualVariableUtils.js";import Z from"../../symbols/SimpleFillSymbol.js";import q from"../../symbols/SimpleLineSymbol.js";import B from"../../symbols/SimpleMarkerSymbol.js";import{to3D as N}from"../../symbols/support/symbolConversion.js";import{getDisplayedSymbol as Q}from"../../symbols/support/symbolUtils.js";import{getServices as J}from"../../undoredo/support/Services.js";import{GraphicState as W}from"../../views/3d/layers/graphics/GraphicState.js";import{defaultDrawingMode as H}from"../../views/draw/DrawingMode.js";import{createQueryGeometry as K}from"../../views/support/drapedUtils.js";import{hitTestSelectSimilarDistance as X,filterGraphicHits as Y}from"../../views/support/hitTestSelectUtils.js";import{isDrawGraphicTool as $}from"../Sketch/support/sketchUtils.js";const _=()=>u.getLogger("esri.widgets.Editor.workflowUtils");function ee(e){return"update"===e.type}function te(e){const t=e.sourceLayer;if(!t||"feature"!==t.type||!se(t.renderer))return{rotation:null,size:null};let r=null,i=null;const n=t.renderer.getVisualVariablesForType("rotation").filter((t=>(!t.axis||"heading"===t.axis)&&t.field&&!t.valueExpression&&null!=G(t,e)));1===n.length&&(r=re(n[0],t));const a=t.renderer.getVisualVariablesForType("size").filter((t=>t.field&&!t.useSymbolValue&&!t.valueExpression&&E(t)===R.RealWorldSize&&null!=D(t,e)));return 1===a.length&&(i=ae(a[0],t)),{rotation:r,size:i}}function re(e,t){const r="heading"===(e.axis||"heading")&&"arithmetic"===e.rotationType?-1:1,i=e.field,n=t.fields&&t.fields.filter((e=>e.name===i)),a=n&&1===n.length?n[0].type:"double",o={initial:0,current:0};return{field:i,fieldType:a,getDefault:()=>Promise.resolve(0),getValue:e=>(o.current=o.initial-r*e,oe((o.current+360)%360,a)),setInitialValue:e=>{o.initial=e,o.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 ne(e,t,r){if(null==t)return 0;const{symbol:i}=N(t);if(null==i||"web-style"===i.type||"cim"===i.type)return 0;const n=i.symbolLayers.at(0);if(!n)return 0;switch(n.type){case"icon":{const{computeIconLayerResourceSize:e}=await import("../../symbols/support/symbolLayerUtils.js");return n.size||Math.min(Pe.icon,(await e(n,Pe.icon))[0])||Pe.icon}case"text":return n.size||Pe.text;case"line":return n.size||Pe.line;case"object":{const{computeObjectLayerResourceSize:t}=await import("../../symbols/support/symbolLayerUtils.js");return ie(await t(n,e.scale/Pe.viewScaleSizeFactor),r)}case"path":return(null!=n.width?n.width:n.height)||e.scale/Pe.viewScaleSizeFactor;case"extrude":return n.size||e.scale/Pe.viewScaleSizeFactor;default:return 0}}function ae(e,t){const r=e.field,i=e.axis,n=t.fields&&t.fields.filter((e=>e.name===r)),a=n&&1===n.length?n[0].type:"double",o={initial:0,current:0},s=C[e.valueUnit]??1;let l;return l="area"===e.valueRepresentation?e=>(e*s/2)**2*Math.PI:"radius"===e.valueRepresentation||"distance"===e.valueRepresentation?e=>e*s/2:e=>e*s,{field:r,fieldType:a,getDefault:async(e,t)=>oe(l(await ne(t,e,i)),a),getValue:(e,t)=>(o.initial||(o.initial=t.pixelSizeAt(t.center)),o.current=o.initial*e,oe(o.current,a)),setInitialValue:e=>{o.initial=e,o.current=0},isUpdatingInteractively:!1,displayUnit:Re(e.valueUnit),axis:e.axis}}function oe(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 se(e){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 le(e,t,r){const i=await Q(e,{useSourceLayer:!0,ignoreGraphicSymbol:!0,webStyleCache:t,scale:r});null!=v(e.symbol,i)&&(e.symbol=i)}function ce(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 i={mode:H,optionsPerTool:r};if(L(t)){const n=t.defaultTool,a=S(t)?t.definition?.inputGeometryType??e:e;switch(n){case"freehand":case"stream-line":return{tool:"polyline"===a?"freehandPolyline":"freehandPolygon",createOptions:i};case"autocomplete-freehand-polygons":case"stream-polygon":return{tool:"freehandPolygon",createOptions:i};case"autocomplete-polygons":case"difference-polygon":case"create-structures":case"polygon":case"trace":return{tool:"polygon"===a?"polygon":"polyline",createOptions:i};case"circle":return r.get("circle").preserveAspectRatio=!0,{tool:"circle",createOptions:i};case"ellipse":return r.get("circle").preserveAspectRatio=!1,{tool:"circle",createOptions:i};case"create-points-along-line":case"multipoint":return{tool:"multipoint",createOptions:i};case"line":case"radial-line":case"right-angle-line":case"split":case"two-point-line":return{tool:"polyline",createOptions:i};case"rectangle":case"regular-polygon":case"right-angle-polygon":return{tool:"rectangle",createOptions:i};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:i}}}else{const n=t.drawingTool;if("circle"===n||"ellipse"===n)return r.get("circle").preserveAspectRatio="circle"===n,{tool:"circle",createOptions:i};if("rectangle"===n)return{tool:"rectangle",createOptions:i};if("freehand"===n)return{tool:"polygon"===e?"freehandPolygon":"freehandPolyline",createOptions:i}}return{tool:e,createOptions:i}}async function ue(e,t,r){const{creationInfo:i,fullTemplate:n}=t;if(!i)throw new a("No creation info provided.");const o=i.layer,s=he(n,i.attributeOverrides),{view:l}=e,c="2d"===l?.type;S(n)||j(n)||await we(e,o,s,r,c?l.scale:null);const{capabilities:u}=o;e.layer.elevationInfo=o.elevationInfo;const p=ce(o.geometryType,n);return 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==i.geometryToPlace?await e.create(p.tool):await e.place(i.geometryToPlace,{graphicProperties:{attributes:s,sourceLayer:o}}),pe({creationAttributes:s,data:t,sketchViewModel:e,view:l,webStyleCache:r})}async function pe(e){return o([await de(e),await ye(e)])}async function de({creationAttributes:e,data:t,sketchViewModel:r,view:i,webStyleCache:n}){const{creationInfo:a}=t,{fullTemplate:o}=t;if(!a||"2d"!==i?.type||S(o)||j(o))return null;const s=f((t=>we(r,a.layer,e,n,t)));return g((()=>i.scale),(e=>s(e)))}async function ye({data:t,sketchViewModel:r,view:i}){const{templateExecutorInfo:n}=t;if(!n)return null;const l=r.activeComponent;if(!i||!$(l))return _().error(new a("Failed to set up template feedback.")),null;const c=new F({effect:"saturate(0.6) opacity(0.8)",listMode:"hide",title:"Shared Template Feedback Graphics"});i.map?.add(c);const{executor:u,serviceLayersById:p}=n,d=i.theme?.accentColor??new e([255,165,0,1]);return o([h((()=>l),["cursor-update","vertex-add"],(()=>{c.removeAll();const e=l.graphic?.geometry;if(!e||!fe(e))return;const t=u(e,"digitizing");if(!m(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=me(e,d);t&&c.add(t)}}})),s((()=>{i.map.remove(c),c.destroy()}))])}function fe(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 i(t.at(0),t.at(-1))?t.length>2:t.length>1}default:return!1}}function me(e,r){let i=null;switch(e.geometry?.type){case"point":case"multipoint":i=new B({angle:0,color:r,outline:new q({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":i=new Z({color:r,outline:new q({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:3}),style:"none"});break;case"polyline":i=new q({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:2});break;default:return null}return new t({geometry:e.geometry,symbol:i,attributes:{...e.attributes}})}async function ge(e,t){const r=await J(t).load(),i=M(e)?e.parent:e,n=r.tablesAndLayersLookup.get(i);if(!n)return new Map;const a=new Map;for(const o of n.layersAndTables)p(a,o.layerId,(()=>[])).push(o);return a}function he(e,t={}){return S(e)||j(e)?{}:I(e)?{...e.prototype.attributes,...t}:T(e)?{...e.definition?.defaultValues,...t}:{...t}}async function we(e,r,i,n,a){const o=new t({sourceLayer:r,attributes:i}),{rotation:s,size:l}=te(o);let c=await Q(o,{useSourceLayer:!0,webStyleCache:n,scale:a}),u=!1;for(const t of[l,s]){if(null==t)continue;null==i[t.field]&&(i[t.field]=await t.getDefault(c,e.view),u=!0)}switch(u&&(c=await Q(o,{useSourceLayer:!0,webStyleCache:n,scale:a})),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}be(e.tooltipOptions,l,s)}function be(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 ve(e,t){return e?.find((e=>e.layer===t))}async function Se(e,t,r,i){switch(t.type){case"3d":return je(e,t,r,i);case"2d":return Ie(e,t,r,i)}}async function je(e,t,i,n){if(0===e.length)return[];const{updatable:a,graphicsByLayer:o}=await i.async((async()=>{const{results:r}=await d(X(t,i),n),a=new Map,o=e=>{const t=e.layer,r=a.get(t);if(!r){const e=new Array;return a.set(t,e),e}return r};Y(r).forEach((({graphic:e})=>o(e).push(e)));const s=e.filter((({capabilities:e,layer:t})=>e.update.enabled&&a.has(t)));return 0!==s.length&&i.stopPropagation(),{updatable:s,graphicsByLayer:a}}));return d(Promise.allSettled(a.map((async({layer:e})=>{const t=o.get(e),i=Te(e);if(t.every((e=>z(i,e))))return t;const a=[];for(const n of t){a.push(n.getObjectId());const e=Object.keys(n.attributes);r(i,e)}const s=e.createQuery();return s.returnGeometry=!1,s.objectIds=a,s.outFields=x(e.fieldsIndex,i),e.queryFeatures(s,{signal:n}).then((({features:e})=>e))}))),n)}async function Ie(e,t,r,i){if(0===e.length)return[];const{mapPoint:n}=r;if(null==n)return[];let a=null;const o=await r.async((async()=>{const{results:n}=await d(t.hitTest(r),i);if(0===n.length)return[];const o=new Set;a=Y(n),a.forEach((({graphic:e})=>e&&o.add(e.layer)));const s=e.filter((e=>o.has(e.layer)&&e.supportsUpdateWorkflow));return s.length>0&&r.stopPropagation(),s}));return d(Promise.allSettled(o.map((async({layer:e})=>{const o=e.createQuery();o.returnGeometry=!1,o.outFields=Te(e);const s="renderer"in e?P({renderer:e.renderer,pointerType:r.pointerType}):0;o.geometry=K(n,s,t),o.outSpatialReference=t.spatialReference;const{features:l}=await e.queryFeatures(o,{signal:i});return a?.forEach((({graphic:t})=>{t.layer!==e||l.some((e=>e.getObjectId()===t.getObjectId()))||l.push(t)})),l}))),i)}function Te(e){return x(e.fieldsIndex,[e.objectIdField,A({displayField:"displayField"in e?e.displayField:null,fields:e.fields})])}async function Ue(e,t,r){const{sourceLayer:i}=e,n=i.createQuery();n.objectIds=[e.getAttribute(i.objectIdField)],n.outFields=["*"],n.returnM=i.capabilities.data.supportsM,n.returnZ=i.capabilities.data.supportsZ,"scene"===i.type&&null!=i.infoFor3D||(n.outSpatialReference=t);const a=await i.queryFeatures(n,{signal:r});y(r);return a.features[0]}async function Ve(e){const{graphic:t,sketchViewModel:r,sourceLayer:i,visualVariables:n}=e;await Le(e);const a={multipleSelectionEnabled:!1};return"point"===i.geometryType&&(a.enableRotation=null!=n.rotation,a.enableScaling=null!=n.size),r.update(t,a)}async function Le(e){const{graphic:t,sketchViewModel:r,sourceLayer:i,visualVariables:n,webStyleCache:a}=e;let o=!1;const{rotation:s,size:l}=n;if([s,l].forEach((async e=>{if(null==e)return;const i=t.getAttribute(e.field);if(null!=i)e.setInitialValue(i);else{const i=await e.getDefault(t.symbol,r.view);e.setInitialValue(i),t.setAttribute(e.field,i),o=!0}})),o){const e="2d"===r.view?.type?r.view.scale:null;await le(t,a,e)}be(r.tooltipOptions,l,s),r.layer.elevationInfo=i.elevationInfo}function ke(e){return null==e||"rotate-start"!==e.type&&"rotate"!==e.type&&"rotate-stop"!==e.type?null:e}function Oe(e){return null==e||"scale-start"!==e.type&&"scale"!==e.type&&"scale-stop"!==e.type?null:e}async function Fe(e,t,r,i,n){if(null==t.geometry||"point"!==t.geometry?.type)return;const a=i.rotation,o=ke(r.toolEventInfo);if(null!=a&&null!=o){const{field:r,getValue:i}=a;"rotate-stop"===o.type?(a.isUpdatingInteractively=!1,a.setInitialValue(t.getAttribute(r))):(a.isUpdatingInteractively=!0,t.setAttribute(r,i(o.angle,e)))}const s=i.size,l=Oe(r.toolEventInfo);if(null!=s&&null!=l){const{field:r,getValue:i}=s;"scale-stop"===l.type?(s.isUpdatingInteractively=!1,s.setInitialValue(t.getAttribute(r))):(s.isUpdatingInteractively=!0,t.setAttribute(r,i(l.xScale,e)))}await le(t,n,"2d"===e.type?e.scale:null)}async function ze({feature:e,featureClone:t,visualVariableAttributes:r,sketchViewModel:i,view:n,onUpdate:a,webStyleCache:c,addUpdatingPromise:u,addHandle:p}){await le(t,c,"2d"===n.type?n.scale:null);let d=null;if("2d"===i?.view?.type){const e=f((e=>le(t,c,e)));d=g((()=>i?.view?.scale),(t=>e(t)))}const y=t.sourceLayer,m=Ze(n,y);await Ve({graphic:t,sketchViewModel:i,sourceLayer:y,visualVariables:r,webStyleCache:c});let h=null;m.then((e=>h=e)).catch((()=>{}));const b=r.size,v=r.rotation,S=g((()=>e.attributes),(async e=>{let r=!1;for(const i in e){const n=e[i];n!==t.getAttribute(i)&&(t.setAttribute(i,n),null==b||b.isUpdatingInteractively||b.field!==i||b.setInitialValue(n),null==v||v.isUpdatingInteractively||v.field!==i||v.setInitialValue(n),(null==h||h.requiredFields.includes(i))&&(r=!0))}r&&await le(t,c,"2d"===n.type?n.scale:null)})),j=i.on("update",(async e=>{const t=e.graphics[0],o={graphic:t,sketchViewModel:i,sourceLayer:y,visualVariables:r,webStyleCache:c};if("complete"===e.state){if(null===n.activeTool)return Ve(o);const e=new AbortController,t=l(e);return p(t),u(w((()=>null===n.activeTool),e.signal).then((()=>(e.abort(),Ve(o)))))}await Fe(n,t,e,r,c),a(Be(t),e)})),I=i.on(["undo","redo"],(async e=>{a(Be(e.graphics[0]),e)}));return o([I,j,s((()=>i.cancel())),S,d])}async function xe(e,t,r){const i=e.view;e.layer.add(r);const a=t.sourceLayer,l=t.layer,c=t.getAttribute(l.objectIdField);let u=null;function p(e){u?.abort(),u=n((async t=>{const r=await Ze(i,a);y(t),r.setVisibility?.(c,e)}))}return await Me(i,r),p(!1),o([Ae(i,r,(e=>p(!e))),s((async()=>{p(!0);try{const e=await Ze(i,a);await w((()=>!e.updating))}finally{e.layer.remove(r)}}))])}function Ae(e,t,r){if("3d"===e.type){const i=new W({graphic:t});return o([e.trackGraphicState(i),g((()=>i.displaying),r)])}return g((()=>t.visible),r)}async function Me(e,t){if("3d"===e.type){const r=new W({graphic:t}),i=e.trackGraphicState(r);await w((()=>r.displaying||r.error)),i.remove()}else await w((()=>t.visible))}const Pe={icon:b(24),text:b(12),line:b(1),viewScaleSizeFactor:100};function Ce(e,t,r){let i=!1;return e.filter((e=>!!i||(i=e===t,i))).map((e=>r[e]()))}function Ee(e,t){e.viewModel.syncFeatureTemplates();const r=e.creationInfo;if("awaiting-feature-creation-info"===t[0].id&&r){const e=r.layer,i=U(e);1===i.length&&"scene"!==e.type&&(r.template=i[0],t.shift())}return t}function Re(e){return"unknown"===e?null:e}function Ge(e){e.filesEnabled=!0,e.mode="view",e.capabilities={editing:!0,operations:{add:!0,update:!0,delete:!0}}}const De=e=>/-stop/.test(e)||/vertex-/.test(e),Ze=(e,t)=>{const r="subtype-sublayer"===t.type?t.parent:t;return e.whenLayerView(r)};function qe(e){return"createInteractiveEditSession"in e}function Be(e){const t=e.geometry;if("mesh"===t?.type){const r=e.cloneShallow();return r.attributes=c(e.attributes),r.geometry=t.cloneShallow(),r.geometry.transform=t.transform?.clone()??null,r}return e.clone()}function Ne(e){const t=e.cursor;return e.cursor="progress",s((()=>e.cursor=t))}async function Qe(e,t){const{template:r}=e;if(null==r)return null;if(V(r))return r.load();if(L(r)){const e=O(t,{makeSharedTemplateFromJSON:Je}),i=await e.getTemplates({templateIds:[r.templateId],featureService:r.featureService});if(0===i.length)throw new a("editor:failed-to-load-template","Unable to load the provided template");return i[0].load()}return r}const Je=e=>k.fromJSON(e);export{Ee as avoidFeatureTemplateSelectionWithOnlyOneItem,qe as canCreateInteractiveEditSession,Be as cloneGraphicExceptMesh,Ce as createWorkflowSteps,Se as fetchCandidates,Ue as fetchFullFeature,ve as findLayerInfo,he as getCreationAttributes,Qe as getFullTemplateForCreationInfo,ge as getServiceLayersById,te as getVisualVariableAttributes,De as isTerminalUpdateEventType,ee as isUpdateWorkflow,Ge as prepareAttachmentsForCreateFeaturesWorkflow,ze as setUpGeometryUpdate,pe as setUpSketchCreateWatchers,Le as setVisualVariablesAndElevationInfoForUpdate,Ne as showProgressCursor,Pe as sizeDefaults,Re as sizeVariableUnitToLengthUnit,ue as startCreatingNewFeature,Ve as startUpdatingFeatureGeometry,xe as swapForEditingSession,le as updateGraphicSymbolWhenRequired,Fe as visualVariableInteractiveUpdate,Ze as whenEditorLayerView,Me as whenGraphicDisplayed};
5
+ import e from"../../Color.js";import t from"../../Graphic.js";import{addMany as r,equals as i}from"../../core/arrayUtils.js";import{createTask as n}from"../../core/asyncUtils.js";import"../../core/has.js";import a from"../../core/Error.js";import{handlesGroup as o,makeHandle as s,abortHandle as l}from"../../core/handleUtils.js";import{clone as c}from"../../core/lang.js";import u from"../../core/Logger.js";import{getOrCreateMapValue as p}from"../../core/MapUtils.js";import{whenOrAbort as d,throwIfAborted as y,debounce as f,isPromiseLike as m}from"../../core/promiseUtils.js";import{watch as g,on as h,whenOnce as w}from"../../core/reactiveUtils.js";import{px2pt as b}from"../../core/screenUtils.js";import{diff as v}from"../../core/accessorSupport/diffUtils.js";import{isSharedGroupTemplate as S,isSharedPresetTemplate as j,isStandardFeatureTemplate as I,isSharedFeatureTemplate as T,getAllStandardFeatureTemplatesForLayer as U,isSharedTemplate as V,isSharedTemplateOrMetadata as L}from"../../editing/templateUtils.js";import k from"../../editing/sharedTemplates/SharedTemplate.js";import{getSharedTemplateProvider as F}from"../../editing/sharedTemplates/SharedTemplateProvider.js";import O from"../../layers/GraphicsLayer.js";import{featureHasFields as A,fixFields as z,getDisplayFieldName as x}from"../../layers/support/fieldUtils.js";import{isSubtypeSublayer as M}from"../../layers/support/layerUtils.js";import{calculateTolerance as P}from"../../renderers/support/clickToleranceUtils.js";import{meterIn as C}from"../../renderers/support/lengthUtils.js";import{getTransformationType as E,TransformationType as R}from"../../renderers/visualVariables/support/sizeVariableUtils.js";import{getRotationAngle as G,getSize as D}from"../../renderers/visualVariables/support/visualVariableUtils.js";import Z from"../../symbols/SimpleFillSymbol.js";import q from"../../symbols/SimpleLineSymbol.js";import B from"../../symbols/SimpleMarkerSymbol.js";import{to3D as N}from"../../symbols/support/symbolConversion.js";import{getDisplayedSymbol as Q}from"../../symbols/support/symbolUtils.js";import{getServices as J}from"../../undoredo/support/Services.js";import{GraphicState as W}from"../../views/3d/layers/graphics/GraphicState.js";import{defaultDrawingMode as H}from"../../views/draw/DrawingMode.js";import{createQueryGeometry as K}from"../../views/support/drapedUtils.js";import{hitTestSelectSimilarDistance as X,filterGraphicHits as Y}from"../../views/support/hitTestSelectUtils.js";import{isDrawGraphicTool as $}from"../Sketch/support/sketchUtils.js";const _=()=>u.getLogger("esri.widgets.Editor.workflowUtils");function ee(e){return"update"===e.type}function te(e){const t=e.sourceLayer;if(!t||"feature"!==t.type||!se(t.renderer))return{rotation:null,size:null};let r=null,i=null;const n=t.renderer.getVisualVariablesForType("rotation").filter((t=>(!t.axis||"heading"===t.axis)&&t.field&&!t.valueExpression&&null!=G(t,e)));1===n.length&&(r=re(n[0],t));const a=t.renderer.getVisualVariablesForType("size").filter((t=>t.field&&!t.useSymbolValue&&!t.valueExpression&&E(t)===R.RealWorldSize&&null!=D(t,e)));return 1===a.length&&(i=ae(a[0],t)),{rotation:r,size:i}}function re(e,t){const r="heading"===(e.axis||"heading")&&"arithmetic"===e.rotationType?-1:1,i=e.field,n=t.fields&&t.fields.filter((e=>e.name===i)),a=n&&1===n.length?n[0].type:"double",o={initial:0,current:0};return{field:i,fieldType:a,getDefault:()=>Promise.resolve(0),getValue:e=>(o.current=o.initial-r*e,oe((o.current+360)%360,a)),setInitialValue:e=>{o.initial=e,o.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 ne(e,t,r){if(null==t)return 0;const{symbol:i}=N(t);if(null==i||"web-style"===i.type||"cim"===i.type)return 0;const n=i.symbolLayers.at(0);if(!n)return 0;switch(n.type){case"icon":{const{computeIconLayerResourceSize:e}=await import("../../symbols/support/symbolLayerUtils.js");return n.size||Math.min(Pe.icon,(await e(n,Pe.icon))[0])||Pe.icon}case"text":return n.size||Pe.text;case"line":return n.size||Pe.line;case"object":{const{computeObjectLayerResourceSize:t}=await import("../../symbols/support/symbolLayerUtils.js");return ie(await t(n,e.scale/Pe.viewScaleSizeFactor),r)}case"path":return(null!=n.width?n.width:n.height)||e.scale/Pe.viewScaleSizeFactor;case"extrude":return n.size||e.scale/Pe.viewScaleSizeFactor;default:return 0}}function ae(e,t){const r=e.field,i=e.axis,n=t.fields&&t.fields.filter((e=>e.name===r)),a=n&&1===n.length?n[0].type:"double",o={initial:0,current:0},s=C[e.valueUnit]??1;let l;return l="area"===e.valueRepresentation?e=>(e*s/2)**2*Math.PI:"radius"===e.valueRepresentation||"distance"===e.valueRepresentation?e=>e*s/2:e=>e*s,{field:r,fieldType:a,getDefault:async(e,t)=>oe(l(await ne(t,e,i)),a),getValue:(e,t)=>(o.initial||(o.initial=t.pixelSizeAt(t.center)),o.current=o.initial*e,oe(o.current,a)),setInitialValue:e=>{o.initial=e,o.current=0},isUpdatingInteractively:!1,displayUnit:Re(e.valueUnit),axis:e.axis}}function oe(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 se(e){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 le(e,t,r){const i=await Q(e,{useSourceLayer:!0,ignoreGraphicSymbol:!0,webStyleCache:t,scale:r});null!=v(e.symbol,i)&&(e.symbol=i)}function ce(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 i={mode:H,optionsPerTool:r};if(L(t)){const n=t.defaultTool,a=S(t)?t.definition?.inputGeometryType??e:e;switch(n){case"freehand":case"stream-line":return{tool:"polyline"===a?"freehandPolyline":"freehandPolygon",createOptions:i};case"autocomplete-freehand-polygons":case"stream-polygon":return{tool:"freehandPolygon",createOptions:i};case"autocomplete-polygons":case"difference-polygon":case"create-structures":case"polygon":case"trace":return{tool:"polygon"===a?"polygon":"polyline",createOptions:i};case"circle":return r.get("circle").preserveAspectRatio=!0,{tool:"circle",createOptions:i};case"ellipse":return r.get("circle").preserveAspectRatio=!1,{tool:"circle",createOptions:i};case"create-points-along-line":case"multipoint":return{tool:"multipoint",createOptions:i};case"line":case"radial-line":case"right-angle-line":case"split":case"two-point-line":return{tool:"polyline",createOptions:i};case"rectangle":case"regular-polygon":case"right-angle-polygon":return{tool:"rectangle",createOptions:i};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:i}}}else{const n=t.drawingTool;if("circle"===n||"ellipse"===n)return r.get("circle").preserveAspectRatio="circle"===n,{tool:"circle",createOptions:i};if("rectangle"===n)return{tool:"rectangle",createOptions:i};if("freehand"===n)return{tool:"polygon"===e?"freehandPolygon":"freehandPolyline",createOptions:i}}return{tool:e,createOptions:i}}async function ue(e,t,r){const{creationInfo:i,fullTemplate:n}=t;if(!i)throw new a("No creation info provided.");const o=i.layer,s=he(n,i.attributeOverrides),{view:l}=e,c="2d"===l?.type;S(n)||j(n)||await we(e,o,s,r,c?l.scale:null);const{capabilities:u}=o;e.layer.elevationInfo=o.elevationInfo;const p=ce(o.geometryType,n);return 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==i.geometryToPlace?await e.create(p.tool):await e.place(i.geometryToPlace,{graphicProperties:{attributes:s,sourceLayer:o}}),pe({creationAttributes:s,data:t,sketchViewModel:e,view:l,webStyleCache:r})}async function pe(e){return o([await de(e),await ye(e)])}async function de({creationAttributes:e,data:t,sketchViewModel:r,view:i,webStyleCache:n}){const{creationInfo:a}=t,{fullTemplate:o}=t;if(!a||"2d"!==i?.type||S(o)||j(o))return null;const s=f((t=>we(r,a.layer,e,n,t)));return g((()=>i.scale),(e=>s(e)))}async function ye({data:t,sketchViewModel:r,view:i}){const{templateExecutorInfo:n}=t;if(!n)return null;const l=r.activeComponent;if(!i||!$(l))return _().error(new a("Failed to set up template feedback.")),null;const c=new O({effect:"saturate(0.6) opacity(0.8)",listMode:"hide",title:"Shared Template Feedback Graphics"});i.map?.add(c);const{executor:u,serviceLayersById:p}=n,d=i.theme?.accentColor??new e([255,165,0,1]);return o([h((()=>l),["cursor-update","vertex-add"],(()=>{c.removeAll();const e=l.graphic?.geometry;if(!e||!fe(e))return;const t=u(e,"digitizing");if(!m(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=me(e,d);t&&c.add(t)}}})),s((()=>{i.map.remove(c),c.destroy()}))])}function fe(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 i(t.at(0),t.at(-1))?t.length>2:t.length>1}default:return!1}}function me(e,r){let i=null;switch(e.geometry?.type){case"point":case"multipoint":i=new B({angle:0,color:r,outline:new q({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":i=new Z({color:r,outline:new q({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:3}),style:"none"});break;case"polyline":i=new q({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:2});break;default:return null}return new t({geometry:e.geometry,symbol:i,attributes:{...e.attributes}})}async function ge(e,t){const r=await J(t).load(),i=M(e)?e.parent:e,n=r.tablesAndLayersLookup.get(i);if(!n)return new Map;const a=new Map;for(const o of n.layersAndTables)p(a,o.layerId,(()=>[])).push(o);return a}function he(e,t={}){return S(e)||j(e)?{}:I(e)?{...e.prototype.attributes,...t}:T(e)?{...e.definition?.defaultValues,...t}:{...t}}async function we(e,r,i,n,a){const o=new t({sourceLayer:r,attributes:i}),{rotation:s,size:l}=te(o);let c=await Q(o,{useSourceLayer:!0,webStyleCache:n,scale:a}),u=!1;for(const t of[l,s]){if(null==t)continue;null==i[t.field]&&(i[t.field]=await t.getDefault(c,e.view),u=!0)}switch(u&&(c=await Q(o,{useSourceLayer:!0,webStyleCache:n,scale:a})),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}be(e.tooltipOptions,l,s)}function be(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 ve(e,t){return e?.find((e=>e.layer===t))}async function Se(e,t,r,i){switch(t.type){case"3d":return je(e,t,r,i);case"2d":return Ie(e,t,r,i)}}async function je(e,t,i,n){if(0===e.length)return[];const{updatable:a,graphicsByLayer:o}=await i.async((async()=>{const{results:r}=await d(X(t,i),n),a=new Map,o=e=>{const t=e.layer,r=a.get(t);if(!r){const e=new Array;return a.set(t,e),e}return r};Y(r).forEach((({graphic:e})=>o(e).push(e)));const s=e.filter((({capabilities:e,layer:t})=>e.update.enabled&&a.has(t)));return 0!==s.length&&i.stopPropagation(),{updatable:s,graphicsByLayer:a}}));return d(Promise.allSettled(a.map((async({layer:e})=>{const t=o.get(e),i=Te(e);if(t.every((e=>A(i,e))))return t;const a=[];for(const n of t){a.push(n.getObjectId());const e=Object.keys(n.attributes);r(i,e)}const s=e.createQuery();return s.returnGeometry=!1,s.objectIds=a,s.outFields=z(e.fieldsIndex,i),e.queryFeatures(s,{signal:n}).then((({features:e})=>e))}))),n)}async function Ie(e,t,r,i){if(0===e.length)return[];const{mapPoint:n}=r;if(null==n)return[];let a=null;const o=await r.async((async()=>{const{results:n}=await d(t.hitTest(r),i);if(0===n.length)return[];const o=new Set;a=Y(n),a.forEach((({graphic:e})=>e&&o.add(e.layer)));const s=e.filter((e=>o.has(e.layer)&&e.supportsUpdateWorkflow));return s.length>0&&r.stopPropagation(),s}));return d(Promise.allSettled(o.map((async({layer:e})=>{const o=e.createQuery();o.returnGeometry=!1,o.outFields=Te(e);const s="renderer"in e?P({renderer:e.renderer,pointerType:r.pointerType}):0;o.geometry=K(n,s,t),o.outSpatialReference=t.spatialReference;const{features:l}=await e.queryFeatures(o,{signal:i});return a?.forEach((({graphic:t})=>{t.layer!==e||l.some((e=>e.getObjectId()===t.getObjectId()))||l.push(t)})),l}))),i)}function Te(e){return z(e.fieldsIndex,[e.objectIdField,x({displayField:"displayField"in e?e.displayField:null,fields:e.fields})])}async function Ue(e,t,r){const{sourceLayer:i}=e,n=i.createQuery();n.objectIds=[e.getAttribute(i.objectIdField)],n.outFields=["*"],n.returnM=i.capabilities.data.supportsM,n.returnZ=i.capabilities.data.supportsZ,"scene"===i.type&&null!=i.infoFor3D||(n.outSpatialReference=t);const a=await i.queryFeatures(n,{signal:r});y(r);return a.features[0]}async function Ve(e){const{graphic:t,sketchViewModel:r,sourceLayer:i,visualVariables:n}=e;await Le(e);const a={multipleSelectionEnabled:!1};return"point"===i.geometryType&&(a.enableRotation=null!=n.rotation,a.enableScaling=null!=n.size),r.update(t,a)}async function Le(e){const{graphic:t,sketchViewModel:r,sourceLayer:i,visualVariables:n,webStyleCache:a}=e;let o=!1;const{rotation:s,size:l}=n;if([s,l].forEach((async e=>{if(null==e)return;const i=t.getAttribute(e.field);if(null!=i)e.setInitialValue(i);else{const i=await e.getDefault(t.symbol,r.view);e.setInitialValue(i),t.setAttribute(e.field,i),o=!0}})),o){const e="2d"===r.view?.type?r.view.scale:null;await le(t,a,e)}be(r.tooltipOptions,l,s),r.layer.elevationInfo=i.elevationInfo}function ke(e){return null==e||"rotate-start"!==e.type&&"rotate"!==e.type&&"rotate-stop"!==e.type?null:e}function Fe(e){return null==e||"scale-start"!==e.type&&"scale"!==e.type&&"scale-stop"!==e.type?null:e}async function Oe(e,t,r,i,n){if(null==t.geometry||"point"!==t.geometry?.type)return;const a=i.rotation,o=ke(r.toolEventInfo);if(null!=a&&null!=o){const{field:r,getValue:i}=a;"rotate-stop"===o.type?(a.isUpdatingInteractively=!1,a.setInitialValue(t.getAttribute(r))):(a.isUpdatingInteractively=!0,t.setAttribute(r,i(o.angle,e)))}const s=i.size,l=Fe(r.toolEventInfo);if(null!=s&&null!=l){const{field:r,getValue:i}=s;"scale-stop"===l.type?(s.isUpdatingInteractively=!1,s.setInitialValue(t.getAttribute(r))):(s.isUpdatingInteractively=!0,t.setAttribute(r,i(l.xScale,e)))}await le(t,n,"2d"===e.type?e.scale:null)}async function Ae({feature:e,featureClone:t,visualVariableAttributes:r,sketchViewModel:i,view:n,onUpdate:a,webStyleCache:c,addUpdatingPromise:u,addHandle:p}){await le(t,c,"2d"===n.type?n.scale:null);let d=null;if("2d"===i?.view?.type){const e=f((e=>le(t,c,e)));d=g((()=>i?.view?.scale),(t=>e(t)))}const y=t.sourceLayer,m=Ze(n,y);await Ve({graphic:t,sketchViewModel:i,sourceLayer:y,visualVariables:r,webStyleCache:c});let h=null;m.then((e=>h=e)).catch((()=>{}));const b=r.size,v=r.rotation,S=g((()=>e.attributes),(async e=>{let r=!1;for(const i in e){const n=e[i];n!==t.getAttribute(i)&&(t.setAttribute(i,n),null==b||b.isUpdatingInteractively||b.field!==i||b.setInitialValue(n),null==v||v.isUpdatingInteractively||v.field!==i||v.setInitialValue(n),(null==h||h.requiredFields.includes(i))&&(r=!0))}r&&await le(t,c,"2d"===n.type?n.scale:null)})),j=i.on("update",(async e=>{const t=e.graphics[0],o={graphic:t,sketchViewModel:i,sourceLayer:y,visualVariables:r,webStyleCache:c};if("complete"===e.state){if(null===n.activeTool)return Ve(o);const e=new AbortController,t=l(e);return p(t),u(w((()=>null===n.activeTool),e.signal).then((()=>(e.abort(),Ve(o)))))}await Oe(n,t,e,r,c),a(Be(t),e)})),I=i.on(["undo","redo"],(async e=>{a(Be(e.graphics[0]),e)}));return o([I,j,s((()=>i.cancel())),S,d])}async function ze(e,t,r){const i=e.view;e.layer.add(r);const a=t.sourceLayer,l=t.layer,c=t.getAttribute(l.objectIdField);let u=null;function p(e){u?.abort(),u=n((async t=>{const r=await Ze(i,a);y(t),r.setVisibility?.(c,e)}))}return await Me(i,r),p(!1),o([xe(i,r,(e=>p(!e))),s((async()=>{p(!0);try{const e=await Ze(i,a);await w((()=>!e.updating))}finally{e.layer.remove(r)}}))])}function xe(e,t,r){if("3d"===e.type){const i=new W({graphic:t});return o([e.trackGraphicState(i),g((()=>i.displaying),r)])}return g((()=>t.visible),r)}async function Me(e,t){if("3d"===e.type){const r=new W({graphic:t}),i=e.trackGraphicState(r);await w((()=>r.displaying||r.error)),i.remove()}else await w((()=>t.visible))}const Pe={icon:b(24),text:b(12),line:b(1),viewScaleSizeFactor:100};function Ce(e,t,r){let i=!1;return e.filter((e=>!!i||(i=e===t,i))).map((e=>r[e]()))}function Ee(e,t){e.viewModel.syncFeatureTemplates();const r=e.creationInfo;if("awaiting-feature-creation-info"===t[0].id&&r){const e=r.layer,i=U(e);1===i.length&&"scene"!==e.type&&(r.template=i[0],t.shift())}return t}function Re(e){return"unknown"===e?null:e}function Ge(e){e.filesEnabled=!0,e.mode="view",e.capabilities={editing:!0,operations:{add:!0,update:!0,delete:!0}}}const De=e=>/-stop/.test(e)||/vertex-/.test(e),Ze=(e,t)=>{const r="subtype-sublayer"===t.type?t.parent:t;return e.whenLayerView(r)};function qe(e){return"createInteractiveEditSession"in e}function Be(e){const t=e.geometry;if("mesh"===t?.type){const r=e.cloneShallow();return r.attributes=c(e.attributes),r.geometry=t.cloneShallow(),r.geometry.transform=t.transform?.clone()??null,r}return e.clone()}function Ne(e){const t=e.cursor;return e.cursor="progress",s((()=>e.cursor=t))}async function Qe(e,t){const{template:r}=e;if(null==r)return null;if(V(r))return r.load();if(L(r)){const e=F(t,{makeSharedTemplateFromJSON:We}),i=await e.getTemplates({templateIds:[r.templateId],featureService:r.featureService});if(0===i.length)throw new a("editor:failed-to-load-template","Unable to load the provided template");return i[0].load()}return r}function Je(e){for(const t of e){const{destinationGraphic:e,destinationField:r,sourceGraphic:i,sourceField:n}=t;e.setAttribute(r,i.getAttribute(n))}}const We=e=>k.fromJSON(e);export{Ee as avoidFeatureTemplateSelectionWithOnlyOneItem,qe as canCreateInteractiveEditSession,Be as cloneGraphicExceptMesh,Ce as createWorkflowSteps,Se as fetchCandidates,Ue as fetchFullFeature,ve as findLayerInfo,he as getCreationAttributes,Qe as getFullTemplateForCreationInfo,ge as getServiceLayersById,te as getVisualVariableAttributes,De as isTerminalUpdateEventType,ee as isUpdateWorkflow,Ge as prepareAttachmentsForCreateFeaturesWorkflow,Je as setRelationshipFields,Ae as setUpGeometryUpdate,pe as setUpSketchCreateWatchers,Le as setVisualVariablesAndElevationInfoForUpdate,Ne as showProgressCursor,Pe as sizeDefaults,Re as sizeVariableUnitToLengthUnit,ue as startCreatingNewFeature,Ve as startUpdatingFeatureGeometry,ze as swapForEditingSession,le as updateGraphicSymbolWhenRequired,Oe as visualVariableInteractiveUpdate,Ze as whenEditorLayerView,Me as whenGraphicDisplayed};