@arcgis/core 4.31.4 → 4.31.6

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.
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.31/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../chunks/tslib.es6.js";import{ClonableMixin as r}from"../core/Clonable.js";import t from"../core/Collection.js";import s from"../core/Error.js";import{loadAll as i}from"../core/loadAll.js";import{MultiOriginJSONMixin as o}from"../core/MultiOriginJSONSupport.js";import{debounce as a,throwIfAbortError as n,whenOrAbort as u}from"../core/promiseUtils.js";import{watch as l,sync as p}from"../core/reactiveUtils.js";import{sqlAnd as y}from"../core/sql.js";import{urlToObject as d,join as c}from"../core/urlUtils.js";import{property as m}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import"../core/RandomLCG.js";import{reader as h}from"../core/accessorSupport/decorators/reader.js";import{subclass as f}from"../core/accessorSupport/decorators/subclass.js";import b from"./Layer.js";import{APIKeyMixin as g}from"./mixins/APIKeyMixin.js";import{ArcGISService as S}from"./mixins/ArcGISService.js";import{BlendLayer as j}from"./mixins/BlendLayer.js";import{CustomParametersMixin as w}from"./mixins/CustomParametersMixin.js";import{EditBusLayer as v}from"./mixins/EditBusLayer.js";import{FeatureLayerBase as L}from"./mixins/FeatureLayerBase.js";import{OperationalLayer as F}from"./mixins/OperationalLayer.js";import{PortalLayer as x}from"./mixins/PortalLayer.js";import{RefreshableLayer as _}from"./mixins/RefreshableLayer.js";import{ScaleRangeLayer as I}from"./mixins/ScaleRangeLayer.js";import{TemporalLayer as C}from"./mixins/TemporalLayer.js";import{titleFromUrlAndName as E}from"./support/arcgisLayerUrl.js";import{id as P}from"./support/commonProperties.js";import{ensureLayerCredential as O,computeEffectiveEditingEnabled as A,addAttachment as T,updateAttachment as U,applyEdits as G,createQuery as q,deleteAttachments as $,fetchRecomputedExtents as R,computeDomainFromSubtypes as V,getFeatureSubtype as k,queryAttachments as M,queryObjectIds as N,queryFeatureCount as D,queryExtent as Q,queryRelatedFeatures as H,queryRelatedFeaturesCount as J,hasDataChanged as B}from"./support/featureLayerUtils.js";import{defineFieldProperties as z}from"./support/fieldProperties.js";import{fixTimeInfoFields as K}from"./support/fieldUtils.js";import{getSymbolWithColorSupport as Z,createSimpleRenderersWithUniqueColors as W}from"./support/subtypeGroupLayerUtils.js";import X from"./support/SubtypeSublayer.js";import Y from"./support/TimeInfo.js";import{serviceSupportsSpatialReference as ee}from"./support/versionUtils.js";import re from"../rest/support/Query.js";import{SaveOperationType as te}from"../webdoc/interfaces.js";const se="SubtypeGroupLayer",ie="esri.layers.SubtypeGroupLayer";function oe(e,r){return new s("layer:unsupported",`Layer (${e.title}, ${e.id}) of type '${e.declaredClass}' ${r}`,{layer:e})}const ae=z();let ne=class extends(L(v(j(C(I(_(S(F(x(o(w(g(r(b)))))))))))))){constructor(...e){super(...e),this._sublayerLookup=new Map,this.fields=null,this.fieldsIndex=null,this.outFields=null,this.sublayers=new(t.ofType(X)),this.useUniqueColorsForSublayers=!0,this.supportedSourceTypes=new Set(["Feature Layer"]),this.timeInfo=null,this.title="Layer",this.type="subtype-group",this._debouncedSaveOperations=a((async(e,r,t)=>{const{save:s,saveAs:i}=await import("./save/featureLayerUtils.js");switch(e){case te.SAVE:return s(this,r);case te.SAVE_AS:return i(this,t,r)}})),this.addHandles(l((()=>this.sublayers),((e,r)=>this._handleSublayersChange(e,r)),p))}destroy(){this.source?.destroy()}normalizeCtorArgs(e,r){return"string"==typeof e?{url:e,...r}:e}load(e){const r=null!=e?e.signal:null,t=this.loadFromPortal({supportedTypes:["Feature Service"]},e).catch(n).then((async()=>{if(!this.url)throw new s("subtype-grouplayer:missing-url-or-source","SubtypeGroupLayer must be created with either a url or a portal item");if(null==this.layerId)throw new s("subtype-grouplayer:missing-layerid","layerId is required for a SubtypeGroupLayer created with url");return this._initLayerProperties(await this.createGraphicsSource(r))})).then((()=>O(this,"load",e)));return this.addResolvingPromise(t),Promise.resolve(this)}get createQueryVersion(){return this.commitProperty("definitionExpression"),this.commitProperty("timeExtent"),this.commitProperty("timeOffset"),this.commitProperty("geometryType"),this.commitProperty("gdbVersion"),this.commitProperty("historicMoment"),this.commitProperty("returnZ"),this.commitProperty("capabilities"),this.commitProperty("returnM"),(this._get("createQueryVersion")??0)+1}get editingEnabled(){return this.loaded&&null!=this.capabilities&&this.capabilities.operations.supportsEditing&&this.userHasEditingPrivileges}get effectiveEditingEnabled(){return A(this)}get parsedUrl(){const e=d(this.url);return null!=e&&null!=this.layerId&&(e.path=c(e.path,this.layerId.toString())),e}set source(e){this._get("source")!==e&&this._set("source",e)}readTitleFromService(e,{name:r}){return this.url?E(this.url,r):r}async addAttachment(e,r){return T(this,e,r,se)}async updateAttachment(e,r,t){return U(this,e,r,t,se)}async applyEdits(e,r){return G(this,e,r)}on(e,r){return super.on(e,r)}async createGraphicsSource(e){const{default:r}=await u(import("./graphics/sources/FeatureLayerSource.js"),e);return new r({layer:this,supportedSourceTypes:this.supportedSourceTypes}).load({signal:e})}createQuery(){const e=q(this),r=this.sublayers.map((e=>e.subtypeCode));return e.where=y(`${this.subtypeField} IN (${r.join(",")})`,this.definitionExpression),e}async deleteAttachments(e,r){return $(this,e,r,se)}async fetchRecomputedExtents(e){return R(this,e,se)}findSublayerForFeature(e){const r=this.fieldsIndex.get(this.subtypeField),t=e.attributes[r.name];return this.findSublayerForSubtypeCode(t)}findSublayerForSubtypeCode(e){return this._sublayerLookup.get(e)}getFieldDomain(e,r){if(!r?.excludeImpliedDomains){const r=V(this,e);if(r)return r}const t=k(this,r?.feature);if(t){const r=t.domains?.[e];return"inherited"===r?.type?this._getLayerDomain(e):r}return this._getLayerDomain(e)}getField(e){return this.fieldsIndex.get(e)}loadAll(){return i(this,(e=>{e(this.sublayers)}))}async queryAttachments(e,r){return M(this,e,r,se)}async queryFeatures(e,r){const t=await this.load(),s=re.from(e)??t.createQuery(),i=s.outFields??[];i.includes(this.subtypeField)||(i.push(this.subtypeField),s.outFields=i);const o=await t.source.queryFeatures(s,r);if(o?.features)for(const a of o.features)a.layer=a.sourceLayer=this.findSublayerForFeature(a);return o}async queryObjectIds(e,r){return N(this,e,r,se)}async queryFeatureCount(e,r){return D(this,e,r,se)}async queryExtent(e,r){return Q(this,e,r,se)}async queryRelatedFeatures(e,r){return H(this,e,r,se)}async queryRelatedFeaturesCount(e,r){return J(this,e,r,se)}async save(e){return this._debouncedSaveOperations(te.SAVE,e)}async saveAs(e,r){return this._debouncedSaveOperations(te.SAVE_AS,r,e)}write(e,r){const{origin:t,layerContainerType:i,messages:o}=r;if(this.isTable){if("web-scene"===t||"web-map"===t&&"tables"!==i)return o?.push(oe(this,"using a table source cannot be written to web scenes and web maps")),null}else if(this.loaded&&"web-map"===t&&"tables"===i)return o?.push(oe(this,"using a non-table source cannot be written to tables in web maps")),null;return this.sublayers?.length?super.write(e,r):(o?.push(new s("web-document-write:invalid-property",`Layer (${this.title}, ${this.id}) of type '${this.declaredClass}' has invalid value for 'sublayers' property. 'sublayers' collection should contain at least one sublayer`,{layer:this})),null)}serviceSupportsSpatialReference(e){return!!this.loaded&&ee(this,e)}_getLayerDomain(e){const r=this.fieldsIndex.get(e);return r?r.domain:null}async _initLayerProperties(e){this._set("source",e);const{sourceJSON:r}=e;if(r&&(this.sourceJSON=r,this.read(r,{origin:"service",url:this.parsedUrl})),!this.subtypes?.length)throw new s("subtype-grouplayer:missing-subtypes","SubtypeGroupLayer must be created using a layer with subtypes");this._verifyFields(),K(this.timeInfo,this.fieldsIndex)}async hasDataChanged(){return B(this)}_verifyFields(){const e=this.parsedUrl?.path??"undefined";this.objectIdField||console.log("SubtypeGroupLayer: 'objectIdField' property is not defined (url: "+e+")"),this.isTable||-1!==e.search(/\/FeatureServer\//i)||this.fields?.some((e=>"geometry"===e.type))||console.log("SubtypeGroupLayer: unable to find field of type 'geometry' in the layer 'fields' list. If you are using a map service layer, features will not have geometry (url: "+e+")")}_handleSublayersChange(e,r){r&&(r.forEach((e=>{e.parent=null})),this.removeHandles("sublayers-owner"),this._sublayerLookup.clear()),e&&(e.forEach((e=>{e.parent=this,this._sublayerLookup.set(e.subtypeCode,e)})),this.addHandles([e.on("after-add",(({item:e})=>{e.parent=this,this._sublayerLookup.set(e.subtypeCode,e)})),e.on("after-remove",(({item:e})=>{e.parent=null,this._sublayerLookup.delete(e.subtypeCode)}))],"sublayers-owner"))}};e([m({readOnly:!0})],ne.prototype,"createQueryVersion",null),e([m({readOnly:!0})],ne.prototype,"editingEnabled",null),e([m({readOnly:!0})],ne.prototype,"effectiveEditingEnabled",null),e([m({...ae.fields,readOnly:!0,json:{origins:{service:{read:!0}},read:!1}})],ne.prototype,"fields",void 0),e([m(ae.fieldsIndex)],ne.prototype,"fieldsIndex",void 0),e([m(P)],ne.prototype,"id",void 0),e([m({type:["show","hide","hide-children"],json:{origins:{"portal-item":{read:!1,write:!1}}}})],ne.prototype,"listMode",void 0),e([m({value:"SubtypeGroupLayer",type:["SubtypeGroupLayer"],json:{origins:{"portal-item":{name:"layerType",write:{enabled:!0,ignoreOrigin:!0}}}}})],ne.prototype,"operationalLayerType",void 0),e([m(ae.outFields)],ne.prototype,"outFields",void 0),e([m({readOnly:!0})],ne.prototype,"parsedUrl",null),e([m({clonable:!1})],ne.prototype,"source",null),e([m({type:t.ofType(X),json:{origins:{service:{read:{source:"subtypes",reader(e,r,s){let i=null;if(this.useUniqueColorsForSublayers){const t=Z(r,s);i=t?W(e.length,t):null}const o=e.map((({code:e},t)=>{const o=new X({subtypeCode:e});o.read(r,s);const a=i?.[t];return a&&o.read({drawingInfo:{renderer:a.toJSON()}},s),o}));return new(t.ofType(X))(o)}}}},name:"layers",write:{ignoreOrigin:!0}}})],ne.prototype,"sublayers",void 0),e([m()],ne.prototype,"useUniqueColorsForSublayers",void 0),e([m({type:Y})],ne.prototype,"timeInfo",void 0),e([m({json:{origins:{"portal-item":{write:{enabled:!0,ignoreOrigin:!0,writerEnsuresNonNull:!0}}}}})],ne.prototype,"title",void 0),e([h("service","title",["name"])],ne.prototype,"readTitleFromService",null),e([m({json:{read:!1}})],ne.prototype,"type",void 0),ne=e([f(ie)],ne);const ue=ne;export{ue as default};
5
+ import{_ as e}from"../chunks/tslib.es6.js";import{ClonableMixin as t}from"../core/Clonable.js";import r from"../core/Collection.js";import s from"../core/Error.js";import{loadAll as i}from"../core/loadAll.js";import{MultiOriginJSONMixin as o}from"../core/MultiOriginJSONSupport.js";import{debounce as a,throwIfAbortError as n,whenOrAbort as u}from"../core/promiseUtils.js";import{watch as l,sync as p}from"../core/reactiveUtils.js";import{sqlAnd as y}from"../core/sql.js";import{urlToObject as d,join as c}from"../core/urlUtils.js";import{property as m}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import"../core/RandomLCG.js";import{reader as h}from"../core/accessorSupport/decorators/reader.js";import{subclass as f}from"../core/accessorSupport/decorators/subclass.js";import b from"./Layer.js";import{APIKeyMixin as g}from"./mixins/APIKeyMixin.js";import{ArcGISService as S}from"./mixins/ArcGISService.js";import{BlendLayer as w}from"./mixins/BlendLayer.js";import{CustomParametersMixin as j}from"./mixins/CustomParametersMixin.js";import{EditBusLayer as v}from"./mixins/EditBusLayer.js";import{FeatureLayerBase as L}from"./mixins/FeatureLayerBase.js";import{OperationalLayer as F}from"./mixins/OperationalLayer.js";import{PortalLayer as E}from"./mixins/PortalLayer.js";import{RefreshableLayer as x}from"./mixins/RefreshableLayer.js";import{ScaleRangeLayer as _}from"./mixins/ScaleRangeLayer.js";import{TemporalLayer as I}from"./mixins/TemporalLayer.js";import{titleFromUrlAndName as C}from"./support/arcgisLayerUrl.js";import{id as P}from"./support/commonProperties.js";import{ensureLayerCredential as O,computeEffectiveEditingEnabled as A,addAttachment as T,updateAttachment as U,applyEdits as G,createQuery as q,deleteAttachments as D,fetchRecomputedExtents as $,computeDomainFromSubtypes as R,getFeatureSubtype as V,queryAttachments as k,queryObjectIds as M,queryFeatureCount as N,queryExtent as Q,queryRelatedFeatures as H,queryRelatedFeaturesCount as J,hasDataChanged as B}from"./support/featureLayerUtils.js";import{defineFieldProperties as z}from"./support/fieldProperties.js";import{fixTimeInfoFields as K}from"./support/fieldUtils.js";import{getSymbolWithColorSupport as Z,createSimpleRenderersWithUniqueColors as W}from"./support/subtypeGroupLayerUtils.js";import X from"./support/SubtypeSublayer.js";import Y from"./support/TimeInfo.js";import{serviceSupportsSpatialReference as ee}from"./support/versionUtils.js";import te from"../rest/support/Query.js";import{SaveOperationType as re}from"../webdoc/interfaces.js";const se="SubtypeGroupLayer",ie="esri.layers.SubtypeGroupLayer";function oe(e,t){return new s("layer:unsupported",`Layer (${e.title}, ${e.id}) of type '${e.declaredClass}' ${t}`,{layer:e})}const ae=z();let ne=class extends(L(v(w(I(_(x(S(F(E(o(j(g(t(b)))))))))))))){constructor(...e){super(...e),this._sublayerLookup=new Map,this.fields=null,this.fieldsIndex=null,this.outFields=null,this.sublayers=new(r.ofType(X)),this.useUniqueColorsForSublayers=!0,this.supportedSourceTypes=new Set(["Feature Layer"]),this.timeInfo=null,this.title="Layer",this.type="subtype-group",this._debouncedSaveOperations=a((async(e,t,r)=>{const{save:s,saveAs:i}=await import("./save/featureLayerUtils.js");switch(e){case re.SAVE:return s(this,t);case re.SAVE_AS:return i(this,r,t)}})),this.addHandles(l((()=>this.sublayers),((e,t)=>this._handleSublayersChange(e,t)),p))}destroy(){this.source?.destroy()}normalizeCtorArgs(e,t){return"string"==typeof e?{url:e,...t}:e}load(e){const t=null!=e?e.signal:null,r=this.loadFromPortal({supportedTypes:["Feature Service"]},e).catch(n).then((async()=>{if(!this.url)throw new s("subtype-grouplayer:missing-url-or-source","SubtypeGroupLayer must be created with either a url or a portal item");if(null==this.layerId)throw new s("subtype-grouplayer:missing-layerid","layerId is required for a SubtypeGroupLayer created with url");return this._initLayerProperties(await this.createGraphicsSource(t))})).then((()=>O(this,"load",e)));return this.addResolvingPromise(r),Promise.resolve(this)}get createQueryVersion(){return this.commitProperty("definitionExpression"),this.commitProperty("timeExtent"),this.commitProperty("timeOffset"),this.commitProperty("geometryType"),this.commitProperty("gdbVersion"),this.commitProperty("historicMoment"),this.commitProperty("returnZ"),this.commitProperty("capabilities"),this.commitProperty("returnM"),(this._get("createQueryVersion")??0)+1}get editingEnabled(){return this.loaded&&null!=this.capabilities&&this.capabilities.operations.supportsEditing&&this.userHasEditingPrivileges}get effectiveEditingEnabled(){return A(this)}get parsedUrl(){const e=d(this.url);return null!=e&&null!=this.layerId&&(e.path=c(e.path,this.layerId.toString())),e}set source(e){this._get("source")!==e&&this._set("source",e)}readTitleFromService(e,{name:t}){return this.url?C(this.url,t):t}async addAttachment(e,t){const r=await T(this,e,t,se);return this.lastEditsEventDate=new Date,r}async updateAttachment(e,t,r){const s=await U(this,e,t,r,se);return this.lastEditsEventDate=new Date,s}async applyEdits(e,t){return G(this,e,t)}on(e,t){return super.on(e,t)}async createGraphicsSource(e){const{default:t}=await u(import("./graphics/sources/FeatureLayerSource.js"),e);return new t({layer:this,supportedSourceTypes:this.supportedSourceTypes}).load({signal:e})}createQuery(){const e=q(this),t=this.sublayers.map((e=>e.subtypeCode));return e.where=y(`${this.subtypeField} IN (${t.join(",")})`,this.definitionExpression),e}async deleteAttachments(e,t){const r=await D(this,e,t,se);return this.lastEditsEventDate=new Date,r}async fetchRecomputedExtents(e){return $(this,e,se)}findSublayerForFeature(e){const t=this.fieldsIndex.get(this.subtypeField),r=e.attributes[t.name];return this.findSublayerForSubtypeCode(r)}findSublayerForSubtypeCode(e){return this._sublayerLookup.get(e)}getFieldDomain(e,t){if(!t?.excludeImpliedDomains){const t=R(this,e);if(t)return t}const r=V(this,t?.feature);if(r){const t=r.domains?.[e];return"inherited"===t?.type?this._getLayerDomain(e):t}return this._getLayerDomain(e)}getField(e){return this.fieldsIndex.get(e)}loadAll(){return i(this,(e=>{e(this.sublayers)}))}async queryAttachments(e,t){return k(this,e,t,se)}async queryFeatures(e,t){const r=await this.load(),s=te.from(e)??r.createQuery(),i=s.outFields??[];i.includes(this.subtypeField)||(i.push(this.subtypeField),s.outFields=i);const o=await r.source.queryFeatures(s,t);if(o?.features)for(const a of o.features)a.layer=a.sourceLayer=this.findSublayerForFeature(a);return o}async queryObjectIds(e,t){return M(this,e,t,se)}async queryFeatureCount(e,t){return N(this,e,t,se)}async queryExtent(e,t){return Q(this,e,t,se)}async queryRelatedFeatures(e,t){return H(this,e,t,se)}async queryRelatedFeaturesCount(e,t){return J(this,e,t,se)}async save(e){return this._debouncedSaveOperations(re.SAVE,e)}async saveAs(e,t){return this._debouncedSaveOperations(re.SAVE_AS,t,e)}write(e,t){const{origin:r,layerContainerType:i,messages:o}=t;if(this.isTable){if("web-scene"===r||"web-map"===r&&"tables"!==i)return o?.push(oe(this,"using a table source cannot be written to web scenes and web maps")),null}else if(this.loaded&&"web-map"===r&&"tables"===i)return o?.push(oe(this,"using a non-table source cannot be written to tables in web maps")),null;return this.sublayers?.length?super.write(e,t):(o?.push(new s("web-document-write:invalid-property",`Layer (${this.title}, ${this.id}) of type '${this.declaredClass}' has invalid value for 'sublayers' property. 'sublayers' collection should contain at least one sublayer`,{layer:this})),null)}serviceSupportsSpatialReference(e){return!!this.loaded&&ee(this,e)}_getLayerDomain(e){const t=this.fieldsIndex.get(e);return t?t.domain:null}async _initLayerProperties(e){this._set("source",e);const{sourceJSON:t}=e;if(t&&(this.sourceJSON=t,this.read(t,{origin:"service",url:this.parsedUrl})),!this.subtypes?.length)throw new s("subtype-grouplayer:missing-subtypes","SubtypeGroupLayer must be created using a layer with subtypes");this._verifyFields(),K(this.timeInfo,this.fieldsIndex)}async hasDataChanged(){return B(this)}_verifyFields(){const e=this.parsedUrl?.path??"undefined";this.objectIdField||console.log("SubtypeGroupLayer: 'objectIdField' property is not defined (url: "+e+")"),this.isTable||-1!==e.search(/\/FeatureServer\//i)||this.fields?.some((e=>"geometry"===e.type))||console.log("SubtypeGroupLayer: unable to find field of type 'geometry' in the layer 'fields' list. If you are using a map service layer, features will not have geometry (url: "+e+")")}_handleSublayersChange(e,t){t&&(t.forEach((e=>{e.parent=null})),this.removeHandles("sublayers-owner"),this._sublayerLookup.clear()),e&&(e.forEach((e=>{e.parent=this,this._sublayerLookup.set(e.subtypeCode,e)})),this.addHandles([e.on("after-add",(({item:e})=>{e.parent=this,this._sublayerLookup.set(e.subtypeCode,e)})),e.on("after-remove",(({item:e})=>{e.parent=null,this._sublayerLookup.delete(e.subtypeCode)}))],"sublayers-owner"))}};e([m({readOnly:!0})],ne.prototype,"createQueryVersion",null),e([m({readOnly:!0})],ne.prototype,"editingEnabled",null),e([m({readOnly:!0})],ne.prototype,"effectiveEditingEnabled",null),e([m({...ae.fields,readOnly:!0,json:{origins:{service:{read:!0}},read:!1}})],ne.prototype,"fields",void 0),e([m(ae.fieldsIndex)],ne.prototype,"fieldsIndex",void 0),e([m(P)],ne.prototype,"id",void 0),e([m({type:["show","hide","hide-children"],json:{origins:{"portal-item":{read:!1,write:!1}}}})],ne.prototype,"listMode",void 0),e([m({value:"SubtypeGroupLayer",type:["SubtypeGroupLayer"],json:{origins:{"portal-item":{name:"layerType",write:{enabled:!0,ignoreOrigin:!0}}}}})],ne.prototype,"operationalLayerType",void 0),e([m(ae.outFields)],ne.prototype,"outFields",void 0),e([m({readOnly:!0})],ne.prototype,"parsedUrl",null),e([m({clonable:!1})],ne.prototype,"source",null),e([m({type:r.ofType(X),json:{origins:{service:{read:{source:"subtypes",reader(e,t,s){let i=null;if(this.useUniqueColorsForSublayers){const r=Z(t,s);i=r?W(e.length,r):null}const o=e.map((({code:e},r)=>{const o=new X({subtypeCode:e});o.read(t,s);const a=i?.[r];return a&&o.read({drawingInfo:{renderer:a.toJSON()}},s),o}));return new(r.ofType(X))(o)}}}},name:"layers",write:{ignoreOrigin:!0}}})],ne.prototype,"sublayers",void 0),e([m()],ne.prototype,"useUniqueColorsForSublayers",void 0),e([m({type:Y})],ne.prototype,"timeInfo",void 0),e([m({json:{origins:{"portal-item":{write:{enabled:!0,ignoreOrigin:!0,writerEnsuresNonNull:!0}}}}})],ne.prototype,"title",void 0),e([h("service","title",["name"])],ne.prototype,"readTitleFromService",null),e([m({json:{read:!1}})],ne.prototype,"type",void 0),ne=e([f(ie)],ne);const ue=ne;export{ue as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcgis/core",
3
- "version": "4.31.4",
3
+ "version": "4.31.6",
4
4
  "homepage": "https://js.arcgis.com",
5
5
  "description": "ArcGIS Maps SDK for JavaScript: A complete 2D and 3D mapping and data visualization API",
6
6
  "keywords": [
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.31/esri/copyright.txt for details.
4
4
  */
5
- const d="20241118",f="fbfe150d1e815fa4780069dcc5f49b0d03d44667";export{d as buildDate,f as commitHash};
5
+ const c="20241122",f="f6f7099a0e79cf518abdcf87c5aa8b6f24ecdcd8";export{c as buildDate,f as commitHash};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.31/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Graphic.js";import r from"../../../core/Accessor.js";import{equals as s,isSome as i}from"../../../core/arrayUtils.js";import a from"../../../core/Collection.js";import o from"../../../core/Error.js";import{clone as n}from"../../../core/lang.js";import u from"../../../core/Logger.js";import p from"../../../core/ReactiveMap.js";import{watch as l,when as h}from"../../../core/reactiveUtils.js";import{property as d}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import{subclass as c}from"../../../core/accessorSupport/decorators/subclass.js";import{isSubtypeGroupLayer as y}from"../../../layers/support/layerUtils.js";import m from"../../../rest/support/AttachmentQuery.js";import _ from"../../../rest/support/RelationshipQuery.js";import{isIFeatureTableSupportedLayerWithAttachments as f,isIFeatureTableSupportedLayerWithAttachmentsEditing as g,isIFeatureTableSupportedLayerWithEditing as b,isIFeatureTableSupportedLayerWithRelationships as v,findRelatedLayer as O}from"./tableUtils.js";let A=class extends r{constructor(e){super(e),this._attachmentsOperationQueue=new a,this._defaultOutFields=["*"],this._editOperationQueue=new a,this._loaded=!1,this._loadError=!1,this._loading=!1,this._objectIdCache=new a,this._queryOperationQueue=new a,this.attachmentsEnabled=!1,this.count=0,this.failures=new a,this.filterGeometry=null,this.initialSize=null,this.layer=null,this.objectIds=null,this.outFields=null,this.pageCache=new p,this.pageSize=50,this.relationshipConfig=null,this.relatedRecordsEnabled=!1,this.returnGeometry=!1,this.returnZ=!1,this.returnM=!1,this.sortOrders=[],this.timeExtent=null,this.view=null,this.where=null}initialize(){this.addHandles([l((()=>[this.filterGeometry,this.layer,this.objectIds,this.outFields,this.pageSize,this.relationshipConfig,this.returnGeometry,this.returnM,this.returnZ,this.timeExtent,this.where]),(()=>this._reset())),l((()=>this.orderByFields),(()=>this._clearCaches()),{equals:s}),h((()=>this.attachmentsEnabled),(()=>this._reset())),h((()=>this.relatedRecordsEnabled),(()=>this._reset()))])}destroy(){this.layer=null,this.itemCache?.destroy(),this.failures?.destroy()}get _capabilities(){const{layer:e}=this;return e?.effectiveCapabilities??e?.capabilities}get _effectiveReturnZ(){return this.returnZ&&this.supportsZ}get _effectiveReturnM(){return this.returnM&&this.supportsM}get _layerWithAttachments(){const{layer:e}=this;return e&&this._capabilities&&this.attachmentsEnabled&&this.supportsAttachments&&f(e)?e:null}get _layerWithAttachmentsEditing(){const{_layerWithAttachments:e}=this;return e&&g(e)&&this.supportsEditing?e:null}get _layerWithEditing(){const e=this.layer;return b(e)&&this.supportsEditing?e:null}get _layerWithRelationships(){const e=this.layer;return v(e)&&this.supportsQueryRelated?e:null}get _relatedLayer(){return this.relationshipConfig?.relatedLayer}get _relatedLayerCapabilities(){const{_relatedLayer:e}=this;return e?.effectiveCapabilities??e?.capabilities}get _relatedLayerSupportsCacheHint(){return!!this._relatedLayerCapabilities?.queryRelated?.supportsCacheHint}get _relatedLayerSupportsQuery(){return!!this._relatedLayerCapabilities?.operations.supportsQuery}get _relatedLayerSupportsQueryRelated(){const{_relatedLayerCapabilities:e}=this;return!!e?.queryRelated?.supportsCount&&!!e?.queryRelated?.supportsPagination}get _sortedFieldNames(){return this.sortOrders.map((({fieldName:e})=>e))}get _canUseRelatedLayer(){return!(!this._relatedLayerSupportsQuery||!this._relatedLayerSupportsQueryRelated)}get canAddRelatedFeature(){const{state:e,relationship:t,supportsAdd:r,supportsEditing:s}=this;if("loaded"!==e||!t||!r||!s)return!1;const{count:i}=this,{cardinality:a,role:o}=t,n=i>0;return("one-to-one"!==a||!n)&&("one-to-many"!==a||"origin"!==o||!n)}get effectiveOutFields(){const{layer:e,outFields:t}=this;if(!e||!t?.length)return this._defaultOutFields;const r=[];t.forEach((t=>{const s=e.fieldsIndex.normalizeFieldName(t);s&&r.push(s)}));const{objectIdField:s}=e,i=e.fieldsIndex.normalizeFieldName(s)??s;return i&&!r.includes(i)&&r.unshift(i),r}get effectiveTimeExtent(){const{layer:e,timeExtent:t}=this;return t||e&&"timeExtent"in e&&e.timeExtent||null}get effectiveWhere(){return this.where||this.layer?.definitionExpression||"1=1"}get itemCache(){return new a({items:[...this.pageCache.values()].flat()})}get layerView(){const{layer:e,view:t}=this;if(!e||!t)return null;const r="sublayer"===e.type?e.parent:e;return t.allLayerViews.find((e=>e.layer===r))}get orderByFields(){const{_sortedFieldNames:e,layer:t,sortOrders:r}=this,s=r.filter((({fieldName:t,direction:r},s)=>e.indexOf(t)===s&&null!=r)).map((({fieldName:e,direction:t})=>`${e} ${t?.toUpperCase()}`));if(t&&!s.length&&!t.objectIdField&&t.fields?.length){const e=t.fields.find((e=>e.name));if(e){const r=t.fieldsIndex.normalizeFieldName(e.name);r&&s.push(`${r} ASC`)}}return s}get querying(){return this._queryOperationQueue.length>0}get relationship(){const{relationshipConfig:e}=this;return null==e?.relationshipId?null:this.relationships?.find((t=>t.id===e.relationshipId))}get relationshipIds(){return this.relationships?.map((e=>e.id))??[]}get relationshipInfos(){const{_layerWithRelationships:e,relatedRecordsEnabled:t,relationships:r,view:s}=this,i=[];return t&&e?.loaded&&s?.map&&r?.length?(r.forEach((t=>{const r=O(e,s,t);r&&(r.load(),i.push({layer:e,relatedLayer:r,relationshipId:t.id}))})),i):i}get relationships(){return this._layerWithRelationships?.relationships}get state(){const{layer:e,_loaded:t,_loadError:r,_loading:s}=this;return!e||e.destroyed?"disabled":r||e.loadError?"error":"loaded"===e.loadStatus&&t?"loaded":s?"loading":"ready"}get supportsAdd(){return!!this._capabilities?.operations.supportsAdd}get supportsAddingAttachments(){return!(!this._layerWithAttachmentsEditing||!this.supportsAdd)}get supportsAttachments(){const{_capabilities:e}=this;return!(!e?.data?.supportsAttachment||!e?.operations.supportsQueryAttachments)}get supportsCacheHint(){return!!this._capabilities?.query?.supportsCacheHint}get supportsCacheHintQueryRelated(){return!!this._capabilities?.queryRelated?.supportsCacheHint}get supportsDelete(){return!!this._capabilities?.operations.supportsDelete}get supportsDeletingAttachments(){return!(!this._layerWithAttachmentsEditing||!this.supportsDelete)}get supportsEditing(){return!!this._capabilities?.operations.supportsEditing}get supportsM(){return!!this.layer?.hasM&&!!this._capabilities?.data?.supportsM}get supportsOrderBy(){return!!this._capabilities?.query?.supportsOrderBy}get supportsPagination(){return!!this._capabilities?.query?.supportsPagination}get supportsQuery(){return!!this._capabilities?.operations.supportsQuery}get supportsQueryRelated(){const{_capabilities:e}=this;return!!e?.queryRelated?.supportsCount&&!!e?.queryRelated?.supportsPagination}get supportsResizeAttachments(){const{_capabilities:e}=this;return!(!this.supportsAttachments||!e?.operations?.supportsResizeAttachments)}get supportsUpdate(){return!!this._capabilities?.operations.supportsUpdate}get supportsUpdateAttachments(){return!(!this._layerWithAttachmentsEditing||!this.supportsUpdate)}get supportsZ(){return!!this.layer?.hasZ&&!!this._capabilities?.data?.supportsZ}get syncing(){return this.syncingFeatureEdits||this.syncingAttachmentEdits}get syncingAttachmentEdits(){return this._attachmentsOperationQueue.length>0}get syncingFeatureEdits(){return this._editOperationQueue.length>0}async addAttachment(e,t){const{_layerWithAttachmentsEditing:r}=this;if(!r||!this.supportsAddingAttachments)return{};const s=await this._queueAttachmentsOperation(e,(()=>r.addAttachment(this._createBaseGraphic(r,e),t)));return this._ensureArrayContent(s)}async deleteAttachments(e,t){const{_layerWithAttachmentsEditing:r}=this;if(!r||!this.supportsDeletingAttachments||!t.length)return[];const s=await this._queueAttachmentsOperation(e,(()=>r.deleteAttachments(this._createBaseGraphic(r,e),t)));return this._ensureArray(s)}async deleteRowsByObjectId(e){const{_layerWithEditing:t}=this;if(!this.supportsDelete||!t)throw new o("store:delete-error","Delete is not supported.");const r=e.map((e=>this.getItemByObjectId(e)?.feature)).filter(i);return this._queueEditOperation((()=>t.applyEdits({deleteFeatures:r})))}async fetchItems(e){const{page:t}=e,{pageSize:r}=this,s=t*r,i=s+r,{layer:a,state:o}=this;return a&&"loaded"===o?this._query({layer:a,start:s,num:i,page:t,pageSize:r}):[]}async getAttachmentsByObjectId(e,t){const r=this.getItemByObjectId(e)?.attachments??[];if(!r.length&&t){return(await this._queryAttachments([e]))[e]??[]}return r}getItemByObjectId(e){for(const t of this.pageCache.values())for(const r of t)if(r.objectId===e)return r}getItemIndexByObjectId(e){const{pageCache:t,pageSize:r}=this,s=t.entries();let i=-1;for(const[a,o]of s)if(o.some(((t,s)=>{const o=t.objectId===e;return o&&(i=a*r+s),o})),i>-1)break;return i}async load(){const{layer:e}=this;if(!this._loading&&!this._loaded&&e){this._reset(),this._loading=!0;try{await e.load(),e.parent&&y(e.parent)&&await e.parent.loadAll(),await e.when();const t=this.initialSize;this.initialSize=null,await this.refresh(t),this._loaded=!0,this._loading=!1}catch(t){throw this._reset(),this._loadError=!0,this._logError("store:load-error","An error occurred."),t}}}async query(e){const{state:t}=this;return this.supportsQuery&&"loaded"===t?this._query(e):[]}async refresh(e){this._clearCaches(),await this._syncCount(e),await this._syncObjectIdCache()}async reset(){this._reset()}async updateAttachment(e,t,r){const{_layerWithAttachmentsEditing:s}=this;if(!s||!this.supportsUpdateAttachments)return{};const i=await this._queueAttachmentsOperation(e,(()=>s.updateAttachment(this._createBaseGraphic(s,e),t,r)));return this._ensureArrayContent(i)}async updateItem(e){const{_sortedFieldNames:t}=this,r=e.updates.map((({fieldName:e})=>e)),s=await this._update(e);return!s.updateFeatureResults.find((e=>e.error))&&r.some((e=>t.includes(e)))&&this._clearCaches(),s}async verifyFeaturesByObjectId(e){const{layer:t,state:r}=this;if(!t||"loaded"!==r)return[];const{objectIdField:s}=t,i=await this._verifyFeaturesByObjectId(e);return e.map((e=>i.some((t=>{const r=t.getObjectId()??t.attributes[s];return e===r}))))}_clearCaches(){this.pageCache.clear(),this._objectIdCache.removeAll()}_createBaseGraphic(e,r){return new t({attributes:{[e.objectIdField]:r}})}_ensureArray(e){return Array.isArray(e)?e:[e]}_ensureArrayContent(e){return Array.isArray(e)?e[0]:e}_getObjectIdsForPage(e,t){const r=this._objectIdCache.toArray();return r.length>=e+t?r.slice(e,e+t):r.slice(e)}_logError(e,t){u.getLogger(this).error(e,t)}_reset(){this._clearCaches(),this.failures.removeAll(),this._attachmentsOperationQueue.removeAll(),this._editOperationQueue.removeAll(),this._queryOperationQueue.removeAll(),this._loading=!1,this._loaded=!1,this._loadError=!1,this._set("count",0)}async _syncCount(e){null==e?await this._queryCount().then((e=>this._set("count",e))):this._set("count",e)}async _syncObjectIdCache(){if(this.supportsPagination)return;const e=await this._queryObjectIds();this._objectIdCache.removeAll(),this._objectIdCache.addMany(e)}async _verifyFeaturesByObjectId(e){const{layer:t}=this;if(!t||!this.supportsQuery)throw new o("store:query-error","Layer does not support query operation.");const{effectiveTimeExtent:r,effectiveWhere:s,orderByFields:i,supportsCacheHint:a,supportsOrderBy:n}=this,u=t.createQuery();u.where=s,u.timeExtent=r,u.returnGeometry=!1,u.objectIds=e.length?e:void 0,u.outFields=[t.objectIdField],n&&(u.orderByFields=i),a&&(u.cacheHint=!0);return(await t.queryFeatures(u)).features}async _update(e){const{objectId:r,updates:s}=e,{_layerWithEditing:i}=this;if(!this.supportsUpdate||!i)throw new o("store:update-error","Update is not supported.");const a=this.getItemByObjectId(r)?.feature;if(!a)throw new o("store:update-error","Feature with provided 'objectId' not found.");const u=n(a.attributes);s.forEach((({fieldName:e,value:t})=>u[e]=t));const p=new t({attributes:u}),l=i.applyEdits({updateFeatures:[p]}).then((e=>{const{updateFeatureResults:t}=e,r=t.find((e=>!!e.error));if(r)throw r.error;return t.length&&(a.attributes=u),e}));return this._queueEditOperation((()=>l))}_prepareFeatureData(e){const{attachments:t,features:r,layer:s,relatedRecords:i}=e,a=s.objectIdField;return r.map((e=>{const r=e.getObjectId()??e.attributes[a],o=[];return e.layer||e.sourceLayer||(e.layer=s,e.sourceLayer=s),i.forEach(((e,t)=>{o.push({relationshipId:t,count:e[r]??0})})),{objectId:r,feature:e,attachments:t[r]??null,relatedRecords:o}}))}async _query(e){const{page:t,refresh:r}=e;!0===r&&await this.refresh();const s=this.pageCache.get(t);if(s)return s;const i=await this._queryPage(e);return this.pageCache.set(t,i),i}_queryAttachments(e){const{_layerWithAttachments:t,effectiveWhere:r,supportsCacheHint:s}=this;return t?e.some((e=>"number"!=typeof e))?Promise.reject(new o("invalid-object-id","Only numeric object ids are valid to query attachments")):t.queryAttachments(new m({cacheHint:s,objectIds:e,where:r,returnMetadata:!0})):Promise.resolve({})}async _queryCount(){const{_relatedLayerSupportsCacheHint:e,layer:t,relationshipConfig:r,supportsCacheHint:s}=this;if(!t)return 0;if(r&&this._canUseRelatedLayer){const{objectId:t,relatedLayer:s,relationshipId:i}=r;return(await s.queryRelatedFeaturesCount(new _({cacheHint:e,relationshipId:i,objectIds:[t]})))[t]??0}const{effectiveTimeExtent:i,effectiveWhere:a,filterGeometry:o,objectIds:n}=this,u=t.createQuery();return u.geometry=o,u.returnGeometry=!1,u.where=a,u.timeExtent=i,u.objectIds=n?.length?n:void 0,s&&(u.cacheHint=!0),t.queryFeatureCount(u)}async _queryFeatures(e){const{relationshipConfig:t}=this;if(t&&this._canUseRelatedLayer)return this._queryRelatedFeatures(e,t);const{_effectiveReturnM:r,_effectiveReturnZ:s,effectiveOutFields:i,effectiveTimeExtent:a,effectiveWhere:o,filterGeometry:n,objectIds:u,orderByFields:p,pageSize:l,returnGeometry:h,supportsCacheHint:d,supportsOrderBy:c,supportsPagination:y}=this,{layer:m,start:_}=e,f=u?.length,g=m.createQuery();g.returnGeometry=h,g.outFields=i,g.returnM=r,g.returnZ=s,y?(g.start=_,g.num=l,g.where=o,g.timeExtent=a,g.objectIds=f?u:void 0):g.objectIds=f?u:this._getObjectIdsForPage(_,l??0),c&&(g.orderByFields=p),n&&(g.geometry=n),d&&(g.cacheHint=!0);return(await m.queryFeatures(g)).features}_queryObjectIds(){const{effectiveTimeExtent:e,effectiveWhere:t,filterGeometry:r,layer:s,objectIds:i,orderByFields:a,supportsCacheHint:o,supportsOrderBy:n}=this;if(!s)return Promise.resolve([]);const u=s.createQuery();return u.geometry=r,u.outFields=[s.objectIdField],u.returnGeometry=!1,u.where=t,u.timeExtent=e,u.objectIds=i?.length?i:void 0,n&&(u.orderByFields=a),o&&(u.cacheHint=!0),s.queryObjectIds(u)}async _queryPage(e){const{layer:t}=e;return this._queueQueryOperation((async()=>{const r=await this._queryFeatures(e),s=r.map((e=>e.getObjectId()??e.attributes[t.objectIdField])),i=await this._queryAttachments(s),a=await this._queryRelatedCounts(s);return this._prepareFeatureData({layer:t,features:r,attachments:i,relatedRecords:a})||[]}))}async _queryRelatedCounts(e){const{_layerWithRelationships:t,relationshipIds:r,supportsCacheHintQueryRelated:s}=this,i=new Map;return t&&e?.length&&r.length?(await Promise.allSettled(r.map((async r=>{const a=await t.queryRelatedFeaturesCount(new _({cacheHint:s,relationshipId:r,objectIds:e}));i.set(r,a)}))),i):i}async _queryRelatedFeatures(e,t){const{_defaultOutFields:r,_effectiveReturnM:s,_effectiveReturnZ:i,orderByFields:a,pageSize:o,returnGeometry:n,supportsCacheHint:u}=this,{layer:p,start:l}=e,{objectId:h,relatedLayer:d,relationshipId:c}=t,y=p.createQuery(),m=new _({cacheHint:u,num:o,objectIds:[h],orderByFields:a,outFields:r,relationshipId:c,returnGeometry:n,returnM:s,returnZ:i,start:l,where:y.where??void 0}),f=await d.queryRelatedFeatures(m);return f[h]?.features||[]}_queueAttachmentsOperation(e,t){return this._attachmentsOperationQueue.push(t),t().then((async r=>{this._attachmentsOperationQueue.remove(t);const s=this._ensureArray(r),i=s.some((e=>e.error)),a=this.getItemByObjectId(e);if(a&&(!i||s.length>1)){const t=await this._queryAttachments([e]);a.attachments=t[e]}return r})).catch((async r=>{this._logError("store:attachment-error","An error occurred.");const s={error:r,retry:()=>{this.failures.remove(s),this._queueAttachmentsOperation(e,t)},cancel:()=>this.failures.remove(s)};throw this.failures.add(s),this._attachmentsOperationQueue.remove(t),r}))}_queueEditOperation(e){return this._editOperationQueue.push(e),e().then((t=>(this._editOperationQueue.remove(e),t))).catch((t=>{this._logError("store:edit-error","An error occurred.");const r={error:t,retry:()=>{this.failures.remove(r),this._queueEditOperation(e)},cancel:()=>this.failures.remove(r)};throw this.failures.add(r),this._editOperationQueue.remove(e),t}))}_queueQueryOperation(e){return this._queryOperationQueue.push(e),e().then((t=>this._queryOperationQueue.includes(e)?t:[])).catch((t=>{this._logError("store:query-error","An error occurred.");const r={error:t,retry:()=>{this.failures.remove(r),this._queueQueryOperation(e)},cancel:()=>this.failures.remove(r)};return this.failures.add(r),[]})).then((t=>(this._queryOperationQueue.remove(e),t)))}};e([d()],A.prototype,"_attachmentsOperationQueue",void 0),e([d({readOnly:!0})],A.prototype,"_capabilities",null),e([d()],A.prototype,"_defaultOutFields",void 0),e([d()],A.prototype,"_editOperationQueue",void 0),e([d()],A.prototype,"_effectiveReturnZ",null),e([d()],A.prototype,"_effectiveReturnM",null),e([d({readOnly:!0})],A.prototype,"_layerWithAttachments",null),e([d({readOnly:!0})],A.prototype,"_layerWithAttachmentsEditing",null),e([d({readOnly:!0})],A.prototype,"_layerWithEditing",null),e([d({readOnly:!0})],A.prototype,"_layerWithRelationships",null),e([d()],A.prototype,"_loaded",void 0),e([d()],A.prototype,"_loadError",void 0),e([d()],A.prototype,"_loading",void 0),e([d()],A.prototype,"_objectIdCache",void 0),e([d()],A.prototype,"_queryOperationQueue",void 0),e([d({readOnly:!0})],A.prototype,"_relatedLayer",null),e([d({readOnly:!0})],A.prototype,"_relatedLayerCapabilities",null),e([d({readOnly:!0})],A.prototype,"_relatedLayerSupportsCacheHint",null),e([d()],A.prototype,"_relatedLayerSupportsQuery",null),e([d()],A.prototype,"_relatedLayerSupportsQueryRelated",null),e([d()],A.prototype,"_sortedFieldNames",null),e([d()],A.prototype,"_canUseRelatedLayer",null),e([d()],A.prototype,"attachmentsEnabled",void 0),e([d()],A.prototype,"canAddRelatedFeature",null),e([d({readOnly:!0})],A.prototype,"count",void 0),e([d()],A.prototype,"effectiveOutFields",null),e([d()],A.prototype,"effectiveTimeExtent",null),e([d()],A.prototype,"effectiveWhere",null),e([d({readOnly:!0})],A.prototype,"failures",void 0),e([d()],A.prototype,"filterGeometry",void 0),e([d()],A.prototype,"initialSize",void 0),e([d({readOnly:!0})],A.prototype,"itemCache",null),e([d()],A.prototype,"layer",void 0),e([d()],A.prototype,"layerView",null),e([d()],A.prototype,"objectIds",void 0),e([d()],A.prototype,"orderByFields",null),e([d()],A.prototype,"outFields",void 0),e([d({readOnly:!0})],A.prototype,"pageCache",void 0),e([d()],A.prototype,"pageSize",void 0),e([d({readOnly:!0})],A.prototype,"querying",null),e([d()],A.prototype,"relationship",null),e([d()],A.prototype,"relationshipConfig",void 0),e([d()],A.prototype,"relationshipIds",null),e([d()],A.prototype,"relationshipInfos",null),e([d()],A.prototype,"relationships",null),e([d()],A.prototype,"relatedRecordsEnabled",void 0),e([d()],A.prototype,"returnGeometry",void 0),e([d()],A.prototype,"returnZ",void 0),e([d()],A.prototype,"returnM",void 0),e([d()],A.prototype,"sortOrders",void 0),e([d({readOnly:!0})],A.prototype,"state",null),e([d()],A.prototype,"supportsAdd",null),e([d()],A.prototype,"supportsAddingAttachments",null),e([d()],A.prototype,"supportsAttachments",null),e([d()],A.prototype,"supportsCacheHint",null),e([d()],A.prototype,"supportsCacheHintQueryRelated",null),e([d()],A.prototype,"supportsDelete",null),e([d()],A.prototype,"supportsDeletingAttachments",null),e([d()],A.prototype,"supportsEditing",null),e([d()],A.prototype,"supportsM",null),e([d()],A.prototype,"supportsOrderBy",null),e([d()],A.prototype,"supportsPagination",null),e([d()],A.prototype,"supportsQuery",null),e([d()],A.prototype,"supportsQueryRelated",null),e([d()],A.prototype,"supportsResizeAttachments",null),e([d()],A.prototype,"supportsUpdate",null),e([d()],A.prototype,"supportsUpdateAttachments",null),e([d()],A.prototype,"supportsZ",null),e([d({readOnly:!0})],A.prototype,"syncing",null),e([d({readOnly:!0})],A.prototype,"syncingAttachmentEdits",null),e([d({readOnly:!0})],A.prototype,"syncingFeatureEdits",null),e([d()],A.prototype,"timeExtent",void 0),e([d()],A.prototype,"view",void 0),e([d()],A.prototype,"where",void 0),A=e([c("esri.widgets.FeatureTable.support.FeatureStore")],A);const I=A;export{I as default};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Graphic.js";import r from"../../../core/Accessor.js";import{equals as s,isSome as i}from"../../../core/arrayUtils.js";import a from"../../../core/Collection.js";import o from"../../../core/Error.js";import{clone as n}from"../../../core/lang.js";import u from"../../../core/Logger.js";import l from"../../../core/ReactiveMap.js";import{watch as p,when as h}from"../../../core/reactiveUtils.js";import{property as d}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import{subclass as c}from"../../../core/accessorSupport/decorators/subclass.js";import{isSubtypeGroupLayer as y}from"../../../layers/support/layerUtils.js";import m from"../../../rest/support/AttachmentQuery.js";import _ from"../../../rest/support/RelationshipQuery.js";import{isIFeatureTableSupportedLayerWithAttachments as f,isIFeatureTableSupportedLayerWithAttachmentsEditing as g,isIFeatureTableSupportedLayerWithEditing as b,isIFeatureTableSupportedLayerWithRelationships as v,findRelatedLayer as O}from"./tableUtils.js";let A=class extends r{constructor(e){super(e),this._attachmentsOperationQueue=new a,this._defaultOutFields=["*"],this._editOperationQueue=new a,this._loaded=!1,this._loadError=!1,this._loading=!1,this._objectIdCache=new a,this._queryOperationQueue=new a,this.attachmentsEnabled=!1,this.count=0,this.failures=new a,this.filterGeometry=null,this.initialSize=null,this.layer=null,this.objectIds=null,this.outFields=null,this.pageCache=new l,this.pageSize=50,this.relationshipConfig=null,this.relatedRecordsEnabled=!1,this.returnGeometry=!1,this.returnZ=!1,this.returnM=!1,this.sortOrders=[],this.timeExtent=null,this.view=null,this.where=null}initialize(){this.addHandles([p((()=>[this.filterGeometry,this.layer,this.objectIds,this.outFields,this.pageSize,this.relationshipConfig,this.returnGeometry,this.returnM,this.returnZ,this.timeExtent,this.where]),(()=>this._reset())),p((()=>this.orderByFields),(()=>this._clearCaches()),{equals:s}),h((()=>this.attachmentsEnabled),(()=>this._reset())),h((()=>this.relatedRecordsEnabled),(()=>this._reset()))])}destroy(){this.layer=null,this.itemCache?.destroy(),this.failures?.destroy()}get _capabilities(){const{layer:e}=this;return e?.effectiveCapabilities??e?.capabilities}get _effectiveReturnZ(){return this.returnZ&&this.supportsZ}get _effectiveReturnM(){return this.returnM&&this.supportsM}get _layerWithAttachments(){const{layer:e}=this;return e&&this._capabilities&&this.attachmentsEnabled&&this.supportsAttachments&&f(e)?e:null}get _layerWithAttachmentsEditing(){const{_layerWithAttachments:e}=this;return e&&g(e)&&this.supportsEditing?e:null}get _layerWithEditing(){const e=this.layer;return b(e)&&this.supportsEditing?e:null}get _layerWithRelationships(){const e=this.layer;return v(e)&&this.supportsQueryRelated?e:null}get _relatedLayer(){return this.relationshipConfig?.relatedLayer}get _relatedLayerCapabilities(){const{_relatedLayer:e}=this;return e?.effectiveCapabilities??e?.capabilities}get _relatedLayerSupportsCacheHint(){return!!this._relatedLayerCapabilities?.queryRelated?.supportsCacheHint}get _relatedLayerSupportsQuery(){return!!this._relatedLayerCapabilities?.operations.supportsQuery}get _relatedLayerSupportsQueryRelated(){const{_relatedLayerCapabilities:e}=this;return!!e?.queryRelated?.supportsCount&&!!e?.queryRelated?.supportsPagination}get _sortedFieldNames(){return this.sortOrders.map((({fieldName:e})=>e))}get _canUseRelatedLayer(){return!(!this._relatedLayerSupportsQuery||!this._relatedLayerSupportsQueryRelated)}get canAddRelatedFeature(){const{state:e,relationship:t,supportsAdd:r,supportsEditing:s}=this;if("loaded"!==e||!t||!r||!s)return!1;const{count:i}=this,{cardinality:a,role:o}=t,n=i>0;return("one-to-one"!==a||!n)&&("one-to-many"!==a||"origin"!==o||!n)}get effectiveOutFields(){const{layer:e,outFields:t}=this;if(!e||!t?.length)return this._defaultOutFields;const r=[];t.forEach((t=>{const s=e.fieldsIndex.normalizeFieldName(t);s&&r.push(s)}));const{objectIdField:s}=e,i=e.fieldsIndex.normalizeFieldName(s)??s;return i&&!r.includes(i)&&r.unshift(i),r}get effectiveTimeExtent(){const{layer:e,timeExtent:t}=this;return t||e&&"timeExtent"in e&&e.timeExtent||null}get effectiveWhere(){return this.where||this.layer?.definitionExpression||"1=1"}get itemCache(){return new a({items:[...this.pageCache.values()].flat()})}get layerView(){const{layer:e,view:t}=this;if(!e||!t)return null;const r="sublayer"===e.type?e.parent:e;return t.allLayerViews.find((e=>e.layer===r))}get orderByFields(){const{_sortedFieldNames:e,layer:t,sortOrders:r}=this,s=r.filter((({fieldName:t,direction:r},s)=>e.indexOf(t)===s&&null!=r)).map((({fieldName:e,direction:t})=>`${e} ${t?.toUpperCase()}`));if(t&&!s.length&&!t.objectIdField&&t.fields?.length){const e=t.fields.find((e=>e.name));if(e){const r=t.fieldsIndex.normalizeFieldName(e.name);r&&s.push(`${r} ASC`)}}return s}get querying(){return this._queryOperationQueue.length>0}get relationship(){const{relationshipConfig:e}=this;return null==e?.relationshipId?null:this.relationships?.find((t=>t.id===e.relationshipId))}get relationshipIds(){return this.relationships?.map((e=>e.id))??[]}get relationshipInfos(){const{_layerWithRelationships:e,relatedRecordsEnabled:t,relationships:r,view:s}=this,i=[];return t&&e?.loaded&&s?.map&&r?.length?(r.forEach((t=>{const r=O(e,s,t);r&&(r.load(),i.push({layer:e,relatedLayer:r,relationshipId:t.id}))})),i):i}get relationships(){return this._layerWithRelationships?.relationships}get state(){const{layer:e,_loaded:t,_loadError:r,_loading:s}=this;return!e||e.destroyed?"disabled":r||e.loadError?"error":"loaded"===e.loadStatus&&t?"loaded":s?"loading":"ready"}get supportsAdd(){return!!this._capabilities?.operations.supportsAdd}get supportsAddingAttachments(){return!(!this._layerWithAttachmentsEditing||!this.supportsAdd)}get supportsAttachments(){const{_capabilities:e}=this;return!(!e?.data?.supportsAttachment||!e?.operations.supportsQueryAttachments)}get supportsCacheHint(){return!!this._capabilities?.query?.supportsCacheHint}get supportsCacheHintQueryRelated(){return!!this._capabilities?.queryRelated?.supportsCacheHint}get supportsDelete(){return!!this._capabilities?.operations.supportsDelete}get supportsDeletingAttachments(){return!(!this._layerWithAttachmentsEditing||!this.supportsDelete)}get supportsEditing(){return!!this._capabilities?.operations.supportsEditing}get supportsM(){return!!this.layer?.hasM&&!!this._capabilities?.data?.supportsM}get supportsOrderBy(){return!!this._capabilities?.query?.supportsOrderBy}get supportsPagination(){return!!this._capabilities?.query?.supportsPagination}get supportsQuery(){return!!this._capabilities?.operations.supportsQuery}get supportsQueryRelated(){const{_capabilities:e}=this;return!!e?.queryRelated?.supportsCount&&!!e?.queryRelated?.supportsPagination}get supportsResizeAttachments(){const{_capabilities:e}=this;return!(!this.supportsAttachments||!e?.operations?.supportsResizeAttachments)}get supportsUpdate(){return!!this._capabilities?.operations.supportsUpdate}get supportsUpdateAttachments(){return!(!this._layerWithAttachmentsEditing||!this.supportsUpdate)}get supportsZ(){return!!this.layer?.hasZ&&!!this._capabilities?.data?.supportsZ}get syncing(){return this.syncingFeatureEdits||this.syncingAttachmentEdits}get syncingAttachmentEdits(){return this._attachmentsOperationQueue.length>0}get syncingFeatureEdits(){return this._editOperationQueue.length>0}async addAttachment(e,t){const{_layerWithAttachmentsEditing:r}=this;if(!r||!this.supportsAddingAttachments)return{};const s=await this._queueAttachmentsOperation(e,(()=>r.addAttachment(this._createBaseGraphic(r,e),t)));return this._ensureArrayContent(s)}async deleteAttachments(e,t){const{_layerWithAttachmentsEditing:r}=this;if(!r||!this.supportsDeletingAttachments||!t.length)return[];const s=await this._queueAttachmentsOperation(e,(()=>r.deleteAttachments(this._createBaseGraphic(r,e),t)));return this._ensureArray(s)}async deleteRowsByObjectId(e){const{_layerWithEditing:t}=this;if(!this.supportsDelete||!t)throw new o("store:delete-error","Delete is not supported.");const r=e.map((e=>this.getItemByObjectId(e)?.feature)).filter(i);return this._queueEditOperation((()=>t.applyEdits({deleteFeatures:r})))}async fetchItems(e){const{page:t}=e,{pageSize:r}=this,s=t*r,i=s+r,{layer:a,state:o}=this;return a&&"loaded"===o?this._query({layer:a,start:s,num:i,page:t,pageSize:r}):[]}async getAttachmentsByObjectId(e,t){const r=this.getItemByObjectId(e)?.attachments??[];if(!r.length&&t){return(await this._queryAttachments([e]))[e]??[]}return r}getItemByObjectId(e){for(const t of this.pageCache.values())for(const r of t)if(r.objectId===e)return r}getItemIndexByObjectId(e){const{pageCache:t,pageSize:r}=this,s=t.entries();let i=-1;for(const[a,o]of s)if(o.some(((t,s)=>{const o=t.objectId===e;return o&&(i=a*r+s),o})),i>-1)break;return i}async load(){const{layer:e}=this;if(!this._loading&&!this._loaded&&e){this._reset(),this._loading=!0;try{await e.load(),e.parent&&y(e.parent)&&await e.parent.loadAll(),await e.when();const t=this.initialSize;this.initialSize=null,await this.refresh(t),this._loaded=!0,this._loading=!1}catch(t){throw this._reset(),this._loadError=!0,this._logError("store:load-error","An error occurred."),t}}}async query(e){const{state:t}=this;return this.supportsQuery&&"loaded"===t?this._query(e):[]}async refresh(e){this._clearCaches(),await this._syncCount(e),await this._syncObjectIdCache()}async reset(){this._reset()}async updateAttachment(e,t,r){const{_layerWithAttachmentsEditing:s}=this;if(!s||!this.supportsUpdateAttachments)return{};const i=await this._queueAttachmentsOperation(e,(()=>s.updateAttachment(this._createBaseGraphic(s,e),t,r)));return this._ensureArrayContent(i)}async updateItem(e){const{_sortedFieldNames:t}=this,r=e.updates.map((({fieldName:e})=>e)),s=await this._update(e);return!s.updateFeatureResults.find((e=>e.error))&&r.some((e=>t.includes(e)))&&this._clearCaches(),s}async verifyFeaturesByObjectId(e){const{layer:t,state:r}=this;if(!t||"loaded"!==r)return[];const{objectIdField:s}=t,i=await this._verifyFeaturesByObjectId(e);return e.map((e=>i.some((t=>{const r=t.getObjectId()??t.attributes[s];return e===r}))))}_clearCaches(){this.pageCache.clear(),this._objectIdCache.removeAll()}_createBaseGraphic(e,r){return new t({attributes:{[e.objectIdField]:r}})}_ensureArray(e){return Array.isArray(e)?e:[e]}_ensureArrayContent(e){return Array.isArray(e)?e[0]:e}_getObjectIdsForPage(e,t){const r=this._objectIdCache.toArray();return r.length>=e+t?r.slice(e,e+t):r.slice(e)}_logError(e,t){u.getLogger(this).error(e,t)}_reset(){this._clearCaches(),this.failures.removeAll(),this._attachmentsOperationQueue.removeAll(),this._editOperationQueue.removeAll(),this._queryOperationQueue.removeAll(),this._loading=!1,this._loaded=!1,this._loadError=!1,this._set("count",0)}async _syncCount(e){null==e?await this._queryCount().then((e=>this._set("count",e))):this._set("count",e)}async _syncObjectIdCache(){if(this.supportsPagination)return;const e=await this._queryObjectIds();this._objectIdCache.removeAll(),this._objectIdCache.addMany(e)}async _verifyFeaturesByObjectId(e){const{layer:t}=this;if(!t||!this.supportsQuery)throw new o("store:query-error","Layer does not support query operation.");const{effectiveTimeExtent:r,effectiveWhere:s,orderByFields:i,supportsCacheHint:a,supportsOrderBy:n}=this,u=t.createQuery();u.where=s,u.timeExtent=r,u.returnGeometry=!1,u.objectIds=e.length?e:void 0,u.outFields=[t.objectIdField],n&&(u.orderByFields=i),a&&(u.cacheHint=!0);return(await t.queryFeatures(u)).features}async _update(e){const{objectId:r,updates:s}=e,{_layerWithEditing:i}=this;if(!this.supportsUpdate||!i)throw new o("store:update-error","Update is not supported.");const a=this.getItemByObjectId(r)?.feature;if(!a)throw new o("store:update-error","Feature with provided 'objectId' not found.");const u=n(a.attributes);s.forEach((({fieldName:e,value:t})=>u[e]=t));const l=new t({attributes:u}),p=i.applyEdits({updateFeatures:[l]}).then((e=>{const{updateFeatureResults:t}=e,r=t.find((e=>!!e.error));if(r)throw r.error;return t.length&&(a.attributes=u),e}));return this._queueEditOperation((()=>p))}_prepareFeatureData(e){const{attachments:t,features:r,layer:s,relatedRecords:i}=e,a=s.objectIdField;return r.map((e=>{const r=e.getObjectId()??e.attributes[a],o=[];return e.layer||e.sourceLayer||(e.layer=s,e.sourceLayer=s),i.forEach(((e,t)=>{o.push({relationshipId:t,count:e[r]??0})})),{objectId:r,feature:e,attachments:t[r]??null,relatedRecords:o}}))}async _query(e){const{page:t,refresh:r}=e;!0===r&&await this.refresh();const s=this.pageCache.get(t);if(s)return s;const i=await this._queryPage(e);return this.pageCache.set(t,i),i}_queryAttachments(e){const{_layerWithAttachments:t,effectiveWhere:r}=this;return t?e.some((e=>"number"!=typeof e))?Promise.reject(new o("invalid-object-id","Only numeric object ids are valid to query attachments")):t.queryAttachments(new m({objectIds:e,where:r,returnMetadata:!0})):Promise.resolve({})}async _queryCount(){const{_relatedLayerSupportsCacheHint:e,layer:t,relationshipConfig:r,supportsCacheHint:s}=this;if(!t)return 0;if(r&&this._canUseRelatedLayer){const{objectId:t,relatedLayer:s,relationshipId:i}=r;return(await s.queryRelatedFeaturesCount(new _({cacheHint:e,relationshipId:i,objectIds:[t]})))[t]??0}const{effectiveTimeExtent:i,effectiveWhere:a,filterGeometry:o,objectIds:n}=this,u=t.createQuery();return u.geometry=o,u.returnGeometry=!1,u.where=a,u.timeExtent=i,u.objectIds=n?.length?n:void 0,s&&(u.cacheHint=!0),t.queryFeatureCount(u)}async _queryFeatures(e){const{relationshipConfig:t}=this;if(t&&this._canUseRelatedLayer)return this._queryRelatedFeatures(e,t);const{_effectiveReturnM:r,_effectiveReturnZ:s,effectiveOutFields:i,effectiveTimeExtent:a,effectiveWhere:o,filterGeometry:n,objectIds:u,orderByFields:l,pageSize:p,returnGeometry:h,supportsCacheHint:d,supportsOrderBy:c,supportsPagination:y}=this,{layer:m,start:_}=e,f=u?.length,g=m.createQuery();g.returnGeometry=h,g.outFields=i,g.returnM=r,g.returnZ=s,y?(g.start=_,g.num=p,g.where=o,g.timeExtent=a,g.objectIds=f?u:void 0):g.objectIds=f?u:this._getObjectIdsForPage(_,p??0),c&&(g.orderByFields=l),n&&(g.geometry=n),d&&(g.cacheHint=!0);return(await m.queryFeatures(g)).features}_queryObjectIds(){const{effectiveTimeExtent:e,effectiveWhere:t,filterGeometry:r,layer:s,objectIds:i,orderByFields:a,supportsCacheHint:o,supportsOrderBy:n}=this;if(!s)return Promise.resolve([]);const u=s.createQuery();return u.geometry=r,u.outFields=[s.objectIdField],u.returnGeometry=!1,u.where=t,u.timeExtent=e,u.objectIds=i?.length?i:void 0,n&&(u.orderByFields=a),o&&(u.cacheHint=!0),s.queryObjectIds(u)}async _queryPage(e){const{layer:t}=e;return this._queueQueryOperation((async()=>{const r=await this._queryFeatures(e),s=r.map((e=>e.getObjectId()??e.attributes[t.objectIdField])),i=await this._queryAttachments(s),a=await this._queryRelatedCounts(s);return this._prepareFeatureData({layer:t,features:r,attachments:i,relatedRecords:a})||[]}))}async _queryRelatedCounts(e){const{_layerWithRelationships:t,relationshipIds:r,supportsCacheHintQueryRelated:s}=this,i=new Map;return t&&e?.length&&r.length?(await Promise.allSettled(r.map((async r=>{const a=await t.queryRelatedFeaturesCount(new _({cacheHint:s,relationshipId:r,objectIds:e}));i.set(r,a)}))),i):i}async _queryRelatedFeatures(e,t){const{_defaultOutFields:r,_effectiveReturnM:s,_effectiveReturnZ:i,orderByFields:a,pageSize:o,returnGeometry:n,supportsCacheHint:u}=this,{layer:l,start:p}=e,{objectId:h,relatedLayer:d,relationshipId:c}=t,y=l.createQuery(),m=new _({cacheHint:u,num:o,objectIds:[h],orderByFields:a,outFields:r,relationshipId:c,returnGeometry:n,returnM:s,returnZ:i,start:p,where:y.where??void 0}),f=await d.queryRelatedFeatures(m);return f[h]?.features||[]}_queueAttachmentsOperation(e,t){return this._attachmentsOperationQueue.push(t),t().then((async r=>{this._attachmentsOperationQueue.remove(t);const s=this._ensureArray(r),i=s.some((e=>e.error)),a=this.getItemByObjectId(e);if(a&&(!i||s.length>1)){const t=await this._queryAttachments([e]);a.attachments=t[e]}return r})).catch((async r=>{this._logError("store:attachment-error","An error occurred.");const s={error:r,retry:()=>{this.failures.remove(s),this._queueAttachmentsOperation(e,t)},cancel:()=>this.failures.remove(s)};throw this.failures.add(s),this._attachmentsOperationQueue.remove(t),r}))}_queueEditOperation(e){return this._editOperationQueue.push(e),e().then((t=>(this._editOperationQueue.remove(e),t))).catch((t=>{this._logError("store:edit-error","An error occurred.");const r={error:t,retry:()=>{this.failures.remove(r),this._queueEditOperation(e)},cancel:()=>this.failures.remove(r)};throw this.failures.add(r),this._editOperationQueue.remove(e),t}))}_queueQueryOperation(e){return this._queryOperationQueue.push(e),e().then((t=>this._queryOperationQueue.includes(e)?t:[])).catch((t=>{this._logError("store:query-error","An error occurred.");const r={error:t,retry:()=>{this.failures.remove(r),this._queueQueryOperation(e)},cancel:()=>this.failures.remove(r)};return this.failures.add(r),[]})).then((t=>(this._queryOperationQueue.remove(e),t)))}};e([d()],A.prototype,"_attachmentsOperationQueue",void 0),e([d({readOnly:!0})],A.prototype,"_capabilities",null),e([d()],A.prototype,"_defaultOutFields",void 0),e([d()],A.prototype,"_editOperationQueue",void 0),e([d()],A.prototype,"_effectiveReturnZ",null),e([d()],A.prototype,"_effectiveReturnM",null),e([d({readOnly:!0})],A.prototype,"_layerWithAttachments",null),e([d({readOnly:!0})],A.prototype,"_layerWithAttachmentsEditing",null),e([d({readOnly:!0})],A.prototype,"_layerWithEditing",null),e([d({readOnly:!0})],A.prototype,"_layerWithRelationships",null),e([d()],A.prototype,"_loaded",void 0),e([d()],A.prototype,"_loadError",void 0),e([d()],A.prototype,"_loading",void 0),e([d()],A.prototype,"_objectIdCache",void 0),e([d()],A.prototype,"_queryOperationQueue",void 0),e([d({readOnly:!0})],A.prototype,"_relatedLayer",null),e([d({readOnly:!0})],A.prototype,"_relatedLayerCapabilities",null),e([d({readOnly:!0})],A.prototype,"_relatedLayerSupportsCacheHint",null),e([d()],A.prototype,"_relatedLayerSupportsQuery",null),e([d()],A.prototype,"_relatedLayerSupportsQueryRelated",null),e([d()],A.prototype,"_sortedFieldNames",null),e([d()],A.prototype,"_canUseRelatedLayer",null),e([d()],A.prototype,"attachmentsEnabled",void 0),e([d()],A.prototype,"canAddRelatedFeature",null),e([d({readOnly:!0})],A.prototype,"count",void 0),e([d()],A.prototype,"effectiveOutFields",null),e([d()],A.prototype,"effectiveTimeExtent",null),e([d()],A.prototype,"effectiveWhere",null),e([d({readOnly:!0})],A.prototype,"failures",void 0),e([d()],A.prototype,"filterGeometry",void 0),e([d()],A.prototype,"initialSize",void 0),e([d({readOnly:!0})],A.prototype,"itemCache",null),e([d()],A.prototype,"layer",void 0),e([d()],A.prototype,"layerView",null),e([d()],A.prototype,"objectIds",void 0),e([d()],A.prototype,"orderByFields",null),e([d()],A.prototype,"outFields",void 0),e([d({readOnly:!0})],A.prototype,"pageCache",void 0),e([d()],A.prototype,"pageSize",void 0),e([d({readOnly:!0})],A.prototype,"querying",null),e([d()],A.prototype,"relationship",null),e([d()],A.prototype,"relationshipConfig",void 0),e([d()],A.prototype,"relationshipIds",null),e([d()],A.prototype,"relationshipInfos",null),e([d()],A.prototype,"relationships",null),e([d()],A.prototype,"relatedRecordsEnabled",void 0),e([d()],A.prototype,"returnGeometry",void 0),e([d()],A.prototype,"returnZ",void 0),e([d()],A.prototype,"returnM",void 0),e([d()],A.prototype,"sortOrders",void 0),e([d({readOnly:!0})],A.prototype,"state",null),e([d()],A.prototype,"supportsAdd",null),e([d()],A.prototype,"supportsAddingAttachments",null),e([d()],A.prototype,"supportsAttachments",null),e([d()],A.prototype,"supportsCacheHint",null),e([d()],A.prototype,"supportsCacheHintQueryRelated",null),e([d()],A.prototype,"supportsDelete",null),e([d()],A.prototype,"supportsDeletingAttachments",null),e([d()],A.prototype,"supportsEditing",null),e([d()],A.prototype,"supportsM",null),e([d()],A.prototype,"supportsOrderBy",null),e([d()],A.prototype,"supportsPagination",null),e([d()],A.prototype,"supportsQuery",null),e([d()],A.prototype,"supportsQueryRelated",null),e([d()],A.prototype,"supportsResizeAttachments",null),e([d()],A.prototype,"supportsUpdate",null),e([d()],A.prototype,"supportsUpdateAttachments",null),e([d()],A.prototype,"supportsZ",null),e([d({readOnly:!0})],A.prototype,"syncing",null),e([d({readOnly:!0})],A.prototype,"syncingAttachmentEdits",null),e([d({readOnly:!0})],A.prototype,"syncingFeatureEdits",null),e([d()],A.prototype,"timeExtent",void 0),e([d()],A.prototype,"view",void 0),e([d()],A.prototype,"where",void 0),A=e([c("esri.widgets.FeatureTable.support.FeatureStore")],A);const I=A;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.31/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"../../symbols.js";import{isSome as r,equals as i}from"../../core/arrayUtils.js";import{createTask as a}from"../../core/asyncUtils.js";import o from"../../core/Collection.js";import{deprecatedProperty as s}from"../../core/deprecate.js";import n from"../../core/Error.js";import l from"../../core/Evented.js";import{isSerializable as c}from"../../core/JSONSupport.js";import{equalsShallow as h}from"../../core/lang.js";import u from"../../core/Logger.js";import{clamp as p}from"../../core/mathUtils.js";import{abortMaybe as m,destroyMaybe as d}from"../../core/maybe.js";import{EsriPromise as g}from"../../core/Promise.js";import{isAbortError as y,throwIfAborted as f,waitTick as v}from"../../core/promiseUtils.js";import w from"../../core/ReactiveMap.js";import{on as b,watch as F,syncAndInitial as _,initial as I}from"../../core/reactiveUtils.js";import{sqlAnd as P}from"../../core/sql.js";import{getMetersPerUnitForSR as S}from"../../core/unitUtils.js";import{property as C}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import{subclass as V}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as A}from"../../core/support/UpdatingHandles.js";import{union as O}from"../../geometry/geometryEngineAsync.js";import{projectWithZConversion as j}from"../../geometry/projection.js";import{isClockwise as M}from"../../geometry/support/coordsUtils.js";import{geographicToWebMercator as R}from"../../geometry/support/webMercatorUtils.js";import k from"../../layers/GraphicsLayer.js";import{searchImages as B}from"../../layers/orientedImagery/queries.js";import{calculateSuitabilities as L}from"../../layers/orientedImagery/core/bestImageUtils.js";import{createCoveragePolygon as G,computePolygonForInspection as x,resizePolygon as E,checkIfPolygonContainsSelectedPoint as H}from"../../layers/orientedImagery/core/coverageUtils.js";import{isConstantElevation as T,isElevationSource as D}from"../../layers/orientedImagery/core/ElevationSourceDefinitions.js";import{imageToWorld as z,imageToWorldPanoramic as U}from"../../layers/orientedImagery/transformations/imageToWorld.js";import N from"../../layers/orientedImagery/transformations/updateElevation.js";import{getElevationSampler as W}from"../../layers/orientedImagery/transformations/updateElevationUtils.js";import{getInitialAngle as q,convertPixelToHeadingPitch as $,pointToArray as J,getUpdateElevationProps as K,isElevationSampler as Q,getImageToWorldProperties as Z,getImageToWorldPanoramicProperties as X,getWorldToImageProperties as Y,convertHeadingPitchToSphereVertex as ee,or as te}from"../../layers/orientedImagery/transformations/utils.js";import{worldToImagePanoramic as re,worldToImage as ie}from"../../layers/orientedImagery/transformations/worldToImage.js";import{getFloorFilterClause as ae}from"../../layers/support/floorFilterUtils.js";import oe from"../../rest/support/AttachmentQuery.js";import{scale as se}from"../../views/draw/support/drawUtils.js";import{ViewEventPriorities as ne}from"../../views/input/InputManager.js";import le from"../PanoramicViewer.js";import{invalidCameraHeading as ce,sectorsInOrder as he,sectorsRadii as ue}from"./constants.js";import{crossSymbol as pe,crossSymbol3D as me,sourcePointSymbol as de,diamondSymbol as ge,diamondSymbol3D as ye,activeSourcePointSymbol as fe}from"./symbols.js";import{isNoAttachmentError as ve,getContentType as we,isTifOrMrf as be,filterOILLayerView as Fe,isSceneView as _e,isGraphic as Ie,calculateSegment as Pe,calculateDirection as Se}from"./utils.js";import Ce from"./components/ImageViewer.js";import Ve from"../../geometry/Point.js";import Ae from"../../geometry/SpatialReference.js";import Oe from"../../symbols/SimpleLineSymbol.js";import je from"../../geometry/Multipoint.js";import Me from"../../geometry/Polyline.js";import Re from"../../geometry/Polygon.js";const ke={click:"view-click",imageClick:"image-click",interactionHandles:"interaction-handles",footprintHandles:"footprint-handles"},Be=new Set(["JPG","JPEG"]),Le=/\.(\w+)$/,Ge=e=>"FA"===e;let xe=class extends(l.EventedMixin(g)){constructor(e){super(e),this.additionalFeatures=new o,this.additionalCameraLocations=new o,this.additionalFootprints=new o,this.bestFeatureAngle=0,this.bestFeatureCurrentFootprint=null,this.bestFeatureFootprint=null,this.coverageFrustums=new o,this.coveragePolygons=new o,this.currentBestFeature=null,this.currentBestFeatureLocation=null,this.currentCoverageVisible=!0,this.determineWorkflowForFeature=async(e,t,r)=>{const{currentBestFeature:i,selectedPoint:a,view:o}=this;if(o?.closePopup(),i&&a){this._initialCurrentCoverageUpdate=!0;try{await this._updatePointsAndPolygons(r),await this._loadImage(r)}catch(s){y(s)||(this.loadImageError(s),u.getLogger(this).error("#loadIImage()","error occured while loading image",s))}}},this.disabled=!1,this.displayMessage={key:"onLoadMessage",type:"info"},this.features=new o,this.isAdditionalCoverageVisible=!1,this.isAdditionalPointSourcesVisible=!1,this.layer=null,this.localPort=null,this.mapImageConversionToolState=!1,this.navigatorCurrentBestFeature=null,this.overlayedCameraLocations=new o,this.overlayedMapFeatures=new w,this.pointSources=new o,this.previousFeatureAngle=0,this.selectedPoint=null,this.shouldShowSelectedImage=!1,this.updateFootprint=async(e,t)=>{"image-loaded"===this.state&&await(this._adapter?.updateFootprint(e,t))},this.updateFootprintPanorama=async(e,t)=>{await(this._adapter?.updateFootprintPanorama(e,t))},this._adapter=null,this._highlightedFeatureHandle=null,this._imageViewer=new Ce,this._initialCurrentCoverageUpdate=!0,this._overlays=new k({listMode:"hide",internal:!0,elevationInfo:{mode:"absolute-height"}}),this._panoramicViewer=new le,this._referencePointOnGround=null,this._referencePointOnImage=null,this._sectorData=null,this._updatingHandles=new A,this._clickTask=null,this._crossSymbol=null,this.footprintExtent=null,this._featureChangedTask=null,this._openPopupTask=null,this._suitabilities=null,this._transformController=new AbortController,this._updateFootprintTask=null,this.highlight=e=>{if(!this._overlaysView)return;this.removeHighlight();const t=this.additionalFootprints.find((({attributes:{imageID:t}})=>t===Number(e)));this._highlightedFeatureHandle=t?this._overlaysView?.highlight(t):null},this.loadImageFromSource=async(e,t)=>this._updatingHandles.addPromise(this._loadImageFromSourceInternal(e,t)),this.loadImageViewer=e=>{this._imageViewer.container=e},this.loadPanoramicViewer=e=>{this._panoramicViewer.container=e},this.removeHighlight=()=>this._highlightedFeatureHandle?.remove(),this.toggleImageAttributes=()=>{m(this._openPopupTask),this._openPopupTask=a((async e=>{const{currentBestFeature:r,popupEnabled:i,layer:a,view:o}=this;if(o?.closePopup(),!(o&&r&&i&&a))return;const{attributes:s,geometry:n}=r,l=new t({geometry:n,attributes:s.toJSON(),layer:a});f(e),await o.openPopup({features:[l],location:s.location.clone()})}))},this._createViewClickHandle=()=>{if(this.removeHandles(ke.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,ne.WIDGET),ke.click)},this._createImageClickHandle=()=>{this.removeHandles(ke.imageClick);const{mapImageConversionToolState:e,mode:t,activeViewer:r,currentBestFeature:i,footprintExtent:o}=this,s=r?.imageSize;if(!(e&&"none"!==t&&s&&o&&i))return;r.clickAction="pixel-location";let n=null;const l=b((()=>r),"pixel-location",(e=>{this.plotReferencePointOnImage(e),n?.abort(),n=a((async r=>{if(!e)return;const a=await this.getMapPoint(e,{feature:i,imageSize:s,mode:t}).then((e=>{const t=this.view?.spatialReference;return te(!t,e.spatialReference.equals(t))?e:j(e,t)}));f(r),this.plotReferencePointOnGround(a)}))}));this.addHandles(l,ke.imageClick)},this._getImageSourceFromAttachment=async(e,t,r)=>{const i=new oe({objectIds:[t]}),a=await e.queryAttachments(i,r),o=a[`${t}`]?.[0],s=o?.url;if(!s)throw new n("NoAttachmentError","no attachments found",{[e.objectIdField]:t,layer:e});return{datasetFormat:o.contentType.split("/")[1].toUpperCase(),url:s}},this._loadAdapter=async e=>{const{view:t}=this;if(t)switch(t.type){case"2d":{const{default:t}=await import("./adapters/OrientedImageryViewerViewModelAdapter2D.js");f(e),this._adapter=new t(this);break}case"3d":{const{default:t}=await import("./adapters/OrientedImageryViewerViewModelAdapter3D.js");f(e),this._adapter=new t(this);break}}else this._adapter=null},this._loadImage=async e=>{const{currentBestFeature:t,layer:r,mode:i}=this;if(this.clearGraphics(),!r||!t||"none"===i)return;const{attributes:a}=t,{imagePath:o,imageRotation:s,cameraHeading:n,cameraRoll:l,cameraPitch:c,objectId:h,cameraOrientation:p,location:m}=a,d=(l??0)+(s??0),g=m.spatialReference.isWGS84&&4!==p?.type?R(m):new Ve(m);let v=o;if(Ge(o))try{v=await this._getImageSourceFromAttachment(r,h,e)}catch(w){if(y(w))return;return ve(w)?(u.getLogger(this).error(w),void this.setMessage("noAttachment","error",`${r.objectIdField}: ${h}`)):(u.getLogger(this).error(w,{[r.objectIdField]:h,layer:r}),void this.setMessage("imageLoadError","error",`query-attachments-failed:${r.objectIdField} ${h}`))}try{await this.loadImageFromSource(v,{imageRotation:d,options:e,pitch:c,yaw:n,mode:i,cameraLocation:g}),f(e),await this.transformAndPlotSelectedLocation(e)}catch(w){y(w)||this.loadImageError(w)}},this._loadImageFromSourceInternal=async(e,t)=>{const{mode:r,imageRotation:i,options:a}=t,o="string"==typeof e,s=o?e:e.url,{origin:n,pathname:l,searchParams:c}=new URL(s);let h=o?l.match(Le)?.[1]??"":e.datasetFormat;if(!h){const e=await we(s,{...t.options});e&&(h=e.split("/")[1]),h??="UNKNOWN FORMAT"}switch(r){case"default":this._imageViewer.imageSource={datasetFormat:h.toUpperCase(),url:`${n}${l}`},this._imageViewer.customParameters=Object.fromEntries(c),this._imageViewer.imageRotation=i??0,await this._imageViewer.loadImage(a);break;case"panoramic":if(Be.has(h.toUpperCase())){const{selectedPoint:e}=this,{pitch:r,yaw:i,cameraLocation:o,viewAngle:n}=t;this._panoramicViewer.imageSource=s;let l=i??0;"number"==typeof n?l=n-l:o&&e&&(l=await q(o,e)-l),this._panoramicViewer.pitch=r??0,this._panoramicViewer.yaw=l,await this._panoramicViewer.loadImage(a)}else this.setMessage("unsupportedPanoramicImageryError","error",void 0,{datasetFormat:h});break}},this._mapImageConversionToolViewClickHandler=e=>{e.stopPropagation(),e.preventDefault(),e.mapPoint&&this.plotMapPoint(e.mapPoint)},this._viewClickHandler=e=>{this._clickTask?.abort(),this._clickTask=a((async t=>{const{pointerType:r,button:i,mapPoint:a}=e;if(("mouse"!==r||0===i)&&a)return e.stopPropagation(),e.preventDefault(),this._updatingHandles.addPromise(this.loadBestImage(a,{signal:t}))}))},this.plotSelectedPointOnImage=async(e,r)=>{if(await v(r),!e)return;const i=new Ve({...c(e)?e.toJSON():e});if("default"===this.mode)i.x-=.5,i.y=.5-i.y,i.spatialReference=this._imageViewer.imageRenderer.spatialReference.clone(),this._crossSymbol=new t({geometry:i,symbol:pe}),this._imageViewer.addGraphic(this._crossSymbol,0);else if("panoramic"===this.mode){const{imageSize:r}=this._panoramicViewer;if(!r)return;const[i,a]=r,{heading:o,pitch:s}=$(e,i,a),n=ee(o,s);this._crossSymbol=new t({geometry:new Ve(n,Ae.WebMercator),symbol:me}),this._panoramicViewer.addGraphic(this._crossSymbol,0)}},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.selectBestFeature=this.selectBestFeature.bind(this)}initialize(){this.addHandles([F((()=>this.view),(()=>{this.load()}),_),F((()=>this.view?.map),((e,t)=>{t?.layers.remove(this._overlays),e?.layers.add(this._overlays)}),I),F((()=>this.view?.map?.allLayers?.length),(e=>{e&&this.view?.map?.layers.reorder(this._overlays,e-1)}),I),F((()=>[this.state,this.mapImageConversionToolState,this.view]),(()=>{this._createViewClickHandle(),this._createImageClickHandle()}),_),F((()=>this.bestFeatureAngle),((e,t)=>{this.previousFeatureAngle=t??0}),_),F((()=>this.currentBestFeature),(async(e,t)=>{m(this._featureChangedTask),this._featureChangedTask=a((async r=>this.determineWorkflowForFeature.apply(this,[e,t,{signal:r}]))),await this._featureChangedTask.promise}),{sync:!0}),F((()=>this.mode),(e=>{switch(this.removeHandles(ke.interactionHandles),e){case"default":this.addHandles(F((()=>this._imageViewer.imagePointsInView),(e=>{e&&(m(this._updateFootprintTask),this._updateFootprintTask=a((async t=>{await this.updateFootprint(e,{signal:t})})))}),{..._,equals:(e,t)=>i(e,t,h)}),ke.interactionHandles);break;case"panoramic":this.addHandles(F((()=>{const{currentBestFeature:e,state:t}=this,{imageSize:r,vfov:i,hfov:a,pitch:o,yaw:s}=this._panoramicViewer;return e&&r&&"image-loading"!==t?[i,a,s,o]:null}),(e=>{if(!e||"image-loading"===this.state)return;const[t,r,i,o]=e;m(this._updateFootprintTask),this._updateFootprintTask=a((async e=>{await this.updateFootprintPanorama({verticalFieldOfView:t,horizontalFieldOfView:r,yaw:i,pitch:o},{signal:e})}))}),{..._,equals:(e,t)=>i(e,t,h)}),ke.interactionHandles)}}),_),F((()=>[this.brightness,this.contrast,this.sharpness]),(()=>{const{_imageViewer:e,brightness:t,contrast:r,mode:i,sharpness:a}=this;"default"===i&&(e.brightness=t,e.contrast=r,e.sharpness=a)}),_)])}destroy(){this._updateFootprintTask=m(this._updateFootprintTask),this._clickTask=m(this._clickTask),this.coverageFrustums.destroy(),this.coveragePolygons.destroy(),this.pointSources.destroy(),this.additionalFootprints.destroy(),this.additionalCameraLocations.destroy(),this.bestFeatureFootprint=d(this.bestFeatureFootprint),this.bestFeatureCurrentFootprint=d(this.bestFeatureCurrentFootprint),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 activeViewer(){const{_imageViewer:e,_panoramicViewer:t,mode:r}=this;switch(r){case"default":return e;case"panoramic":return t;default:return null}}get brightness(){return this._get("brightness")??0}set brightness(e){this._set("brightness",p(e,-10,10))}get contrast(){return this._get("contrast")??0}set contrast(e){this._set("contrast",p(e,-10,10))}get featureCount(){return this.features?.length??0}get imageGalleryEnabled(){return be(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 invalidCameraHeading(){return this.currentBestFeature?.attributes?.cameraHeading===ce}get imagePointsInView(){const{mode:e,_imageViewer:t}=this;return"default"===e?t.imagePointsInView:null}get layerView(){const{layer:e,view:t}=this;if(e&&t)return t.allLayerViews.find(Fe(e))}get layerFloorFilterClause(){const{layerView:e}=this;return e?ae(e):null}get mode(){const e=this.currentBestFeature?.attributes;if(!e)return"none";const{horizontalFieldOfView:t,isSpherical:r}=e;return 360===t||r?"panoramic":"default"}get popupEnabled(){return!0===this.layer?.popupEnabled}get referencePoint(){return this._referencePointOnGround?.geometry}get sectorData(){const{_sectorData:e}=this;return e?he.map((t=>e[t])):null}get sharpness(){return this._get("sharpness")??0}set sharpness(e){this._set("sharpness",p(e,0,1))}get state(){const{mode:e,disabled:t}=this;if(t)return"disabled";if(!this.isFulfilled())return"loading";if(this.isRejected())return"error";if(this._updatingHandles.updating)return"image-loading";if("error"===this.displayMessage?.type)return"image-load-error";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 a=e.trim();return be(a)?{url:a,objectId:t,rotation:(r??0)+(i??0)}:null})).filter(r)):null}set view(e){this._set("view",e)}get _overlaysView(){return this.view?.layerViews.find((({layer:e})=>e===this._overlays))}filterByFootprints(e,t){const r=[],i=[],a=[];return e.forEach((e=>{const{layer:{coveragePercent:o},attributes:s}=e;let n;const l=S(e.geometry.spatialReference);s.cameraHeight/=l,s.farDistance/=l,s.nearDistance/=l,T(s.elevationSource)&&(s.elevationSource.constantElevation/=l);const{polygon:c,frustum:h}=G(s);if(n=c.clone(),s.isInspection&&(n=x(s)),o&&(n=E(n,o)),H(n,t)){a.push(e);const{geometry:t,objectId:o,cameraHeight:n,cameraHeading:l}=s,u=t.clone();u.z=n,u.imageID=o,this.pointSources.push(u),l!==ce&&(r.push(c),h&&i.push(h))}})),{features:a,polygons:r,frustums:i}}handleSectorClick(e){if(isNaN(e))return;const t=this._sectorData?.[he[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 load(e){return this.addResolvingPromise(this._loadAdapter(e).catch((e=>{if(!y(e))throw e}))),this}async loadBestImage(e,t){return this.view?.closePopup(),this.displayMessage=null,this.selectedPoint=e.spatialReference.isGeographic?R(e):e.clone(),this.features.removeAll(),this.currentBestFeature=null,this.additionalFeatures.removeAll(),this.additionalFootprints.removeAll(),this.additionalCameraLocations.removeAll(),this.bestFeatureCurrentFootprint=d(this.bestFeatureCurrentFootprint),this._overlays?.removeAll(),this._fetchFeaturesWithController(e,t)}loadImageError(e){u.getLogger(this).error("oriented-imagery-viewer:load-image",e),this.setMessage("imageLoadError","error",e.message)}async overlayCameraLocations(e){const{activeViewer:r,currentBestFeature:i,overlayedCameraLocations:a,layer:o,mode:s,state:n}=this,l=r?.imageSize;if(!l||!i||!o||"none"===s||n.includes("loading"))return;const{polygon:c}=G(i.attributes);if(r.removeManyGraphics(a.toArray()),a.removeAll(),e){const{features:e}=await o.queryFeatures({where:`${o.objectIdField} <> ${i.attributes.objectId}`,geometry:c,returnGeometry:!0,outFields:[o.objectIdField]}),n=await Promise.all(e.map((async e=>{const{attributes:r,geometry:a}=e,o=await this.getPixels(a,{feature:i,imageSize:l,mode:s}),n=de.clone();return n.outline=new Oe({color:[0,0,0],width:1}),new t({attributes:r,symbol:n,geometry:o})})));a.addMany(n),r.addManyGraphics(a.toArray())}}overlayGraphicsOnImage(e,t){this.overlayedMapFeatures.set(e,t),this.activeViewer?.addManyGraphics(t.toArray())}async overlayMapFeatures(e,i=!1){const{activeViewer:a,currentBestFeature:s,mode:n,state:l}=this,c=a?.imageSize;if(!c||!s||"none"===n||l.includes("loading"))return;const{polygon:h}=G(s.attributes),{features:u}=await e.queryFeatures({geometry:h,returnGeometry:!0,outFields:[e.objectIdField]}),p=new o((await Promise.all(u.map((async r=>{const{attributes:a,geometry:o}=r,l=r.symbol?.clone()??e.renderer?.getSymbol(r).clone();switch(o?.type){case"point":{const r=await this.getPixels(o,{feature:s,imageSize:c,mode:n});return new t({attributes:a,layer:e,symbol:l,geometry:r,visible:e.visible&&i})}case"polygon":{const{rings:r,spatialReference:h}=o,u=r.map((e=>e.map((([e,t,r])=>new Ve({x:e,y:t,z:r,spatialReference:h}))))),p=await Promise.all(u.map((async e=>this.getPixels(e,{feature:s,imageSize:c,mode:n}).then((e=>e.map(J))))));return new t({attributes:a,layer:e,symbol:l,geometry:new Re({rings:p,spatialReference:Ae.WebMercator}),visible:e.visible&&i})}case"polyline":{const{paths:r,spatialReference:h}=o,u=r.map((e=>e.map((([e,t,r])=>new Ve({x:e,y:t,z:r,spatialReference:h}))))),p=await Promise.all(u.map((async e=>this.getPixels(e,{feature:s,imageSize:c,mode:n}).then((e=>e.map(J))))));return new t({attributes:a,layer:e,symbol:l,geometry:new Me({paths:p,spatialReference:Ae.WebMercator}),visible:e.visible&&i})}case"multipoint":{const{points:r,spatialReference:h}=o,u=r.map((([e,t,r])=>new Ve({x:e,y:t,z:r,spatialReference:h}))),p=await this.getPixels(u,{feature:s,imageSize:c,mode:n}).then((e=>e.map(J)));return new t({attributes:a,layer:e,symbol:l,geometry:new je({points:p,spatialReference:Ae.WebMercator}),visible:e.visible&&i})}}return null})))).filter(r));this.overlayGraphicsOnImage(`${e.id}`,p)}async getPixels(e,t){const{imageSize:r,mode:i}=t,a=(await this.worldToImage(Array.isArray(e)?e:[e])).map((e=>{if("default"===i)return new Ve({x:e.x-.5,y:.5-e.y,spatialReference:Ae.WebMercator});const[t,a]=r,{heading:o,pitch:s}=$(e,t,a),n=ee(o,s);return new Ve(n,Ae.WebMercator)}));return Array.isArray(e)?a:a[0]}async getMapPoint(e,t){const{feature:r,mode:i,imageSize:a}=t,{elevationSample:o,attributes:s}=r,{elevationSource:n,location:l,elevation:c,cameraHeight:h}=s;let u=l.clone();u.spatialReference.isGeographic&&(u=await j(u,Ae.WebMercator));const p=await K(c??(l.z??0)-h,{elevationSample:o,elevationSource:n,extent:this.footprintExtent});let m;if("elevationSample"in p&&Q(p.elevationSample)&&(r.elevationSample=p.elevationSample),"default"===i){const t=Z(s,a[0],a[1]);m=await z(Array.isArray(e)?e:[e],{...t,cameraLocation:u},p)}else{const t=X(s,a[0],a[1]);m=await U(Array.isArray(e)?e:[e],{...t,cameraLocation:u},p)}return Array.isArray(e)?m:m[0]}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:new Ve({...e.toJSON()}),symbol:ge}),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.clearReferencePointOnImage(),this.mode){case"default":{const r=c(e)?e.toJSON():e;r.x-=.5,r.y=.5-r.y,this._referencePointOnImage=new t({geometry:new Ve({spatialReference:this._imageViewer.imageRenderer.spatialReference.clone(),...r}),symbol:ge}),this._imageViewer.addGraphic(this._referencePointOnImage,0);break}case"panoramic":{const{imageSize:r}=this._panoramicViewer;if(!r)return;const[i,a]=r,{heading:o,pitch:s}=$(e,i,a),n=ee(o,s);this._referencePointOnImage=new t({geometry:new Ve(n,Ae.WebMercator),symbol:ye}),this._panoramicViewer.addGraphic(this._referencePointOnImage,0);break}}}removeAllOverlayMapFeatures(){this.overlayedMapFeatures.forEach((e=>{this._imageViewer.removeManyGraphics(e.toArray())})),this.overlayedMapFeatures.clear()}removeOverlayedGraphicsOnImage(e){const t=this.overlayedMapFeatures.get(e);t?.length&&(this.activeViewer?.removeManyGraphics(t.toArray()),this.overlayedMapFeatures.delete(e))}resetImage(){switch(this.setMessage("onLoadMessage","info"),this.mode){case"default":this._imageViewer.clearImage(),this._imageViewer.clearGraphics();break;case"panoramic":this._panoramicViewer.clearGraphics()}this._clickTask=m(this._clickTask)}async searchBestImage(e,t){try{const r=await B(e,t);r&&await this._processFeatureResponse(r,e.point,{signal:t?.signal})}catch(r){y(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.additionalCameraLocations.forEach((t=>{t.visible=e}))}setAdditionalCoverageVisibility(e){this.additionalFootprints.forEach((t=>{t.visible=e}))}setCurrentCoverageVisibility(e){this.bestFeatureCurrentFootprint&&(this.bestFeatureCurrentFootprint.visible=e),this.currentBestFeatureLocation&&(this.currentBestFeatureLocation.visible=e)}setMapImageConversionToolState(e){this.mapImageConversionToolState=e}toggleAllOverlayMapFeatures(e){this.overlayedMapFeatures.forEach((t=>{this._toggleVisiblity(t,e)}))}toggleOverlayMapFeatures(e,t){const r=this.overlayedMapFeatures.get(e);r&&this._toggleVisiblity(r,t)}async transformAndPlotReferencePointOnImage(e){const{selectedLocation:t,options:r}=e;let i=!1,a=!1;const o=this.bestFeatureFootprint?.geometry;switch(o?.type){case"polygon":{const e=t.spatialReference.equals(o.spatialReference)?t:await j(t,o.spatialReference);i=o.contains(e);break}case"mesh":{const e=t.spatialReference.equals(o.spatialReference)?t:await j(t,o.spatialReference);a=o.extent.contains(e);break}}if(!i&&!a)return void this.clearReferencePointOnImage();const s=await this.worldToImage(t,r);if(s)return f(r),this.plotReferencePointOnImage(s),{x:s.x,y:s.y};this.clearReferencePointOnImage()}updateSuitabilities(e){e.sort(((e,t)=>e.suitability-t.suitability)),this._suitabilities=e;const t=this._suitabilities.map((({feature:e})=>e));this._initialCurrentCoverageUpdate=!0,this._updateFeatures(t),this._groupFeaturesBySectors()}async _fetchFeatures(e,t){if(!this.view)return;const r=this.layer;if(r){const i={include:r},a=this.view.toScreen(e);if(!a)return;const o=await this.view.hitTest(a,i);return this._processHitTestResults(r,o,t)}}async _fetchFeaturesWithController(e,t){try{await this._fetchFeatures(e,t)}catch(r){if(y(r))return;this.setMessage("imageLoadError","error"),u.getLogger(this).error("error occurred while fetching features",r)}}_groupFeaturesBySectors(){const{_suitabilities:e,additionalFeatures:t,currentBestFeature:r,features:i,invalidCameraHeading:a}=this;if(!e||!t||!r||!i||a)return void(this._sectorData=null);this._sectorData={};for(const c of he)this._sectorData[c]=new o;const s=e.map(((e,t)=>({...e,featureIndex:t})));s.sort(((e,t)=>e.trueSuitability-t.trueSuitability));const n=s.map((({distance:e})=>e)),l=Math.max(...n);s.forEach((e=>{const{distance:t,angle:r,featureIndex:a}=e,o=t/l*ue[2],s=Pe(t,l),n=Se(r);if(!this._sectorData)return;const c=ue[3]+o*Math.sin(r*Math.PI/180),h=ue[3]+o*Math.cos(r*Math.PI/180);let u;const p=i.at(a),m=p===this.currentBestFeature,d=this.currentBestFeature?.attributes.cameraPitch&&this.currentBestFeature?.attributes.cameraPitch<5;if(m&&d)u=-90;else{const e=c-ue[3],t=h-ue[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 g=""===s?n:`${s}_${n}`;m&&(u===this.bestFeatureAngle?this.previousFeatureAngle=u:this.bestFeatureAngle=u,this.navigatorCurrentBestFeature=d?null:{x:c,y:h,direction:n});const y=this._sectorData[g];y.add({angle:r,featureIndex:a,x:c,y:h,objectID:p.attributes.objectId,sector:g,featureIndexInSector:y.length})}))}async _processFeatureResponse(e,t,r){const{features:i}=e;if(!i?.length)return this.setMessage("noImageError","error"),void(this.currentBestFeature=null);this.coveragePolygons.removeAll(),this.coverageFrustums.removeAll(),this.pointSources.removeAll();const{features:a,polygons:o,frustums:s}=this.filterByFootprints(i,t);if(!a.length)return this.setMessage("noImageError","error"),void(this.currentBestFeature=null);let n;if(this.coveragePolygons.addMany(o),this.coverageFrustums.addMany(s),o[0]){let e=new Re({spatialReference:o[0].spatialReference});for(const r of o)e=await O(e,r);const t=[];for(const{geometry:r}of a)e.contains(r)||t.push([r.x,r.y]);if(t.sort(((e,t)=>+M([e,t]))),e.addRing(t),this.footprintExtent=se(e.extent,2,2),this.view?.supportsGround)try{n=await this.view.map.ground.createElevationSampler(this.footprintExtent,r)}catch(l){y(l)||u.getLogger(this).error(l)}}if((n||a[0].attributes.elevationSource)&&this.footprintExtent){const e=a[0].attributes.elevationSource;D(e)&&!n&&(n=await W({extent:this.footprintExtent,lod:e.lod,url:e.url,rasterFunction:e.rasterFunction}));const r=await K((a[0].attributes.location.z??0)-a[0].attributes.cameraHeight,{elevationSample:n,elevationSource:e,extent:this.footprintExtent}),[i,...o]=await N([t,...a.map((e=>e.attributes.geometry.clone()))],r);a[0].elevationSample=n??r.elevationSample,t.elevation=i.z,a.forEach(((e,t)=>{e.attributes.elevation=o[t].z}))}a[0].elevationSample&&a.forEach((e=>{e.elevationSample=a[0].elevationSample})),this._suitabilities=L({features:a,selectedPoint:t,camera:_e(this.view)?this.view.camera:null,currentImage:this.currentBestFeature}),this.updateSuitabilities(this._suitabilities)}async _processHitTestResults(e,t,r){const{screenPoint:i,results:[a]}=t,o="graphic"===a?.type&&this.shouldShowSelectedImage,s=a?.mapPoint??this.view?.toMap(i);if(!s)return;const{layerFloorFilterClause:n}=this,l=P("1=1",P(e.definitionExpression,n)),c=s.spatialReference.isGeographic?1:S(s.spatialReference),h={layerInstanceOrURL:e,point:s,queryParams:{where:l,maximumDistance:e.maximumDistance?e.maximumDistance/c:void 0,objectIds:o?[a.graphic.getAttribute(e.objectIdField)]:void 0}};await this.searchBestImage(h,r)}_toggleVisiblity(e,t){e.forEach((e=>{e.visible=t}))}_updateFeatures(e){if(!e.length)return this.currentBestFeature=null,void this.additionalFeatures.removeAll();this.features.removeAll(),this.features.addMany(e),e.length>1?this.additionalFeatures.addMany(e.slice(1)):this.additionalFeatures.removeAll(),this.currentBestFeature=e[0]}async _updatePointsAndPolygons(e){const{pointSources:r,currentBestFeature:i,currentCoverageVisible:a,isAdditionalPointSourcesVisible:o}=this;if(i&&(this.additionalFootprints.removeAll(),this.additionalCameraLocations.removeAll(),this.bestFeatureCurrentFootprint&&(this.bestFeatureCurrentFootprint.destroy(),this.bestFeatureCurrentFootprint=null,this.bestFeatureFootprint=null),!this.invalidCameraHeading)){await(this._adapter?.createFootprints(e)),f(e);for(const e of r)e.imageID===i.attributes.objectId?this.currentBestFeatureLocation=new t({attributes:{imageID:e.imageID},geometry:e,symbol:fe,visible:a}):this.additionalCameraLocations.push(new t({attributes:{imageID:e.imageID},geometry:e,symbol:de,visible:o}))}}_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-ue[3],i=e.y-ue[3],a=i/Math.sqrt(t**2+i**2);let o=180*Math.acos(a)/Math.PI;(t<0&&i<0||t<0&&i>0)&&(o*=-1),r=o}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()}clearReferencePointOnImage(){this._referencePointOnImage&&(this._imageViewer.removeGraphic(this._referencePointOnImage),this._panoramicViewer.removeGraphic(this._referencePointOnImage),this._referencePointOnImage=d(this._referencePointOnImage))}plotReferencePoint(e){"mapPoint"in e?this.plotReferencePointOnGround(e.mapPoint):this.plotReferencePointOnGround(e)}setMessage(e,t,r,i){this.displayMessage={key:e,type:t,data:r,map:i}}async transformAndPlotSelectedLocation(e){const{currentBestFeature:t,invalidCameraHeading:r,selectedPoint:i,state:a}=this;if(this._crossSymbol&&(this._panoramicViewer.removeGraphic(this._crossSymbol),this._imageViewer.removeGraphic(this._crossSymbol),this._crossSymbol=d(this._crossSymbol)),!i||!t||"image-loaded"!==a||r)return;let o;try{o=await this.worldToImage(i,e),f(e),await this.plotSelectedPointOnImage(o,e)}catch(s){y(s)||u.getLogger(this).error("failed to transform map point to pixel, cross symbol will not be plotted on image",{error:s,selectedPoint:i,feature:t})}}async worldToImage(e,t){const{footprintExtent:r}=this,{imageSize:i}=this.activeViewer;if("none"===this.mode||!this.currentBestFeature||!i||!r)return;const{attributes:{location:a,elevationSource:o,cameraHeading:s,elevation:n,cameraHeight:l},elevationSample:c}=this.currentBestFeature;let h=a.clone();const u=await K(n??(a.z??0)-l,{elevationSample:c,elevationSource:o});this.currentBestFeature.elevationSample=u.elevationSample;const p=Array.isArray(e)?e:[e];let m,d=await Promise.all(p.map((e=>new Promise((t=>{if(!e.hasZ)return t(N(e,u));t(e)})))));if(a.spatialReference.isGeographic&&(h=await j(h,Ae.WebMercator,t)),d=await Promise.all(d.map((async e=>h.spatialReference.equals(e.spatialReference)?e:await j(e,h.spatialReference,t)))),f(t),"panoramic"===this.mode)m=re(d,{imageHeight:i[1],imageWidth:i[0],cameraHeading:s,cameraLocation:h});else{const e=Y(this.currentBestFeature.attributes,i[0],i[1]);m=ie(d,{...e,cameraLocation:h})}return Array.isArray(e)?m:m[0]}updateCurrentCoveragePolygon(e){const{additionalFootprints:r,additionalCameraLocations:i,currentBestFeature:a,currentBestFeatureLocation:o,currentCoverageVisible:s,selectedPoint:n,view:l,_adapter:c}=this,{attributes:{objectId:h},elevationSample:u}=a;if(this._initialCurrentCoverageUpdate){if(this._overlays?.removeAll(),this._initialCurrentCoverageUpdate=!1,this.bestFeatureCurrentFootprint=d(this.bestFeatureCurrentFootprint),e&&!this.invalidCameraHeading&&(e.visible=s,this.bestFeatureCurrentFootprint=e),l){const e=[...r,...i,this.bestFeatureCurrentFootprint,o].filter(Ie);l.supportsGround&&u&&c?.updateGroundElevation&&c.updateGroundElevation(e,u),n&&e.push(new t({geometry:n.clone(),symbol:pe.clone(),attributes:{imageID:h}})),this._overlays.graphics.addMany(e)}}else if(l){if(this.invalidCameraHeading)return;this.bestFeatureCurrentFootprint&&(this._overlays?.remove(this.bestFeatureCurrentFootprint),this.bestFeatureCurrentFootprint=d(this.bestFeatureCurrentFootprint));const t=this.bestFeatureCurrentFootprint&&this._overlays?this._overlays.graphics.indexOf(this.bestFeatureCurrentFootprint):-1;e&&(this.bestFeatureCurrentFootprint=e,l?.supportsGround&&u&&c?.updateGroundElevation&&c.updateGroundElevation([e],u),e.visible=this.currentCoverageVisible,this._overlays?.graphics.add(this.bestFeatureCurrentFootprint,t>=0?t:this._overlays.graphics.length-1))}}};e([C()],xe.prototype,"activeLayer",null),e([C({readOnly:!0})],xe.prototype,"activeViewer",null),e([C()],xe.prototype,"additionalFeatures",void 0),e([C({type:o.ofType(t)})],xe.prototype,"additionalCameraLocations",void 0),e([C({type:o.ofType(t)})],xe.prototype,"additionalFootprints",void 0),e([C()],xe.prototype,"bestFeatureAngle",void 0),e([C()],xe.prototype,"bestFeatureCurrentFootprint",void 0),e([C({type:t})],xe.prototype,"bestFeatureFootprint",void 0),e([C({type:Number})],xe.prototype,"brightness",null),e([C({type:Number})],xe.prototype,"contrast",null),e([C()],xe.prototype,"coverageFrustums",void 0),e([C()],xe.prototype,"coveragePolygons",void 0),e([C()],xe.prototype,"currentBestFeature",void 0),e([C()],xe.prototype,"currentBestFeatureLocation",void 0),e([C()],xe.prototype,"currentCoverageVisible",void 0),e([C({json:{write:!1}})],xe.prototype,"determineWorkflowForFeature",void 0),e([C()],xe.prototype,"disabled",void 0),e([C()],xe.prototype,"displayMessage",void 0),e([C({readOnly:!0})],xe.prototype,"featureCount",null),e([C()],xe.prototype,"features",void 0),e([C({readOnly:!0})],xe.prototype,"imageGalleryEnabled",null),e([C({readOnly:!0})],xe.prototype,"imageLoaded",null),e([C({readOnly:!0})],xe.prototype,"invalidCameraHeading",null),e([C()],xe.prototype,"imagePointsInView",null),e([C()],xe.prototype,"isAdditionalCoverageVisible",void 0),e([C()],xe.prototype,"isAdditionalPointSourcesVisible",void 0),e([C()],xe.prototype,"layer",void 0),e([C()],xe.prototype,"layerView",null),e([C({readOnly:!0})],xe.prototype,"layerFloorFilterClause",null),e([C({type:Number})],xe.prototype,"localPort",void 0),e([C()],xe.prototype,"mapImageConversionToolState",void 0),e([C({readOnly:!0,value:"none"})],xe.prototype,"mode",null),e([C()],xe.prototype,"navigatorCurrentBestFeature",void 0),e([C({type:o.ofType(t)})],xe.prototype,"overlayedCameraLocations",void 0),e([C()],xe.prototype,"overlayedMapFeatures",void 0),e([C()],xe.prototype,"pointSources",void 0),e([C({readOnly:!0})],xe.prototype,"popupEnabled",null),e([C()],xe.prototype,"previousFeatureAngle",void 0),e([C()],xe.prototype,"referencePoint",null),e([C({readOnly:!0})],xe.prototype,"sectorData",null),e([C()],xe.prototype,"selectedPoint",void 0),e([C({type:Number})],xe.prototype,"sharpness",null),e([C()],xe.prototype,"shouldShowSelectedImage",void 0),e([C({readOnly:!0})],xe.prototype,"state",null),e([C({readOnly:!0})],xe.prototype,"thumbnails",null),e([C()],xe.prototype,"updateFootprint",void 0),e([C()],xe.prototype,"updateFootprintPanorama",void 0),e([C({value:null})],xe.prototype,"view",null),e([C()],xe.prototype,"_adapter",void 0),e([C()],xe.prototype,"_highlightedFeatureHandle",void 0),e([C()],xe.prototype,"_imageViewer",void 0),e([C()],xe.prototype,"_initialCurrentCoverageUpdate",void 0),e([C()],xe.prototype,"_overlays",void 0),e([C({readOnly:!0})],xe.prototype,"_overlaysView",null),e([C()],xe.prototype,"_panoramicViewer",void 0),e([C()],xe.prototype,"_referencePointOnGround",void 0),e([C()],xe.prototype,"_referencePointOnImage",void 0),e([C()],xe.prototype,"_sectorData",void 0),e([C({readOnly:!0})],xe.prototype,"_updatingHandles",void 0),e([C()],xe.prototype,"footprintExtent",void 0),xe=e([V("esri.widgets.OrientedImageryViewer.OrientedImageryViewerViewModel")],xe);const Ee=xe;export{Ee as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import"../../geometry.js";import t from"../../Graphic.js";import"../../symbols.js";import{isSome as r,equals as i}from"../../core/arrayUtils.js";import{createTask as a}from"../../core/asyncUtils.js";import o from"../../core/Collection.js";import{deprecatedProperty as s}from"../../core/deprecate.js";import n from"../../core/Error.js";import l from"../../core/Evented.js";import{isSerializable as c}from"../../core/JSONSupport.js";import{equalsShallow as h}from"../../core/lang.js";import u from"../../core/Logger.js";import{clamp as p}from"../../core/mathUtils.js";import{abortMaybe as m,destroyMaybe as d}from"../../core/maybe.js";import{EsriPromise as g}from"../../core/Promise.js";import{isAbortError as y,throwIfAborted as f,waitTick as v}from"../../core/promiseUtils.js";import w from"../../core/ReactiveMap.js";import{on as b,watch as F,syncAndInitial as _,initial as I}from"../../core/reactiveUtils.js";import{sqlAnd as P}from"../../core/sql.js";import{getMetersPerUnitForSR as S}from"../../core/unitUtils.js";import{property as C}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import{subclass as V}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as A}from"../../core/support/UpdatingHandles.js";import{union as O}from"../../geometry/geometryEngineAsync.js";import{projectWithZConversion as j}from"../../geometry/projection.js";import{isClockwise as M}from"../../geometry/support/coordsUtils.js";import{geographicToWebMercator as R}from"../../geometry/support/webMercatorUtils.js";import k from"../../layers/GraphicsLayer.js";import{searchImages as B}from"../../layers/orientedImagery/queries.js";import{calculateSuitabilities as L}from"../../layers/orientedImagery/core/bestImageUtils.js";import{createCoveragePolygon as G,computePolygonForInspection as x,resizePolygon as E,checkIfPolygonContainsSelectedPoint as H}from"../../layers/orientedImagery/core/coverageUtils.js";import{isConstantElevation as T,isElevationSource as D}from"../../layers/orientedImagery/core/ElevationSourceDefinitions.js";import{imageToWorld as z,imageToWorldPanoramic as U}from"../../layers/orientedImagery/transformations/imageToWorld.js";import N from"../../layers/orientedImagery/transformations/updateElevation.js";import{getElevationSampler as W}from"../../layers/orientedImagery/transformations/updateElevationUtils.js";import{getInitialAngle as q,convertPixelToHeadingPitch as $,pointToArray as J,getUpdateElevationProps as K,isElevationSampler as Q,getImageToWorldProperties as Z,getImageToWorldPanoramicProperties as X,getWorldToImageProperties as Y,convertHeadingPitchToSphereVertex as ee,or as te}from"../../layers/orientedImagery/transformations/utils.js";import{worldToImagePanoramic as re,worldToImage as ie}from"../../layers/orientedImagery/transformations/worldToImage.js";import{getFloorFilterClause as ae}from"../../layers/support/floorFilterUtils.js";import oe from"../../rest/support/AttachmentQuery.js";import{scale as se}from"../../views/draw/support/drawUtils.js";import{ViewEventPriorities as ne}from"../../views/input/InputManager.js";import le from"../PanoramicViewer.js";import{invalidCameraHeading as ce,sectorsInOrder as he,sectorsRadii as ue}from"./constants.js";import{crossSymbol as pe,crossSymbol3D as me,sourcePointSymbol as de,diamondSymbol as ge,diamondSymbol3D as ye,activeSourcePointSymbol as fe}from"./symbols.js";import{isNoAttachmentError as ve,getContentType as we,isTifOrMrf as be,filterOILLayerView as Fe,isSceneView as _e,isGraphic as Ie,calculateSegment as Pe,calculateDirection as Se}from"./utils.js";import Ce from"./components/ImageViewer.js";import Ve from"../../geometry/Point.js";import Ae from"../../geometry/SpatialReference.js";import Oe from"../../symbols/SimpleLineSymbol.js";import je from"../../geometry/Multipoint.js";import Me from"../../geometry/Polyline.js";import Re from"../../geometry/Polygon.js";const ke={click:"view-click",imageClick:"image-click",interactionHandles:"interaction-handles",footprintHandles:"footprint-handles"},Be=new Set(["JPG","JPEG"]),Le=/\.(\w+)$/,Ge=e=>"FA"===e;let xe=class extends(l.EventedMixin(g)){constructor(e){super(e),this.additionalFeatures=new o,this.additionalCameraLocations=new o,this.additionalFootprints=new o,this.bestFeatureAngle=0,this.bestFeatureCurrentFootprint=null,this.bestFeatureFootprint=null,this.coverageFrustums=new o,this.coveragePolygons=new o,this.currentBestFeature=null,this.currentBestFeatureLocation=null,this.currentCoverageVisible=!0,this.determineWorkflowForFeature=async(e,t,r)=>{const{currentBestFeature:i,selectedPoint:a,view:o}=this;if(o?.closePopup(),i&&a){this._initialCurrentCoverageUpdate=!0;try{await this._updatePointsAndPolygons(r),await this._loadImage(r)}catch(s){y(s)||(this.loadImageError(s),u.getLogger(this).error("#loadIImage()","error occured while loading image",s))}}},this.disabled=!1,this.displayMessage={key:"onLoadMessage",type:"info"},this.features=new o,this.isAdditionalCoverageVisible=!1,this.isAdditionalPointSourcesVisible=!1,this.layer=null,this.localPort=null,this.mapImageConversionToolState=!1,this.navigatorCurrentBestFeature=null,this.overlayedCameraLocations=new o,this.overlayedMapFeatures=new w,this.pointSources=new o,this.previousFeatureAngle=0,this.selectedPoint=null,this.shouldShowSelectedImage=!1,this.updateFootprint=async(e,t)=>{"image-loaded"===this.state&&await(this._adapter?.updateFootprint(e,t))},this.updateFootprintPanorama=async(e,t)=>{await(this._adapter?.updateFootprintPanorama(e,t))},this._adapter=null,this._highlightedFeatureHandle=null,this._imageViewer=new Ce,this._initialCurrentCoverageUpdate=!0,this._overlays=new k({listMode:"hide",internal:!0,elevationInfo:{mode:"absolute-height"}}),this._panoramicViewer=new le,this._referencePointOnGround=null,this._referencePointOnImage=null,this._sectorData=null,this._updatingHandles=new A,this._clickTask=null,this._crossSymbol=null,this.footprintExtent=null,this._featureChangedTask=null,this._openPopupTask=null,this._suitabilities=null,this._transformController=new AbortController,this._updateFootprintTask=null,this.highlight=e=>{if(!this._overlaysView)return;this.removeHighlight();const t=this.additionalFootprints.find((({attributes:{imageID:t}})=>t===Number(e)));this._highlightedFeatureHandle=t?this._overlaysView?.highlight(t):null},this.loadImageFromSource=async(e,t)=>this._updatingHandles.addPromise(this._loadImageFromSourceInternal(e,t)),this.loadImageViewer=e=>{this._imageViewer.container=e},this.loadPanoramicViewer=e=>{this._panoramicViewer.container=e},this.removeHighlight=()=>this._highlightedFeatureHandle?.remove(),this.toggleImageAttributes=()=>{m(this._openPopupTask),this._openPopupTask=a((async e=>{const{currentBestFeature:r,popupEnabled:i,layer:a,view:o}=this;if(o?.closePopup(),!(o&&r&&i&&a))return;const{attributes:s,geometry:n}=r,l=new t({geometry:n,attributes:s.toJSON(),layer:a});f(e),await o.openPopup({features:[l],location:s.location.clone()})}))},this._createViewClickHandle=()=>{if(this.removeHandles(ke.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,ne.WIDGET),ke.click)},this._createImageClickHandle=()=>{this.removeHandles(ke.imageClick);const{mapImageConversionToolState:e,mode:t,activeViewer:r,currentBestFeature:i,footprintExtent:o}=this,s=r?.imageSize;if(!(e&&"none"!==t&&s&&o&&i))return;r.clickAction="pixel-location";let n=null;const l=b((()=>r),"pixel-location",(e=>{this.plotReferencePointOnImage(e),n?.abort(),n=a((async r=>{if(!e)return;const a=await this.getMapPoint(e,{feature:i,imageSize:s,mode:t}).then((e=>{const t=this.view?.spatialReference;return te(!t,e.spatialReference.equals(t))?e:j(e,t)}));f(r),this.plotReferencePointOnGround(a)}))}));this.addHandles(l,ke.imageClick)},this._getImageSourceFromAttachment=async(e,t,r)=>{const i=new oe({objectIds:[t]}),a=await e.queryAttachments(i,r),o=a[`${t}`]?.[0],s=o?.url;if(!s)throw new n("NoAttachmentError","no attachments found",{[e.objectIdField]:t,layer:e});return{datasetFormat:o.contentType.split("/")[1].toUpperCase(),url:s}},this._loadAdapter=async e=>{const{view:t}=this;if(t)switch(t.type){case"2d":{const{default:t}=await import("./adapters/OrientedImageryViewerViewModelAdapter2D.js");f(e),this._adapter=new t(this);break}case"3d":{const{default:t}=await import("./adapters/OrientedImageryViewerViewModelAdapter3D.js");f(e),this._adapter=new t(this);break}}else this._adapter=null},this._loadImage=async e=>{const{currentBestFeature:t,layer:r,mode:i}=this;if(this.clearGraphics(),!r||!t||"none"===i)return;const{attributes:a}=t,{imagePath:o,imageRotation:s,cameraHeading:n,cameraRoll:l,cameraPitch:c,objectId:h,cameraOrientation:p,location:m}=a,d=(l??0)+(s??0),g=m.spatialReference.isWGS84&&4!==p?.type?R(m):new Ve(m);let v=o;if(Ge(o))try{v=await this._getImageSourceFromAttachment(r,h,e)}catch(w){if(y(w))return;return ve(w)?(u.getLogger(this).error(w),void this.setMessage("noAttachment","error",`${r.objectIdField}: ${h}`)):(u.getLogger(this).error(w,{[r.objectIdField]:h,layer:r}),void this.setMessage("imageLoadError","error",`query-attachments-failed:${r.objectIdField} ${h}`))}try{await this.loadImageFromSource(v,{imageRotation:d,options:e,pitch:c,yaw:n,mode:i,cameraLocation:g}),f(e),await this.transformAndPlotSelectedLocation(e)}catch(w){y(w)||this.loadImageError(w)}},this._loadImageFromSourceInternal=async(e,t)=>{const{mode:r,imageRotation:i,options:a}=t,o="string"==typeof e,s=o?e:e.url,{pathname:n,searchParams:l}=new URL(s);let c=o?n.match(Le)?.[1]:e.datasetFormat;if(!c){const e=await we(s,{...t.options});c=e?.split("/")[1]??"UNKNOWN FORMAT"}switch(r){case"default":this._imageViewer.imageSource={datasetFormat:c.toUpperCase(),url:s.split("?")[0]},this._imageViewer.customParameters=Object.fromEntries(l),this._imageViewer.imageRotation=i??0,await this._imageViewer.loadImage(a);break;case"panoramic":if(Be.has(c.toUpperCase())){const{selectedPoint:e}=this,{pitch:r,yaw:i,cameraLocation:o,viewAngle:n}=t;this._panoramicViewer.imageSource=s;let l=i??0;"number"==typeof n?l=n-l:o&&e&&(l=await q(o,e)-l),this._panoramicViewer.pitch=r??0,this._panoramicViewer.yaw=l,await this._panoramicViewer.loadImage(a)}else this.setMessage("unsupportedPanoramicImageryError","error",void 0,{datasetFormat:c});break}},this._mapImageConversionToolViewClickHandler=e=>{e.stopPropagation(),e.preventDefault(),e.mapPoint&&this.plotMapPoint(e.mapPoint)},this._viewClickHandler=e=>{this._clickTask?.abort(),this._clickTask=a((async t=>{const{pointerType:r,button:i,mapPoint:a}=e;if(("mouse"!==r||0===i)&&a)return e.stopPropagation(),e.preventDefault(),this._updatingHandles.addPromise(this.loadBestImage(a,{signal:t}))}))},this.plotSelectedPointOnImage=async(e,r)=>{if(await v(r),!e)return;const i=new Ve({...c(e)?e.toJSON():e});if("default"===this.mode)i.x-=.5,i.y=.5-i.y,i.spatialReference=this._imageViewer.imageRenderer.spatialReference.clone(),this._crossSymbol=new t({geometry:i,symbol:pe}),this._imageViewer.addGraphic(this._crossSymbol,0);else if("panoramic"===this.mode){const{imageSize:r}=this._panoramicViewer;if(!r)return;const[i,a]=r,{heading:o,pitch:s}=$(e,i,a),n=ee(o,s);this._crossSymbol=new t({geometry:new Ve(n,Ae.WebMercator),symbol:me}),this._panoramicViewer.addGraphic(this._crossSymbol,0)}},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.selectBestFeature=this.selectBestFeature.bind(this)}initialize(){this.addHandles([F((()=>this.view),(()=>{this.load()}),_),F((()=>this.view?.map),((e,t)=>{t?.layers.remove(this._overlays),e?.layers.add(this._overlays)}),I),F((()=>this.view?.map?.allLayers?.length),(e=>{e&&this.view?.map?.layers.reorder(this._overlays,e-1)}),I),F((()=>[this.state,this.mapImageConversionToolState,this.view]),(()=>{this._createViewClickHandle(),this._createImageClickHandle()}),_),F((()=>this.bestFeatureAngle),((e,t)=>{this.previousFeatureAngle=t??0}),_),F((()=>this.currentBestFeature),(async(e,t)=>{m(this._featureChangedTask),this._featureChangedTask=a((async r=>this.determineWorkflowForFeature.apply(this,[e,t,{signal:r}]))),await this._featureChangedTask.promise}),{sync:!0}),F((()=>this.mode),(e=>{switch(this.removeHandles(ke.interactionHandles),e){case"default":this.addHandles(F((()=>this._imageViewer.imagePointsInView),(e=>{e&&(m(this._updateFootprintTask),this._updateFootprintTask=a((async t=>{await this.updateFootprint(e,{signal:t})})))}),{..._,equals:(e,t)=>i(e,t,h)}),ke.interactionHandles);break;case"panoramic":this.addHandles(F((()=>{const{currentBestFeature:e,state:t}=this,{imageSize:r,vfov:i,hfov:a,pitch:o,yaw:s}=this._panoramicViewer;return e&&r&&"image-loading"!==t?[i,a,s,o]:null}),(e=>{if(!e||"image-loading"===this.state)return;const[t,r,i,o]=e;m(this._updateFootprintTask),this._updateFootprintTask=a((async e=>{await this.updateFootprintPanorama({verticalFieldOfView:t,horizontalFieldOfView:r,yaw:i,pitch:o},{signal:e})}))}),{..._,equals:(e,t)=>i(e,t,h)}),ke.interactionHandles)}}),_),F((()=>[this.brightness,this.contrast,this.sharpness]),(()=>{const{_imageViewer:e,brightness:t,contrast:r,mode:i,sharpness:a}=this;"default"===i&&(e.brightness=t,e.contrast=r,e.sharpness=a)}),_)])}destroy(){this._updateFootprintTask=m(this._updateFootprintTask),this._clickTask=m(this._clickTask),this.coverageFrustums.destroy(),this.coveragePolygons.destroy(),this.pointSources.destroy(),this.additionalFootprints.destroy(),this.additionalCameraLocations.destroy(),this.bestFeatureFootprint=d(this.bestFeatureFootprint),this.bestFeatureCurrentFootprint=d(this.bestFeatureCurrentFootprint),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 activeViewer(){const{_imageViewer:e,_panoramicViewer:t,mode:r}=this;switch(r){case"default":return e;case"panoramic":return t;default:return null}}get brightness(){return this._get("brightness")??0}set brightness(e){this._set("brightness",p(e,-10,10))}get contrast(){return this._get("contrast")??0}set contrast(e){this._set("contrast",p(e,-10,10))}get featureCount(){return this.features?.length??0}get imageGalleryEnabled(){return be(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 invalidCameraHeading(){return this.currentBestFeature?.attributes?.cameraHeading===ce}get imagePointsInView(){const{mode:e,_imageViewer:t}=this;return"default"===e?t.imagePointsInView:null}get layerView(){const{layer:e,view:t}=this;if(e&&t)return t.allLayerViews.find(Fe(e))}get layerFloorFilterClause(){const{layerView:e}=this;return e?ae(e):null}get mode(){const e=this.currentBestFeature?.attributes;if(!e)return"none";const{horizontalFieldOfView:t,isSpherical:r}=e;return 360===t||r?"panoramic":"default"}get popupEnabled(){return!0===this.layer?.popupEnabled}get referencePoint(){return this._referencePointOnGround?.geometry}get sectorData(){const{_sectorData:e}=this;return e?he.map((t=>e[t])):null}get sharpness(){return this._get("sharpness")??0}set sharpness(e){this._set("sharpness",p(e,0,1))}get state(){const{mode:e,disabled:t}=this;if(t)return"disabled";if(!this.isFulfilled())return"loading";if(this.isRejected())return"error";if(this._updatingHandles.updating)return"image-loading";if("error"===this.displayMessage?.type)return"image-load-error";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 a=e.trim();return be(a)?{url:a,objectId:t,rotation:(r??0)+(i??0)}:null})).filter(r)):null}set view(e){this._set("view",e)}get _overlaysView(){return this.view?.layerViews.find((({layer:e})=>e===this._overlays))}filterByFootprints(e,t){const r=[],i=[],a=[];return e.forEach((e=>{const{layer:{coveragePercent:o},attributes:s}=e;let n;const l=S(e.geometry.spatialReference);s.cameraHeight/=l,s.farDistance/=l,s.nearDistance/=l,T(s.elevationSource)&&(s.elevationSource.constantElevation/=l);const{polygon:c,frustum:h}=G(s);if(n=c.clone(),s.isInspection&&(n=x(s)),o&&(n=E(n,o)),H(n,t)){a.push(e);const{geometry:t,objectId:o,cameraHeight:n,cameraHeading:l}=s,u=t.clone();u.z=n,u.imageID=o,this.pointSources.push(u),l!==ce&&(r.push(c),h&&i.push(h))}})),{features:a,polygons:r,frustums:i}}handleSectorClick(e){if(isNaN(e))return;const t=this._sectorData?.[he[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 load(e){return this.addResolvingPromise(this._loadAdapter(e).catch((e=>{if(!y(e))throw e}))),this}async loadBestImage(e,t){return this.view?.closePopup(),this.displayMessage=null,this.selectedPoint=e.spatialReference.isGeographic?R(e):e.clone(),this.features.removeAll(),this.currentBestFeature=null,this.additionalFeatures.removeAll(),this.additionalFootprints.removeAll(),this.additionalCameraLocations.removeAll(),this.bestFeatureCurrentFootprint=d(this.bestFeatureCurrentFootprint),this._overlays?.removeAll(),this._fetchFeaturesWithController(e,t)}loadImageError(e){u.getLogger(this).error("oriented-imagery-viewer:load-image",e),this.setMessage("imageLoadError","error",e.message)}async overlayCameraLocations(e){const{activeViewer:r,currentBestFeature:i,overlayedCameraLocations:a,layer:o,mode:s,state:n}=this,l=r?.imageSize;if(!l||!i||!o||"none"===s||n.includes("loading"))return;const{polygon:c}=G(i.attributes);if(r.removeManyGraphics(a.toArray()),a.removeAll(),e){const{features:e}=await o.queryFeatures({where:`${o.objectIdField} <> ${i.attributes.objectId}`,geometry:c,returnGeometry:!0,outFields:[o.objectIdField]}),n=await Promise.all(e.map((async e=>{const{attributes:r,geometry:a}=e,o=await this.getPixels(a,{feature:i,imageSize:l,mode:s}),n=de.clone();return n.outline=new Oe({color:[0,0,0],width:1}),new t({attributes:r,symbol:n,geometry:o})})));a.addMany(n),r.addManyGraphics(a.toArray())}}overlayGraphicsOnImage(e,t){this.overlayedMapFeatures.set(e,t),this.activeViewer?.addManyGraphics(t.toArray())}async overlayMapFeatures(e,i=!1){const{activeViewer:a,currentBestFeature:s,mode:n,state:l}=this,c=a?.imageSize;if(!c||!s||"none"===n||l.includes("loading"))return;const{polygon:h}=G(s.attributes),{features:u}=await e.queryFeatures({geometry:h,returnGeometry:!0,outFields:[e.objectIdField]}),p=new o((await Promise.all(u.map((async r=>{const{attributes:a,geometry:o}=r,l=r.symbol?.clone()??e.renderer?.getSymbol(r).clone();switch(o?.type){case"point":{const r=await this.getPixels(o,{feature:s,imageSize:c,mode:n});return new t({attributes:a,layer:e,symbol:l,geometry:r,visible:e.visible&&i})}case"polygon":{const{rings:r,spatialReference:h}=o,u=r.map((e=>e.map((([e,t,r])=>new Ve({x:e,y:t,z:r,spatialReference:h}))))),p=await Promise.all(u.map((async e=>this.getPixels(e,{feature:s,imageSize:c,mode:n}).then((e=>e.map(J))))));return new t({attributes:a,layer:e,symbol:l,geometry:new Re({rings:p,spatialReference:Ae.WebMercator}),visible:e.visible&&i})}case"polyline":{const{paths:r,spatialReference:h}=o,u=r.map((e=>e.map((([e,t,r])=>new Ve({x:e,y:t,z:r,spatialReference:h}))))),p=await Promise.all(u.map((async e=>this.getPixels(e,{feature:s,imageSize:c,mode:n}).then((e=>e.map(J))))));return new t({attributes:a,layer:e,symbol:l,geometry:new Me({paths:p,spatialReference:Ae.WebMercator}),visible:e.visible&&i})}case"multipoint":{const{points:r,spatialReference:h}=o,u=r.map((([e,t,r])=>new Ve({x:e,y:t,z:r,spatialReference:h}))),p=await this.getPixels(u,{feature:s,imageSize:c,mode:n}).then((e=>e.map(J)));return new t({attributes:a,layer:e,symbol:l,geometry:new je({points:p,spatialReference:Ae.WebMercator}),visible:e.visible&&i})}}return null})))).filter(r));this.overlayGraphicsOnImage(`${e.id}`,p)}async getPixels(e,t){const{imageSize:r,mode:i}=t,a=(await this.worldToImage(Array.isArray(e)?e:[e])).map((e=>{if("default"===i)return new Ve({x:e.x-.5,y:.5-e.y,spatialReference:Ae.WebMercator});const[t,a]=r,{heading:o,pitch:s}=$(e,t,a),n=ee(o,s);return new Ve(n,Ae.WebMercator)}));return Array.isArray(e)?a:a[0]}async getMapPoint(e,t){const{feature:r,mode:i,imageSize:a}=t,{elevationSample:o,attributes:s}=r,{elevationSource:n,location:l,elevation:c,cameraHeight:h}=s;let u=l.clone();u.spatialReference.isGeographic&&(u=await j(u,Ae.WebMercator));const p=await K(c??(l.z??0)-h,{elevationSample:o,elevationSource:n,extent:this.footprintExtent});let m;if("elevationSample"in p&&Q(p.elevationSample)&&(r.elevationSample=p.elevationSample),"default"===i){const t=Z(s,a[0],a[1]);m=await z(Array.isArray(e)?e:[e],{...t,cameraLocation:u},p)}else{const t=X(s,a[0],a[1]);m=await U(Array.isArray(e)?e:[e],{...t,cameraLocation:u},p)}return Array.isArray(e)?m:m[0]}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:new Ve({...e.toJSON()}),symbol:ge}),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.clearReferencePointOnImage(),this.mode){case"default":{const r=c(e)?e.toJSON():e;r.x-=.5,r.y=.5-r.y,this._referencePointOnImage=new t({geometry:new Ve({spatialReference:this._imageViewer.imageRenderer.spatialReference.clone(),...r}),symbol:ge}),this._imageViewer.addGraphic(this._referencePointOnImage,0);break}case"panoramic":{const{imageSize:r}=this._panoramicViewer;if(!r)return;const[i,a]=r,{heading:o,pitch:s}=$(e,i,a),n=ee(o,s);this._referencePointOnImage=new t({geometry:new Ve(n,Ae.WebMercator),symbol:ye}),this._panoramicViewer.addGraphic(this._referencePointOnImage,0);break}}}removeAllOverlayMapFeatures(){this.overlayedMapFeatures.forEach((e=>{this._imageViewer.removeManyGraphics(e.toArray())})),this.overlayedMapFeatures.clear()}removeOverlayedGraphicsOnImage(e){const t=this.overlayedMapFeatures.get(e);t?.length&&(this.activeViewer?.removeManyGraphics(t.toArray()),this.overlayedMapFeatures.delete(e))}resetImage(){switch(this.setMessage("onLoadMessage","info"),this.mode){case"default":this._imageViewer.clearImage(),this._imageViewer.clearGraphics();break;case"panoramic":this._panoramicViewer.clearGraphics()}this._clickTask=m(this._clickTask)}async searchBestImage(e,t){try{const r=await B(e,t);r&&await this._processFeatureResponse(r,e.point,{signal:t?.signal})}catch(r){y(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.additionalCameraLocations.forEach((t=>{t.visible=e}))}setAdditionalCoverageVisibility(e){this.additionalFootprints.forEach((t=>{t.visible=e}))}setCurrentCoverageVisibility(e){this.bestFeatureCurrentFootprint&&(this.bestFeatureCurrentFootprint.visible=e),this.currentBestFeatureLocation&&(this.currentBestFeatureLocation.visible=e)}setMapImageConversionToolState(e){this.mapImageConversionToolState=e}toggleAllOverlayMapFeatures(e){this.overlayedMapFeatures.forEach((t=>{this._toggleVisiblity(t,e)}))}toggleOverlayMapFeatures(e,t){const r=this.overlayedMapFeatures.get(e);r&&this._toggleVisiblity(r,t)}async transformAndPlotReferencePointOnImage(e){const{selectedLocation:t,options:r}=e;let i=!1,a=!1;const o=this.bestFeatureFootprint?.geometry;switch(o?.type){case"polygon":{const e=t.spatialReference.equals(o.spatialReference)?t:await j(t,o.spatialReference);i=o.contains(e);break}case"mesh":{const e=t.spatialReference.equals(o.spatialReference)?t:await j(t,o.spatialReference);a=o.extent.contains(e);break}}if(!i&&!a)return void this.clearReferencePointOnImage();const s=await this.worldToImage(t,r);if(s)return f(r),this.plotReferencePointOnImage(s),{x:s.x,y:s.y};this.clearReferencePointOnImage()}updateSuitabilities(e){e.sort(((e,t)=>e.suitability-t.suitability)),this._suitabilities=e;const t=this._suitabilities.map((({feature:e})=>e));this._initialCurrentCoverageUpdate=!0,this._updateFeatures(t),this._groupFeaturesBySectors()}async _fetchFeatures(e,t){if(!this.view)return;const r=this.layer;if(r){const i={include:r},a=this.view.toScreen(e);if(!a)return;const o=await this.view.hitTest(a,i);return this._processHitTestResults(r,o,t)}}async _fetchFeaturesWithController(e,t){try{await this._fetchFeatures(e,t)}catch(r){if(y(r))return;this.setMessage("imageLoadError","error"),u.getLogger(this).error("error occurred while fetching features",r)}}_groupFeaturesBySectors(){const{_suitabilities:e,additionalFeatures:t,currentBestFeature:r,features:i,invalidCameraHeading:a}=this;if(!e||!t||!r||!i||a)return void(this._sectorData=null);this._sectorData={};for(const c of he)this._sectorData[c]=new o;const s=e.map(((e,t)=>({...e,featureIndex:t})));s.sort(((e,t)=>e.trueSuitability-t.trueSuitability));const n=s.map((({distance:e})=>e)),l=Math.max(...n);s.forEach((e=>{const{distance:t,angle:r,featureIndex:a}=e,o=t/l*ue[2],s=Pe(t,l),n=Se(r);if(!this._sectorData)return;const c=ue[3]+o*Math.sin(r*Math.PI/180),h=ue[3]+o*Math.cos(r*Math.PI/180);let u;const p=i.at(a),m=p===this.currentBestFeature,d=this.currentBestFeature?.attributes.cameraPitch&&this.currentBestFeature?.attributes.cameraPitch<5;if(m&&d)u=-90;else{const e=c-ue[3],t=h-ue[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 g=""===s?n:`${s}_${n}`;m&&(u===this.bestFeatureAngle?this.previousFeatureAngle=u:this.bestFeatureAngle=u,this.navigatorCurrentBestFeature=d?null:{x:c,y:h,direction:n});const y=this._sectorData[g];y.add({angle:r,featureIndex:a,x:c,y:h,objectID:p.attributes.objectId,sector:g,featureIndexInSector:y.length})}))}async _processFeatureResponse(e,t,r){const{features:i}=e;if(!i?.length)return this.setMessage("noImageError","error"),void(this.currentBestFeature=null);this.coveragePolygons.removeAll(),this.coverageFrustums.removeAll(),this.pointSources.removeAll();const{features:a,polygons:o,frustums:s}=this.filterByFootprints(i,t);if(!a.length)return this.setMessage("noImageError","error"),void(this.currentBestFeature=null);let n;if(this.coveragePolygons.addMany(o),this.coverageFrustums.addMany(s),o[0]){let e=new Re({spatialReference:o[0].spatialReference});for(const r of o)e=await O(e,r);const t=[];for(const{geometry:r}of a)e.contains(r)||t.push([r.x,r.y]);if(t.sort(((e,t)=>+M([e,t]))),e.addRing(t),this.footprintExtent=se(e.extent,2,2),this.view?.supportsGround)try{n=await this.view.map.ground.createElevationSampler(this.footprintExtent,r)}catch(l){y(l)||u.getLogger(this).error(l)}}if((n||a[0].attributes.elevationSource)&&this.footprintExtent){const e=a[0].attributes.elevationSource;D(e)&&!n&&(n=await W({extent:this.footprintExtent,lod:e.lod,url:e.url,rasterFunction:e.rasterFunction}));const r=await K((a[0].attributes.location.z??0)-a[0].attributes.cameraHeight,{elevationSample:n,elevationSource:e,extent:this.footprintExtent}),[i,...o]=await N([t,...a.map((e=>e.attributes.geometry.clone()))],r);a[0].elevationSample=n??r.elevationSample,t.elevation=i.z,a.forEach(((e,t)=>{e.attributes.elevation=o[t].z}))}a[0].elevationSample&&a.forEach((e=>{e.elevationSample=a[0].elevationSample})),this._suitabilities=L({features:a,selectedPoint:t,camera:_e(this.view)?this.view.camera:null,currentImage:this.currentBestFeature}),this.updateSuitabilities(this._suitabilities)}async _processHitTestResults(e,t,r){const{screenPoint:i,results:[a]}=t,o="graphic"===a?.type&&this.shouldShowSelectedImage,s=a?.mapPoint??this.view?.toMap(i);if(!s)return;const{layerFloorFilterClause:n}=this,l=P("1=1",P(e.definitionExpression,n)),c=s.spatialReference.isGeographic?1:S(s.spatialReference),h={layerInstanceOrURL:e,point:s,queryParams:{where:l,maximumDistance:e.maximumDistance?e.maximumDistance/c:void 0,objectIds:o?[a.graphic.getAttribute(e.objectIdField)]:void 0}};await this.searchBestImage(h,r)}_toggleVisiblity(e,t){e.forEach((e=>{e.visible=t}))}_updateFeatures(e){if(!e.length)return this.currentBestFeature=null,void this.additionalFeatures.removeAll();this.features.removeAll(),this.features.addMany(e),e.length>1?this.additionalFeatures.addMany(e.slice(1)):this.additionalFeatures.removeAll(),this.currentBestFeature=e[0]}async _updatePointsAndPolygons(e){const{pointSources:r,currentBestFeature:i,currentCoverageVisible:a,isAdditionalPointSourcesVisible:o}=this;if(i&&(this.additionalFootprints.removeAll(),this.additionalCameraLocations.removeAll(),this.bestFeatureCurrentFootprint&&(this.bestFeatureCurrentFootprint.destroy(),this.bestFeatureCurrentFootprint=null,this.bestFeatureFootprint=null),!this.invalidCameraHeading)){await(this._adapter?.createFootprints(e)),f(e);for(const e of r)e.imageID===i.attributes.objectId?this.currentBestFeatureLocation=new t({attributes:{imageID:e.imageID},geometry:e,symbol:fe,visible:a}):this.additionalCameraLocations.push(new t({attributes:{imageID:e.imageID},geometry:e,symbol:de,visible:o}))}}_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-ue[3],i=e.y-ue[3],a=i/Math.sqrt(t**2+i**2);let o=180*Math.acos(a)/Math.PI;(t<0&&i<0||t<0&&i>0)&&(o*=-1),r=o}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()}clearReferencePointOnImage(){this._referencePointOnImage&&(this._imageViewer.removeGraphic(this._referencePointOnImage),this._panoramicViewer.removeGraphic(this._referencePointOnImage),this._referencePointOnImage=d(this._referencePointOnImage))}plotReferencePoint(e){"mapPoint"in e?this.plotReferencePointOnGround(e.mapPoint):this.plotReferencePointOnGround(e)}setMessage(e,t,r,i){this.displayMessage={key:e,type:t,data:r,map:i}}async transformAndPlotSelectedLocation(e){const{currentBestFeature:t,invalidCameraHeading:r,selectedPoint:i,state:a}=this;if(this._crossSymbol&&(this._panoramicViewer.removeGraphic(this._crossSymbol),this._imageViewer.removeGraphic(this._crossSymbol),this._crossSymbol=d(this._crossSymbol)),!i||!t||"image-loaded"!==a||r)return;let o;try{o=await this.worldToImage(i,e),f(e),await this.plotSelectedPointOnImage(o,e)}catch(s){y(s)||u.getLogger(this).error("failed to transform map point to pixel, cross symbol will not be plotted on image",{error:s,selectedPoint:i,feature:t})}}async worldToImage(e,t){const{footprintExtent:r}=this,{imageSize:i}=this.activeViewer;if("none"===this.mode||!this.currentBestFeature||!i||!r)return;const{attributes:{location:a,elevationSource:o,cameraHeading:s,elevation:n,cameraHeight:l},elevationSample:c}=this.currentBestFeature;let h=a.clone();const u=await K(n??(a.z??0)-l,{elevationSample:c,elevationSource:o});this.currentBestFeature.elevationSample=u.elevationSample;const p=Array.isArray(e)?e:[e];let m,d=await Promise.all(p.map((e=>new Promise((t=>{if(!e.hasZ)return t(N(e,u));t(e)})))));if(a.spatialReference.isGeographic&&(h=await j(h,Ae.WebMercator,t)),d=await Promise.all(d.map((async e=>h.spatialReference.equals(e.spatialReference)?e:await j(e,h.spatialReference,t)))),f(t),"panoramic"===this.mode)m=re(d,{imageHeight:i[1],imageWidth:i[0],cameraHeading:s,cameraLocation:h});else{const e=Y(this.currentBestFeature.attributes,i[0],i[1]);m=ie(d,{...e,cameraLocation:h})}return Array.isArray(e)?m:m[0]}updateCurrentCoveragePolygon(e){const{additionalFootprints:r,additionalCameraLocations:i,currentBestFeature:a,currentBestFeatureLocation:o,currentCoverageVisible:s,selectedPoint:n,view:l,_adapter:c}=this,{attributes:{objectId:h},elevationSample:u}=a;if(this._initialCurrentCoverageUpdate){if(this._overlays?.removeAll(),this._initialCurrentCoverageUpdate=!1,this.bestFeatureCurrentFootprint=d(this.bestFeatureCurrentFootprint),e&&!this.invalidCameraHeading&&(e.visible=s,this.bestFeatureCurrentFootprint=e),l){const e=[...r,...i,this.bestFeatureCurrentFootprint,o].filter(Ie);l.supportsGround&&u&&c?.updateGroundElevation&&c.updateGroundElevation(e,u),n&&e.push(new t({geometry:n.clone(),symbol:pe.clone(),attributes:{imageID:h}})),this._overlays.graphics.addMany(e)}}else if(l){if(this.invalidCameraHeading)return;this.bestFeatureCurrentFootprint&&(this._overlays?.remove(this.bestFeatureCurrentFootprint),this.bestFeatureCurrentFootprint=d(this.bestFeatureCurrentFootprint));const t=this.bestFeatureCurrentFootprint&&this._overlays?this._overlays.graphics.indexOf(this.bestFeatureCurrentFootprint):-1;e&&(this.bestFeatureCurrentFootprint=e,l?.supportsGround&&u&&c?.updateGroundElevation&&c.updateGroundElevation([e],u),e.visible=this.currentCoverageVisible,this._overlays?.graphics.add(this.bestFeatureCurrentFootprint,t>=0?t:this._overlays.graphics.length-1))}}};e([C()],xe.prototype,"activeLayer",null),e([C({readOnly:!0})],xe.prototype,"activeViewer",null),e([C()],xe.prototype,"additionalFeatures",void 0),e([C({type:o.ofType(t)})],xe.prototype,"additionalCameraLocations",void 0),e([C({type:o.ofType(t)})],xe.prototype,"additionalFootprints",void 0),e([C()],xe.prototype,"bestFeatureAngle",void 0),e([C()],xe.prototype,"bestFeatureCurrentFootprint",void 0),e([C({type:t})],xe.prototype,"bestFeatureFootprint",void 0),e([C({type:Number})],xe.prototype,"brightness",null),e([C({type:Number})],xe.prototype,"contrast",null),e([C()],xe.prototype,"coverageFrustums",void 0),e([C()],xe.prototype,"coveragePolygons",void 0),e([C()],xe.prototype,"currentBestFeature",void 0),e([C()],xe.prototype,"currentBestFeatureLocation",void 0),e([C()],xe.prototype,"currentCoverageVisible",void 0),e([C({json:{write:!1}})],xe.prototype,"determineWorkflowForFeature",void 0),e([C()],xe.prototype,"disabled",void 0),e([C()],xe.prototype,"displayMessage",void 0),e([C({readOnly:!0})],xe.prototype,"featureCount",null),e([C()],xe.prototype,"features",void 0),e([C({readOnly:!0})],xe.prototype,"imageGalleryEnabled",null),e([C({readOnly:!0})],xe.prototype,"imageLoaded",null),e([C({readOnly:!0})],xe.prototype,"invalidCameraHeading",null),e([C()],xe.prototype,"imagePointsInView",null),e([C()],xe.prototype,"isAdditionalCoverageVisible",void 0),e([C()],xe.prototype,"isAdditionalPointSourcesVisible",void 0),e([C()],xe.prototype,"layer",void 0),e([C()],xe.prototype,"layerView",null),e([C({readOnly:!0})],xe.prototype,"layerFloorFilterClause",null),e([C({type:Number})],xe.prototype,"localPort",void 0),e([C()],xe.prototype,"mapImageConversionToolState",void 0),e([C({readOnly:!0,value:"none"})],xe.prototype,"mode",null),e([C()],xe.prototype,"navigatorCurrentBestFeature",void 0),e([C({type:o.ofType(t)})],xe.prototype,"overlayedCameraLocations",void 0),e([C()],xe.prototype,"overlayedMapFeatures",void 0),e([C()],xe.prototype,"pointSources",void 0),e([C({readOnly:!0})],xe.prototype,"popupEnabled",null),e([C()],xe.prototype,"previousFeatureAngle",void 0),e([C()],xe.prototype,"referencePoint",null),e([C({readOnly:!0})],xe.prototype,"sectorData",null),e([C()],xe.prototype,"selectedPoint",void 0),e([C({type:Number})],xe.prototype,"sharpness",null),e([C()],xe.prototype,"shouldShowSelectedImage",void 0),e([C({readOnly:!0})],xe.prototype,"state",null),e([C({readOnly:!0})],xe.prototype,"thumbnails",null),e([C()],xe.prototype,"updateFootprint",void 0),e([C()],xe.prototype,"updateFootprintPanorama",void 0),e([C({value:null})],xe.prototype,"view",null),e([C()],xe.prototype,"_adapter",void 0),e([C()],xe.prototype,"_highlightedFeatureHandle",void 0),e([C()],xe.prototype,"_imageViewer",void 0),e([C()],xe.prototype,"_initialCurrentCoverageUpdate",void 0),e([C()],xe.prototype,"_overlays",void 0),e([C({readOnly:!0})],xe.prototype,"_overlaysView",null),e([C()],xe.prototype,"_panoramicViewer",void 0),e([C()],xe.prototype,"_referencePointOnGround",void 0),e([C()],xe.prototype,"_referencePointOnImage",void 0),e([C()],xe.prototype,"_sectorData",void 0),e([C({readOnly:!0})],xe.prototype,"_updatingHandles",void 0),e([C()],xe.prototype,"footprintExtent",void 0),xe=e([V("esri.widgets.OrientedImageryViewer.OrientedImageryViewerViewModel")],xe);const Ee=xe;export{Ee as default};