@arcgis/core 4.29.0-next.20240222 → 4.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/assets/esri/core/workers/RemoteClient.js +1 -1
  2. package/assets/esri/core/workers/chunks/0bc21d2a0b65bd4e9d76.js +1 -0
  3. package/assets/esri/core/workers/chunks/9307d485a9e5f9fa77d1.js +1 -0
  4. package/assets/esri/core/workers/chunks/{e7b26c7e9e24dc6255be.js → cacf97b0a7a1057b9f79.js} +1 -1
  5. package/config.js +1 -1
  6. package/copyright.txt +56 -28
  7. package/geometry/support/meshUtils/rotate.js +1 -1
  8. package/interfaces.d.ts +6 -6
  9. package/kernel.js +1 -1
  10. package/layers/orientedImagery/core/CameraOrientation.js +1 -1
  11. package/layers/orientedImagery/core/ElevationSourceDefinitions.js +1 -1
  12. package/layers/orientedImagery/transformations/imageToWorld.js +5 -0
  13. package/layers/orientedImagery/transformations/updateElevation.js +5 -0
  14. package/layers/orientedImagery/transformations/updateElevationUtils.js +5 -0
  15. package/layers/orientedImagery/transformations/utils.js +1 -1
  16. package/layers/orientedImagery/transformations/worldToImage.js +5 -0
  17. package/layers/support/EditingCapabilities.js +1 -1
  18. package/layers/support/editableLayers.js +1 -1
  19. package/package.json +1 -1
  20. package/smartMapping/renderers/pieChart.js +1 -1
  21. package/support/revision.js +1 -1
  22. package/views/3d/layers/graphics/Graphics3DMeshFillSymbolLayer.js +1 -1
  23. package/views/3d/layers/i3s/I3SOverrides.js +1 -1
  24. package/views/layers/support/editableLayerViews.js +5 -0
  25. package/widgets/Editor/EditorViewModel.js +1 -1
  26. package/widgets/Editor/support/EditorEditingCapabilities.js +1 -1
  27. package/widgets/Editor/support/EditorItem.js +1 -1
  28. package/widgets/FeatureForm.js +1 -1
  29. package/widgets/OrientedImageryViewer/OrientedImageryViewerViewModel.js +1 -1
  30. package/widgets/OrientedImageryViewer.js +1 -1
  31. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceViewModel.js +1 -1
  32. package/widgets/UtilityNetworkTrace.js +1 -1
  33. package/assets/esri/core/workers/chunks/25f73748df0ee82d06cb.js +0 -1
  34. package/assets/esri/core/workers/chunks/2d7a18f8c540269ecee9.js +0 -1
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../../chunks/tslib.es6.js";import t from"../../../../request.js";import i from"../../../../core/Accessor.js";import{splitIntoChunks as r}from"../../../../core/arrayUtils.js";import{resultOrAbort as s,result as o}from"../../../../core/asyncUtils.js";import{estimateStringByteSize as n,estimateNumberByteSize as a}from"../../../../core/byteSizeEstimations.js";import d from"../../../../core/Collection.js";import{makeHandle as c}from"../../../../core/handleUtils.js";import h from"../../../../core/Logger.js";import{destroyMaybe as l,abortMaybe as u}from"../../../../core/maybe.js";import{whenOrAbort as m,createResolver as g}from"../../../../core/promiseUtils.js";import p from"../../../../core/ReactiveSet.js";import{watch as y,initial as f}from"../../../../core/reactiveUtils.js";import{property as b}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import{subclass as _}from"../../../../core/accessorSupport/decorators/subclass.js";import{equals as O}from"../../../../geometry/support/spatialReferenceUtils.js";import{formatNumber as v}from"../../../../intl/number.js";import{getMaximumQuerySize as j,queryAllJSON as C}from"../../../../layers/support/featureQueryAll.js";import{assetMapFromAssetMapsJSON as w,extractMesh as I}from"../../../../rest/support/meshFeatureSet.js";import{direct3DObjectFeatureLayerDisplayEnabled as F,i3sPatchingEnabled as A,sceneLayerEditingEnabled as L}from"../../../../support/featureFlags.js";import{isTimeoutError as x}from"../../../../support/requestUtils.js";import{ViewingMode as E}from"../../../ViewingMode.js";import S from"../FeatureLayerView3D.js";const D="esri.views.3d.layers.i3s.I3SOverrides";let G=class extends i{constructor(e){super(e),this._warnMaximumChangedObjectsExceeded=!1,this._maximumNumberOfEditOVerrides=$,this._original3DOFLDefinitionExpression=null,this._interactiveEditingSessions=new d,this.geometryOverrides=new d,this._clientGeometryCache=new Map,this._associatedLayerView=null,this._attributeChangedObjectIds=new p,this._geometryChangedObjectIds=new p,this._pendingFetchChangedObjectIds=null,this._pendingFetchAbortController=new AbortController,this._featureIdLocks=new Map}initialize(){this._memCache=this.memoryController.newCache(`i3s-attribute-overrides-${this.layer.uid}`),this._pendingFetchChangedObjectIds=this._fetchChangedObjectIds(this._pendingFetchAbortController?.signal),this._pendingFetchChangedObjectIds.finally((()=>{this._pendingFetchAbortController=null,this._pendingFetchChangedObjectIds=null})),this.is3DOFL&&null!=this._associatedLayer&&(F()?this._associatedLayer.load().then((e=>{this.destroyed||(this._original3DOFLDefinitionExpression=e.definitionExpression,this.addHandles(y((()=>this._definitionExpression),(t=>e.definitionExpression=t),f)),this._associatedLayerView=new S({layer:this._associatedLayer,view:this.view}))})):A())}destroy(){this.is3DOFL&&null!=this._associatedLayer&&(F()?null!=this._associatedLayerView&&(this._associatedLayer.definitionExpression=this._original3DOFLDefinitionExpression):A()),this._set("layer",null),this._memCache=l(this._memCache),this._pendingFetchAbortController=u(this._pendingFetchAbortController),this._pendingFetchChangedObjectIds=null,this._featureIdLocks.clear()}get is3DOFL(){return L()&&null!=this._associatedLayer?.infoFor3D}get sortedGeometryChangedObjectIds(){return this.is3DOFL?[...this._geometryChangedObjectIds].sort(((e,t)=>e-t)):[]}get _associatedLayer(){return null==this.layer?null:this.layer.associatedLayer}get hasGeometryChanges(){return this._geometryChangedObjectIds.size>0}get _definitionExpression(){const e=this.sortedGeometryChangedObjectIds;return 0===e.length?"1 = 0":`OBJECTID IN (${e.join(",")})`}get updating(){if(!this.is3DOFL)return!1;if(this._pendingFetchChangedObjectIds)return!0;if(F()){return!(null!=this._associatedLayerView)||null!=this._associatedLayerView&&this._associatedLayerView.updating}return!1}get isEmpty(){return null==this._pendingFetchChangedObjectIds&&0===this._attributeChangedObjectIds.size&&0===this._geometryChangedObjectIds.size}featureHasGeometryChanges(e){return this._geometryChangedObjectIds.has(e)}featureHasAttributeChanges(e){return this._attributeChangedObjectIds.has(e)}createInteractiveEditSession(e){this._attributeChangedObjectIds.add(e);const t=this._interactiveEditingSessions,i=new M(e,(()=>{t.remove(i)}));return t.unshift(i),i}async applyAttributeOverrides(e,t,i,r=[]){if(this._pendingFetchChangedObjectIds&&await m(this._pendingFetchChangedObjectIds,i),null==t)return;const{attributeData:s,loadedAttributes:o}=t;if(null==o||null==s||0===this._attributeChangedObjectIds.size)return;const n=new Set;for(const d of o)n.add(d.index);for(const d of r)n.has(d.index)||(o.push(d),s[d.name]=new Array(e.length));const a=await this._lockFeatureIds(e);try{const t={attributeData:s,loadedAttributes:o},r=this._getOverridesFromCache(e,t,this._attributeChangedObjectIds),{objectIds:n,fieldNames:a}=r;if(0===n.length||0===a.length)return;const d=await this._queryAttributeOverridesFromAssociatedLayer(n,a,i);if(null==d)return;this._processOverridesFromAssociatedLayer(e,d,a,t)}finally{a.remove()}}updateGeometry(e,t){this._geometryChangedObjectIds.add(e);const i=this._clientGeometryCache.get(e);if(null!=i&&(this.geometryOverrides.remove(i),this._clientGeometryCache.delete(e)),null!=t){const i={oid:e,mesh:t};this.geometryOverrides.add(i),this._clientGeometryCache.set(e,i)}}updateAttributeValue(e,t,i){this._attributeChangedObjectIds.add(e),this._cacheAttributeValue(e,t,i)}featureAdded(e){this.is3DOFL&&A()&&this._geometryChangedObjectIds.add(e),this._attributeChangedObjectIds.add(e)}_cacheAttributeValue(e,t,i){this._memCache.put(this._getAttributeCacheKey(e,t),i,this._memCacheAttributeValueSize(i))}_getOverridesFromCache(e,{loadedAttributes:t,attributeData:i},r){const s=new Set,o=new Array;for(const a of t)o[a.index]=i[a.name];const n=new Set;for(let a=0;a<e.length;a++){const i=e[a];if(r.has(i))for(const e of t){const t=this._attributeFromCache(i,e.index);void 0===t?(s.add(i),n.add(e.name)):o[e.index][a]=t}}return{objectIds:Array.from(s),fieldNames:Array.from(n)}}_attributeFromCache(e,t){const i=this._fromInteractiveEditingSession(e,t);if(void 0!==i)return i;const r=this._getAttributeCacheKey(e,t);return this._memCache.get(r)}_fromInteractiveEditingSession(e,t){if(null!=this._interactiveEditingSessions)for(const i of this._interactiveEditingSessions){if(i.objectId!==e)continue;const r=i.getAttribute(t);if(void 0!==r)return r}}_getAttributeCacheKey(e,t){return`${e}-${t}`}async _queryAttributeOverridesFromAssociatedLayer(e,t,i){if(0===e.length)return null;this._logWarningIfMaximumObjectsExceeded();const{associatedLayer:r}=this.layer;if(null==r)return null;const s=r.createQuery(),{objectIdField:o}=r,n=[o,...t];s.where="1=1",s.returnGeometry=!1,s.outFields=n,s.cacheHint=!0;const a=await this._executeBatchQuery(r,e,s,i),d=[];for(const c of a)if(c.ok)for(const e of c.value.features)d.push(e);return d}async _queryGeometryOverridesFromAssociatedLayer(e,t){if(0===e.length||!this.is3DOFL||!A())return null;const i=this.layer.associatedLayer,r=i.infoFor3D,{spatialReference:s}=i,{state:{viewingMode:o},spatialReference:n}=this.view,a=o===E.Global,d=s.isGeographic;if(a&&!d)return h.getLogger(D).warn("unsupported-pcs-edits-in-global-view",this.layer.title,N(s,n,this.view.viewingMode,k.Mode)),null;if(!a){if(d)return h.getLogger(D).warn("unsupported-gcs-edits-in-local-view",this.layer.title,N(s,n,this.view.viewingMode,k.Mode)),null;if(!O(n,s))return h.getLogger(D).warn("unsupported-mismatched-spatial-reference-edits-in-local-view",this.layer.title,N(s,n,this.view.viewingMode,k.SpatialReference)),null}this._logWarningIfMaximumObjectsExceeded();const{objectIdField:c,globalIdField:l}=i,u=[c,...null!=l?[l]:[]],m=i.createQuery();m.where="1=1",m.returnGeometry=!0,m.outFields=u,m.cacheHint=!0,m.returnZ=i.hasZ,m.returnM=i.hasM;const g=await this._executeBatchQuery(i,e,m,t),p=[];for(const h of g){if(!h.ok)continue;const e=h.value,{assetMaps:t,features:i,globalIdFieldName:o}=e;if(null==t)continue;const n=w(r,t);for(const a of i){const e=I(a,o,s,r,n),t=a;null!=e?(t.geometry=e,p.push(t)):t.geometry=null}}return p}_logWarningIfMaximumObjectsExceeded(){if(!this._warnMaximumChangedObjectsExceeded)return;this._warnMaximumChangedObjectsExceeded=!1;let e=`The number of edited objects that are not yet cached in the scene service exceeds the maximum limit. Attribute changes will only be available for the first ${v(this._maximumNumberOfEditOVerrides)} objects. Please consider re-caching the scene service`;const t=this.layer.portalItem;t&&t.loaded?e+=` (${t.portal.url}/home/item.html?id=${t.id}#settings)`:e+=` (${this.layer.parsedUrl.path})`,h.getLogger(D).warn("#queryOverrides()",this.layer.title,`${e}.`)}async _executeBatchQuery(e,t,i,o){if(0===t.length)return[];const n=j(e);t=[...t].sort(((e,t)=>e-t));const a=r(t,n).map((t=>{const r=i.clone();return r.objectIds=t,s(C(e,r,{signal:o}))}));return Promise.all(a)}_processOverridesFromAssociatedLayer(e,t,i,{loadedAttributes:r,attributeData:s}){const o=this._associatedLayer;if(null==o)return;const n=o.objectIdField,a=i.map((t=>(t in s||(s[t]=new Array(e.length)),s[t]))),d=new Map(r.map((e=>[e.name,e.index]))),c=i.map((e=>d.get(e))),h=new Map(Array.from(e,((e,t)=>[e,t])));for(const l of t){const e=l.attributes[n];for(let t=0;t<i.length;t++){const r=c[t],s=h.get(e),o=l.attributes[i[t]];a[t][s]=o,this._cacheAttributeValue(e,r,o)}}}_memCacheAttributeValueSize(e){return"string"==typeof e?n(e):a()}async _fetchChangedObjectIds(e){const i=this.layer;await i.load({signal:e}),this._geometryChangedObjectIds.clear(),this._attributeChangedObjectIds.clear();const{associatedLayer:r}=i;if(null==r||!r.capabilities?.operations?.supportsChangeTracking)return;const s=this._getFetchChangedObjectIdsServerGen();if(null==s)return;const n=r.layerId,a=this.is3DOFL,d={f:"json",returnIdsOnly:!0,layers:`[${n}]`,returnUpdates:!0,returnDeletes:a,returnInserts:a,layerServerGens:JSON.stringify([{id:n,serverGen:s}])};if(a){const e=r.infoFor3D;d.fieldsToCompare=JSON.stringify({fields:[...Object.values(e.transformFieldRoles),e.sourceHashField]})}const c=await o(t(`${r.url}/extractChanges`,{method:"post",query:d,timeout:V,signal:e}));if(!c.ok&&x(c.error)){const e=this.layer.title;h.getLogger(D).warn("extractChanges:timeout",e,`${e} could not obtain edited features that are not cached in the scene service. Display of features may not be up to date with the latest edits. Consider re-caching the scene service.`)}if(c.ok&&1===c.value.data?.edits?.length){const t=c.value.data.edits[0],i=t?.objectIds,s=t?.fieldUpdates,o=i?.adds??[],n=i?.updates??[],d=i?.deletes??[],h=[...o,...n,...d],l=a?[...o,...s??n,...d]:[],u=Math.min(this._maximumNumberOfEditOVerrides,h.length);u<h.length&&(this._warnMaximumChangedObjectsExceeded=!0);const m=h.sort(((e,t)=>e-t));for(let e=0;e<u;++e){const t=m[e];this._attributeChangedObjectIds.add(t)}for(const e of l)this._geometryChangedObjectIds.add(e);if(this.is3DOFL&&A()&&this._geometryChangedObjectIds.size>0){const t=await this._queryGeometryOverridesFromAssociatedLayer(Array.from(this._geometryChangedObjectIds),e);if(null!=t)for(const e of t)null!=e.geometry&&this.updateGeometry(e.attributes[r.objectIdField],e.geometry)}}}_getFetchChangedObjectIdsServerGen(){const e=this.layer;if(null!=e.serviceUpdateTimeStamp?.lastUpdate)return e.serviceUpdateTimeStamp.lastUpdate;const t=e.associatedLayer;return null!=t?.serverGens?.minServerGen?t.serverGens.minServerGen:null}async _lockFeatureIds(e){const t=this._featureIdLocks;let i=!0;for(;i;){const r=new Array;for(const i of e){const e=t.get(i);e&&r.push(e)}0===r.length?i=!1:await Promise.all(r)}const r=g(),s=r.promise;for(const o of e)t.set(o,s);return c((()=>{for(const i of e)t.delete(i);r.resolve()}))}get test(){const e=Array.from(this._attributeChangedObjectIds),t=this._pendingFetchChangedObjectIds,i=this;return{changedObjectIds:e,pendingFetchChangedObjectIds:t,get maximumNumberOfEditOVerrides(){return i._maximumNumberOfEditOVerrides},set maximumNumberOfEditOVerrides(e){i._maximumNumberOfEditOVerrides=e}}}};e([b({constructOnly:!0})],G.prototype,"view",void 0),e([b({constructOnly:!0})],G.prototype,"layer",void 0),e([b({readOnly:!0})],G.prototype,"is3DOFL",null),e([b()],G.prototype,"_interactiveEditingSessions",void 0),e([b({readOnly:!0})],G.prototype,"sortedGeometryChangedObjectIds",null),e([b({readOnly:!0})],G.prototype,"geometryOverrides",void 0),e([b()],G.prototype,"_clientGeometryCache",void 0),e([b()],G.prototype,"_associatedLayer",null),e([b()],G.prototype,"_associatedLayerView",void 0),e([b({constructOnly:!0})],G.prototype,"memoryController",void 0),e([b()],G.prototype,"_attributeChangedObjectIds",void 0),e([b()],G.prototype,"_geometryChangedObjectIds",void 0),e([b()],G.prototype,"hasGeometryChanges",null),e([b()],G.prototype,"_pendingFetchChangedObjectIds",void 0),e([b()],G.prototype,"_pendingFetchAbortController",void 0),e([b()],G.prototype,"_definitionExpression",null),e([b()],G.prototype,"updating",null),e([b()],G.prototype,"isEmpty",null),G=e([_(D)],G);class M{constructor(e,t){this.objectId=e,this._remove=t,this._updates=new Map,this._isActive=!0}getAttribute(e){return this._updates.get(e)}setAttribute(e,t){this.isActive&&this._updates.set(e,t)}remove(){this.isActive&&(this._isActive=!1,this._remove())}get isActive(){return this._isActive}}const V=1e4,$=5e4;var k;function N(e,t,i,r){return`Displaying the edits of a SceneLayer with a${r===k.Mode?e.isGeographic?" geographic ":" projected ":" "}spatial reference (wkid:${e.wkid}) in ${i} viewing mode${r===k.SpatialReference?` with spatial reference (wkid:${t.wkid}) `:" "}is not supported. No geometry edits will be displayed for this layer.\nPlease consider re-caching the scene service or changing the ${r===k.Mode?"viewing mode":"view spatial reference"} to display edits.`}!function(e){e[e.Mode=0]="Mode",e[e.SpatialReference=1]="SpatialReference"}(k||(k={}));export{G as I3SOverrides};
5
+ import{_ as e}from"../../../../chunks/tslib.es6.js";import t from"../../../../request.js";import i from"../../../../core/Accessor.js";import{splitIntoChunks as r}from"../../../../core/arrayUtils.js";import{resultOrAbort as s,result as o}from"../../../../core/asyncUtils.js";import{estimateStringByteSize as n,estimateNumberByteSize as a}from"../../../../core/byteSizeEstimations.js";import d from"../../../../core/Collection.js";import{makeHandle as c}from"../../../../core/handleUtils.js";import h from"../../../../core/Logger.js";import{destroyMaybe as l,abortMaybe as u}from"../../../../core/maybe.js";import{whenOrAbort as m,createResolver as g}from"../../../../core/promiseUtils.js";import p from"../../../../core/ReactiveSet.js";import{watch as y,initial as f}from"../../../../core/reactiveUtils.js";import{property as b}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import{subclass as _}from"../../../../core/accessorSupport/decorators/subclass.js";import{equals as O}from"../../../../geometry/support/spatialReferenceUtils.js";import{formatNumber as v}from"../../../../intl/number.js";import{getMaximumQuerySize as j,queryAllJSON as C}from"../../../../layers/support/featureQueryAll.js";import{assetMapFromAssetMapsJSON as w,extractMesh as I}from"../../../../rest/support/meshFeatureSet.js";import{direct3DObjectFeatureLayerDisplayEnabled as F,i3sPatchingEnabled as A,sceneLayerEditingEnabled as L}from"../../../../support/featureFlags.js";import{isTimeoutError as x}from"../../../../support/requestUtils.js";import{ViewingMode as E}from"../../../ViewingMode.js";import S from"../FeatureLayerView3D.js";const G="esri.views.3d.layers.i3s.I3SOverrides";let D=class extends i{constructor(e){super(e),this._warnMaximumChangedObjectsExceeded=!1,this._maximumNumberOfEditOVerrides=$,this._original3DOFLDefinitionExpression=null,this._interactiveEditingSessions=new d,this.geometryOverrides=new d,this._clientGeometryCache=new Map,this._associatedLayerView=null,this._attributeChangedObjectIds=new p,this._geometryChangedObjectIds=new p,this._pendingFetchChangedObjectIds=null,this._pendingFetchAbortController=new AbortController,this._featureIdLocks=new Map}initialize(){this._memCache=this.memoryController.newCache(`i3s-attribute-overrides-${this.layer.uid}`),this._pendingFetchChangedObjectIds=this._fetchChangedObjectIds(this._pendingFetchAbortController?.signal),this._pendingFetchChangedObjectIds.finally((()=>{this._pendingFetchAbortController=null,this._pendingFetchChangedObjectIds=null})),this.is3DOFL&&null!=this._associatedLayer&&(F()?this._associatedLayer.load().then((e=>{this.destroyed||(this._original3DOFLDefinitionExpression=e.definitionExpression,this.addHandles(y((()=>this._definitionExpression),(t=>e.definitionExpression=t),f)),this._associatedLayerView=new S({layer:this._associatedLayer,view:this.view}))})):A())}destroy(){this.is3DOFL&&null!=this._associatedLayer&&(F()?null!=this._associatedLayerView&&(this._associatedLayer.definitionExpression=this._original3DOFLDefinitionExpression):A()),this._set("layer",null),this._memCache=l(this._memCache),this._pendingFetchAbortController=u(this._pendingFetchAbortController),this._pendingFetchChangedObjectIds=null,this._featureIdLocks.clear()}get is3DOFL(){return L()&&null!=this._associatedLayer?.infoFor3D}get sortedGeometryChangedObjectIds(){return this.is3DOFL?[...this._geometryChangedObjectIds].sort(((e,t)=>e-t)):[]}get _associatedLayer(){return null==this.layer?null:this.layer.associatedLayer}get hasGeometryChanges(){return this._geometryChangedObjectIds.size>0}get _definitionExpression(){const e=this.sortedGeometryChangedObjectIds;return 0===e.length?"1 = 0":`OBJECTID IN (${e.join(",")})`}get updating(){if(!this.is3DOFL)return!1;if(this._pendingFetchChangedObjectIds)return!0;if(F()){return!(null!=this._associatedLayerView)||null!=this._associatedLayerView&&this._associatedLayerView.updating}return!1}get isEmpty(){return null==this._pendingFetchChangedObjectIds&&0===this._attributeChangedObjectIds.size&&0===this._geometryChangedObjectIds.size}featureHasGeometryChanges(e){return this._geometryChangedObjectIds.has(e)}featureHasAttributeChanges(e){return this._attributeChangedObjectIds.has(e)}createInteractiveEditSession(e){this._attributeChangedObjectIds.add(e);const t=this._interactiveEditingSessions,i=new M(e,(()=>{t.remove(i)}));return t.unshift(i),i}async applyAttributeOverrides(e,t,i,r=[]){if(this._pendingFetchChangedObjectIds&&await m(this._pendingFetchChangedObjectIds,i),null==t)return;const{attributeData:s,loadedAttributes:o}=t;if(null==o||null==s||0===this._attributeChangedObjectIds.size)return;const n=new Set;for(const d of o)n.add(d.index);for(const d of r)n.has(d.index)||(o.push(d),s[d.name]=new Array(e.length));const a=await this._lockFeatureIds(e);try{const t={attributeData:s,loadedAttributes:o},r=this._getOverridesFromCache(e,t,this._attributeChangedObjectIds),{objectIds:n,fieldNames:a}=r;if(0===n.length||0===a.length)return;const d=await this._queryAttributeOverridesFromAssociatedLayer(n,a,i);if(null==d)return;this._processOverridesFromAssociatedLayer(e,d,a,t)}finally{a.remove()}}updateGeometry(e,t){this._geometryChangedObjectIds.add(e);const i=this._clientGeometryCache.get(e);if(null!=i&&(this.geometryOverrides.remove(i),this._clientGeometryCache.delete(e)),null!=t){const i={oid:e,mesh:t};this.geometryOverrides.add(i),this._clientGeometryCache.set(e,i)}}updateAttributeValue(e,t,i){this._attributeChangedObjectIds.add(e),this._cacheAttributeValue(e,t,i)}featureAdded(e){this.is3DOFL&&A()&&this._geometryChangedObjectIds.add(e),this._attributeChangedObjectIds.add(e)}_cacheAttributeValue(e,t,i){this._memCache.put(this._getAttributeCacheKey(e,t),i,this._memCacheAttributeValueSize(i))}_getOverridesFromCache(e,{loadedAttributes:t,attributeData:i},r){const s=new Set,o=new Array;for(const a of t)o[a.index]=i[a.name];const n=new Set;for(let a=0;a<e.length;a++){const i=e[a];if(r.has(i))for(const e of t){const t=this._attributeFromCache(i,e.index);void 0===t?(s.add(i),n.add(e.name)):o[e.index][a]=t}}return{objectIds:Array.from(s),fieldNames:Array.from(n)}}_attributeFromCache(e,t){const i=this._fromInteractiveEditingSession(e,t);if(void 0!==i)return i;const r=this._getAttributeCacheKey(e,t);return this._memCache.get(r)}_fromInteractiveEditingSession(e,t){if(null!=this._interactiveEditingSessions)for(const i of this._interactiveEditingSessions){if(i.objectId!==e)continue;const r=i.getAttribute(t);if(void 0!==r)return r}}_getAttributeCacheKey(e,t){return`${e}-${t}`}async _queryAttributeOverridesFromAssociatedLayer(e,t,i){if(0===e.length)return null;this._logWarningIfMaximumObjectsExceeded();const{associatedLayer:r}=this.layer;if(null==r)return null;const s=r.createQuery(),{objectIdField:o}=r,n=[o,...t];s.where="1=1",s.returnGeometry=!1,s.outFields=n,s.cacheHint=!0;const a=await this._executeBatchQuery(r,e,s,i),d=[];for(const c of a)if(c.ok)for(const e of c.value.features)d.push(e);return d}async _queryGeometryOverridesFromAssociatedLayer(e,t){if(0===e.length||!this.is3DOFL||!A())return null;const i=this.layer.associatedLayer,r=i.infoFor3D,{spatialReference:s}=i,{state:{viewingMode:o},spatialReference:n}=this.view,a=o===E.Global,d=s.isGeographic;if(a&&!d)return h.getLogger(G).warn("unsupported-pcs-edits-in-global-view",this.layer.title,N(s,n,this.view.viewingMode,k.Mode)),null;if(!a&&d)return h.getLogger(G).warn("unsupported-gcs-edits-in-local-view",this.layer.title,N(s,n,this.view.viewingMode,k.Mode)),null;if(!(O(s,n)||a&&n.isWebMercator&&s.isWGS84))return h.getLogger(G).warn("unsupported-mismatched-spatial-reference-edits",this.layer.title,N(s,n,this.view.viewingMode,k.SpatialReference)),null;this._logWarningIfMaximumObjectsExceeded();const{objectIdField:c,globalIdField:l}=i,u=[c,...null!=l?[l]:[]],m=i.createQuery();m.where="1=1",m.returnGeometry=!0,m.outFields=u,m.cacheHint=!0,m.returnZ=i.hasZ,m.returnM=i.hasM;const g=await this._executeBatchQuery(i,e,m,t),p=[];for(const h of g){if(!h.ok)continue;const e=h.value,{assetMaps:t,features:i,globalIdFieldName:o}=e;if(null==t)continue;const n=w(r,t);for(const a of i){const e=I(a,o,s,r,n),t=a;null!=e?(t.geometry=e,p.push(t)):t.geometry=null}}return p}_logWarningIfMaximumObjectsExceeded(){if(!this._warnMaximumChangedObjectsExceeded)return;this._warnMaximumChangedObjectsExceeded=!1;let e=`The number of edited objects that are not yet cached in the scene service exceeds the maximum limit. Attribute changes will only be available for the first ${v(this._maximumNumberOfEditOVerrides)} objects. Please consider re-caching the scene service`;const t=this.layer.portalItem;t&&t.loaded?e+=` (${t.portal.url}/home/item.html?id=${t.id}#settings)`:e+=` (${this.layer.parsedUrl.path})`,h.getLogger(G).warn("#queryOverrides()",this.layer.title,`${e}.`)}async _executeBatchQuery(e,t,i,o){if(0===t.length)return[];const n=j(e);t=[...t].sort(((e,t)=>e-t));const a=r(t,n).map((t=>{const r=i.clone();return r.objectIds=t,s(C(e,r,{signal:o}))}));return Promise.all(a)}_processOverridesFromAssociatedLayer(e,t,i,{loadedAttributes:r,attributeData:s}){const o=this._associatedLayer;if(null==o)return;const n=o.objectIdField,a=i.map((t=>(t in s||(s[t]=new Array(e.length)),s[t]))),d=new Map(r.map((e=>[e.name,e.index]))),c=i.map((e=>d.get(e))),h=new Map(Array.from(e,((e,t)=>[e,t])));for(const l of t){const e=l.attributes[n];for(let t=0;t<i.length;t++){const r=c[t],s=h.get(e),o=l.attributes[i[t]];a[t][s]=o,this._cacheAttributeValue(e,r,o)}}}_memCacheAttributeValueSize(e){return"string"==typeof e?n(e):a()}async _fetchChangedObjectIds(e){const i=this.layer;await i.load({signal:e}),this._geometryChangedObjectIds.clear(),this._attributeChangedObjectIds.clear();const{associatedLayer:r}=i;if(null==r||!r.capabilities?.operations?.supportsChangeTracking)return;const s=this._getFetchChangedObjectIdsServerGen();if(null==s)return;const n=r.layerId,a=this.is3DOFL,d={f:"json",returnIdsOnly:!0,layers:`[${n}]`,returnUpdates:!0,returnDeletes:a,returnInserts:a,layerServerGens:JSON.stringify([{id:n,serverGen:s}])};if(a){const e=r.infoFor3D;d.fieldsToCompare=JSON.stringify({fields:[...Object.values(e.transformFieldRoles),e.sourceHashField]})}const c=await o(t(`${r.url}/extractChanges`,{method:"post",query:d,timeout:V,signal:e}));if(!c.ok&&x(c.error)){const e=this.layer.title;h.getLogger(G).warn("extractChanges:timeout",e,`${e} could not obtain edited features that are not cached in the scene service. Display of features may not be up to date with the latest edits. Consider re-caching the scene service.`)}if(c.ok&&1===c.value.data?.edits?.length){const t=c.value.data.edits[0],i=t?.objectIds,s=t?.fieldUpdates,o=i?.adds??[],n=i?.updates??[],d=i?.deletes??[],h=[...o,...n,...d],l=a?[...o,...s??n,...d]:[],u=Math.min(this._maximumNumberOfEditOVerrides,h.length);u<h.length&&(this._warnMaximumChangedObjectsExceeded=!0);const m=h.sort(((e,t)=>e-t));for(let e=0;e<u;++e){const t=m[e];this._attributeChangedObjectIds.add(t)}for(const e of l)this._geometryChangedObjectIds.add(e);if(this.is3DOFL&&A()&&this._geometryChangedObjectIds.size>0){const t=await this._queryGeometryOverridesFromAssociatedLayer(Array.from(this._geometryChangedObjectIds),e);if(null!=t)for(const e of t)null!=e.geometry&&this.updateGeometry(e.attributes[r.objectIdField],e.geometry)}}}_getFetchChangedObjectIdsServerGen(){const e=this.layer;if(null!=e.serviceUpdateTimeStamp?.lastUpdate)return e.serviceUpdateTimeStamp.lastUpdate;const t=e.associatedLayer;return null!=t?.serverGens?.minServerGen?t.serverGens.minServerGen:null}async _lockFeatureIds(e){const t=this._featureIdLocks;let i=!0;for(;i;){const r=new Array;for(const i of e){const e=t.get(i);e&&r.push(e)}0===r.length?i=!1:await Promise.all(r)}const r=g(),s=r.promise;for(const o of e)t.set(o,s);return c((()=>{for(const i of e)t.delete(i);r.resolve()}))}get test(){const e=Array.from(this._attributeChangedObjectIds),t=this._pendingFetchChangedObjectIds,i=this;return{changedObjectIds:e,pendingFetchChangedObjectIds:t,get maximumNumberOfEditOVerrides(){return i._maximumNumberOfEditOVerrides},set maximumNumberOfEditOVerrides(e){i._maximumNumberOfEditOVerrides=e}}}};e([b({constructOnly:!0})],D.prototype,"view",void 0),e([b({constructOnly:!0})],D.prototype,"layer",void 0),e([b({readOnly:!0})],D.prototype,"is3DOFL",null),e([b()],D.prototype,"_interactiveEditingSessions",void 0),e([b({readOnly:!0})],D.prototype,"sortedGeometryChangedObjectIds",null),e([b({readOnly:!0})],D.prototype,"geometryOverrides",void 0),e([b()],D.prototype,"_clientGeometryCache",void 0),e([b()],D.prototype,"_associatedLayer",null),e([b()],D.prototype,"_associatedLayerView",void 0),e([b({constructOnly:!0})],D.prototype,"memoryController",void 0),e([b()],D.prototype,"_attributeChangedObjectIds",void 0),e([b()],D.prototype,"_geometryChangedObjectIds",void 0),e([b()],D.prototype,"hasGeometryChanges",null),e([b()],D.prototype,"_pendingFetchChangedObjectIds",void 0),e([b()],D.prototype,"_pendingFetchAbortController",void 0),e([b()],D.prototype,"_definitionExpression",null),e([b()],D.prototype,"updating",null),e([b()],D.prototype,"isEmpty",null),D=e([_(G)],D);class M{constructor(e,t){this.objectId=e,this._remove=t,this._updates=new Map,this._isActive=!0}getAttribute(e){return this._updates.get(e)}setAttribute(e,t){this.isActive&&this._updates.set(e,t)}remove(){this.isActive&&(this._isActive=!1,this._remove())}get isActive(){return this._isActive}}const V=1e4,$=5e4;var k;function N(e,t,i,r){return`Displaying the edits of a SceneLayer with a${r===k.Mode?e.isGeographic?" geographic ":" projected ":" "}spatial reference (wkid:${e.wkid}) in ${i} viewing mode${r===k.SpatialReference?` with spatial reference (wkid:${t.wkid}) `:" "}is not supported. No geometry edits will be displayed for this layer.\nPlease consider re-caching the scene service or changing the ${r===k.Mode?"viewing mode":"view spatial reference"} to display edits.`}!function(e){e[e.Mode=0]="Mode",e[e.SpatialReference=1]="SpatialReference"}(k||(k={}));export{D as I3SOverrides};
@@ -0,0 +1,5 @@
1
+ /*
2
+ All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
+ See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
+ */
5
+ import e from"../../../core/Logger.js";import{equals as t,isGeographic as r,isWebMercator as i,isWGS84 as o}from"../../../geometry/support/spatialReferenceUtils.js";import{getMimeTypeFormatId as s,getFilenameFormatId as n}from"../../../layers/support/infoFor3D.js";import{ViewingMode as a}from"../../ViewingMode.js";const d="esri.views.layers.support.editableLayerViews";function c(c,l){const{associatedLayer:g}=c,p=g?.infoFor3D;if(!!!p)return!1;const{supportedFormats:u,queryFormats:f}=p,w=s("model/gltf-binary",u)??n("glb",u);if(!(null!=w&&f.includes(w)))return e.getLogger(d).warnOnce(`SceneLayer (${c.title??"Untitled layer"}, ${c.id}) does not support geometry edits because it does not support GLB queries.`),!1;const y=c.spatialReference,m=g.spatialReference;if(!t(y,m))return e.getLogger(d).warnOnce(`SceneLayer (${c.title??"Untitled layer"}, ${c.id}) does not support geometry edits because its spatial reference (wkid:${y.wkid}) is different from its associated FeatureLayer's spatial reference (wkid:${m.wkid}).`),!1;const $=g.sourceJSON.sourceSpatialReference;if(!(null==$||t($,m)))return e.getLogger(d).warnOnce(`SceneLayer (${c.title??"Untitled layer"}, ${c.id}) does not support geometry edits because the spatial reference of its associated FeatureLayer's service (wkid:${m.wkid}) is different from its source spatial reference (wkid:${$.wkid}).`),!1;const{view:{spatialReference:L,state:{viewingMode:k}}}=l,b=r(y),v=k===a.Global;if(b&&!v)return e.getLogger(d).warnOnce(`SceneLayer (${c.title??"Untitled layer"}, ${c.id}) does not support geometry edits in local viewing mode because its spatial reference (wkid:${y.wkid}) is geographic. Please consider changing the viewing mode to global.`),!1;if(!b&&v)return e.getLogger(d).warnOnce(`SceneLayer (${c.title??"Untitled layer"}, ${c.id}) does not support geometry edits in global viewing mode because its spatial reference (wkid:${y.wkid}) is projected. Please consider changing the viewing mode to local.`),!1;return!!(t(y,L)||v&&i(L)&&o(y))||(e.getLogger(d).warnOnce(`SceneLayer (${c.title??"Untitled layer"}, ${c.id}) does not support geometry edits because its spatial reference (wkid:${y.wkid}) does not match the view spatial reference (wkid:${L.wkid}).`),!1)}export{c as isGeometryEditableSceneLayer};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as t}from"../../chunks/tslib.es6.js";import{createTask as e}from"../../core/asyncUtils.js";import a from"../../core/Collection.js";import{deprecatedProperty as r,deprecated as i}from"../../core/deprecate.js";import s from"../../core/Error.js";import o from"../../core/Evented.js";import{makeHandle as n}from"../../core/handleUtils.js";import l from"../../core/Logger.js";import{abortMaybe as p,removeMaybe as d,destroyMaybe as c}from"../../core/maybe.js";import{throwIfAborted as u,createResolver as h}from"../../core/promiseUtils.js";import{watch as w,on as f,when as m,whenOnce as y,syncAndInitial as k,initial as g,sync as v}from"../../core/reactiveUtils.js";import{property as _}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as W}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as b}from"../../core/support/UpdatingHandles.js";import I from"../../layers/GraphicsLayer.js";import{isEditableLayer as F}from"../../layers/support/editableLayers.js";import{isFeatureLayer as E,getOwningPortalUrl as M}from"../../layers/support/layerUtils.js";import{parseKnownArcGISOnlineDomain as C}from"../../portal/support/urlUtils.js";import V from"../../views/interactive/sketch/SketchOptions.js";import{SnappingManager as O}from"../../views/interactive/snapping/SnappingManager.js";import U from"../../views/interactive/snapping/SnappingOptions.js";import T from"../Attachments/AttachmentsViewModel.js";import L from"./CreateFeaturesWorkflow.js";import A from"./UpdateWorkflow.js";import{whenEditorLayerView as j}from"./workflowUtils.js";import S from"./support/EditorItem.js";import P from"../FeatureTemplates/FeatureTemplatesViewModel.js";import R from"../Sketch/SketchViewModel.js";import H from"../Spinner/SpinnerViewModel.js";const x="esri.widgets.Editor.EditorViewModel",G=()=>l.getLogger(x),D=["create-features","update"];function q(t,e,a){G().error(new s(t,e,a))}function B(t,e){return t?.find((t=>t.layer===e))}let Q=class extends o.EventedAccessor{constructor(t){super(t),this._sketchEventListenerHandle=null,this._sketchGraphicsLayer=new I({listMode:"hide",internal:!0}),this._snappingManager=null,this._updateItemsTask=null,this._updatingHandles=new b,this._featureTemplatesViewModelLocked=!1,this.activeWorkflow=null,this._activityQueue=new a,this.editorItems=new a,this.failures=[],this.hideTemplatesForInactiveLayers=!1,this.attachmentsViewModel=new T({capabilities:{editing:!0}}),this.featureTemplatesViewModel=new P({disabledItemFunction:({layer:t})=>this._itemIsSuspended(t)}),this.ownSketchViewModel=new R({layer:this._sketchGraphicsLayer}),this.sketchOptions=new V,this.snappingOptions=new U,this.spinnerViewModel=new H,this.pageStack=[],this.showDiscardEditsPrompt=()=>Promise.resolve(!0),this._candidateCommitted=!1,this.back=async()=>{this.canGoBack&&(this.activeWorkflow?.hasPreviousStep?await this.activeWorkflow.back(this.showDiscardEditsPrompt):await this._cancelWorkflow({force:!this.hasPendingEdits}))},this.saveWorkflow=async()=>{const{featureFormViewModel:t}=this;if(t){if(t.submit(),!t.submittable)return;const e=t.getValues();if(t.validateContingencyConstraints(e,{includeIncompleteViolations:!0}).length>0)return}await(this.activeWorkflow?.save())},this.selectFeature=(t,e=!1)=>{const a=this.activeWorkflow;this._candidateCommitted||"update"!==a?.type||(a.data.rootFeature=t,e&&(a.next(),this._candidateCommitted=!0))}}initialize(){this.addHandles([w((()=>{const t=this.view,e=t?.map?.editableLayers,a=t?.allLayerViews,r=a?.filter((t=>!!e?.includes(t.layer)));return[e,r,this.layerInfos,this.allowedWorkflows]}),(()=>this._updateEditorItems()),k),w((()=>this.hideTemplatesForInactiveLayers),(()=>this.syncFeatureTemplates())),f((()=>this.activeWorkflow),"cancel",(()=>this.emit("workflow-cancel"))),f((()=>this.activeWorkflow),"commit",(()=>this.emit("workflow-commit"))),f((()=>this.activeWorkflow),"complete",(()=>{this.emit("workflow-commit"),this._set("activeWorkflow",null)})),m((()=>this.view?.map),(t=>t.add(this._sketchGraphicsLayer)),g),f((()=>this.editorItems),"change",(()=>this._afterEditorItemsChange())),w((()=>[this.canCreate,this.canUpdateVisible]),(()=>this._afterEditorItemsChange())),w((()=>this.page),((t,e)=>{const a=[...this.pageStack];if(-1===a.indexOf(t))a.push(t);else for(;a.length&&a.at(-1)!==t;)a.pop();this.pageStack=a}),k),m((()=>"awaiting-update-feature-candidate"===this.state),(()=>this._candidateCommitted=!1)),f((()=>this.featureTemplatesViewModel),"select",(async({item:t,oldItem:e})=>{const{activeWorkflow:a}=this;if(a){if("update"===a.type&&"awaiting-feature-creation-info"===a.activeWorkflow?.stepId)return;try{await this.cancelWorkflow({force:!this.hasPendingEdits})}catch{return void this.featureTemplatesViewModel.select(e,{emit:!1})}}if(!t)return;const r={layer:t.layer,template:t.template};if(t.supportsUpload)return this.featureTemplatesViewModel.select(e,{emit:!1}),this.startCreateFeaturesWorkflow(r);this.startCreateFeaturesWorkflowAtFeatureCreation(r)})),f((()=>this.view),"key-down",(t=>{"Escape"===t.key&&this.activeWorkflow?.keyboardCancellationEnabled&&(t.stopPropagation(),this.back())})),f((()=>this.sketchViewModel),["create","delete","update"],(t=>{const{activeWorkflow:e}=this,a="update"===e?.type,r=a?e.activeWorkflow?.layer:e?.layer,i=a?e?.activeWorkflow?.parentLayer:void 0,s=`sketch-${t.type}`;this.emit(s,{type:s,detail:t,layer:r,parentLayer:i})}),v),w((()=>this.view),(t=>{if(this._snappingManager=c(this._snappingManager),!t)return;const e=this.snappingOptions;this._snappingManager=new O({view:t,options:e})}),k),w((()=>this.snappingOptions),(t=>{this._snappingManager&&(this._snappingManager.options=t)}),k)])}destroy(){this._cancelWorkflow({warnIfNoWorkflow:!1}).then((()=>{this.view?.map?.remove(this._sketchGraphicsLayer),this.view=null})),this._updateItemsTask=p(this._updateItemsTask),this._updatingHandles.destroy(),this._sketchEventListenerHandle=d(this._sketchEventListenerHandle)}get allowedWorkflows(){return this._get("allowedWorkflows")}set allowedWorkflows(t){r(l.getLogger(this),"allowedWorkflows",{replacement:"Editor.visibleElements",version:"4.29",warnOnce:!0}),t&&0!==t.length||(t=[...D]),this._set("allowedWorkflows",t)}get canCreate(){return this.editorItems.some((t=>t.supportsCreateFeaturesWorkflow))}get canCreateVisible(){return!!this.featureTemplatesLayers.length}get canUpdate(){return this.editorItems.some((t=>t.supportsUpdateWorkflow))}get canUpdateVisible(){return this.editorItems.some((t=>t.supportsUpdateWorkflow&&t.visible))}get featureTemplatesLayers(){const t=new a;for(const e of this.editorItems){const a=e.supportsCreateFeaturesWorkflow&&!e.isTable,r=this.hideTemplatesForInactiveLayers&&!e.visible;a&&!r&&t.push(e.layer)}return t}get editableItems(){return r(l.getLogger(this),"editableItems",{replacement:"editorItems",version:"4.29",warnOnce:!0}),this.editorItems.map((t=>{const{capabilities:e,disabled:a,hasInvalidFormTemplate:r,layer:i}=t,s=[],o=e.create,n=e.update,l=e.delete;return o.enabled&&s.push("create"),n.enabled&&s.push("update"),l.enabled&&s.push("delete"),{layer:i,supports:s,suspended:a,attributeUpdatesEnabled:n.attributes,geometryUpdatesEnabled:n.geometry,attachmentsOnCreateEnabled:o.attachments.enabled,attachmentsOnUpdateEnabled:n.attachments.enabled,hasInvalidFormTemplate:r,hasAttachments:e.attachments.enabled}}))}get featureFormViewModel(){const{activeWorkflow:t}=this;return"update"===t?.type?t.activeFeatureFormViewModel:"create-features"===t?.type?t.featureFormViewModel:null}get labelOptions(){return this.sketchOptions.labels}set labelOptions(t){this.sketchOptions.labels=t}set layerInfos(t){const e=t?.some((t=>"allowAttachments"in t));e&&i(G(),"Property: layerInfo.allowAttachments",{replacement:"layerInfo.attachmentsOnCreateEnabled or layerInfo.attachmentsOnUpdateEnabled",version:"4.26"}),this._set("layerInfos",t)}get sketchViewModel(){const{activeWorkflow:t}=this;return"update"===t?.type?t.activeSketchViewModel:"create-features"===t?.type?t.sketchViewModel:this.ownSketchViewModel}get state(){if(!this.view?.ready)return"disabled";const t=this.attachmentsViewModel.mode;if("add"===t)return"adding-attachment";if("edit"===t)return"editing-attachment";const{activeWorkflow:e}=this;return e?.stepId?"update"===e.type&&e.activeWorkflow?.stepId?e.activeWorkflow.stepId:e.stepId:"ready"}get syncing(){return this._activityQueue.length>0}get updating(){return this._updatingHandles.updating||!0===this.activeWorkflow?.updating}get tooltipOptions(){return this.sketchOptions.tooltips}set tooltipOptions(t){this.sketchOptions.tooltips=t}get valueOptions(){return this.sketchOptions.values}set valueOptions(t){this.sketchOptions.values=t}set view(t){this.ownSketchViewModel.view=t,this.spinnerViewModel.view=t,this._set("view",t)}get page(){const{activeWorkflow:t,state:e}=this;if("update"===t?.type&&"awaiting-feature-to-update"===t.stepId)return"ready";if("create-features"===t?.type&&0===t.numPendingFeatures){const e=t.data.upload;if(e)return"default"===e.state?"ready":"creating-features-upload-details"}return e??"disabled"}get featureFormDisabled(){const{activeWorkflow:t}=this;return"update"===t?.type&&!1===t.activeEditorItem?.capabilities.update.attributes}get canGoBack(){return null!=this.activeWorkflow&&!this.syncing}get shouldShowDeleteButton(){const{activeWorkflow:t}=this;return!!t&&"update"===t.type&&!!t.activeEditorItem?.capabilities.delete.enabled}get hasPendingEdits(){return this.activeWorkflow?.hasPendingEdits??!1}async startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.startCreateFeaturesWorkflow()}async startCreateFeaturesWorkflowAtFeatureCreation(t){return this.startCreateFeaturesWorkflow(t,"creating-features")}async startCreateFeaturesWorkflow(t,e="awaiting-feature-creation-info"){if(await y((()=>!this.updating)),!this.canCreate)throw new s("editing:unsupported-workflow","Creating features is unsupported or disabled.");const a=this._createUpdatingResolver();await this._cancelWorkflow();const r=this._createCreateFeaturesWorkflow(t,e);this._set("activeWorkflow",r),await r.start(),a.resolve()}async startCreateFeaturesWorkflowAtFeatureEdit(t){await y((()=>!this.updating));const e=this._createUpdatingResolver(),{initialFeature:a}=t,r=a.sourceLayer,i=r?this.findEditorItemForLayer(r):void 0;if(!i?.supportsCreateFeaturesWorkflow)throw new s("editing:unsupported-workflow","Creating features is unsupported or disabled for this layer.");await this._cancelWorkflow();const o=this._createCreateFeaturesWorkflow({initialFeature:a,layer:i.layer,maxFeatures:1},"creating-features");this._set("activeWorkflow",o),await o.start(),e.resolve()}async startUpdateWorkflowAtFeatureSelection(){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const t=this._createUpdatingResolver();await this._cancelWorkflow();const e=this._createUpdateWorkflow();this._set("activeWorkflow",e),await e.start(),t.resolve()}async startUpdateWorkflowAtMultipleFeatureSelection(t){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const e=this._createUpdatingResolver();await this._cancelWorkflow();const a=this._createUpdateWorkflow("awaiting-update-feature-candidate");a.data.candidates=t,this._set("activeWorkflow",a),await a.start(),e.resolve()}async startUpdateWorkflowAtFeatureEdit(t){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const e=this._createUpdatingResolver();await this._cancelWorkflow();const a=this._createUpdateWorkflow("editing-existing-feature");a.data.rootFeature=t,this._set("activeWorkflow",a),await a.start(),e.resolve()}async deleteFeatureFromWorkflow(){const{activeWorkflow:t}=this;t&&"update"===t.type?await t.deleteActiveFeature():q("editing:unsupported-workflow","Deleting requires an active update workflow.")}async cancelWorkflow(t){return this._cancelWorkflow({warnIfNoWorkflow:!0,...t})}findEditorItemForLayer(t){const e="subtype-sublayer"===t.type?t.parent:t;return this.editorItems.find((t=>t.layer===e))}itemHasInvalidFormTemplate(t){return null!=t&&!0===this.findEditorItemForLayer(t.layer)?.hasInvalidFormTemplate}syncFeatureTemplates(){this._featureTemplatesViewModelLocked||(this.featureTemplatesViewModel.layers=this.featureTemplatesLayers.toArray())}async toggleUpdateWorkflow(){this.canUpdate&&(this.hasPendingEdits&&!await this.showDiscardEditsPrompt()||(this.activeWorkflow&&"awaiting-feature-to-update"===this.state?await this.cancelWorkflow({force:!0}):await this.startUpdateWorkflowAtFeatureSelection()))}lockFeatureTemplatesViewModel(){return this._featureTemplatesViewModelLocked=!0,n((()=>{this._featureTemplatesViewModelLocked=!1,this.syncFeatureTemplates()}))}async _getEditorItemCandidates(t){const{view:e}=this;if(!e?.map)return[];const{map:a}=e,r=a.editableLayers.toArray()??[],i=a.allTables.toArray().filter(E)??[];return await Promise.allSettled([...r.map((t=>"subtype-group"===t.type?t.loadAll():Promise.resolve())),...i.map((t=>t.load()))]),u(t),[...r.reverse(),...i.reverse()].filter((t=>{if(!F(t))return!1;const{geometryType:a,spatialReference:r}=t;if("mesh"===a){if("3d"!==e.type)return!1;const{isGeographic:t}=r;switch(e.viewingMode){case"global":return t;case"local":return!t}}return!0})).flatMap((t=>"subtype-group"===t.type?t.sublayers.toArray():t))}_drainEditorItems(){this.editorItems.drain((t=>t.destroy()))}async _updateEditorItems(){p(this._updateItemsTask);const{view:t}=this,a=e((async e=>{if(!t?.map||!t?.allLayerViews)return;const a=await this._getEditorItemCandidates(e);if(!a.length)return void this._drainEditorItems();const r=[],i=[],s=[],{layerInfos:o}=this;for(const l of a){const e=B(o,l),a=await j(t,l).catch((()=>null));(e?r:a?i:s).push(new S({layer:l,layerInfo:e,layerView:a}))}o?.length&&r.sort(((t,e)=>o.findIndex((({layer:e})=>e===t.layer))-o.findIndex((({layer:t})=>t===e.layer))));const n=[...r,...i,...s];e.aborted||(this._drainEditorItems(),this.editorItems.addMany(n))}));this._updatingHandles.addPromise(a.promise),this._updateItemsTask=a}_afterEditorItemsChange(){const{activeWorkflow:t}=this;if(this.syncFeatureTemplates(),!t)return;const{stepId:e}=t;"create-features"!==t.type?"update"===t.type&&("awaiting-feature-to-update"===e&&!this.canUpdateVisible||"awaiting-update-feature-candidate"===e&&!t.hasUpdatableCandidates)&&this._cancelWorkflow():"awaiting-feature-creation-info"!==e||this.canCreate||this._cancelWorkflow()}async _cancelWorkflow(t){const e=this.activeWorkflow;if(!e)return void(t?.warnIfNoWorkflow&&q("editing:no-active-workflow","There is no active workflow to cancel."));if(!t||!1!==t.force)return this.emit("workflow-cancel"),this._set("activeWorkflow",null),void await e.cancel(t);await e.cancel(t),this._set("activeWorkflow",null)}_createCreateFeaturesWorkflow(t,e){return L.create({viewModel:this,creationInfo:t,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:e,applyEditsCallback:(t,e,a)=>this._applyEdits(t,e,a),addAttachmentsCallback:(t,e)=>this._addAttachments(t,e)})}_createUpdateWorkflow(t){return A.create({viewModel:this,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:t,applyEditsCallback:(t,e,a)=>this._applyEdits(t,e,a),addAttachmentsCallback:(t,e)=>this._addAttachments(t,e)})}_addAttachments(t,e){const a=e.map((e=>this._addAttachment(t,e.feature,e.attachment)))??[];return Promise.all(a)}async _addAttachment(t,e,a){let r=null;if(!("addAttachment"in t)||null==t.capabilities?.attachment)throw new s("editor:attachments-not-supported","Adding attachments is not supported for this layer type");return await this._queueOperation((async()=>(r=await(t.addAttachment?.(e,a).catch((t=>{throw t?.error||t})))??null,r))),r}async _applyEdits(t,e,a){let r=null;const i=t.url?await M(t.url):null,s={returnServiceEditsOption:(!i||!C(i))&&!RegExp("/hosted/","i").test(t.url)?"original-and-current-features":void 0,...a};return await this._queueOperation((async()=>{const{view:a}=this;if(!a)return null;const i=await j(a,t).catch((()=>null));return r=await t.applyEdits(e,s),i&&await y((()=>!i.updating)),r})),r}_queueOperation(t){this._activityQueue.push(t);const e=(t,e)=>{const a=e.indexOf(t);a>-1&&e.splice(a,1)};return t().then((t=>{if(null!=t&&"error"in t&&null!=t.error)throw t.error;if(null!=t&&"addFeatureResults"in t){const{addFeatureResults:e,deleteFeatureResults:a,updateFeatureResults:r}=t,i=e.find((t=>!!t.error))||r.find((t=>!!t.error))||a.find((t=>!!t.error));if(i)throw i.error}return t})).catch((a=>{q("editing:operation-error","An error occurred.",{error:a});const r={error:a,retry:()=>(e(r,this.failures),this._queueOperation(t)),cancel:()=>{e(r,this.failures)}};this._set("failures",[...this.failures,r])})).then((()=>{e(t,this._activityQueue)}))}_createUpdatingResolver(){const t=h();return this._updatingHandles.addPromise(t.promise),t}_itemIsSuspended(t){const e=this.findEditorItemForLayer(t);return null!=e&&(!e.visible||e.disabled)}};t([_({readOnly:!0})],Q.prototype,"activeWorkflow",void 0),t([_({readOnly:!0})],Q.prototype,"_activityQueue",void 0),t([_({value:[...D]})],Q.prototype,"allowedWorkflows",null),t([_({readOnly:!0})],Q.prototype,"canCreate",null),t([_()],Q.prototype,"canCreateVisible",null),t([_({readOnly:!0})],Q.prototype,"canUpdate",null),t([_()],Q.prototype,"canUpdateVisible",null),t([_()],Q.prototype,"featureTemplatesLayers",null),t([_()],Q.prototype,"editableItems",null),t([_()],Q.prototype,"editorItems",void 0),t([_({readOnly:!0})],Q.prototype,"failures",void 0),t([_()],Q.prototype,"hideTemplatesForInactiveLayers",void 0),t([_()],Q.prototype,"attachmentsViewModel",void 0),t([_()],Q.prototype,"featureFormViewModel",null),t([_()],Q.prototype,"featureTemplatesViewModel",void 0),t([_()],Q.prototype,"labelOptions",null),t([_()],Q.prototype,"layerInfos",null),t([_()],Q.prototype,"ownSketchViewModel",void 0),t([_()],Q.prototype,"sketchOptions",void 0),t([_()],Q.prototype,"sketchViewModel",null),t([_({type:U,nonNullable:!0})],Q.prototype,"snappingOptions",void 0),t([_()],Q.prototype,"spinnerViewModel",void 0),t([_()],Q.prototype,"state",null),t([_({readOnly:!0})],Q.prototype,"syncing",null),t([_()],Q.prototype,"updating",null),t([_()],Q.prototype,"tooltipOptions",null),t([_()],Q.prototype,"valueOptions",null),t([_()],Q.prototype,"view",null),t([_()],Q.prototype,"pageStack",void 0),t([_()],Q.prototype,"showDiscardEditsPrompt",void 0),t([_()],Q.prototype,"_candidateCommitted",void 0),t([_()],Q.prototype,"page",null),t([_()],Q.prototype,"featureFormDisabled",null),t([_()],Q.prototype,"canGoBack",null),t([_()],Q.prototype,"shouldShowDeleteButton",null),t([_()],Q.prototype,"hasPendingEdits",null),Q=t([W(x)],Q);const N=Q;export{N as default};
5
+ import{_ as t}from"../../chunks/tslib.es6.js";import{createTask as e}from"../../core/asyncUtils.js";import a from"../../core/Collection.js";import{deprecatedProperty as r,deprecated as i}from"../../core/deprecate.js";import s from"../../core/Error.js";import o from"../../core/Evented.js";import{makeHandle as n}from"../../core/handleUtils.js";import l from"../../core/Logger.js";import{abortMaybe as p,removeMaybe as d,destroyMaybe as c}from"../../core/maybe.js";import{throwIfAborted as u,createResolver as h}from"../../core/promiseUtils.js";import{watch as w,on as f,when as m,whenOnce as y,syncAndInitial as k,initial as g,sync as v}from"../../core/reactiveUtils.js";import{property as _}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as W}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as b}from"../../core/support/UpdatingHandles.js";import I from"../../layers/GraphicsLayer.js";import{isEditableLayer as F}from"../../layers/support/editableLayers.js";import{isFeatureLayer as E,getOwningPortalUrl as M}from"../../layers/support/layerUtils.js";import{parseKnownArcGISOnlineDomain as C}from"../../portal/support/urlUtils.js";import V from"../../views/interactive/sketch/SketchOptions.js";import{SnappingManager as O}from"../../views/interactive/snapping/SnappingManager.js";import U from"../../views/interactive/snapping/SnappingOptions.js";import T from"../Attachments/AttachmentsViewModel.js";import L from"./CreateFeaturesWorkflow.js";import A from"./UpdateWorkflow.js";import{whenEditorLayerView as j}from"./workflowUtils.js";import S from"./support/EditorItem.js";import P from"../FeatureTemplates/FeatureTemplatesViewModel.js";import R from"../Sketch/SketchViewModel.js";import H from"../Spinner/SpinnerViewModel.js";const x="esri.widgets.Editor.EditorViewModel",D=()=>l.getLogger(x),G=["create-features","update"];function q(t,e,a){D().error(new s(t,e,a))}function B(t,e){return t?.find((t=>t.layer===e))}let Q=class extends o.EventedAccessor{constructor(t){super(t),this._sketchEventListenerHandle=null,this._sketchGraphicsLayer=new I({listMode:"hide",internal:!0}),this._snappingManager=null,this._updateItemsTask=null,this._updatingHandles=new b,this._featureTemplatesViewModelLocked=!1,this.activeWorkflow=null,this._activityQueue=new a,this.editorItems=new a,this.failures=[],this.hideTemplatesForInactiveLayers=!1,this.attachmentsViewModel=new T({capabilities:{editing:!0}}),this.featureTemplatesViewModel=new P({disabledItemFunction:({layer:t})=>this._itemIsSuspended(t)}),this.ownSketchViewModel=new R({layer:this._sketchGraphicsLayer}),this.sketchOptions=new V,this.snappingOptions=new U,this.spinnerViewModel=new H,this.pageStack=[],this.showDiscardEditsPrompt=()=>Promise.resolve(!0),this._candidateCommitted=!1,this.back=async()=>{this.canGoBack&&(this.activeWorkflow?.hasPreviousStep?await this.activeWorkflow.back(this.showDiscardEditsPrompt):await this._cancelWorkflow({force:!this.hasPendingEdits}))},this.saveWorkflow=async()=>{const{featureFormViewModel:t}=this;if(t){if(t.submit(),!t.submittable)return;const e=t.getValues();if(t.validateContingencyConstraints(e,{includeIncompleteViolations:!0}).length>0)return}await(this.activeWorkflow?.save())},this.selectFeature=(t,e=!1)=>{const a=this.activeWorkflow;this._candidateCommitted||"update"!==a?.type||(a.data.rootFeature=t,e&&(a.next(),this._candidateCommitted=!0))}}initialize(){this.addHandles([w((()=>{const t=this.view,e=t?.map?.editableLayers,a=t?.allLayerViews,r=a?.filter((t=>!!e?.includes(t.layer)));return[e,r,this.layerInfos,this.allowedWorkflows]}),(()=>this._updateEditorItems()),k),w((()=>this.hideTemplatesForInactiveLayers),(()=>this.syncFeatureTemplates())),f((()=>this.activeWorkflow),"cancel",(()=>this.emit("workflow-cancel"))),f((()=>this.activeWorkflow),"commit",(()=>this.emit("workflow-commit"))),f((()=>this.activeWorkflow),"complete",(()=>{this.emit("workflow-commit"),this._set("activeWorkflow",null)})),m((()=>this.view?.map),(t=>t.add(this._sketchGraphicsLayer)),g),f((()=>this.editorItems),"change",(()=>this._afterEditorItemsChange())),w((()=>[this.canCreate,this.canUpdateVisible]),(()=>this._afterEditorItemsChange())),w((()=>this.page),((t,e)=>{const a=[...this.pageStack];if(-1===a.indexOf(t))a.push(t);else for(;a.length&&a.at(-1)!==t;)a.pop();this.pageStack=a}),k),m((()=>"awaiting-update-feature-candidate"===this.state),(()=>this._candidateCommitted=!1)),f((()=>this.featureTemplatesViewModel),"select",(async({item:t,oldItem:e})=>{const{activeWorkflow:a}=this;if(a){if("update"===a.type&&"awaiting-feature-creation-info"===a.activeWorkflow?.stepId)return;try{await this.cancelWorkflow({force:!this.hasPendingEdits})}catch{return void this.featureTemplatesViewModel.select(e,{emit:!1})}}if(!t)return;const r={layer:t.layer,template:t.template};if(t.supportsUpload)return this.featureTemplatesViewModel.select(e,{emit:!1}),this.startCreateFeaturesWorkflow(r);this.startCreateFeaturesWorkflowAtFeatureCreation(r)})),f((()=>this.view),"key-down",(t=>{"Escape"===t.key&&this.activeWorkflow?.keyboardCancellationEnabled&&(t.stopPropagation(),this.back())})),f((()=>this.sketchViewModel),["create","delete","update"],(t=>{const{activeWorkflow:e}=this,a="update"===e?.type,r=a?e.activeWorkflow?.layer:e?.layer,i=a?e?.activeWorkflow?.parentLayer:void 0,s=`sketch-${t.type}`;this.emit(s,{type:s,detail:t,layer:r,parentLayer:i})}),v),w((()=>this.view),(t=>{if(this._snappingManager=c(this._snappingManager),!t)return;const e=this.snappingOptions;this._snappingManager=new O({view:t,options:e})}),k),w((()=>this.snappingOptions),(t=>{this._snappingManager&&(this._snappingManager.options=t)}),k)])}destroy(){this._cancelWorkflow({warnIfNoWorkflow:!1}).then((()=>{this.view?.map?.remove(this._sketchGraphicsLayer),this.view=null})),this._updateItemsTask=p(this._updateItemsTask),this._updatingHandles.destroy(),this._sketchEventListenerHandle=d(this._sketchEventListenerHandle)}get allowedWorkflows(){return this._get("allowedWorkflows")}set allowedWorkflows(t){r(l.getLogger(this),"allowedWorkflows",{replacement:"Editor.visibleElements",version:"4.29",warnOnce:!0}),t&&0!==t.length||(t=[...G]),this._set("allowedWorkflows",t)}get canCreate(){return this.editorItems.some((t=>t.supportsCreateFeaturesWorkflow))}get canCreateVisible(){return!!this.featureTemplatesLayers.length}get canUpdate(){return this.editorItems.some((t=>t.supportsUpdateWorkflow))}get canUpdateVisible(){return this.editorItems.some((t=>t.supportsUpdateWorkflow&&t.visible))}get featureTemplatesLayers(){const t=new a;for(const e of this.editorItems){const a=e.supportsCreateFeaturesWorkflow&&!e.isTable,r=this.hideTemplatesForInactiveLayers&&!e.visible;a&&!r&&t.push(e.layer)}return t}get editableItems(){return r(l.getLogger(this),"editableItems",{replacement:"editorItems",version:"4.29",warnOnce:!0}),this.editorItems.map((t=>{const{capabilities:e,disabled:a,hasInvalidFormTemplate:r,layer:i}=t,s=[],o=e.create,n=e.update,l=e.delete;return o.enabled&&s.push("create"),n.enabled&&s.push("update"),l.enabled&&s.push("delete"),{layer:i,supports:s,suspended:a,attributeUpdatesEnabled:n.attributes,geometryUpdatesEnabled:n.geometry,attachmentsOnCreateEnabled:o.attachments.enabled,attachmentsOnUpdateEnabled:n.attachments.enabled,hasInvalidFormTemplate:r,hasAttachments:e.attachments.enabled}}))}get featureFormViewModel(){const{activeWorkflow:t}=this;return"update"===t?.type?t.activeFeatureFormViewModel:"create-features"===t?.type?t.featureFormViewModel:null}get labelOptions(){return this.sketchOptions.labels}set labelOptions(t){this.sketchOptions.labels=t}set layerInfos(t){const e=t?.some((t=>"allowAttachments"in t));e&&i(D(),"Property: layerInfo.allowAttachments",{replacement:"layerInfo.attachmentsOnCreateEnabled or layerInfo.attachmentsOnUpdateEnabled",version:"4.26"}),this._set("layerInfos",t)}get sketchViewModel(){const{activeWorkflow:t}=this;return"update"===t?.type?t.activeSketchViewModel:"create-features"===t?.type?t.sketchViewModel:this.ownSketchViewModel}get state(){if(!this.view?.ready)return"disabled";const t=this.attachmentsViewModel.mode;if("add"===t)return"adding-attachment";if("edit"===t)return"editing-attachment";const{activeWorkflow:e}=this;return e?.stepId?"update"===e.type&&e.activeWorkflow?.stepId?e.activeWorkflow.stepId:e.stepId:"ready"}get syncing(){return this._activityQueue.length>0}get updating(){return this._updatingHandles.updating||!0===this.activeWorkflow?.updating}get tooltipOptions(){return this.sketchOptions.tooltips}set tooltipOptions(t){this.sketchOptions.tooltips=t}get valueOptions(){return this.sketchOptions.values}set valueOptions(t){this.sketchOptions.values=t}set view(t){this.ownSketchViewModel.view=t,this.spinnerViewModel.view=t,this._set("view",t)}get page(){const{activeWorkflow:t,state:e}=this;if("update"===t?.type&&"awaiting-feature-to-update"===t.stepId)return"ready";if("create-features"===t?.type&&0===t.numPendingFeatures){const e=t.data.upload;if(e)return"default"===e.state?"ready":"creating-features-upload-details"}return e??"disabled"}get featureFormDisabled(){const{activeWorkflow:t}=this;return"update"===t?.type&&!1===t.activeEditorItem?.capabilities.update.attributes}get canGoBack(){return null!=this.activeWorkflow&&!this.syncing}get shouldShowDeleteButton(){const{activeWorkflow:t}=this;return!!t&&"update"===t.type&&!!t.activeEditorItem?.capabilities.delete.enabled}get hasPendingEdits(){return this.activeWorkflow?.hasPendingEdits??!1}async startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.startCreateFeaturesWorkflow()}async startCreateFeaturesWorkflowAtFeatureCreation(t){return this.startCreateFeaturesWorkflow(t,"creating-features")}async startCreateFeaturesWorkflow(t,e="awaiting-feature-creation-info"){if(await y((()=>!this.updating)),!this.canCreate)throw new s("editing:unsupported-workflow","Creating features is unsupported or disabled.");const a=this._createUpdatingResolver();await this._cancelWorkflow();const r=this._createCreateFeaturesWorkflow(t,e);this._set("activeWorkflow",r),await r.start(),a.resolve()}async startCreateFeaturesWorkflowAtFeatureEdit(t){await y((()=>!this.updating));const e=this._createUpdatingResolver(),{initialFeature:a}=t,r=a.sourceLayer,i=r?this.findEditorItemForLayer(r):void 0;if(!i?.supportsCreateFeaturesWorkflow)throw new s("editing:unsupported-workflow","Creating features is unsupported or disabled for this layer.");await this._cancelWorkflow();const o=this._createCreateFeaturesWorkflow({initialFeature:a,layer:i.layer,maxFeatures:1},"creating-features");this._set("activeWorkflow",o),await o.start(),e.resolve()}async startUpdateWorkflowAtFeatureSelection(){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const t=this._createUpdatingResolver();await this._cancelWorkflow();const e=this._createUpdateWorkflow();this._set("activeWorkflow",e),await e.start(),t.resolve()}async startUpdateWorkflowAtMultipleFeatureSelection(t){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const e=this._createUpdatingResolver();await this._cancelWorkflow();const a=this._createUpdateWorkflow("awaiting-update-feature-candidate");a.data.candidates=t,this._set("activeWorkflow",a),await a.start(),e.resolve()}async startUpdateWorkflowAtFeatureEdit(t){if(await y((()=>!this.updating)),!this.canUpdate)return void q("editing:unsupported-workflow","Update workflow is unsupported or disabled.");const e=this._createUpdatingResolver();await this._cancelWorkflow();const a=this._createUpdateWorkflow("editing-existing-feature");a.data.rootFeature=t,this._set("activeWorkflow",a),await a.start(),e.resolve()}async deleteFeatureFromWorkflow(){const{activeWorkflow:t}=this;t&&"update"===t.type?await t.deleteActiveFeature():q("editing:unsupported-workflow","Deleting requires an active update workflow.")}async cancelWorkflow(t){return this._cancelWorkflow({warnIfNoWorkflow:!0,...t})}findEditorItemForLayer(t){const e="subtype-sublayer"===t.type?t.parent:t;return this.editorItems.find((t=>t.layer===e))}itemHasInvalidFormTemplate(t){return null!=t&&!0===this.findEditorItemForLayer(t.layer)?.hasInvalidFormTemplate}syncFeatureTemplates(){this._featureTemplatesViewModelLocked||(this.featureTemplatesViewModel.layers=this.featureTemplatesLayers.toArray())}async toggleUpdateWorkflow(){this.canUpdate&&(this.hasPendingEdits&&!await this.showDiscardEditsPrompt()||(this.activeWorkflow&&"awaiting-feature-to-update"===this.state?await this.cancelWorkflow({force:!0}):await this.startUpdateWorkflowAtFeatureSelection()))}lockFeatureTemplatesViewModel(){return this._featureTemplatesViewModelLocked=!0,n((()=>{this._featureTemplatesViewModelLocked=!1,this.syncFeatureTemplates()}))}async _getEditorItemCandidates(t){const{view:e}=this;if(!e?.map)return[];const{map:a}=e,r=a.editableLayers.toArray()??[],i=a.allTables.toArray().filter(E)??[];return await Promise.allSettled([...r.map((t=>"subtype-group"===t.type?t.loadAll():Promise.resolve())),...i.map((t=>t.load()))]),u(t),[...r.reverse(),...i.reverse()].filter((t=>F(t)&&("mesh"!==t.geometryType||"3d"===e.type))).flatMap((t=>"subtype-group"===t.type?t.sublayers.toArray():t))}_drainEditorItems(){this.editorItems.drain((t=>t.destroy()))}async _updateEditorItems(){p(this._updateItemsTask);const{view:t}=this,a=e((async e=>{if(!t?.map||!t?.allLayerViews)return;const a=await this._getEditorItemCandidates(e);if(!a.length)return void this._drainEditorItems();const r=[],i=[],s=[],{layerInfos:o}=this;for(const l of a){const e=B(o,l),a=await j(t,l).catch((()=>null));(e?r:a?i:s).push(new S({layer:l,layerInfo:e,layerView:a}))}o?.length&&r.sort(((t,e)=>o.findIndex((({layer:e})=>e===t.layer))-o.findIndex((({layer:t})=>t===e.layer))));const n=[...r,...i,...s];e.aborted||(this._drainEditorItems(),this.editorItems.addMany(n))}));this._updatingHandles.addPromise(a.promise),this._updateItemsTask=a}_afterEditorItemsChange(){const{activeWorkflow:t}=this;if(this.syncFeatureTemplates(),!t)return;const{stepId:e}=t;"create-features"!==t.type?"update"===t.type&&("awaiting-feature-to-update"===e&&!this.canUpdateVisible||"awaiting-update-feature-candidate"===e&&!t.hasUpdatableCandidates)&&this._cancelWorkflow():"awaiting-feature-creation-info"!==e||this.canCreate||this._cancelWorkflow()}async _cancelWorkflow(t){const e=this.activeWorkflow;if(!e)return void(t?.warnIfNoWorkflow&&q("editing:no-active-workflow","There is no active workflow to cancel."));if(!t||!1!==t.force)return this.emit("workflow-cancel"),this._set("activeWorkflow",null),void await e.cancel(t);await e.cancel(t),this._set("activeWorkflow",null)}_createCreateFeaturesWorkflow(t,e){return L.create({viewModel:this,creationInfo:t,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:e,applyEditsCallback:(t,e,a)=>this._applyEdits(t,e,a),addAttachmentsCallback:(t,e)=>this._addAttachments(t,e)})}_createUpdateWorkflow(t){return A.create({viewModel:this,sketchOptions:this.sketchOptions,snappingManager:this._snappingManager,startAt:t,applyEditsCallback:(t,e,a)=>this._applyEdits(t,e,a),addAttachmentsCallback:(t,e)=>this._addAttachments(t,e)})}_addAttachments(t,e){const a=e.map((e=>this._addAttachment(t,e.feature,e.attachment)))??[];return Promise.all(a)}async _addAttachment(t,e,a){let r=null;if(!("addAttachment"in t)||null==t.capabilities?.attachment)throw new s("editor:attachments-not-supported","Adding attachments is not supported for this layer type");return await this._queueOperation((async()=>(r=await(t.addAttachment?.(e,a).catch((t=>{throw t?.error||t})))??null,r))),r}async _applyEdits(t,e,a){let r=null;const i=t.url?await M(t.url):null,s={returnServiceEditsOption:(!i||!C(i))&&!RegExp("/hosted/","i").test(t.url)?"original-and-current-features":void 0,...a};return await this._queueOperation((async()=>{const{view:a}=this;if(!a)return null;const i=await j(a,t).catch((()=>null));return r=await t.applyEdits(e,s),i&&await y((()=>!i.updating)),r})),r}_queueOperation(t){this._activityQueue.push(t);const e=(t,e)=>{const a=e.indexOf(t);a>-1&&e.splice(a,1)};return t().then((t=>{if(null!=t&&"error"in t&&null!=t.error)throw t.error;if(null!=t&&"addFeatureResults"in t){const{addFeatureResults:e,deleteFeatureResults:a,updateFeatureResults:r}=t,i=e.find((t=>!!t.error))||r.find((t=>!!t.error))||a.find((t=>!!t.error));if(i)throw i.error}return t})).catch((a=>{q("editing:operation-error","An error occurred.",{error:a});const r={error:a,retry:()=>(e(r,this.failures),this._queueOperation(t)),cancel:()=>{e(r,this.failures)}};this._set("failures",[...this.failures,r])})).then((()=>{e(t,this._activityQueue)}))}_createUpdatingResolver(){const t=h();return this._updatingHandles.addPromise(t.promise),t}_itemIsSuspended(t){const e=this.findEditorItemForLayer(t);return null!=e&&(!e.visible||e.disabled)}};t([_({readOnly:!0})],Q.prototype,"activeWorkflow",void 0),t([_({readOnly:!0})],Q.prototype,"_activityQueue",void 0),t([_({value:[...G]})],Q.prototype,"allowedWorkflows",null),t([_({readOnly:!0})],Q.prototype,"canCreate",null),t([_()],Q.prototype,"canCreateVisible",null),t([_({readOnly:!0})],Q.prototype,"canUpdate",null),t([_()],Q.prototype,"canUpdateVisible",null),t([_()],Q.prototype,"featureTemplatesLayers",null),t([_()],Q.prototype,"editableItems",null),t([_()],Q.prototype,"editorItems",void 0),t([_({readOnly:!0})],Q.prototype,"failures",void 0),t([_()],Q.prototype,"hideTemplatesForInactiveLayers",void 0),t([_()],Q.prototype,"attachmentsViewModel",void 0),t([_()],Q.prototype,"featureFormViewModel",null),t([_()],Q.prototype,"featureTemplatesViewModel",void 0),t([_()],Q.prototype,"labelOptions",null),t([_()],Q.prototype,"layerInfos",null),t([_()],Q.prototype,"ownSketchViewModel",void 0),t([_()],Q.prototype,"sketchOptions",void 0),t([_()],Q.prototype,"sketchViewModel",null),t([_({type:U,nonNullable:!0})],Q.prototype,"snappingOptions",void 0),t([_()],Q.prototype,"spinnerViewModel",void 0),t([_()],Q.prototype,"state",null),t([_({readOnly:!0})],Q.prototype,"syncing",null),t([_()],Q.prototype,"updating",null),t([_()],Q.prototype,"tooltipOptions",null),t([_()],Q.prototype,"valueOptions",null),t([_()],Q.prototype,"view",null),t([_()],Q.prototype,"pageStack",void 0),t([_()],Q.prototype,"showDiscardEditsPrompt",void 0),t([_()],Q.prototype,"_candidateCommitted",void 0),t([_()],Q.prototype,"page",null),t([_()],Q.prototype,"featureFormDisabled",null),t([_()],Q.prototype,"canGoBack",null),t([_()],Q.prototype,"shouldShowDeleteButton",null),t([_()],Q.prototype,"hasPendingEdits",null),Q=t([W(x)],Q);const N=Q;export{N as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import{property as t}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/Logger.js";import"../../../core/RandomLCG.js";import{subclass as r}from"../../../core/accessorSupport/decorators/subclass.js";import a from"../../../layers/support/EditingCapabilities.js";import{isRelatableFeatureSupportedLayer as n}from"../../Feature/support/featureUtils.js";let l=class extends a{constructor(e){super(e),this.layerInfo=null}get attachments(){const e=this.defaults.attachments.enabled,t=this.layerInfo;return{enabled:e&&!1!==t?.allowAttachments&&!1!==t?.enabled}}get create(){const{attachments:e,defaults:t,layerInfo:r}=this,a=t.create,n=!1!==r?.enabled&&!1!==r?.addEnabled,l=a.enabled&&n;return{attributes:l&&a.attributes,enabled:l,geometry:l&&a.geometry,attachments:{enabled:e.enabled&&l&&!1!==r?.attachmentsOnCreateEnabled},reliesOnOwnerAdminPrivileges:a.reliesOnOwnerAdminPrivileges}}get defaults(){return new a({layer:this.layer})}get delete(){const{defaults:e,layerInfo:t}=this,r=e.delete,a=!1!==t?.enabled&&!1!==t?.deleteEnabled;return{enabled:r.enabled&&a,reliesOnOwnerAdminPrivileges:r.reliesOnOwnerAdminPrivileges}}get formTemplate(){const{layer:e,layerInfo:t}=this;return t?.formTemplate?t.formTemplate:e&&"formTemplate"in e?e.formTemplate:null}get relationship(){const{layer:e}=this,t=!(!n(e)||!e.relationships?.length),r=!!this.formTemplate?.elements?.some((e=>"relationship"===e.type));return{enabled:t&&r}}get update(){const{attachments:e,defaults:t,layerInfo:r}=this,a=t.update,n=!1!==r?.enabled&&!1!==r?.updateEnabled,l=a.enabled&&n,s=l&&a.attributes&&!1!==r?.attributeUpdatesEnabled,o=l&&a.geometry&&!1!==r?.geometryUpdatesEnabled,i=e.enabled&&!1!==r?.attachmentsOnUpdateEnabled;return{attributes:s,enabled:l,geometry:o,attachments:{enabled:i,create:i&&a.attachments.create,update:i&&a.attachments.update},reliesOnOwnerAdminPrivileges:a.reliesOnOwnerAdminPrivileges}}};e([t()],l.prototype,"attachments",null),e([t()],l.prototype,"create",null),e([t()],l.prototype,"defaults",null),e([t()],l.prototype,"delete",null),e([t()],l.prototype,"formTemplate",null),e([t()],l.prototype,"layerInfo",void 0),e([t()],l.prototype,"relationship",null),e([t()],l.prototype,"update",null),l=e([r("esri.widgets.Editor.support.EditorEditingCapabilities")],l);const s=l;export{s as default};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import{property as t}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/Logger.js";import"../../../core/RandomLCG.js";import{subclass as r}from"../../../core/accessorSupport/decorators/subclass.js";import a from"../../../layers/support/EditingCapabilities.js";import{isGeometryEditableSceneLayer as l}from"../../../views/layers/support/editableLayerViews.js";import{isRelatableFeatureSupportedLayer as n}from"../../Feature/support/featureUtils.js";let s=class extends a{constructor(e){super(e),this.layerInfo=null,this.layerView=null}get attachments(){const e=this.defaults.attachments.enabled,t=this.layerInfo;return{enabled:e&&!1!==t?.allowAttachments&&!1!==t?.enabled}}get create(){const{attachments:e,defaults:t,layerInfo:r,layer:a,layerView:l}=this,n=t.create,s=!1!==r?.enabled&&!1!==r?.addEnabled,i=n.enabled&&s;return{attributes:i&&n.attributes,enabled:i,geometry:i&&n.geometry&&o(a,l),attachments:{enabled:e.enabled&&i&&!1!==r?.attachmentsOnCreateEnabled},reliesOnOwnerAdminPrivileges:n.reliesOnOwnerAdminPrivileges}}get defaults(){return new a({layer:this.layer})}get delete(){const{defaults:e,layerInfo:t}=this,r=e.delete,a=!1!==t?.enabled&&!1!==t?.deleteEnabled;return{enabled:r.enabled&&a,reliesOnOwnerAdminPrivileges:r.reliesOnOwnerAdminPrivileges}}get formTemplate(){const{layer:e,layerInfo:t}=this;return t?.formTemplate?t.formTemplate:e&&"formTemplate"in e?e.formTemplate:null}get relationship(){const{layer:e}=this,t=!(!n(e)||!e.relationships?.length),r=!!this.formTemplate?.elements?.some((e=>"relationship"===e.type));return{enabled:t&&r}}get update(){const{attachments:e,defaults:t,layerInfo:r,layer:a,layerView:l}=this,n=t.update,s=!1!==r?.enabled&&!1!==r?.updateEnabled,i=n.enabled&&s,p=i&&n.attributes&&!1!==r?.attributeUpdatesEnabled,d=i&&n.geometry&&!1!==r?.geometryUpdatesEnabled&&o(a,l),m=e.enabled&&!1!==r?.attachmentsOnUpdateEnabled;return{attributes:p,enabled:i,geometry:d,attachments:{enabled:m,create:m&&n.attachments.create,update:m&&n.attachments.update},reliesOnOwnerAdminPrivileges:n.reliesOnOwnerAdminPrivileges}}};function o(e,t){return"scene"!==e.type||null!=t&&"type"in t&&"scene-layer-3d"===t.type&&l(e,t)}e([t()],s.prototype,"attachments",null),e([t()],s.prototype,"create",null),e([t()],s.prototype,"defaults",null),e([t()],s.prototype,"delete",null),e([t()],s.prototype,"formTemplate",null),e([t()],s.prototype,"layerInfo",void 0),e([t()],s.prototype,"layerView",void 0),e([t()],s.prototype,"relationship",null),e([t()],s.prototype,"update",null),s=e([r("esri.widgets.Editor.support.EditorEditingCapabilities")],s);const i=s;export{i as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../core/Accessor.js";import{property as r}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/Logger.js";import"../../../core/RandomLCG.js";import{subclass as s}from"../../../core/accessorSupport/decorators/subclass.js";import{isTable as o}from"../../../layers/support/layerUtils.js";import l from"./EditorEditingCapabilities.js";import{formTemplateHasInvalidFields as a}from"../../FeatureForm/featureFormUtils.js";let i=class extends t{constructor(e){super(e),this.disabled=!1,this.layer=null,this.layerInfo=null,this.layerView=null}get _suspended(){return!!this.layerView?.suspended}get capabilities(){return new l({layer:this.layer,layerInfo:this.layerInfo})}get editable(){const{create:e,relationship:t,update:r,delete:{enabled:s}}=this.capabilities,o=e.attachments.enabled||r.attachments.enabled;return!this.disabled&&(e.enabled||r.enabled||o||s||t.enabled)}get formTemplate(){return this.capabilities.formTemplate}get hasInvalidFormTemplate(){return a(this.layer,this.formTemplate)}get isTable(){return o(this.layer)}get supportsCreateFeaturesWorkflow(){return!this.disabled&&this.capabilities.create.enabled}get supportsUpdateWorkflow(){const{capabilities:e}=this;return!this.disabled&&(e.update.enabled||e.update.attachments.enabled||e.delete.enabled)}get visible(){const{layer:e}=this,t=e.parent;return!this._suspended&&e.visible&&(!t||!("visible"in t)||t.visible)}};e([r()],i.prototype,"_suspended",null),e([r()],i.prototype,"capabilities",null),e([r()],i.prototype,"disabled",void 0),e([r()],i.prototype,"editable",null),e([r()],i.prototype,"formTemplate",null),e([r()],i.prototype,"hasInvalidFormTemplate",null),e([r()],i.prototype,"isTable",null),e([r()],i.prototype,"layer",void 0),e([r()],i.prototype,"layerInfo",void 0),e([r()],i.prototype,"layerView",void 0),e([r()],i.prototype,"supportsCreateFeaturesWorkflow",null),e([r()],i.prototype,"supportsUpdateWorkflow",null),e([r()],i.prototype,"visible",null),i=e([s("esri.widgets.editor.support.EditorItem")],i);const p=i;export{p as default};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../core/Accessor.js";import{property as r}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/Logger.js";import"../../../core/RandomLCG.js";import{subclass as s}from"../../../core/accessorSupport/decorators/subclass.js";import{isTable as o}from"../../../layers/support/layerUtils.js";import i from"./EditorEditingCapabilities.js";import{formTemplateHasInvalidFields as l}from"../../FeatureForm/featureFormUtils.js";let a=class extends t{constructor(e){super(e),this.disabled=!1,this.layer=null,this.layerInfo=null,this.layerView=null}get _suspended(){return!!this.layerView?.suspended}get capabilities(){return new i({layer:this.layer,layerInfo:this.layerInfo,layerView:this.layerView})}get editable(){const{create:e,relationship:t,update:r,delete:{enabled:s}}=this.capabilities,o=e.attachments.enabled||r.attachments.enabled;return!this.disabled&&(e.enabled||r.enabled||o||s||t.enabled)}get formTemplate(){return this.capabilities.formTemplate}get hasInvalidFormTemplate(){return l(this.layer,this.formTemplate)}get isTable(){return o(this.layer)}get supportsCreateFeaturesWorkflow(){if(this.disabled)return!1;const{enabled:e,geometry:t}=this.capabilities.create;return this.isTable?e:e&&t}get supportsUpdateWorkflow(){const{capabilities:e}=this;return!this.disabled&&(e.update.enabled||e.update.attachments.enabled||e.delete.enabled)}get visible(){const{layer:e}=this,t=e.parent;return!this._suspended&&e.visible&&(!t||!("visible"in t)||t.visible)}};e([r()],a.prototype,"_suspended",null),e([r()],a.prototype,"capabilities",null),e([r()],a.prototype,"disabled",void 0),e([r()],a.prototype,"editable",null),e([r()],a.prototype,"formTemplate",null),e([r()],a.prototype,"hasInvalidFormTemplate",null),e([r()],a.prototype,"isTable",null),e([r()],a.prototype,"layer",void 0),e([r()],a.prototype,"layerInfo",void 0),e([r()],a.prototype,"layerView",void 0),e([r()],a.prototype,"supportsCreateFeaturesWorkflow",null),e([r()],a.prototype,"supportsUpdateWorkflow",null),e([r()],a.prototype,"visible",null),a=e([s("esri.widgets.editor.support.EditorItem")],a);const p=a;export{p as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../chunks/tslib.es6.js";import"../intl.js";import{isSome as t}from"../core/arrayUtils.js";import{deprecatedProperty as i}from"../core/deprecate.js";import o from"../core/Logger.js";import{watch as n,whenOnce as a}from"../core/reactiveUtils.js";import{property as s}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import{subclass as r}from"../core/accessorSupport/decorators/subclass.js";import{isIntegerField as l}from"../layers/support/fieldUtils.js";import d from"./Widget.js";import{css as c}from"./FeatureForm/css.js";import{isGroupInput as p,isFieldInput as u,isRelationshipInput as m,isInputInGroupInput as h,isFieldElementWithInputType as v,getErrorMessageForFieldInput as b,getIconForFeature as _,isNumberFieldInput as C}from"./FeatureForm/featureFormUtils.js";import g from"./FeatureForm/FeatureFormViewModel.js";import{loadCalciteComponents as f}from"./support/componentsUtils.js";import{isString as y}from"./support/dataUtils.js";import{getLabelForDateFieldValue as F,getIntlOptionsForField as R,numberingSystem as w,prepareISOFieldValueForDateComponents as O,prepareUnixFieldValueForDateComponents as k,normalizeTimeOnlyString as x,getISOFieldValueFromDateComponents as I,getUnixFieldValueFromDateComponents as M}from"./support/dateUtils.js";import{globalCss as D}from"./support/globalCss.js";import{Heading as V,incrementHeadingLevel as N}from"./support/Heading.js";import"./support/widgetUtils.js";import{messageBundle as L}from"./support/decorators/messageBundle.js";import{vmEvent as T}from"./support/decorators/vmEvent.js";import{tsx as j}from"./support/jsxFactory.js";import{substitute as E}from"../intl/substitute.js";const S="data-field-name";let U=class extends d{constructor(e,t){super(e,t),this._attemptFocusOnNextRender=!1,this._dateComponentMap=new Map,this._inputsWithChanges=new Set,this._focusedFieldName=null,this._listObserverNode=null,this._listObserver=new IntersectionObserver((e=>{e.length&&e[0].isIntersecting&&this._incrementRelatedRecordPage()}),{root:window.document}),this.groupDisplay="all",this.headingLevel=2,this.messages=null,this.messagesCommon=null,this.messagesFeature=null,this.messagesTemplates=null,this.viewModel=new g,this._onShowAllRelatedRecordsClick=e=>{const{feature:t,relatedRecordCallbacks:i}=this;t&&i?.showAllRelatedRecords&&i.showAllRelatedRecords({parentFeature:t,relationshipId:e})},this._onAddRelatedRecordsClick=(e,t)=>{const{feature:i,relatedRecordCallbacks:o}=this;i&&o?.addRelatedRecord&&o.addRelatedRecord({parentFeature:i,relatedLayer:t,relationshipId:e})},this._activeCombobox=null,this._activeComboboxClosedByWorkaround=!1,this._onFormKeyDown=this._onFormKeyDown.bind(this),this._onFormSubmit=this._onFormSubmit.bind(this),this._onGroupToggle=this._onGroupToggle.bind(this),this._onComponentBlur=this._onComponentBlur.bind(this),this._onComponentFocus=this._onComponentFocus.bind(this),this._onComponentKeyDown=this._onComponentKeyDown.bind(this),this._afterComponentCreate=this._afterComponentCreate.bind(this),this._afterComponentCreateOrUpdate=this._afterComponentCreateOrUpdate.bind(this),this._afterDateComponentCreate=this._afterDateComponentCreate.bind(this),this._afterDateComponentCreateOrUpdate=this._afterDateComponentCreateOrUpdate.bind(this),this._afterRadioGroupCreateOrUpdate=this._afterRadioGroupCreateOrUpdate.bind(this),this._onComboboxOpen=this._onComboboxOpen.bind(this),this._onComboboxClose=this._onComboboxClose.bind(this),this.onScroll=this.onScroll.bind(this)}initialize(){this.addHandles([n((()=>this.feature),(()=>{a((()=>!this.viewModel.updating)).then((()=>{const e=this._getFocusableInput("forward");this._inputsWithChanges.clear(),this._dateComponentMap.clear(),this._syncGroupInputStates(),this._focusedFieldName=e?.name||null,this._attemptFocusOnNextRender=!0}))})),n((()=>this.groupDisplay),(()=>this._syncGroupInputStates())),this.on("submit",(e=>{if(e.invalid.length>0){const[t]=e.invalid;e.invalid.forEach((e=>this._inputsWithChanges.add(e))),this._focusedFieldName=t,this._attemptFocusOnNextRender=!0,this.scheduleRender()}})),n((()=>[this.viewModel.activeRelationshipInput,this._listObserverNode]),(()=>this._onObserverChange()))])}loadDependencies(){return f({block:()=>import("@esri/calcite-components/dist/components/calcite-block.js"),button:()=>import("@esri/calcite-components/dist/components/calcite-button.js"),combobox:()=>import("@esri/calcite-components/dist/components/calcite-combobox.js"),"combobox-item":()=>import("@esri/calcite-components/dist/components/calcite-combobox-item.js"),"combobox-item-group":()=>import("@esri/calcite-components/dist/components/calcite-combobox-item-group.js"),icon:()=>import("@esri/calcite-components/dist/components/calcite-icon.js"),input:()=>import("@esri/calcite-components/dist/components/calcite-input.js"),"input-date-picker":()=>import("@esri/calcite-components/dist/components/calcite-input-date-picker.js"),"input-message":()=>import("@esri/calcite-components/dist/components/calcite-input-message.js"),"input-number":()=>import("@esri/calcite-components/dist/components/calcite-input-number.js"),"input-time-picker":()=>import("@esri/calcite-components/dist/components/calcite-input-time-picker.js"),"input-time-zone":()=>import("@esri/calcite-components/dist/components/calcite-input-time-zone.js"),label:()=>import("@esri/calcite-components/dist/components/calcite-label.js"),list:()=>import("@esri/calcite-components/dist/components/calcite-list.js"),"list-item":()=>import("@esri/calcite-components/dist/components/calcite-list-item.js"),loader:()=>import("@esri/calcite-components/dist/components/calcite-loader.js"),notice:()=>import("@esri/calcite-components/dist/components/calcite-notice.js"),"radio-button":()=>import("@esri/calcite-components/dist/components/calcite-radio-button.js"),"radio-button-group":()=>import("@esri/calcite-components/dist/components/calcite-radio-button-group.js"),switch:()=>import("@esri/calcite-components/dist/components/calcite-switch.js"),"text-area":()=>import("@esri/calcite-components/dist/components/calcite-text-area.js")})}destroy(){this._listObserverNode&&this._listObserver.unobserve(this._listObserverNode)}get _relatedRecordsEnabled(){const e=this.relatedRecordCallbacks;return!(!e||!(e.addRelatedRecord||e.editRelatedRecord||e.showAllRelatedRecords))}get disabled(){return this.viewModel.disabled}set disabled(e){this.viewModel.disabled=e}get feature(){return this.viewModel.feature}set feature(e){this.viewModel.feature=e}get formTemplate(){return this.viewModel.formTemplate}set formTemplate(e){this.viewModel.formTemplate=e}get label(){return this.messages?.widgetLabel??""}set label(e){this._overrideIfSome("label",e)}get layer(){return this.viewModel.layer}set layer(e){this.viewModel.layer=e}get map(){return this.viewModel.map}set map(e){this.viewModel.map=e}get relatedRecordCallbacks(){return this.viewModel.relatedRecordCallbacks}set relatedRecordCallbacks(e){this.viewModel.relatedRecordCallbacks=e}get relationshipId(){return this.viewModel.relationshipId}set relationshipId(e){this.viewModel.relationshipId=e}get spatialReference(){return this.viewModel.spatialReference}set spatialReference(e){this.viewModel.spatialReference=e}get strict(){return this.viewModel.strict}set strict(e){this.viewModel.strict=e}get timeZone(){return this.viewModel.timeZone}set timeZone(e){this.viewModel.timeZone=e}get view(){return i(o.getLogger(this),"view",{replacement:"Use FeatureForm.map instead.",version:"4.27"}),this.viewModel.view}set view(e){i(o.getLogger(this),"view",{replacement:"Use FeatureForm.map instead.",version:"4.27"}),this.viewModel.view=e}getValues(){return this.viewModel.getValues()}submit(){return this.viewModel.submit()}render(){const{state:e}=this.viewModel;return j("div",{class:this.classes(c.base,D.widget,D.panel),onscroll:this.onScroll},"ready"===e?this._renderForm():null)}_renderForm(){return j("form",{class:c.form,novalidate:!0,onkeydown:this._onFormKeyDown,onsubmit:this._onFormSubmit},this._renderHeader(),this._renderContent())}_renderHeader(){const e=this.viewModel;if(!e.formHeaderVisible)return;const t=null!=e.formTitle&&j(V,{key:"title",level:this.headingLevel},e.formTitle),i=null!=e.formDescription&&j("p",{class:c.description,key:"description"},e.formDescription);return j("div",{class:c.formHeader},t,i)}_renderContent(){const{viewModel:e}=this;return e.activeRelationshipInput?this._renderActiveRelationshipInput(e.activeRelationshipInput):e.inputs.filter(t).filter((e=>e.visible)).map(((e,t)=>p(e)?this._renderGroup(e,t):u(e)?this._renderLabeledField(e):m(e)?this._renderRelationshipInput(e):void 0))}_renderActiveRelationshipInput(e){return this._renderRelationshipInput(e)}_renderDescriptionOrEmpty(e,t){return null==e?null:j("div",{class:this.classes(c.description),id:t},e)}_renderGroup(e,t){const{disabled:i,formTemplate:o,headingLevel:n}=this,{description:a,inputs:s,label:r,open:l}=e,d=s.filter((e=>e.visible)),p=this.viewModel.findField(this._focusedFieldName),h=p?.group===e,v=`${this.id}_group_${t}`,b="sequential"===this.groupDisplay;return j("calcite-block",{class:this.classes(c.group,b?c.groupSequential:null,h?c.groupActive:null,i?c.inputDisabled:null),collapsible:!0,"data-group":e,description:a||void 0,disabled:i,heading:`${r}`,headingLevel:o?.title?N(n):n,id:v,key:v,open:l,onCalciteBlockToggle:({target:t})=>this._onGroupToggle(t,e)},d.map((e=>u(e)?this._renderLabeledField(e):m(e)?this._renderRelationshipInput(e):void 0)))}_getFocusableInput(e,t){const i=this.viewModel.allFieldInputs,o="forward"===e?i:i.slice().reverse();let n;if(!t||m(t))n=0;else if(p(t)){const e=t.inputs.find(u);n=e?o.indexOf(e):0}else{let i;if(h(t)&&!t.group.open){const o=t.group.inputs.filter(u);i="forward"===e?o[o.length-1]:o[0]}else i=t;n=o.indexOf(i)+1}for(let a=n;a<o.length;a++){const e=o[a];if(e.visible&&u(e))return e}return null}_renderLabeledField(e){const{dataType:t,feature:i,label:o,layer:n,required:a}=e,s={"aria-label":a?E(this.messages.requiredFieldLabel,{name:o}):o,class:c.label,key:`${n.id}-${i.uid}-${e.name}`},r=[j("div",{class:c.labelTextContent,key:"labelTextContainer"},o,a?j("span",{"aria-hidden":"true",title:this.messagesCommon.required},"*"):void 0),"unsupported"!==t?this._renderFieldInput(e):this._renderReadOnlyComponent(e),this._renderAuxiliaryText(e)];return"date"===t&&"coded-value"!==e.domain?.type?j("label",{...s},r):j("calcite-label",{...s},r)}_renderFieldInput(e){const{dataType:t,domain:i,inputType:o,name:n}=e,a=this.getCommonInputProps(e);if("coded-value"===i?.type){const t=this.viewModel.getFieldValueOptionsForField(n,this.messages.empty);return"switch"!==o||e.hasInvalidSwitchValue?"radio-buttons"===o?this._renderRadioButtonComponents(e,t.flat(),a):this._renderComboBoxComponent(e,t,a):this._renderSwitchComponent(e,a)}return"datetime-picker"===o||"date"===t?this._renderDateComponents(e,a):"number"===t?this._renderNumberComponent(e,a):this._renderStringComponent(e,a)}_renderStringComponent(e,t){return"text-area"===e.inputType?t.readOnly?j("calcite-input",{...t,loading:e.updating,type:"textarea",onCalciteInputInput:e=>this._saveValueFromComponent(e.target)}):j("calcite-text-area",{...t,resize:"vertical",onCalciteTextAreaInput:e=>this._saveValueFromComponent(e.target)}):j("calcite-input",{...t,loading:e.updating,type:"text",onCalciteInputInput:e=>this._saveValueFromComponent(e.target)})}_renderNumberComponent(e,t){return j("calcite-input-number",{...t,integer:l(e.field),loading:e.updating,type:"number",onCalciteInputNumberInput:e=>this._saveValueFromComponent(e.target)})}_renderDateComponents(e,t){const{field:i}=e;switch(i.type){case"date":return this._renderDateFieldComponents(e,t);case"date-only":return this._renderDateOnlyFieldComponent(e,t);case"time-only":return this._renderTimeOnlyFieldComponent(e,t);case"timestamp-offset":return this._renderTimestampOffsetFieldComponents(e,t);default:return this._renderReadOnlyComponent(e,F(i,t.value,{timeZone:this.timeZone,...R(i)}))}}_renderDateOnlyFieldComponent(e,t){const{range:i,valid:o,value:n}=e,{class:a,key:s,readOnly:r}=t,{rawMax:l,rawMin:d}=i;return j("calcite-input-date-picker",{afterCreate:this._afterDateComponentCreate,afterUpdate:this._afterDateComponentCreateOrUpdate,"aria-invalid":!o,class:a,"data-date-part":"date","data-field-name":t[S],key:`${s}-date-input`,max:y(l)?l:void 0,min:y(d)?d:void 0,numberingSystem:w,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},onfocus:this._onComponentFocus,overlayPositioning:"fixed",readOnly:r,value:null!=n?`${n}`:void 0,onCalciteInputDatePickerChange:e=>this._saveValueFromDateComponent(e.target)})}_renderTimeOnlyFieldComponent(e,t){const{valid:i,value:o}=e,{class:n,key:a,readOnly:s}=t;return j("calcite-input-time-picker",{afterCreate:this._afterDateComponentCreate,afterUpdate:this._afterDateComponentCreateOrUpdate,"aria-invalid":!i,class:n,"data-date-part":"time","data-field-name":t[S],key:`${a}-time-input`,numberingSystem:w,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},onfocus:this._onComponentFocus,overlayPositioning:"fixed",readOnly:s,step:e.timeStep,value:null!=o?`${o}`:void 0,onCalciteInputTimePickerChange:e=>this._saveValueFromDateComponent(e.target)})}_renderTimestampOffsetFieldComponents(e,t){const{name:i,range:o,timeZone:n,valid:a,value:s}=e,{class:r,key:l,readOnly:d}=t,{rawMax:p,rawMin:u}=o,m={afterCreate:this._afterDateComponentCreate,afterUpdate:this._afterDateComponentCreateOrUpdate,"aria-invalid":!a,numberingSystem:w,overlayPositioning:"fixed",readOnly:d,[S]:i,onfocus:this._onComponentFocus},h=O(p,n),v=O(u,n),b=O(s,n);return j("div",{class:c.dateInputContainer,key:`${l}-date-time-container`},j("calcite-input-date-picker",{...m,class:r,"data-date-part":"date",key:`${l}-date-input`,max:h?.date??void 0,min:v?.date??void 0,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},value:b.date??void 0,onCalciteInputDatePickerChange:e=>this._saveValueFromDateComponent(e.target)}),j("calcite-input-time-picker",{...m,class:r,"data-date-part":"time",key:`${l}-time-input`,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},step:e.timeStep,value:b.time??void 0,onCalciteInputTimePickerChange:e=>this._saveValueFromDateComponent(e.target)}),e.includeTimeOffset?j("calcite-input-time-zone",{...m,class:r,"data-date-part":"timeZone",disabled:d,key:`${l}-timezone-input`,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},value:b.timeZoneOffset??"0",onCalciteInputTimeZoneChange:e=>this._saveValueFromDateComponent(e.target)}):null)}_renderDateFieldComponents(e,t){const{includeTime:i,name:o,valid:n,value:a}=e,{class:s,key:r,max:l,min:d,readOnly:p}=t,{timeZone:u}=this,m={afterCreate:this._afterDateComponentCreate,afterUpdate:this._afterDateComponentCreateOrUpdate,"aria-invalid":!n,numberingSystem:w,overlayPositioning:"fixed",readOnly:p,[S]:o,onfocus:this._onComponentFocus},h=k(a,u),v=k(l,u),b=k(d,u);return j("div",{class:c.dateInputContainer,key:`${r}-date-time-container`},j("calcite-input-date-picker",{...m,class:s,"data-date-part":"date",key:`${r}-date-input`,max:v?.date??void 0,min:b?.date??void 0,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},value:h.date??void 0,onCalciteInputDatePickerChange:e=>this._saveValueFromDateComponent(e.target)}),i?j("calcite-input-time-picker",{...m,class:s,"data-date-part":"time",key:`${r}-time-input`,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},step:1,value:h.time??void 0,onCalciteInputTimePickerChange:e=>this._saveValueFromDateComponent(e.target)}):null)}_renderReadOnlyComponent(e,t){const i=this.getCommonInputProps(e);return j("calcite-input",{...i,class:this.classes(c.fieldInput,c.inputDisabled),readOnly:!0,type:"text",value:null!=t?`${t}`:i.value})}_renderComboBoxComponent(e,t,i){const{value:o,name:n}=e,{messages:a,messagesTemplates:s,viewModel:r,_inputsWithChanges:l}=this,d=t.map((e=>e.map((({name:e,value:t})=>j("calcite-combobox-item",{key:`#${t}`,selected:o===t,textLabel:e,value:`${t}`}))))),[c,p]=d;this.viewModel.fieldsWithInvalidCodedValue.has(e)&&p.unshift(j("calcite-combobox-item",{key:"incompatible-option",readOnly:!0,textLabel:`${e.value}`,value:`${e.value}`}));const u=p.length>0?[j("calcite-combobox-item-group",{key:"recommended",label:a.recommended},c),j("calcite-combobox-item-group",{key:"other",label:s.other},p)]:c,m="INSERT"===r.arcadeEditType,h=l.has(n),v=null==o&&(!m||h);e.showNoValueOptionEnabled&&u.unshift(j("calcite-combobox-item",{key:"empty-option",selected:v,textLabel:e.showNoValueLabel||a.empty,value:""}));const b=m&&e.showNoValueOptionEnabled&&!h?()=>{}:i.onblur;return j("calcite-combobox",{...i,allowCustomValues:!1,clearDisabled:!0,disabled:i.readOnly,onblur:b,overlayPositioning:"fixed",selectionMode:"single",onCalciteComboboxBeforeOpen:this._onComboboxOpen,onCalciteComboboxChange:({target:e})=>{v&&0===e.selectedItems.length?this._ignoreDeselectionOfNoValueOption(e):this._saveValueFromComponent(e)},onCalciteComboboxClose:this._onComboboxClose},u)}_renderRadioButtonComponents(e,t,i){const{name:o,value:n}=e,a=t.map((({name:e,value:t})=>this._renderRadioButtonComponent({key:e,label:e,name:o,value:t,selected:t===n,props:i})));if(e.showNoValueOptionEnabled){const t="",s=e.showNoValueLabel||this.messages.empty,r=n===t||null===n;a.unshift(this._renderRadioButtonComponent({key:"empty-option",label:s,name:o,value:t,selected:r,props:i}))}return j("calcite-radio-button-group",{afterCreate:this._afterRadioGroupCreateOrUpdate,afterUpdate:this._afterRadioGroupCreateOrUpdate,class:c.inputRadioGroup,"data-field-name":i[S],key:`${i.key}-radio-group`,layout:"vertical",name:i.key,required:i.required},a)}_renderSwitchComponent(e,t){const{value:i}=e,o=!!v(e.element,"switch")&&i===e.element.input.onValue;return j("calcite-switch",{...t,checked:o,class:c.inputSwitch,disabled:t.readOnly,onblur:()=>{this._focusedFieldName=null},onCalciteSwitchChange:e=>this._saveValueFromComponent(e.target)})}_renderRadioButtonComponent({key:e,name:t,value:i,selected:o,label:n,props:a}){return j("calcite-label",{class:c.inputRadioLabel,key:e,layout:"inline"},j("calcite-radio-button",{...a,afterCreate:void 0,afterUpdate:void 0,checked:o,class:c.inputRadio,disabled:a.readOnly,name:t,onblur:()=>{this._focusedFieldName=null},value:i,onCalciteRadioButtonChange:({target:e})=>{e.checked&&this._saveValueFromComponent(e)}}),n)}_renderAuxiliaryText(e){const t=e.name,i=this._inputsWithChanges.has(t)&&!e.valid?b(e,this.messages,this.timeZone):null!=this.viewModel.contingencyConstraintViolations.get(t)?this.messages.validationErrors.valuesIncompatible:null!=e.valueExpressionExecutor&&e.valueExpressionExecutor.stale?this.messages.valueExpressionError:null;return null!=i?j("calcite-input-message",{icon:!0,status:"invalid"},i):this._renderDescriptionOrEmpty(e.description)}_renderShowAllRelatedRecordsListItem(e){const{featureCount:t,relationshipId:i,showAllActionVisible:o}=e,{relatedRecordCallbacks:n}=this;if(!o||!n?.showAllRelatedRecords)return;const a=this.messages;return j("calcite-list-item",{description:E(a.totalCount,{count:t}),label:a.showAll,value:!0,onCalciteListItemSelect:()=>this._onShowAllRelatedRecordsClick(i)},j("calcite-icon",{icon:"list",scale:"s",slot:"content-end"}))}_renderAddRelatedRecordButton(e){const{canAddRelatedFeature:t,relationshipId:i,relatedLayer:o}=e,{messages:n,relatedRecordCallbacks:a}=this;if(t&&a?.addRelatedRecord&&o)return j("calcite-button",{alignment:"center",appearance:"outline-fill",class:c.centeredButton,disabled:e.updating||!e.originHasValidKey,iconStart:"plus",key:`${i}-add-button`,onclick:()=>{!e.updating&&e.originHasValidKey&&this._onAddRelatedRecordsClick(i,o)},round:!0,scale:"s",width:"half"},e.relatedLayerIsTable?n.addRecord:n.addFeature)}_renderRelatedRecordListItem(e,t){const{feature:i,description:o,title:n}=e,{feature:a,relatedRecordCallbacks:s}=this,{highlightHelper:r}=this.viewModel,l=()=>{r?.removeAll(),s?.editRelatedRecord&&a&&s.editRelatedRecord({parentFeature:a,relationshipId:t,relatedFeature:i})},d=r?()=>r.add(i):void 0,c=r?()=>r.remove(i):void 0;return j("calcite-list-item",{bind:this,description:o,key:`${t}-${i.uid}`,label:n,onclick:l,onmouseenter:d,onmouseleave:c,value:n},j("calcite-icon",{icon:_(i),scale:"m",slot:"content-start"}),j("calcite-icon",{icon:"chevron-right",scale:"s",slot:"content-end"}))}_renderRelationshipInput(e){if(!this._relatedRecordsEnabled||!e.editable)return;const{featureCount:t,relationshipId:i,showAllEnabled:o}=e,n=o?null:this._renderDescriptionOrEmpty(e.description),a=t>0?this._renderRelatedRecordsList(e):e.loaded?e.originHasValidKey?this._renderNoRelatedRecordsNotice():this._renderNoValidOriginKeyNotice(e):void 0;return j("calcite-label",{class:this.classes(c.label,c.relatedRecordsLabel),key:`relationship-${i}-container`},j("div",null,this._renderRelatedRecordsHeaderContainer(e),n,a),this._renderAddRelatedRecordButton(e))}_renderRelatedRecordsHeaderContainer(e){const t=e.updating||!e.loaded;return j("div",{class:c.relatedRecordsHeader,key:`relationship-${e.relationshipId}-header`},j("span",null,e.label),t?j("calcite-loader",{inline:!0,key:"loader",label:this.messagesCommon?.loading,scale:"s",type:"indeterminate"}):void 0)}_renderRelatedRecordsList(e){const{relationshipId:t}=e;return j("calcite-list",{class:c.relatedRecordsList},e.relatedFeatureInfos.map((e=>this._renderRelatedRecordListItem(e,t))),this._renderShowAllRelatedRecordsListItem(e),this._renderObserverNode())}_renderNoValidOriginKeyNotice(e){const{messages:t}=this,i=e.relatedLayerIsTable?t.noOriginKeyRecord:t.noOriginKeyFeature,o=e.relationship?.keyField,n=this.viewModel.findField(o),a=e.layer?.fieldsIndex.get(o),s=n?.label||a?.alias||o,r=E(i,{relatedLayerName:e.relatedLayer?.title,originKeyField:s});return j("calcite-notice",{icon:"information",kind:"brand",open:!0,scale:"s",width:"full"},j("div",{slot:"message"},r))}_renderNoRelatedRecordsNotice(){return j("calcite-notice",{icon:"information",kind:"brand",open:!0,scale:"s",width:"full"},j("div",{slot:"message"},this.messagesFeature.noRelatedFeatures))}_renderObserverNode(){if(this.viewModel.activeRelationshipInput?.showAllEnabled)return j("div",{afterCreate:this._afterListObserverCreated,afterRemoved:this._afterListObserverRemoved,bind:this,class:c.listObserver,key:"feature-observer"})}getCommonInputProps(e){const{disabled:t}=this,{editable:i,hint:o,label:n,maxLength:a,minLength:s,name:r,range:{max:l,min:d},required:p,valid:u,value:m}=e,h=this._inputsWithChanges.has(r),v=!i||t;return{afterCreate:this._afterComponentCreate,afterUpdate:this._afterComponentCreateOrUpdate,"aria-invalid":u?"false":"true",class:this.classes(c.fieldInput,v?c.inputDisabled:null,h&&!u?c.inputInvalid:null),key:r,label:n,max:null!=l?l:void 0,min:null!=d?d:void 0,maxLength:a>-1?a:void 0,minLength:s>-1?s:void 0,placeholder:o??void 0,readOnly:v,required:p,value:null==m?"":`${m}`,onblur:this._onComponentBlur,onfocus:this._onComponentFocus,onkeydown:this._onComponentKeyDown,[S]:r}}_getFieldInputFromHTMLElement(e){return this.viewModel.findField(e.getAttribute(S))}_afterDateComponentCreate(e){const t=this._getFieldInputFromHTMLElement(e),i=e.dataset.datePart,o=this._dateComponentMap.get(t.name);if("valueAsDate"in e&&null!=e.value){const t=e.value,i=new ResizeObserver((()=>{e.value=void 0,e.value=t,i.unobserve(e)}));i.observe(e)}if(null!=o)switch(i){case"date":o.date=e;break;case"time":o.time=e;break;case"timeZone":o.timeZone=e}else this._dateComponentMap.set(t.name,{[i]:e});this._afterDateComponentCreateOrUpdate(e)}_afterDateComponentCreateOrUpdate(e){this._afterComponentCreateOrUpdate(e)}_afterComponentCreate(e){const t=this._getFieldInputFromHTMLElement(e);C(t)&&null!=e.value&&"setNumberValue"in e&&e.setNumberValue({committing:!1,value:e.value,origin:"direct"}),this._afterComponentCreateOrUpdate(e)}_afterRadioGroupCreateOrUpdate(e){const t=e.selectedItem,i=e.querySelector("calcite-radio-button"),o=t||i;o&&this._afterComponentCreateOrUpdate(o)}_afterComponentCreateOrUpdate(e){const{viewModel:t}=this,i=this._getFieldInputFromHTMLElement(e),o=t.findField(this._focusedFieldName);this._attemptFocusOnNextRender&&o===i&&(this._attemptFocusOnNextRender=!1,h(i)&&(i.group.open=!0),e.setFocus())}_onComponentFocus(e){const t=e.target,i=this._getFieldInputFromHTMLElement(t);this._focusedFieldName=i.name}_onComponentBlur(e){const t=e.target;this._focusedFieldName=null,this._saveValueFromComponent(t)}_saveValueFromDateComponent(e){const{timeZone:t}=this,i=this._getFieldInputFromHTMLElement(e),o=i.field.type,{name:n,range:a}=i,s=this._dateComponentMap.get(n);if(!s)return;let r=this.viewModel.getValue(n),l=null;"date-only"===o?l=e.value:"time-only"===o?(r=x(r),l=x(e.value)):l="timestamp-offset"===o?null!=e.value?I({dateComponent:s.date,timeComponent:s.time,timeZoneComponent:s.timeZone,oldValue:r,defaultTimeZone:t}):null:null!=e.value?M({oldValue:r,dateComponent:s.date,timeComponent:s.time,timeZone:t,max:a.max,min:a.min}):null,null!==l&&e.value?r!==l&&this._updateFieldValue(n,l):this._updateFieldValue(n,null)}_saveValueFromComponent(e){const t=this._getFieldInputFromHTMLElement(e);this._updateFieldValue(t.name,this._parseValue(e))}_onComponentKeyDown({key:e,target:t}){const i=this._getFieldInputFromHTMLElement(t);"Enter"===e&&h(i)&&!i.group.open&&(i.group.open=!0)}_updateFieldValue(e,t){if(this.viewModel.setValue(e,t),this._inputsWithChanges.add(e),this.viewModel.fieldsWithContingentValues.has(e)){const e=Object.fromEntries(Object.entries(this.getValues()).filter((([e,t])=>null!=t)));this.viewModel.validateContingencyConstraints(e)}}_parseValue(e){const t=this._getFieldInputFromHTMLElement(e),i=e.value;return v(t.element,"switch")?e.checked?t.element.input.onValue:t.element.input.offValue:null==i||""===i?null:"number"===t.dataType?"-0"===i||"-0."===i||"-0,"===i?i:parseFloat(i):"date"===t.field.type?parseFloat(i):i}_ignoreDeselectionOfNoValueOption(e){const{firstChild:t,selectedItems:i}=e;0===i.length&&t&&"selected"in t?t.selected=!0:o.getLogger(this).warnOnce("Failed to override user attempt to deselect 'No value' option.")}_onGroupToggle(e,t){e.open?(t.open=!0,this._focusedFieldName=this._getFocusableInput("forward",t)?.name||null,this._attemptFocusOnNextRender=!0,"sequential"===this.groupDisplay&&this.viewModel.allGroupInputs.forEach((e=>{e!==t&&(e.open=!1)}))):t.open=!1,this.scheduleRender()}_onFormSubmit(e){e.preventDefault()}_onFormKeyDown(e){"Enter"===e.key&&this.viewModel.submit()}_afterListObserverCreated(e){this.viewModel.activeRelationshipInput&&(this._listObserverNode=e)}_afterListObserverRemoved(){this._listObserverNode=null}_onObserverChange(){this._listObserverNode&&this._listObserver.unobserve(this._listObserverNode);const e=this.viewModel.activeRelationshipInput;e&&this._listObserverNode&&e.showAllEnabled&&this._listObserver.observe(this._listObserverNode)}_incrementRelatedRecordPage(){const e=this.viewModel.activeRelationshipInput;e?.incrementPage()}_syncGroupInputStates(){if("sequential"!==this.groupDisplay)return;const e=this.viewModel.allGroupInputs;if(!e.length)return;const t=e.filter((e=>e.open));0===t.length?e[0].open=!0:t.length>1&&t.slice(1).forEach((e=>e.open=!1))}_onComboboxClose(e){this._activeComboboxClosedByWorkaround||this._activeCombobox!==e.target||(this._activeCombobox=null)}_onComboboxOpen(e){this._activeComboboxClosedByWorkaround=!1,this._activeCombobox=e.target}onScroll(e){if(this._activeCombobox){const t=this._activeCombobox.getBoundingClientRect(),i=e.target.getBoundingClientRect();t.bottom>i.bottom?(this._activeComboboxClosedByWorkaround=!0,this._activeCombobox.open=!1):(this._activeComboboxClosedByWorkaround&&(this._activeCombobox.open=!0,this._activeComboboxClosedByWorkaround=!1),this._activeCombobox.reposition())}}};e([s()],U.prototype,"_listObserverNode",void 0),e([s()],U.prototype,"_relatedRecordsEnabled",null),e([s()],U.prototype,"disabled",null),e([s()],U.prototype,"feature",null),e([s()],U.prototype,"formTemplate",null),e([s()],U.prototype,"groupDisplay",void 0),e([s()],U.prototype,"headingLevel",void 0),e([s()],U.prototype,"label",null),e([s()],U.prototype,"layer",null),e([s()],U.prototype,"map",null),e([s(),L("esri/widgets/FeatureForm/t9n/FeatureForm")],U.prototype,"messages",void 0),e([s(),L("esri/t9n/common")],U.prototype,"messagesCommon",void 0),e([s(),L("esri/widgets/Feature/t9n/Feature")],U.prototype,"messagesFeature",void 0),e([s(),L("esri/widgets/FeatureTemplates/t9n/FeatureTemplates")],U.prototype,"messagesTemplates",void 0),e([s()],U.prototype,"relatedRecordCallbacks",null),e([s()],U.prototype,"relationshipId",null),e([s()],U.prototype,"spatialReference",null),e([s()],U.prototype,"strict",null),e([s()],U.prototype,"timeZone",null),e([s()],U.prototype,"view",null),e([s(),T(["value-change","submit"])],U.prototype,"viewModel",void 0),U=e([r("esri.widgets.FeatureForm")],U);const $=U;export{$ as default};
5
+ import{_ as e}from"../chunks/tslib.es6.js";import"../intl.js";import{isSome as t}from"../core/arrayUtils.js";import{deprecatedProperty as i}from"../core/deprecate.js";import o from"../core/Logger.js";import{watch as n,whenOnce as a}from"../core/reactiveUtils.js";import{property as s}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import{subclass as r}from"../core/accessorSupport/decorators/subclass.js";import{isIntegerField as l}from"../layers/support/fieldUtils.js";import d from"./Widget.js";import{css as c}from"./FeatureForm/css.js";import{isGroupInput as p,isFieldInput as u,isRelationshipInput as m,isInputInGroupInput as h,isFieldElementWithInputType as v,getErrorMessageForFieldInput as b,getIconForFeature as _,isNumberFieldInput as C}from"./FeatureForm/featureFormUtils.js";import g from"./FeatureForm/FeatureFormViewModel.js";import{loadCalciteComponents as f}from"./support/componentsUtils.js";import{isString as y}from"./support/dataUtils.js";import{getLabelForDateFieldValue as F,getIntlOptionsForField as R,numberingSystem as w,prepareISOFieldValueForDateComponents as O,prepareUnixFieldValueForDateComponents as k,normalizeTimeOnlyString as x,getISOFieldValueFromDateComponents as I,getUnixFieldValueFromDateComponents as M}from"./support/dateUtils.js";import{globalCss as D}from"./support/globalCss.js";import{Heading as V,incrementHeadingLevel as N}from"./support/Heading.js";import"./support/widgetUtils.js";import{messageBundle as L}from"./support/decorators/messageBundle.js";import{vmEvent as T}from"./support/decorators/vmEvent.js";import{tsx as j}from"./support/jsxFactory.js";import{substitute as E}from"../intl/substitute.js";const S="data-field-name";let U=class extends d{constructor(e,t){super(e,t),this._attemptFocusOnNextRender=!1,this._dateComponentMap=new Map,this._inputsWithChanges=new Set,this._focusedFieldName=null,this._listObserverNode=null,this._listObserver=new IntersectionObserver((e=>{e.length&&e[0].isIntersecting&&this._incrementRelatedRecordPage()}),{root:window.document}),this.groupDisplay="all",this.headingLevel=2,this.messages=null,this.messagesCommon=null,this.messagesFeature=null,this.messagesTemplates=null,this.viewModel=new g,this._onShowAllRelatedRecordsClick=e=>{const{feature:t,relatedRecordCallbacks:i}=this;t&&i?.showAllRelatedRecords&&i.showAllRelatedRecords({parentFeature:t,relationshipId:e})},this._onAddRelatedRecordsClick=(e,t)=>{const{feature:i,relatedRecordCallbacks:o}=this;i&&o?.addRelatedRecord&&o.addRelatedRecord({parentFeature:i,relatedLayer:t,relationshipId:e})},this._activeCombobox=null,this._activeComboboxClosedByWorkaround=!1,this._onFormKeyDown=this._onFormKeyDown.bind(this),this._onFormSubmit=this._onFormSubmit.bind(this),this._onGroupToggle=this._onGroupToggle.bind(this),this._onComponentBlur=this._onComponentBlur.bind(this),this._onComponentFocus=this._onComponentFocus.bind(this),this._onComponentKeyDown=this._onComponentKeyDown.bind(this),this._afterComponentCreate=this._afterComponentCreate.bind(this),this._afterComponentCreateOrUpdate=this._afterComponentCreateOrUpdate.bind(this),this._afterDateComponentCreate=this._afterDateComponentCreate.bind(this),this._afterDateComponentCreateOrUpdate=this._afterDateComponentCreateOrUpdate.bind(this),this._afterRadioGroupCreateOrUpdate=this._afterRadioGroupCreateOrUpdate.bind(this),this._onComboboxOpen=this._onComboboxOpen.bind(this),this._onComboboxClose=this._onComboboxClose.bind(this),this.onScroll=this.onScroll.bind(this)}initialize(){this.addHandles([n((()=>this.feature),(()=>{this._inputsWithChanges.clear(),this._dateComponentMap.clear(),a((()=>!this.viewModel.updating)).then((()=>{const e=this._getFocusableInput("forward");this._syncGroupInputStates(),this._focusedFieldName=e?.name||null,this._attemptFocusOnNextRender=!0}))})),n((()=>this.groupDisplay),(()=>this._syncGroupInputStates())),this.on("submit",(e=>{if(e.invalid.length>0){const[t]=e.invalid;e.invalid.forEach((e=>this._inputsWithChanges.add(e))),this._focusedFieldName=t,this._attemptFocusOnNextRender=!0,this.scheduleRender()}})),n((()=>[this.viewModel.activeRelationshipInput,this._listObserverNode]),(()=>this._onObserverChange()))])}loadDependencies(){return f({block:()=>import("@esri/calcite-components/dist/components/calcite-block.js"),button:()=>import("@esri/calcite-components/dist/components/calcite-button.js"),combobox:()=>import("@esri/calcite-components/dist/components/calcite-combobox.js"),"combobox-item":()=>import("@esri/calcite-components/dist/components/calcite-combobox-item.js"),"combobox-item-group":()=>import("@esri/calcite-components/dist/components/calcite-combobox-item-group.js"),icon:()=>import("@esri/calcite-components/dist/components/calcite-icon.js"),input:()=>import("@esri/calcite-components/dist/components/calcite-input.js"),"input-date-picker":()=>import("@esri/calcite-components/dist/components/calcite-input-date-picker.js"),"input-message":()=>import("@esri/calcite-components/dist/components/calcite-input-message.js"),"input-number":()=>import("@esri/calcite-components/dist/components/calcite-input-number.js"),"input-time-picker":()=>import("@esri/calcite-components/dist/components/calcite-input-time-picker.js"),"input-time-zone":()=>import("@esri/calcite-components/dist/components/calcite-input-time-zone.js"),label:()=>import("@esri/calcite-components/dist/components/calcite-label.js"),list:()=>import("@esri/calcite-components/dist/components/calcite-list.js"),"list-item":()=>import("@esri/calcite-components/dist/components/calcite-list-item.js"),loader:()=>import("@esri/calcite-components/dist/components/calcite-loader.js"),notice:()=>import("@esri/calcite-components/dist/components/calcite-notice.js"),"radio-button":()=>import("@esri/calcite-components/dist/components/calcite-radio-button.js"),"radio-button-group":()=>import("@esri/calcite-components/dist/components/calcite-radio-button-group.js"),switch:()=>import("@esri/calcite-components/dist/components/calcite-switch.js"),"text-area":()=>import("@esri/calcite-components/dist/components/calcite-text-area.js")})}destroy(){this._listObserverNode&&this._listObserver.unobserve(this._listObserverNode)}get _relatedRecordsEnabled(){const e=this.relatedRecordCallbacks;return!(!e||!(e.addRelatedRecord||e.editRelatedRecord||e.showAllRelatedRecords))}get disabled(){return this.viewModel.disabled}set disabled(e){this.viewModel.disabled=e}get feature(){return this.viewModel.feature}set feature(e){this.viewModel.feature=e}get formTemplate(){return this.viewModel.formTemplate}set formTemplate(e){this.viewModel.formTemplate=e}get label(){return this.messages?.widgetLabel??""}set label(e){this._overrideIfSome("label",e)}get layer(){return this.viewModel.layer}set layer(e){this.viewModel.layer=e}get map(){return this.viewModel.map}set map(e){this.viewModel.map=e}get relatedRecordCallbacks(){return this.viewModel.relatedRecordCallbacks}set relatedRecordCallbacks(e){this.viewModel.relatedRecordCallbacks=e}get relationshipId(){return this.viewModel.relationshipId}set relationshipId(e){this.viewModel.relationshipId=e}get spatialReference(){return this.viewModel.spatialReference}set spatialReference(e){this.viewModel.spatialReference=e}get strict(){return this.viewModel.strict}set strict(e){this.viewModel.strict=e}get timeZone(){return this.viewModel.timeZone}set timeZone(e){this.viewModel.timeZone=e}get view(){return i(o.getLogger(this),"view",{replacement:"Use FeatureForm.map instead.",version:"4.27"}),this.viewModel.view}set view(e){i(o.getLogger(this),"view",{replacement:"Use FeatureForm.map instead.",version:"4.27"}),this.viewModel.view=e}getValues(){return this.viewModel.getValues()}submit(){return this.viewModel.submit()}render(){const{state:e}=this.viewModel;return j("div",{class:this.classes(c.base,D.widget,D.panel),onscroll:this.onScroll},"ready"===e?this._renderForm():null)}_renderForm(){return j("form",{class:c.form,novalidate:!0,onkeydown:this._onFormKeyDown,onsubmit:this._onFormSubmit},this._renderHeader(),this._renderContent())}_renderHeader(){const e=this.viewModel;if(!e.formHeaderVisible)return;const t=null!=e.formTitle&&j(V,{key:"title",level:this.headingLevel},e.formTitle),i=null!=e.formDescription&&j("p",{class:c.description,key:"description"},e.formDescription);return j("div",{class:c.formHeader},t,i)}_renderContent(){const{viewModel:e}=this;return e.activeRelationshipInput?this._renderActiveRelationshipInput(e.activeRelationshipInput):e.inputs.filter(t).filter((e=>e.visible)).map(((e,t)=>p(e)?this._renderGroup(e,t):u(e)?this._renderLabeledField(e):m(e)?this._renderRelationshipInput(e):void 0))}_renderActiveRelationshipInput(e){return this._renderRelationshipInput(e)}_renderDescriptionOrEmpty(e,t){return null==e?null:j("div",{class:this.classes(c.description),id:t},e)}_renderGroup(e,t){const{disabled:i,formTemplate:o,headingLevel:n}=this,{description:a,inputs:s,label:r,open:l}=e,d=s.filter((e=>e.visible)),p=this.viewModel.findField(this._focusedFieldName),h=p?.group===e,v=`${this.id}_group_${t}`,b="sequential"===this.groupDisplay;return j("calcite-block",{class:this.classes(c.group,b?c.groupSequential:null,h?c.groupActive:null,i?c.inputDisabled:null),collapsible:!0,"data-group":e,description:a||void 0,disabled:i,heading:`${r}`,headingLevel:o?.title?N(n):n,id:v,key:v,open:l,onCalciteBlockToggle:({target:t})=>this._onGroupToggle(t,e)},d.map((e=>u(e)?this._renderLabeledField(e):m(e)?this._renderRelationshipInput(e):void 0)))}_getFocusableInput(e,t){const i=this.viewModel.allFieldInputs,o="forward"===e?i:i.slice().reverse();let n;if(!t||m(t))n=0;else if(p(t)){const e=t.inputs.find(u);n=e?o.indexOf(e):0}else{let i;if(h(t)&&!t.group.open){const o=t.group.inputs.filter(u);i="forward"===e?o[o.length-1]:o[0]}else i=t;n=o.indexOf(i)+1}for(let a=n;a<o.length;a++){const e=o[a];if(e.visible&&u(e))return e}return null}_renderLabeledField(e){const{dataType:t,feature:i,label:o,layer:n,required:a}=e,s={"aria-label":a?E(this.messages.requiredFieldLabel,{name:o}):o,class:c.label,key:`${n.id}-${i.uid}-${e.name}`},r=[j("div",{class:c.labelTextContent,key:"labelTextContainer"},o,a?j("span",{"aria-hidden":"true",title:this.messagesCommon.required},"*"):void 0),"unsupported"!==t?this._renderFieldInput(e):this._renderReadOnlyComponent(e),this._renderAuxiliaryText(e)];return"date"===t&&"coded-value"!==e.domain?.type?j("label",{...s},r):j("calcite-label",{...s},r)}_renderFieldInput(e){const{dataType:t,domain:i,inputType:o,name:n}=e,a=this.getCommonInputProps(e);if("coded-value"===i?.type){const t=this.viewModel.getFieldValueOptionsForField(n,this.messages.empty);return"switch"!==o||e.hasInvalidSwitchValue?"radio-buttons"===o?this._renderRadioButtonComponents(e,t.flat(),a):this._renderComboBoxComponent(e,t,a):this._renderSwitchComponent(e,a)}return"datetime-picker"===o||"date"===t?this._renderDateComponents(e,a):"number"===t?this._renderNumberComponent(e,a):this._renderStringComponent(e,a)}_renderStringComponent(e,t){return"text-area"===e.inputType?t.readOnly?j("calcite-input",{...t,loading:e.updating,type:"textarea",onCalciteInputInput:e=>this._saveValueFromComponent(e.target)}):j("calcite-text-area",{...t,resize:"vertical",onCalciteTextAreaInput:e=>this._saveValueFromComponent(e.target)}):j("calcite-input",{...t,loading:e.updating,type:"text",onCalciteInputInput:e=>this._saveValueFromComponent(e.target)})}_renderNumberComponent(e,t){return j("calcite-input-number",{...t,integer:l(e.field),loading:e.updating,type:"number",onCalciteInputNumberInput:e=>this._saveValueFromComponent(e.target)})}_renderDateComponents(e,t){const{field:i}=e;switch(i.type){case"date":return this._renderDateFieldComponents(e,t);case"date-only":return this._renderDateOnlyFieldComponent(e,t);case"time-only":return this._renderTimeOnlyFieldComponent(e,t);case"timestamp-offset":return this._renderTimestampOffsetFieldComponents(e,t);default:return this._renderReadOnlyComponent(e,F(i,t.value,{timeZone:this.timeZone,...R(i)}))}}_renderDateOnlyFieldComponent(e,t){const{range:i,valid:o,value:n}=e,{class:a,key:s,readOnly:r}=t,{rawMax:l,rawMin:d}=i;return j("calcite-input-date-picker",{afterCreate:this._afterDateComponentCreate,afterUpdate:this._afterDateComponentCreateOrUpdate,"aria-invalid":!o,class:a,"data-date-part":"date","data-field-name":t[S],key:`${s}-date-input`,max:y(l)?l:void 0,min:y(d)?d:void 0,numberingSystem:w,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},onfocus:this._onComponentFocus,overlayPositioning:"fixed",readOnly:r,value:null!=n?`${n}`:void 0,onCalciteInputDatePickerChange:e=>this._saveValueFromDateComponent(e.target)})}_renderTimeOnlyFieldComponent(e,t){const{valid:i,value:o}=e,{class:n,key:a,readOnly:s}=t;return j("calcite-input-time-picker",{afterCreate:this._afterDateComponentCreate,afterUpdate:this._afterDateComponentCreateOrUpdate,"aria-invalid":!i,class:n,"data-date-part":"time","data-field-name":t[S],key:`${a}-time-input`,numberingSystem:w,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},onfocus:this._onComponentFocus,overlayPositioning:"fixed",readOnly:s,step:e.timeStep,value:null!=o?`${o}`:void 0,onCalciteInputTimePickerChange:e=>this._saveValueFromDateComponent(e.target)})}_renderTimestampOffsetFieldComponents(e,t){const{name:i,range:o,timeZone:n,valid:a,value:s}=e,{class:r,key:l,readOnly:d}=t,{rawMax:p,rawMin:u}=o,m={afterCreate:this._afterDateComponentCreate,afterUpdate:this._afterDateComponentCreateOrUpdate,"aria-invalid":!a,numberingSystem:w,overlayPositioning:"fixed",readOnly:d,[S]:i,onfocus:this._onComponentFocus},h=O(p,n),v=O(u,n),b=O(s,n);return j("div",{class:c.dateInputContainer,key:`${l}-date-time-container`},j("calcite-input-date-picker",{...m,class:r,"data-date-part":"date",key:`${l}-date-input`,max:h?.date??void 0,min:v?.date??void 0,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},value:b.date??void 0,onCalciteInputDatePickerChange:e=>this._saveValueFromDateComponent(e.target)}),j("calcite-input-time-picker",{...m,class:r,"data-date-part":"time",key:`${l}-time-input`,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},step:e.timeStep,value:b.time??void 0,onCalciteInputTimePickerChange:e=>this._saveValueFromDateComponent(e.target)}),e.includeTimeOffset?j("calcite-input-time-zone",{...m,class:r,"data-date-part":"timeZone",disabled:d,key:`${l}-timezone-input`,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},value:b.timeZoneOffset??"0",onCalciteInputTimeZoneChange:e=>this._saveValueFromDateComponent(e.target)}):null)}_renderDateFieldComponents(e,t){const{includeTime:i,name:o,valid:n,value:a}=e,{class:s,key:r,max:l,min:d,readOnly:p}=t,{timeZone:u}=this,m={afterCreate:this._afterDateComponentCreate,afterUpdate:this._afterDateComponentCreateOrUpdate,"aria-invalid":!n,numberingSystem:w,overlayPositioning:"fixed",readOnly:p,[S]:o,onfocus:this._onComponentFocus},h=k(a,u),v=k(l,u),b=k(d,u);return j("div",{class:c.dateInputContainer,key:`${r}-date-time-container`},j("calcite-input-date-picker",{...m,class:s,"data-date-part":"date",key:`${r}-date-input`,max:v?.date??void 0,min:b?.date??void 0,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},value:h.date??void 0,onCalciteInputDatePickerChange:e=>this._saveValueFromDateComponent(e.target)}),i?j("calcite-input-time-picker",{...m,class:s,"data-date-part":"time",key:`${r}-time-input`,onblur:e=>{this._focusedFieldName=null,this._saveValueFromDateComponent(e.target)},step:1,value:h.time??void 0,onCalciteInputTimePickerChange:e=>this._saveValueFromDateComponent(e.target)}):null)}_renderReadOnlyComponent(e,t){const i=this.getCommonInputProps(e);return j("calcite-input",{...i,class:this.classes(c.fieldInput,c.inputDisabled),readOnly:!0,type:"text",value:null!=t?`${t}`:i.value})}_renderComboBoxComponent(e,t,i){const{value:o,name:n}=e,{messages:a,messagesTemplates:s,viewModel:r,_inputsWithChanges:l}=this,d=t.map((e=>e.map((({name:e,value:t})=>j("calcite-combobox-item",{key:`#${t}`,selected:o===t,textLabel:e,value:`${t}`}))))),[c,p]=d;this.viewModel.fieldsWithInvalidCodedValue.has(e)&&p.unshift(j("calcite-combobox-item",{key:"incompatible-option",readOnly:!0,textLabel:`${e.value}`,value:`${e.value}`}));const u=p.length>0?[j("calcite-combobox-item-group",{key:"recommended",label:a.recommended},c),j("calcite-combobox-item-group",{key:"other",label:s.other},p)]:c,m="INSERT"===r.arcadeEditType,h=l.has(n),v=null==o&&(!m||h);e.showNoValueOptionEnabled&&u.unshift(j("calcite-combobox-item",{key:"empty-option",selected:v,textLabel:e.showNoValueLabel||a.empty,value:""}));const b=m&&e.showNoValueOptionEnabled&&!h?()=>{}:i.onblur;return j("calcite-combobox",{...i,allowCustomValues:!1,clearDisabled:!0,disabled:i.readOnly,onblur:b,overlayPositioning:"fixed",selectionMode:"single",onCalciteComboboxBeforeOpen:this._onComboboxOpen,onCalciteComboboxChange:({target:e})=>{v&&0===e.selectedItems.length?this._ignoreDeselectionOfNoValueOption(e):this._saveValueFromComponent(e)},onCalciteComboboxClose:this._onComboboxClose},u)}_renderRadioButtonComponents(e,t,i){const{name:o,value:n}=e,a=t.map((({name:e,value:t})=>this._renderRadioButtonComponent({key:e,label:e,name:o,value:t,selected:t===n,props:i})));if(e.showNoValueOptionEnabled){const t="",s=e.showNoValueLabel||this.messages.empty,r=n===t||null===n;a.unshift(this._renderRadioButtonComponent({key:"empty-option",label:s,name:o,value:t,selected:r,props:i}))}return j("calcite-radio-button-group",{afterCreate:this._afterRadioGroupCreateOrUpdate,afterUpdate:this._afterRadioGroupCreateOrUpdate,class:c.inputRadioGroup,"data-field-name":i[S],key:`${i.key}-radio-group`,layout:"vertical",name:i.key,required:i.required},a)}_renderSwitchComponent(e,t){const{value:i}=e,o=!!v(e.element,"switch")&&i===e.element.input.onValue;return j("calcite-switch",{...t,checked:o,class:c.inputSwitch,disabled:t.readOnly,onblur:()=>{this._focusedFieldName=null},onCalciteSwitchChange:e=>this._saveValueFromComponent(e.target)})}_renderRadioButtonComponent({key:e,name:t,value:i,selected:o,label:n,props:a}){return j("calcite-label",{class:c.inputRadioLabel,key:e,layout:"inline"},j("calcite-radio-button",{...a,afterCreate:void 0,afterUpdate:void 0,checked:o,class:c.inputRadio,disabled:a.readOnly,name:t,onblur:()=>{this._focusedFieldName=null},value:i,onCalciteRadioButtonChange:({target:e})=>{e.checked&&this._saveValueFromComponent(e)}}),n)}_renderAuxiliaryText(e){const t=e.name,i=this._inputsWithChanges.has(t)&&!e.valid?b(e,this.messages,this.timeZone):null!=this.viewModel.contingencyConstraintViolations.get(t)?this.messages.validationErrors.valuesIncompatible:null!=e.valueExpressionExecutor&&e.valueExpressionExecutor.stale?this.messages.valueExpressionError:null;return null!=i?j("calcite-input-message",{icon:!0,status:"invalid"},i):this._renderDescriptionOrEmpty(e.description)}_renderShowAllRelatedRecordsListItem(e){const{featureCount:t,relationshipId:i,showAllActionVisible:o}=e,{relatedRecordCallbacks:n}=this;if(!o||!n?.showAllRelatedRecords)return;const a=this.messages;return j("calcite-list-item",{description:E(a.totalCount,{count:t}),label:a.showAll,value:!0,onCalciteListItemSelect:()=>this._onShowAllRelatedRecordsClick(i)},j("calcite-icon",{icon:"list",scale:"s",slot:"content-end"}))}_renderAddRelatedRecordButton(e){const{canAddRelatedFeature:t,relationshipId:i,relatedLayer:o}=e,{messages:n,relatedRecordCallbacks:a}=this;if(t&&a?.addRelatedRecord&&o)return j("calcite-button",{alignment:"center",appearance:"outline-fill",class:c.centeredButton,disabled:e.updating||!e.originHasValidKey,iconStart:"plus",key:`${i}-add-button`,onclick:()=>{!e.updating&&e.originHasValidKey&&this._onAddRelatedRecordsClick(i,o)},round:!0,scale:"s",width:"half"},e.relatedLayerIsTable?n.addRecord:n.addFeature)}_renderRelatedRecordListItem(e,t){const{feature:i,description:o,title:n}=e,{feature:a,relatedRecordCallbacks:s}=this,{highlightHelper:r}=this.viewModel,l=()=>{r?.removeAll(),s?.editRelatedRecord&&a&&s.editRelatedRecord({parentFeature:a,relationshipId:t,relatedFeature:i})},d=r?()=>r.add(i):void 0,c=r?()=>r.remove(i):void 0;return j("calcite-list-item",{bind:this,description:o,key:`${t}-${i.uid}`,label:n,onclick:l,onmouseenter:d,onmouseleave:c,value:n},j("calcite-icon",{icon:_(i),scale:"m",slot:"content-start"}),j("calcite-icon",{icon:"chevron-right",scale:"s",slot:"content-end"}))}_renderRelationshipInput(e){if(!this._relatedRecordsEnabled||!e.editable)return;const{featureCount:t,relationshipId:i,showAllEnabled:o}=e,n=o?null:this._renderDescriptionOrEmpty(e.description),a=t>0?this._renderRelatedRecordsList(e):e.loaded?e.originHasValidKey?this._renderNoRelatedRecordsNotice():this._renderNoValidOriginKeyNotice(e):void 0;return j("calcite-label",{class:this.classes(c.label,c.relatedRecordsLabel),key:`relationship-${i}-container`},j("div",null,this._renderRelatedRecordsHeaderContainer(e),n,a),this._renderAddRelatedRecordButton(e))}_renderRelatedRecordsHeaderContainer(e){const t=e.updating||!e.loaded;return j("div",{class:c.relatedRecordsHeader,key:`relationship-${e.relationshipId}-header`},j("span",null,e.label),t?j("calcite-loader",{inline:!0,key:"loader",label:this.messagesCommon?.loading,scale:"s",type:"indeterminate"}):void 0)}_renderRelatedRecordsList(e){const{relationshipId:t}=e;return j("calcite-list",{class:c.relatedRecordsList},e.relatedFeatureInfos.map((e=>this._renderRelatedRecordListItem(e,t))),this._renderShowAllRelatedRecordsListItem(e),this._renderObserverNode())}_renderNoValidOriginKeyNotice(e){const{messages:t}=this,i=e.relatedLayerIsTable?t.noOriginKeyRecord:t.noOriginKeyFeature,o=e.relationship?.keyField,n=this.viewModel.findField(o),a=e.layer?.fieldsIndex.get(o),s=n?.label||a?.alias||o,r=E(i,{relatedLayerName:e.relatedLayer?.title,originKeyField:s});return j("calcite-notice",{icon:"information",kind:"brand",open:!0,scale:"s",width:"full"},j("div",{slot:"message"},r))}_renderNoRelatedRecordsNotice(){return j("calcite-notice",{icon:"information",kind:"brand",open:!0,scale:"s",width:"full"},j("div",{slot:"message"},this.messagesFeature.noRelatedFeatures))}_renderObserverNode(){if(this.viewModel.activeRelationshipInput?.showAllEnabled)return j("div",{afterCreate:this._afterListObserverCreated,afterRemoved:this._afterListObserverRemoved,bind:this,class:c.listObserver,key:"feature-observer"})}getCommonInputProps(e){const{disabled:t}=this,{editable:i,hint:o,label:n,maxLength:a,minLength:s,name:r,range:{max:l,min:d},required:p,valid:u,value:m}=e,h=this._inputsWithChanges.has(r),v=!i||t;return{afterCreate:this._afterComponentCreate,afterUpdate:this._afterComponentCreateOrUpdate,"aria-invalid":u?"false":"true",class:this.classes(c.fieldInput,v?c.inputDisabled:null,h&&!u?c.inputInvalid:null),key:r,label:n,max:null!=l?l:void 0,min:null!=d?d:void 0,maxLength:a>-1?a:void 0,minLength:s>-1?s:void 0,placeholder:o??void 0,readOnly:v,required:p,value:null==m?"":`${m}`,onblur:this._onComponentBlur,onfocus:this._onComponentFocus,onkeydown:this._onComponentKeyDown,[S]:r}}_getFieldInputFromHTMLElement(e){return this.viewModel.findField(e.getAttribute(S))}_afterDateComponentCreate(e){const t=this._getFieldInputFromHTMLElement(e),i=e.dataset.datePart,o=this._dateComponentMap.get(t.name);if("valueAsDate"in e&&null!=e.value){const t=e.value,i=new ResizeObserver((()=>{e.value=void 0,e.value=t,i.unobserve(e)}));i.observe(e)}if(null!=o)switch(i){case"date":o.date=e;break;case"time":o.time=e;break;case"timeZone":o.timeZone=e}else this._dateComponentMap.set(t.name,{[i]:e});this._afterDateComponentCreateOrUpdate(e)}_afterDateComponentCreateOrUpdate(e){this._afterComponentCreateOrUpdate(e)}_afterComponentCreate(e){const t=this._getFieldInputFromHTMLElement(e);C(t)&&null!=e.value&&"setNumberValue"in e&&e.setNumberValue({committing:!1,value:e.value,origin:"direct"}),this._afterComponentCreateOrUpdate(e)}_afterRadioGroupCreateOrUpdate(e){const t=e.selectedItem,i=e.querySelector("calcite-radio-button"),o=t||i;o&&this._afterComponentCreateOrUpdate(o)}_afterComponentCreateOrUpdate(e){const{viewModel:t}=this,i=this._getFieldInputFromHTMLElement(e),o=t.findField(this._focusedFieldName);this._attemptFocusOnNextRender&&o===i&&(this._attemptFocusOnNextRender=!1,h(i)&&(i.group.open=!0),e.setFocus())}_onComponentFocus(e){const t=e.target,i=this._getFieldInputFromHTMLElement(t);this._focusedFieldName=i.name}_onComponentBlur(e){const t=e.target;this._focusedFieldName=null,this._saveValueFromComponent(t)}_saveValueFromDateComponent(e){const{timeZone:t}=this,i=this._getFieldInputFromHTMLElement(e),o=i.field.type,{name:n,range:a}=i,s=this._dateComponentMap.get(n);if(!s)return;let r=this.viewModel.getValue(n),l=null;"date-only"===o?l=e.value:"time-only"===o?(r=x(r),l=x(e.value)):l="timestamp-offset"===o?null!=e.value?I({dateComponent:s.date,timeComponent:s.time,timeZoneComponent:s.timeZone,oldValue:r,defaultTimeZone:t}):null:null!=e.value?M({oldValue:r,dateComponent:s.date,timeComponent:s.time,timeZone:t,max:a.max,min:a.min}):null,null!==l&&e.value?r!==l&&this._updateFieldValue(n,l):this._updateFieldValue(n,null)}_saveValueFromComponent(e){const t=this._getFieldInputFromHTMLElement(e);this._updateFieldValue(t.name,this._parseValue(e))}_onComponentKeyDown({key:e,target:t}){const i=this._getFieldInputFromHTMLElement(t);"Enter"===e&&h(i)&&!i.group.open&&(i.group.open=!0)}_updateFieldValue(e,t){if(this.viewModel.setValue(e,t),this._inputsWithChanges.add(e),this.viewModel.fieldsWithContingentValues.has(e)){const e=Object.fromEntries(Object.entries(this.getValues()).filter((([e,t])=>null!=t)));this.viewModel.validateContingencyConstraints(e)}}_parseValue(e){const t=this._getFieldInputFromHTMLElement(e),i=e.value;return v(t.element,"switch")?e.checked?t.element.input.onValue:t.element.input.offValue:null==i||""===i?null:"number"===t.dataType?"-0"===i||"-0."===i||"-0,"===i?i:parseFloat(i):"date"===t.field.type?parseFloat(i):i}_ignoreDeselectionOfNoValueOption(e){const{firstChild:t,selectedItems:i}=e;0===i.length&&t&&"selected"in t?t.selected=!0:o.getLogger(this).warnOnce("Failed to override user attempt to deselect 'No value' option.")}_onGroupToggle(e,t){e.open?(t.open=!0,this._focusedFieldName=this._getFocusableInput("forward",t)?.name||null,this._attemptFocusOnNextRender=!0,"sequential"===this.groupDisplay&&this.viewModel.allGroupInputs.forEach((e=>{e!==t&&(e.open=!1)}))):t.open=!1,this.scheduleRender()}_onFormSubmit(e){e.preventDefault()}_onFormKeyDown(e){"Enter"===e.key&&this.viewModel.submit()}_afterListObserverCreated(e){this.viewModel.activeRelationshipInput&&(this._listObserverNode=e)}_afterListObserverRemoved(){this._listObserverNode=null}_onObserverChange(){this._listObserverNode&&this._listObserver.unobserve(this._listObserverNode);const e=this.viewModel.activeRelationshipInput;e&&this._listObserverNode&&e.showAllEnabled&&this._listObserver.observe(this._listObserverNode)}_incrementRelatedRecordPage(){const e=this.viewModel.activeRelationshipInput;e?.incrementPage()}_syncGroupInputStates(){if("sequential"!==this.groupDisplay)return;const e=this.viewModel.allGroupInputs;if(!e.length)return;const t=e.filter((e=>e.open));0===t.length?e[0].open=!0:t.length>1&&t.slice(1).forEach((e=>e.open=!1))}_onComboboxClose(e){this._activeComboboxClosedByWorkaround||this._activeCombobox!==e.target||(this._activeCombobox=null)}_onComboboxOpen(e){this._activeComboboxClosedByWorkaround=!1,this._activeCombobox=e.target}onScroll(e){if(this._activeCombobox){const t=this._activeCombobox.getBoundingClientRect(),i=e.target.getBoundingClientRect();t.bottom>i.bottom?(this._activeComboboxClosedByWorkaround=!0,this._activeCombobox.open=!1):(this._activeComboboxClosedByWorkaround&&(this._activeCombobox.open=!0,this._activeComboboxClosedByWorkaround=!1),this._activeCombobox.reposition())}}};e([s()],U.prototype,"_listObserverNode",void 0),e([s()],U.prototype,"_relatedRecordsEnabled",null),e([s()],U.prototype,"disabled",null),e([s()],U.prototype,"feature",null),e([s()],U.prototype,"formTemplate",null),e([s()],U.prototype,"groupDisplay",void 0),e([s()],U.prototype,"headingLevel",void 0),e([s()],U.prototype,"label",null),e([s()],U.prototype,"layer",null),e([s()],U.prototype,"map",null),e([s(),L("esri/widgets/FeatureForm/t9n/FeatureForm")],U.prototype,"messages",void 0),e([s(),L("esri/t9n/common")],U.prototype,"messagesCommon",void 0),e([s(),L("esri/widgets/Feature/t9n/Feature")],U.prototype,"messagesFeature",void 0),e([s(),L("esri/widgets/FeatureTemplates/t9n/FeatureTemplates")],U.prototype,"messagesTemplates",void 0),e([s()],U.prototype,"relatedRecordCallbacks",null),e([s()],U.prototype,"relationshipId",null),e([s()],U.prototype,"spatialReference",null),e([s()],U.prototype,"strict",null),e([s()],U.prototype,"timeZone",null),e([s()],U.prototype,"view",null),e([s(),T(["value-change","submit"])],U.prototype,"viewModel",void 0),U=e([r("esri.widgets.FeatureForm")],U);const $=U;export{$ as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../chunks/tslib.es6.js";import"../../geometry.js";import t from"../../Graphic.js";import{isSome as r,equals as i}from"../../core/arrayUtils.js";import o from"../../core/Collection.js";import{deprecatedProperty as s}from"../../core/deprecate.js";import a from"../../core/Error.js";import n from"../../core/Evented.js";import{isSerializable as l}from"../../core/JSONSupport.js";import{clone as c,equalsShallow as h}from"../../core/lang.js";import u from"../../core/Logger.js";import{clamp as g}from"../../core/mathUtils.js";import{destroyMaybe as d}from"../../core/maybe.js";import{isAbortError as m,waitTick as p}from"../../core/promiseUtils.js";import{watch as y,initial as f,syncAndInitial as v,when as _}from"../../core/reactiveUtils.js";import{property as w}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import{subclass as b}from"../../core/accessorSupport/decorators/subclass.js";import{geographicToWebMercator as P}from"../../geometry/support/webMercatorUtils.js";import C from"../../layers/GraphicsLayer.js";import{searchImages as F}from"../../layers/orientedImagery/queries.js";import{calculateSuitabilities as I}from"../../layers/orientedImagery/core/bestImageUtils.js";import{createCoveragePolygon as S,computePolygonForInspection as V,resizePolygon as O,checkIfPolygonContainsSelectedPoint as A}from"../../layers/orientedImagery/core/coverageUtils.js";import{updateElevation as B,transformPoints as j}from"../../layers/orientedImagery/transformations/groundToImageUtils.js";import{transformPoints as G}from"../../layers/orientedImagery/transformations/imageToGroundUtils.js";import{getInitialAngle as M,convertPixelToHeadingPitch as R,convertHeadingPitchToSphereVertex as x}from"../../layers/orientedImagery/transformations/utils.js";import L from"../../rest/support/AttachmentQuery.js";import{ViewEventPriorities as k}from"../../views/input/InputManager.js";import D from"../PanoramicViewer.js";import{sectorsInOrder as E,sectorsRadii as H}from"./constants.js";import{activePolygonSymbol as U,crossSymbol as N,crossSymbol3D as T,diamondSymbol as z,diamondSymbol3D as W,polygonSymbol as J,activeSourcePointSymbol as q,sourcePointSymbol as $}from"./symbols.js";import{isNoAttachmentError as Q,isTifOrMrf as Z,isSceneView as K,isGraphic as X,calculateSegment as Y,calculateDirection as ee}from"./utils.js";import te from"./components/ImageViewer.js";import re from"../../geometry/Point.js";import ie from"../../geometry/Polygon.js";import oe from"../../geometry/SpatialReference.js";const se={click:"view-click",imageClick:"image-click",interactionHandles:"interaction-handles",footprintHandles:"footprint-handles"},ae=new Set(["JPG","JPEG"]),ne=e=>"FA"===e;let le=class extends n.EventedAccessor{constructor(e){super(e),this.additionalFeatures=new o,this.determineWorkflowForFeature=async()=>{const{currentBestFeature:e,selectedPoint:t}=this;if(e&&t){this._initialCurrentCoverageUpdate=!0,this._updatePointsAndPolygons(),this._fetchFeaturesController??=new AbortController;const{signal:e}=this._fetchFeaturesController;try{await this._loadImage({signal:e})}catch(r){m(r)||(this.loadImageError(r),u.getLogger(this).error("#loadIImage()","error occured while loading image",r))}this._fetchFeaturesController=null}},this.drawFootprint=()=>{this._initialCurrentCoveragePolygon&&this.updateCurrentCoveragePolygon(this._initialCurrentCoveragePolygon)},this.layer=null,this.shouldShowSelectedImage=!1,this.coverageFrustums=new o,this.coveragePolygons=new o,this.currentCoverageVisible=!0,this.disabled=!1,this.displayMessage={key:"onLoadMessage",type:"info"},this.pointSources=new o,this.previousFeatureAngle=0,this.currentBestFeature=null,this.bestFeatureAngle=0,this.selectedPoint=null,this.features=new o,this.isAdditionalCoverageVisible=!1,this.isAdditionalPointSourcesVisible=!1,this.localPort=null,this.mapImageConversionToolState=!1,this.navigatorCurrentBestFeature=null,this.updateFootprint=async e=>{if("image-loaded"!==this.state)return;const t=new AbortController,{signal:r}=t;if(this._updateCoverageController=t,"default"===this.mode)try{const t=await G(e,{feature:this.currentBestFeature,imageProperties:this._imageViewer.viewModel.image.serviceRasterInfo,options:{signal:r},footprintExtent:this._footprintExtent});await this._updateCurrentFootprint(t,r)}catch(i){m(i)||u.getLogger(this).error("#updateFootprint()",i)}},this._additionalCoveragePolygons=new o,this._additionalFeatureGraphics=new o,this._currentCoveragePolygon=null,this._fetchFeaturesController=null,this._imageViewer=new te,this._initialCurrentCoveragePolygon=null,this._initialCurrentCoverageUpdate=!0,this._loading=!1,this._overlays=new C({listMode:"hide",internal:!0}),this._panoramicViewer=new D,this._referencePointOnGround=null,this._referencePointOnImage=null,this._sectorData=null,this._crossSymbol=null,this._footprintExtent=null,this._suitabilities=null,this._transformController=new AbortController,this._updateCoverageController=null,this.loadImageFromSource=async(e,t)=>{const{mode:r,imageRotation:i,options:o}=t,s="string"==typeof e,a=s?e.split(".").pop():e.datasetFormat,n=s?e:e.url,l=ae.has(a.toUpperCase());switch(r){case"default":this._imageViewer.imageSource=e,this._imageViewer.imageRotation=i??0,await this._imageViewer.loadImage(o);break;case"panoramic":if(l){const{pitch:e,yaw:r,cameraLocation:i}=t;this._panoramicViewer.imageSource=n;const s=await M(i,this.selectedPoint)-(r??0);this._panoramicViewer.pitch=e??0,this._panoramicViewer.yaw=s,await this._panoramicViewer.loadImage(o)}else this.setMessage("unsupportedPanoramicImageryError","error",void 0,{datasetFormat:a})}},this.loadImageViewer=e=>{this._imageViewer.container=e},this.loadPanoramicViewer=e=>{this._panoramicViewer.container=e},this._getImageSourceFromAttachment=async(e,t,r)=>{const i=new L({objectIds:[t]}),o=await e.queryAttachments(i,r),s=o[`${t}`]?.[0],n=s?.url;if(!n)throw new a("NoAttachmentError","no attachments found",{[e.objectIdField]:t,layer:e});return{datasetFormat:s.contentType.split("/")[1].toUpperCase(),url:n}},this._loadImage=async e=>{const{currentBestFeature:t,layer:r,mode:i}=this;if(this.clearGraphics(),!r||!t||"none"===i)return;const{attributes:o}=t,{imagePath:s,imageRotation:a,cameraHeading:n,cameraRoll:l,cameraPitch:c,objectId:h,cameraOrientation:g,location:d}=o,p=(l??0)+(a??0),y=d.spatialReference.isWGS84&&4!==g?.type?P(d):new re(d);let f=s;if(ne(s))try{f=await this._getImageSourceFromAttachment(r,h,e)}catch(v){if(m(v))return;return Q(v)?(u.getLogger(this).error(v),void this.setMessage("noAttachment","error",`${r.objectIdField}: ${h}`)):(u.getLogger(this).error(v,{[r.objectIdField]:h,layer:r}),void this.setMessage("imageLoadError","error",`query-attachments-failed:${r.objectIdField} ${h}`))}try{await this.loadImageFromSource(f,{imageRotation:p,options:e,pitch:c,yaw:n,mode:i,cameraLocation:y}),this.transformAndPlotSelectedLocation(e)}catch(v){m(v)||this.loadImageError(v)}},this._mapImageConversionToolViewClickHandler=e=>{e.stopPropagation(),e.preventDefault(),e.mapPoint&&this.plotMapPoint(e.mapPoint)},this._updateCurrentFootprint=async(e,i)=>{await p(i);const o=e.filter(r);if(o.length){const e=[o.map((({x:e,y:t})=>[e,t,1]))];e[0].push(e[0][0]);const r=new ie({hasZ:!0,rings:e,spatialReference:o[0].spatialReference});this.updateCurrentCoveragePolygon(new t({attributes:{imageID:this.currentBestFeature?.attributes.objectId},geometry:r,symbol:U,visible:this.currentCoverageVisible}))}},this._viewClickHandler=e=>{"mouse"===e.pointerType&&0!==e.button||(e.stopPropagation(),e.preventDefault(),e.mapPoint&&this.loadBestImage(e.mapPoint))},this.plotSelectedPointOnImage=async(e,r)=>{if(await p(r),!e)return;const i=new re({...l(e)?e.toJSON():e,spatialReference:oe.WebMercator});if("default"===this.mode)i.x-=.5,i.y=.5-i.y,this._crossSymbol=new t({geometry:i,symbol:N}),this._imageViewer.addGraphic(this._crossSymbol,0);else if("panoramic"===this.mode){const{imageSize:r}=this._panoramicViewer;if(!r)return;const[i,o]=r,{heading:s,pitch:a}=R(e,i,o),n=x(s,a);this._crossSymbol=new t({geometry:new re(n,oe.WebMercator),symbol:T}),this._panoramicViewer.addGraphic(this._crossSymbol,0)}},this.updateFootprintPanorama=async()=>{const{yaw:e,pitch:r,fov:i,imageSize:o,imageRenderer:{size:s}}=this._panoramicViewer,a=this.currentBestFeature?.clone();if(!o||!a)return;const n=i/(s[0]/s[1]),{attributes:l}=a;l.orientedImageryType=null,l.cameraHeading=(e+l.cameraHeading)%360,l.cameraPitch=r,l.horizontalFieldOfView=i,l.verticalFieldOfView=n,l.cameraRoll=0;const{polygon:c}=S(a);this.updateCurrentCoveragePolygon(new t({attributes:{imageID:l.objectId},geometry:c,symbol:U,visible:this.currentCoverageVisible}))},this.handleSectorClick=this.handleSectorClick.bind(this),this.searchBestImage=this.searchBestImage.bind(this),this.transformAndPlotReferencePointOnImage=this.transformAndPlotReferencePointOnImage.bind(this),this.updateSuitabilities=this.updateSuitabilities.bind(this),this.determineWorkflowForFeature=this.determineWorkflowForFeature.bind(this),this.updateCoverage=this.updateCoverage.bind(this),this.selectBestFeature=this.selectBestFeature.bind(this),this.drawFootprint=this.drawFootprint.bind(this)}initialize(){this.addHandles([y((()=>this.view?.map),((e,t)=>{t?.layers.remove(this._overlays),e?.layers.add(this._overlays)}),f),y((()=>this.view?.map?.allLayers?.length),(e=>{e&&this.view?.map?.layers.reorder(this._overlays,e-1)}),f),y((()=>[this.state,this.mapImageConversionToolState,this.view]),(()=>{if(this.removeHandles(se.click),"disabled"===this.state||null==this.view)return;const e=this.mapImageConversionToolState&&"image-loaded"===this.state?this._mapImageConversionToolViewClickHandler:this._viewClickHandler;this.addHandles(this.view.on("click",e,k.WIDGET),se.click),this.removeHandles(se.imageClick);const{mapImageConversionToolState:t,mode:r}=this;if(t&&"none"!==r)switch(r){case"default":this._imageViewer.clickAction="pixel-location",this.addHandles(this._imageViewer.on("pixel-location",(async e=>{this.plotReferencePointOnImage(e);const t=this.currentBestFeature;if(t){const r=(await G([e.toJSON()],{feature:t,imageProperties:{width:this._imageViewer.imageSize[0],height:this._imageViewer.imageSize[1]},options:{signal:this._transformController?.signal},footprintExtent:this._footprintExtent}))[0];r&&this.plotReferencePointOnGround(r)}})),se.imageClick);break;case"panoramic":this._panoramicViewer.clickAction="pixel-location",this.addHandles(this._panoramicViewer.on("pixel-location",(async e=>{this.plotReferencePointOnImage(e);const t=this.currentBestFeature,{imageSize:r}=this._panoramicViewer;if(t&&e&&r){const i=(await G([e],{feature:t,imageProperties:{width:r[0],height:r[1]},options:{signal:this._transformController?.signal},footprintExtent:this._footprintExtent}))[0];i&&this.plotReferencePointOnGround(i)}})),se.imageClick)}}),v),y((()=>this.bestFeatureAngle),((e,t)=>{this.previousFeatureAngle=t??0}),v),y((()=>this.currentBestFeature),((e,t)=>{this.determineWorkflowForFeature(e,t)}),{sync:!0}),y((()=>this.mode),(e=>{switch(this.removeHandles(se.interactionHandles),e){case"default":this.addHandles(y((()=>this._imageViewer.imagePointsInView),(e=>{e&&this.updateCoverage()}),{...v,equals:(e,t)=>i(e,t,h)}),se.interactionHandles);break;case"panoramic":this.addHandles(_((()=>this._panoramicViewer.imageSize),(()=>{this._createFootprintHandles()})),se.interactionHandles)}}),v),y((()=>[this.brightness,this.contrast,this.sharpness]),(()=>{const{_imageViewer:e,brightness:t,contrast:r,mode:i,sharpness:o}=this;"default"===i&&(e.brightness=t,e.contrast=r,e.sharpness=o)}),v)])}destroy(){this._cancelCurrentCoverageUpdate(),this._cancelFetchingFeatures(),this.coverageFrustums.destroy(),this.coveragePolygons.destroy(),this.pointSources.destroy(),this._additionalCoveragePolygons.destroy(),this._additionalFeatureGraphics.destroy(),this._initialCurrentCoveragePolygon=d(this._initialCurrentCoveragePolygon),this._currentCoveragePolygon=d(this._currentCoveragePolygon),this._crossSymbol=d(this._crossSymbol),this._referencePointOnGround=d(this._referencePointOnGround),this._referencePointOnImage=d(this._referencePointOnImage),this._overlays&&this.view?.map.remove(this._overlays),this._overlays.destroy()}get activeLayer(){return s(u.getLogger(this),"activeLayer",{replacement:"layer"}),this.layer}set activeLayer(e){s(u.getLogger(this),"activeLayer",{replacement:"layer"}),this.layer=e}get mode(){const e=this.currentBestFeature?.attributes;if(!e)return"none";const{horizontalFieldOfView:t,isSpherical:r}=e;return 360===t||r?"panoramic":"default"}get imagePointsInView(){const{mode:e,_imageViewer:t}=this;return"default"===e?t.imagePointsInView:null}get brightness(){return this._get("brightness")??0}set brightness(e){this._set("brightness",e>10?10:e<-10?-10:e)}get contrast(){return this._get("contrast")??0}set contrast(e){this._set("contrast",g(e,-10,10))}get featureCount(){return this.features?.length??0}get imageGalleryEnabled(){return Z(this.currentBestFeature?.attributes.imagePath.trim())}get imageLoaded(){return s(u.getLogger(this),"imageLoaded",{replacement:'Use OrientedImageryViewer.state === "image-loaded"',version:"4.29",warnOnce:!0}),"image-loaded"===this.state}get referencePoint(){return this._referencePointOnGround?.geometry}get sharpness(){return this._get("sharpness")??0}set sharpness(e){this._set("sharpness",g(e,0,1))}get sectorData(){const{_sectorData:e}=this;return e?E.map((t=>e[t])):null}get state(){const{mode:e,disabled:t}=this;if(t)return"disabled";if(this._loading)return"image-loading";switch(e){case"default":return this._imageViewer.state;case"panoramic":return this._panoramicViewer.state}return"ready"}get thumbnails(){const{features:e}=this;return e?new o(e.map((({attributes:{imagePath:e,objectId:t}})=>{const r=e.trim();return Z(r)?{url:r,objectId:t}:null})).filter(r)):null}set view(e){this._set("view",e)}filterByFootprints(e,t){const r=[],i=[],o=[];return e.forEach((e=>{const{layer:{coveragePercent:s},attributes:a}=e;let n;const{polygon:c,frustum:h}=S(e);if(n=c,a.isInspection&&(n=V(a)),s&&(n=O(n,s)),A(n,t)){o.push(e);const t=n.toJSON(),s=h?.toJSON(),{cameraHeight:c,cameraHeading:u,location:g,objectId:d}=a,m=l(g)?g.toJSON():g;t.imageID=m.imageID=d,s&&(s.imageID=d),m.z=c,this.pointSources?.push(m),r.push(u>0?t:void 0),i.push(u>0?s:void 0)}})),{features:o,polygons:r,frustums:i}}getCurrentCoveragePolygon(){return this._currentCoveragePolygon}getCurrentBestFeaturePolygon(){return this._initialCurrentCoveragePolygon}handleSectorClick(e){if(isNaN(e))return;const t=this._sectorData?.[E[e]];t?.length&&this._updateCurrentBestFeature(t.at(0))}handleFeatureClick(e){const{sector:t,featureIndexInSector:r}=e;if(isNaN(r))return;const i=this._sectorData?.[t];i?.length&&this._updateCurrentBestFeature(i.at(r))}async loadBestImage(e){this._loading=!0,this.displayMessage=null,this.selectedPoint=e.spatialReference.isGeographic?P(e):e.clone(),this.features.removeAll(),this.currentBestFeature=null,this.additionalFeatures.removeAll(),this._additionalCoveragePolygons.removeAll(),this._additionalFeatureGraphics.removeAll(),this._currentCoveragePolygon=d(this._currentCoveragePolygon),this._overlays?.removeAll(),await this._fetchFeaturesWithController(e)}loadImageError(e){u.getLogger(this).error("oriented-imagery-viewer:load-image",e),this.setMessage("imageLoadError","error",e.message)}async plotMapPoint(e){return this.plotReferencePoint(e),this.transformAndPlotReferencePointOnImage({feature:this.currentBestFeature,selectedLocation:e,options:{signal:this._transformController?.signal}})}plotReferencePointOnGround(e){this._referencePointOnGround&&(this._overlays?.remove(this._referencePointOnGround),this._referencePointOnGround.destroy()),null!=e&&(this._referencePointOnGround=new t({geometry:{type:"point",...e.toJSON()},symbol:z}),this.view?this._overlays?.add(this._referencePointOnGround):this.emit("plot-ground-point",{data:{point:this._referencePointOnGround?.geometry}}))}plotReferencePointOnImage(e){if("image-loaded"===this.state)switch(this._referencePointOnImage&&(this._imageViewer.removeGraphic(this._referencePointOnImage),this._panoramicViewer.removeGraphic(this._referencePointOnImage),this._referencePointOnImage.destroy()),this.mode){case"default":{const r=l(e)?e.toJSON():e;r.x-=.5,r.y=.5-r.y,this._referencePointOnImage=new t({geometry:{type:"point",spatialReference:this._imageViewer.imageRenderer.spatialReference,...r},symbol:z}),this._imageViewer.addGraphic(this._referencePointOnImage,0);break}case"panoramic":{const{imageSize:r}=this._panoramicViewer;if(!r)return;const[i,o]=r,{heading:s,pitch:a}=R(e,i,o),n=x(s,a);this._referencePointOnImage=new t({geometry:new re(n,oe.WebMercator),symbol:W}),this._panoramicViewer.addGraphic(this._referencePointOnImage,0);break}}}resetImage(){switch(this.setMessage("onLoadMessage","info"),this.mode){case"default":this._imageViewer.clearImage(),this._imageViewer.clearGraphics();break;case"panoramic":this._panoramicViewer.clearGraphics()}this._cancelCurrentCoverageUpdate(),this._cancelFetchingFeatures()}async searchBestImage(e,t){try{const r=await F(e,t);r&&await this._processFeatureResponse(r,{signal:t?.signal})}catch(r){m(r)||(this.setMessage("imageLoadError","error",r.message),u.getLogger(this).error("error occurred while finding best image",r))}}selectBestFeature(e){this.currentBestFeature=this.features?.find((({attributes:t})=>t.objectId===Number(e)))}setAdditionalCameraLocationsVisibility(e){this._additionalFeatureGraphics.forEach((t=>{t.visible=e}))}setAdditionalCoverageVisibility(e){this._additionalCoveragePolygons.forEach((t=>{t.visible=e}))}setCurrentCoverageVisibility(e){this._currentCoveragePolygon&&(this._currentCoveragePolygon.visible=e),this._currentBestFeatureGraphic&&(this._currentBestFeatureGraphic.visible=e)}setMapImageConversionToolState(e){this.mapImageConversionToolState=e}async transformAndPlotReferencePointOnImage(e){const{selectedLocation:t,options:r}=e,i=this._initialCurrentCoveragePolygon?.geometry;if(!i?.contains(t))return;const o=await this.transformPoint(t,r);return o?(this.plotReferencePointOnImage(o),{x:o.x,y:o.y}):void 0}updateSuitabilities(e){this._suitabilities=e.sort(((e,t)=>e.suitability-t.suitability));const t=this._suitabilities.map((e=>e.feature));this._updateFeatures(t),this._groupFeaturesBySectors(),this._initialCurrentCoverageUpdate=!0}_cancelFetchingFeatures(e){const t=this._fetchFeaturesController;t&&t.abort(e),this._fetchFeaturesController=null}_cancelCurrentCoverageUpdate(){const e=this._updateCoverageController;e&&e.abort("Multiple Coverage Updates: Aborting Current Coverage Update to sync image and coverage"),this._updateCoverageController=null}_createFootprintHandles(){this.removeHandles(se.footprintHandles),this.addHandles(y((()=>[this._panoramicViewer.fov,this._panoramicViewer.yaw,this._panoramicViewer.pitch]),(()=>{this.updateFootprintPanorama()}),v),se.footprintHandles)}async _fetchFeatures(e,t){if(!this.view)return;const r=this.layer;if(r){const i={include:r},o=this.view.toScreen(e);if(!o)return;const s=await this.view.hitTest(o,i);this._processHitTestResults(r,s,t)}}async _fetchFeaturesWithController(e){this._cancelFetchingFeatures();const t=new AbortController,{signal:r}=t;this._fetchFeaturesController=t;try{await this._fetchFeatures(e,{signal:r}).finally((()=>{this._fetchFeaturesController=null}))}catch(i){this.setMessage("imageLoadError","error"),u.getLogger(this).error("error occurred while fetching features",i)}}_groupFeaturesBySectors(){const{_suitabilities:e,additionalFeatures:t,currentBestFeature:r,features:i}=this;if(!(e&&t&&r&&i))return void(this._sectorData=null);this._sectorData={};for(const l of E)this._sectorData[l]=new o;const s=e.map(((e,t)=>({...e,featureIndex:t})));s.sort(((e,t)=>e.trueSuitability-t.trueSuitability));const a=s.map((({distance:e})=>e)),n=Math.max(...a);s.forEach((e=>{const{distance:t,angle:r,featureIndex:o}=e,s=t/n*H[2],a=Y(t,n),l=ee(r);if(!this._sectorData)return;const c=H[3]+s*Math.sin(r*Math.PI/180),h=H[3]+s*Math.cos(r*Math.PI/180);let u;const g=i.at(o),d=g===this.currentBestFeature,m=this.currentBestFeature?.attributes.cameraPitch&&this.currentBestFeature?.attributes.cameraPitch<5;if(d&&m)u=-90;else{const e=c-H[3],t=h-H[3],r=t/Math.sqrt(e**2+t**2);let i=180*Math.acos(r)/Math.PI;(e<0&&t<0||e<0&&t>0)&&(i*=-1),u=i}const p=""===a?l:`${a}_${l}`;d&&(u===this.bestFeatureAngle?this.previousFeatureAngle=u:this.bestFeatureAngle=u,this.navigatorCurrentBestFeature=m?null:{x:c,y:h,direction:l});const y=this._sectorData[p];y.add({angle:r,featureIndex:o,x:c,y:h,objectID:g.attributes.objectId,sector:p,featureIndexInSector:y.length})}))}async _processFeatureResponse(e,t){const{selectedPoint:i}=this;if(!i)return;if(!e)return;const o=e;if(!o)return;const{features:s}=o;if(!s.length)return this.setMessage("noImageError","error"),void(this.currentBestFeature=null);this.coveragePolygons.removeAll(),this.coverageFrustums.removeAll(),this.pointSources.removeAll();const{features:a,polygons:n,frustums:l}=this.filterByFootprints(s,i),c=a;this.coveragePolygons.addMany(n),this.coverageFrustums.addMany(l);const h=n.filter(r).reduce(((e,t)=>(e.push(...t.rings.flat()),e)),new Array),u=new ie({rings:h,spatialReference:n[0]?.spatialReference}).extent;if(!c.length)return void this.setMessage("noImageError","error");if(this._footprintExtent=u,c[0].attributes.elevationSource&&!i.z&&u){const e=await B([i],{feature:c[0],footprintExtent:u,options:t});if(e[0]){const t=e[0];i.elevation=t.z}c[0].elevationSample&&c.forEach((e=>{e.elevationSample=c[0].elevationSample}))}this._suitabilities=I({features:c,selectedPoint:i,camera:K(this.view)?this.view.camera:null,currentImage:this.currentBestFeature}),this.updateSuitabilities(this._suitabilities);const g=this._suitabilities.map((e=>e.feature));this.currentBestFeature=g[0],this._loading=!1}async _processHitTestResults(e,t,r){const{screenPoint:i,results:[o]}=t,s="graphic"===o?.type&&this.shouldShowSelectedImage,a={layerInstanceOrURL:e,point:o?.mapPoint??this.view?.toMap(i),queryParams:{maximumDistance:e.maximumDistance,objectIds:s?[o.graphic.getAttribute(e.objectIdField)]:void 0},queryFeatures:null};await this.searchBestImage(a,r)}_updateFeatures(e){if(!e.length)return this.currentBestFeature=null,void this.additionalFeatures.removeAll();this.features.removeAll(),this.features.addMany(e),this.currentBestFeature=e[0],e.length>1?this.additionalFeatures.addMany(e.slice(1)):this.additionalFeatures.removeAll()}_updatePointsAndPolygons(){const{coveragePolygons:e,pointSources:r,currentBestFeature:i,currentCoverageVisible:o,isAdditionalCoverageVisible:s,isAdditionalPointSourcesVisible:a}=this;if(e&&r&&i){this._additionalCoveragePolygons.removeAll(),this._additionalFeatureGraphics.removeAll(),this._currentCoveragePolygon&&(this._currentCoveragePolygon.destroy(),this._currentCoveragePolygon=null,this._initialCurrentCoveragePolygon=null);for(const r of e)r?.imageID===i.attributes.objectId?this._initialCurrentCoveragePolygon=new t({attributes:{imageID:r?.imageID},geometry:{type:"polygon",...r},symbol:U,visible:!1}):this._additionalCoveragePolygons.push(new t({attributes:{imageID:r?.imageID},geometry:{type:"polygon",...r},symbol:J,visible:s}));for(const e of r)e.imageID===i.attributes.objectId?this._currentBestFeatureGraphic=new t({attributes:{imageID:e.imageID},geometry:{type:"point",...e},symbol:q,visible:o}):this._additionalFeatureGraphics?.push(new t({attributes:{imageID:e.imageID},geometry:{type:"point",...e},symbol:$,visible:a}))}}_updateCurrentBestFeature(e){if(!e)return;this.currentBestFeature=this.features?.at(e.featureIndex);const t=this.currentBestFeature?.attributes.cameraPitch&&this.currentBestFeature?.attributes.cameraPitch<5;let r;if(t)r=-90;else{const t=e.x-H[3],i=e.y-H[3],o=i/Math.sqrt(t**2+i**2);let s=180*Math.acos(o)/Math.PI;(t<0&&i<0||t<0&&i>0)&&(s*=-1),r=s}r===this.bestFeatureAngle?this.previousFeatureAngle=r:this.bestFeatureAngle=r,this.navigatorCurrentBestFeature=t?null:{x:e.x,y:e.y,direction:e.sector.includes("_")?e.sector.split("_")[1]:e.sector}}clearGraphics(){this._imageViewer.clearGraphics(),this._panoramicViewer.clearGraphics()}plotReferencePoint(e){"mapPoint"in e?this.plotReferencePointOnGround(e.mapPoint):this.plotReferencePointOnGround(e)}setMessage(e,t,r,i){this._loading=!1,this.displayMessage={key:e,type:t,data:r,map:i}}async transformAndPlotSelectedLocation(e){const{currentBestFeature:t,selectedPoint:r,state:i}=this;if(this._crossSymbol&&(this._panoramicViewer.removeGraphic(this._crossSymbol),this._imageViewer.removeGraphic(this._crossSymbol),this._crossSymbol=d(this._crossSymbol)),!r||!t||"image-loaded"!==i)return;let o;try{o=await this.transformPoint(r,e),await this.plotSelectedPointOnImage(o,e)}catch(s){m(s)||u.getLogger(this).error("failed to transform map point to pixel, cross symbol will not be plotted on image",{error:s,selectedPoint:r,feature:t})}}async transformPoint(e,t){if("none"===this.mode)return;const r=this.currentBestFeature,i=await j([e],{feature:r,imageProperties:"default"===this.mode?this._imageViewer.viewModel.image.serviceRasterInfo:{width:this._panoramicViewer.imageSize?.[0],height:this._panoramicViewer.imageSize?.[1]},options:t});if(!i.length)return;return i[0]}updateCurrentCoveragePolygon(e){if(this._initialCurrentCoverageUpdate){if(this._overlays?.removeAll(),this._initialCurrentCoverageUpdate=!1,e&&(this._currentCoveragePolygon&&this._currentCoveragePolygon.destroy(),e.visible=this.currentCoverageVisible,this._currentCoveragePolygon=e),this.view){const e=this.selectedPoint?new t({geometry:this.selectedPoint.clone(),symbol:N,attributes:{imageID:this.currentBestFeature?.attributes.objectId}}):null;this._overlays?.graphics.addMany([...this._additionalCoveragePolygons,...this._additionalFeatureGraphics,this._currentCoveragePolygon,this._currentBestFeatureGraphic,e].filter(X))}}else if(this.view){const t=this._currentCoveragePolygon&&this._overlays?this._overlays.graphics.indexOf(this._currentCoveragePolygon):-1;e&&(this._currentCoveragePolygon&&(this._overlays?.remove(this._currentCoveragePolygon),this._currentCoveragePolygon.destroy()),e.visible=this.currentCoverageVisible,this._currentCoveragePolygon=e,this._overlays?.graphics.add(this._currentCoveragePolygon,t>=0?t:void 0))}}async updateCoverage(){if("default"===this.mode){this._cancelCurrentCoverageUpdate();const{imagePointsInView:e,state:t}=this._imageViewer,r=c(e);if(!r||"image-loaded"!==t)return;this.updateFootprint(r)}}};e([w()],le.prototype,"activeLayer",null),e([w()],le.prototype,"additionalFeatures",void 0),e([w({json:{write:!1}})],le.prototype,"determineWorkflowForFeature",void 0),e([w()],le.prototype,"drawFootprint",void 0),e([w({readOnly:!0,value:"none"})],le.prototype,"mode",null),e([w()],le.prototype,"imagePointsInView",null),e([w()],le.prototype,"layer",void 0),e([w()],le.prototype,"shouldShowSelectedImage",void 0),e([w({type:Number})],le.prototype,"brightness",null),e([w({type:Number})],le.prototype,"contrast",null),e([w()],le.prototype,"coverageFrustums",void 0),e([w()],le.prototype,"coveragePolygons",void 0),e([w()],le.prototype,"currentCoverageVisible",void 0),e([w()],le.prototype,"disabled",void 0),e([w()],le.prototype,"displayMessage",void 0),e([w()],le.prototype,"pointSources",void 0),e([w()],le.prototype,"previousFeatureAngle",void 0),e([w()],le.prototype,"currentBestFeature",void 0),e([w()],le.prototype,"bestFeatureAngle",void 0),e([w()],le.prototype,"selectedPoint",void 0),e([w({readOnly:!0})],le.prototype,"featureCount",null),e([w()],le.prototype,"features",void 0),e([w({readOnly:!0})],le.prototype,"imageGalleryEnabled",null),e([w({readOnly:!0})],le.prototype,"imageLoaded",null),e([w()],le.prototype,"isAdditionalCoverageVisible",void 0),e([w()],le.prototype,"isAdditionalPointSourcesVisible",void 0),e([w({type:Number})],le.prototype,"localPort",void 0),e([w()],le.prototype,"mapImageConversionToolState",void 0),e([w()],le.prototype,"navigatorCurrentBestFeature",void 0),e([w()],le.prototype,"referencePoint",null),e([w({type:Number})],le.prototype,"sharpness",null),e([w({readOnly:!0})],le.prototype,"sectorData",null),e([w({readOnly:!0})],le.prototype,"state",null),e([w({readOnly:!0})],le.prototype,"thumbnails",null),e([w()],le.prototype,"updateFootprint",void 0),e([w({value:null})],le.prototype,"view",null),e([w()],le.prototype,"_additionalCoveragePolygons",void 0),e([w()],le.prototype,"_additionalFeatureGraphics",void 0),e([w()],le.prototype,"_currentCoveragePolygon",void 0),e([w()],le.prototype,"_fetchFeaturesController",void 0),e([w()],le.prototype,"_imageViewer",void 0),e([w()],le.prototype,"_initialCurrentCoveragePolygon",void 0),e([w()],le.prototype,"_initialCurrentCoverageUpdate",void 0),e([w()],le.prototype,"_loading",void 0),e([w()],le.prototype,"_overlays",void 0),e([w()],le.prototype,"_panoramicViewer",void 0),e([w()],le.prototype,"_referencePointOnGround",void 0),e([w()],le.prototype,"_referencePointOnImage",void 0),e([w()],le.prototype,"_currentBestFeatureGraphic",void 0),e([w()],le.prototype,"_sectorData",void 0),le=e([b("esri.widgets.OrientedImageryViewer.OrientedImageryViewerViewModel")],le);const ce=le;export{ce as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import"../../geometry.js";import t from"../../Graphic.js";import{isSome as r,equals as i}from"../../core/arrayUtils.js";import o from"../../core/Collection.js";import{deprecatedProperty as s}from"../../core/deprecate.js";import a from"../../core/Error.js";import n from"../../core/Evented.js";import{isSerializable as l}from"../../core/JSONSupport.js";import{clone as c,equalsShallow as h}from"../../core/lang.js";import u from"../../core/Logger.js";import{clamp as g}from"../../core/mathUtils.js";import{destroyMaybe as d}from"../../core/maybe.js";import{isAbortError as m,waitTick as p}from"../../core/promiseUtils.js";import{watch as y,initial as f,syncAndInitial as v,when as _}from"../../core/reactiveUtils.js";import{property as w}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import{subclass as b}from"../../core/accessorSupport/decorators/subclass.js";import{geographicToWebMercator as P}from"../../geometry/support/webMercatorUtils.js";import C from"../../layers/GraphicsLayer.js";import{searchImages as F}from"../../layers/orientedImagery/queries.js";import{calculateSuitabilities as I}from"../../layers/orientedImagery/core/bestImageUtils.js";import{createCoveragePolygon as S,computePolygonForInspection as V,resizePolygon as O,checkIfPolygonContainsSelectedPoint as A}from"../../layers/orientedImagery/core/coverageUtils.js";import{updateElevation as B,transformPoints as j}from"../../layers/orientedImagery/transformations/groundToImageUtils.js";import{transformPoints as G}from"../../layers/orientedImagery/transformations/imageToGroundUtils.js";import{getInitialAngle as M,convertPixelToHeadingPitch as R,convertHeadingPitchToSphereVertex as x}from"../../layers/orientedImagery/transformations/utils.js";import L from"../../rest/support/AttachmentQuery.js";import{ViewEventPriorities as k}from"../../views/input/InputManager.js";import D from"../PanoramicViewer.js";import{sectorsInOrder as E,sectorsRadii as H}from"./constants.js";import{activePolygonSymbol as U,crossSymbol as N,crossSymbol3D as T,diamondSymbol as z,diamondSymbol3D as W,polygonSymbol as J,activeSourcePointSymbol as q,sourcePointSymbol as $}from"./symbols.js";import{isNoAttachmentError as Q,isTifOrMrf as Z,isSceneView as K,isGraphic as X,calculateSegment as Y,calculateDirection as ee}from"./utils.js";import te from"./components/ImageViewer.js";import re from"../../geometry/Point.js";import ie from"../../geometry/Polygon.js";import oe from"../../geometry/SpatialReference.js";const se={click:"view-click",imageClick:"image-click",interactionHandles:"interaction-handles",footprintHandles:"footprint-handles"},ae=new Set(["JPG","JPEG"]),ne=e=>"FA"===e;let le=class extends n.EventedAccessor{constructor(e){super(e),this.additionalFeatures=new o,this.determineWorkflowForFeature=async()=>{const{currentBestFeature:e,selectedPoint:t}=this;if(e&&t){this._initialCurrentCoverageUpdate=!0,this._updatePointsAndPolygons(),this._fetchFeaturesController??=new AbortController;const{signal:e}=this._fetchFeaturesController;try{await this._loadImage({signal:e})}catch(r){m(r)||(this.loadImageError(r),u.getLogger(this).error("#loadIImage()","error occured while loading image",r))}this._fetchFeaturesController=null}},this.drawFootprint=()=>{this._initialCurrentCoveragePolygon&&this.updateCurrentCoveragePolygon(this._initialCurrentCoveragePolygon)},this.layer=null,this.shouldShowSelectedImage=!1,this.coverageFrustums=new o,this.coveragePolygons=new o,this.currentCoverageVisible=!0,this.disabled=!1,this.displayMessage={key:"onLoadMessage",type:"info"},this.pointSources=new o,this.previousFeatureAngle=0,this.currentBestFeature=null,this.bestFeatureAngle=0,this.selectedPoint=null,this.features=new o,this.isAdditionalCoverageVisible=!1,this.isAdditionalPointSourcesVisible=!1,this.localPort=null,this.mapImageConversionToolState=!1,this.navigatorCurrentBestFeature=null,this.updateFootprint=async e=>{if("image-loaded"!==this.state)return;const t=new AbortController,{signal:r}=t;if(this._updateCoverageController=t,"default"===this.mode)try{const t=await G(e,{feature:this.currentBestFeature,imageProperties:this._imageViewer.viewModel.image.serviceRasterInfo,options:{signal:r},footprintExtent:this._footprintExtent});await this._updateCurrentFootprint(t,r)}catch(i){m(i)||u.getLogger(this).error("#updateFootprint()",i)}},this._additionalCoveragePolygons=new o,this._additionalFeatureGraphics=new o,this._currentCoveragePolygon=null,this._fetchFeaturesController=null,this._imageViewer=new te,this._initialCurrentCoveragePolygon=null,this._initialCurrentCoverageUpdate=!0,this._loading=!1,this._overlays=new C({listMode:"hide",internal:!0}),this._panoramicViewer=new D,this._referencePointOnGround=null,this._referencePointOnImage=null,this._sectorData=null,this._crossSymbol=null,this._footprintExtent=null,this._suitabilities=null,this._transformController=new AbortController,this._updateCoverageController=null,this.loadImageFromSource=async(e,t)=>{const{mode:r,imageRotation:i,options:o}=t,s="string"==typeof e,a=s?e.split(".").pop():e.datasetFormat,n=s?e:e.url,l=ae.has(a.toUpperCase());switch(r){case"default":this._imageViewer.imageSource=e,this._imageViewer.imageRotation=i??0,await this._imageViewer.loadImage(o);break;case"panoramic":if(l){const{pitch:e,yaw:r,cameraLocation:i}=t;this._panoramicViewer.imageSource=n;const s=await M(i,this.selectedPoint)-(r??0);this._panoramicViewer.pitch=e??0,this._panoramicViewer.yaw=s,await this._panoramicViewer.loadImage(o)}else this.setMessage("unsupportedPanoramicImageryError","error",void 0,{datasetFormat:a})}},this.loadImageViewer=e=>{this._imageViewer.container=e},this.loadPanoramicViewer=e=>{this._panoramicViewer.container=e},this._getImageSourceFromAttachment=async(e,t,r)=>{const i=new L({objectIds:[t]}),o=await e.queryAttachments(i,r),s=o[`${t}`]?.[0],n=s?.url;if(!n)throw new a("NoAttachmentError","no attachments found",{[e.objectIdField]:t,layer:e});return{datasetFormat:s.contentType.split("/")[1].toUpperCase(),url:n}},this._loadImage=async e=>{const{currentBestFeature:t,layer:r,mode:i}=this;if(this.clearGraphics(),!r||!t||"none"===i)return;const{attributes:o}=t,{imagePath:s,imageRotation:a,cameraHeading:n,cameraRoll:l,cameraPitch:c,objectId:h,cameraOrientation:g,location:d}=o,p=(l??0)+(a??0),y=d.spatialReference.isWGS84&&4!==g?.type?P(d):new re(d);let f=s;if(ne(s))try{f=await this._getImageSourceFromAttachment(r,h,e)}catch(v){if(m(v))return;return Q(v)?(u.getLogger(this).error(v),void this.setMessage("noAttachment","error",`${r.objectIdField}: ${h}`)):(u.getLogger(this).error(v,{[r.objectIdField]:h,layer:r}),void this.setMessage("imageLoadError","error",`query-attachments-failed:${r.objectIdField} ${h}`))}try{await this.loadImageFromSource(f,{imageRotation:p,options:e,pitch:c,yaw:n,mode:i,cameraLocation:y}),this.transformAndPlotSelectedLocation(e)}catch(v){m(v)||this.loadImageError(v)}},this._mapImageConversionToolViewClickHandler=e=>{e.stopPropagation(),e.preventDefault(),e.mapPoint&&this.plotMapPoint(e.mapPoint)},this._updateCurrentFootprint=async(e,i)=>{await p(i);const o=e.filter(r);if(o.length){const e=[o.map((({x:e,y:t})=>[e,t,1]))];e[0].push(e[0][0]);const r=new ie({hasZ:!0,rings:e,spatialReference:o[0].spatialReference});this.updateCurrentCoveragePolygon(new t({attributes:{imageID:this.currentBestFeature?.attributes.objectId},geometry:r,symbol:U,visible:this.currentCoverageVisible}))}},this._viewClickHandler=e=>{"mouse"===e.pointerType&&0!==e.button||(e.stopPropagation(),e.preventDefault(),e.mapPoint&&this.loadBestImage(e.mapPoint))},this.plotSelectedPointOnImage=async(e,r)=>{if(await p(r),!e)return;const i=new re({...l(e)?e.toJSON():e,spatialReference:oe.WebMercator});if("default"===this.mode)i.x-=.5,i.y=.5-i.y,this._crossSymbol=new t({geometry:i,symbol:N}),this._imageViewer.addGraphic(this._crossSymbol,0);else if("panoramic"===this.mode){const{imageSize:r}=this._panoramicViewer;if(!r)return;const[i,o]=r,{heading:s,pitch:a}=R(e,i,o),n=x(s,a);this._crossSymbol=new t({geometry:new re(n,oe.WebMercator),symbol:T}),this._panoramicViewer.addGraphic(this._crossSymbol,0)}},this.updateFootprintPanorama=async()=>{const{yaw:e,pitch:r,fov:i,imageSize:o,imageRenderer:{size:s}}=this._panoramicViewer,a=this.currentBestFeature?.clone();if(!o||!a)return;const n=i/(s[0]/s[1]),{attributes:l}=a;l.orientedImageryType=null,l.cameraHeading=(e+l.cameraHeading)%360,l.cameraPitch=r,l.horizontalFieldOfView=i,l.verticalFieldOfView=n,l.cameraRoll=0;const{polygon:c}=S(a);this.updateCurrentCoveragePolygon(new t({attributes:{imageID:l.objectId},geometry:c,symbol:U,visible:this.currentCoverageVisible}))},this.handleSectorClick=this.handleSectorClick.bind(this),this.searchBestImage=this.searchBestImage.bind(this),this.transformAndPlotReferencePointOnImage=this.transformAndPlotReferencePointOnImage.bind(this),this.updateSuitabilities=this.updateSuitabilities.bind(this),this.determineWorkflowForFeature=this.determineWorkflowForFeature.bind(this),this.updateCoverage=this.updateCoverage.bind(this),this.selectBestFeature=this.selectBestFeature.bind(this),this.drawFootprint=this.drawFootprint.bind(this)}initialize(){this.addHandles([y((()=>this.view?.map),((e,t)=>{t?.layers.remove(this._overlays),e?.layers.add(this._overlays)}),f),y((()=>this.view?.map?.allLayers?.length),(e=>{e&&this.view?.map?.layers.reorder(this._overlays,e-1)}),f),y((()=>[this.state,this.mapImageConversionToolState,this.view]),(()=>{if(this.removeHandles(se.click),"disabled"===this.state||null==this.view)return;const e=this.mapImageConversionToolState&&"image-loaded"===this.state?this._mapImageConversionToolViewClickHandler:this._viewClickHandler;this.addHandles(this.view.on("click",e,k.WIDGET),se.click),this.removeHandles(se.imageClick);const{mapImageConversionToolState:t,mode:r}=this;if(t&&"none"!==r)switch(r){case"default":this._imageViewer.clickAction="pixel-location",this.addHandles(this._imageViewer.on("pixel-location",(async e=>{this.plotReferencePointOnImage(e);const t=this.currentBestFeature;if(t){const r=(await G([e.toJSON()],{feature:t,imageProperties:{width:this._imageViewer.imageSize[0],height:this._imageViewer.imageSize[1]},options:{signal:this._transformController?.signal},footprintExtent:this._footprintExtent}))[0];r&&this.plotReferencePointOnGround(r)}})),se.imageClick);break;case"panoramic":this._panoramicViewer.clickAction="pixel-location",this.addHandles(this._panoramicViewer.on("pixel-location",(async e=>{this.plotReferencePointOnImage(e);const t=this.currentBestFeature,{imageSize:r}=this._panoramicViewer;if(t&&e&&r){const i=(await G([e],{feature:t,imageProperties:{width:r[0],height:r[1]},options:{signal:this._transformController?.signal},footprintExtent:this._footprintExtent}))[0];i&&this.plotReferencePointOnGround(i)}})),se.imageClick)}}),v),y((()=>this.bestFeatureAngle),((e,t)=>{this.previousFeatureAngle=t??0}),v),y((()=>this.currentBestFeature),((e,t)=>{this.determineWorkflowForFeature(e,t)}),{sync:!0}),y((()=>this.mode),(e=>{switch(this.removeHandles(se.interactionHandles),e){case"default":this.addHandles(y((()=>this._imageViewer.imagePointsInView),(e=>{e&&this.updateCoverage()}),{...v,equals:(e,t)=>i(e,t,h)}),se.interactionHandles);break;case"panoramic":this.addHandles(_((()=>this._panoramicViewer.imageSize),(()=>{this._createFootprintHandles()})),se.interactionHandles)}}),v),y((()=>[this.brightness,this.contrast,this.sharpness]),(()=>{const{_imageViewer:e,brightness:t,contrast:r,mode:i,sharpness:o}=this;"default"===i&&(e.brightness=t,e.contrast=r,e.sharpness=o)}),v)])}destroy(){this._cancelCurrentCoverageUpdate(),this._cancelFetchingFeatures(),this.coverageFrustums.destroy(),this.coveragePolygons.destroy(),this.pointSources.destroy(),this._additionalCoveragePolygons.destroy(),this._additionalFeatureGraphics.destroy(),this._initialCurrentCoveragePolygon=d(this._initialCurrentCoveragePolygon),this._currentCoveragePolygon=d(this._currentCoveragePolygon),this._crossSymbol=d(this._crossSymbol),this._referencePointOnGround=d(this._referencePointOnGround),this._referencePointOnImage=d(this._referencePointOnImage),this._overlays&&this.view?.map.remove(this._overlays),this._overlays.destroy()}get activeLayer(){return s(u.getLogger(this),"activeLayer",{replacement:"layer"}),this.layer}set activeLayer(e){s(u.getLogger(this),"activeLayer",{replacement:"layer"}),this.layer=e}get mode(){const e=this.currentBestFeature?.attributes;if(!e)return"none";const{horizontalFieldOfView:t,isSpherical:r}=e;return 360===t||r?"panoramic":"default"}get imagePointsInView(){const{mode:e,_imageViewer:t}=this;return"default"===e?t.imagePointsInView:null}get brightness(){return this._get("brightness")??0}set brightness(e){this._set("brightness",e>10?10:e<-10?-10:e)}get contrast(){return this._get("contrast")??0}set contrast(e){this._set("contrast",g(e,-10,10))}get featureCount(){return this.features?.length??0}get imageGalleryEnabled(){return Z(this.currentBestFeature?.attributes.imagePath.trim())}get imageLoaded(){return s(u.getLogger(this),"imageLoaded",{replacement:'Use OrientedImageryViewer.state === "image-loaded"',version:"4.29",warnOnce:!0}),"image-loaded"===this.state}get referencePoint(){return this._referencePointOnGround?.geometry}get sharpness(){return this._get("sharpness")??0}set sharpness(e){this._set("sharpness",g(e,0,1))}get sectorData(){const{_sectorData:e}=this;return e?E.map((t=>e[t])):null}get state(){const{mode:e,disabled:t}=this;if(t)return"disabled";if(this._loading)return"image-loading";switch(e){case"default":return this._imageViewer.state;case"panoramic":return this._panoramicViewer.state}return"ready"}get thumbnails(){const{features:e}=this;return e?new o(e.map((({attributes:{imagePath:e,objectId:t,cameraRoll:r,imageRotation:i}})=>{const o=e.trim();return Z(o)?{url:o,objectId:t,rotation:(r??0)+(i??0)}:null})).filter(r)):null}set view(e){this._set("view",e)}filterByFootprints(e,t){const r=[],i=[],o=[];return e.forEach((e=>{const{layer:{coveragePercent:s},attributes:a}=e;let n;const{polygon:c,frustum:h}=S(e);if(n=c,a.isInspection&&(n=V(a)),s&&(n=O(n,s)),A(n,t)){o.push(e);const t=n.toJSON(),s=h?.toJSON(),{cameraHeight:c,cameraHeading:u,location:g,objectId:d}=a,m=l(g)?g.toJSON():g;t.imageID=m.imageID=d,s&&(s.imageID=d),m.z=c,this.pointSources?.push(m),r.push(u>0?t:void 0),i.push(u>0?s:void 0)}})),{features:o,polygons:r,frustums:i}}getCurrentCoveragePolygon(){return this._currentCoveragePolygon}getCurrentBestFeaturePolygon(){return this._initialCurrentCoveragePolygon}handleSectorClick(e){if(isNaN(e))return;const t=this._sectorData?.[E[e]];t?.length&&this._updateCurrentBestFeature(t.at(0))}handleFeatureClick(e){const{sector:t,featureIndexInSector:r}=e;if(isNaN(r))return;const i=this._sectorData?.[t];i?.length&&this._updateCurrentBestFeature(i.at(r))}async loadBestImage(e){this._loading=!0,this.displayMessage=null,this.selectedPoint=e.spatialReference.isGeographic?P(e):e.clone(),this.features.removeAll(),this.currentBestFeature=null,this.additionalFeatures.removeAll(),this._additionalCoveragePolygons.removeAll(),this._additionalFeatureGraphics.removeAll(),this._currentCoveragePolygon=d(this._currentCoveragePolygon),this._overlays?.removeAll(),await this._fetchFeaturesWithController(e)}loadImageError(e){u.getLogger(this).error("oriented-imagery-viewer:load-image",e),this.setMessage("imageLoadError","error",e.message)}async plotMapPoint(e){return this.plotReferencePoint(e),this.transformAndPlotReferencePointOnImage({feature:this.currentBestFeature,selectedLocation:e,options:{signal:this._transformController?.signal}})}plotReferencePointOnGround(e){this._referencePointOnGround&&(this._overlays?.remove(this._referencePointOnGround),this._referencePointOnGround.destroy()),null!=e&&(this._referencePointOnGround=new t({geometry:{type:"point",...e.toJSON()},symbol:z}),this.view?this._overlays?.add(this._referencePointOnGround):this.emit("plot-ground-point",{data:{point:this._referencePointOnGround?.geometry}}))}plotReferencePointOnImage(e){if("image-loaded"===this.state)switch(this._referencePointOnImage&&(this._imageViewer.removeGraphic(this._referencePointOnImage),this._panoramicViewer.removeGraphic(this._referencePointOnImage),this._referencePointOnImage.destroy()),this.mode){case"default":{const r=l(e)?e.toJSON():e;r.x-=.5,r.y=.5-r.y,this._referencePointOnImage=new t({geometry:{type:"point",spatialReference:this._imageViewer.imageRenderer.spatialReference,...r},symbol:z}),this._imageViewer.addGraphic(this._referencePointOnImage,0);break}case"panoramic":{const{imageSize:r}=this._panoramicViewer;if(!r)return;const[i,o]=r,{heading:s,pitch:a}=R(e,i,o),n=x(s,a);this._referencePointOnImage=new t({geometry:new re(n,oe.WebMercator),symbol:W}),this._panoramicViewer.addGraphic(this._referencePointOnImage,0);break}}}resetImage(){switch(this.setMessage("onLoadMessage","info"),this.mode){case"default":this._imageViewer.clearImage(),this._imageViewer.clearGraphics();break;case"panoramic":this._panoramicViewer.clearGraphics()}this._cancelCurrentCoverageUpdate(),this._cancelFetchingFeatures()}async searchBestImage(e,t){try{const r=await F(e,t);r&&await this._processFeatureResponse(r,{signal:t?.signal})}catch(r){m(r)||(this.setMessage("imageLoadError","error",r.message),u.getLogger(this).error("error occurred while finding best image",r))}}selectBestFeature(e){this.currentBestFeature=this.features?.find((({attributes:t})=>t.objectId===Number(e)))}setAdditionalCameraLocationsVisibility(e){this._additionalFeatureGraphics.forEach((t=>{t.visible=e}))}setAdditionalCoverageVisibility(e){this._additionalCoveragePolygons.forEach((t=>{t.visible=e}))}setCurrentCoverageVisibility(e){this._currentCoveragePolygon&&(this._currentCoveragePolygon.visible=e),this._currentBestFeatureGraphic&&(this._currentBestFeatureGraphic.visible=e)}setMapImageConversionToolState(e){this.mapImageConversionToolState=e}async transformAndPlotReferencePointOnImage(e){const{selectedLocation:t,options:r}=e,i=this._initialCurrentCoveragePolygon?.geometry;if(!i?.contains(t))return;const o=await this.transformPoint(t,r);return o?(this.plotReferencePointOnImage(o),{x:o.x,y:o.y}):void 0}updateSuitabilities(e){this._suitabilities=e.sort(((e,t)=>e.suitability-t.suitability));const t=this._suitabilities.map((e=>e.feature));this._updateFeatures(t),this._groupFeaturesBySectors(),this._initialCurrentCoverageUpdate=!0}_cancelFetchingFeatures(e){const t=this._fetchFeaturesController;t&&t.abort(e),this._fetchFeaturesController=null}_cancelCurrentCoverageUpdate(){const e=this._updateCoverageController;e&&e.abort("Multiple Coverage Updates: Aborting Current Coverage Update to sync image and coverage"),this._updateCoverageController=null}_createFootprintHandles(){this.removeHandles(se.footprintHandles),this.addHandles(y((()=>[this._panoramicViewer.fov,this._panoramicViewer.yaw,this._panoramicViewer.pitch]),(()=>{this.updateFootprintPanorama()}),v),se.footprintHandles)}async _fetchFeatures(e,t){if(!this.view)return;const r=this.layer;if(r){const i={include:r},o=this.view.toScreen(e);if(!o)return;const s=await this.view.hitTest(o,i);this._processHitTestResults(r,s,t)}}async _fetchFeaturesWithController(e){this._cancelFetchingFeatures();const t=new AbortController,{signal:r}=t;this._fetchFeaturesController=t;try{await this._fetchFeatures(e,{signal:r}).finally((()=>{this._fetchFeaturesController=null}))}catch(i){this.setMessage("imageLoadError","error"),u.getLogger(this).error("error occurred while fetching features",i)}}_groupFeaturesBySectors(){const{_suitabilities:e,additionalFeatures:t,currentBestFeature:r,features:i}=this;if(!(e&&t&&r&&i))return void(this._sectorData=null);this._sectorData={};for(const l of E)this._sectorData[l]=new o;const s=e.map(((e,t)=>({...e,featureIndex:t})));s.sort(((e,t)=>e.trueSuitability-t.trueSuitability));const a=s.map((({distance:e})=>e)),n=Math.max(...a);s.forEach((e=>{const{distance:t,angle:r,featureIndex:o}=e,s=t/n*H[2],a=Y(t,n),l=ee(r);if(!this._sectorData)return;const c=H[3]+s*Math.sin(r*Math.PI/180),h=H[3]+s*Math.cos(r*Math.PI/180);let u;const g=i.at(o),d=g===this.currentBestFeature,m=this.currentBestFeature?.attributes.cameraPitch&&this.currentBestFeature?.attributes.cameraPitch<5;if(d&&m)u=-90;else{const e=c-H[3],t=h-H[3],r=t/Math.sqrt(e**2+t**2);let i=180*Math.acos(r)/Math.PI;(e<0&&t<0||e<0&&t>0)&&(i*=-1),u=i}const p=""===a?l:`${a}_${l}`;d&&(u===this.bestFeatureAngle?this.previousFeatureAngle=u:this.bestFeatureAngle=u,this.navigatorCurrentBestFeature=m?null:{x:c,y:h,direction:l});const y=this._sectorData[p];y.add({angle:r,featureIndex:o,x:c,y:h,objectID:g.attributes.objectId,sector:p,featureIndexInSector:y.length})}))}async _processFeatureResponse(e,t){const{selectedPoint:i}=this;if(!i)return;if(!e)return;const o=e;if(!o)return;const{features:s}=o;if(!s.length)return this.setMessage("noImageError","error"),void(this.currentBestFeature=null);this.coveragePolygons.removeAll(),this.coverageFrustums.removeAll(),this.pointSources.removeAll();const{features:a,polygons:n,frustums:l}=this.filterByFootprints(s,i),c=a;this.coveragePolygons.addMany(n),this.coverageFrustums.addMany(l);const h=n.filter(r).reduce(((e,t)=>(e.push(...t.rings.flat()),e)),new Array),u=new ie({rings:h,spatialReference:n[0]?.spatialReference}).extent;if(!c.length)return void this.setMessage("noImageError","error");if(this._footprintExtent=u,c[0].attributes.elevationSource&&!i.z&&u){const e=await B([i],{feature:c[0],footprintExtent:u,options:t});if(e[0]){const t=e[0];i.elevation=t.z}c[0].elevationSample&&c.forEach((e=>{e.elevationSample=c[0].elevationSample}))}this._suitabilities=I({features:c,selectedPoint:i,camera:K(this.view)?this.view.camera:null,currentImage:this.currentBestFeature}),this.updateSuitabilities(this._suitabilities);const g=this._suitabilities.map((e=>e.feature));this.currentBestFeature=g[0],this._loading=!1}async _processHitTestResults(e,t,r){const{screenPoint:i,results:[o]}=t,s="graphic"===o?.type&&this.shouldShowSelectedImage,a={layerInstanceOrURL:e,point:o?.mapPoint??this.view?.toMap(i),queryParams:{maximumDistance:e.maximumDistance,objectIds:s?[o.graphic.getAttribute(e.objectIdField)]:void 0},queryFeatures:null};await this.searchBestImage(a,r)}_updateFeatures(e){if(!e.length)return this.currentBestFeature=null,void this.additionalFeatures.removeAll();this.features.removeAll(),this.features.addMany(e),this.currentBestFeature=e[0],e.length>1?this.additionalFeatures.addMany(e.slice(1)):this.additionalFeatures.removeAll()}_updatePointsAndPolygons(){const{coveragePolygons:e,pointSources:r,currentBestFeature:i,currentCoverageVisible:o,isAdditionalCoverageVisible:s,isAdditionalPointSourcesVisible:a}=this;if(e&&r&&i){this._additionalCoveragePolygons.removeAll(),this._additionalFeatureGraphics.removeAll(),this._currentCoveragePolygon&&(this._currentCoveragePolygon.destroy(),this._currentCoveragePolygon=null,this._initialCurrentCoveragePolygon=null);for(const r of e)r?.imageID===i.attributes.objectId?this._initialCurrentCoveragePolygon=new t({attributes:{imageID:r?.imageID},geometry:{type:"polygon",...r},symbol:U,visible:!1}):this._additionalCoveragePolygons.push(new t({attributes:{imageID:r?.imageID},geometry:{type:"polygon",...r},symbol:J,visible:s}));for(const e of r)e.imageID===i.attributes.objectId?this._currentBestFeatureGraphic=new t({attributes:{imageID:e.imageID},geometry:{type:"point",...e},symbol:q,visible:o}):this._additionalFeatureGraphics?.push(new t({attributes:{imageID:e.imageID},geometry:{type:"point",...e},symbol:$,visible:a}))}}_updateCurrentBestFeature(e){if(!e)return;this.currentBestFeature=this.features?.at(e.featureIndex);const t=this.currentBestFeature?.attributes.cameraPitch&&this.currentBestFeature?.attributes.cameraPitch<5;let r;if(t)r=-90;else{const t=e.x-H[3],i=e.y-H[3],o=i/Math.sqrt(t**2+i**2);let s=180*Math.acos(o)/Math.PI;(t<0&&i<0||t<0&&i>0)&&(s*=-1),r=s}r===this.bestFeatureAngle?this.previousFeatureAngle=r:this.bestFeatureAngle=r,this.navigatorCurrentBestFeature=t?null:{x:e.x,y:e.y,direction:e.sector.includes("_")?e.sector.split("_")[1]:e.sector}}clearGraphics(){this._imageViewer.clearGraphics(),this._panoramicViewer.clearGraphics()}plotReferencePoint(e){"mapPoint"in e?this.plotReferencePointOnGround(e.mapPoint):this.plotReferencePointOnGround(e)}setMessage(e,t,r,i){this._loading=!1,this.displayMessage={key:e,type:t,data:r,map:i}}async transformAndPlotSelectedLocation(e){const{currentBestFeature:t,selectedPoint:r,state:i}=this;if(this._crossSymbol&&(this._panoramicViewer.removeGraphic(this._crossSymbol),this._imageViewer.removeGraphic(this._crossSymbol),this._crossSymbol=d(this._crossSymbol)),!r||!t||"image-loaded"!==i)return;let o;try{o=await this.transformPoint(r,e),await this.plotSelectedPointOnImage(o,e)}catch(s){m(s)||u.getLogger(this).error("failed to transform map point to pixel, cross symbol will not be plotted on image",{error:s,selectedPoint:r,feature:t})}}async transformPoint(e,t){if("none"===this.mode)return;const r=this.currentBestFeature,i=await j([e],{feature:r,imageProperties:"default"===this.mode?this._imageViewer.viewModel.image.serviceRasterInfo:{width:this._panoramicViewer.imageSize?.[0],height:this._panoramicViewer.imageSize?.[1]},options:t});if(!i.length)return;return i[0]}updateCurrentCoveragePolygon(e){if(this._initialCurrentCoverageUpdate){if(this._overlays?.removeAll(),this._initialCurrentCoverageUpdate=!1,e&&(this._currentCoveragePolygon&&this._currentCoveragePolygon.destroy(),e.visible=this.currentCoverageVisible,this._currentCoveragePolygon=e),this.view){const e=this.selectedPoint?new t({geometry:this.selectedPoint.clone(),symbol:N,attributes:{imageID:this.currentBestFeature?.attributes.objectId}}):null;this._overlays?.graphics.addMany([...this._additionalCoveragePolygons,...this._additionalFeatureGraphics,this._currentCoveragePolygon,this._currentBestFeatureGraphic,e].filter(X))}}else if(this.view){const t=this._currentCoveragePolygon&&this._overlays?this._overlays.graphics.indexOf(this._currentCoveragePolygon):-1;e&&(this._currentCoveragePolygon&&(this._overlays?.remove(this._currentCoveragePolygon),this._currentCoveragePolygon.destroy()),e.visible=this.currentCoverageVisible,this._currentCoveragePolygon=e,this._overlays?.graphics.add(this._currentCoveragePolygon,t>=0?t:void 0))}}async updateCoverage(){if("default"===this.mode){this._cancelCurrentCoverageUpdate();const{imagePointsInView:e,state:t}=this._imageViewer,r=c(e);if(!r||"image-loaded"!==t)return;this.updateFootprint(r)}}};e([w()],le.prototype,"activeLayer",null),e([w()],le.prototype,"additionalFeatures",void 0),e([w({json:{write:!1}})],le.prototype,"determineWorkflowForFeature",void 0),e([w()],le.prototype,"drawFootprint",void 0),e([w({readOnly:!0,value:"none"})],le.prototype,"mode",null),e([w()],le.prototype,"imagePointsInView",null),e([w()],le.prototype,"layer",void 0),e([w()],le.prototype,"shouldShowSelectedImage",void 0),e([w({type:Number})],le.prototype,"brightness",null),e([w({type:Number})],le.prototype,"contrast",null),e([w()],le.prototype,"coverageFrustums",void 0),e([w()],le.prototype,"coveragePolygons",void 0),e([w()],le.prototype,"currentCoverageVisible",void 0),e([w()],le.prototype,"disabled",void 0),e([w()],le.prototype,"displayMessage",void 0),e([w()],le.prototype,"pointSources",void 0),e([w()],le.prototype,"previousFeatureAngle",void 0),e([w()],le.prototype,"currentBestFeature",void 0),e([w()],le.prototype,"bestFeatureAngle",void 0),e([w()],le.prototype,"selectedPoint",void 0),e([w({readOnly:!0})],le.prototype,"featureCount",null),e([w()],le.prototype,"features",void 0),e([w({readOnly:!0})],le.prototype,"imageGalleryEnabled",null),e([w({readOnly:!0})],le.prototype,"imageLoaded",null),e([w()],le.prototype,"isAdditionalCoverageVisible",void 0),e([w()],le.prototype,"isAdditionalPointSourcesVisible",void 0),e([w({type:Number})],le.prototype,"localPort",void 0),e([w()],le.prototype,"mapImageConversionToolState",void 0),e([w()],le.prototype,"navigatorCurrentBestFeature",void 0),e([w()],le.prototype,"referencePoint",null),e([w({type:Number})],le.prototype,"sharpness",null),e([w({readOnly:!0})],le.prototype,"sectorData",null),e([w({readOnly:!0})],le.prototype,"state",null),e([w({readOnly:!0})],le.prototype,"thumbnails",null),e([w()],le.prototype,"updateFootprint",void 0),e([w({value:null})],le.prototype,"view",null),e([w()],le.prototype,"_additionalCoveragePolygons",void 0),e([w()],le.prototype,"_additionalFeatureGraphics",void 0),e([w()],le.prototype,"_currentCoveragePolygon",void 0),e([w()],le.prototype,"_fetchFeaturesController",void 0),e([w()],le.prototype,"_imageViewer",void 0),e([w()],le.prototype,"_initialCurrentCoveragePolygon",void 0),e([w()],le.prototype,"_initialCurrentCoverageUpdate",void 0),e([w()],le.prototype,"_loading",void 0),e([w()],le.prototype,"_overlays",void 0),e([w()],le.prototype,"_panoramicViewer",void 0),e([w()],le.prototype,"_referencePointOnGround",void 0),e([w()],le.prototype,"_referencePointOnImage",void 0),e([w()],le.prototype,"_currentBestFeatureGraphic",void 0),e([w()],le.prototype,"_sectorData",void 0),le=e([b("esri.widgets.OrientedImageryViewer.OrientedImageryViewerViewModel")],le);const ce=le;export{ce as default};