@arcgis/core 5.2.0 → 5.2.1

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.
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import{EventEmitter as t}from"../../../../core/Evented.js";import{handlesGroup as n}from"../../../../core/handleUtils.js";import{destroyMaybe as r}from"../../../../core/maybe.js";import i from"../../../../core/ReactiveMap.js";import{initial as a,watch as o,syncAndInitial as s}from"../../../../core/reactiveUtils.js";import{property as c,subclass as l}from"../../../../core/accessorSupport/decorators.js";import{UpdatingHandles as u}from"../../../../core/support/UpdatingHandles.js";import{create as d,fromPoints as f}from"../../../../geometry/support/lineSegment.js";import{LineOfSightInteractionVisuals as p}from"./LineOfSightInteractionVisuals.js";import{LineOfSightObserverManipulator as m,LineOfSightTargetManipulator as h,LineOfSightTargetManipulatorState as g,getInteractiveLineOfSightTargetManipulatorState as _}from"./LineOfSightManipulators.js";import{SnappingVisualizer3D as v}from"../../interactive/SnappingVisualizer3D.js";import{screenToMapAtSceneSurface as y}from"../../interactive/editingTools/dragEventPipeline3D.js";import{mouseButtons as b}from"../../../input/mouseButtons.js";import{createManipulatorDragEventPipeline as x,dragAtLocation as S,sceneSnappingAtLocation as C,dragManipulatedObject as w}from"../../../interactive/dragEventPipeline.js";import{InteractiveToolBase as T}from"../../../interactive/InteractiveToolBase.js";import{SnappingContext as E}from"../../../interactive/snapping/SnappingContext.js";import{createSnapDragEventPipelineStep as D}from"../../../interactive/snapping/SnappingDragPipelineStep.js";import{enterInputModeIfAvailable as O}from"../../../interactive/tooltip/tooltipCommonUtils.js";const k=d(),A=Symbol(`inactiveManipulatorDisplay`);let j=class extends T{get _manipulatorsToHide(){let e=this._manipulatorByObject.values();return this.view.tools.some(e=>e.hasGrabbedManipulators)||e.some(e=>e.grabbing)?e.filter(e=>!e.grabbing).toArray():[]}constructor(e){super(e),this.events=new t,this.automaticManipulatorSelection=!1,this.removeIncompleteOnCancel=!1,this.interacting=!1,this.manipulatorsInteractive=!0,this._objectByItem=new Map,this._manipulatorByObject=new i,this._updatingHandles=new u,this._interactionVisuals=null,this._grabbedManipulator=null,this._visualsManipulator=null}initialize(){let{view:e}=this;this._interactionVisuals=new p({view:e}),this.addHandles([this._updatingHandles.add(()=>({analysisVisible:this.analysisViewData.visible,computations:this.analysisViewData.computations.toArray().map(e=>({isTargetVisible:e.computationResult.isTargetVisible,isValid:e.computationResult.isValid,target:e.target})),grabbedManipulator:this._grabbedManipulator,interacting:this.interacting,manipulatorsInteractive:this.manipulatorsInteractive,visible:this.visible}),()=>this._syncManipulators(),a),o(()=>this._manipulatorsToHide,e=>{let t=e.map(e=>e.disableDisplay());this.removeHandles(A),this.addHandles(t,A)},s)]),this.finishToolCreation()}destroy(){this.removeHandles(A),this._interactionVisuals=r(this._interactionVisuals),this._updatingHandles.destroy(),this._objectByItem.clear(),this._manipulatorByObject.clear(),super.destroy()}get updating(){return this._updatingHandles.updating||this.snappingManager.updating}get laserLineVisualElement(){return this._interactionVisuals?.laserLineVisualElement??null}get verticalLineVisualElement(){return this._interactionVisuals?.verticalLineVisualElement??null}showInteractionVisuals(e){this._visualsManipulator=this._manipulatorByObject.get(e),this._syncInteractionVisuals()}hideInteractionVisuals(){this._visualsManipulator=null,this._syncInteractionVisuals()}addObject(e){if(this._manipulatorByObject.has(e))return;let t=e.item.type===`observer`?new m(this.view,{deleting:!1,intersection:null,type:`observer`}):new h(this.view,{deleting:!1,target:e.item,type:`target`});t.cursor=`move`,this._objectByItem.set(e.item,e),this._manipulatorByObject.set(e,t),this.manipulators.add(t),this.addHandles(this._connectManipulator(e,t),e),this._syncManipulator(e,t)}removeObject(e){let t=this._manipulatorByObject.get(e);t!=null&&(this._grabbedManipulator===t&&(this._grabbedManipulator=null),this._visualsManipulator===t&&this.hideInteractionVisuals(),this.removeHandles(e),this._objectByItem.delete(e.item),this._manipulatorByObject.delete(e),this.manipulators.remove(t),t.destroy())}getManipulator(e){let t=this._objectByItem.get(e);return t==null?null:this._manipulatorByObject.get(t)}hasManipulatorAt(e,t){for(let n of this._manipulatorByObject.values())if(n.consumesClicks&&n.intersectionDistance(e,t)!=null)return!0;return!1}selectObject(e){let t=!1;for(let[n,r]of this._manipulatorByObject){let i=n===e;r.selected=i,t||=i}return this._syncManipulators(),t}onInputEvent(e){e.type===`hold`&&this._grabbedManipulator!=null&&(this._visualsManipulator=this._grabbedManipulator,this._syncInteractionVisuals()),O(e,this.tooltip)}onManipulatorSelectionChanged(){[...this._manipulatorByObject.values()].some(e=>e.selected)||this.events.emit(`selection-cleared`)}_connectManipulator(e,t){let r=()=>this._syncManipulator(e,t);return n([e.on(`committed`,r),e.on(`modified-externally`,r),t.events.on(`immediate-click`,n=>{this.events.emit(`select-item`,{item:e.item}),n.button===b.Right&&t.metadata.type===`target`&&this.events.emit(`delete-item`,{target:t.metadata.target}),n.stopPropagation()}),t.events.on(`grab-changed`,({action:n})=>{n===`start`?(this.events.emit(`select-item`,{item:e.item}),this._grabbedManipulator=t):this._grabbedManipulator===t&&(this._grabbedManipulator=null,this.hideInteractionVisuals()),this._manipulatorByObject.set(e,t)}),t.events.on(`drag`,t=>{e.updateDragIntersection(t),t.action===`start`&&this.showInteractionVisuals(e)}),t.events.on(`location-update`,()=>this._syncInteractionVisuals()),this._createDragHandle(e,t)])}_createDragHandle(e,t){return x(t,(n,r,i,a)=>{let o=e.operations;if(o==null)return;let s=null,{cancelSnapping:c,snappingStep:l}=D({snappingContext:new E({editGeometryOperations:o,elevationInfo:e.elevationInfo,pointer:a,visualizer:new v}),snappingManager:this.snappingManager,updatingHandles:this._updatingHandles,useZ:!0});i.next(e=>(s?.undo(null),s=null,e)).next(c);let u=o.data.allVerticesUnordered.at(0);r.next(t=>(t.action===`start`&&(s=e.createUndoRecord()),{...t,snapOrigin:u?.pos})).next(S(this.view,t.elevationAlignedLocation)).next(y(this.view,o.data.geometry,e.elevationInfo,o.data.spatialReference)).next(C(this.view,e.elevationInfo)).next(...l).next(w(e)).next(e=>(e.action===`end`&&s!=null&&(this.events.emit(`record-undo`,{record:s}),s=null),e))})}_syncManipulators(){for(let[e,t]of this._manipulatorByObject)this._syncManipulator(e,t);this._syncInteractionVisuals()}_syncManipulator(e,t){let n=e.origin;if(t.available=this.visible&&e.visible&&n!=null,t.interactive=this.manipulatorsInteractive&&(this._grabbedManipulator==null||this._grabbedManipulator===t),n!=null&&(t.elevationAlignedLocation=n),e.item.type!==`target`)return;let r=this.analysisViewData.computations.find(t=>t.target===e.item),i=r==null||!r.computationResult.isValid?g.undefined:r.computationResult.isTargetVisible?g.visible:g.occluded;t.state=this.interacting&&t.selected?_(i):i}_syncInteractionVisuals(){let e=this._interactionVisuals,t=this._visualsManipulator,n=this.visible&&this.analysisViewData.visible;if(e==null||t==null||!n){e?.hide();return}let r=[...this._manipulatorByObject.entries()].find(([e])=>e.item.type===`observer`)?.[1];if(r==null){e.hide();return}let i=t===r?null:f(r.renderLocation,t.renderLocation,k);e.update({target:t.renderLocation,lineVerticalPlaneSegment:i,visible:!0})}};e([c({constructOnly:!0})],j.prototype,`analysisViewData`,void 0),e([c({constructOnly:!0})],j.prototype,`snappingManager`,void 0),e([c({constructOnly:!0})],j.prototype,`view`,void 0),e([c({constructOnly:!0})],j.prototype,`tooltip`,void 0),e([c()],j.prototype,`automaticManipulatorSelection`,void 0),e([c()],j.prototype,`removeIncompleteOnCancel`,void 0),e([c()],j.prototype,`interacting`,void 0),e([c()],j.prototype,`manipulatorsInteractive`,void 0),e([c()],j.prototype,`_grabbedManipulator`,void 0),e([c()],j.prototype,`_manipulatorsToHide`,null),e([c()],j.prototype,`updating`,null),j=e([l(`esri.views.3d.analysis.LineOfSight.LineOfSightItemTool`)],j);export{j as LineOfSightItemTool};
2
+ import{__decorate as e}from"tslib";import{EventEmitter as t}from"../../../../core/Evented.js";import{handlesGroup as n}from"../../../../core/handleUtils.js";import{destroyMaybe as r}from"../../../../core/maybe.js";import i from"../../../../core/ReactiveMap.js";import{initial as a,watch as o,syncAndInitial as s}from"../../../../core/reactiveUtils.js";import{property as c,subclass as l}from"../../../../core/accessorSupport/decorators.js";import{UpdatingHandles as u}from"../../../../core/support/UpdatingHandles.js";import{create as d,fromPoints as f}from"../../../../geometry/support/lineSegment.js";import{LineOfSightInteractionVisuals as p}from"./LineOfSightInteractionVisuals.js";import{LineOfSightObserverManipulator as m,LineOfSightTargetManipulator as h,LineOfSightTargetManipulatorState as g,getInteractiveLineOfSightTargetManipulatorState as _}from"./LineOfSightManipulators.js";import{SnappingVisualizer3D as v}from"../../interactive/SnappingVisualizer3D.js";import{screenToMapAtSceneSurface as y}from"../../interactive/editingTools/dragEventPipeline3D.js";import{mouseButtons as b}from"../../../input/mouseButtons.js";import{createManipulatorDragEventPipeline as x,dragAtLocation as S,sceneSnappingAtLocation as C,dragManipulatedObject as w}from"../../../interactive/dragEventPipeline.js";import{InteractiveToolBase as T}from"../../../interactive/InteractiveToolBase.js";import{areToolManipulatorsEditable as E}from"../../../interactive/interactiveToolUtils.js";import{SnappingContext as D}from"../../../interactive/snapping/SnappingContext.js";import{createSnapDragEventPipelineStep as O}from"../../../interactive/snapping/SnappingDragPipelineStep.js";import{enterInputModeIfAvailable as k}from"../../../interactive/tooltip/tooltipCommonUtils.js";import{createScreenPointFromEvent as A}from"../../../support/screenUtils.js";const j=d(),M=Symbol(`inactiveManipulatorDisplay`);let N=class extends T{get _manipulatorsToHide(){let e=this._manipulatorByObject.values();return this.view.tools.some(e=>e.hasGrabbedManipulators)||e.some(e=>e.grabbing)?e.filter(e=>!e.grabbing).toArray():[]}constructor(e){super(e),this.events=new t,this.automaticManipulatorSelection=!1,this.removeIncompleteOnCancel=!1,this.interacting=!1,this.manipulatorsInteractive=!0,this._objectByItem=new Map,this._manipulatorByObject=new i,this._updatingHandles=new u,this._interactionVisuals=null,this._selectedManipulator=null,this._grabbedManipulator=null,this._visualsManipulator=null}initialize(){let{view:e}=this;this._interactionVisuals=new p({view:e}),this.addHandles([this._updatingHandles.add(()=>({analysisVisible:this.analysisViewData.visible,computations:this.analysisViewData.computations.toArray().map(e=>({isTargetVisible:e.computationResult.isTargetVisible,isValid:e.computationResult.isValid,target:e.target})),grabbedManipulator:this._grabbedManipulator,interacting:this.interacting,manipulatorsInteractive:this.manipulatorsInteractive,visible:this.visible}),()=>this._syncManipulators(),a),o(()=>this._manipulatorsToHide,e=>{let t=e.map(e=>e.disableDisplay());this.removeHandles(M),this.addHandles(t,M)},s)]),this.finishToolCreation()}destroy(){this.removeHandles(M),this._interactionVisuals=r(this._interactionVisuals),this._updatingHandles.destroy(),this._selectedManipulator=null,this._objectByItem.clear(),this._manipulatorByObject.clear(),super.destroy()}get updating(){return this._updatingHandles.updating||this.snappingManager.updating}get laserLineVisualElement(){return this._interactionVisuals?.laserLineVisualElement??null}get verticalLineVisualElement(){return this._interactionVisuals?.verticalLineVisualElement??null}showInteractionVisuals(e){this._visualsManipulator=this._manipulatorByObject.get(e),this._syncInteractionVisuals()}hideInteractionVisuals(){this._visualsManipulator=null,this._syncInteractionVisuals()}addObject(e){if(this._manipulatorByObject.has(e))return;let t=e.item.type===`observer`?new m(this.view,{deleting:!1,intersection:null,type:`observer`}):new h(this.view,{deleting:!1,target:e.item,type:`target`});t.cursor=`move`,this._objectByItem.set(e.item,e),this._manipulatorByObject.set(e,t),this.manipulators.add(t),this.addHandles(this._connectManipulator(e,t),e),this._syncManipulator(e,t)}removeObject(e){let t=this._manipulatorByObject.get(e);t!=null&&(this._grabbedManipulator===t&&(this._grabbedManipulator=null),this._selectedManipulator===t&&(this._selectedManipulator=null),this._visualsManipulator===t&&this.hideInteractionVisuals(),this.removeHandles(e),this._objectByItem.delete(e.item),this._manipulatorByObject.delete(e),this.manipulators.remove(t),t.destroy())}getManipulator(e){let t=this._objectByItem.get(e);return t==null?null:this._manipulatorByObject.get(t)}hasManipulatorAt(e,t){for(let n of this._manipulatorByObject.values())if(n.consumesClicks&&n.intersectionDistance(e,t)!=null)return!0;return!1}selectObject(e){this._selectedManipulator=e==null?null:this._manipulatorByObject.get(e);for(let e of this._manipulatorByObject.values())e.selected=e===this._selectedManipulator;return this._syncManipulators(),this._selectedManipulator!=null}onInputEvent(e){if(e.type===`immediate-click`&&!e.native.shiftKey&&this._selectedManipulator!=null){let t=A(e),n=this.view.tools.find(n=>E(n)&&n.manipulators.intersect(t,e.pointerType)!=null);n!==this&&n!==this.moveTool&&this.events.emit(`deselect-item`)}e.type===`hold`&&this._grabbedManipulator!=null&&(this._visualsManipulator=this._grabbedManipulator,this._syncInteractionVisuals()),k(e,this.tooltip)}onManipulatorSelectionChanged(){let e=this._selectedManipulator;e==null||e.selected||(this.view.activeTool==null||this.moveTool.active?(e.selected=!0,this._syncManipulators()):this.events.emit(`deselect-item`))}_connectManipulator(e,t){let r=()=>this._syncManipulator(e,t);return n([e.on(`committed`,r),e.on(`modified-externally`,r),t.events.on(`immediate-click`,n=>{this.events.emit(`select-item`,{item:e.item}),n.button===b.Right&&t.metadata.type===`target`&&this.events.emit(`delete-item`,{target:t.metadata.target}),n.stopPropagation()}),t.events.on(`grab-changed`,({action:n})=>{n===`start`?(this.events.emit(`select-item`,{item:e.item}),this._grabbedManipulator=t):this._grabbedManipulator===t&&(this._grabbedManipulator=null,this.hideInteractionVisuals()),this._manipulatorByObject.set(e,t)}),t.events.on(`drag`,t=>{e.updateDragIntersection(t),t.action===`start`&&this.showInteractionVisuals(e)}),t.events.on(`location-update`,()=>this._syncInteractionVisuals()),this._createDragHandle(e,t)])}_createDragHandle(e,t){return x(t,(n,r,i,a)=>{let o=e.operations;if(o==null)return;let s=null,{cancelSnapping:c,snappingStep:l}=O({snappingContext:new D({editGeometryOperations:o,elevationInfo:e.elevationInfo,pointer:a,visualizer:new v}),snappingManager:this.snappingManager,updatingHandles:this._updatingHandles,useZ:!0});i.next(e=>(s?.undo(null),s=null,e)).next(c);let u=o.data.allVerticesUnordered.at(0);r.next(t=>(t.action===`start`&&(s=e.createUndoRecord()),{...t,snapOrigin:u?.pos})).next(S(this.view,t.elevationAlignedLocation)).next(y(this.view,o.data.geometry,e.elevationInfo,o.data.spatialReference)).next(C(this.view,e.elevationInfo)).next(...l).next(w(e)).next(e=>(e.action===`end`&&s!=null&&(this.events.emit(`record-undo`,{record:s}),s=null),e))})}_syncManipulators(){for(let[e,t]of this._manipulatorByObject)this._syncManipulator(e,t);this._syncInteractionVisuals()}_syncManipulator(e,t){let n=e.origin;if(t.available=this.visible&&e.visible&&n!=null,t.interactive=this.manipulatorsInteractive&&(this._grabbedManipulator==null||this._grabbedManipulator===t),n!=null&&(t.elevationAlignedLocation=n),e.item.type!==`target`)return;let r=this.analysisViewData.computations.find(t=>t.target===e.item),i=r==null||!r.computationResult.isValid?g.undefined:r.computationResult.isTargetVisible?g.visible:g.occluded;t.state=this.interacting&&t.selected?_(i):i}_syncInteractionVisuals(){let e=this._interactionVisuals,t=this._visualsManipulator,n=this.visible&&this.analysisViewData.visible;if(e==null||t==null||!n){e?.hide();return}let r=[...this._manipulatorByObject.entries()].find(([e])=>e.item.type===`observer`)?.[1];if(r==null){e.hide();return}let i=t===r?null:f(r.renderLocation,t.renderLocation,j);e.update({target:t.renderLocation,lineVerticalPlaneSegment:i,visible:!0})}};e([c({constructOnly:!0})],N.prototype,`analysisViewData`,void 0),e([c({constructOnly:!0})],N.prototype,`moveTool`,void 0),e([c({constructOnly:!0})],N.prototype,`snappingManager`,void 0),e([c({constructOnly:!0})],N.prototype,`view`,void 0),e([c({constructOnly:!0})],N.prototype,`tooltip`,void 0),e([c()],N.prototype,`automaticManipulatorSelection`,void 0),e([c()],N.prototype,`removeIncompleteOnCancel`,void 0),e([c()],N.prototype,`interacting`,void 0),e([c()],N.prototype,`manipulatorsInteractive`,void 0),e([c()],N.prototype,`_grabbedManipulator`,void 0),e([c()],N.prototype,`_manipulatorsToHide`,null),e([c()],N.prototype,`updating`,null),N=e([l(`esri.views.3d.analysis.LineOfSight.LineOfSightItemTool`)],N);export{N as LineOfSightItemTool};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{watch as e}from"../../../../core/reactiveUtils.js";import{getObserverRGBA as t,observerConfiguration as n,targetConfiguration as r,getInteractiveTargetRGBA as i,lineOfSightTransparentRenderOrder as a}from"./LineOfSightConfiguration.js";import{Manipulator3D as o}from"../../interactive/Manipulator3D.js";import{createManipulatorMaterial as s}from"../../interactive/manipulatorUtils.js";import{RenderObject as c}from"../../interactive/RenderObject.js";import{createSphereGeometry as l}from"../../webgl-engine/lib/GeometryUtil.js";const u=1024;class d extends o{constructor(r,i){let a=g(t(r.effectiveTheme)),o=l(a,n.size,32,32),s=[new c(o)];super({view:r,renderObjects:s,metadata:i,elevationInfo:{mode:`absolute-height`,offset:0}}),this.themeHandle=e(()=>({color:t(r.effectiveTheme)}),e=>{a.setParameters(e)})}destroy(){this.themeHandle.remove(),super.destroy()}}class f extends o{constructor(t,n){let{size:a,visibleColor:o,occludedColor:s,undefinedColor:d}=r,f=g(i(t.effectiveTheme)),p=[new c(l(f,a,32,32),u),h(a,o,2176),h(a,s,2304),h(a,d,2560)];super({view:t,renderObjects:p,metadata:n,elevationInfo:{mode:`absolute-height`,offset:0}}),this.themeHandle=e(()=>({color:i(t.effectiveTheme)}),e=>{f.setParameters(e)})}destroy(){this.themeHandle.remove(),super.destroy()}}const p={visible:2176,occluded:2304,undefined:2560};function m(e){return e&-2049|u}function h(e,t,n){return new c(l(g(t.toUnitRGBA()),e,32,32),n)}function g(e){let t=s(e);return t.setParameters({testsTransparentRenderOrder:a.manipulator}),t}export{d as LineOfSightObserverManipulator,f as LineOfSightTargetManipulator,p as LineOfSightTargetManipulatorState,m as getInteractiveLineOfSightTargetManipulatorState};
2
+ import{watch as e}from"../../../../core/reactiveUtils.js";import{getObserverRGBA as t,observerConfiguration as n,targetConfiguration as r,getInteractiveTargetRGBA as i,lineOfSightTransparentRenderOrder as a}from"./LineOfSightConfiguration.js";import{Manipulator3D as o}from"../../interactive/Manipulator3D.js";import{createManipulatorMaterial as s}from"../../interactive/manipulatorUtils.js";import{RenderObject as c}from"../../interactive/RenderObject.js";import{createSphereGeometry as l}from"../../webgl-engine/lib/GeometryUtil.js";const u=1024;class d extends o{constructor(r,i){let a=g(t(r.effectiveTheme)),o=l(a,1,32,32),s=[new c(o)];super({view:r,renderObjects:s,metadata:i,radius:n.radius,elevationInfo:{mode:`absolute-height`,offset:0}}),this.themeHandle=e(()=>({color:t(r.effectiveTheme)}),e=>{a.setParameters(e)})}destroy(){this.themeHandle.remove(),super.destroy()}}class f extends o{constructor(t,n){let{radius:a,visibleColor:o,occludedColor:s,undefinedColor:d}=r,f=g(i(t.effectiveTheme)),p=[new c(l(f,1,32,32),u),h(o,2176),h(s,2304),h(d,2560)];super({view:t,renderObjects:p,metadata:n,radius:a,elevationInfo:{mode:`absolute-height`,offset:0}}),this.themeHandle=e(()=>({color:i(t.effectiveTheme)}),e=>{f.setParameters(e)})}destroy(){this.themeHandle.remove(),super.destroy()}}const p={visible:2176,occluded:2304,undefined:2560};function m(e){return e&-2049|u}function h(e,t){return new c(l(g(e.toUnitRGBA()),1,32,32),t)}function g(e){let t=s(e);return t.setParameters({testsTransparentRenderOrder:a.manipulator}),t}export{d as LineOfSightObserverManipulator,f as LineOfSightTargetManipulator,p as LineOfSightTargetManipulatorState,m as getInteractiveLineOfSightTargetManipulatorState};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../core/Accessor.js";import{isSome as n}from"../../../core/arrayUtils.js";import{destroyHandle as r}from"../../../core/handleUtils.js";import"../../../core/has.js";import{mapCollectionAsync as i}from"../../../core/mapCollectionUtils.js";import{allSettledValues as a,throwIfAborted as o,onAbort as s}from"../../../core/promiseUtils.js";import{watch as c,sync as l}from"../../../core/reactiveUtils.js";import{getMetersPerUnitForSR as u,getMetersPerVerticalUnitForSR as d}from"../../../core/units.js";import{property as f,subclass as p}from"../../../core/accessorSupport/decorators.js";import{squaredDistance as m}from"../../../core/libs/gl-matrix-2/math/vec2.js";import{copy as h,squaredDistance as g}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{create as _}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{getEpsilon as v}from"../../../core/libs/gl-matrix-2/math/common.js";import{UpdatingHandles as y}from"../../../core/support/UpdatingHandles.js";import{absoluteHeightElevationInfo as b}from"../../../support/elevationInfoUtils.js";import{VerticalHalfPlaneConstraint as x,isLine as S,isDrapedLine as C}from"../sketch/constraints.js";import{fromAnyMapPoint as w,asVec2 as T,markAsTarget as E}from"../sketch/normalizedPoint.js";import{FeatureSnappingSourceInfo as D}from"./FeatureSnappingSourceInfo.js";import{sortCandidatesInPlace as O}from"./snappingUtils.js";import{DrapedEdgeSnappingCandidate as k}from"./candidates/DrapedEdgeSnappingCandidate.js";import{EdgeSnappingCandidate as A}from"./candidates/EdgeSnappingCandidate.js";import{FeatureSnappingCandidate as j}from"./candidates/FeatureSnappingCandidate.js";import{RightAngleSnappingCandidate as M}from"./candidates/RightAngleSnappingCandidate.js";import{vectorToScreenPoint as N}from"../support/viewUtils.js";import{screenDistance as P}from"../../../core/screenUtils.js";let F=class extends t{get updating(){return this._snappingSources.some(e=>e?.valid==null||e.valid===!0&&e.snappingSource?.updating===!0)||this._updatingHandles.updating}constructor(e){super(e),this.options=null,this._domain=1,this._updatingHandles=new y,this._sourceModules={featureService:{module:null,loader:null},featureCollection:{module:null,loader:null},graphics:{module:null,loader:null},notes:{module:null,loader:null},scene:{module:null,loader:null}}}initialize(){let e=i(()=>this.options?._effectiveFeatureSources,(e,t)=>this._createSourceInfo(e,t));this._snappingSources=e,this.addHandles([r(e),c(()=>({rulesEnabled:!!this.options?.attributeRulesEnabled,sources:this._snappingSources.filter(n)}),({rulesEnabled:e,sources:t})=>{for(let n of t)n.attributeRulesEnabled=e},l)])}destroy(){this._set(`options`,null),this._updatingHandles.destroy()}async fetchCandidates(e,t,n,r){if(!(t&this._domain)||this.options==null||!this.options.effectiveFeatureEnabled)return[];let i=[],s=this._computeScreenSizeDistanceParameters(e,n);for(let t of this._snappingSources){if(!t?.valid||!t.snappingSource?.layerSource?.enabled||t.layerView?.suspended)continue;let a=t.getFetchCandidatesParameters(e,n,s);for(let e of a)i.push(t.snappingSource.fetchCandidates(e,r).then(e=>this._processCandidatesFromSource(t,e,n)))}let c=(await a(i)).flat();return this._addRightAngleCandidates(c,e,s,n),o(r),O(e,c),c}_addRightAngleCandidates(e,t,n,r){let i=r.vertexHandle==null?r.editGeometryOperations!=null&&r.editGeometryOperations.data.type===`polygon`?r.editGeometryOperations.data.parts[0]?.getFirstVertex()?.pos:null:r.vertexHandle.rightSegment?.rightVertex?.pos,a=r.vertexHandle==null?r.editGeometryOperations==null?null:r.editGeometryOperations.data.parts[0]?.getLastVertex()?.pos:r.vertexHandle.leftSegment?.leftVertex?.pos,{view:o}=this,s=w(i,o,r),c=w(a,o,r),l=e.length;for(let r=0;r<l;r++)this._addRightAngleCandidate(e[r],c,t,n,e),this._addRightAngleCandidate(e[r],s,t,n,e)}_addRightAngleCandidate(e,t,n,r,i){if(t==null||!I(e))return;let a=e.constraint.closestTo(t),o=(a[0]-n[0])/r.x,s=(a[1]-n[1])/r.y,{start:c,end:l}=e.constraint;if(o*o+s*s<=1){let n=m(T(a),T(c))>m(T(a),T(l))?c:l,r=new M({targetPoint:E(a),otherVertex:t,otherVertexType:0,previousVertex:n,constraint:new x(t,a),objectId:e.objectId,isDraped:e.isDraped,domain:1});i.push(r)}}_computeScreenSizeDistanceParameters(e,t){let n=this.options==null?0:this.options.distance*(t.pointer===`touch`?this.options.touchSensitivityMultiplier:1);return this.view==null?{x:n,y:n,z:n,distance:n}:this.view.type===`2d`?(n*=this.view.resolution,{x:n,y:n,z:n,distance:n}):this._computeScreenSizeDistanceParameters3D(e,n,this.view,t)}_computeScreenSizeDistanceParameters3D(e,t,n,r){let{spatialReference:i}=r;n.renderCoordsHelper.toRenderCoords(e,i,z);let a=n.state.camera.computeScreenPixelSizeAt(z),o=a*n.renderCoordsHelper.unitInMeters,s=o/u(i),c=o/d(i),l=t*s,f=t*c,p=N(e,i,b,n),m=p?R(p,e,s,0,0,n,r):0,h=p?R(p,e,0,s,0,n,r):0,g=p?R(p,e,0,0,c,n,r):0;return{x:m===0?0:l/m,y:h===0?0:l/h,z:g===0?0:f/g,distance:a*t}}_processCandidatesFromSource(e,t,n){let r=[];for(let i of t)e.snappingSource&&!this._candidateIsExcluded(e.snappingSource,i,n.excludeFeature)&&(i instanceof j&&(i.layer=e.layer),r.push(i));return r}_candidateIsExcluded(e,t,n){if(n==null)return!1;let r=this._getCandidateObjectId(t);if(r==null)return!1;let i=e.layerSource.layer;return i.type===`graphics`?n.uid===r:n.sourceLayer!==i||!n.attributes||!(`objectIdField`in i)?!1:n.attributes[i.objectIdField]===r}_getCandidateObjectId(e){return e instanceof j?e.objectId:null}async _createSourceInfo(e,t){let n=e.layer;n.loaded||(await n.load(),o(t));let{view:r}=this,i=await this._createFeatureSnappingSourceType(e,t);return o(t),i==null?new D({}):new D({snappingSource:i,view:r,layer:n})}_handleSourceAbort(e,t){let n=s(t,()=>e.destroy());return n&&e.addHandles(n),e}async _createFeatureSnappingSourceType(e,t){switch(e.layer.type){case`feature`:case`geojson`:case`csv`:case`oriented-imagery`:case`subtype-group`:case`wfs`:return this._createFeatureSnappingSourceFeatureLayer(e,t);case`graphics`:case`sketch`:return this._createFeatureSnappingSourceGraphicsLayer(e,t);case`map-notes`:return this._createFeatureSnappingSourceMapNotesLayer(e,t);case`scene`:case`building-scene`:return this._createFeatureSnappingSourceSceneLayer(e,t)}return null}async _createFeatureSnappingSourceSceneLayer(e,t){let{view:n}=this;if(n==null||n.type!==`3d`)return null;let r=await this._getSourceModule(`scene`);return o(t),this._handleSourceAbort(new r.SceneLayerSnappingSource({layerSource:e,view:n}),t)}async _createFeatureSnappingSourceFeatureLayer(e,t){switch(e.layer.source?.type){case`feature-layer`:case`oriented-imagery`:{let n=await this._getSourceModule(`featureService`);return o(t),this._handleSourceAbort(new n.FeatureServiceSnappingSource({spatialReference:this.spatialReference,view:this.view,layerSource:e}),t)}case`memory`:case`csv`:case`geojson`:case`wfs`:{if(e.layer.geometryType===`mesh`)return null;let n=await this._getSourceModule(`featureCollection`);return o(t),this._handleSourceAbort(new n.FeatureCollectionSnappingSource({layerSource:e,view:this.view}),t)}}return null}async _createFeatureSnappingSourceGraphicsLayer(e,t){let n=await this._getSourceModule(`graphics`);return o(t),this._handleSourceAbort(new n.GraphicsSnappingSource({getGraphicsLayers:()=>[e.layer],spatialReference:this.spatialReference,view:this.view,layerSource:e}),t)}async _createFeatureSnappingSourceMapNotesLayer(e,t){let n=await this._getSourceModule(`notes`);return o(t),this._handleSourceAbort(new n.GraphicsSnappingSource({getGraphicsLayers:()=>e.layer.sublayers?.toArray()??[],spatialReference:this.spatialReference,view:this.view,layerSource:e}),t)}async _getSourceModule(e){let t=this._sourceModules[e];if(t.loader==null){let t=this._loadSourceModule(e),n={module:null,loader:t};this._sourceModules[e]=n;let r=await t,i={module:r,loader:t};return this._sourceModules[e]=i,r}return t.module==null?t.loader:t.module}_loadSourceModule(e){let t=this._updatingHandles;switch(e){case`featureService`:return t.addPromise(import(`./featureSources/FeatureServiceSnappingSource.js`));case`featureCollection`:return t.addPromise(import(`./featureSources/FeatureCollectionSnappingSource.js`));case`graphics`:return t.addPromise(import(`./featureSources/GraphicsSnappingSource.js`));case`notes`:return t.addPromise(import(`./featureSources/GraphicsSnappingSource.js`));case`scene`:return t.addPromise(import(`./featureSources/SceneLayerSnappingSource.js`))}}get test(){}};e([f({constructOnly:!0})],F.prototype,`spatialReference`,void 0),e([f({constructOnly:!0})],F.prototype,`view`,void 0),e([f()],F.prototype,`options`,void 0),e([f({readOnly:!0})],F.prototype,`updating`,null),e([f()],F.prototype,`_snappingSources`,void 0),F=e([p(`esri.views.interactive.snapping.FeatureSnappingEngine`)],F);function I(e){let t=e instanceof A||e instanceof k,n=S(e.constraint)||C(e.constraint);return t&&n&&!L(e.constraint)}function L({start:e,end:t}){let n=g(e,t),r=m(T(e),T(t));return n<v()||r/n<V}function R(e,t,n,r,i,a,{spatialReference:o}){let s=h(B,t);s[0]+=n,s[1]+=r,s[2]+=i;let c=N(s,o,b,a);return c?P(c,e):1/0}const z=_(),B=_(),V=1e-4;export{F as FeatureSnappingEngine};
2
+ import{__decorate as e}from"tslib";import t from"../../../core/Accessor.js";import{isSome as n}from"../../../core/arrayUtils.js";import{destroyHandle as r}from"../../../core/handleUtils.js";import"../../../core/has.js";import{mapCollectionAsync as i}from"../../../core/mapCollectionUtils.js";import{allSettledValues as a,throwIfAborted as o,onAbort as s}from"../../../core/promiseUtils.js";import{watch as c,sync as l}from"../../../core/reactiveUtils.js";import{getMetersPerUnitForSR as u,getMetersPerVerticalUnitForSR as d}from"../../../core/units.js";import{property as f,subclass as p}from"../../../core/accessorSupport/decorators.js";import{squaredDistance as m}from"../../../core/libs/gl-matrix-2/math/vec2.js";import{copy as h,squaredDistance as g}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{create as _}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{getEpsilon as v}from"../../../core/libs/gl-matrix-2/math/common.js";import{UpdatingHandles as y}from"../../../core/support/UpdatingHandles.js";import{absoluteHeightElevationInfo as b}from"../../../support/elevationInfoUtils.js";import{VerticalHalfPlaneConstraint as x,isLine as S,isDrapedLine as C}from"../sketch/constraints.js";import{fromAnyMapPoint as w,asVec2 as T,markAsTarget as E}from"../sketch/normalizedPoint.js";import{FeatureSnappingSourceInfo as D}from"./FeatureSnappingSourceInfo.js";import{sortCandidatesInPlace as O}from"./snappingUtils.js";import{DrapedEdgeSnappingCandidate as k}from"./candidates/DrapedEdgeSnappingCandidate.js";import{EdgeSnappingCandidate as A}from"./candidates/EdgeSnappingCandidate.js";import{FeatureSnappingCandidate as j}from"./candidates/FeatureSnappingCandidate.js";import{RightAngleSnappingCandidate as M}from"./candidates/RightAngleSnappingCandidate.js";import{vectorToScreenPoint as N}from"../support/viewUtils.js";import{screenDistance as P}from"../../../core/screenUtils.js";let F=class extends t{get updating(){return this._snappingSources.some(e=>e?.valid==null||e.valid===!0&&e.snappingSource?.updating===!0)||this._updatingHandles.updating}constructor(e){super(e),this.options=null,this._domain=1,this._updatingHandles=new y,this._sourceModules={featureService:{module:null,loader:null},featureCollection:{module:null,loader:null},graphics:{module:null,loader:null},notes:{module:null,loader:null},scene:{module:null,loader:null}}}initialize(){let e=i(()=>this.options?._effectiveFeatureSources,(e,t)=>this._createSourceInfo(e,t));this._snappingSources=e,this.addHandles([r(e),c(()=>({rulesEnabled:!!this.options?.attributeRulesEnabled,sources:this._snappingSources.filter(n)}),({rulesEnabled:e,sources:t})=>{for(let n of t)n.attributeRulesEnabled=e},l)])}destroy(){this._set(`options`,null),this._updatingHandles.destroy()}async fetchCandidates(e,t,n,r){if(!(t&this._domain)||this.options==null||!this.options.effectiveFeatureEnabled)return[];let i=[],s=this._computeScreenSizeDistanceParameters(e,n);for(let t of this._snappingSources){if(!t?.valid||!t.snappingSource?.layerSource?.enabled||t.layerView?.suspended)continue;let a=t.getFetchCandidatesParameters(e,n,s);for(let e of a)i.push(t.snappingSource.fetchCandidates(e,r).then(e=>this._processCandidatesFromSource(t,e,n)))}let c=(await a(i)).flat();return this._addRightAngleCandidates(c,e,s,n),o(r),O(e,c),c}_addRightAngleCandidates(e,t,n,r){let i=r.vertexHandle==null?r.editGeometryOperations!=null&&r.editGeometryOperations.data.type===`polygon`?r.editGeometryOperations.data.parts[0]?.getFirstVertex()?.pos:null:r.vertexHandle.rightSegment?.rightVertex?.pos,a=r.vertexHandle==null?r.editGeometryOperations!=null&&(r.editGeometryOperations.data.type===`polyline`||r.editGeometryOperations.data.type===`polygon`)?r.editGeometryOperations.data.parts[0]?.getLastVertex()?.pos:null:r.vertexHandle.leftSegment?.leftVertex?.pos,{view:o}=this,s=w(i,o,r),c=w(a,o,r),l=e.length;for(let r=0;r<l;r++)this._addRightAngleCandidate(e[r],c,t,n,e),this._addRightAngleCandidate(e[r],s,t,n,e)}_addRightAngleCandidate(e,t,n,r,i){if(t==null||!I(e))return;let a=e.constraint.closestTo(t),o=(a[0]-n[0])/r.x,s=(a[1]-n[1])/r.y,{start:c,end:l}=e.constraint;if(o*o+s*s<=1){let n=m(T(a),T(c))>m(T(a),T(l))?c:l,r=new M({targetPoint:E(a),otherVertex:t,otherVertexType:0,previousVertex:n,constraint:new x(t,a),objectId:e.objectId,isDraped:e.isDraped,domain:1});i.push(r)}}_computeScreenSizeDistanceParameters(e,t){let n=this.options==null?0:this.options.distance*(t.pointer===`touch`?this.options.touchSensitivityMultiplier:1);return this.view==null?{x:n,y:n,z:n,distance:n}:this.view.type===`2d`?(n*=this.view.resolution,{x:n,y:n,z:n,distance:n}):this._computeScreenSizeDistanceParameters3D(e,n,this.view,t)}_computeScreenSizeDistanceParameters3D(e,t,n,r){let{spatialReference:i}=r;n.renderCoordsHelper.toRenderCoords(e,i,z);let a=n.state.camera.computeScreenPixelSizeAt(z),o=a*n.renderCoordsHelper.unitInMeters,s=o/u(i),c=o/d(i),l=t*s,f=t*c,p=N(e,i,b,n),m=p?R(p,e,s,0,0,n,r):0,h=p?R(p,e,0,s,0,n,r):0,g=p?R(p,e,0,0,c,n,r):0;return{x:m===0?0:l/m,y:h===0?0:l/h,z:g===0?0:f/g,distance:a*t}}_processCandidatesFromSource(e,t,n){let r=[];for(let i of t)e.snappingSource&&!this._candidateIsExcluded(e.snappingSource,i,n.excludeFeature)&&(i instanceof j&&(i.layer=e.layer),r.push(i));return r}_candidateIsExcluded(e,t,n){if(n==null)return!1;let r=this._getCandidateObjectId(t);if(r==null)return!1;let i=e.layerSource.layer;return i.type===`graphics`?n.uid===r:n.sourceLayer!==i||!n.attributes||!(`objectIdField`in i)?!1:n.attributes[i.objectIdField]===r}_getCandidateObjectId(e){return e instanceof j?e.objectId:null}async _createSourceInfo(e,t){let n=e.layer;n.loaded||(await n.load(),o(t));let{view:r}=this,i=await this._createFeatureSnappingSourceType(e,t);return o(t),i==null?new D({}):new D({snappingSource:i,view:r,layer:n})}_handleSourceAbort(e,t){let n=s(t,()=>e.destroy());return n&&e.addHandles(n),e}async _createFeatureSnappingSourceType(e,t){switch(e.layer.type){case`feature`:case`geojson`:case`csv`:case`oriented-imagery`:case`subtype-group`:case`wfs`:return this._createFeatureSnappingSourceFeatureLayer(e,t);case`graphics`:case`sketch`:return this._createFeatureSnappingSourceGraphicsLayer(e,t);case`map-notes`:return this._createFeatureSnappingSourceMapNotesLayer(e,t);case`scene`:case`building-scene`:return this._createFeatureSnappingSourceSceneLayer(e,t)}return null}async _createFeatureSnappingSourceSceneLayer(e,t){let{view:n}=this;if(n==null||n.type!==`3d`)return null;let r=await this._getSourceModule(`scene`);return o(t),this._handleSourceAbort(new r.SceneLayerSnappingSource({layerSource:e,view:n}),t)}async _createFeatureSnappingSourceFeatureLayer(e,t){switch(e.layer.source?.type){case`feature-layer`:case`oriented-imagery`:{let n=await this._getSourceModule(`featureService`);return o(t),this._handleSourceAbort(new n.FeatureServiceSnappingSource({spatialReference:this.spatialReference,view:this.view,layerSource:e}),t)}case`memory`:case`csv`:case`geojson`:case`wfs`:{if(e.layer.geometryType===`mesh`)return null;let n=await this._getSourceModule(`featureCollection`);return o(t),this._handleSourceAbort(new n.FeatureCollectionSnappingSource({layerSource:e,view:this.view}),t)}}return null}async _createFeatureSnappingSourceGraphicsLayer(e,t){let n=await this._getSourceModule(`graphics`);return o(t),this._handleSourceAbort(new n.GraphicsSnappingSource({getGraphicsLayers:()=>[e.layer],spatialReference:this.spatialReference,view:this.view,layerSource:e}),t)}async _createFeatureSnappingSourceMapNotesLayer(e,t){let n=await this._getSourceModule(`notes`);return o(t),this._handleSourceAbort(new n.GraphicsSnappingSource({getGraphicsLayers:()=>e.layer.sublayers?.toArray()??[],spatialReference:this.spatialReference,view:this.view,layerSource:e}),t)}async _getSourceModule(e){let t=this._sourceModules[e];if(t.loader==null){let t=this._loadSourceModule(e),n={module:null,loader:t};this._sourceModules[e]=n;let r=await t,i={module:r,loader:t};return this._sourceModules[e]=i,r}return t.module==null?t.loader:t.module}_loadSourceModule(e){let t=this._updatingHandles;switch(e){case`featureService`:return t.addPromise(import(`./featureSources/FeatureServiceSnappingSource.js`));case`featureCollection`:return t.addPromise(import(`./featureSources/FeatureCollectionSnappingSource.js`));case`graphics`:return t.addPromise(import(`./featureSources/GraphicsSnappingSource.js`));case`notes`:return t.addPromise(import(`./featureSources/GraphicsSnappingSource.js`));case`scene`:return t.addPromise(import(`./featureSources/SceneLayerSnappingSource.js`))}}get test(){}};e([f({constructOnly:!0})],F.prototype,`spatialReference`,void 0),e([f({constructOnly:!0})],F.prototype,`view`,void 0),e([f()],F.prototype,`options`,void 0),e([f({readOnly:!0})],F.prototype,`updating`,null),e([f()],F.prototype,`_snappingSources`,void 0),F=e([p(`esri.views.interactive.snapping.FeatureSnappingEngine`)],F);function I(e){let t=e instanceof A||e instanceof k,n=S(e.constraint)||C(e.constraint);return t&&n&&!L(e.constraint)}function L({start:e,end:t}){let n=g(e,t),r=m(T(e),T(t));return n<v()||r/n<V}function R(e,t,n,r,i,a,{spatialReference:o}){let s=h(B,t);s[0]+=n,s[1]+=r,s[2]+=i;let c=N(s,o,b,a);return c?P(c,e):1/0}const z=_(),B=_(),V=1e-4;export{F as FeatureSnappingEngine};
@@ -72,7 +72,7 @@ export default class Environment extends JSONSupport {
72
72
  get lighting(): SunLighting | VirtualLighting;
73
73
  set lighting(value: (SunLightingProperties & { type?: "sun" }) | (VirtualLightingProperties & { type: "virtual" }));
74
74
  /**
75
- * Indicates whether stars visualization is enabled.
75
+ * Indicates whether the deep-sky background, which contains stars and the Milky Way, is enabled.
76
76
  *
77
77
  * @default true
78
78
  */
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import{pushIfSome as t}from"../../core/arrayUtils.js";import{createTask as n}from"../../core/asyncUtils.js";import r from"../../core/Collection.js";import i from"../../core/Error.js";import{EventedAccessor as a}from"../../core/Evented.js";import o from"../../core/Logger.js";import{getOrCreateMapValue as s}from"../../core/MapUtils.js";import{destroyMaybe as c,abortMaybe as l}from"../../core/maybe.js";import{throwIfAborted as u,whenOrAbort as ee,ignoreAbortErrors as d,isAbortError as f}from"../../core/promiseUtils.js";import p from"../../core/ReactiveMap.js";import{on as te,sync as m,watch as h,syncAndInitial as g,initial as _,whenOnce as v}from"../../core/reactiveUtils.js";import{property as y,subclass as b}from"../../core/accessorSupport/decorators.js";import{UpdatingHandles as ne}from"../../core/support/UpdatingHandles.js";import x from"../../geometry/SpatialReference.js";import{getGraphicLayer as S}from"../../graphic/graphicOriginUtils.js";import{isSubtypeGroupLayer as C,isSubtypeSublayer as w,isFeatureLayer as re,getSubtypesFromLayer as ie}from"../../layers/support/layerUtils.js";import{system as T}from"../../time/constants.js";import{getAttachmentKey as E}from"./attachmentUtils.js";import{getLayerTimeZone as D,getEffectiveTimeZone as O,createReactiveGraphic as k,isAttributeFormSupportedLayerWithAttachments as A,layerSupportsAttachments as j,queryAttachmentsForElements as M}from"./batchAttributeFormUtils.js";import{ReactiveContingentValuesManager as N}from"./ReactiveContingentValuesManager.js";import{parseFormTemplateString as P}from"./stringUtils.js";import{ValueChangeTransaction as F}from"./ValueChangeTransaction.js";import{ArcadeExecutorProvider as I}from"./expressions/ArcadeExecutorProvider.js";import{ExpressionsManager as L}from"./expressions/ExpressionsManager.js";import{ExpressionsModel as R}from"./expressions/ExpressionsModel.js";import z from"./inputs/BatchFormInputs.js";import{createBatchFormInputsFromBatchFormTemplate as B,mergeBatchFormInputsFromNewTemplate as V}from"./inputs/support/createBatchFormInputs.js";import{isGroupInput as H,isFieldInput as U}from"./inputs/support/inputUtils.js";import W from"./templates/BatchFormTemplate.js";import{createBatchFormTemplate as G}from"./templates/support/createBatchFormTemplate.js";import{isExcludedFromSharedForm as K,isGroupElementTemplate as q}from"./templates/support/templateUtils.js";import{ContingentValuesManager as J,isLayerWithContingentValues as Y}from"../support/ContingentValuesManager.js";import{isEmptyValue as X}from"../support/forms/formUtils.js";function ae(e,t){return e?.find(e=>e.layer===t)}let Z=class extends a{constructor(e){super(e),this._attachmentCache=new p,this.activeFeatureIndex=-1,this.attachmentsEnabled=!1,this.callbacks=null,this.disabled=!1,this.editType=`NA`,this.features=new r,this._hasAsyncArcadeExpressions=!1,this.highlightHelper=null,this.maximumFeatureCount=2e3,this.maximumFeatureCountWithComplexForms=50,this.pageStack=[],this.readOnly=!1,this.pendingSubtypeChoice=null,this.spatialReference=null,this.submitHasBeenAttempted=!1,this.view=null,this.userHasChangedValues=!1,this.layerInfos=null,this._arcadeExecutorProvider=new I,this._activeAssociation=null,this._activeAssociationsInput=null,this._activeRelationshipInput=null,this._ownContingentValuesManager=null,this._activeFormInputsByElementId=new Map,this._emptyForm=new z({inputs:[]}),this._emptyFormTemplate=new W({elements:[]}),this._featureFormMap=new p,this._prepareTask=null,this._layerTemplateUpdateTask=null,this._syncAttachmentsTask=null,this._reactiveGraphicLookup=new p,this._updatingHandles=new ne,this._submitTask=null,this._layerTemplateMap=new p,this._workingFeatures=new r,this._expressionsManager=new L({arcadeContext:{editType:`NA`,spatialReference:null,map:null,timeZone:T}}),this._getExternalErrorForFeature=(e,t)=>this._reactiveContingentValuesManager.getViolationTypeForField(e,t),this._getFieldValueOptionsForFeature=e=>this._reactiveContingentValuesManager.getAndWatchFieldValueOptions(e),this._requestDeferredExpressionEvaluation=async({features:e,getExecutor:t})=>this._valueChangeTransaction(n=>this._expressionsManager.requestDeferredExecution(e,t,n),`user`),this.sharedForm=this._emptyForm,this.sharedFormTemplate=this._emptyFormTemplate}initialize(){this.contingentValuesManager||=this._ownContingentValuesManager=new J,this.addHandles([te(()=>this.features,`after-changes`,()=>{this.goHome(),this.notifyChange(`layers`),this._prepare()},m),h(()=>[this.attachmentsEnabled,this.features,this.map,this.timeZone,this.editType],()=>this._prepare(),m),h(()=>this.activeForm,()=>{this.goHome(),this._activeFormInputsByElementId.clear(),this._syncAttachments()},m),h(()=>this.activeFeature,()=>{this.goHome()},m),h(()=>this.page,e=>{let t=[...this.pageStack];if(!t.includes(e))t.push(e);else for(;t.length&&t.at(-1)!==e;)t.pop();this.pageStack=t},g),h(()=>this.contingentValuesManager,e=>{c(this._reactiveContingentValuesManager),this._reactiveContingentValuesManager=new N({manager:e})},_)]),this._prepare()}destroy(){this._prepareTask=l(this._prepareTask),this.pendingSubtypeChoice?.reject(),this._layerTemplateUpdateTask=l(this._layerTemplateUpdateTask),this._syncAttachmentsTask=l(this._syncAttachmentsTask),this._workingFeatures.destroyAll(),c(this._expressionsManager),c(this._reactiveContingentValuesManager),this._updatingHandles.destroy(),this._reactiveGraphicLookup=new p,this._emptyForm.destroy(),this._emptyFormTemplate.destroy(),this._ownContingentValuesManager=c(this._ownContingentValuesManager),this.highlightHelper?.removeAll()}get activeFeature(){let e=this.activeFeatureIndex;return e<0?null:this.features.at(e)}get activeForm(){if(this.mode===`batch`)return this.sharedForm;let e=this._workingFeatures.at(this.activeFeatureIndex);if(!e)return this._emptyForm;let t=this._featureFormMap.get(e);if(t)return t;let n=this._makeBatchFormInputsForFeature(e);return n!==this._emptyForm&&this._featureFormMap.set(e,n),n}get activeLayer(){let{activeFeature:e}=this;return e?S(e)??null:null}get activeAssociation(){return this._activeAssociation}get activeAssociationsInput(){return this._activeAssociationsInput}get activeAssociationType(){return this.activeAssociationsInput?.activeAssociationType}get activeRelationshipInput(){return this._activeRelationshipInput}get calculating(){return this._expressionsManager.calculating}get expressionsManager(){return this._expressionsManager}get canGoBack(){return this.pageStack.length>1}get expressionEvaluationFailed(){return this._expressionsManager.expressionEvaluationFailed}get hasNonActiveInvalidFeatures(){if(this.mode===`batch`)return!1;let{activeFeature:e}=this;return this.invalidFeatures.some(t=>t!==e)}get hasAsyncArcadeExpressions(){return this._hasAsyncArcadeExpressions}get hasTooManyFeatures(){return this._workingFeatures.length>this.maximumFeatureCount}get hasTooManyComplexFeatures(){return this._workingFeatures.length>this.maximumFeatureCountWithComplexForms&&this.hasAsyncArcadeExpressions}get invalidFeatures(){return this.sharedForm.invalidFeatures}get hasVisibleInputs(){return this.visibleInputs.length>0}get hasLayersWithContingentValues(){let e=this.contingentValuesManager;for(let t of this.layers)if(e.getFieldsWithContingentValues(t).size>0)return!0;return!1}get formDescription(){return this._computeFormHeaderField(this.activeForm?.description)}get formTitle(){return this._computeFormHeaderField(this.activeForm?.title)}get effectiveTimeZone(){let{activeLayer:e,timeZone:t}=this;if(!e)return t??`system`;let n=D(e);return O(t,n)}get visibleInputs(){return this.activeForm.inputs.filter(e=>e.visible)}get map(){return this.view?.map??null}set map(e){this._override(`map`,e)}get noVisibleElementsReason(){if(this.hasVisibleInputs)return null;if(this.activeForm.inputs.length===0)return`noElements`;let e=new Set;for(let t of this.activeForm.inputs)switch(t.visibilityCode){case`hidden:not-in-all-layers`:case`hidden:no-domain-in-common`:e.add(`noElementsInCommon`);break;case`hidden:field-definition`:case`hidden:group-visibility-expression:all-features`:case`hidden:visibility-expression:all-features`:e.add(`allElementsHidden`);break;case`hidden:group-visibility-expression:some-features`:case`hidden:visibility-expression:some-features`:return`elementsHiddenInSome`}return e.has(`allElementsHidden`)?`allElementsHidden`:`noElementsInCommon`}get page(){return this.showingSelectedAttachmentReplacePage&&this.selectedAttachmentDetails?`replacing-attachment`:this.selectedAttachmentDetails?`viewing-attachment-details`:this.selectedAttachmentAddInput?`adding-attachments`:this.selectedAttachmentListInput?`viewing-attachments`:this.activeAssociationsInput?.associatedLayer?`viewing-associated-features`:this.activeAssociationsInput?`viewing-associated-layers`:this.activeRelationshipInput?.showAllRelatedRecords?`viewing-related-records`:this.activeRelationshipInput?.showAllCategories?`viewing-related-categories`:`default`}get subtypes(){let e=this.activeLayer;return C(e)||w(e)||re(e)?ie(e):[]}get status(){let e=this._prepareTask;return e==null?`not-loaded`:e.finished?e.error==null?`loaded`:`failed`:`loading`}get timeZone(){return this.view?.timeZone??null}set timeZone(e){this._overrideIfSome(`timeZone`,e)}get updating(){return this._updatingHandles.updating||this.calculating}get valid(){return this.sharedForm.valid&&Array.from(this._featureFormMap.values()).every(e=>e.valid)}get layers(){return Array.from(this._layersSet)}get mode(){return this.activeFeatureIndex>-1?`single`:`batch`}submit(){if(this.submitHasBeenAttempted=!0,this.sharedForm.touchAll(),this._featureFormMap.forEach(e=>e.touchAll()),this.validateContingentValues(this._workingFeatures),!this._hasPendingAttachmentHydration)return this._emitSubmit(),Promise.resolve();if(this._submitTask)return this._submitTask.promise;let e=n(async()=>{await Promise.all(this._allAttachmentInputs.map(e=>e.waitForPendingAttachmentUpdateData())),this._emitSubmit()});return this._submitTask=e,e.promise.finally(()=>{this._submitTask===e&&(this._submitTask=null)}),e.promise}get selectedAttachment(){return this._get(`selectedAttachment`)??null}set selectedAttachment(e){this.showingSelectedAttachmentReplacePage=!1,this._set(`selectedAttachment`,e),e!=null&&(this.selectedAttachmentAddElementId=null)}get selectedAttachmentAddElementId(){return this._get(`selectedAttachmentAddElementId`)??null}set selectedAttachmentAddElementId(e){this.showingSelectedAttachmentReplacePage=!1,this._set(`selectedAttachmentAddElementId`,e),e!=null&&(this.selectedAttachment=null,this.selectedAttachmentListElementId=null)}get selectedAttachmentListElementId(){return this._get(`selectedAttachmentListElementId`)??null}set selectedAttachmentListElementId(e){this._set(`selectedAttachmentListElementId`,e),e!=null&&(this.selectedAttachment=null,this.selectedAttachmentAddElementId=null)}get selectedAttachmentListInput(){let e=this.selectedAttachmentListElementId,t=this.activeForm;if(!e||!t)return null;let n=t.allAttachmentElementInputs.find(t=>t.template.elementId===e)||null;return n?.attachments.length?n:null}get showingSelectedAttachmentReplacePage(){return this._get(`showingSelectedAttachmentReplacePage`)??!1}set showingSelectedAttachmentReplacePage(e){this._set(`showingSelectedAttachmentReplacePage`,e&&this.selectedAttachmentDetails!=null)}get selectedAttachmentAddInput(){let e=this.selectedAttachmentAddElementId,t=this.activeForm;return!e||!t?null:t.allAttachmentElementInputs.find(t=>t.template.elementId===e)||null}get selectedAttachmentDetails(){let e=this.selectedAttachment,t=this.activeForm;if(!e||!t)return null;let n=t.allAttachmentElementInputs.find(t=>t.template.elementId===e.elementId);if(!n)return null;let r=n.attachments.findIndex(t=>E(t)===e.attachmentKey);return r===-1?null:{attachment:n.attachments[r],input:n}}get _allAttachmentInputs(){let e=[...this.sharedForm.allAttachmentElementInputs];for(let t of this._featureFormMap.values())e.push(...t.allAttachmentElementInputs);return e}get _hasPendingAttachmentHydration(){return this._allAttachmentInputs.some(e=>e.hasPendingAttachmentUpdateData)}get _layersSet(){let e=new Set;for(let t of this._workingFeatures){let n=S(t.plainGraphic);n&&e.add(n)}return e}applyStashedAttachmentEdits(e){let t=this._allAttachmentInputs;for(let n of e){let e=t.find(e=>e.label===n.label&&e.attachmentKeyword===n.keywords);e&&e.applyStashedEdits(n)}}findFieldInput(e){if(e==null)return;let t=this._activeFormInputsByElementId;if(t.has(e))return t.get(e);let n=this.activeForm.allFieldInputs.find(t=>t.template.elementId===e);if(n!==void 0)return t.set(e,n),n}getFirstVisibleInvalidFieldInput(){if(this.hasVisibleInputs&&!this.activeForm.valid)for(let e of this.visibleInputs){if(H(e)){let t=e.inputs.find(e=>U(e)&&!e.valid);if(t)return{input:t,groupInput:e}}if(U(e)&&!e.valid)return{input:e}}}getFieldInputValue(e){return this.findFieldInput(e)?.value}getValues(e){let t=this._reactiveGraphicLookup.get(e);if(!t)throw new i(`feature-not-found`,`The given feature is not present in the BatchAttributeForm`);return{...t.attributes}}async goBack(){switch(this.page){case`replacing-attachment`:this.setShowingSelectedAttachmentReplacePage(!1);return;case`viewing-attachment-details`:this.setSelectedAttachment(null);return;case`adding-attachments`:this.setSelectedAttachmentAddElementId(null);return;case`viewing-attachments`:this.setSelectedAttachmentListElementId(null);return;case`viewing-associated-features`:this.setActiveAssociationsLayer(null);return;case`viewing-associated-layers`:this.setActiveAssociationsInput(null);return;case`viewing-related-categories`:case`viewing-related-records`:this.clearActiveRelationshipCategoryOrInput();return;default:return}}async goHome(){this.setShowingSelectedAttachmentReplacePage(!1),this.setSelectedAttachment(null),this.setSelectedAttachmentAddElementId(null),this.setSelectedAttachmentListElementId(null),this.setActiveAssociationsLayer(null),this.setActiveAssociationsInput(null),this.clearAllRelationshipSettings()}notifyGeometriesChanged(e){let t=[];for(let n of e){let e=this._reactiveGraphicLookup.get(n);e&&(t.push(e),e.geometry=n.geometry)}this._updatingHandles.consumePromise(this._valueChangeTransaction(async e=>this._expressionsManager.runGeometryDependentExpressions(t,e),`user`))}async overrideOriginalFeature(e,t){await this._prepareTask?.promise;let n=this._reactiveGraphicLookup.get(e);n&&(n.original=t,this._updatingHandles.consumePromise(this._valueChangeTransaction(e=>this._expressionsManager.runOriginalFeatureDependentExpressions(n,e),`expression`)))}async setFieldInputValue(e,t){let{fieldName:n}=e;await this._updatingHandles.addPromise(this._valueChangeTransaction(async r=>{for(let i of e.features)r.setValue(i,n,t)},`user`,e))}async setFieldInputValuePerFeature(e,t){await this._updatingHandles.addPromise(this._valueChangeTransaction(async n=>{for(let[r,i]of t)n.setValue(r,e.fieldName,i);n.hasChanges&&(e.userHasChangedValue=!0)},`user`,e))}async setValueForFieldName(e,t,n){await this._updatingHandles.addPromise(this._valueChangeTransaction(async r=>{for(let i of n){let n=this._reactiveGraphicLookup.get(i);n&&r.setValue(n,e,t)}},`user`,e))}async setValuePerFeatureForFieldName(e,t){await this._updatingHandles.addPromise(this._valueChangeTransaction(async n=>{for(let[r,i]of t){let t=this._reactiveGraphicLookup.get(r);t&&n.setValue(t,e,i)}},`user`,e))}async setFieldValue(e,t){let n=this.activeForm.allFieldInputs.find(t=>t.fieldName===e);if(n==null)throw new i(`no-field-input-found`,`Cannot set the value of FieldInput with field name: ${e} because none was found in the active form`);await this.setFieldInputValue(n,t)}async setValue(e,t){let n=this.findFieldInput(e);if(n==null)throw new i(`no-FieldInput-found`,`Cannot set the value of FieldInput with ID: ${e} because none was found in the active form`);await this.setFieldInputValue(n,t)}async applySubtypeDefaults(e){let{defaultValues:t}=e,{allFieldInputs:n}=this.activeForm;await this._updatingHandles.addPromise(this._valueChangeTransaction(async e=>{for(let r of n){let{fieldName:n}=r,i=t[n];if(i!=null)for(let t of r.features)e.setValue(t,n,i)}},`user`))}async handleSubtypeChanged(e){let t=this._workingFeatures.at(e);if(t)return this._updatingHandles.addPromise(this._handleSubtypeChanged(t))}async stageAddAttachments(e,t){if(t.length===0)return[];let n=this._findAttachmentInput(e);if(!n)return[];let r=await this._updatingHandles.addPromise(n.stageAddAttachments(t,this._expressionsManager.arcadeContext));return r.length===0?r:(this.userHasChangedValues=!0,this._emitAttachmentsChange(n),r)}stageDeleteAttachment(e,t){let n=this._findAttachmentInput(e);if(!n)return;let r=this._findAttachment(n,t);r&&(n.stageDeleteAttachment(r),this.userHasChangedValues=!0,this._emitAttachmentsChange(n))}async stageRenameAttachment(e,t,n){let r=this._findAttachmentInput(e);if(!r)return;let i=this._findAttachment(r,t);i&&(r.stageRenameAttachment(i,n.trim()),this.userHasChangedValues=!0,await r.ensureStagedUpdateData(i),this._emitAttachmentsChange(r))}async stageReplaceAttachment(e,t,n){let r=this._findAttachmentInput(e);if(!r)return!1;let i=this._findAttachment(r,t);return!i||!await this._updatingHandles.addPromise(r.stageReplaceAttachment(i,n,this._expressionsManager.arcadeContext))?!1:(this.userHasChangedValues=!0,this._emitAttachmentsChange(r),!0)}clearAttachmentChanges(e){let t=this._findAttachmentInput(e);t&&(t.clearAttachmentChanges(),this._emitAttachmentsChange(t))}setActiveAssociation(e){this._activeAssociation=e}setActiveAssociationsInput(e){this._activeAssociationsInput=e}setActiveAssociationsLayer(e){this._activeAssociationsInput?.setAssociatedLayer(e)}setActiveAssociationType(e){this._activeAssociationsInput?.setActiveAssociationType(e)}setActiveRelationshipInput(e){e||this._activeRelationshipInput?.setActiveCategory(null),this._activeRelationshipInput=e}setActiveRelationshipCategory(e,t){t.setActiveCategory(e),this.setActiveRelationshipInput(t)}clearAllRelationshipSettings(){let e=this.activeRelationshipInput;e&&(e.setActiveCategory(null),e.setShowAllCategories(!1),e.setShowAllRelatedRecords(!1),this._activeRelationshipInput=null)}clearActiveRelationshipCategoryOrInput(){let e=this.activeRelationshipInput;e&&(e.showAllRelatedRecords?e.showAllCategories?e.setActiveCategory(null):this.setActiveRelationshipInput(null):e.showAllCategories&&(e.setShowAllCategories(!1),this.setActiveRelationshipInput(null)))}resetAttachmentChanges(e,t){let n=this._findAttachmentInput(e);if(!n||!n.editable)return;let r=this._findAttachment(n,t);r&&(n.discardStagedEdits(r),this._emitAttachmentsChange(n))}setSelectedAttachment(e){this.selectedAttachment=e??null}setShowingSelectedAttachmentReplacePage(e){this.showingSelectedAttachmentReplacePage=e}setSelectedAttachmentAddElementId(e){this.selectedAttachmentAddElementId=e??null}setSelectedAttachmentListElementId(e){this.selectedAttachmentListElementId=e??null}userChangesHaveMadeFeatureInvalid(e){return!!this._reactiveGraphicLookup.get(e)?.userChangesHaveMadeInvalid}validate(){return!1}validateContingentValues(e,t=!1){if(t&&!this.submitHasBeenAttempted)for(let t of e)this._reactiveContingentValuesManager.validateContingenciesForNonNullFields(t);else for(let t of e)this._reactiveContingentValuesManager.validateContingencyConstraints(t,{includeIncompleteViolations:!0})}_makeBatchFormInputsForFeature(e){let t=this._layerTemplateMap.get(e.layer);return t?B(t,{allFeatures:new r([e]),expressionsManager:this._expressionsManager,requestDeferredExpressionEvaluation:this._requestDeferredExpressionEvaluation,getExternalErrorForFeature:this._getExternalErrorForFeature,getFieldValueOptionsForFeature:this._getFieldValueOptionsForFeature,map:this.map}):this._emptyForm}async _ensureLayerTemplate(e,t){let{_layersSet:n,contingentValuesManager:r}=this,i=e.layer,a=!1;for(let e of this._layerTemplateMap.keys())n.has(e)||(this._layerTemplateMap.delete(e),this._expressionsManager.layerExpressionsModelMap.delete(e),r.resetOptionsForLayer(e),Y(e)&&r.resetViolationsForLayer(e),a=!0);this._layerTemplateMap.has(i)||(await this._prepareLayer(i,t),u(t),r.layers.add(i),a=!0),a&&(this._prepareSharedFormTemplate(),V(this.sharedForm,this.sharedFormTemplate,{allFeatures:this._workingFeatures,expressionsManager:this._expressionsManager,getFieldValueOptionsForFeature:this._getFieldValueOptionsForFeature,requestDeferredExpressionEvaluation:this._requestDeferredExpressionEvaluation,map:this.map}),this._recomputeHasAsyncArcadeExpressions(),await v(()=>!r.updating,t))}_recomputeHasAsyncArcadeExpressions(){this._hasAsyncArcadeExpressions=!1;for(let e of this._expressionsManager.layerExpressionsModelMap.values())for(let t of e.arcadeExecutorUses.keys())if(t.isAsync){this._hasAsyncArcadeExpressions=!0;return}}_computeFormHeaderField(e){let{activeFeature:t,activeLayer:n}=this;return!e||!n||!t?null:P({attributes:t?.attributes,label:e,layer:n,timeZone:this.effectiveTimeZone})}_makeSubmitResults(){let e=new Map;for(let[n,r]of this._reactiveGraphicLookup){let i=[],a=[],o=this._featureFormMap.get(r)?.allAttachmentElementInputs??[];for(let e of o)t(i,e.toSubmitEdits()),e.valid||a.push(e.template.elementId);e.set(n,{feature:n,values:{...r.attributes},invalidFields:[],attachmentEdits:i,invalidAttachmentElementIds:a})}for(let t of this.sharedForm.allFieldInputs)for(let n of t.invalidFeatures)e.get(n)?.invalidFields.push(t.fieldName);return Array.from(e.values())}async _handleSubtypeChanged(e){let t=e.layer;if(this.contingentValuesManager.resetOptionsForFeature(t,e.plainGraphic),Y(t)&&this.contingentValuesManager.resetViolationsForFeature(t,e.plainGraphic),!w(t))return;let r=t.parent?.findSublayerForFeature(e.plainGraphic);if(!r)return;this._layerTemplateUpdateTask=l(this._layerTemplateUpdateTask);let i=n(async t=>{u(t),e.source.sourceLayer=r,e.source.origin=r.graphicOrigin,await this._ensureLayerTemplate(e,t),u(t),this._featureFormMap.get(e)?.destroy(),this._featureFormMap.set(e,this._makeBatchFormInputsForFeature(e)),await ee(this._valueChangeTransaction(t=>this._expressionsManager.runAllExpressions([e],t),`user`),t),u(t)});this._layerTemplateUpdateTask=i,await d(this._updatingHandles.addPromise(i.promise))}_emitSubmit(){this.emit(`submit`,{name:`submit`,results:this._makeSubmitResults(),valid:this.valid})}_findAttachmentInput(e){let t=this.activeForm.allAttachmentElementInputs.find(t=>t.template.elementId===e);return t||o.getLogger(this).error(`Attachment input not found for elementId '${e}'`),t}_findAttachment(e,t){let n=e.findAttachment(t);return n||o.getLogger(this).error(`Attachment '${t}' not found for attachment element '${e.template.elementId}'`),n}_makeAttachmentEdits(e){let n=[];for(let r of e.allAttachmentElementInputs)t(n,r.toSubmitEdits());return n}_emitAttachmentsChange(e){let t=e.single.feature;if(!t)return;let n=this._featureFormMap.get(t);this.emit(`attachments-change`,{name:`attachments-change`,feature:t.source,attachmentEdits:this._makeAttachmentEdits(n??this.activeForm),valid:this.valid})}async _valueChangeTransaction(e,t,n){let r=typeof n==`string`?n:n?.fieldName,i=new F(this,t,r);if(await e(i),t===`user`&&await this._expressionsManager.runExpressionsDependentOnChangedFields(i),await i.close(),i.hasChanges&&n){let e=typeof n==`string`?this.activeForm.allFieldInputs.find(e=>e.fieldName===n):n;e&&(e.userHasChangedValue=!0)}}_prepare(){this.pendingSubtypeChoice?.reject(),this._hasAsyncArcadeExpressions=!1,this._prepareTask=l(this._prepareTask),this._layerTemplateUpdateTask=l(this._layerTemplateUpdateTask),this._layerTemplateMap.clear(),this._updateWorkingFeatures(),c(this._expressionsManager),this.userHasChangedValues=!1,this._expressionsManager=new L({arcadeContext:{editType:this.editType,spatialReference:this.spatialReference??x.WebMercator,map:this.map,timeZone:this.timeZone||`system`}});let{layers:e}=this;if(e.length===0)return;let t=n(async t=>{try{u(t),this._updateWorkingFeatures(),this.contingentValuesManager.layers.addMany(e),await Promise.all(e.map(e=>e.load()));for(let n of e)await this._prepareLayer(n,t);if(this.hasTooManyComplexFeatures)throw new i(`too-many-features-with-complex-forms`,`There are too many features to load into the form with the configured complexity`);if(this.hasTooManyFeatures)throw new i(`too-many-features`,`There are too many features to load into the form.`);this._prepareSharedFormTemplate(),this.sharedForm=B(this.sharedFormTemplate,{allFeatures:this._workingFeatures,expressionsManager:this._expressionsManager,getExternalErrorForFeature:this._getExternalErrorForFeature,getFieldValueOptionsForFeature:this._getFieldValueOptionsForFeature,map:this.map,requestDeferredExpressionEvaluation:this._requestDeferredExpressionEvaluation}),await this._valueChangeTransaction(async e=>await this._expressionsManager.runAllExpressions(this._workingFeatures.toArray(),e),`expression`),await v(()=>!this.contingentValuesManager.updating)}catch(e){throw f(e)||o.getLogger(this).error(`Failed preparing form`,e),e}});this._updatingHandles.consumePromise(t.promise),this._prepareTask=t}async _prepareLayer(e,t){let n=ae(this.layerInfos,e),r=await G(e,{arcadeExecutorProvider:this._arcadeExecutorProvider,formTimeZone:this.timeZone,attachmentsEnabled:this.attachmentsEnabled},n?.formTemplate);u(t),this._layerTemplateMap.set(e,r);let i=r.getExpressionExecutorsForLayer(e);if(this._expressionsManager.layerExpressionsModelMap.set(e,new R({preserveFieldValuesWhenHidden:r.preserveFieldValuesWhenHidden,executorMap:i,fieldsIndex:e.fieldsIndex})),!this._hasAsyncArcadeExpressions){for(let e of i.values())if(e&&(this._hasAsyncArcadeExpressions=(e.editableExpression?.isAsync||e.requiredExpression?.isAsync||e.valueExpression?.isAsync||e.visibilityExpression?.isAsync)===!0,this._hasAsyncArcadeExpressions))break}}_prepareSharedFormTemplate(){let e=new Map;for(let t of this._layerTemplateMap.values())for(let n of t.elements){if(K(n))continue;let t=n.clone();q(t)&&(t.elements=t.elements.filter(e=>!K(e)));let{elementId:r}=t;e.has(r)?e.get(r).foldIn(t):e.set(r,t)}this.sharedFormTemplate=new W({elements:Array.from(e.values())})}_updateWorkingFeatures(){this._workingFeatures.destroyAll(),this._reactiveContingentValuesManager.reset();for(let e of this._featureFormMap.values())e.destroy();this._featureFormMap.clear(),this._attachmentCache.clear();let{features:e}=this;if(this._reactiveGraphicLookup=new p,e.length!==0){this._workingFeatures.addMany(e.map(k));for(let e of this._workingFeatures)this._reactiveGraphicLookup.set(e.source,e)}}async _syncAttachments(){let{activeFeature:e,activeLayer:t,activeForm:r}=this;if(!e||!r||!A(t)||!j(t))return;let i=e.getObjectId();if(i==null)return;let a=this._attachmentCache.get(t),o=r.allAttachmentElementInputs;if(!o.length)return;let c=n(async e=>{let n;if(a){let e=a.get(i);e&&(n=e)}n||(n=await M(t,i,o,e),s(this._attachmentCache,t,()=>new p).set(i,n));for(let e of o)e.applyFetchedAttachments(se(e,n))});this._syncAttachmentsTask=c,await d(c.promise)}get test(){return{expressionsManager:this._expressionsManager,reactiveGraphicLookup:this._reactiveGraphicLookup,syncAttachmentsTask:this._syncAttachmentsTask,arcadeExecutorProvider:this._arcadeExecutorProvider,requestDeferredExpressionEvaluation:this._requestDeferredExpressionEvaluation}}};e([y()],Z.prototype,`_attachmentCache`,void 0),e([y({readOnly:!0})],Z.prototype,`activeFeature`,null),e([y()],Z.prototype,`activeFeatureIndex`,void 0),e([y({readOnly:!0})],Z.prototype,`activeForm`,null),e([y({readOnly:!0})],Z.prototype,`activeLayer`,null),e([y()],Z.prototype,`activeAssociation`,null),e([y()],Z.prototype,`activeAssociationsInput`,null),e([y()],Z.prototype,`activeAssociationType`,null),e([y()],Z.prototype,`activeRelationshipInput`,null),e([y()],Z.prototype,`attachmentsEnabled`,void 0),e([y()],Z.prototype,`callbacks`,void 0),e([y()],Z.prototype,`disabled`,void 0),e([y()],Z.prototype,`calculating`,null),e([y()],Z.prototype,`canGoBack`,null),e([y()],Z.prototype,`contingentValuesManager`,void 0),e([y()],Z.prototype,`editType`,void 0),e([y()],Z.prototype,`features`,void 0),e([y()],Z.prototype,`expressionEvaluationFailed`,null),e([y()],Z.prototype,`hasNonActiveInvalidFeatures`,null),e([y()],Z.prototype,`hasAsyncArcadeExpressions`,null),e([y()],Z.prototype,`_hasAsyncArcadeExpressions`,void 0),e([y()],Z.prototype,`invalidFeatures`,null),e([y()],Z.prototype,`hasVisibleInputs`,null),e([y()],Z.prototype,`hasLayersWithContingentValues`,null),e([y()],Z.prototype,`formDescription`,null),e([y()],Z.prototype,`formTitle`,null),e([y()],Z.prototype,`effectiveTimeZone`,null),e([y()],Z.prototype,`highlightHelper`,void 0),e([y()],Z.prototype,`maximumFeatureCount`,void 0),e([y()],Z.prototype,`maximumFeatureCountWithComplexForms`,void 0),e([y()],Z.prototype,`visibleInputs`,null),e([y()],Z.prototype,`map`,null),e([y()],Z.prototype,`noVisibleElementsReason`,null),e([y()],Z.prototype,`page`,null),e([y()],Z.prototype,`pageStack`,void 0),e([y()],Z.prototype,`readOnly`,void 0),e([y()],Z.prototype,`pendingSubtypeChoice`,void 0),e([y()],Z.prototype,`subtypes`,null),e([y()],Z.prototype,`spatialReference`,void 0),e([y()],Z.prototype,`submitHasBeenAttempted`,void 0),e([y()],Z.prototype,`timeZone`,null),e([y()],Z.prototype,`view`,void 0),e([y()],Z.prototype,`updating`,null),e([y()],Z.prototype,`valid`,null),e([y()],Z.prototype,`layers`,null),e([y()],Z.prototype,`mode`,null),e([y()],Z.prototype,`sharedForm`,void 0),e([y()],Z.prototype,`sharedFormTemplate`,void 0),e([y()],Z.prototype,`selectedAttachment`,null),e([y()],Z.prototype,`selectedAttachmentAddElementId`,null),e([y()],Z.prototype,`selectedAttachmentListElementId`,null),e([y()],Z.prototype,`selectedAttachmentListInput`,null),e([y()],Z.prototype,`showingSelectedAttachmentReplacePage`,null),e([y()],Z.prototype,`selectedAttachmentAddInput`,null),e([y()],Z.prototype,`selectedAttachmentDetails`,null),e([y()],Z.prototype,`userHasChangedValues`,void 0),e([y()],Z.prototype,`layerInfos`,void 0),e([y()],Z.prototype,`_arcadeExecutorProvider`,void 0),e([y()],Z.prototype,`_activeAssociation`,void 0),e([y()],Z.prototype,`_activeAssociationsInput`,void 0),e([y()],Z.prototype,`_activeRelationshipInput`,void 0),e([y()],Z.prototype,`_prepareTask`,void 0),e([y()],Z.prototype,`_reactiveGraphicLookup`,void 0),e([y()],Z.prototype,`_allAttachmentInputs`,null),e([y()],Z.prototype,`_hasPendingAttachmentHydration`,null),e([y()],Z.prototype,`_layerTemplateMap`,void 0),e([y()],Z.prototype,`_layersSet`,null),e([y()],Z.prototype,`_workingFeatures`,void 0),e([y()],Z.prototype,`_expressionsManager`,void 0),Z=e([b(`esri.widgets.BatchAttributeForm.BatchAttributeFormViewModel`)],Z);const oe=Z;function Q(e){return e!=null&&e.trim().length>0}function $(e,t){let n=e.keywords;return Q(n)&&n.toLowerCase()===t}function se(e,t){let n=e.input?.type===`attachment`?e.input.attachmentAssociationType:`exact`,r=e.attachmentKeyword;if(n===`any`)return t;if(n===`exactOrNone`){if(X(r))return t.filter(e=>!Q(e.keywords));let e=r.toLowerCase();return t.filter(t=>!Q(t.keywords)||$(t,e))}if(X(r))return t;let i=r.toLowerCase();return t.filter(e=>$(e,i))}export{oe as default};
2
+ import{__decorate as e}from"tslib";import{pushIfSome as t}from"../../core/arrayUtils.js";import{createTask as n}from"../../core/asyncUtils.js";import r from"../../core/Collection.js";import i from"../../core/Error.js";import{EventedAccessor as a}from"../../core/Evented.js";import o from"../../core/Logger.js";import{getOrCreateMapValue as s}from"../../core/MapUtils.js";import{destroyMaybe as c,abortMaybe as l}from"../../core/maybe.js";import{throwIfAborted as u,whenOrAbort as ee,ignoreAbortErrors as d,isAbortError as f}from"../../core/promiseUtils.js";import p from"../../core/ReactiveMap.js";import{on as te,sync as m,watch as h,syncAndInitial as g,initial as _,whenOnce as v}from"../../core/reactiveUtils.js";import{property as y,subclass as b}from"../../core/accessorSupport/decorators.js";import{UpdatingHandles as ne}from"../../core/support/UpdatingHandles.js";import x from"../../geometry/SpatialReference.js";import{getGraphicLayer as S}from"../../graphic/graphicOriginUtils.js";import{isSubtypeGroupLayer as C,isSubtypeSublayer as w,isFeatureLayer as re,getSubtypesFromLayer as ie}from"../../layers/support/layerUtils.js";import{system as T}from"../../time/constants.js";import{getAttachmentKey as E}from"./attachmentUtils.js";import{getLayerTimeZone as D,getEffectiveTimeZone as O,createReactiveGraphic as k,isAttributeFormSupportedLayerWithAttachments as A,layerSupportsAttachments as j,queryAttachmentsForElements as M}from"./batchAttributeFormUtils.js";import{ReactiveContingentValuesManager as N}from"./ReactiveContingentValuesManager.js";import{parseFormTemplateString as P}from"./stringUtils.js";import{ValueChangeTransaction as F}from"./ValueChangeTransaction.js";import{ArcadeExecutorProvider as I}from"./expressions/ArcadeExecutorProvider.js";import{ExpressionsManager as L}from"./expressions/ExpressionsManager.js";import{ExpressionsModel as R}from"./expressions/ExpressionsModel.js";import z from"./inputs/BatchFormInputs.js";import{createBatchFormInputsFromBatchFormTemplate as B,mergeBatchFormInputsFromNewTemplate as V}from"./inputs/support/createBatchFormInputs.js";import{isGroupInput as H,isFieldInput as U}from"./inputs/support/inputUtils.js";import W from"./templates/BatchFormTemplate.js";import{createBatchFormTemplate as G}from"./templates/support/createBatchFormTemplate.js";import{isExcludedFromSharedForm as K,isGroupElementTemplate as q}from"./templates/support/templateUtils.js";import{ContingentValuesManager as J,isLayerWithContingentValues as Y}from"../support/ContingentValuesManager.js";import{isEmptyValue as X}from"../support/forms/formUtils.js";function ae(e,t){return e?.find(e=>e.layer===t)}let Z=class extends a{constructor(e){super(e),this._attachmentCache=new p,this.activeFeatureIndex=-1,this.attachmentsEnabled=!1,this.callbacks=null,this.disabled=!1,this.editType=`NA`,this.features=new r,this._hasAsyncArcadeExpressions=!1,this.highlightHelper=null,this.maximumFeatureCount=2e3,this.maximumFeatureCountWithComplexForms=50,this.pageStack=[],this.readOnly=!1,this.pendingSubtypeChoice=null,this.spatialReference=null,this.submitHasBeenAttempted=!1,this.view=null,this.userHasChangedValues=!1,this.layerInfos=null,this._arcadeExecutorProvider=new I,this._activeAssociation=null,this._activeAssociationsInput=null,this._activeRelationshipInput=null,this._ownContingentValuesManager=null,this._activeFormInputsByElementId=new Map,this._emptyForm=new z({inputs:[]}),this._emptyFormTemplate=new W({elements:[]}),this._featureFormMap=new p,this._prepareTask=null,this._layerTemplateUpdateTask=null,this._syncAttachmentsTask=null,this._reactiveGraphicLookup=new p,this._updatingHandles=new ne,this._submitTask=null,this._layerTemplateMap=new p,this._workingFeatures=new r,this._expressionsManager=new L({arcadeContext:{editType:`NA`,spatialReference:null,map:null,timeZone:T}}),this._getExternalErrorForFeature=(e,t)=>this._reactiveContingentValuesManager.getViolationTypeForField(e,t),this._getFieldValueOptionsForFeature=e=>this._reactiveContingentValuesManager.getAndWatchFieldValueOptions(e),this._requestDeferredExpressionEvaluation=async({features:e,getExecutor:t})=>this._valueChangeTransaction(n=>this._expressionsManager.requestDeferredExecution(e,t,n),`user`),this._executeFeatureSetDependentExpressions=async e=>this._updatingHandles.addPromise(this._valueChangeTransaction(t=>this._expressionsManager.runFeatureSetDependentExpressions(e,t),`user`)),this.sharedForm=this._emptyForm,this.sharedFormTemplate=this._emptyFormTemplate}initialize(){this.contingentValuesManager||=this._ownContingentValuesManager=new J,this.addHandles([te(()=>this.features,`after-changes`,()=>{this.goHome(),this.notifyChange(`layers`),this._prepare()},m),h(()=>[this.attachmentsEnabled,this.features,this.map,this.timeZone,this.editType],()=>this._prepare(),m),h(()=>this.activeForm,()=>{this.goHome(),this._activeFormInputsByElementId.clear(),this._syncAttachments()},m),h(()=>this.activeFeature,()=>{this.goHome()},m),h(()=>this.page,e=>{let t=[...this.pageStack];if(!t.includes(e))t.push(e);else for(;t.length&&t.at(-1)!==e;)t.pop();this.pageStack=t},g),h(()=>this.contingentValuesManager,e=>{c(this._reactiveContingentValuesManager),this._reactiveContingentValuesManager=new N({manager:e})},_)]),this._prepare()}destroy(){this._prepareTask=l(this._prepareTask),this.pendingSubtypeChoice?.reject(),this._layerTemplateUpdateTask=l(this._layerTemplateUpdateTask),this._syncAttachmentsTask=l(this._syncAttachmentsTask),this._workingFeatures.destroyAll(),c(this._expressionsManager),c(this._reactiveContingentValuesManager),this._updatingHandles.destroy(),this._reactiveGraphicLookup=new p,this._emptyForm.destroy(),this._emptyFormTemplate.destroy(),this._ownContingentValuesManager=c(this._ownContingentValuesManager),this.highlightHelper?.removeAll()}get activeFeature(){let e=this.activeFeatureIndex;return e<0?null:this.features.at(e)}get activeForm(){if(this.mode===`batch`)return this.sharedForm;let e=this._workingFeatures.at(this.activeFeatureIndex);if(!e)return this._emptyForm;let t=this._featureFormMap.get(e);if(t)return t;let n=this._makeBatchFormInputsForFeature(e);return n!==this._emptyForm&&this._featureFormMap.set(e,n),n}get activeLayer(){let{activeFeature:e}=this;return e?S(e)??null:null}get activeAssociation(){return this._activeAssociation}get activeAssociationsInput(){return this._activeAssociationsInput}get activeAssociationType(){return this.activeAssociationsInput?.activeAssociationType}get activeRelationshipInput(){return this._activeRelationshipInput}get calculating(){return this._expressionsManager.calculating}get expressionsManager(){return this._expressionsManager}get canGoBack(){return this.pageStack.length>1}get expressionEvaluationFailed(){return this._expressionsManager.expressionEvaluationFailed}get hasNonActiveInvalidFeatures(){if(this.mode===`batch`)return!1;let{activeFeature:e}=this;return this.invalidFeatures.some(t=>t!==e)}get hasAsyncArcadeExpressions(){return this._hasAsyncArcadeExpressions}get hasTooManyFeatures(){return this._workingFeatures.length>this.maximumFeatureCount}get hasTooManyComplexFeatures(){return this._workingFeatures.length>this.maximumFeatureCountWithComplexForms&&this.hasAsyncArcadeExpressions}get invalidFeatures(){return this.sharedForm.invalidFeatures}get hasVisibleInputs(){return this.visibleInputs.length>0}get hasLayersWithContingentValues(){let e=this.contingentValuesManager;for(let t of this.layers)if(e.getFieldsWithContingentValues(t).size>0)return!0;return!1}get formDescription(){return this._computeFormHeaderField(this.activeForm?.description)}get formTitle(){return this._computeFormHeaderField(this.activeForm?.title)}get effectiveTimeZone(){let{activeLayer:e,timeZone:t}=this;if(!e)return t??`system`;let n=D(e);return O(t,n)}get visibleInputs(){return this.activeForm.inputs.filter(e=>e.visible)}get map(){return this.view?.map??null}set map(e){this._override(`map`,e)}get noVisibleElementsReason(){if(this.hasVisibleInputs)return null;if(this.activeForm.inputs.length===0)return`noElements`;let e=new Set;for(let t of this.activeForm.inputs)switch(t.visibilityCode){case`hidden:not-in-all-layers`:case`hidden:no-domain-in-common`:e.add(`noElementsInCommon`);break;case`hidden:field-definition`:case`hidden:group-visibility-expression:all-features`:case`hidden:visibility-expression:all-features`:e.add(`allElementsHidden`);break;case`hidden:group-visibility-expression:some-features`:case`hidden:visibility-expression:some-features`:return`elementsHiddenInSome`}return e.has(`allElementsHidden`)?`allElementsHidden`:`noElementsInCommon`}get page(){return this.showingSelectedAttachmentReplacePage&&this.selectedAttachmentDetails?`replacing-attachment`:this.selectedAttachmentDetails?`viewing-attachment-details`:this.selectedAttachmentAddInput?`adding-attachments`:this.selectedAttachmentListInput?`viewing-attachments`:this.activeAssociationsInput?.associatedLayer?`viewing-associated-features`:this.activeAssociationsInput?`viewing-associated-layers`:this.activeRelationshipInput?.showAllRelatedRecords?`viewing-related-records`:this.activeRelationshipInput?.showAllCategories?`viewing-related-categories`:`default`}get subtypes(){let e=this.activeLayer;return C(e)||w(e)||re(e)?ie(e):[]}get status(){let e=this._prepareTask;return e==null?`not-loaded`:e.finished?e.error==null?`loaded`:`failed`:`loading`}get timeZone(){return this.view?.timeZone??null}set timeZone(e){this._overrideIfSome(`timeZone`,e)}get updating(){return this._updatingHandles.updating||this.calculating}get valid(){return this.sharedForm.valid&&Array.from(this._featureFormMap.values()).every(e=>e.valid)}get layers(){return Array.from(this._layersSet)}get mode(){return this.activeFeatureIndex>-1?`single`:`batch`}submit(){if(this.submitHasBeenAttempted=!0,this.sharedForm.touchAll(),this._featureFormMap.forEach(e=>e.touchAll()),this.validateContingentValues(this._workingFeatures),!this._hasPendingAttachmentHydration)return this._emitSubmit(),Promise.resolve();if(this._submitTask)return this._submitTask.promise;let e=n(async()=>{await Promise.all(this._allAttachmentInputs.map(e=>e.waitForPendingAttachmentUpdateData())),this._emitSubmit()});return this._submitTask=e,e.promise.finally(()=>{this._submitTask===e&&(this._submitTask=null)}),e.promise}get selectedAttachment(){return this._get(`selectedAttachment`)??null}set selectedAttachment(e){this.showingSelectedAttachmentReplacePage=!1,this._set(`selectedAttachment`,e),e!=null&&(this.selectedAttachmentAddElementId=null)}get selectedAttachmentAddElementId(){return this._get(`selectedAttachmentAddElementId`)??null}set selectedAttachmentAddElementId(e){this.showingSelectedAttachmentReplacePage=!1,this._set(`selectedAttachmentAddElementId`,e),e!=null&&(this.selectedAttachment=null,this.selectedAttachmentListElementId=null)}get selectedAttachmentListElementId(){return this._get(`selectedAttachmentListElementId`)??null}set selectedAttachmentListElementId(e){this._set(`selectedAttachmentListElementId`,e),e!=null&&(this.selectedAttachment=null,this.selectedAttachmentAddElementId=null)}get selectedAttachmentListInput(){let e=this.selectedAttachmentListElementId,t=this.activeForm;if(!e||!t)return null;let n=t.allAttachmentElementInputs.find(t=>t.template.elementId===e)||null;return n?.attachments.length?n:null}get showingSelectedAttachmentReplacePage(){return this._get(`showingSelectedAttachmentReplacePage`)??!1}set showingSelectedAttachmentReplacePage(e){this._set(`showingSelectedAttachmentReplacePage`,e&&this.selectedAttachmentDetails!=null)}get selectedAttachmentAddInput(){let e=this.selectedAttachmentAddElementId,t=this.activeForm;return!e||!t?null:t.allAttachmentElementInputs.find(t=>t.template.elementId===e)||null}get selectedAttachmentDetails(){let e=this.selectedAttachment,t=this.activeForm;if(!e||!t)return null;let n=t.allAttachmentElementInputs.find(t=>t.template.elementId===e.elementId);if(!n)return null;let r=n.attachments.findIndex(t=>E(t)===e.attachmentKey);return r===-1?null:{attachment:n.attachments[r],input:n}}get _allAttachmentInputs(){let e=[...this.sharedForm.allAttachmentElementInputs];for(let t of this._featureFormMap.values())e.push(...t.allAttachmentElementInputs);return e}get _hasPendingAttachmentHydration(){return this._allAttachmentInputs.some(e=>e.hasPendingAttachmentUpdateData)}get _layersSet(){let e=new Set;for(let t of this._workingFeatures){let n=S(t.plainGraphic);n&&e.add(n)}return e}applyStashedAttachmentEdits(e){let t=this._allAttachmentInputs;for(let n of e){let e=t.find(e=>e.label===n.label&&e.attachmentKeyword===n.keywords);e&&e.applyStashedEdits(n)}}findFieldInput(e){if(e==null)return;let t=this._activeFormInputsByElementId;if(t.has(e))return t.get(e);let n=this.activeForm.allFieldInputs.find(t=>t.template.elementId===e);if(n!==void 0)return t.set(e,n),n}getFirstVisibleInvalidFieldInput(){if(this.hasVisibleInputs&&!this.activeForm.valid)for(let e of this.visibleInputs){if(H(e)){let t=e.inputs.find(e=>U(e)&&!e.valid);if(t)return{input:t,groupInput:e}}if(U(e)&&!e.valid)return{input:e}}}getFieldInputValue(e){return this.findFieldInput(e)?.value}getValues(e){let t=this._reactiveGraphicLookup.get(e);if(!t)throw new i(`feature-not-found`,`The given feature is not present in the BatchAttributeForm`);return{...t.attributes}}async goBack(){switch(this.page){case`replacing-attachment`:this.setShowingSelectedAttachmentReplacePage(!1);return;case`viewing-attachment-details`:this.setSelectedAttachment(null);return;case`adding-attachments`:this.setSelectedAttachmentAddElementId(null);return;case`viewing-attachments`:this.setSelectedAttachmentListElementId(null);return;case`viewing-associated-features`:this.setActiveAssociationsLayer(null);return;case`viewing-associated-layers`:this.setActiveAssociationsInput(null);return;case`viewing-related-categories`:case`viewing-related-records`:this.clearActiveRelationshipCategoryOrInput();return;default:return}}async goHome(){this.setShowingSelectedAttachmentReplacePage(!1),this.setSelectedAttachment(null),this.setSelectedAttachmentAddElementId(null),this.setSelectedAttachmentListElementId(null),this.setActiveAssociationsLayer(null),this.setActiveAssociationsInput(null),this.clearAllRelationshipSettings()}notifyGeometriesChanged(e){let t=[];for(let n of e){let e=this._reactiveGraphicLookup.get(n);e&&(t.push(e),e.geometry=n.geometry)}this._updatingHandles.consumePromise(this._valueChangeTransaction(async e=>this._expressionsManager.runGeometryDependentExpressions(t,e),`user`))}async overrideOriginalFeature(e,t){await this._prepareTask?.promise;let n=this._reactiveGraphicLookup.get(e);n&&(n.original=t,this._updatingHandles.consumePromise(this._valueChangeTransaction(e=>this._expressionsManager.runOriginalFeatureDependentExpressions(n,e),`expression`)))}async setFieldInputValue(e,t){let{fieldName:n}=e;await this._updatingHandles.addPromise(this._valueChangeTransaction(async r=>{for(let i of e.features)r.setValue(i,n,t)},`user`,e))}async setFieldInputValuePerFeature(e,t){await this._updatingHandles.addPromise(this._valueChangeTransaction(async n=>{for(let[r,i]of t)n.setValue(r,e.fieldName,i);n.hasChanges&&(e.userHasChangedValue=!0)},`user`,e))}async setValueForFieldName(e,t,n){await this._updatingHandles.addPromise(this._valueChangeTransaction(async r=>{for(let i of n){let n=this._reactiveGraphicLookup.get(i);n&&r.setValue(n,e,t)}},`user`,e))}async setValuePerFeatureForFieldName(e,t){await this._updatingHandles.addPromise(this._valueChangeTransaction(async n=>{for(let[r,i]of t){let t=this._reactiveGraphicLookup.get(r);t&&n.setValue(t,e,i)}},`user`,e))}async setFieldValue(e,t){let n=this.activeForm.allFieldInputs.find(t=>t.fieldName===e);if(n==null)throw new i(`no-field-input-found`,`Cannot set the value of FieldInput with field name: ${e} because none was found in the active form`);await this.setFieldInputValue(n,t)}async setValue(e,t){let n=this.findFieldInput(e);if(n==null)throw new i(`no-FieldInput-found`,`Cannot set the value of FieldInput with ID: ${e} because none was found in the active form`);await this.setFieldInputValue(n,t)}async applySubtypeDefaults(e){let{defaultValues:t}=e,{allFieldInputs:n}=this.activeForm;await this._updatingHandles.addPromise(this._valueChangeTransaction(async e=>{for(let r of n){let{fieldName:n}=r,i=t[n];if(i!=null)for(let t of r.features)e.setValue(t,n,i)}},`user`))}async handleSubtypeChanged(e){let t=this._workingFeatures.at(e);if(t)return this._updatingHandles.addPromise(this._handleSubtypeChanged(t))}async stageAddAttachments(e,t){if(t.length===0)return[];let n=this._findAttachmentInput(e);if(!n)return[];let r=await this._updatingHandles.addPromise(n.stageAddAttachments(t,this._expressionsManager.arcadeContext));return r.length===0?r:(this.userHasChangedValues=!0,this._emitAttachmentsChange(n),r)}stageDeleteAttachment(e,t){let n=this._findAttachmentInput(e);if(!n)return;let r=this._findAttachment(n,t);r&&(n.stageDeleteAttachment(r),this.userHasChangedValues=!0,this._emitAttachmentsChange(n))}async stageRenameAttachment(e,t,n){let r=this._findAttachmentInput(e);if(!r)return;let i=this._findAttachment(r,t);i&&(r.stageRenameAttachment(i,n.trim()),this.userHasChangedValues=!0,await r.ensureStagedUpdateData(i),this._emitAttachmentsChange(r))}async stageReplaceAttachment(e,t,n){let r=this._findAttachmentInput(e);if(!r)return!1;let i=this._findAttachment(r,t);return!i||!await this._updatingHandles.addPromise(r.stageReplaceAttachment(i,n,this._expressionsManager.arcadeContext))?!1:(this.userHasChangedValues=!0,this._emitAttachmentsChange(r),!0)}clearAttachmentChanges(e){let t=this._findAttachmentInput(e);t&&(t.clearAttachmentChanges(),this._emitAttachmentsChange(t))}setActiveAssociation(e){this._activeAssociation=e}setActiveAssociationsInput(e){this._activeAssociationsInput=e}setActiveAssociationsLayer(e){this._activeAssociationsInput?.setAssociatedLayer(e)}setActiveAssociationType(e){this._activeAssociationsInput?.setActiveAssociationType(e)}setActiveRelationshipInput(e){e||this._activeRelationshipInput?.setActiveCategory(null),this._activeRelationshipInput=e}setActiveRelationshipCategory(e,t){t.setActiveCategory(e),this.setActiveRelationshipInput(t)}clearAllRelationshipSettings(){let e=this.activeRelationshipInput;e&&(e.setActiveCategory(null),e.setShowAllCategories(!1),e.setShowAllRelatedRecords(!1),this._activeRelationshipInput=null)}clearActiveRelationshipCategoryOrInput(){let e=this.activeRelationshipInput;e&&(e.showAllRelatedRecords?e.showAllCategories?e.setActiveCategory(null):this.setActiveRelationshipInput(null):e.showAllCategories&&(e.setShowAllCategories(!1),this.setActiveRelationshipInput(null)))}resetAttachmentChanges(e,t){let n=this._findAttachmentInput(e);if(!n||!n.editable)return;let r=this._findAttachment(n,t);r&&(n.discardStagedEdits(r),this._emitAttachmentsChange(n))}setSelectedAttachment(e){this.selectedAttachment=e??null}setShowingSelectedAttachmentReplacePage(e){this.showingSelectedAttachmentReplacePage=e}setSelectedAttachmentAddElementId(e){this.selectedAttachmentAddElementId=e??null}setSelectedAttachmentListElementId(e){this.selectedAttachmentListElementId=e??null}userChangesHaveMadeFeatureInvalid(e){return!!this._reactiveGraphicLookup.get(e)?.userChangesHaveMadeInvalid}validate(){return!1}validateContingentValues(e,t=!1){if(t&&!this.submitHasBeenAttempted)for(let t of e)this._reactiveContingentValuesManager.validateContingenciesForNonNullFields(t);else for(let t of e)this._reactiveContingentValuesManager.validateContingencyConstraints(t,{includeIncompleteViolations:!0})}_makeBatchFormInputsForFeature(e){let t=this._layerTemplateMap.get(e.layer);return t?B(t,{allFeatures:new r([e]),expressionsManager:this._expressionsManager,requestDeferredExpressionEvaluation:this._requestDeferredExpressionEvaluation,executeFeatureSetDependentExpressions:this._executeFeatureSetDependentExpressions,getExternalErrorForFeature:this._getExternalErrorForFeature,getFieldValueOptionsForFeature:this._getFieldValueOptionsForFeature,map:this.map}):this._emptyForm}async _ensureLayerTemplate(e,t){let{_layersSet:n,contingentValuesManager:r}=this,i=e.layer,a=!1;for(let e of this._layerTemplateMap.keys())n.has(e)||(this._layerTemplateMap.delete(e),this._expressionsManager.layerExpressionsModelMap.delete(e),r.resetOptionsForLayer(e),Y(e)&&r.resetViolationsForLayer(e),a=!0);this._layerTemplateMap.has(i)||(await this._prepareLayer(i,t),u(t),r.layers.add(i),a=!0),a&&(this._prepareSharedFormTemplate(),V(this.sharedForm,this.sharedFormTemplate,{allFeatures:this._workingFeatures,expressionsManager:this._expressionsManager,getFieldValueOptionsForFeature:this._getFieldValueOptionsForFeature,requestDeferredExpressionEvaluation:this._requestDeferredExpressionEvaluation,executeFeatureSetDependentExpressions:this._executeFeatureSetDependentExpressions,map:this.map}),this._recomputeHasAsyncArcadeExpressions(),await v(()=>!r.updating,t))}_recomputeHasAsyncArcadeExpressions(){this._hasAsyncArcadeExpressions=!1;for(let e of this._expressionsManager.layerExpressionsModelMap.values())for(let t of e.arcadeExecutorUses.keys())if(t.isAsync){this._hasAsyncArcadeExpressions=!0;return}}_computeFormHeaderField(e){let{activeFeature:t,activeLayer:n}=this;return!e||!n||!t?null:P({attributes:t?.attributes,label:e,layer:n,timeZone:this.effectiveTimeZone})}_makeSubmitResults(){let e=new Map;for(let[n,r]of this._reactiveGraphicLookup){let i=[],a=[],o=this._featureFormMap.get(r)?.allAttachmentElementInputs??[];for(let e of o)t(i,e.toSubmitEdits()),e.valid||a.push(e.template.elementId);e.set(n,{feature:n,values:{...r.attributes},invalidFields:[],attachmentEdits:i,invalidAttachmentElementIds:a})}for(let t of this.sharedForm.allFieldInputs)for(let n of t.invalidFeatures)e.get(n)?.invalidFields.push(t.fieldName);return Array.from(e.values())}async _handleSubtypeChanged(e){let t=e.layer;if(this.contingentValuesManager.resetOptionsForFeature(t,e.plainGraphic),Y(t)&&this.contingentValuesManager.resetViolationsForFeature(t,e.plainGraphic),!w(t))return;let r=t.parent?.findSublayerForFeature(e.plainGraphic);if(!r)return;this._layerTemplateUpdateTask=l(this._layerTemplateUpdateTask);let i=n(async t=>{u(t),e.source.sourceLayer=r,e.source.origin=r.graphicOrigin,await this._ensureLayerTemplate(e,t),u(t),this._featureFormMap.get(e)?.destroy(),this._featureFormMap.set(e,this._makeBatchFormInputsForFeature(e)),await ee(this._valueChangeTransaction(t=>this._expressionsManager.runAllExpressions([e],t),`user`),t),u(t)});this._layerTemplateUpdateTask=i,await d(this._updatingHandles.addPromise(i.promise))}_emitSubmit(){this.emit(`submit`,{name:`submit`,results:this._makeSubmitResults(),valid:this.valid})}_findAttachmentInput(e){let t=this.activeForm.allAttachmentElementInputs.find(t=>t.template.elementId===e);return t||o.getLogger(this).error(`Attachment input not found for elementId '${e}'`),t}_findAttachment(e,t){let n=e.findAttachment(t);return n||o.getLogger(this).error(`Attachment '${t}' not found for attachment element '${e.template.elementId}'`),n}_makeAttachmentEdits(e){let n=[];for(let r of e.allAttachmentElementInputs)t(n,r.toSubmitEdits());return n}_emitAttachmentsChange(e){let t=e.single.feature;if(!t)return;let n=this._featureFormMap.get(t);this.emit(`attachments-change`,{name:`attachments-change`,feature:t.source,attachmentEdits:this._makeAttachmentEdits(n??this.activeForm),valid:this.valid})}async _valueChangeTransaction(e,t,n){let r=typeof n==`string`?n:n?.fieldName,i=new F(this,t,r);if(await e(i),t===`user`&&await this._expressionsManager.runExpressionsDependentOnChangedFields(i),await i.close(),i.hasChanges&&n){let e=typeof n==`string`?this.activeForm.allFieldInputs.find(e=>e.fieldName===n):n;e&&(e.userHasChangedValue=!0)}}_prepare(){this.pendingSubtypeChoice?.reject(),this._hasAsyncArcadeExpressions=!1,this._prepareTask=l(this._prepareTask),this._layerTemplateUpdateTask=l(this._layerTemplateUpdateTask),this._layerTemplateMap.clear(),this._updateWorkingFeatures(),c(this._expressionsManager),this.userHasChangedValues=!1,this._expressionsManager=new L({arcadeContext:{editType:this.editType,spatialReference:this.spatialReference??x.WebMercator,map:this.map,timeZone:this.timeZone||`system`}});let{layers:e}=this;if(e.length===0)return;let t=n(async t=>{try{u(t),this._updateWorkingFeatures(),this.contingentValuesManager.layers.addMany(e),await Promise.all(e.map(e=>e.load()));for(let n of e)await this._prepareLayer(n,t);if(this.hasTooManyComplexFeatures)throw new i(`too-many-features-with-complex-forms`,`There are too many features to load into the form with the configured complexity`);if(this.hasTooManyFeatures)throw new i(`too-many-features`,`There are too many features to load into the form.`);this._prepareSharedFormTemplate(),this.sharedForm=B(this.sharedFormTemplate,{allFeatures:this._workingFeatures,expressionsManager:this._expressionsManager,getExternalErrorForFeature:this._getExternalErrorForFeature,getFieldValueOptionsForFeature:this._getFieldValueOptionsForFeature,map:this.map,requestDeferredExpressionEvaluation:this._requestDeferredExpressionEvaluation,executeFeatureSetDependentExpressions:this._executeFeatureSetDependentExpressions}),await this._valueChangeTransaction(async e=>await this._expressionsManager.runAllExpressions(this._workingFeatures.toArray(),e),`expression`),await v(()=>!this.contingentValuesManager.updating)}catch(e){throw f(e)||o.getLogger(this).error(`Failed preparing form`,e),e}});this._updatingHandles.consumePromise(t.promise),this._prepareTask=t}async _prepareLayer(e,t){let n=ae(this.layerInfos,e),r=await G(e,{arcadeExecutorProvider:this._arcadeExecutorProvider,formTimeZone:this.timeZone,attachmentsEnabled:this.attachmentsEnabled},n?.formTemplate);u(t),this._layerTemplateMap.set(e,r);let i=r.getExpressionExecutorsForLayer(e);if(this._expressionsManager.layerExpressionsModelMap.set(e,new R({preserveFieldValuesWhenHidden:r.preserveFieldValuesWhenHidden,executorMap:i,fieldsIndex:e.fieldsIndex})),!this._hasAsyncArcadeExpressions){for(let e of i.values())if(e&&(this._hasAsyncArcadeExpressions=(e.editableExpression?.isAsync||e.requiredExpression?.isAsync||e.valueExpression?.isAsync||e.visibilityExpression?.isAsync)===!0,this._hasAsyncArcadeExpressions))break}}_prepareSharedFormTemplate(){let e=new Map;for(let t of this._layerTemplateMap.values())for(let n of t.elements){if(K(n))continue;let t=n.clone();q(t)&&(t.elements=t.elements.filter(e=>!K(e)));let{elementId:r}=t;e.has(r)?e.get(r).foldIn(t):e.set(r,t)}this.sharedFormTemplate=new W({elements:Array.from(e.values())})}_updateWorkingFeatures(){this._workingFeatures.destroyAll(),this._reactiveContingentValuesManager.reset();for(let e of this._featureFormMap.values())e.destroy();this._featureFormMap.clear(),this._attachmentCache.clear();let{features:e}=this;if(this._reactiveGraphicLookup=new p,e.length!==0){this._workingFeatures.addMany(e.map(k));for(let e of this._workingFeatures)this._reactiveGraphicLookup.set(e.source,e)}}async _syncAttachments(){let{activeFeature:e,activeLayer:t,activeForm:r}=this;if(!e||!r||!A(t)||!j(t))return;let i=e.getObjectId();if(i==null)return;let a=this._attachmentCache.get(t),o=r.allAttachmentElementInputs;if(!o.length)return;let c=n(async e=>{let n;if(a){let e=a.get(i);e&&(n=e)}n||(n=await M(t,i,o,e),s(this._attachmentCache,t,()=>new p).set(i,n));for(let e of o)e.applyFetchedAttachments(se(e,n))});this._syncAttachmentsTask=c,await d(c.promise)}get test(){return{expressionsManager:this._expressionsManager,reactiveGraphicLookup:this._reactiveGraphicLookup,syncAttachmentsTask:this._syncAttachmentsTask,arcadeExecutorProvider:this._arcadeExecutorProvider,requestDeferredExpressionEvaluation:this._requestDeferredExpressionEvaluation,executeAsyncExpressions:this._executeFeatureSetDependentExpressions}}};e([y()],Z.prototype,`_attachmentCache`,void 0),e([y({readOnly:!0})],Z.prototype,`activeFeature`,null),e([y()],Z.prototype,`activeFeatureIndex`,void 0),e([y({readOnly:!0})],Z.prototype,`activeForm`,null),e([y({readOnly:!0})],Z.prototype,`activeLayer`,null),e([y()],Z.prototype,`activeAssociation`,null),e([y()],Z.prototype,`activeAssociationsInput`,null),e([y()],Z.prototype,`activeAssociationType`,null),e([y()],Z.prototype,`activeRelationshipInput`,null),e([y()],Z.prototype,`attachmentsEnabled`,void 0),e([y()],Z.prototype,`callbacks`,void 0),e([y()],Z.prototype,`disabled`,void 0),e([y()],Z.prototype,`calculating`,null),e([y()],Z.prototype,`canGoBack`,null),e([y()],Z.prototype,`contingentValuesManager`,void 0),e([y()],Z.prototype,`editType`,void 0),e([y()],Z.prototype,`features`,void 0),e([y()],Z.prototype,`expressionEvaluationFailed`,null),e([y()],Z.prototype,`hasNonActiveInvalidFeatures`,null),e([y()],Z.prototype,`hasAsyncArcadeExpressions`,null),e([y()],Z.prototype,`_hasAsyncArcadeExpressions`,void 0),e([y()],Z.prototype,`invalidFeatures`,null),e([y()],Z.prototype,`hasVisibleInputs`,null),e([y()],Z.prototype,`hasLayersWithContingentValues`,null),e([y()],Z.prototype,`formDescription`,null),e([y()],Z.prototype,`formTitle`,null),e([y()],Z.prototype,`effectiveTimeZone`,null),e([y()],Z.prototype,`highlightHelper`,void 0),e([y()],Z.prototype,`maximumFeatureCount`,void 0),e([y()],Z.prototype,`maximumFeatureCountWithComplexForms`,void 0),e([y()],Z.prototype,`visibleInputs`,null),e([y()],Z.prototype,`map`,null),e([y()],Z.prototype,`noVisibleElementsReason`,null),e([y()],Z.prototype,`page`,null),e([y()],Z.prototype,`pageStack`,void 0),e([y()],Z.prototype,`readOnly`,void 0),e([y()],Z.prototype,`pendingSubtypeChoice`,void 0),e([y()],Z.prototype,`subtypes`,null),e([y()],Z.prototype,`spatialReference`,void 0),e([y()],Z.prototype,`submitHasBeenAttempted`,void 0),e([y()],Z.prototype,`timeZone`,null),e([y()],Z.prototype,`view`,void 0),e([y()],Z.prototype,`updating`,null),e([y()],Z.prototype,`valid`,null),e([y()],Z.prototype,`layers`,null),e([y()],Z.prototype,`mode`,null),e([y()],Z.prototype,`sharedForm`,void 0),e([y()],Z.prototype,`sharedFormTemplate`,void 0),e([y()],Z.prototype,`selectedAttachment`,null),e([y()],Z.prototype,`selectedAttachmentAddElementId`,null),e([y()],Z.prototype,`selectedAttachmentListElementId`,null),e([y()],Z.prototype,`selectedAttachmentListInput`,null),e([y()],Z.prototype,`showingSelectedAttachmentReplacePage`,null),e([y()],Z.prototype,`selectedAttachmentAddInput`,null),e([y()],Z.prototype,`selectedAttachmentDetails`,null),e([y()],Z.prototype,`userHasChangedValues`,void 0),e([y()],Z.prototype,`layerInfos`,void 0),e([y()],Z.prototype,`_arcadeExecutorProvider`,void 0),e([y()],Z.prototype,`_activeAssociation`,void 0),e([y()],Z.prototype,`_activeAssociationsInput`,void 0),e([y()],Z.prototype,`_activeRelationshipInput`,void 0),e([y()],Z.prototype,`_prepareTask`,void 0),e([y()],Z.prototype,`_reactiveGraphicLookup`,void 0),e([y()],Z.prototype,`_allAttachmentInputs`,null),e([y()],Z.prototype,`_hasPendingAttachmentHydration`,null),e([y()],Z.prototype,`_layerTemplateMap`,void 0),e([y()],Z.prototype,`_layersSet`,null),e([y()],Z.prototype,`_workingFeatures`,void 0),e([y()],Z.prototype,`_expressionsManager`,void 0),Z=e([b(`esri.widgets.BatchAttributeForm.BatchAttributeFormViewModel`)],Z);const oe=Z;function Q(e){return e!=null&&e.trim().length>0}function $(e,t){let n=e.keywords;return Q(n)&&n.toLowerCase()===t}function se(e,t){let n=e.input?.type===`attachment`?e.input.attachmentAssociationType:`exact`,r=e.attachmentKeyword;if(n===`any`)return t;if(n===`exactOrNone`){if(X(r))return t.filter(e=>!Q(e.keywords));let e=r.toLowerCase();return t.filter(t=>!Q(t.keywords)||$(t,e))}if(X(r))return t;let i=r.toLowerCase();return t.filter(e=>$(e,i))}export{oe as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../core/Accessor.js";import n from"../../../core/Error.js";import r from"../../../core/Logger.js";import{getOrCreateMapValue as i}from"../../../core/MapUtils.js";import{whenOrAbort as a,settleWithPromise as o}from"../../../core/promiseUtils.js";import s from"../../../core/ReactiveMap.js";import{addMany as c,first as l}from"../../../core/SetUtils.js";import{property as u,subclass as d}from"../../../core/accessorSupport/decorators.js";import{makeArcadeContext as f,castArcadeValue as p,isDeferredExpressionType as m}from"./expressionUtils.js";import{makeUseId as h}from"../inputs/support/inputUtils.js";import{isFieldElementTemplate as g,isGroupElementTemplate as _}from"../templates/support/templateUtils.js";let v=null;const y=()=>r.getLogger(`esri.widgets.BatchAttributeForm.expressions.ExpressionsManager`);let b=class extends t{constructor(e){super(e),this.calculating=!1,this.arcadeContext=null,this._abortController=new AbortController,this.layerExpressionsModelMap=new Map,this.outcomes=new s,this.expressionEvaluationFailed=!1}destroy(){this.abort()}abort(){this._abortController.abort()}async runAllExpressions(e,t){return this._evaluateSpecifiedExecutorsForEachFeature(e,S,t)}async requestDeferredExecution(e,t,n){return this._evaluateSpecifiedExecutorsForEachFeature(e,(e,n)=>{let r=t(n);return r?[r]:[]},n,!0)}async runGeometryDependentExpressions(e,t){return this._evaluateSpecifiedExecutorsForEachFeature(e,C,t)}async runOriginalFeatureDependentExpressions(e,t){return this._evaluateSpecifiedExecutorsForEachFeature([e],w,t)}async runExpressionsDependentOnChangedFields(e){try{this.calculating=!0;let t=Array.from(e.changes).map(([t,n])=>this.runExpressionsDependentOnChangedFieldsForFeature([...n.keys()],t,e));O(await Promise.allSettled(t))}catch(e){y().error(e),this.expressionEvaluationFailed=!0}finally{this.calculating=!1}}async runExpressionsDependentOnChangedFieldsForFeature(e,t,n){if(this._abortController.signal.aborted)return;let r=this.layerExpressionsModelMap.get(t.layer);if(!r||r.components.length===0)return;let i=E(r,e);i.length!==0&&await this.evaluateAffectedExecutors([...i],t,r,n)}async evaluateAffectedExecutors(e,t,n,r,o=!1){let c=new Map,l=i(this.outcomes,t,()=>new s);for(let r of e){if(!o){let e=P(r,l,n);e&&(e.invalidated=!0)}let e=n.dependencyGraphComponents.get(r);e&&i(c,e,()=>this.createSccEvaluator({scc:e,feature:t,evaluatorMap:c,expressionModel:n}))}let u=[...c.values()],d={transaction:r,previousOutcomes:new s,isDeferred:o},f=u.map(e=>e.evaluate(d));O(await a(Promise.allSettled(f),this._abortController))}createSccEvaluator({scc:e,feature:t,evaluatorMap:n,expressionModel:r}){let a=i(this.outcomes,t,()=>new s),o=new x(e,t,this.arcadeContext,r,a,this._abortController);for(let a of e.adjacencyList)i(n,a,()=>this.createSccEvaluator({scc:a,feature:t,evaluatorMap:n,expressionModel:r})).dependencies.push(o);return o}async _evaluateSpecifiedExecutorsForEachFeature(e,t,n,r=!1){r||(this.calculating=!0);try{let i=[];for(let a of e){let{layer:e}=a,o=this.layerExpressionsModelMap.get(e);o&&o.components.length!==0&&i.push(this.evaluateAffectedExecutors(t(o,e),a,o,n,r))}O(await a(Promise.allSettled(i),this._abortController))}catch(e){y().error(e),this.expressionEvaluationFailed=!0}finally{this.calculating=!1}}};e([u()],b.prototype,`calculating`,void 0),e([u({constructOnly:!0})],b.prototype,`arcadeContext`,void 0),e([u()],b.prototype,`_abortController`,void 0),e([u()],b.prototype,`layerExpressionsModelMap`,void 0),e([u()],b.prototype,`outcomes`,void 0),e([u()],b.prototype,`expressionEvaluationFailed`,void 0),b=e([d(`esri.widgets.BatchAttributeForm.expressions.ExpressionsManager`)],b);class x{constructor(e,t,n,r,i,a){this.scc=e,this.feature=t,this.arcadeContextInfo=n,this.expressionsModel=r,this.outcomes=i,this._abortController=a,this._resolver=null,this.dependencies=[]}get baseContext(){return f(this.arcadeContextInfo,this.feature,this._abortController.signal)}evaluate(e){return this._resolver||(this._resolver=Promise.withResolvers(),o(this._resolver,this._evaluate(e))),this._resolver.promise}async _evaluate(e){v===null&&(v=await import(`../../../arcade/languageUtils.js`));let t=[],n=this.dependencies.map(t=>t.evaluate(e));O(await a(Promise.allSettled(n),this._abortController));let{executors:r}=this.scc;if(r.size===1?await this._evaluateSingleExecutorComponent({context:e,executor:l(r),errorsToReport:t}):await this._evaluateMultiExecutorComponent({context:e,errorsToReport:t}),t.length>0)throw D(t)}async _evaluateMultiExecutorComponent({context:e,errorsToReport:t}){let{transaction:n}=e,r=new Map,i=!0,a=0;for(;i&&a<3;){i=!1,a++;for(let a of this.scc.executors){let o=this._findOutcome(a)??{status:`not-run`,invalidated:!0};o.invalidated||=this._invalidatedSinceCheckpoint(a,n,r.get(a)),this._shouldEvaluate(a,o,e)&&(i=!0,r.set(a,n.currentCheckpoint),await this._performEvaluation({context:e,executor:a,errorsToReport:t}))}}}async _evaluateSingleExecutorComponent({context:e,executor:t,errorsToReport:n}){let r=this._findOutcome(t)??{status:`not-run`,invalidated:!0};r.invalidated||=this._invalidatedSinceCheckpoint(t,e.transaction),this._shouldEvaluate(t,r,e)&&await this._performEvaluation({context:e,executor:t,errorsToReport:n})}async _performEvaluation({context:e,executor:t,errorsToReport:r}){let{variables:i,executeContext:a}=this.baseContext,o=null,s=null;try{o=t.isAsync?await t.executeAsync(i,a):t.execute(i,a),s={result:o,status:`success`}}catch(e){s={error:e,status:`error`}}let{transaction:c,previousOutcomes:l}=e,{outcomes:u}=this,d=this.expressionsModel.arcadeExecutorUses.get(t)??[];for(let t of d){let n=h(t),r=u.get(n);r&&l.set(n,r),u.set(h(t),s);let i=this.expressionsModel.elementTemplateMap.get(t.elementId);switch(t.executorPurpose){case`editableExpression`:if(s.result===!1&&r?.result!==!1){let e=u.get(h({elementId:i.elementId,executorPurpose:`valueExpression`}));if(e){let{fieldName:t}=i,n=T(this.feature,t),r=p(e.result,n,this.arcadeContextInfo.timeZone,v);c.setValue(this.feature,t,r)}}break;case`valueExpression`:{if(s?.status===`error`)continue;let e=i.getExpressionExecutorsForLayer(this.feature.layer),t=!0;if(e?.editableExpression&&(t=u.get(h({elementId:i.elementId,executorPurpose:`editableExpression`}))?.result===!1),t){let e=i.fieldName,t=this.feature.getAttribute(e)??null;try{let n=T(this.feature,e),r=p(s.result,n,this.arcadeContextInfo.timeZone,v);r!==t&&c.setValue(this.feature,e,r)}catch(t){y().error(`Failed to set calculated value for field '${e}'`,t)}}}break;case`visibilityExpression`:!this.expressionsModel.preserveFieldValuesWhenHidden&&r?.result===!0&&s.result===!1&&c.originActor===`user`&&k(i,this.feature,u,e)}}if(s?.status===`error`){let e=new Set;for(let t of d){let n=this.expressionsModel.elementTemplateMap.get(t.elementId);if(n)switch(t.executorPurpose){case`editableExpression`:e.add(n.label+` - Editable expression`);break;case`requiredExpression`:e.add(n.label+` - Required expression`);break;case`valueExpression`:e.add(n.label+` - Value expression`);break;case`visibilityExpression`:e.add(n.label+` - Visibility expression`)}}r.push(e.size>0?new n(`expression-evaluation-failed`,`Arcade evaluation failed (`+[...e].join(`,`)+`)`):new n(`expression-evaluation-failed`,`Arcade evaluation failed `))}}_invalidatedSinceCheckpoint(e,t,n=-1){let r=t.changesForFeature(this.feature);return!r||r.size===0?!1:this.scc.getFieldsReferenced(e).values().some(e=>r.has(e)&&r.get(e)>n)}_shouldEvaluate(e,t,{isDeferred:n}){return this._abortController.signal.aborted||F(this.expressionsModel.arcadeExecutorUses.get(e))&&!n?!1:!!t.invalidated}_findOutcome(e){return P(e,this.outcomes,this.expressionsModel)}}function S(e){return Array.from(e.dependencyGraphComponents.keys())}function C(e){return Array.from(e.geometryReferences)}function w(e){return Array.from(e.originalFeatureReferences)}function T(e,t){let r=e.layer.fieldsIndex.get(t);if(!r)throw new n(`field-not-found`,`Field '${t}' not found on layer.`);return r}function E(e,t){let n=new Set;for(let r of t)c(n,e.fieldReferencesMap.get(r));return Array.from(n)}function D(e){return AggregateError(e,`One or more expression executions failed. First error message: ${e[0].message}`)}function O(e){let t=[],n=new Set;for(let r of e){if(r.status===`fulfilled`)continue;let e=r.reason instanceof AggregateError?r.reason.errors:[r.reason];for(let r of e)n.has(r)||(n.add(r),t.push(r))}if(t.length>0)throw D(t)}function k(e,t,n,r){g(e)?A(e,t,n,r):_(e)&&j(e,t,n,r)}function A(e,t,n,r){let{group:i}=e;(!i||N(i,n,r.previousOutcomes))&&M(t,e,r)}function j(e,t,n,r){for(let i of e.elements)g(i)&&N(i,n,r.previousOutcomes)&&M(t,i,r)}function M(e,{fieldName:t},n){n.transaction.setValue(e,t,null)}function N(e,t,n){let r=h({elementId:e.elementId,executorPurpose:`visibilityExpression`}),i=n.get(r)??t.get(r);return!i||!!i.result}function P(e,t,n){let r=n.arcadeExecutorUses.get(e);if(r)for(let e of r){let n=t.get(h(e));if(n)return n}}function F(e){return e?.every(e=>m(e.executorPurpose))??!1}export{b as ExpressionsManager};
2
+ import{__decorate as e}from"tslib";import t from"../../../core/Accessor.js";import n from"../../../core/Error.js";import r from"../../../core/Logger.js";import{getOrCreateMapValue as i}from"../../../core/MapUtils.js";import{whenOrAbort as a,settleWithPromise as o}from"../../../core/promiseUtils.js";import s from"../../../core/ReactiveMap.js";import{addMany as c,first as l}from"../../../core/SetUtils.js";import{property as u,subclass as d}from"../../../core/accessorSupport/decorators.js";import{makeArcadeContext as f,castArcadeValue as p,isDeferredExpressionType as m}from"./expressionUtils.js";import{makeUseId as h}from"../inputs/support/inputUtils.js";import{isFieldElementTemplate as g,isGroupElementTemplate as _}from"../templates/support/templateUtils.js";let v=null;const y=()=>r.getLogger(`esri.widgets.BatchAttributeForm.expressions.ExpressionsManager`);let b=class extends t{constructor(e){super(e),this.calculating=!1,this.arcadeContext=null,this._abortController=new AbortController,this.layerExpressionsModelMap=new Map,this.outcomes=new s,this.expressionEvaluationFailed=!1}destroy(){this.abort()}abort(){this._abortController.abort()}async runAllExpressions(e,t){return this._evaluateSpecifiedExecutorsForEachFeature(e,S,t)}async requestDeferredExecution(e,t,n){return this._evaluateSpecifiedExecutorsForEachFeature(e,(e,n)=>{let r=t(n);return r?[r]:[]},n,!0)}async runFeatureSetDependentExpressions(e,t){return this._evaluateSpecifiedExecutorsForEachFeature(e,C,t)}async runGeometryDependentExpressions(e,t){return this._evaluateSpecifiedExecutorsForEachFeature(e,w,t)}async runOriginalFeatureDependentExpressions(e,t){return this._evaluateSpecifiedExecutorsForEachFeature([e],T,t)}async runExpressionsDependentOnChangedFields(e){try{this.calculating=!0;let t=Array.from(e.changes).map(([t,n])=>this.runExpressionsDependentOnChangedFieldsForFeature([...n.keys()],t,e));k(await Promise.allSettled(t))}catch(e){y().error(e),this.expressionEvaluationFailed=!0}finally{this.calculating=!1}}async runExpressionsDependentOnChangedFieldsForFeature(e,t,n){if(this._abortController.signal.aborted)return;let r=this.layerExpressionsModelMap.get(t.layer);if(!r||r.components.length===0)return;let i=D(r,e);i.length!==0&&await this.evaluateAffectedExecutors([...i],t,r,n)}async evaluateAffectedExecutors(e,t,n,r,o=!1){let c=new Map,l=i(this.outcomes,t,()=>new s);for(let r of e){if(!o){let e=F(r,l,n);e&&(e.invalidated=!0)}let e=n.dependencyGraphComponents.get(r);e&&i(c,e,()=>this.createSccEvaluator({scc:e,feature:t,evaluatorMap:c,expressionModel:n}))}let u=[...c.values()],d={transaction:r,previousOutcomes:new s,isDeferred:o},f=u.map(e=>e.evaluate(d));k(await a(Promise.allSettled(f),this._abortController))}createSccEvaluator({scc:e,feature:t,evaluatorMap:n,expressionModel:r}){let a=i(this.outcomes,t,()=>new s),o=new x(e,t,this.arcadeContext,r,a,this._abortController);for(let a of e.adjacencyList)i(n,a,()=>this.createSccEvaluator({scc:a,feature:t,evaluatorMap:n,expressionModel:r})).dependencies.push(o);return o}async _evaluateSpecifiedExecutorsForEachFeature(e,t,n,r=!1){r||(this.calculating=!0);try{let i=[];for(let a of e){let{layer:e}=a,o=this.layerExpressionsModelMap.get(e);o&&o.components.length!==0&&i.push(this.evaluateAffectedExecutors(t(o,e),a,o,n,r))}k(await a(Promise.allSettled(i),this._abortController))}catch(e){y().error(e),this.expressionEvaluationFailed=!0}finally{this.calculating=!1}}};e([u()],b.prototype,`calculating`,void 0),e([u({constructOnly:!0})],b.prototype,`arcadeContext`,void 0),e([u()],b.prototype,`_abortController`,void 0),e([u()],b.prototype,`layerExpressionsModelMap`,void 0),e([u()],b.prototype,`outcomes`,void 0),e([u()],b.prototype,`expressionEvaluationFailed`,void 0),b=e([d(`esri.widgets.BatchAttributeForm.expressions.ExpressionsManager`)],b);class x{constructor(e,t,n,r,i,a){this.scc=e,this.feature=t,this.arcadeContextInfo=n,this.expressionsModel=r,this.outcomes=i,this._abortController=a,this._resolver=null,this.dependencies=[]}get baseContext(){return f(this.arcadeContextInfo,this.feature,this._abortController.signal)}evaluate(e){return this._resolver||(this._resolver=Promise.withResolvers(),o(this._resolver,this._evaluate(e))),this._resolver.promise}async _evaluate(e){v===null&&(v=await import(`../../../arcade/languageUtils.js`));let t=[],n=this.dependencies.map(t=>t.evaluate(e));k(await a(Promise.allSettled(n),this._abortController));let{executors:r}=this.scc;if(r.size===1?await this._evaluateSingleExecutorComponent({context:e,executor:l(r),errorsToReport:t}):await this._evaluateMultiExecutorComponent({context:e,errorsToReport:t}),t.length>0)throw O(t)}async _evaluateMultiExecutorComponent({context:e,errorsToReport:t}){let{transaction:n}=e,r=new Map,i=!0,a=0;for(;i&&a<3;){i=!1,a++;for(let a of this.scc.executors){let o=this._findOutcome(a)??{status:`not-run`,invalidated:!0};o.invalidated||=this._invalidatedSinceCheckpoint(a,n,r.get(a)),this._shouldEvaluate(a,o,e)&&(i=!0,r.set(a,n.currentCheckpoint),await this._performEvaluation({context:e,executor:a,errorsToReport:t}))}}}async _evaluateSingleExecutorComponent({context:e,executor:t,errorsToReport:n}){let r=this._findOutcome(t)??{status:`not-run`,invalidated:!0};r.invalidated||=this._invalidatedSinceCheckpoint(t,e.transaction),this._shouldEvaluate(t,r,e)&&await this._performEvaluation({context:e,executor:t,errorsToReport:n})}async _performEvaluation({context:e,executor:t,errorsToReport:r}){let{variables:i,executeContext:a}=this.baseContext,o=null,s=null;try{o=t.isAsync?await t.executeAsync(i,a):t.execute(i,a),s={result:o,status:`success`}}catch(e){s={error:e,status:`error`}}let{transaction:c,previousOutcomes:l}=e,{outcomes:u}=this,d=this.expressionsModel.arcadeExecutorUses.get(t)??[];for(let t of d){let n=h(t),r=u.get(n);r&&l.set(n,r),u.set(h(t),s);let i=this.expressionsModel.elementTemplateMap.get(t.elementId);switch(t.executorPurpose){case`editableExpression`:if(s.result===!1&&r?.result!==!1){let e=u.get(h({elementId:i.elementId,executorPurpose:`valueExpression`}));if(e){let{fieldName:t}=i,n=E(this.feature,t),r=p(e.result,n,this.arcadeContextInfo.timeZone,v);c.setValue(this.feature,t,r)}}break;case`valueExpression`:{if(s?.status===`error`)continue;let e=i.getExpressionExecutorsForLayer(this.feature.layer),t=!0;if(e?.editableExpression&&(t=u.get(h({elementId:i.elementId,executorPurpose:`editableExpression`}))?.result===!1),t){let e=i.fieldName,t=this.feature.getAttribute(e)??null;try{let n=E(this.feature,e),r=p(s.result,n,this.arcadeContextInfo.timeZone,v);r!==t&&c.setValue(this.feature,e,r)}catch(t){y().error(`Failed to set calculated value for field '${e}'`,t)}}}break;case`visibilityExpression`:!this.expressionsModel.preserveFieldValuesWhenHidden&&r?.result===!0&&s.result===!1&&c.originActor===`user`&&A(i,this.feature,u,e)}}if(s?.status===`error`){let e=new Set;for(let t of d){let n=this.expressionsModel.elementTemplateMap.get(t.elementId);if(n)switch(t.executorPurpose){case`editableExpression`:e.add(n.label+` - Editable expression`);break;case`requiredExpression`:e.add(n.label+` - Required expression`);break;case`valueExpression`:e.add(n.label+` - Value expression`);break;case`visibilityExpression`:e.add(n.label+` - Visibility expression`)}}r.push(e.size>0?new n(`expression-evaluation-failed`,`Arcade evaluation failed (`+[...e].join(`,`)+`)`):new n(`expression-evaluation-failed`,`Arcade evaluation failed `))}}_invalidatedSinceCheckpoint(e,t,n=-1){let r=t.changesForFeature(this.feature);return!r||r.size===0?!1:this.scc.getFieldsReferenced(e).values().some(e=>r.has(e)&&r.get(e)>n)}_shouldEvaluate(e,t,{isDeferred:n}){return this._abortController.signal.aborted||I(this.expressionsModel.arcadeExecutorUses.get(e))&&!n?!1:!!t.invalidated}_findOutcome(e){return F(e,this.outcomes,this.expressionsModel)}}function S(e){return Array.from(e.dependencyGraphComponents.keys())}function C(e){return Array.from(e.dependencyGraphComponents.keys().filter(e=>e.syntaxTree.usesFeatureSet))}function w(e){return Array.from(e.geometryReferences)}function T(e){return Array.from(e.originalFeatureReferences)}function E(e,t){let r=e.layer.fieldsIndex.get(t);if(!r)throw new n(`field-not-found`,`Field '${t}' not found on layer.`);return r}function D(e,t){let n=new Set;for(let r of t)c(n,e.fieldReferencesMap.get(r));return Array.from(n)}function O(e){return AggregateError(e,`One or more expression executions failed. First error message: ${e[0].message}`)}function k(e){let t=[],n=new Set;for(let r of e){if(r.status===`fulfilled`)continue;let e=r.reason instanceof AggregateError?r.reason.errors:[r.reason];for(let r of e)n.has(r)||(n.add(r),t.push(r))}if(t.length>0)throw O(t)}function A(e,t,n,r){g(e)?j(e,t,n,r):_(e)&&M(e,t,n,r)}function j(e,t,n,r){let{group:i}=e;(!i||P(i,n,r.previousOutcomes))&&N(t,e,r)}function M(e,t,n,r){for(let i of e.elements)g(i)&&P(i,n,r.previousOutcomes)&&N(t,i,r)}function N(e,{fieldName:t},n){n.transaction.setValue(e,t,null)}function P(e,t,n){let r=h({elementId:e.elementId,executorPurpose:`visibilityExpression`}),i=n.get(r)??t.get(r);return!i||!!i.result}function F(e,t,n){let r=n.arcadeExecutorUses.get(e);if(r)for(let e of r){let n=t.get(h(e));if(n)return n}}function I(e){return e?.every(e=>m(e.executorPurpose))??!1}export{b as ExpressionsManager};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import{destroyMaybe as t}from"../../../core/maybe.js";import{on as n}from"../../../core/reactiveUtils.js";import{property as r,subclass as i}from"../../../core/accessorSupport/decorators.js";import{isSubtypeGroupLayer as a,getEffectiveLayerCapabilities as o}from"../../../layers/support/layerUtils.js";import{isRelatableFeatureSupportedLayer as s}from"../../../popup/support/featureUtils.js";import{getComputedAttributes as c,parseFormTemplateString as l}from"../stringUtils.js";import u from"./EditableInput.js";import d from"./SingleFeatureInputAdapter.js";import f from"../../Feature/FeatureRelationship/FeatureRelationshipViewModel.js";let p=class extends u{constructor(e){super(e),this._relationshipVM=new f,this._showAllCategories=!1,this._showAllRelatedRecords=!1,this.group=null,this.map=null,this.single=new d({input:this}),this.type=`relationship`}initialize(){this._setRelationshipVMProps(),this.addHandles([n(()=>this.relatedLayer,`edits`,()=>this._relationshipVM?.refresh())])}destroy(){t(this._relationshipVM)}get activeCategory(){return this._relationshipVM.activeCategory}get allCategories(){let{relatedLayer:e,_relationshipVM:t}=this;if(!a(e))return;let n=t?.categories,r=(e.subtypes??[]).map(({code:e,name:t})=>{let r=n?.find(e=>e.name===t);return{name:t,count:r?.count??0,value:r?.value??e}});return r.length?r:null}get categories(){return this.showAllEnabled?this.allCategories:this.allCategories?.slice(0,this.displayCount)}get canAddRelatedFeature(){let{editable:e,relatedFeatureCount:t,relationship:n}=this;if(!n||!this.loaded||!this._relatedLayerAllowsAdds||this.allCategories?.length&&!this.activeCategory)return!1;let{cardinality:r,role:i}=n;return r===`one-to-one`&&t>0||r===`many-to-many`||r===`one-to-many`&&i===`destination`&&t>0?!1:e}get displayCount(){return this.template.displayCount}get displayType(){return this.template.displayType}get editable(){return this._relatedLayerAllowsEdits?this._evaluatedEditableExpression??!0:!1}get feature(){return this.single.feature}get relatedFeatureCount(){return this._relationshipVM?.featureCount??0}get label(){return this.activeCategory?.name?this.activeCategory.name:this._computeStringLiteralText(this.template.label)}get layer(){return this.single.layer}get loaded(){return this._relationshipVM?.state!==`loading`}get orderByFields(){return this.template.orderByFields}get originHasValidKey(){let e=this.feature?.layer.fieldsIndex.get(this.relationship?.keyField)?.name;return!!e&&this.feature?.getAttribute(e)!=null}get relationship(){return this._relationshipVM?.relationship}get relationshipId(){return this.template.relationshipId}get relatedFeatureInfos(){let{_relationshipVM:e,effectiveTimeZone:t}=this;if(!e?.relatedFeatures?.length||!e?.relatedLayer)return[];let{itemDescriptionFieldName:n,relatedFeatures:r,relatedLayer:i}=e,a=i?.formTemplate?.title||void 0;return r.map(e=>{let r;if(n){let a=e.getAttribute(n),o=i.fieldsIndex.get(n);if(o){let e=c({fields:[o],layer:i,values:[a],timeZone:t})[n];e!=null&&(r=e.toString())}}let o=a?l({attributes:e.attributes,label:a,layer:i,timeZone:t}):void 0;return{feature:e,description:r,title:o}}).toArray()}get relatedLayer(){return this._relationshipVM?.relatedLayer}get relatedLayerIsTable(){return!!this.relatedLayer?.isTable}get showAllEnabled(){return this._relationshipVM.showAllEnabled}get showAllActionVisible(){return!this.showAllEnabled&&this.relatedFeatureCount>0&&this.relatedFeatureCount>this.displayCount}get showAllCategories(){return this._showAllCategories}get showAllCategoriesVisible(){let e=this.allCategories?.length??0;return!this.showAllEnabled&&e>0&&e>this.displayCount}get showAllRelatedRecords(){return this._showAllRelatedRecords}get updating(){return this._relationshipVM?.state===`loading`||this._relationshipVM?.state===`querying`}incrementPage(){this._relationshipVM&&this._relationshipVM.featurePage++}setActiveCategory(e){this._relationshipVM.activeCategory=e,this.setShowAllRelatedRecords(!!e)}setShowAllCategories(e){this._showAllCategories=e,this._showAllRelatedRecords||this._setShowAllEnabled(e)}setShowAllRelatedRecords(e){this._showAllRelatedRecords=e,this._showAllCategories||this._setShowAllEnabled(e)}get _relatedLayerAllowsAdds(){let{relatedLayer:e}=this;return!e||!this._relatedLayerAllowsEdits?!1:!!o(e)?.operations?.supportsAdd}get _relatedLayerAllowsEdits(){let{relatedLayer:e}=this;return e?!!o(e)?.operations?.supportsEditing:!1}_setRelationshipVMProps(){let{displayCount:e,feature:t,layer:n,orderByFields:r,map:i,relationshipId:a,showAllEnabled:o}=this;t&&n&&s(n)&&this._relationshipVM.set({displayCount:e,graphic:t.plainGraphic,layer:n,map:i,orderByFields:r,relationshipId:a,showAllEnabled:o})}_setShowAllEnabled(e){this._relationshipVM.showAllEnabled=e}};e([r()],p.prototype,`_relationshipVM`,void 0),e([r()],p.prototype,`_showAllCategories`,void 0),e([r()],p.prototype,`_showAllRelatedRecords`,void 0),e([r()],p.prototype,`activeCategory`,null),e([r()],p.prototype,`allCategories`,null),e([r()],p.prototype,`categories`,null),e([r()],p.prototype,`canAddRelatedFeature`,null),e([r()],p.prototype,`displayCount`,null),e([r()],p.prototype,`displayType`,null),e([r()],p.prototype,`editable`,null),e([r()],p.prototype,`feature`,null),e([r()],p.prototype,`group`,void 0),e([r()],p.prototype,`label`,null),e([r()],p.prototype,`layer`,null),e([r()],p.prototype,`loaded`,null),e([r()],p.prototype,`map`,void 0),e([r()],p.prototype,`orderByFields`,null),e([r()],p.prototype,`originHasValidKey`,null),e([r()],p.prototype,`relationship`,null),e([r()],p.prototype,`relationshipId`,null),e([r()],p.prototype,`relatedFeatureInfos`,null),e([r()],p.prototype,`relatedLayer`,null),e([r()],p.prototype,`relatedLayerIsTable`,null),e([r({readOnly:!0})],p.prototype,`single`,void 0),e([r()],p.prototype,`showAllEnabled`,null),e([r()],p.prototype,`showAllActionVisible`,null),e([r()],p.prototype,`showAllCategories`,null),e([r()],p.prototype,`showAllCategoriesVisible`,null),e([r()],p.prototype,`showAllRelatedRecords`,null),e([r({readOnly:!0})],p.prototype,`type`,void 0),e([r()],p.prototype,`updating`,null),e([r()],p.prototype,`_relatedLayerAllowsAdds`,null),e([r()],p.prototype,`_relatedLayerAllowsEdits`,null),p=e([i(`esri.widgets.BatchAttributeForm.inputs.RelationshipElementInput`)],p);const m=p;export{m as default};
2
+ import{__decorate as e}from"tslib";import{destroyMaybe as t}from"../../../core/maybe.js";import{on as n}from"../../../core/reactiveUtils.js";import{property as r,subclass as i}from"../../../core/accessorSupport/decorators.js";import{isSubtypeGroupLayer as a,getEffectiveLayerCapabilities as o}from"../../../layers/support/layerUtils.js";import{isRelatableFeatureSupportedLayer as s}from"../../../popup/support/featureUtils.js";import{getComputedAttributes as c,parseFormTemplateString as l}from"../stringUtils.js";import u from"./EditableInput.js";import d from"./SingleFeatureInputAdapter.js";import f from"../../Feature/FeatureRelationship/FeatureRelationshipViewModel.js";let p=class extends u{constructor(e){super(e),this._relationshipVM=new f,this._showAllCategories=!1,this._showAllRelatedRecords=!1,this.executeFeatureSetDependentExpressions=null,this.group=null,this.map=null,this.single=new d({input:this}),this.type=`relationship`}initialize(){this._setRelationshipVMProps(),this.addHandles([n(()=>this.relatedLayer,`edits`,()=>{this._relationshipVM?.refresh(),this.executeFeatureSetDependentExpressions?.(this.features.toArray())})])}destroy(){t(this._relationshipVM)}get activeCategory(){return this._relationshipVM.activeCategory}get allCategories(){let{relatedLayer:e,_relationshipVM:t}=this;if(!a(e))return;let n=t?.categories,r=(e.subtypes??[]).map(({code:e,name:t})=>{let r=n?.find(e=>e.name===t);return{name:t,count:r?.count??0,value:r?.value??e}});return r.length?r:null}get categories(){return this.showAllEnabled?this.allCategories:this.allCategories?.slice(0,this.displayCount)}get canAddRelatedFeature(){let{editable:e,relatedFeatureCount:t,relationship:n}=this;if(!n||!this.loaded||!this._relatedLayerAllowsAdds||this.allCategories?.length&&!this.activeCategory)return!1;let{cardinality:r,role:i}=n;return r===`one-to-one`&&t>0||r===`many-to-many`||r===`one-to-many`&&i===`destination`&&t>0?!1:e}get displayCount(){return this.template.displayCount}get displayType(){return this.template.displayType}get editable(){return this._relatedLayerAllowsEdits?this._evaluatedEditableExpression??!0:!1}get feature(){return this.single.feature}get relatedFeatureCount(){return this._relationshipVM?.featureCount??0}get label(){return this.activeCategory?.name?this.activeCategory.name:this._computeStringLiteralText(this.template.label)}get layer(){return this.single.layer}get loaded(){return this._relationshipVM?.state!==`loading`}get orderByFields(){return this.template.orderByFields}get originHasValidKey(){let e=this.feature?.layer.fieldsIndex.get(this.relationship?.keyField)?.name;return!!e&&this.feature?.getAttribute(e)!=null}get relationship(){return this._relationshipVM?.relationship}get relationshipId(){return this.template.relationshipId}get relatedFeatureInfos(){let{_relationshipVM:e,effectiveTimeZone:t}=this;if(!e?.relatedFeatures?.length||!e?.relatedLayer)return[];let{itemDescriptionFieldName:n,relatedFeatures:r,relatedLayer:i}=e,a=i?.formTemplate?.title||void 0;return r.map(e=>{let r;if(n){let a=e.getAttribute(n),o=i.fieldsIndex.get(n);if(o){let e=c({fields:[o],layer:i,values:[a],timeZone:t})[n];e!=null&&(r=e.toString())}}let o=a?l({attributes:e.attributes,label:a,layer:i,timeZone:t}):void 0;return{feature:e,description:r,title:o}}).toArray()}get relatedLayer(){return this._relationshipVM?.relatedLayer}get relatedLayerIsTable(){return!!this.relatedLayer?.isTable}get showAllEnabled(){return this._relationshipVM.showAllEnabled}get showAllActionVisible(){return!this.showAllEnabled&&this.relatedFeatureCount>0&&this.relatedFeatureCount>this.displayCount}get showAllCategories(){return this._showAllCategories}get showAllCategoriesVisible(){let e=this.allCategories?.length??0;return!this.showAllEnabled&&e>0&&e>this.displayCount}get showAllRelatedRecords(){return this._showAllRelatedRecords}get updating(){return this._relationshipVM?.state===`loading`||this._relationshipVM?.state===`querying`}incrementPage(){this._relationshipVM&&this._relationshipVM.featurePage++}setActiveCategory(e){this._relationshipVM.activeCategory=e,this.setShowAllRelatedRecords(!!e)}setShowAllCategories(e){this._showAllCategories=e,this._showAllRelatedRecords||this._setShowAllEnabled(e)}setShowAllRelatedRecords(e){this._showAllRelatedRecords=e,this._showAllCategories||this._setShowAllEnabled(e)}get _relatedLayerAllowsAdds(){let{relatedLayer:e}=this;return!e||!this._relatedLayerAllowsEdits?!1:!!o(e)?.operations?.supportsAdd}get _relatedLayerAllowsEdits(){let{relatedLayer:e}=this;return e?!!o(e)?.operations?.supportsEditing:!1}_setRelationshipVMProps(){let{displayCount:e,feature:t,layer:n,orderByFields:r,map:i,relationshipId:a,showAllEnabled:o}=this;t&&n&&s(n)&&this._relationshipVM.set({displayCount:e,graphic:t.plainGraphic,layer:n,map:i,orderByFields:r,relationshipId:a,showAllEnabled:o})}_setShowAllEnabled(e){this._relationshipVM.showAllEnabled=e}};e([r()],p.prototype,`_relationshipVM`,void 0),e([r()],p.prototype,`_showAllCategories`,void 0),e([r()],p.prototype,`_showAllRelatedRecords`,void 0),e([r()],p.prototype,`activeCategory`,null),e([r()],p.prototype,`allCategories`,null),e([r()],p.prototype,`categories`,null),e([r()],p.prototype,`canAddRelatedFeature`,null),e([r()],p.prototype,`displayCount`,null),e([r()],p.prototype,`displayType`,null),e([r()],p.prototype,`editable`,null),e([r()],p.prototype,`executeFeatureSetDependentExpressions`,void 0),e([r()],p.prototype,`feature`,null),e([r()],p.prototype,`group`,void 0),e([r()],p.prototype,`label`,null),e([r()],p.prototype,`layer`,null),e([r()],p.prototype,`loaded`,null),e([r()],p.prototype,`map`,void 0),e([r()],p.prototype,`orderByFields`,null),e([r()],p.prototype,`originHasValidKey`,null),e([r()],p.prototype,`relationship`,null),e([r()],p.prototype,`relationshipId`,null),e([r()],p.prototype,`relatedFeatureInfos`,null),e([r()],p.prototype,`relatedLayer`,null),e([r()],p.prototype,`relatedLayerIsTable`,null),e([r({readOnly:!0})],p.prototype,`single`,void 0),e([r()],p.prototype,`showAllEnabled`,null),e([r()],p.prototype,`showAllActionVisible`,null),e([r()],p.prototype,`showAllCategories`,null),e([r()],p.prototype,`showAllCategoriesVisible`,null),e([r()],p.prototype,`showAllRelatedRecords`,null),e([r({readOnly:!0})],p.prototype,`type`,void 0),e([r()],p.prototype,`updating`,null),e([r()],p.prototype,`_relatedLayerAllowsAdds`,null),e([r()],p.prototype,`_relatedLayerAllowsEdits`,null),p=e([i(`esri.widgets.BatchAttributeForm.inputs.RelationshipElementInput`)],p);const m=p;export{m as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import e from"../../../../core/Error.js";import t from"../AttachmentElementInput.js";import n from"../BatchFormInputs.js";import r from"../FieldInput.js";import i from"../GroupInput.js";import a from"../RelationshipElementInput.js";import o from"../TextElementInput.js";import s from"../UtilityNetworkAssociationsElementInput.js";import{isMultipleChoiceController as c}from"./controllerUtils.js";import{hashGroupElementTemplateWithoutChildren as l}from"../../templates/support/hashElementTemplate.js";import{isFieldElementTemplate as u,isGroupElementTemplate as d,isRelationshipElementTemplate as f,isTextElementTemplate as p,isAttachmentElementTemplate as m,isUtilityNetworkAssociationsElementTemplate as h}from"../../templates/support/templateUtils.js";function g(e,t){let r=new n({inputs:e.elements.map(e=>S(e,t)),template:e});return x(r),r}function _(e,t,n){let r=g(t,n),{mergedInputs:i}=v(e.inputs,r.inputs,e.staleInputs);e.template=t,e.inputs=i,x(e)}function v(e,t,n){let r=new Set,i=[],a=new Map(e.map(e=>[b(e),e]));for(let e of t){let t=b(e);r.add(t);let o=a.get(t);if(o){y(o,e),i.push(o),e.destroy();continue}let s=n.get(t);if(s){y(s,e),i.push(s),n.delete(t),e.destroy();continue}i.push(e)}for(let t of e){let e=b(t);r.has(e)||n.set(e,t)}return{mergedInputs:i}}function y(e,t){if(e.features=t.features,e.existsInAllLayers=t.existsInAllLayers,e instanceof r&&t instanceof r&&e.template.foldIn(t.template),e.type!==`group`||t.type!==`group`)return;let{mergedInputs:n}=v(e.inputs,t.inputs,e.staleInputs);e.inputs=n;for(let t of n)t.group=e}function b(e){return e.type===`group`?l(e.template):e.template.elementId}function x(e){let t=e.allFieldInputs,n=new Set(t.map(e=>e.fieldName));for(let e of t){let t=c(e.inputController)?e.inputController:null,r=t?.otherChoiceFieldName;if(!r)continue;let i=e.layers[0]?.getField(r)?.name??r;n.has(i)&&(t.shouldShowOtherChoice=!1)}}function S(n,c){let{allFeatures:l,expressionsManager:g,getFieldValueOptionsForFeature:_,getExternalErrorForFeature:v,map:y,requestDeferredExpressionEvaluation:b}=c,x=new Set(n.layers),C=l.filter(e=>x.has(e.layer)),w=C.length===l.length;if(u(n))return new r({existsInAllLayers:w,features:C,template:n,expressionsManager:g,getExternalErrorForFeature:v,getFieldValueOptionsForFeature:_,requestDeferredExpressionEvaluation:b});if(d(n)){let e=n.elements.map(e=>S(e,c));return new i({existsInAllLayers:w,features:C,inputs:e,template:n,expressionsManager:g})}if(f(n))return new a({existsInAllLayers:w,features:C,map:y,template:n,expressionsManager:g});if(p(n))return new o({existsInAllLayers:w,features:C,template:n,expressionsManager:g});if(m(n))return new t({existsInAllLayers:w,features:C,template:n,expressionsManager:g});if(h(n))return new s({existsInAllLayers:w,features:C,template:n,expressionsManager:g,map:y});throw new e(`batch-attribute-form:unsupported-element-template`,`The type of form element template provided is not supported`)}export{g as createBatchFormInputsFromBatchFormTemplate,_ as mergeBatchFormInputsFromNewTemplate};
2
+ import e from"../../../../core/Error.js";import t from"../AttachmentElementInput.js";import n from"../BatchFormInputs.js";import r from"../FieldInput.js";import i from"../GroupInput.js";import a from"../RelationshipElementInput.js";import o from"../TextElementInput.js";import s from"../UtilityNetworkAssociationsElementInput.js";import{isMultipleChoiceController as c}from"./controllerUtils.js";import{hashGroupElementTemplateWithoutChildren as l}from"../../templates/support/hashElementTemplate.js";import{isFieldElementTemplate as u,isGroupElementTemplate as d,isRelationshipElementTemplate as f,isTextElementTemplate as p,isAttachmentElementTemplate as m,isUtilityNetworkAssociationsElementTemplate as h}from"../../templates/support/templateUtils.js";function g(e,t){let r=new n({inputs:e.elements.map(e=>S(e,t)),template:e});return x(r),r}function _(e,t,n){let r=g(t,n),{mergedInputs:i}=v(e.inputs,r.inputs,e.staleInputs);e.template=t,e.inputs=i,x(e)}function v(e,t,n){let r=new Set,i=[],a=new Map(e.map(e=>[b(e),e]));for(let e of t){let t=b(e);r.add(t);let o=a.get(t);if(o){y(o,e),i.push(o),e.destroy();continue}let s=n.get(t);if(s){y(s,e),i.push(s),n.delete(t),e.destroy();continue}i.push(e)}for(let t of e){let e=b(t);r.has(e)||n.set(e,t)}return{mergedInputs:i}}function y(e,t){if(e.features=t.features,e.existsInAllLayers=t.existsInAllLayers,e instanceof r&&t instanceof r&&e.template.foldIn(t.template),e.type!==`group`||t.type!==`group`)return;let{mergedInputs:n}=v(e.inputs,t.inputs,e.staleInputs);e.inputs=n;for(let t of n)t.group=e}function b(e){return e.type===`group`?l(e.template):e.template.elementId}function x(e){let t=e.allFieldInputs,n=new Set(t.map(e=>e.fieldName));for(let e of t){let t=c(e.inputController)?e.inputController:null,r=t?.otherChoiceFieldName;if(!r)continue;let i=e.layers[0]?.getField(r)?.name??r;n.has(i)&&(t.shouldShowOtherChoice=!1)}}function S(n,c){let{allFeatures:l,expressionsManager:g,getFieldValueOptionsForFeature:_,getExternalErrorForFeature:v,map:y,requestDeferredExpressionEvaluation:b,executeFeatureSetDependentExpressions:x}=c,C=new Set(n.layers),w=l.filter(e=>C.has(e.layer)),T=w.length===l.length;if(u(n))return new r({existsInAllLayers:T,features:w,template:n,expressionsManager:g,getExternalErrorForFeature:v,getFieldValueOptionsForFeature:_,requestDeferredExpressionEvaluation:b});if(d(n)){let e=n.elements.map(e=>S(e,c));return new i({existsInAllLayers:T,features:w,inputs:e,template:n,expressionsManager:g})}if(f(n))return new a({existsInAllLayers:T,features:w,map:y,template:n,expressionsManager:g,executeFeatureSetDependentExpressions:x});if(p(n))return new o({existsInAllLayers:T,features:w,template:n,expressionsManager:g});if(m(n))return new t({existsInAllLayers:T,features:w,template:n,expressionsManager:g});if(h(n))return new s({existsInAllLayers:T,features:w,template:n,expressionsManager:g,map:y});throw new e(`batch-attribute-form:unsupported-element-template`,`The type of form element template provided is not supported`)}export{g as createBatchFormInputsFromBatchFormTemplate,_ as mergeBatchFormInputsFromNewTemplate};