@arcgis/core 4.34.0-next.40 → 4.34.0-next.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/assets/esri/core/workers/RemoteClient.js +1 -1
  2. package/assets/esri/core/workers/chunks/1a2278b9fe9666342728.js +1 -0
  3. package/assets/esri/core/workers/chunks/{4e6e5677b90b00622146.js → 7ef7f3925495b9ade88c.js} +1 -1
  4. package/assets/esri/core/workers/chunks/{5fe3c279d57f44416c28.js → a1d3f1c221389eb6090c.js} +1 -1
  5. package/assets/esri/core/workers/chunks/{306a68137e62656b0f05.js → d5d2d4df407cf078bb81.js} +1 -1
  6. package/config.js +1 -1
  7. package/core/workers/registry.js +1 -1
  8. package/editing/sharedTemplates/executor/support/createFeatureServiceEdit.js +1 -1
  9. package/geometry/support/curves/closestPointOnCurve.js +1 -1
  10. package/geometry/support/curves/curveExtent.js +1 -1
  11. package/geometry/support/curves/curveLength.js +1 -1
  12. package/geometry/support/curves/curveUtils.js +1 -1
  13. package/geometry/support/curves/densifyCurvedGeometry.js +1 -1
  14. package/geometry/support/curves/ellipticArc7Utils.js +1 -1
  15. package/geometry/support/curves/splitCurveAtPoint.js +1 -1
  16. package/geometry/support/meshUtils/exporters/gltf/gltf.js +1 -1
  17. package/interfaces.d.ts +24 -2
  18. package/kernel.js +1 -1
  19. package/layers/PointCloudLayer.js +1 -1
  20. package/package.json +1 -1
  21. package/rest/networks/support/CircuitPath.js +1 -1
  22. package/smartMapping/raster/support/adapters/ImageryLayerAdapter.js +1 -1
  23. package/support/revision.js +1 -1
  24. package/views/2d/engine/webgl/cpuMapped/MappedMesh.js +1 -1
  25. package/views/2d/interactive/editingTools/ControlPointsTransformTool.js +1 -1
  26. package/views/2d/interactive/editingTools/TransformTool.js +1 -1
  27. package/views/2d/layers/features/processor/TrackStrategy.js +1 -1
  28. package/views/2d/layers/features/sources/FeatureSource.js +1 -1
  29. package/views/3d/analysis/AreaMeasurement/support/AreaMeasurementPathHelper.js +1 -1
  30. package/views/3d/analysis/ViewshedAnalysisView3D.js +1 -1
  31. package/views/3d/analysis/VolumeMeasurement/CutFillVolumeMeasurementController.js +1 -1
  32. package/views/3d/interactive/editingTools/media/MediaElementControllerControlPoints.js +1 -1
  33. package/views/3d/interactive/editingTools/reshape/ReshapeOperation.js +1 -1
  34. package/views/3d/interactive/editingTools/transform/extentTransform/ExtentScale.js +1 -1
  35. package/views/3d/layers/graphics/Graphics3DGraphic.js +1 -1
  36. package/views/3d/layers/graphics/Graphics3DSymbolLayer.js +1 -1
  37. package/views/3d/support/intersectionUtils.js +1 -1
  38. package/views/3d/webgl-engine/effects/RenderPlugin.js +1 -1
  39. package/views/3d/webgl-engine/materials/renderers/MergedBuffer.js +5 -0
  40. package/views/3d/webgl-engine/materials/renderers/MergedRenderer.js +1 -1
  41. package/views/3d/webgl-engine/materials/renderers/PerBufferData.js +1 -1
  42. package/views/3d/webgl-engine/materials/renderers/VaoRenderer.js +5 -0
  43. package/views/PopupView.js +1 -1
  44. package/views/draw/DrawAction.js +1 -1
  45. package/views/draw/DrawOperation.js +1 -1
  46. package/views/draw/SegmentDrawAction.js +1 -1
  47. package/views/draw/support/Reshape.js +1 -1
  48. package/views/interactive/SegmentLabels.js +1 -1
  49. package/views/interactive/editGeometry/EditGeometry.js +1 -1
  50. package/views/interactive/editGeometry/EditGeometryOperations.js +1 -1
  51. package/views/interactive/editGeometry/operations/AppendVertex.js +1 -1
  52. package/views/interactive/editGeometry/operations/ClosePart.js +5 -0
  53. package/views/interactive/editGeometry/operations/MoveMesh.js +1 -1
  54. package/views/interactive/editGeometry/operations/MoveVertex.js +1 -1
  55. package/views/interactive/editGeometry/operations/OffsetEdgeVertex.js +1 -1
  56. package/views/interactive/editGeometry/operations/RemoveVertices.js +1 -1
  57. package/views/interactive/editGeometry/operations/RotateVertex.js +1 -1
  58. package/views/interactive/editGeometry/operations/ScaleVertex.js +1 -1
  59. package/views/interactive/editGeometry/operations/SetAllVertexPositions.js +1 -1
  60. package/views/interactive/editGeometry/operations/SetVertexPosition.js +1 -1
  61. package/views/interactive/editGeometry/operations/SplitSegment.js +5 -0
  62. package/views/interactive/editGeometry/operations/UpdateVertices.js +1 -1
  63. package/views/interactive/editGeometry/operations/curveOperationUtils.js +5 -0
  64. package/views/interactive/editGeometry/operations.js +1 -1
  65. package/views/interactive/snapping/FeatureSnappingEngine.js +1 -1
  66. package/views/interactive/snapping/LineSnapper.js +1 -1
  67. package/views/interactive/snapping/ParallelLineSnapper.js +1 -1
  68. package/views/interactive/snapping/RightAngleSnapper.js +1 -1
  69. package/views/interactive/snapping/RightAngleTriangleSnapper.js +1 -1
  70. package/views/interactive/snapping/SnappingDragPipelineStep.js +1 -1
  71. package/views/layers/support/MapServiceLayerViewHelper.js +1 -1
  72. package/widgets/BatchAttributeForm/BatchAttributeFormViewModel.js +1 -1
  73. package/widgets/Editor/AddAssociationWorkflow.js +1 -1
  74. package/widgets/Editor/CreateFeaturesWorkflow.js +1 -1
  75. package/widgets/Editor/EditorViewModel.js +1 -1
  76. package/widgets/Editor/support/SketchController.js +1 -1
  77. package/widgets/Feature/FeatureMedia.js +1 -1
  78. package/widgets/FeatureForm/FeatureFormViewModel.js +1 -1
  79. package/widgets/FeatureTable/FeatureTableViewModel.js +1 -1
  80. package/widgets/FeatureTable/Grid/Grid.js +1 -1
  81. package/widgets/FeatureTable/Grid/GridViewModel.js +1 -1
  82. package/widgets/FeatureTable/support/FeatureStore.js +1 -1
  83. package/widgets/FeatureTemplates/FeatureTemplatesViewModel.js +1 -1
  84. package/widgets/Features.js +1 -1
  85. package/widgets/Legend/support/ActiveLayerInfo.js +1 -1
  86. package/widgets/OrientedImageryViewer/OrientedImageryViewerViewModel.js +1 -1
  87. package/widgets/OrientedImageryViewer/adapters/sketch/MeasurementAdapter.js +1 -1
  88. package/widgets/OrientedImageryViewer/adapters/sketch/TriangulatedMeasurementAdapter.js +1 -1
  89. package/widgets/PanoramicViewer/support/PanoramicMeshManager.js +5 -0
  90. package/widgets/PanoramicViewer/support/PanoramicMeshWorker.js +5 -0
  91. package/widgets/Spinner.js +1 -1
  92. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceFeature.js +1 -1
  93. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceViewModel.js +1 -1
  94. package/widgets/UtilityNetworkTrace.js +1 -1
  95. package/widgets/UtilityNetworkTraceAnalysis/UtilityNetworkTraceAnalysisViewModel.js +1 -1
  96. package/widgets/smartMapping/HeatmapSlider/HeatmapSliderViewModel.js +1 -1
  97. package/views/interactive/editGeometry/operations/CloseComponent.js +0 -5
  98. package/views/interactive/editGeometry/operations/SplitEdge.js +0 -5
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";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{geometryTypes as y}from"../../../geometry/support/typeUtils.js";import{isSubtypeGroupLayer as m,isSubtypeSublayer as _}from"../../../layers/support/layerUtils.js";import f from"../../../rest/support/AttachmentQuery.js";import g from"../../../rest/support/RelationshipQuery.js";import{T as b}from"../../../chunks/TimeExtent.js";import{isIFeatureTableSupportedLayerWithAttachments as v,isIFeatureTableSupportedLayerWithAttachmentsEditing as O,isIFeatureTableSupportedLayerWithEditing as A,isIFeatureTableSupportedLayerWithRelationships as I,findRelatedLayer as j}from"./tableUtils.js";let C=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&&v(e)?e:null}get _layerWithAttachmentsEditing(){const{_layerWithAttachments:e}=this;return e&&O(e)&&this.supportsEditing?e:null}get _layerWithEditing(){const e=this.layer;return A(e)&&this.supportsEditing?e:null}get _layerWithRelationships(){const e=this.layer;return I(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 _subtypeCode(){return this.layer?.subtypeCode??null}get _subtypeField(){const{layer:e}=this;return m(e?.parent)?e.subtypeField:null}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 isQuerying(){return this._queryOperationQueue.length>0}get isSyncing(){return this.isSyncingFeatureEdits||this.isSyncingAttachmentEdits}get isSyncingAttachmentEdits(){return this._attachmentsOperationQueue.length>0}get isSyncingFeatureEdits(){return this._editOperationQueue.length>0}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)?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 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=j(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?.attachment?.supportsResize)}get supportsUpdate(){return!!this._capabilities?.operations.supportsUpdate}get supportsUpdateAttachments(){return!(!this._layerWithAttachmentsEditing||!this.supportsUpdate)}get supportsZ(){return!!this.layer?.hasZ&&!!this._capabilities?.data?.supportsZ}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&&m(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){const s=new t({attributes:{[e.objectIdField]:r}});return this._subtypeField&&null!=this._subtypeCode&&(s.attributes[this._subtypeField]=this._subtypeCode),s}_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}=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 f({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 g({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 g({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 g({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}),_=await d.queryRelatedFeatures(m);return _[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()],C.prototype,"_attachmentsOperationQueue",void 0),e([d({readOnly:!0})],C.prototype,"_capabilities",null),e([d()],C.prototype,"_defaultOutFields",void 0),e([d()],C.prototype,"_editOperationQueue",void 0),e([d()],C.prototype,"_effectiveReturnZ",null),e([d()],C.prototype,"_effectiveReturnM",null),e([d({readOnly:!0})],C.prototype,"_layerWithAttachments",null),e([d({readOnly:!0})],C.prototype,"_layerWithAttachmentsEditing",null),e([d({readOnly:!0})],C.prototype,"_layerWithEditing",null),e([d({readOnly:!0})],C.prototype,"_layerWithRelationships",null),e([d()],C.prototype,"_loaded",void 0),e([d()],C.prototype,"_loadError",void 0),e([d()],C.prototype,"_loading",void 0),e([d()],C.prototype,"_objectIdCache",void 0),e([d()],C.prototype,"_queryOperationQueue",void 0),e([d({readOnly:!0})],C.prototype,"_relatedLayer",null),e([d({readOnly:!0})],C.prototype,"_relatedLayerCapabilities",null),e([d({readOnly:!0})],C.prototype,"_relatedLayerSupportsCacheHint",null),e([d()],C.prototype,"_relatedLayerSupportsQuery",null),e([d()],C.prototype,"_relatedLayerSupportsQueryRelated",null),e([d()],C.prototype,"_sortedFieldNames",null),e([d()],C.prototype,"_subtypeCode",null),e([d()],C.prototype,"_subtypeField",null),e([d()],C.prototype,"_canUseRelatedLayer",null),e([d()],C.prototype,"attachmentsEnabled",void 0),e([d()],C.prototype,"canAddRelatedFeature",null),e([d({readOnly:!0})],C.prototype,"count",void 0),e([d()],C.prototype,"effectiveOutFields",null),e([d()],C.prototype,"effectiveTimeExtent",null),e([d()],C.prototype,"effectiveWhere",null),e([d({readOnly:!0})],C.prototype,"failures",void 0),e([d({types:y})],C.prototype,"filterGeometry",void 0),e([d()],C.prototype,"initialSize",void 0),e([d({readOnly:!0})],C.prototype,"isQuerying",null),e([d({readOnly:!0})],C.prototype,"isSyncing",null),e([d({readOnly:!0})],C.prototype,"isSyncingAttachmentEdits",null),e([d({readOnly:!0})],C.prototype,"isSyncingFeatureEdits",null),e([d({readOnly:!0})],C.prototype,"itemCache",null),e([d()],C.prototype,"layer",void 0),e([d()],C.prototype,"layerView",null),e([d()],C.prototype,"objectIds",void 0),e([d()],C.prototype,"orderByFields",null),e([d()],C.prototype,"outFields",void 0),e([d({readOnly:!0})],C.prototype,"pageCache",void 0),e([d()],C.prototype,"pageSize",void 0),e([d()],C.prototype,"relationship",null),e([d()],C.prototype,"relationshipConfig",void 0),e([d()],C.prototype,"relationshipIds",null),e([d()],C.prototype,"relationshipInfos",null),e([d()],C.prototype,"relationships",null),e([d()],C.prototype,"relatedRecordsEnabled",void 0),e([d()],C.prototype,"returnGeometry",void 0),e([d()],C.prototype,"returnZ",void 0),e([d()],C.prototype,"returnM",void 0),e([d()],C.prototype,"sortOrders",void 0),e([d({readOnly:!0})],C.prototype,"state",null),e([d()],C.prototype,"supportsAdd",null),e([d()],C.prototype,"supportsAddingAttachments",null),e([d()],C.prototype,"supportsAttachments",null),e([d()],C.prototype,"supportsCacheHint",null),e([d()],C.prototype,"supportsCacheHintQueryRelated",null),e([d()],C.prototype,"supportsDelete",null),e([d()],C.prototype,"supportsDeletingAttachments",null),e([d()],C.prototype,"supportsEditing",null),e([d()],C.prototype,"supportsM",null),e([d()],C.prototype,"supportsOrderBy",null),e([d()],C.prototype,"supportsPagination",null),e([d()],C.prototype,"supportsQuery",null),e([d()],C.prototype,"supportsQueryRelated",null),e([d()],C.prototype,"supportsResizeAttachments",null),e([d()],C.prototype,"supportsUpdate",null),e([d()],C.prototype,"supportsUpdateAttachments",null),e([d()],C.prototype,"supportsZ",null),e([d({type:b})],C.prototype,"timeExtent",void 0),e([d()],C.prototype,"view",void 0),e([d()],C.prototype,"where",void 0),C=e([c("esri.widgets.FeatureTable.support.FeatureStore")],C);const w=C;export{w as default};
5
+ import{__decorate as e}from"tslib";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{geometryTypes as y}from"../../../geometry/support/typeUtils.js";import{isSubtypeGroupLayer as m,isSubtypeSublayer as _}from"../../../layers/support/layerUtils.js";import f from"../../../rest/support/AttachmentQuery.js";import g from"../../../rest/support/RelationshipQuery.js";import{T as b}from"../../../chunks/TimeExtent.js";import{isIFeatureTableSupportedLayerWithAttachments as v,isIFeatureTableSupportedLayerWithAttachmentsEditing as O,isIFeatureTableSupportedLayerWithEditing as A,isIFeatureTableSupportedLayerWithRelationships as I,findRelatedLayer as j}from"./tableUtils.js";let C=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&&v(e)?e:null}get _layerWithAttachmentsEditing(){const{_layerWithAttachments:e}=this;return e&&O(e)&&this.supportsEditing?e:null}get _layerWithEditing(){const e=this.layer;return A(e)&&this.supportsEditing?e:null}get _layerWithRelationships(){const e=this.layer;return I(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 _subtypeCode(){return this.layer?.subtypeCode??null}get _subtypeField(){const{layer:e}=this;return m(e?.parent)?e.subtypeField:null}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 isQuerying(){return this._queryOperationQueue.length>0}get isSyncing(){return this.isSyncingFeatureEdits||this.isSyncingAttachmentEdits}get isSyncingAttachmentEdits(){return this._attachmentsOperationQueue.length>0}get isSyncingFeatureEdits(){return this._editOperationQueue.length>0}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)?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 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=j(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?.attachment?.supportsResize)}get supportsUpdate(){return!!this._capabilities?.operations.supportsUpdate}get supportsUpdateAttachments(){return!(!this._layerWithAttachmentsEditing||!this.supportsUpdate)}get supportsZ(){return!!this.layer?.hasZ&&!!this._capabilities?.data?.supportsZ}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&&m(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()}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){const s=new t({attributes:{[e.objectIdField]:r}});return this._subtypeField&&null!=this._subtypeCode&&(s.attributes[this._subtypeField]=this._subtypeCode),s}_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}=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 f({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 g({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 g({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 g({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}),_=await d.queryRelatedFeatures(m);return _[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()],C.prototype,"_attachmentsOperationQueue",void 0),e([d({readOnly:!0})],C.prototype,"_capabilities",null),e([d()],C.prototype,"_defaultOutFields",void 0),e([d()],C.prototype,"_editOperationQueue",void 0),e([d()],C.prototype,"_effectiveReturnZ",null),e([d()],C.prototype,"_effectiveReturnM",null),e([d({readOnly:!0})],C.prototype,"_layerWithAttachments",null),e([d({readOnly:!0})],C.prototype,"_layerWithAttachmentsEditing",null),e([d({readOnly:!0})],C.prototype,"_layerWithEditing",null),e([d({readOnly:!0})],C.prototype,"_layerWithRelationships",null),e([d()],C.prototype,"_loaded",void 0),e([d()],C.prototype,"_loadError",void 0),e([d()],C.prototype,"_loading",void 0),e([d()],C.prototype,"_objectIdCache",void 0),e([d()],C.prototype,"_queryOperationQueue",void 0),e([d({readOnly:!0})],C.prototype,"_relatedLayer",null),e([d({readOnly:!0})],C.prototype,"_relatedLayerCapabilities",null),e([d({readOnly:!0})],C.prototype,"_relatedLayerSupportsCacheHint",null),e([d()],C.prototype,"_relatedLayerSupportsQuery",null),e([d()],C.prototype,"_relatedLayerSupportsQueryRelated",null),e([d()],C.prototype,"_sortedFieldNames",null),e([d()],C.prototype,"_subtypeCode",null),e([d()],C.prototype,"_subtypeField",null),e([d()],C.prototype,"_canUseRelatedLayer",null),e([d()],C.prototype,"attachmentsEnabled",void 0),e([d()],C.prototype,"canAddRelatedFeature",null),e([d({readOnly:!0})],C.prototype,"count",void 0),e([d()],C.prototype,"effectiveOutFields",null),e([d()],C.prototype,"effectiveTimeExtent",null),e([d()],C.prototype,"effectiveWhere",null),e([d({readOnly:!0})],C.prototype,"failures",void 0),e([d({types:y})],C.prototype,"filterGeometry",void 0),e([d()],C.prototype,"initialSize",void 0),e([d({readOnly:!0})],C.prototype,"isQuerying",null),e([d({readOnly:!0})],C.prototype,"isSyncing",null),e([d({readOnly:!0})],C.prototype,"isSyncingAttachmentEdits",null),e([d({readOnly:!0})],C.prototype,"isSyncingFeatureEdits",null),e([d({readOnly:!0})],C.prototype,"itemCache",null),e([d()],C.prototype,"layer",void 0),e([d()],C.prototype,"layerView",null),e([d()],C.prototype,"objectIds",void 0),e([d()],C.prototype,"orderByFields",null),e([d()],C.prototype,"outFields",void 0),e([d({readOnly:!0})],C.prototype,"pageCache",void 0),e([d()],C.prototype,"pageSize",void 0),e([d()],C.prototype,"relationship",null),e([d()],C.prototype,"relationshipConfig",void 0),e([d()],C.prototype,"relationshipIds",null),e([d()],C.prototype,"relationshipInfos",null),e([d()],C.prototype,"relationships",null),e([d()],C.prototype,"relatedRecordsEnabled",void 0),e([d()],C.prototype,"returnGeometry",void 0),e([d()],C.prototype,"returnZ",void 0),e([d()],C.prototype,"returnM",void 0),e([d()],C.prototype,"sortOrders",void 0),e([d({readOnly:!0})],C.prototype,"state",null),e([d()],C.prototype,"supportsAdd",null),e([d()],C.prototype,"supportsAddingAttachments",null),e([d()],C.prototype,"supportsAttachments",null),e([d()],C.prototype,"supportsCacheHint",null),e([d()],C.prototype,"supportsCacheHintQueryRelated",null),e([d()],C.prototype,"supportsDelete",null),e([d()],C.prototype,"supportsDeletingAttachments",null),e([d()],C.prototype,"supportsEditing",null),e([d()],C.prototype,"supportsM",null),e([d()],C.prototype,"supportsOrderBy",null),e([d()],C.prototype,"supportsPagination",null),e([d()],C.prototype,"supportsQuery",null),e([d()],C.prototype,"supportsQueryRelated",null),e([d()],C.prototype,"supportsResizeAttachments",null),e([d()],C.prototype,"supportsUpdate",null),e([d()],C.prototype,"supportsUpdateAttachments",null),e([d()],C.prototype,"supportsZ",null),e([d({type:b})],C.prototype,"timeExtent",void 0),e([d()],C.prototype,"view",void 0),e([d()],C.prototype,"where",void 0),C=e([c("esri.widgets.FeatureTable.support.FeatureStore")],C);const w=C;export{w as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as t}from"tslib";import{createTask as e}from"../../core/asyncUtils.js";import{EventedAccessor as s}from"../../core/Evented.js";import{abortMaybe as l}from"../../core/maybe.js";import{throwIfAborted as o}from"../../core/promiseUtils.js";import{watch as i,syncAndInitial as r,sync as a,when as n}from"../../core/reactiveUtils.js";import{property as p}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import"../../core/RandomLCG.js";import{subclass as m}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as u}from"../../core/support/UpdatingHandles.js";import{getTemplatesForLayers as d,isSharedTemplateOrMetadata as c}from"../../editing/templateUtils.js";import{getEffectiveLayerCapabilities as h,isSubtypeGroupLayer as y}from"../../layers/support/layerUtils.js";import{isTemplateItemGroup as f,mapItemsByTemplate as g,isTemplateGroupInfo as _,loadLayerWithTemplates as I,makeTemplateItemInfos as F,makeGroupItemInfos as b,nullGroupBy as v}from"./featureTemplatesUtils.js";import T from"./TemplateItem.js";import j from"./TemplateItemGroup.js";const B=({layer:t})=>({key:t,label:t.title??""}),w=({layer:t})=>({key:t.geometryType,label:t.geometryType??""});let k=class extends s{constructor(t){super(t),this._allItems=[],this._updatingHandles=new u,this._updateTask=null,this.disabled=!1,this.disabledItemFunction=null,this.filterFunction=null,this.selectedItem=null,this.templateInfos=null,this.view=null}initialize(){this._get("groupBy")||(this.groupBy="layer"),this.addHandles([i(()=>[this.templateInfos,this.layers],([t],e)=>{t&&t===e?.at(0)||(this._updateTask=l(this._updateTask),t?this._updateAllItems(t):this._getTemplatesAndUpdateAllItems())},r),i(()=>this._groupByFunction,()=>{null==this.templateInfos&&(this._updateTask=l(this._updateTask),this._getTemplatesAndUpdateAllItems())},a),i(()=>this.filterFunction,t=>{for(const e of this._allItems)f(e)&&(e.filterFunction=t)},a)])}set groupBy(t){if(this._set("groupBy",t),"function"!=typeof t)switch(t){case"layer":this._groupByFunction=B;break;case"geometry":this._groupByFunction=w;break;default:this._groupByFunction=null}else this._groupByFunction=e=>this._ensureGroupByObject(t(e))}get layers(){return this._get("layers")}set layers(t){const e="layers";if(this.removeHandles(e),t){const s=()=>this.notifyChange("state");this.addHandles(t.map(t=>n(()=>t.loadStatus,s)),e)}this._set("layers",t)}get state(){return this.updating?"loading":0!==this.layers.length||this.templateInfos?.length?"ready":"disabled"}get numberOfFeatureTemplates(){return this._allItems.reduce((t,e)=>f(e)?t+e.allItems.length:t+1,0)}get items(){const{filterFunction:t}=this;return null==t?this._allItems:this._allItems.filter(e=>f(e)?e.items.length>0:t(e))}get updating(){return this._updatingHandles.updating}refresh(){this.notifyChange("filterFunction");for(const t of this._allItems)f(t)&&t.reapplyFilter()}select(t,{emit:e=!0}={}){const s=this.selectedItem,l=t?.clone()||null;this._set("selectedItem",l),e&&this.emit("select",{item:l,oldItem:s,template:l?.template??null})}_createItem(t,e){return new T({disabledFunction:this.disabledItemFunction,layer:e,template:t})}_ensureGroupByObject(t){return"string"==typeof t?{key:t,label:t}:t}_updateAllItems(t){const e=this._allItems;if(0===t.length)return A(e),void(this._allItems=[]);const[s,l]=g(e),o=t=>{const e=s.get(t.template);return e?(s.delete(t.template),e):this._createItem(t.template,t.layer)},{filterFunction:i}=this,r=t.filter(U).map(t=>_(t)?new j({filterFunction:i,label:t.label,allItems:t.templateInfos.filter(U).map(t=>o(t))}):o(t));for(const a of[...s.values(),...l])a.destroy();this._allItems=r}async _getTemplatesFromLayers(t){const e=[],s={signal:t};await Promise.all(this.layers.map(async l=>{await I(l,s),o(t);const i=h(l)?.operations;i?.supportsEditing&&i?.supportsAdd&&(y(l)?e.push(...l.sublayers):e.push(l))}));const l=await d(e,this.view,t);o(t);const i=F(l),r=this._groupByFunction;if(null==r)return i;const a=b(i,r);return 1===a.length&&a[0].label===v.label?a[0].templateInfos:a}async _getTemplatesAndUpdateAllItems(){if(0===this.layers.length)return;const t=e(async t=>{const e=await this._getTemplatesFromLayers(t);o(t),this._updateAllItems(e)});this._updateTask=t,this._updatingHandles.addPromise(t.promise)}};function A(t){for(const e of t){if(f(e))for(const t of e.items)t.destroy();e.destroy()}}function U(t){return _(t)?t.templateInfos.some(U):!c(t.template)||!1!==t.template.visible}t([p()],k.prototype,"_allItems",void 0),t([p()],k.prototype,"_groupByFunction",void 0),t([p()],k.prototype,"_updatingHandles",void 0),t([p()],k.prototype,"disabled",void 0),t([p()],k.prototype,"disabledItemFunction",void 0),t([p({value:null})],k.prototype,"filterFunction",void 0),t([p()],k.prototype,"groupBy",null),t([p({value:[]})],k.prototype,"layers",null),t([p()],k.prototype,"state",null),t([p({readOnly:!0})],k.prototype,"numberOfFeatureTemplates",null),t([p({readOnly:!0})],k.prototype,"items",null),t([p({readOnly:!0})],k.prototype,"selectedItem",void 0),t([p()],k.prototype,"templateInfos",void 0),t([p()],k.prototype,"updating",null),t([p()],k.prototype,"view",void 0),k=t([m("esri.widgets.FeatureTemplates.FeatureTemplatesViewModel")],k);const H=k;export{H as default};
5
+ import{__decorate as t}from"tslib";import{createTask as e}from"../../core/asyncUtils.js";import{EventedAccessor as s}from"../../core/Evented.js";import{abortMaybe as l}from"../../core/maybe.js";import{throwIfAborted as o}from"../../core/promiseUtils.js";import{watch as i,syncAndInitial as r,sync as a,when as n}from"../../core/reactiveUtils.js";import{property as p}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import"../../core/RandomLCG.js";import{subclass as m}from"../../core/accessorSupport/decorators/subclass.js";import{UpdatingHandles as u}from"../../core/support/UpdatingHandles.js";import{getTemplatesForLayers as d,isSharedTemplateOrMetadata as c}from"../../editing/templateUtils.js";import{getEffectiveLayerCapabilities as h,isSubtypeGroupLayer as y}from"../../layers/support/layerUtils.js";import{isTemplateItemGroup as f,mapItemsByTemplate as g,isTemplateGroupInfo as _,loadLayerWithTemplates as I,makeTemplateItemInfos as F,makeGroupItemInfos as b,nullGroupBy as v}from"./featureTemplatesUtils.js";import T from"./TemplateItem.js";import j from"./TemplateItemGroup.js";const w=({layer:t})=>({key:t,label:t.title??""}),B=({layer:t})=>({key:t.geometryType,label:t.geometryType??""});let k=class extends s{constructor(t){super(t),this._allItems=[],this._updatingHandles=new u,this._updateTask=null,this.disabled=!1,this.disabledItemFunction=null,this.filterFunction=null,this.selectedItem=null,this.templateInfos=null,this.view=null}initialize(){this._get("groupBy")||(this.groupBy="layer"),this.addHandles([i(()=>[this.templateInfos,this.layers],([t],e)=>{t&&t===e?.at(0)||(this._updateTask=l(this._updateTask),t?this._updateAllItems(t):this._getTemplatesAndUpdateAllItems())},r),i(()=>this._groupByFunction,()=>{null==this.templateInfos&&(this._updateTask=l(this._updateTask),this._getTemplatesAndUpdateAllItems())},a),i(()=>this.filterFunction,t=>{for(const e of this._allItems)f(e)&&(e.filterFunction=t)},a)])}set groupBy(t){if(this._set("groupBy",t),"function"!=typeof t)switch(t){case"layer":this._groupByFunction=w;break;case"geometry":this._groupByFunction=B;break;default:this._groupByFunction=null}else this._groupByFunction=e=>this._ensureGroupByObject(t(e))}get layers(){return this._get("layers")}set layers(t){const e="layers";if(this.removeHandles(e),t){const s=()=>this.notifyChange("state");this.addHandles(t.map(t=>n(()=>t.loadStatus,s)),e)}this._set("layers",t)}get state(){return this.updating?"loading":0!==this.layers.length||this.templateInfos?.length?"ready":"disabled"}get numberOfFeatureTemplates(){return this._allItems.reduce((t,e)=>f(e)?t+e.allItems.length:t+1,0)}get items(){const{filterFunction:t}=this;return null==t?this._allItems:this._allItems.filter(e=>f(e)?e.items.length>0:t(e))}get updating(){return this._updatingHandles.updating}refresh(){this.notifyChange("filterFunction");for(const t of this._allItems)f(t)&&t.reapplyFilter()}select(t,{emit:e=!0}={}){const s=this.selectedItem,l=t?.clone()||null;this._set("selectedItem",l),e&&this.emit("select",{item:l,oldItem:s,template:l?.template??null})}_createItem(t,e){return new T({disabledFunction:this.disabledItemFunction,layer:e,template:t})}_ensureGroupByObject(t){return"string"==typeof t?{key:t,label:t}:t}_updateAllItems(t){const e=this._allItems;if(0===t.length)return A(e),void(this._allItems=[]);const[s,l]=g(e),o=t=>{const e=s.get(t.template);return e?(s.delete(t.template),e):this._createItem(t.template,t.layer)},{filterFunction:i}=this,r=t.filter(U).map(t=>_(t)?new j({filterFunction:i,label:t.label,allItems:t.templateInfos.filter(U).map(t=>o(t))}):o(t));for(const a of[...s.values(),...l])a.destroy();this._allItems=r}async _getTemplatesFromLayers(t){const e=[],s={signal:t};await Promise.all(this.layers.map(async l=>{await I(l,s),o(t);const i=h(l)?.operations;i?.supportsEditing&&i?.supportsAdd&&(y(l)?e.push(...l.sublayers):e.push(l))}));const l=await d(e,this.view,t);o(t);const i=F(l),r=this._groupByFunction;if(null==r)return i;const a=b(i,r);return 1===a.length&&a[0].label===v.label?a[0].templateInfos:a}async _getTemplatesAndUpdateAllItems(){if(0===this.layers.length)return;const t=e(async t=>{const e=await this._getTemplatesFromLayers(t);o(t),this._updateAllItems(e)});this._updateTask=t,await this._updatingHandles.addPromise(t.promise)}};function A(t){for(const e of t){if(f(e))for(const t of e.items)t.destroy();e.destroy()}}function U(t){return _(t)?t.templateInfos.some(U):!c(t.template)||!1!==t.template.visible}t([p()],k.prototype,"_allItems",void 0),t([p()],k.prototype,"_groupByFunction",void 0),t([p()],k.prototype,"_updatingHandles",void 0),t([p()],k.prototype,"disabled",void 0),t([p()],k.prototype,"disabledItemFunction",void 0),t([p({value:null})],k.prototype,"filterFunction",void 0),t([p()],k.prototype,"groupBy",null),t([p({value:[]})],k.prototype,"layers",null),t([p()],k.prototype,"state",null),t([p({readOnly:!0})],k.prototype,"numberOfFeatureTemplates",null),t([p({readOnly:!0})],k.prototype,"items",null),t([p({readOnly:!0})],k.prototype,"selectedItem",void 0),t([p()],k.prototype,"templateInfos",void 0),t([p()],k.prototype,"updating",null),t([p()],k.prototype,"view",void 0),k=t([m("esri.widgets.FeatureTemplates.FeatureTemplatesViewModel")],k);const H=k;export{H as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import"../intl.js";import t from"../core/Collection.js";import i from"../core/Logger.js";import{ignoreAbortErrors as o}from"../core/promiseUtils.js";import{watch as s,initial as n,when as r}from"../core/reactiveUtils.js";import{waitAnimationFrame as l}from"../core/scheduling.js";import{throttle as a}from"../core/throttle.js";import{property as d}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/RandomLCG.js";import{subclass as c}from"../core/accessorSupport/decorators/subclass.js";import{getPointFromGeometry as u}from"../geometry/support/geometryUtils.js";import{loadActionUtilsComponents as h,substituteActionImage as p,getActionStyles as m,renderAction as v}from"../support/actions/actionUtils.js";import g from"./Feature.js";import w from"./Spinner.js";import _ from"./Widget.js";import{css as M}from"./Feature/resources.js";import{FeatureContentMixin as f}from"./Feature/support/FeatureContentMixin.js";import{css as F}from"./Features/css.js";import y from"./Features/FeaturesDrillIn.js";import b from"./Features/FeaturesViewModel.js";import I from"./Features/FeaturesVisibleElements.js";import{ActionsCollection as C}from"./Popup/actions.js";import{zoomToLocation as x}from"./Popup/actionUtils.js";import{loadCalciteComponents as A}from"./support/componentsUtils.js";import{globalCss as N}from"./support/globalCss.js";import{Heading as T}from"./support/Heading.js";import{setFocus as k}from"./support/widgetUtils.js";import{messageBundle as O}from"./support/decorators/messageBundle.js";import{vmEvent as E}from"./support/decorators/vmEvent.js";import{tsx as L}from"./support/jsxFactory.js";import{substitute as j}from"../intl/substitute.js";import{formatNumber as W}from"../intl/number.js";const D="selected-index",B=0,S="features-spinner";function R(e){return e?.declaredClass.startsWith("esri.layers.")??!1}let H=class extends(f(_)){constructor(e,i){super(e,i),this._featureMenuIntersectionObserverCallback=([e])=>{e?.isIntersecting&&null!=this.viewModel.featurePage&&this.viewModel.featurePage++},this._featureMenuIntersectionObserver=new IntersectionObserver(this._featureMenuIntersectionObserverCallback,{root:window.document}),this._featureMenuIntersectionObserverNode=null,this._spinner=null,this._feature=null,this._focusAbortController=null,this._drillInFlowItems=new t,this._drillInWidget=new y({flowItems:this._drillInFlowItems}),this._rootNode=null,this._rootFlowItemNode=null,this._featureMenuViewportNode=null,this._actionBarMenuNode=null,this.collapsed=!1,this.featureNavigationTop=!1,this.headerActions=new C,this.headingLevel=2,this.messages=null,this.messagesCommon=null,this.responsiveActionsEnabled=!1,this.viewModel=new b,this.visibleElements=new I,this._previousFeature=()=>{this.viewModel.previous()},this._nextFeature=()=>{this.viewModel.next()},this._handleFeatureBack=()=>{"list"===this.initialDisplayMode?(this.selectedFeatureIndex=-1,this._focusFlowItemNode()):this._openFeatureMenu()},this._handleFeatureMenuBack=()=>{"list"===this.initialDisplayMode?(this.selectedFeatureIndex=-1,this._focusFlowItemNode()):this.featureMenuOpen&&this._closeFeatureMenu()},this._storeRootNode=e=>{this._rootNode=e},this._displaySpinnerThrottled=a(()=>this._displaySpinner(),B),this._addSelectedFeatureIndexHandle(),this.addHandles([this._displaySpinnerThrottled,s(()=>this.viewModel?.active,()=>this._toggleScreenLocationEnabled()),s(()=>this.viewModel?.active,e=>this._drillInWidget.closed=!e),s(()=>this.visibleElements?.closeButton,e=>this._drillInWidget.closable=e),s(()=>this.visibleElements?.spinner,e=>this._spinnerEnabledChange(e)),s(()=>this.viewModel?.view,(e,t)=>this._viewChange(e,t)),s(()=>this.viewModel?.view?.ready,(e,t)=>this._viewReadyChange(e??!1,t??!1)),s(()=>[this.viewModel?.waitingForResult,this.viewModel?.location],()=>{this._hideSpinner(),this._displaySpinnerThrottled()}),s(()=>this.viewModel?.screenLocation,()=>this._closeOpenActionMenu()),s(()=>this.selectedFeatureWidget?.viewModel,()=>this._destroyDrillInFlowItemWidgets()),s(()=>this.featureMenuOpen,()=>this._drillInWidget.selectLastFlowItem="list"===this.initialDisplayMode||!this.featureMenuOpen,n),s(()=>{const e=this.selectedFeatureWidget?.viewModel;return[e?.title,e?.state]},()=>this._setTitleFromFeatureWidget()),s(()=>{const e=this.selectedFeatureWidget?.viewModel;return[e?.content,e?.state]},()=>this._setContentFromFeatureWidget()),s(()=>this.viewModel?.featureViewModels,()=>this._featureMenuViewportScrollTop()),s(()=>this._drillInFlowItems.length,()=>this._focusFlowItemNode()),this._drillInWidget.on("close",()=>this.close()),this._drillInWidget.on("exit",()=>this._destroyDrillInFlowItemWidgets()),this._drillInWidget.on("open-feature",({feature:e})=>this._openRelatedFeature(e)),this._drillInWidget.on("zoom-to-feature",({featureWidget:e})=>x(this.viewModel,e))])}loadDependencies(){return Promise.all([h(),A({action:()=>import("@esri/calcite-components/dist/components/calcite-action"),"action-bar":()=>import("@esri/calcite-components/dist/components/calcite-action-bar"),"action-group":()=>import("@esri/calcite-components/dist/components/calcite-action-group"),button:()=>import("@esri/calcite-components/dist/components/calcite-button"),icon:()=>import("@esri/calcite-components/dist/components/calcite-icon"),flow:()=>import("@esri/calcite-components/dist/components/calcite-flow"),"flow-item":()=>import("@esri/calcite-components/dist/components/calcite-flow-item"),list:()=>import("@esri/calcite-components/dist/components/calcite-list"),"list-item":()=>import("@esri/calcite-components/dist/components/calcite-list-item"),"list-item-group":()=>import("@esri/calcite-components/dist/components/calcite-list-item-group"),loader:()=>import("@esri/calcite-components/dist/components/calcite-loader")})])}destroy(){this._destroyDrillInFlowItemWidgets(),this._destroySelectedFeatureWidget(),this._destroySpinner(),this._unobserveFeatureMenuObserver(),this._featureMenuIntersectionObserver?.disconnect(),this._drillInWidget?.destroy(),this._focusAbortController?.abort()}get _hideActionText(){if(!this.responsiveActionsEnabled)return!1;const e=this.view?.widthBreakpoint;return"xsmall"===e||"small"===e||"medium"===e}get _featureNavigationVisible(){return this.viewModel.active&&this.viewModel.featureCount>1&&!!this.viewModel.selectedFeature&&this.visibleElements.featureNavigation}get _isCollapsed(){return this._collapseEnabled&&this.collapsed}get _collapseEnabled(){return this.visibleElements.collapseButton&&("list"===this.initialDisplayMode||!!this.title&&!!this.content)}get active(){return this.viewModel.active}get content(){return this.viewModel.content}set content(e){this.viewModel.content=e}get icon(){return null}get featureMenuOpen(){return this.viewModel.featureMenuOpen}set featureMenuOpen(e){this.viewModel.featureMenuOpen=e}get featureMenuTitle(){return this.viewModel.featureMenuTitle}set featureMenuTitle(e){this.viewModel.featureMenuTitle=e}get features(){return this.viewModel.features}set features(e){this.viewModel.features=e}get goToOverride(){return this.viewModel.goToOverride}set goToOverride(e){this.viewModel.goToOverride=e}get initialDisplayMode(){return this.viewModel.initialDisplayMode}set initialDisplayMode(e){this.viewModel.initialDisplayMode=e}get location(){return this.viewModel.location}set location(e){this.viewModel.location=e}get label(){return this.messages?.widgetLabel??""}set label(e){this._overrideIfSome("label",e)}get map(){return this.viewModel.map}set map(e){this.viewModel.map=e}get promises(){return this.viewModel.promises}set promises(e){this.viewModel.promises=e}get selectedFeature(){return this.viewModel.selectedFeature}get selectedDrillInFeature(){const e=Array.from(this._drillInFlowItems).at(-1);if(!e)return null;const{flowType:t}=e;return"feature-association"===t||"feature-relationship"===t?e.graphic??null:null}get selectedFeatureIndex(){return this.viewModel.selectedFeatureIndex}set selectedFeatureIndex(e){this.viewModel.selectedFeatureIndex=e}get selectedFeatureWidget(){const{_feature:e,headingLevel:t,_drillInFlowItems:i,timeZone:o,spatialReference:s,map:n}=this,{selectedFeatureViewModel:r}=this.viewModel,l={title:!1};return r?(e?(e.viewModel=r,e.visibleElements=l):this._feature=new g({flowItems:i,headingLevel:t+1,timeZone:o,spatialReference:s,map:n,viewModel:r,visibleElements:l}),this._feature):null}get spatialReference(){return this.viewModel.spatialReference}set spatialReference(e){this.viewModel.spatialReference=e}get title(){return this.viewModel.title}set title(e){this.viewModel.title=e}get timeZone(){return this.viewModel.timeZone}set timeZone(e){this.viewModel.timeZone=e}get updateLocationEnabled(){return this.viewModel.updateLocationEnabled}set updateLocationEnabled(e){this.viewModel.updateLocationEnabled=e}get view(){return this.viewModel.view}set view(e){this.viewModel.view=e}get visible(){return this.viewModel.visible}set visible(e){this.viewModel.visible=e}blur(){const{active:e}=this.viewModel;e?this._rootFlowItemNode?.blur():i.getLogger(this).warn("Features can only be blurred when currently active.")}clear(){return this.viewModel.clear()}close(){this.viewModel.visible=!1}fetchFeatures(e,t){return this.viewModel.fetchFeatures(e,t)}focus(){const{active:e}=this.viewModel;e?this._focusFlowItemNode():i.getLogger(this).warn("Features can only be focused when currently active.")}next(){return this.viewModel.next()}open(e){this.removeHandles(D);const t={collapsed:e?.collapsed??!1};this.set(t),this.viewModel.open(e),this.addHandles(r(()=>!this.viewModel.waitingForResult,()=>this._addSelectedFeatureIndexHandle(),{once:!0}))}previous(){return this.viewModel.previous()}triggerAction(e){return this.viewModel.triggerAction(e)}render(){return L("div",{afterCreate:this._storeRootNode,bind:this,class:this.classes(F.base,N.widget,N.panel),onkeydown:this._onMainKeydown},this._renderHeader(),this._renderContentContainer())}_renderFeatureNavigation(){return[this._renderPagination(),"list"===this.initialDisplayMode?this._renderFeaturePaginationText():this._renderFeatureMenuButton()]}_renderHeader(){return this.featureNavigationTop&&this._featureNavigationVisible?L("div",{class:F.header,key:"header-actions"},this._renderFeatureNavigation()):null}_renderFooter(){return!this.featureNavigationTop&&this._featureNavigationVisible?L("div",{class:F.footer,key:"footer-actions",slot:"footer"},this._renderFeatureNavigation()):null}_renderFeaturePaginationText(){const{messages:e,viewModel:t}=this,{featureCount:i,selectedFeatureIndex:o}=t;return L("div",{class:F.paginationText,key:"feature-pagination-text"},j(e.pageText,{index:W(o+1),total:W(i)}))}_renderFeatureMenuButton(){const{messages:e,viewModel:t}=this,{featureCount:i,selectedFeatureIndex:o,pendingPromisesCount:s}=t;return L("calcite-action",{appearance:"solid",bind:this,class:F.paginationMenuButton,icon:"list",key:"feature-menu-button",label:e.selectFeature,loading:s>0,onclick:this._handlePaginationMenuButton,scale:"s",text:j(e.pageText,{index:W(o+1),total:W(i)}),textEnabled:!0,title:e.selectFeature})}_renderPagination(){const{previous:e,next:t}=this.messagesCommon.pagination;return L("calcite-action-bar",{class:F.paginationActionBar,expandDisabled:!0,key:"pagination-action-bar",layout:"horizontal",overflowActionsDisabled:!0,scale:"s"},L("calcite-action-group",{scale:"s"},L("calcite-action",{appearance:"solid",class:F.paginationPrevious,icon:"chevron-left",iconFlipRtl:!0,label:e,onclick:this._previousFeature,scale:"s",text:e,title:e}),L("calcite-action",{appearance:"solid",icon:"chevron-right",iconFlipRtl:!0,label:t,onclick:this._nextFeature,scale:"s",text:t,title:t})))}_renderFeatureMenuItem(e){const{initialDisplayMode:t}=this,{selectedFeatureViewModel:i,featureViewModels:o}=this.viewModel,s=e===i,n=o.indexOf(e);return L("calcite-list-item",{bind:this,"data-feature-index":n,key:`feature-menu-item-${e.uid}`,onblur:this._removeActiveFeature,onfocus:this._setActiveFeature,onmouseleave:this._removeActiveFeature,onmouseover:this._setActiveFeature,selected:s,onCalciteListItemSelect:this._selectFeature},L("span",{innerHTML:e.title||this.messagesCommon.untitled,slot:"content"}),"list"===t?L("calcite-icon",{flipRtl:!0,icon:"chevron-right",scale:"s",slot:"content-end"}):null)}_groupResultsByLayer(){const{featureViewModels:e}=this.viewModel,t=new Map;return e.forEach(e=>{const i=e?.graphic;if(!i)return;const{layer:o,sourceLayer:s}=i,n=(R(o)?o:null)||(R(s)?s:null),r=t.get(n)??[];t.set(n,[...r,e])}),t}_renderFeatureMenu(){const{messages:e,viewModel:t}=this,i=this._groupResultsByLayer(),o="list"===this.initialDisplayMode?"none":"single";return t.featureViewModels.length?L("calcite-list",{displayMode:"flat",label:e?.featuresList,selectionAppearance:"icon",selectionMode:o},Array.from(i.keys(),e=>{const t=i.get(e)?.map(e=>this._renderFeatureMenuItem(e)),o=e?e.title??this.messagesCommon.untitled:null;return this.visibleElements.featureListLayerTitle&&null!==o?L("calcite-list-item-group",{heading:o,key:e?.uid||"map-graphics"},t):t})):null}_renderHeaderAction(e,t){const i=e.title||"";return e.visible?L("calcite-action",{active:"toggle"===e.type&&e.value,appearance:"solid",bind:this,"data-action-id":e.id,"data-action-uid":e.uid,disabled:e.disabled,icon:e.icon??void 0,indicator:e.indicator,key:`header-action-${t}`,loading:e.active,onclick:this._triggerHeaderAction,slot:"header-actions-end",text:i,title:i}):null}_renderHeaderActions(){return this.headerActions.map((e,t)=>this._renderHeaderAction(e,t)).toArray()}_renderContentFeature(){const{headingLevel:e,visibleElements:t,_isCollapsed:i,_collapseEnabled:o,featureNavigationTop:s,_drillInFlowItems:n,initialDisplayMode:r,selectedFeature:l,featureMenuOpen:a}=this,{title:d,active:c}=this.viewModel,u=t.heading&&d?d:"";if("list"===r&&!l)return null;const h=0===n.length&&("list"===r?!!l:!a);return L("calcite-flow-item",{afterCreate:this._storeRootFlowItemNode,bind:this,class:this.classes({[F.contentFeature]:!0,[F.flowItemCollapsed]:i}),closable:t.closeButton,closed:!c,collapsed:i,collapseDirection:s?"down":"up",collapsible:o,headingLevel:e,key:"root-flow-item",selected:h,onCalciteFlowItemBack:this._handleFeatureBack,onCalciteFlowItemClose:this.close,onCalciteFlowItemToggle:this._handleCollapseToggle},u?L(T,{class:this.classes(F.featuresHeading,N.heading),innerHTML:u,key:"header-content",level:this.headingLevel,slot:"header-content"}):null,this._renderHeaderActions(),this._renderActionBar(),L("div",{class:this.classes(F.container,F.contentContainer)},this._renderContent()),this._renderFooter())}_renderFeatureMenuContainer(){const{viewModel:e,visibleElements:t,featureMenuTitle:i,messages:o,messagesCommon:s,initialDisplayMode:n,featureMenuOpen:r,selectedFeature:l,_collapseEnabled:a,_isCollapsed:d,featureNavigationTop:c,headingLevel:u}=this,{active:h,featureViewModels:p,pendingPromisesCount:m}=e,{featureMenuHeading:v}=t,g=i??o.selectFeature;if("feature"===n&&!r)return null;const w="list"===n?!l:r;return L("calcite-flow-item",{afterCreate:this._storeFeatureMenuFlowItemNode,bind:this,class:this.classes({[F.flowItemCollapsed]:d}),closable:"list"===n&&t.closeButton,closed:!h,collapsed:"list"===n&&d,collapseDirection:c?"down":"up",collapsible:"list"===n&&a,description:v?j(o.total,{total:p.length}):void 0,heading:v?g:void 0,headingLevel:u,key:"feature-menu",loading:e.waitingForContents,selected:w,onCalciteFlowItemBack:e=>{e.preventDefault(),this._handleFeatureMenuBack()},onCalciteFlowItemClose:this.close,onCalciteFlowItemToggle:this._handleCollapseToggle},"list"===n?this._renderHeaderActions():null,m>0?L("calcite-loader",{class:F.loader,inline:!0,key:"feature-menu-loader",label:s.loading,slot:"header-actions-end"}):null,L("div",{class:F.container},this._renderFeatureMenu()),L("div",{afterCreate:this._featureMenuIntersectionObserverCreated,bind:this,class:F.featureMenuObserver}),"feature"===n?L("calcite-button",{appearance:"transparent",onclick:this._handleFeatureMenuBack,slot:"footer-actions",width:"full"},s.back):null)}_renderContentContainer(){const e="list"===this.initialDisplayMode?[this._renderFeatureMenuContainer(),this._renderContentFeature(),this._drillInWidget.render()]:[this._renderContentFeature(),this._drillInWidget.render(),this._renderFeatureMenuContainer()];return this.visibleElements.flow?L("calcite-flow",{key:"content-container"},e):e}_getFallbackIcon(e){const{className:t,icon:i}=e;if(i)return null;const o=p({action:e,feature:this.selectedFeature}),s={[F.icon]:!!t,[F.actionImage]:!!o};return t&&(s[t]=!0),o||t?L("span",{"aria-hidden":"true",class:this.classes(F.icon,s),key:"icon",styles:m(o)}):null}_renderActionBar(){return!this._isCollapsed&&this.visibleElements.actionBar&&this.viewModel.allActions?.length?L("calcite-action-bar",{expandDisabled:!0,expanded:!this._hideActionText,key:"header-action-bar",scale:"s",slot:"action-bar"},L("calcite-action-group",{afterCreate:e=>this._actionBarMenuNode=e,overlayPositioning:"fixed",scale:"s"},this._renderActions())):null}_renderActions(){return this.viewModel.allActions.toArray().map((e,t)=>{const i=this._getActionTitle(e);return v(e,{key:`action-${t}`,title:i,text:i,textEnabled:!this._hideActionText,onclick:this._triggerAction,bind:this},this._getFallbackIcon(e))})}_renderContent(){const e=this.viewModel?.content;return e?"string"==typeof e?L("div",{class:M.contentNode,innerHTML:e,key:e}):this.renderNodeContent(e):null}_handleCollapseToggle(){this.collapsed=!this.collapsed}async _openRelatedFeature(e){await e.viewModel.updateGeometry();const t=e.graphic,i=t?.geometry;if(null==i||null==t)return;this._destroyDrillInFlowItemWidgets(),await this.viewModel.zoomTo({target:i});const o=u(i);this.open({features:[t],location:null!=o?o:void 0}),this._focusFlowItemNode()}_handlePaginationMenuButton(){this._updateFeatureMenu()}_openFeatureMenu(){this._updateFeatureMenu(!0)}_closeFeatureMenu(){this._updateFeatureMenu(!1)}_updateFeatureMenu(e=!this.featureMenuOpen){this.featureMenuOpen=e,this._focusFlowItemNode()}async _focusFlowItemNode(){this._focusAbortController?.abort(),this._focusAbortController=new AbortController;const e=this._focusAbortController.signal;await o(l(e));const t=this._rootNode?.querySelector("calcite-flow-item[selected]");k(t)}_storeRootFlowItemNode(e){this._rootFlowItemNode=e}_storeFeatureMenuFlowItemNode(e){this._featureMenuViewportNode=e}_setActiveFeature(e){const{viewModel:t}=this,i=e.currentTarget["data-feature-index"];t.activeFeature=t.features?.[i]||null}_removeActiveFeature(){this.viewModel.activeFeature=null}_selectFeature(e){const t=e.currentTarget["data-feature-index"];isNaN(t)||(this.viewModel.selectedFeatureIndex=t),"feature"===this.initialDisplayMode?this._handleFeatureMenuBack():this._focusFlowItemNode()}_unobserveFeatureMenuObserver(){this._featureMenuIntersectionObserverNode&&this._featureMenuIntersectionObserver.unobserve(this._featureMenuIntersectionObserverNode)}_featureMenuIntersectionObserverCreated(e){this._unobserveFeatureMenuObserver(),this._featureMenuIntersectionObserver.observe(e),this._featureMenuIntersectionObserverNode=e}_getActionTitle(e){const{messages:t,selectedFeature:i,messagesCommon:o}=this,{id:s}=e,n=i?.attributes,r=e.title??"",l="zoom-to-feature"===s?j(r,{messages:t}):"remove-selected-feature"===s?j(r,{messages:o}):"zoom-to-clustered-features"===s||"browse-clustered-features"===s?j(r,{messages:t}):e.title;return l&&n?j(l,n):l??""}_onMainKeydown(e){const{key:t}=e;"ArrowLeft"===t&&(e.stopPropagation(),this._handleFeatureMenuBack(),this.previous()),"ArrowRight"===t&&(e.stopPropagation(),this._handleFeatureMenuBack(),this.next())}_featureMenuViewportScrollTop(){this._featureMenuViewportNode&&this._featureMenuViewportNode.scrollContentTo({top:0})}_setContentFromFeatureWidget(){const{selectedFeatureWidget:e}=this;e&&(this.viewModel.content=e)}_setTitleFromFeatureWidget(){const{selectedFeatureWidget:e,messagesCommon:t}=this,i=e?.viewModel;e&&(this.viewModel.title="error"===i?.state?t?.errorMessage:i?.title||"")}_addSelectedFeatureIndexHandle(){const e=s(()=>this.viewModel?.selectedFeatureIndex,(e,t)=>this._selectedFeatureIndexUpdated(e,t));this.addHandles(e,D)}_selectedFeatureIndexUpdated(e,t){const{featureCount:i}=this.viewModel;i&&e!==t&&-1!==e&&(this._destroyDrillInFlowItemWidgets(),this._rootFlowItemNode&&this._rootFlowItemNode.scrollContentTo({top:0}))}_triggerHeaderAction(e){const t=e.currentTarget;if(t.disabled)return;const i=t.dataset.actionUid,o=this.headerActions.find(({uid:e})=>e===i);o&&!o.disabled&&("toggle"===o?.type&&(o.value=!o.value),this.emit("trigger-header-action",{action:o}))}_triggerAction(e){const t=e.currentTarget;if(t.disabled)return;const i=t.dataset.actionUid,{allActions:o}=this.viewModel,s=o.findIndex(e=>e.uid===i),n=o.at(s);n&&"toggle"===n.type&&(n.value=!n.value),this.viewModel.triggerAction(s)}_createSpinner(e){e&&(this._spinner=new w({view:e}),e.ui.add(this._spinner,{key:S,position:"manual",internal:!0}))}_wireUpView(e){this._destroySpinner(),e&&this.visibleElements?.spinner&&this._createSpinner(e)}_hideSpinner(){const{_spinner:e}=this;e&&(e.location=null,e.hide())}_viewReadyChange(e,t){e?this._wireUpView(this.viewModel?.view):t&&this.viewModel.clear()}_viewChange(e,t){e&&t&&this.viewModel.clear()}_destroySelectedFeatureWidget(){const{_feature:e}=this;e&&(e.viewModel=null,!e.destroyed&&e.destroy()),this._feature=null}_closeOpenActionMenu(){const{_actionBarMenuNode:e}=this;e&&(e.menuOpen=!1)}_destroyDrillInFlowItemWidgets(){this._drillInFlowItems.drain(e=>{"showAllEnabled"in e.viewModel&&(e.viewModel.showAllEnabled=!1),"activeCategory"in e.viewModel&&(e.viewModel.activeCategory=null),e.viewModel=null,e.destroy()})}_toggleScreenLocationEnabled(){const{viewModel:e}=this;e&&(e.screenLocationEnabled=e.active)}_displaySpinner(){const{_spinner:e}=this;if(!e)return;const{location:t,waitingForResult:i}=this.viewModel;i&&t?e.show({location:t}):e.hide()}_destroySpinner(){const{_spinner:e}=this;e&&(e.view?.ui?.remove(e,S),e.destroy(),this._spinner=null)}_spinnerEnabledChange(e){this._destroySpinner(),e&&this._createSpinner(this.viewModel?.view)}};e([d()],H.prototype,"_drillInFlowItems",void 0),e([d()],H.prototype,"_hideActionText",null),e([d()],H.prototype,"_featureNavigationVisible",null),e([d()],H.prototype,"_isCollapsed",null),e([d()],H.prototype,"_collapseEnabled",null),e([d({readOnly:!0})],H.prototype,"active",null),e([d()],H.prototype,"collapsed",void 0),e([d()],H.prototype,"content",null),e([d()],H.prototype,"icon",null),e([d()],H.prototype,"featureMenuOpen",null),e([d()],H.prototype,"featureMenuTitle",null),e([d()],H.prototype,"featureNavigationTop",void 0),e([d()],H.prototype,"features",null),e([d()],H.prototype,"goToOverride",null),e([d({type:C})],H.prototype,"headerActions",void 0),e([d()],H.prototype,"headingLevel",void 0),e([d()],H.prototype,"initialDisplayMode",null),e([d()],H.prototype,"location",null),e([d()],H.prototype,"label",null),e([d()],H.prototype,"map",null),e([d(),O("esri/widgets/Features/t9n/Features")],H.prototype,"messages",void 0),e([d(),O("esri/t9n/common")],H.prototype,"messagesCommon",void 0),e([d()],H.prototype,"promises",null),e([d()],H.prototype,"responsiveActionsEnabled",void 0),e([d({readOnly:!0})],H.prototype,"selectedFeature",null),e([d({readOnly:!0})],H.prototype,"selectedDrillInFeature",null),e([d()],H.prototype,"selectedFeatureIndex",null),e([d({readOnly:!0})],H.prototype,"selectedFeatureWidget",null),e([d()],H.prototype,"spatialReference",null),e([d()],H.prototype,"title",null),e([d()],H.prototype,"timeZone",null),e([d()],H.prototype,"updateLocationEnabled",null),e([d()],H.prototype,"view",null),e([d({type:b}),E(["triggerAction","trigger-action"])],H.prototype,"viewModel",void 0),e([d({type:I,nonNullable:!0})],H.prototype,"visibleElements",void 0),e([d()],H.prototype,"visible",null),H=e([c("esri.widgets.Features")],H);export{H as default};
5
+ import{__decorate as e}from"tslib";import"../intl.js";import t from"../core/Collection.js";import i from"../core/Logger.js";import{ignoreAbortErrors as o}from"../core/promiseUtils.js";import{watch as s,initial as n,when as r}from"../core/reactiveUtils.js";import{waitAnimationFrame as l}from"../core/scheduling.js";import{throttle as a}from"../core/throttle.js";import{property as d}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/RandomLCG.js";import{subclass as c}from"../core/accessorSupport/decorators/subclass.js";import{getPointFromGeometry as u}from"../geometry/support/geometryUtils.js";import{loadActionUtilsComponents as h,substituteActionImage as p,getActionStyles as m,renderAction as v}from"../support/actions/actionUtils.js";import g from"./Feature.js";import w from"./Spinner.js";import _ from"./Widget.js";import{css as M}from"./Feature/resources.js";import{FeatureContentMixin as f}from"./Feature/support/FeatureContentMixin.js";import{css as F}from"./Features/css.js";import y from"./Features/FeaturesDrillIn.js";import b from"./Features/FeaturesViewModel.js";import I from"./Features/FeaturesVisibleElements.js";import{ActionsCollection as C}from"./Popup/actions.js";import{zoomToLocation as x}from"./Popup/actionUtils.js";import{loadCalciteComponents as A}from"./support/componentsUtils.js";import{globalCss as T}from"./support/globalCss.js";import{Heading as N}from"./support/Heading.js";import{setFocus as k}from"./support/widgetUtils.js";import{messageBundle as O}from"./support/decorators/messageBundle.js";import{vmEvent as E}from"./support/decorators/vmEvent.js";import{tsx as L}from"./support/jsxFactory.js";import{substitute as j}from"../intl/substitute.js";import{formatNumber as W}from"../intl/number.js";const D="selected-index",B=0,S="features-spinner";function R(e){return e?.declaredClass.startsWith("esri.layers.")??!1}let H=class extends(f(_)){constructor(e,i){super(e,i),this._featureMenuIntersectionObserverCallback=([e])=>{e?.isIntersecting&&null!=this.viewModel.featurePage&&this.viewModel.featurePage++},this._featureMenuIntersectionObserver=new IntersectionObserver(this._featureMenuIntersectionObserverCallback,{root:window.document}),this._featureMenuIntersectionObserverNode=null,this._spinner=null,this._feature=null,this._focusAbortController=null,this._drillInFlowItems=new t,this._drillInWidget=new y({flowItems:this._drillInFlowItems}),this._rootNode=null,this._rootFlowItemNode=null,this._featureMenuViewportNode=null,this._actionBarMenuNode=null,this.collapsed=!1,this.featureNavigationTop=!1,this.headerActions=new C,this.headingLevel=2,this.messages=null,this.messagesCommon=null,this.responsiveActionsEnabled=!1,this.viewModel=new b,this.visibleElements=new I,this._previousFeature=()=>{this.viewModel.previous()},this._nextFeature=()=>{this.viewModel.next()},this._handleFeatureBack=()=>{"list"===this.initialDisplayMode?(this.selectedFeatureIndex=-1,this._focusFlowItemNode()):this._openFeatureMenu()},this._handleFeatureMenuBack=()=>{"list"===this.initialDisplayMode?(this.selectedFeatureIndex=-1,this._focusFlowItemNode()):this.featureMenuOpen&&this._closeFeatureMenu()},this._storeRootNode=e=>{this._rootNode=e},this._displaySpinnerThrottled=a(()=>this._displaySpinner(),B),this._addSelectedFeatureIndexHandle(),this.addHandles([this._displaySpinnerThrottled,s(()=>this.viewModel?.active,()=>this._toggleScreenLocationEnabled()),s(()=>this.viewModel?.active,e=>this._drillInWidget.closed=!e),s(()=>this.visibleElements?.closeButton,e=>this._drillInWidget.closable=e),s(()=>this.visibleElements?.spinner,e=>this._spinnerEnabledChange(e)),s(()=>this.viewModel?.view,(e,t)=>this._viewChange(e,t)),s(()=>this.viewModel?.view?.ready,(e,t)=>this._viewReadyChange(e??!1,t??!1)),s(()=>[this.viewModel?.waitingForResult,this.viewModel?.location],()=>{this._hideSpinner(),this._displaySpinnerThrottled()}),s(()=>this.viewModel?.screenLocation,()=>this._closeOpenActionMenu()),s(()=>this.selectedFeatureWidget?.viewModel,()=>this._destroyDrillInFlowItemWidgets()),s(()=>this.featureMenuOpen,()=>this._drillInWidget.selectLastFlowItem="list"===this.initialDisplayMode||!this.featureMenuOpen,n),s(()=>{const e=this.selectedFeatureWidget?.viewModel;return[e?.title,e?.state]},()=>this._setTitleFromFeatureWidget()),s(()=>{const e=this.selectedFeatureWidget?.viewModel;return[e?.content,e?.state]},()=>this._setContentFromFeatureWidget()),s(()=>this.viewModel?.featureViewModels,()=>this._featureMenuViewportScrollTop()),s(()=>this._drillInFlowItems.length,()=>this._focusFlowItemNode()),this._drillInWidget.on("close",()=>this.close()),this._drillInWidget.on("exit",()=>this._destroyDrillInFlowItemWidgets()),this._drillInWidget.on("open-feature",({feature:e})=>this._openRelatedFeature(e)),this._drillInWidget.on("zoom-to-feature",({featureWidget:e})=>x(this.viewModel,e))])}loadDependencies(){return Promise.all([h(),A({action:()=>import("@esri/calcite-components/dist/components/calcite-action"),"action-bar":()=>import("@esri/calcite-components/dist/components/calcite-action-bar"),"action-group":()=>import("@esri/calcite-components/dist/components/calcite-action-group"),button:()=>import("@esri/calcite-components/dist/components/calcite-button"),icon:()=>import("@esri/calcite-components/dist/components/calcite-icon"),flow:()=>import("@esri/calcite-components/dist/components/calcite-flow"),"flow-item":()=>import("@esri/calcite-components/dist/components/calcite-flow-item"),list:()=>import("@esri/calcite-components/dist/components/calcite-list"),"list-item":()=>import("@esri/calcite-components/dist/components/calcite-list-item"),"list-item-group":()=>import("@esri/calcite-components/dist/components/calcite-list-item-group"),loader:()=>import("@esri/calcite-components/dist/components/calcite-loader")})])}destroy(){this._destroyDrillInFlowItemWidgets(),this._destroySelectedFeatureWidget(),this._destroySpinner(),this._unobserveFeatureMenuObserver(),this._featureMenuIntersectionObserver?.disconnect(),this._drillInWidget?.destroy(),this._focusAbortController?.abort()}get _hideActionText(){if(!this.responsiveActionsEnabled)return!1;const e=this.view?.widthBreakpoint;return"xsmall"===e||"small"===e||"medium"===e}get _featureNavigationVisible(){return this.viewModel.active&&this.viewModel.featureCount>1&&!!this.viewModel.selectedFeature&&this.visibleElements.featureNavigation}get _isCollapsed(){return this._collapseEnabled&&this.collapsed}get _collapseEnabled(){return this.visibleElements.collapseButton&&("list"===this.initialDisplayMode||!!this.title&&!!this.content)}get active(){return this.viewModel.active}get content(){return this.viewModel.content}set content(e){this.viewModel.content=e}get icon(){return null}get featureMenuOpen(){return this.viewModel.featureMenuOpen}set featureMenuOpen(e){this.viewModel.featureMenuOpen=e}get featureMenuTitle(){return this.viewModel.featureMenuTitle}set featureMenuTitle(e){this.viewModel.featureMenuTitle=e}get features(){return this.viewModel.features}set features(e){this.viewModel.features=e}get goToOverride(){return this.viewModel.goToOverride}set goToOverride(e){this.viewModel.goToOverride=e}get initialDisplayMode(){return this.viewModel.initialDisplayMode}set initialDisplayMode(e){this.viewModel.initialDisplayMode=e}get location(){return this.viewModel.location}set location(e){this.viewModel.location=e}get label(){return this.messages?.widgetLabel??""}set label(e){this._overrideIfSome("label",e)}get map(){return this.viewModel.map}set map(e){this.viewModel.map=e}get promises(){return this.viewModel.promises}set promises(e){this.viewModel.promises=e}get selectedFeature(){return this.viewModel.selectedFeature}get selectedDrillInFeature(){const e=Array.from(this._drillInFlowItems).at(-1);if(!e)return null;const{flowType:t}=e;return"feature-association"===t||"feature-relationship"===t?e.graphic??null:null}get selectedFeatureIndex(){return this.viewModel.selectedFeatureIndex}set selectedFeatureIndex(e){this.viewModel.selectedFeatureIndex=e}get selectedFeatureWidget(){const{_feature:e,headingLevel:t,_drillInFlowItems:i,timeZone:o,spatialReference:s,map:n}=this,{selectedFeatureViewModel:r}=this.viewModel,l={title:!1};return r?(e?(e.viewModel=r,e.visibleElements=l):this._feature=new g({flowItems:i,headingLevel:t+1,timeZone:o,spatialReference:s,map:n,viewModel:r,visibleElements:l}),this._feature):null}get spatialReference(){return this.viewModel.spatialReference}set spatialReference(e){this.viewModel.spatialReference=e}get title(){return this.viewModel.title}set title(e){this.viewModel.title=e}get timeZone(){return this.viewModel.timeZone}set timeZone(e){this.viewModel.timeZone=e}get updateLocationEnabled(){return this.viewModel.updateLocationEnabled}set updateLocationEnabled(e){this.viewModel.updateLocationEnabled=e}get view(){return this.viewModel.view}set view(e){this.viewModel.view=e}get visible(){return this.viewModel.visible}set visible(e){this.viewModel.visible=e}blur(){const{active:e}=this.viewModel;e?this._rootFlowItemNode?.blur():i.getLogger(this).warn("Features can only be blurred when currently active.")}clear(){return this.viewModel.clear()}close(){this.viewModel.visible=!1}fetchFeatures(e,t){return this.viewModel.fetchFeatures(e,t)}focus(){const{active:e}=this.viewModel;e?this._focusFlowItemNode():i.getLogger(this).warn("Features can only be focused when currently active.")}next(){return this.viewModel.next()}open(e){this.removeHandles(D);const t={collapsed:e?.collapsed??!1};this.set(t),this.viewModel.open(e),this.addHandles(r(()=>!this.viewModel.waitingForResult,()=>this._addSelectedFeatureIndexHandle(),{once:!0}))}previous(){return this.viewModel.previous()}triggerAction(e){return this.viewModel.triggerAction(e)}render(){return L("div",{afterCreate:this._storeRootNode,bind:this,class:this.classes(F.base,T.widget,T.panel),onkeydown:this._onMainKeydown},this._renderHeader(),this._renderContentContainer())}_renderFeatureNavigation(){return[this._renderPagination(),"list"===this.initialDisplayMode?this._renderFeaturePaginationText():this._renderFeatureMenuButton()]}_renderHeader(){return this.featureNavigationTop&&this._featureNavigationVisible?L("div",{class:F.header,key:"header-actions"},this._renderFeatureNavigation()):null}_renderFooter(){return!this.featureNavigationTop&&this._featureNavigationVisible?L("div",{class:F.footer,key:"footer-actions",slot:"footer"},this._renderFeatureNavigation()):null}_renderFeaturePaginationText(){const{messages:e,viewModel:t}=this,{featureCount:i,selectedFeatureIndex:o}=t;return L("div",{class:F.paginationText,key:"feature-pagination-text"},j(e.pageText,{index:W(o+1),total:W(i)}))}_renderFeatureMenuButton(){const{messages:e,viewModel:t}=this,{featureCount:i,selectedFeatureIndex:o,pendingPromisesCount:s}=t;return L("calcite-action",{appearance:"solid",bind:this,class:F.paginationMenuButton,icon:"list",key:"feature-menu-button",label:e.selectFeature,loading:s>0,onclick:this._handlePaginationMenuButton,scale:"s",text:j(e.pageText,{index:W(o+1),total:W(i)}),textEnabled:!0,title:e.selectFeature})}_renderPagination(){const{previous:e,next:t}=this.messagesCommon.pagination;return L("calcite-action-bar",{class:F.paginationActionBar,expandDisabled:!0,key:"pagination-action-bar",layout:"horizontal",overflowActionsDisabled:!0,scale:"s"},L("calcite-action-group",{scale:"s"},L("calcite-action",{appearance:"solid",class:F.paginationPrevious,icon:"chevron-left",iconFlipRtl:!0,label:e,onclick:this._previousFeature,scale:"s",text:e,title:e}),L("calcite-action",{appearance:"solid",icon:"chevron-right",iconFlipRtl:!0,label:t,onclick:this._nextFeature,scale:"s",text:t,title:t})))}_renderFeatureMenuItem(e){const{initialDisplayMode:t}=this,{selectedFeatureViewModel:i,featureViewModels:o}=this.viewModel,s=e===i,n=o.indexOf(e);return L("calcite-list-item",{bind:this,"data-feature-index":n,key:`feature-menu-item-${e.uid}`,onblur:this._removeActiveFeature,onfocus:this._setActiveFeature,onmouseleave:this._removeActiveFeature,onmouseover:this._setActiveFeature,selected:s,onCalciteListItemSelect:this._selectFeature},L("span",{innerHTML:e.title||this.messagesCommon.untitled,slot:"content"}),"list"===t?L("calcite-icon",{flipRtl:!0,icon:"chevron-right",scale:"s",slot:"content-end"}):null)}_groupResultsByLayer(){const{featureViewModels:e}=this.viewModel,t=new Map;return e.forEach(e=>{const i=e?.graphic;if(!i)return;const{layer:o,sourceLayer:s}=i,n=(R(o)?o:null)||(R(s)?s:null),r=t.get(n)??[];t.set(n,[...r,e])}),t}_renderFeatureMenu(){const{messages:e,viewModel:t}=this,i=this._groupResultsByLayer(),o="list"===this.initialDisplayMode?"none":"single";return t.featureViewModels.length?L("calcite-list",{displayMode:"flat",label:e?.featuresList,selectionAppearance:"icon",selectionMode:o},Array.from(i.keys(),e=>{const t=i.get(e)?.map(e=>this._renderFeatureMenuItem(e)),o=e?e.title??this.messagesCommon.untitled:null;return this.visibleElements.featureListLayerTitle&&null!==o?L("calcite-list-item-group",{heading:o,key:e?.uid||"map-graphics"},t):t})):null}_renderHeaderAction(e,t){const i=e.title||"";return e.visible?L("calcite-action",{active:"toggle"===e.type&&e.value,appearance:"solid",bind:this,"data-action-id":e.id,"data-action-uid":e.uid,disabled:e.disabled,icon:e.icon??void 0,indicator:e.indicator,key:`header-action-${t}`,loading:e.active,onclick:this._triggerHeaderAction,slot:"header-actions-end",text:i,title:i}):null}_renderHeaderActions(){return this.headerActions.map((e,t)=>this._renderHeaderAction(e,t)).toArray()}_renderContentFeature(){const{headingLevel:e,visibleElements:t,_isCollapsed:i,_collapseEnabled:o,featureNavigationTop:s,_drillInFlowItems:n,initialDisplayMode:r,selectedFeature:l,featureMenuOpen:a}=this,{title:d,active:c}=this.viewModel,u=t.heading&&d?d:"";if("list"===r&&!l)return null;const h=0===n.length&&("list"===r?!!l:!a);return L("calcite-flow-item",{afterCreate:this._storeRootFlowItemNode,bind:this,class:this.classes({[F.contentFeature]:!0,[F.flowItemCollapsed]:i}),closable:t.closeButton,closed:!c,collapsed:i,collapseDirection:s?"down":"up",collapsible:o,headingLevel:e,key:"root-flow-item",selected:h,onCalciteFlowItemBack:this._handleFeatureBack,onCalciteFlowItemClose:this.close,onCalciteFlowItemToggle:this._handleCollapseToggle},u?L(N,{class:this.classes(F.featuresHeading,T.heading),innerHTML:u,key:"header-content",level:this.headingLevel,slot:"header-content"}):null,this._renderHeaderActions(),this._renderActionBar(),L("div",{class:this.classes(F.container,F.contentContainer)},this._renderContent()),this._renderFooter())}_renderFeatureMenuContainer(){const{viewModel:e,visibleElements:t,featureMenuTitle:i,messages:o,messagesCommon:s,initialDisplayMode:n,featureMenuOpen:r,selectedFeature:l,_collapseEnabled:a,_isCollapsed:d,featureNavigationTop:c,headingLevel:u}=this,{active:h,featureViewModels:p,pendingPromisesCount:m}=e,{featureMenuHeading:v}=t,g=i??o.selectFeature;if("feature"===n&&!r)return null;const w="list"===n?!l:r;return L("calcite-flow-item",{afterCreate:this._storeFeatureMenuFlowItemNode,bind:this,class:this.classes({[F.flowItemCollapsed]:d}),closable:"list"===n&&t.closeButton,closed:!h,collapsed:"list"===n&&d,collapseDirection:c?"down":"up",collapsible:"list"===n&&a,description:v?j(o.total,{total:p.length}):void 0,heading:v?g:void 0,headingLevel:u,key:"feature-menu",loading:e.waitingForContents,selected:w,onCalciteFlowItemBack:e=>{e.preventDefault(),this._handleFeatureMenuBack()},onCalciteFlowItemClose:this.close,onCalciteFlowItemToggle:this._handleCollapseToggle},"list"===n?this._renderHeaderActions():null,m>0?L("calcite-loader",{class:F.loader,inline:!0,key:"feature-menu-loader",label:s.loading,slot:"header-actions-end"}):null,L("div",{class:F.container},this._renderFeatureMenu()),L("div",{afterCreate:this._featureMenuIntersectionObserverCreated,bind:this,class:F.featureMenuObserver}),"feature"===n?L("calcite-button",{appearance:"transparent",onclick:this._handleFeatureMenuBack,slot:"footer-actions",width:"full"},s.back):null)}_renderContentContainer(){const e="list"===this.initialDisplayMode?[this._renderFeatureMenuContainer(),this._renderContentFeature(),this._drillInWidget.render()]:[this._renderContentFeature(),this._drillInWidget.render(),this._renderFeatureMenuContainer()];return this.visibleElements.flow?L("calcite-flow",{key:"content-container"},e):e}_getFallbackIcon(e){const{className:t,icon:i}=e;if(i)return null;const o=p({action:e,feature:this.selectedFeature}),s={[F.icon]:!!t,[F.actionImage]:!!o};return t&&(s[t]=!0),o||t?L("span",{"aria-hidden":"true",class:this.classes(F.icon,s),key:"icon",styles:m(o)}):null}_renderActionBar(){return!this._isCollapsed&&this.visibleElements.actionBar&&this.viewModel.allActions?.length?L("calcite-action-bar",{expandDisabled:!0,expanded:!this._hideActionText,key:"header-action-bar",scale:"s",slot:"action-bar"},L("calcite-action-group",{afterCreate:e=>this._actionBarMenuNode=e,overlayPositioning:"fixed",scale:"s"},this._renderActions())):null}_renderActions(){return this.viewModel.allActions.toArray().map((e,t)=>{const i=this._getActionTitle(e);return v(e,{key:`action-${t}`,title:i,text:i,textEnabled:!this._hideActionText,onclick:this._triggerAction,bind:this},this._getFallbackIcon(e))})}_renderContent(){const e=this.viewModel?.content;return e?"string"==typeof e?L("div",{class:M.contentNode,innerHTML:e,key:e}):this.renderNodeContent(e):null}_handleCollapseToggle(){this.collapsed=!this.collapsed}async _openRelatedFeature(e){await e.viewModel.updateGeometry();const t=e.graphic,i=t?.geometry;if(null==i||null==t)return;this._destroyDrillInFlowItemWidgets(),await this.viewModel.zoomTo({target:i});const o=u(i);this.open({features:[t],location:null!=o?o:void 0}),this._focusFlowItemNode()}_handlePaginationMenuButton(){this._updateFeatureMenu()}_openFeatureMenu(){this._updateFeatureMenu(!0)}_closeFeatureMenu(){this._updateFeatureMenu(!1)}_updateFeatureMenu(e=!this.featureMenuOpen){this.featureMenuOpen=e,this._focusFlowItemNode()}async _focusFlowItemNode(){this._focusAbortController?.abort(),this._focusAbortController=new AbortController;const e=this._focusAbortController.signal;await o(l(e));const t=this._rootNode?.querySelector("calcite-flow-item[selected]");k(t)}_storeRootFlowItemNode(e){this._rootFlowItemNode=e}_storeFeatureMenuFlowItemNode(e){this._featureMenuViewportNode=e}_setActiveFeature(e){const{viewModel:t}=this,i=e.currentTarget["data-feature-index"];t.activeFeature=t.features?.[i]||null}_removeActiveFeature(){this.viewModel.activeFeature=null}_selectFeature(e){const t=e.currentTarget["data-feature-index"];isNaN(t)||(this.viewModel.selectedFeatureIndex=t),"feature"===this.initialDisplayMode?this._handleFeatureMenuBack():this._focusFlowItemNode()}_unobserveFeatureMenuObserver(){this._featureMenuIntersectionObserverNode&&this._featureMenuIntersectionObserver.unobserve(this._featureMenuIntersectionObserverNode)}_featureMenuIntersectionObserverCreated(e){this._unobserveFeatureMenuObserver(),this._featureMenuIntersectionObserver.observe(e),this._featureMenuIntersectionObserverNode=e}_getActionTitle(e){const{messages:t,selectedFeature:i,messagesCommon:o}=this,{id:s}=e,n=i?.attributes,r=e.title??"",l="zoom-to-feature"===s?j(r,{messages:t}):"remove-selected-feature"===s?j(r,{messages:o}):"zoom-to-clustered-features"===s||"browse-clustered-features"===s?j(r,{messages:t}):e.title;return l&&n?j(l,n):l??""}_onMainKeydown(e){const{key:t}=e;"ArrowLeft"===t&&(e.stopPropagation(),this._handleFeatureMenuBack(),this.previous()),"ArrowRight"===t&&(e.stopPropagation(),this._handleFeatureMenuBack(),this.next())}_featureMenuViewportScrollTop(){this._featureMenuViewportNode?.scrollContentTo({top:0})}_setContentFromFeatureWidget(){const{selectedFeatureWidget:e}=this;e&&(this.viewModel.content=e)}_setTitleFromFeatureWidget(){const{selectedFeatureWidget:e,messagesCommon:t}=this,i=e?.viewModel;e&&(this.viewModel.title="error"===i?.state?t?.errorMessage:i?.title||"")}_addSelectedFeatureIndexHandle(){const e=s(()=>this.viewModel?.selectedFeatureIndex,(e,t)=>this._selectedFeatureIndexUpdated(e,t));this.addHandles(e,D)}_selectedFeatureIndexUpdated(e,t){const{featureCount:i}=this.viewModel;i&&e!==t&&-1!==e&&(this._destroyDrillInFlowItemWidgets(),this._rootFlowItemNode?.scrollContentTo({top:0}))}_triggerHeaderAction(e){const t=e.currentTarget;if(t.disabled)return;const i=t.dataset.actionUid,o=this.headerActions.find(({uid:e})=>e===i);o&&!o.disabled&&("toggle"===o?.type&&(o.value=!o.value),this.emit("trigger-header-action",{action:o}))}_triggerAction(e){const t=e.currentTarget;if(t.disabled)return;const i=t.dataset.actionUid,{allActions:o}=this.viewModel,s=o.findIndex(e=>e.uid===i),n=o.at(s);n&&"toggle"===n.type&&(n.value=!n.value),this.viewModel.triggerAction(s)}_createSpinner(e){e&&(this._spinner=new w({view:e}),e.ui.add(this._spinner,{key:S,position:"manual",internal:!0}))}_wireUpView(e){this._destroySpinner(),e&&this.visibleElements?.spinner&&this._createSpinner(e)}_hideSpinner(){const{_spinner:e}=this;e&&(e.location=null,e.hide())}_viewReadyChange(e,t){e?this._wireUpView(this.viewModel?.view):t&&this.viewModel.clear()}_viewChange(e,t){e&&t&&this.viewModel.clear()}_destroySelectedFeatureWidget(){const{_feature:e}=this;e&&(e.viewModel=null,!e.destroyed&&e.destroy()),this._feature=null}_closeOpenActionMenu(){const{_actionBarMenuNode:e}=this;e&&(e.menuOpen=!1)}_destroyDrillInFlowItemWidgets(){this._drillInFlowItems.drain(e=>{"showAllEnabled"in e.viewModel&&(e.viewModel.showAllEnabled=!1),"activeCategory"in e.viewModel&&(e.viewModel.activeCategory=null),e.viewModel=null,e.destroy()})}_toggleScreenLocationEnabled(){const{viewModel:e}=this;e&&(e.screenLocationEnabled=e.active)}_displaySpinner(){const{_spinner:e}=this;if(!e)return;const{location:t,waitingForResult:i}=this.viewModel;i&&t?e.show({location:t}):e.hide()}_destroySpinner(){const{_spinner:e}=this;e&&(e.view?.ui?.remove(e,S),e.destroy(),this._spinner=null)}_spinnerEnabledChange(e){this._destroySpinner(),e&&this._createSpinner(this.viewModel?.view)}};e([d()],H.prototype,"_drillInFlowItems",void 0),e([d()],H.prototype,"_hideActionText",null),e([d()],H.prototype,"_featureNavigationVisible",null),e([d()],H.prototype,"_isCollapsed",null),e([d()],H.prototype,"_collapseEnabled",null),e([d({readOnly:!0})],H.prototype,"active",null),e([d()],H.prototype,"collapsed",void 0),e([d()],H.prototype,"content",null),e([d()],H.prototype,"icon",null),e([d()],H.prototype,"featureMenuOpen",null),e([d()],H.prototype,"featureMenuTitle",null),e([d()],H.prototype,"featureNavigationTop",void 0),e([d()],H.prototype,"features",null),e([d()],H.prototype,"goToOverride",null),e([d({type:C})],H.prototype,"headerActions",void 0),e([d()],H.prototype,"headingLevel",void 0),e([d()],H.prototype,"initialDisplayMode",null),e([d()],H.prototype,"location",null),e([d()],H.prototype,"label",null),e([d()],H.prototype,"map",null),e([d(),O("esri/widgets/Features/t9n/Features")],H.prototype,"messages",void 0),e([d(),O("esri/t9n/common")],H.prototype,"messagesCommon",void 0),e([d()],H.prototype,"promises",null),e([d()],H.prototype,"responsiveActionsEnabled",void 0),e([d({readOnly:!0})],H.prototype,"selectedFeature",null),e([d({readOnly:!0})],H.prototype,"selectedDrillInFeature",null),e([d()],H.prototype,"selectedFeatureIndex",null),e([d({readOnly:!0})],H.prototype,"selectedFeatureWidget",null),e([d()],H.prototype,"spatialReference",null),e([d()],H.prototype,"title",null),e([d()],H.prototype,"timeZone",null),e([d()],H.prototype,"updateLocationEnabled",null),e([d()],H.prototype,"view",null),e([d({type:b}),E(["triggerAction","trigger-action"])],H.prototype,"viewModel",void 0),e([d({type:I,nonNullable:!0})],H.prototype,"visibleElements",void 0),e([d()],H.prototype,"visible",null),H=e([c("esri.widgets.Features")],H);export{H as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import t from"../../../Color.js";import"../../../intl.js";import{addTokenParameter as s}from"../../../kernel.js";import i from"../../../request.js";import l from"../../../core/Accessor.js";import{isSome as r}from"../../../core/arrayUtils.js";import n from"../../../core/Collection.js";import has from"../../../core/has.js";import{JSONMap as a}from"../../../core/jsonMap.js";import o from"../../../core/Logger.js";import{clamp as u}from"../../../core/mathUtils.js";import{debounce as c}from"../../../core/promiseUtils.js";import{on as d,watch as y,initial as h,whenOnce as m}from"../../../core/reactiveUtils.js";import{px2pt as f}from"../../../core/screenUtils.js";import{parseWhereClause as p}from"../../../core/sql.js";import{addQueryParameters as g}from"../../../core/urlUtils.js";import{property as b}from"../../../core/accessorSupport/decorators/property.js";import{subclass as S}from"../../../core/accessorSupport/decorators/subclass.js";import{EffectView as _}from"../../../layers/effects/EffectView.js";import{effectFunctionsFromJSON as w}from"../../../layers/effects/jsonUtils.js";import{getEffectiveDisplayFilter as v}from"../../../layers/support/displayFilterUtils.js";import{ExportImageParameters as L}from"../../../layers/support/ExportImageParameters.js";import{collectFields as E,collectArcadeFieldNames as C}from"../../../layers/support/fieldUtils.js";import{isFeatureLayer as F}from"../../../layers/support/layerUtils.js";import{getPixelValueRange as I}from"../../../layers/support/rasterFormats/pixelRangeUtils.js";import{fromJSON as R}from"../../../renderers/support/jsonUtils.js";import{isSupportedRenderer3D as V}from"../../../renderers/support/rendererConversion.js";import D from"../../../renderers/visualVariables/SizeVariable.js";import x from"../../../renderers/visualVariables/support/SizeVariableLegendOptions.js";import{updateReferenceSizeSymbol as z}from"../../../smartMapping/renderers/support/referenceSizeUtils.js";import T from"../../../symbols/SimpleFillSymbol.js";import j from"../../../symbols/SimpleMarkerSymbol.js";import{applyCIMSymbolColor as O}from"../../../symbols/support/cimSymbolUtils.js";import{renderSymbol as P}from"../../../symbols/support/renderUtils.js";import{renderColorRampPreviewHTML as M,renderDotDensityPreviewHTML as A,renderPieChartPreviewHTML as k,renderPreviewHTML as U}from"../../../symbols/support/symbolUtils.js";import{isVolumetricSymbol as B}from"../../../symbols/support/utils.js";import{getEffectiveClusterSizeVariable as N}from"./clusterUtils.js";import{getColorFromPointCloudStops as q,getRampStopsForPointCloud as $,getStretchRampStops as H,getRampStops as W}from"./colorRampUtils.js";import{getHeatmapRampStops as G}from"./heatmapRampUtils.js";import{getRotationAngleForFocus as J,getRelationshipRampElement as Q}from"./relationshipRampUtils.js";import{getRampStops as Z,realWorldMaxSize as K,realWorldMinSize as X}from"./sizeRampUtils.js";import{specialCharsLessThan as Y,specialCharsGreaterThan as ee,getAuthoringInfoVisualVariableByTheme as te,getSymbolForFlowRenderer as se,getMedianColor as ie,rgbImgSource as le,getDateFormatOptions as re}from"./utils.js";import{formatNumberLabel as ne}from"../../smartMapping/support/utils.js";import{fetchMessageBundle as ae}from"../../../intl/messages.js";import{substitute as oe}from"../../../intl/substitute.js";const ue=16,ce="https://utility.arcgis.com/sharing/tools/legend",de="esri.layers.ImageryLayer",ye="esri.layers.ImageryTileLayer",he="esri.layers.WCSLayer",me=/^\s*(return\s+)?\$view\.scale\s*(;)?\s*$/i,fe=new a({esriGeometryPoint:"point",esriGeometryMultipoint:"multipoint",esriGeometryPolyline:"polyline",esriGeometryPolygon:"polygon",esriGeometryMultiPatch:"multipatch"}),pe=new j({size:6,outline:{color:[128,128,128,.5],width:.5}}),ge=new T({style:"solid"});function be(e){return"flow"===e.type}function Se(e){return"vector-field"===e.type}function _e(e){return"raster-colormap"===e.type}function we(e){return"raster-stretch"===e.type}function ve(e){return"raster-shaded-relief"===e.type}function Le(e){return"esri.renderers.SimpleRenderer"===e.declaredClass}function Ee(e){return"esri.renderers.ClassBreaksRenderer"===e.declaredClass}function Ce(e){return"esri.renderers.UniqueValueRenderer"===e.declaredClass}function Fe(e){return"esri.renderers.HeatmapRenderer"===e.declaredClass}function Ie(e){return Ve(e)||De(e)||xe(e)||Re(e)}function Re(e){return"esri.renderers.PointCloudRGBRenderer"===e.declaredClass}function Ve(e){return"esri.renderers.PointCloudClassBreaksRenderer"===e.declaredClass}function De(e){return"esri.renderers.PointCloudStretchRenderer"===e.declaredClass}function xe(e){return"esri.renderers.PointCloudUniqueValueRenderer"===e.declaredClass}function ze(e){return"esri.renderers.DotDensityRenderer"===e.declaredClass}function Te(e){return"esri.renderers.PieChartRenderer"===e.declaredClass}function je(e,t){return Le(e)||Ee(e)||Ce(e)||Fe(e)||ze(e)||Te(e)?"2d"===t.type||V(e):we(e)||_e(e)||ve(e)||Ve(e)||De(e)||xe(e)||Se(e)||be(e)}function Oe(e){return"esri.layers.BuildingSceneLayer"===e.declaredClass}function Pe(e){return"esri.layers.SubtypeGroupLayer"===e.declaredClass}function Me(e){return"esri.layers.VoxelLayer"===e.declaredClass}function Ae(e){return"esri.layers.WMSLayer"===e.declaredClass}function ke(e){return"esri.layers.WMTSLayer"===e.declaredClass}function Ue(e){return"esri.layers.MapImageLayer"===e.declaredClass}function Be(e){return"esri.layers.TileLayer"===e.declaredClass}function Ne(e){return e.declaredClass===de}function qe(e){return e.declaredClass===ye}function $e(e){return e.declaredClass===he}function He(e){return"stretch-ramp"===e.type}function We(e){const t="authoringInfo"in e?e?.authoringInfo:null;return"univariate-color-size"===t?.type}function Ge(e){const t="authoringInfo"in e?e?.authoringInfo:null;return"univariate-color-size"===t?.type&&"above-and-below"===t?.univariateTheme}function Je(e){return"sublayers"in e}function Qe(e){return e&&"symbol"in e}async function Ze(e,t){const s=await ae("esri/widgets/Legend/t9n/Legend");return"previewTemplateAriaLabel"!==e||t||(e="previewAriaLabel"),oe(s[e],{label:t})}function Ke(e,t){const{field:s,field2:i,field3:l,fieldDelimiter:r,valueExpression:n}=e;if(!s)return null;const a=!(!s&&!n||!i&&!l)?t?.toString().split(r||""):[t],o=s?{[s]:a?.[0]}:null;return o&&(i&&(o[i]=a?.[1]),l&&(o[l]=a?.[2])),o}const Xe=new j({style:"path",path:"M10,5 L5,0 0,5 M5,0 L5,15",size:15,outline:{width:1,color:[85,85,85,1]}});let Ye={},et=class extends l{constructor(e){super(e),this._hasColorRamp=!1,this._hasOpacityRamp=!1,this._hasSizeRamp=!1,this._webStyleSymbolCache=new Map,this._dotDensityUrlCache=new Map,this._scaleDrivenSizeVariable=null,this._hasClusterSizeVariable=!1,this._layerDefinitionExpression=null,this._layerDefinitionExpressionClause=null,this._layerDisplayFilterId=null,this._layerDisplayFilterClause=null,this.children=new n,this.layerView=null,this.layer=null,this.legendElements=[],this.parent=null,this.hideLayersNotInCurrentView=!1,this.keepCacheOnDestroy=!1,this.respectLayerDefinitionExpression=!1,this.respectLayerVisibility=!0,this.sublayerIds=[],this.title=null,this.view=null}initialize(){const e=()=>this.notifyChange("ready");this.addHandles([d(()=>this.children,"change",t=>{const{added:s,removed:i}=t;s.forEach(t=>{const s=`activeLayerInfo-ready-watcher-${t.layer.uid}`;this.addHandles(y(()=>t.ready,e,h),s)}),i.forEach(e=>this.removeHandles(e.layer.uid)),e()})]),this.keepCacheOnDestroy||(Ye={})}destroy(){this._webStyleSymbolCache=null,this._dotDensityUrlCache=null,this._scaleDrivenSizeVariable=null,this.keepCacheOnDestroy||(Ye=null),this._layerDefinitionExpressionClause=null}get effectList(){const e=this.layer;let t=null;return"effect"in e&&e.effect&&(t=new _,t.effect=e.effect,t.endTransition(),t.scale=this.scale),t}get opacity(){const e=this.layer.opacity,t=this.parent?.opacity,s=this.layer.parent,i=s&&"uid"in s?this._getParentLayerOpacity(s):null;return null!=t?t*e:null!=i?i*e:e}get ready(){return null===this.layer||(this.children.length>0?this._isGroupActive():this.legendElements.length>0)}get scale(){return this.view?.scale??0}get isScaleDriven(){const e=this.layer;if(null===e)return!1;if("effect"in e&&e.effect&&Array.isArray(e.effect))return!0;if("featureReduction"in e&&e.featureReduction){if("cluster"===e.featureReduction.type)return!0;if("binning"===e.featureReduction.type&&"renderer"in e.featureReduction&&e.featureReduction.renderer)return this._isRendererScaleDriven(e.featureReduction.renderer)}return"renderer"in e&&e.renderer?!!("displayFilterInfo"in e&&e.displayFilterInfo&&Ce(e.renderer))||this._isRendererScaleDriven(e.renderer):this._isLayerScaleDriven(this.layer)}get version(){return this._get("version")+1}async buildLegendElementsForFeatureCollections(e){if(!(!this.hideLayersNotInCurrentView||await this._isLayerInCurrentView()))return this.legendElements=[],void this.notifyChange("ready");const t=Array.from(e,e=>{if(F(e))return this._getRendererLegendElements(e.renderer,{title:e.title});if(e.featureSet?.features.length){const t=e.layerDefinition,s=t?.drawingInfo,i=s&&R(s.renderer),l=fe.read(t.geometryType);return i?this._getRendererLegendElements(i,{title:e.name,geometryType:l}):(o.getLogger(this).warn("drawingInfo not available!"),null)}return null});try{const e=[],s=await Promise.allSettled(t);for(const t of s)if("fulfilled"===t.status)for(const s of t.value??[])e.push(s);this.legendElements=e,this.notifyChange("ready")}catch(s){o.getLogger(this).warn("error while building legend for layer!",s)}}async buildLegendElementsForRenderer(e){try{const t=!this.hideLayersNotInCurrentView||await this._isLayerInCurrentView();this.legendElements=t?await this._getRendererLegendElements(e):[],this.notifyChange("ready")}catch(t){o.getLogger(this).warn("error while building legend for layer!",t)}}async buildLegendElementsForFeatureReduction(e){try{const t=!this.hideLayersNotInCurrentView||await this._isLayerInCurrentView();this.legendElements=t?await this._getLegendElementsForFeatureReduction(e):[],this.notifyChange("ready")}catch(t){o.getLogger(this).warn("error while building legend for layer!",t)}}async buildLegendElementsForTools(){const e=this.layer;if(Me(e))this._constructLegendElementsForVoxelLayer();else if(ke(e))this._constructLegendElementsForWMTSlayer();else if(Ae(e))await this._constructLegendElementsForWMSSublayers();else if(Oe(e))await this._constructLegendElementsForBuildingSceneLayer();else if(Ue(e)||Be(e)||Pe(e))await this._constructLegendElementsForSublayers();else{this.removeHandles("imageryLayers-watcher");let t="default";if(Ne(e)){const s=e;t=(s?.rasterFunction?.functionName||"default")+"_"+(e.bandIds?.length?e.bandIds.join(""):"###")}if(qe(e)||"link-chart"===e.type)return;await this._getLegendLayers(`${e.uid}-${t}`).then(async t=>{this.legendElements=[],this.notifyChange("ready");const s=t.map(async t=>{if(Ne(e)){const t=y(()=>[e.rasterFunction,e.bandIds],()=>c(async()=>{Ye.default=null,e.renderer?await this.buildLegendElementsForRenderer(e.renderer):await this.buildLegendElementsForTools()})());this.addHandles(t,"imageryLayers-watcher")}const s=this._generateSymbolTableElementForLegendLayer(t);s?.infos.length&&(Ne(e)&&(s.title=e.title),this.legendElements.push(s)),this.notifyChange("ready")});await Promise.allSettled(s)}).catch(e=>{o.getLogger(this).warn("Request to server for legend has failed!",e)})}}async _isLayerInCurrentView(){const e=this.layer,t=this.layerView,s=t&&"createQuery"in t&&"queryFeatureCount"in t;if(!s&&!(t&&"createQuery"in e&&"queryFeatureCount"in e))return!0;await m(()=>!t.updating);const i=s?"createQuery"in t&&t.createQuery():"createQuery"in e&&e.createQuery();if(!i)return!0;i.geometry=this.view.extent;return 0!==(s?"queryFeatureCount"in t&&await t.queryFeatureCount(i):"queryFeatureCount"in e&&await e.queryFeatureCount(i))}_getParentLayerOpacity(e){let t=1;const s=e.parent;return s&&"uid"in s&&(t=this._getParentLayerOpacity(s)),e.opacity*t}_isGroupActive(){return this.children.some(e=>e.ready)}_isRendererScaleDriven(e){if("dot-density"===e.type)return!0;const t="valueExpression"in e?e.valueExpression:null;if(me.test(t))return!0;const s="visualVariables"in e?e.visualVariables:null;return!!s?.some(e=>this._isScaleDrivenSizeVariable(e))||this._hasScaleDrivenSymbols(e)}_hasScaleDrivenSymbols(e){switch(e.type){case"simple":return this._isScaleDrivenSymbol(e.symbol);case"class-breaks":return this._isScaleDrivenSymbol(e.defaultSymbol)||e.classBreakInfos.some(e=>this._isScaleDrivenSymbol(e.symbol));case"unique-value":return this._isScaleDrivenSymbol(e.defaultSymbol)||!!e.uniqueValueInfos?.some(e=>this._isScaleDrivenSymbol(e.symbol))}return!1}_isScaleDrivenSymbol(e){if("cim"===e?.type){const{primitiveOverrides:t,minScale:s,maxScale:i}=e.data,l=t?.some(e=>/\$view\.scale/.test(e.valueExpressionInfo?.expression||""))??!1;return null!=s||null!=i||l}return!1}_isScaleDrivenSizeVariable(e){if(e&&"size"!==e.type)return!1;const t=e,s=t.minSize,i=t.maxSize;return!("object"!=typeof s||!s||!this._isScaleDrivenSizeVariable(s))||(!("object"!=typeof i||!i||!this._isScaleDrivenSizeVariable(i))||me.test(t.valueExpression))}_isLayerScaleDriven(e){if("minScale"in e&&e.minScale>0||"maxScale"in e&&e.maxScale>0)return!0;if("sublayers"in e&&e.sublayers)return e.sublayers.some(e=>this._isLayerScaleDriven(e));const t=e.parent;if(!1===e.loaded&&t&&Ue(t)&&"source"in e&&e.source&&"map-layer"===e.source.type)for(const s of t.sourceJSON.layers??[])if(s.id===e.source.mapLayerId&&(s.minScale>0||s.maxScale>0))return!0;return!1}async _constructLegendElementsForVoxelLayer(){this.legendElements=[],this.removeHandles("voxel-style-watcher"),this.removeHandles("voxel-current-variable");const e=this.layer;this.addHandles(y(()=>e.currentVariableId,()=>this._constructLegendElementsForVoxelLayer()),"voxel-current-variable"),this.addHandles(y(()=>e.getVariableStyles(),()=>this._constructLegendElementsForVoxelLayer()),"voxel-style-watcher");const t=e.getVariableStyle(null),s=[];if(t)if(t.uniqueValues?.length){const e=[];t.uniqueValues.forEach(t=>{t.enabled&&e.push({label:t.label||`${t.value}`,value:t.value,symbol:new T({color:t.color,outline:null})})}),e.length&&s.push({type:"symbol-table",title:t.label,infos:e})}else if(t.transferFunction){const{colorStops:e,stretchRange:i}=t.transferFunction,l=e.toArray().reverse(),r=i.map((e,t)=>`${0===t?Y:ee} ${ne(e)}`).reverse(),n=l.map(e=>({color:e.color,value:null,label:null}));n[0].label=r[0],n[n.length-1].label=r[1],s.push({type:"color-ramp",title:t.label,infos:n,preview:M(l.map(e=>e.color),{ariaLabel:await Ze("previewColorRampAriaLabel")})})}await this._generatePreviewsForLegendElements(s,{opacity:e.opacity}),this.legendElements=s,this.notifyChange("ready")}_constructLegendElementsForWMTSlayer(){this.legendElements=[],this.removeHandles("wmts-activeLayer-watcher");const e=this.layer.activeLayer;this.addHandles(y(()=>{const{layer:e}=this;return e&&"activeLayer"in e&&e.activeLayer},()=>this._constructLegendElementsForWMTSlayer()),"wmts-activeLayer-watcher");const t=e.styleId?e.styles?.find(({id:t})=>t===e.styleId)?.legendUrl:void 0;t&&(this.legendElements=[{type:"symbol-table",title:e.title,infos:[{src:t,opacity:this.opacity}]}]),this.notifyChange("ready")}async _constructLegendElementsForWMSSublayers(){this.legendElements=[],this.removeHandles("wms-sublayers-watcher");const e=this.layer;let t=null;(e.customParameters||e.customLayerParameters)&&(t={...e.customParameters,...e.customLayerParameters}),this.addHandles(y(()=>{const{layer:e}=this;return e&&"sublayers"in e&&e.sublayers},()=>this._constructLegendElementsForWMSSublayers()),"wms-sublayers-watcher"),this.legendElements=await this._generateLegendElementsForWMSSublayers(e.sublayers,t),this.notifyChange("ready")}async _generateLegendElementsForWMSSublayers(e,t){const s=this.layer,i=[];this.addHandles(e.on("change",()=>this._constructLegendElementsForWMSSublayers()),"wms-sublayers-watcher");const l=this.sublayerIds?.map(e=>s.findSublayerById(e))?.filter(r)??[],n=l.length?l:e.toArray();for(const r of n){const e=y(()=>[r.title,r.visible,r.legendEnabled],()=>this._constructLegendElementsForWMSSublayers());if(this.addHandles(e,"wms-sublayers-watcher"),!this.respectLayerVisibility||r.visible&&r.legendEnabled){const e=await this._generateSymbolTableElementForWMSSublayer(r,t);e?.infos.length&&i.unshift(e)}}return i}async _generateSymbolTableElementForWMSSublayer(e,t){if(!e.legendUrl&&e.sublayers){const s=(await this._generateLegendElementsForWMSSublayers(e.sublayers,t)).filter(e=>e);return{type:"symbol-table",title:e.title,infos:s}}return this._generateSymbolTableElementForLegendUrl(e,t)}async _generateSymbolTableElementForLegendUrl(e,t){let s=e.legendUrl;if(!s)return;const l={type:"symbol-table",title:e.title||e.name||String(e.id??""),infos:[]};t&&(s=g(s,t));let r=null;const n=e.layer?.opacity;try{r=(await i(s,{responseType:"image"})).data,r&&(r.style.opacity=n)}catch{}return l.infos.push({src:s,preview:r,opacity:n}),l}_getLegendLayers(e,t){const s=Ye&&Ye[e];return s?Promise.resolve(s):this._legendRequest(t).then(t=>{const s=t.layers;return Ye[e]=s,s})}_legendRequest(e){const t=this.layer;let s={f:"json",dynamicLayers:e};if(Ne(t)){const e=t.exportImageServiceParameters.rasterFunction;if(e&&(s.renderingRule=JSON.stringify(e.functionDefinition?.toJSON()||e.toJSON())),t.bandIds&&(s.bandIds=t.bandIds.join()),t.raster||t.viewId||t.customParameters){const{raster:e,viewId:i,customParameters:l}=t;s={raster:e,viewId:i,...s,...l}}}let l=t.url.replace(/(\/)+$/,"");if("version"in t&&+t.version>=10.01){const e=l.indexOf("?");e>-1?l=l.slice(0,e)+"/legend"+l.slice(e):l+="/legend"}else{const e=l.toLowerCase().indexOf("/rest/"),t=-1===e?l:l.slice(0,e)+l.slice(e+5);l=ce+"?soapUrl="+encodeURI(t)+"&returnbytes=true"}return i(l,{query:s}).then(e=>e.data)}async _constructLegendElementsForBuildingSceneLayer(){this.legendElements=[],this.removeHandles("sublayers-watcher");const e=this.layer;this.addHandles(y(()=>e.sublayers,()=>this._constructLegendElementsForBuildingSceneLayer()),"sublayers-watcher");try{this.legendElements=await this._generateLegendElementsForBuildingSublayers(e.sublayers,this.opacity),this.notifyChange("ready")}catch(t){o.getLogger(this).warn("Request to server for legend has failed!",t)}}async _generateLegendElementsForBuildingSublayers(e,t){let s=[];this.addHandles(e.on("change",()=>this._constructLegendElementsForBuildingSceneLayer()),"sublayers-watcher");const i=e.toArray();for(const l of i){const e=y(()=>["renderer"in l&&l.renderer,l.opacity,l.title,l.visible],()=>this._constructLegendElementsForBuildingSceneLayer());if(this.addHandles(e,"sublayers-watcher"),!this.respectLayerVisibility||l.visible){const e=null!=l?.opacity?l.opacity:null,i=null!=e?e*t:t;if("building-group"===l.type){const e={type:"symbol-table",title:l.title,infos:[]},t=await this._generateLegendElementsForBuildingSublayers(l.sublayers,i);e.infos.push(...t),s=[e,...s]}else if(l.renderer){s=[...await this._getRendererLegendElements(l.renderer,{title:l.title,opacity:i,sublayer:l}),...s]}}}return s.filter(e=>!!e&&(!("infos"in e)||!e.infos||e.infos.length>0))}async _constructLegendElementsForSublayers(){this.legendElements=[],this.removeHandles("sublayers-watcher");const e=this.layer;if(Ue(e)||Be(e)||Pe(e)){this.addHandles(y(()=>e.sublayers,()=>this._constructLegendElementsForSublayers),"sublayers-watcher");try{this.legendElements=await this._generateLegendElementsForSublayers(e.sublayers,this.opacity),this.notifyChange("ready")}catch(t){o.getLogger(this).warn("Request to server for legend has failed!",t)}}}async _generateLegendElementsForSublayers(e,t,s){const i=this.layer;let l=[];this.addHandles(e.on("change",()=>this._constructLegendElementsForSublayers()),"sublayers-watcher");let n=e.toArray();!s&&this.sublayerIds&&this.sublayerIds.length&&(n=Pe(i)?this.sublayerIds.map(e=>i.findSublayerForSubtypeCode(e)).filter(r):this.sublayerIds.map(e=>i.findSublayerById(e)).filter(r));for(const r of n){const e=y(()=>[r.renderer,r.opacity,r.title,r.visible,r.legendEnabled],()=>this._constructLegendElementsForSublayers());if(this.addHandles(e,"sublayers-watcher"),!this.respectLayerVisibility||r.visible&&r.legendEnabled&&this._isSublayerInScale(r)){const e=null!=r?.opacity?r.opacity:null,i=null!=e?e*t:t,n=!Je(r)||r.originIdOf("renderer")>2&&!r.sublayers;if(r.renderer&&n){await r.load();l=[...await this._getRendererLegendElements(r.renderer,{title:r.title,opacity:i,sublayer:r}),...l]}else if(Je(r)){const e=await this._generateSymbolTableElementForSublayer(r,i,s);e&&l.unshift(e)}}}return l.filter(e=>!!e&&(!("infos"in e)||!e.infos||e.infos.length>0))}async _generateSymbolTableElementForSublayer(e,t,s){if(!s){s=new Map;const t=this.layer,i=e.source;let l=null;if(!(!i||"map-layer"===i.type&&i.mapLayerId===e.id&&(!i.gdbVersion||i.gdbVersion===("gdbVersion"in t&&t.gdbVersion)))||e.originIdOf("renderer")>2||e.originIdOf("labelingInfo")>2||e.originIdOf("labelsVisible")>2){const e=new L({layer:this.layer});l=e.hasDynamicLayers?e.dynamicLayers:null,e.destroy()}const r=l||`${t.uid}-default`;(await this._getLegendLayers(r,l)).forEach(e=>s.set(e.layerId,e))}const i=s.get(e.id);if((!i||i?.subLayerIds&&i.defaultVisibility)&&e.sublayers){const i=await this._generateLegendElementsForSublayers(e.sublayers,t,s);return{type:"symbol-table",title:e.title,infos:i}}return this._generateSymbolTableElementForLegendLayer(i,e,t)}_generateSymbolTableElementForLegendLayer(e,t,s){if(!e?.legend||this.respectLayerVisibility&&!this._isLegendLayerInScale(e,t))return null;const i=t?.renderer;let l=t?.title||e.layerName;if(i&&(!t||t?.originIdOf("renderer")>2)){const e=t?.title||this._getRendererTitle(i,t);e&&(l&&"string"!=typeof e&&"title"in e&&(e.title=l),l=e)}const r={type:"symbol-table",title:l,legendType:e.legendType||null,infos:[]},n=t?this._sanitizeLegendForSublayer(e.legend.slice(),t):e.legend;return e.legendGroups&&e.legendGroups.length>0?e.legendGroups.forEach(t=>{const i={type:"symbol-table",title:t.heading,legendType:e.legendType||null,infos:this._generateSymbolTableElementInfosForLegendLayer(n.filter(e=>e.groupId===t.id),e.layerId,s)};i.infos?.length>0&&r.infos.push(i)}):r.infos=this._generateSymbolTableElementInfosForLegendLayer(n,e.layerId,s),r.infos.length>0?r:null}_generateSymbolTableElementInfosForLegendLayer(e,t,i){return e.map(e=>{let l=e.url;if(e.imageData&&e.imageData.length>0)l=`data:image/png;base64,${e.imageData}`;else{if(0===l.indexOf("http"))return null;l=s(`${this.layer.url}/${t}/images/${l}`)}return{label:e.label,src:l,opacity:i??this.opacity,width:e.width,height:e.height}}).filter(r)}_isSublayerInScale(e){const t=e.minScale||0,s=e.maxScale||0;return!(t>0&&t<this.scale||s>this.scale)}_isLegendLayerInScale(e,t){const s=t||this.layer;let i=null,l=null,r=!0;return!s.minScale&&0!==s.minScale||!s.maxScale&&0!==s.maxScale?(0===e.minScale&&s.tileInfo&&(i=s.tileInfo.lods[0].scale),0===e.maxScale&&s.tileInfo&&(l=s.tileInfo.lods[s.tileInfo.lods.length-1].scale)):(i=Math.min(s.minScale,e.minScale)||s.minScale||e.minScale,l=Math.max(s.maxScale,e.maxScale)),(i>0&&i<this.scale||l>this.scale)&&(r=!1),r}_sanitizeLegendForSublayer(e,t){if("version"in this.layer&&+this.layer.version<10.1||0===e.length)return e;const s=t.renderer,i=e.some(e=>e.values);let l=0,r=null;return i&&e.some((e,t)=>(e.values||(l=t,r=e,r.label||(r.label="others")),null!=r)),s?"unique-value"===s.type?r&&(e.splice(l,1),e.push(r)):"class-breaks"===s.type&&(r&&e.splice(l,1),s.legendOptions?.order||e.reverse(),r&&e.push(r)):r&&(e.splice(l,1),e.push(r)),e}async _getRendererLegendElements(e,t={}){if(!je(e,this.view))return o.getLogger(this).warn(`Renderer of type '${e.type}' not supported!`),[];if(Ie(e))return this._constructPointCloudRendererLegendElements(e,t);if(ze(e))return this._constructDotDensityRendererLegendElements(e);const s=await this._loadRenderer(e);return Te(s)?this._constructPieChartRendererLegendElements(s):this._constructRendererLegendElements(s,t)}async _getLegendElementsForFeatureReduction(e){let t=null;return"binning"===e.type?t=e.renderer:"cluster"===e.type&&(t=this._getClusterRenderer(e)),t?this._getRendererLegendElements(t):[]}_getPointCloudRendererTitle(e){return(e.legendOptions?.title||e.field)??""}async _constructPointCloudRendererLegendElements(e,t={}){const s=t.title,i=[];let l=null,r=null;if(Ve(e))l={type:"symbol-table",title:s||this._getPointCloudRendererTitle(e),infos:[]},e.colorClassBreakInfos.forEach(e=>{l.infos.unshift({label:e.label||e.minValue+" - "+e.maxValue,value:[e.minValue,e.maxValue],symbol:this._getAppliedCloneSymbol(pe,e.color)})});else if(De(e)){const t=e.stops;let i=null;if(t?.length&&(1===t.length&&(i=t[0].color),!i)){const e=t[0].value,s=t[t.length-1].value;if(null!=e&&null!=s){i=q(e+(s-e)/2,t)}}l={type:"symbol-table",title:null,infos:[{label:null,value:null,symbol:this._getAppliedCloneSymbol(pe,i||pe.color)}]};const n=$(e.stops??[])??[];r={type:"color-ramp",title:s||this._getPointCloudRendererTitle(e),infos:n,preview:M(n.map(e=>e.color),{ariaLabel:await Ze("previewColorRampAriaLabel")})}}else xe(e)&&(l={type:"symbol-table",title:s||this._getPointCloudRendererTitle(e),infos:[]},e.colorUniqueValueInfos?.forEach(e=>{l.infos.push({label:e.label||e.values.join(", "),value:e.values.join(", "),symbol:this._getAppliedCloneSymbol(pe,e.color)})}));return l?.infos.length&&i.push(l),r?.infos.length&&i.push(r),await this._generatePreviewsForLegendElements(i,{opacity:this.opacity,symbolConfig:{applyColorModulation:!!e.colorModulation}}),i}async _getElementInfoForDotDensity(e,t){const{color:s,label:i,valueExpressionTitle:l}=t,{backgroundColor:r,outline:n,dotSize:a}=e,o=this.effectList,u=o?.effects.map(e=>e.toJSON()),c=w(u),d=await Ze("previewTemplateAriaLabel",i||l),y=a+"-"+s+"-"+r+"-"+(n&&JSON.stringify(n.toJSON()))+"-"+c,h=this._dotDensityUrlCache,m=h.has(y)?h.get(y):A(e,s,{ariaLabel:d});h.set(y,m);const f={shape:{type:"image",x:0,y:0,width:m.width,height:m.height,src:m.src},fill:null,stroke:null,offset:[0,0]},p=P([[f]],[m.width,m.height],{effectView:this.effectList,ariaLabel:d});return{opacity:1,src:m.src,preview:p,width:m.width,height:m.height}}async _constructDotDensityRendererLegendElements(e){const t=e.calculateDotValue(this.view.scale),s=e.legendOptions?.unit,i={type:"symbol-table",title:{value:t&&Math.round(t),unit:s||""},infos:[]};for(const l of e.attributes){const t=await this._getElementInfoForDotDensity(e,l);t.label=l.label||l.valueExpressionTitle||l.field,i.infos.push(t)}return[i]}async _constructPieChartRendererLegendElements(e){const t=[];let s=null;const i=e.outline;e.attributes.forEach(e=>{const s=new j({color:e.color,outline:i}),l=e.label||e.valueExpressionTitle||e.field;t.push({label:l,symbol:s})});const l=t.length?[...t]:[];if(e.othersCategory?.color&&0!==e.othersCategory?.threshold){const l=new j({color:e.othersCategory.color,outline:i});s=e.othersCategory.label||"Other",t.push({label:s,symbol:l})}if(e.defaultColor?.a){const s=new j({color:e.defaultColor,outline:i});t.push({label:e.defaultLabel,symbol:s})}const r=await this._getVisualVariableLegendElements(e,this.layer)||[];if(t.length){r.unshift({type:"symbol-table",title:null,infos:t});const n=l.filter(e=>e.label!==s).map(e=>e.symbol.color).filter(Boolean),a=k(n,{holePercentage:e.holePercentage,backgroundColor:e.backgroundFillSymbol?.color,effectList:this.effectList,outline:i,ariaLabel:await Ze("previewPieChartAriaLabel")});r.unshift({type:"pie-chart-ramp",title:this._getRendererTitle(e,this.layer),infos:t,preview:a})}return await this._generatePreviewsForLegendElements(r,{opacity:this.layer.opacity,effectView:this.effectList}),r}async _getWhereClause(e,t,s){const i=await p(e,s),l=new Set,{field:r,field2:n,field3:a}=t;E(l,s,[r,n,a]),C(l,s,t.valueExpression);const o=new Set(Array.from(l,e=>e.toLowerCase())),u=i?.fieldNames.map(e=>e.toLowerCase());return u?.some(e=>!o.has(e))?null:i}async _processDefinitionExpression(e,t){if(!("definitionExpression"in e))return;const s=e.definitionExpression;s&&this.respectLayerDefinitionExpression?this._layerDefinitionExpression!==s&&(this._layerDefinitionExpressionClause=await this._getWhereClause(s,t,e.fieldsIndex)):this._layerDefinitionExpressionClause=null,this._layerDefinitionExpression=s}async _processDisplayFilter(e,t){if(!("displayFilterInfo"in e))return;const s=e.displayFilterInfo?v(e.displayFilterInfo,this.view):null;return s?.where?this._layerDisplayFilterId!==s?.id&&(this._layerDisplayFilterClause=await this._getWhereClause(s.where,t,e.fieldsIndex)):this._layerDisplayFilterClause=null,this._layerDisplayFilterId=s?.id,s}async _constructRendererLegendElements(e,t={}){const{title:s,sublayer:i}=t,l=i||this.layer,r=te(e,"reference-size"),n=te(e,"spike");let a=null;Ce(e)&&(await this._processDefinitionExpression(l,e),a=await this._processDisplayFilter(l,e)),this._hasColorRamp=!1,this._hasOpacityRamp=!1,this._hasSizeRamp=!1,this._scaleDrivenSizeVariable=null;const o=await this._getVisualVariableLegendElements(e,l)||[],u={type:"symbol-table",title:s||this._getRendererTitle(e,l),infos:[]};let c=null,d=!1;const y=new Set;if(be(e)&&!this._hasSizeRamp){const t=await se(e);u.infos.push({label:null,symbol:t})}else if(We(e)){let t=s;const i=Ge(e)?"univariate-above-and-below-ramp":"univariate-color-size-ramp",l=o.findIndex(e=>"color-ramp"===e.type),r=-1!==l?o.splice(l,1)[0]:null,n=o.findIndex(e=>"size-ramp"===e.type),a=-1!==n?o.splice(n,1)[0]:null,u=[];r&&(t=r.title,u.push(r)),a&&(t=a.title,u.push(a)),u.length>0&&o.push({type:i,title:t,infos:u})}else if(Fe(e)){const t=G(e);o.push({type:"heatmap-ramp",title:s||this._getRendererTitle(e,l),infos:t,preview:M(t.map(e=>e.color),{effectList:this.effectList,ariaLabel:await Ze("previewColorRampAriaLabel")})})}else if(Ce(e)){const t=e.authoringInfo;if(t&&"relationship"===t.type){const{numClasses:s,field1:i,field2:r}=t,n=t.focus;if(s&&i&&r){const t=[i,r];let a=J(n)||0;for(const e of t){const{field:t,normalizationField:s,label:i}=e,r=i||{field:this._getFieldAlias(t,l),normField:s&&this._getFieldAlias(s,l)},n=Xe.clone();n.angle=a,u.infos.push({label:r,symbol:n}),y.add(n),a+=90}const c=Q({focus:n,numClasses:s,infos:e.uniqueValueInfos??[]});o.unshift(c)}}else if(Ne(this.layer)||qe(this.layer))e.uniqueValueInfos?.forEach(t=>{t.symbol&&this._checkClausesForUVR(e,t.value)&&u.infos.push({label:t.label||t.value,value:t.value,symbol:t.symbol})});else{const{field:t,field2:i,field3:n,fieldDelimiter:o,valueExpression:c,defaultSymbol:y}=e,h=!(!t&&!c||!i&&!n),m=this._layerDisplayFilterClause?a?.title:null,f=[];if(e.uniqueValueGroups?.forEach(s=>{const a={type:"symbol-table",title:m||s.heading,infos:[]};s.classes?.forEach(s=>{const{symbol:u,values:d}=s;if(u){const y=[],m=[];for(const e of d??[]){const{value:s,value2:r,value3:a}=e,u=[],d=[];(t||c)&&(u.push(s),d.push(this._getDomainName(t,s,l))),i&&(u.push(r),d.push(this._getDomainName(i,r,l))),n&&(u.push(a),d.push(this._getDomainName(n,a,l))),y.push(h?u.join(o||""):u[0]),m.push(d.join(" - "))}const f=y.join(", ");let p=s.label;if(!p){const e=m.filter(Boolean);p=e.length?e.join(", "):f}const g=u.clone();"cim"===g.type&&r&&z(g,{innerDotSize:.5*ue,outerRingSize:ue}),y.some(t=>this._checkClausesForUVR(e,t))&&a.infos.push({label:p,value:f,symbol:g})}}),a.infos.length&&f.push(a)}),f.length){const t=f[0];if(1===f.length&&"title"in t&&!t.title){const e=t.infos?.filter(Qe)??[];u.infos.push(...e)}else y&&(f.push({type:"symbol-table",infos:[{label:e.defaultLabel||"others",symbol:y}]}),d=!0),u.infos.push(...f);s||e.legendOptions?.title||e.valueExpressionTitle||(u.title=null)}}e.defaultSymbol&&!d&&(u.infos.push({label:e.defaultLabel||"others",symbol:e.defaultSymbol}),d=!0)}else if(Ee(e)){if(!r&&!n){c=this._isUnclassedRenderer(e);if(!c||!this._hasSizeRamp){const t=e.classBreakInfos.filter(({symbol:e})=>e),s="ascending-values"===e.legendOptions?.order;for(const{label:e,minValue:i,maxValue:l,symbol:r}of t){const t={label:e||(c?null:`${i} - ${l}`),value:[i,l],symbol:r};s?u.infos.push(t):u.infos.unshift(t)}c&&(u.title=null),this._updateInfosForClassedSizeRenderer(e,u.infos)}e.defaultSymbol&&!c&&(u.infos.push({label:e.defaultLabel||"others",symbol:e.defaultSymbol}),d=!0)}}else if(we(e))if(qe(this.layer)||$e(this.layer)){const t=await this._constructTileImageryStretchRendererElements(e);He(t)?o.push(t):u.infos=t}else{const t=this.layer;let s,i;e.customStatistics?.length&&({min:s,max:i}=e.customStatistics[0]);let l=[],r=t.serviceRasterInfo;if(t.rasterFunction)try{r=await t.generateRasterInfo(t.rasterFunction)}catch{}const n=I(r.pixelType);if(1===r.bandCount){const l=t.bandIds?.[0]||0;s=null!=s?s:r.statistics?r.statistics[l].min:n[0],i=null!=i?i:r.statistics?r.statistics[l].max:n[1],s||i?o.push(await this._getStretchLegendElements(e,{min:s,max:i})):this._getServerSideLegend()}else if(t.bandIds&&1===t.bandIds.length)s=null!=s?s:r.statistics?r.statistics[t.bandIds[0]].min:n[0],i=null!=i?i:r.statistics?r.statistics[t.bandIds[0]].max:n[1],s||i?o.push(await this._getStretchLegendElements(e,{min:s,max:i})):this._getServerSideLegend();else if(r.bandCount>=3){const{bandInfos:e}=r,{bandIds:s}=t;e.length>=r.bandCount?3===s?.length?(l=s.map(t=>e[t].name),u.infos=this._createSymbolTableElementMultiBand(l)):"lerc"===t.format?(l=[0,1,2].map(t=>e[t].name),u.infos=this._createSymbolTableElementMultiBand(l)):this._getServerSideLegend():"lerc"===t.format?(l=["band1","band2","band3"],u.infos=this._createSymbolTableElementMultiBand(l)):this._getServerSideLegend()}else this._getServerSideLegend()}else if(_e(e))e.colormapInfos.forEach(e=>{u.infos.push({label:e.label,value:e.value,symbol:this._getAppliedCloneSymbol(ge,e.color)})});else if(Le(e)){let s=e.symbol;switch(t.geometryType){case"point":s="pointSymbol"in l?l.pointSymbol:null;break;case"polyline":s="lineSymbol"in l?l.lineSymbol:null;break;case"polygon":s="polygonSymbol"in l?l.polygonSymbol:null}const i=this._hasClusterSizeVariable&&this._getClusterSymbol()||!this._hasSizeRamp;e.symbol&&i&&u.infos.push({label:e.label,symbol:s})}else if(Se(e)){e.outputUnit&&(this.title="("+e.toJSON().outputUnit+")"),u.title=e.attributeField;const t=e.getClassBreakInfos();t?.length?t.forEach(e=>{u.infos.push({label:e.minValue+" - "+e.maxValue,symbol:e.symbol})}):u.infos.push({label:e.attributeField,symbol:e.getDefaultSymbol()})}else ve(e)&&o.push(await this._getStretchLegendElements(e,{min:0,max:255}));const h=e.defaultSymbol;!h||d||Le(e)||c&&!this._hasColorRamp&&!this._hasSizeRamp&&!this._hasOpacityRamp||o.push({type:"symbol-table",infos:[{label:e.defaultLabel||"others",symbol:h}]}),u.infos.length&&o.unshift(u);const m=null==t.opacity?this.opacity:t.opacity,f=this._isTallSymbol("visualVariables"in e?e.visualVariables:null),p=Ne(this.layer)||qe(this.layer);return await this._generatePreviewsForLegendElements(o,{opacity:m,symbolConfig:{isTall:f,isSquareFill:p},effectView:this.effectList},{defaultSymbol:h,arrowMarkerSymbols:y}),e=null,o}_checkClausesForUVR(e,t){const s=Ke(e,t);return!s||(!this._layerDefinitionExpressionClause||this._layerDefinitionExpressionClause.testFeature(s))&&(!this._layerDisplayFilterClause||this._layerDisplayFilterClause.testFeature(s))}_getServerSideLegend(){setTimeout(()=>this.buildLegendElementsForTools(),0)}_getAllInfos(e){const t=e?.infos;return t?t.reduce((e,t)=>e.concat(this._getAllInfos(t)),[]):[e]}async _constructTileImageryStretchRendererElements(e){const t=this.layer,s=t.symbolizer.rasterInfo??t.raster.rasterInfo;let i,l;const r=e?.customStatistics?.length?e.customStatistics:s?.statistics;if(r)({min:i,max:l}=r[0]);else{const e=I(s.pixelType);i=e[0],l=e[1]}if(t.hasStandardTime()&&(i=t.getStandardTimeValue(i),l=t.getStandardTimeValue(l)),1===s.bandCount||1===t.bandIds?.length)return this._getStretchLegendElements(e,{min:i,max:l});const n=(t?.bandIds?.length?t.bandIds:Array.from(Array(Math.min(s.bandCount,3)).keys())).map(e=>s.bandInfos[e].name);return n.length<3?n.push(n[1]):n.length>3&&n.splice(3),this._createSymbolTableElementMultiBand(n)}async _getStretchLegendElements(e,t){const s=e.colorRamp,i=H(s,t);return{type:"stretch-ramp",title:"",infos:i,preview:M(i.map(e=>e.color),{ariaLabel:await Ze("previewColorRampAriaLabel")})}}_getClusterSymbol(){const e=this.layer,t="featureReduction"in e&&e.featureReduction,s=t&&"symbol"in t&&t.renderer;return s&&!0!==s?.authoringInfo?.isAutoGenerated?null:t&&"symbol"in t?t.symbol:null}async _getSizeLegendElement(e,t,s,i){return{type:"size-ramp",title:this._hasClusterSizeVariable?this._getClusterTitle(t):e,infos:await Z(s,t,await ie(s),this.scale,this.view,i,this._hasClusterSizeVariable?this._getClusterSymbol():null)}}_createSymbolTableElementMultiBand(e){const t=[],s=["red","green","blue"];return e.forEach((e,i)=>{t.push({label:{colorName:s[i],bandName:e},src:le[i],opacity:this.opacity??1})}),t}_updateInfosForClassedSizeRenderer(e,t){const s=e.authoringInfo&&"class-breaks-size"===e.authoringInfo.type,i=e.classBreakInfos.some(e=>B(e.symbol));if(s&&i){const s=K,i=X,l=e.classBreakInfos.length,r=(s-i)/(l>1?l-1:l);t.forEach((e,t)=>{e.size=s-r*t})}}_isTallSymbol(e){let t=!1,s=!1;if(e)for(let i=0;i<e.length&&(!t||!s);i++){const l=e[i];"size"===l.type&&("height"===l.axis&&(t=!0),"width-and-depth"===l.axis&&(s=!0))}return t&&s}async _generatePreviewsForLegendElements(e,t,s){const i=[];for(const l of e)for(const e of l.infos??[])if("infos"in e&&e.infos&&i.push(this._generatePreviewsForLegendElements([e],t,s)),Qe(e)&&e.symbol&&!e.preview){let r=!0;if("cim"===e.symbol.type){const{minScale:t,maxScale:s}=e.symbol.data;(t&&t<this.scale||s&&s>this.scale)&&(r=!1)}r&&i.push(this._generateSymbolPreviewForInfo(e,{...t,clipBloomEffect:"theme"in l&&"spike"===l.theme,effectView:s?.arrowMarkerSymbols?.has(e.symbol)?null:t.effectView},s?{isDefault:e.symbol===s.defaultSymbol,applyScaleDrivenSize:!s.arrowMarkerSymbols?.has(e.symbol)}:void 0))}await Promise.all(i)}async _generateSymbolPreviewForInfo(e,t,s){try{let i=!s?.isDefault&&null==e.size&&this._hasSizeRamp?f(22):e.size;if(this._scaleDrivenSizeVariable&&s?.applyScaleDrivenSize){const{getSize:t}=await import("../../../renderers/visualVariables/support/visualVariableUtils.js");i=t(this._scaleDrivenSizeVariable,null,{view:this.view.type,scale:this.scale,shape:"simple-marker"===e.symbol.type?e.symbol.style:null})}const l="cim"===e.symbol.type?{style:"legend",cimOptions:{allowScalingUp:!s?.isDefault&&this._hasSizeRamp||!(!this._scaleDrivenSizeVariable||!s?.applyScaleDrivenSize),viewParams:this.isScaleDriven?{viewingMode:"2d"===this.view?.type?"map":this.view?.viewingMode,scale:this.view?.scale}:null}}:{},r=e.label&&"string"!=typeof e.label?null:await Ze("previewTemplateAriaLabel",e.label);e.preview=await U(e.symbol,{size:i,scale:!1,ariaLabel:r,...t,...l})}catch{e.preview=null,o.getLogger(this).warn(`Generating symbol preview failed for symbol type: ${e.symbol?.type}`)}}_getClusterRenderer(e){this._hasClusterSizeVariable=!1;const t="renderer"in this.layer?this.layer.renderer:null,s=e.renderer?.clone()||t?.clone(),i=N(e,this.layerView,this.view);if(i&&null!=s&&"visualVariables"in s){const t=s.visualVariables?.some(e=>"size"===e.type&&"outline"!==e.target&&!me.test(e.valueExpression));if(!t){if("clusterMinSize"in e&&"clusterMaxSize"in e){const{clusterMinSize:t,clusterMaxSize:s}=e;i.legendOptions=new x({showLegend:t!==s})}const t=s.visualVariables||[];s.visualVariables=t.concat([i]),this._hasClusterSizeVariable=!0}}return s}async _loadRenderer(e){const t=[],s=e.clone(),i=await ie(s);if(Ee(s)||Ce(s)){const e=(s.classBreakInfos||s.uniqueValueInfos).map(e=>this._fetchSymbol(e.symbol,i).then(t=>{e.symbol=t}).catch(()=>{e.symbol=null}));Array.prototype.push.apply(t,e)}return t.push(this._fetchSymbol(s.symbol||s.defaultSymbol,s.defaultSymbol?null:i).then(e=>{this._applySymbolToRenderer(s,e,Le(s))}).catch(()=>{this._applySymbolToRenderer(s,null,Le(s))})),await Promise.allSettled(t),s}_applySymbolToRenderer(e,t,s){s?e.symbol=t:e.defaultSymbol=t}async _fetchSymbol(e,t){if(!e)throw new Error;if("web-style"===e.type){const s=this._webStyleSymbolCache;try{const i=await e.fetchSymbol({cache:s});return this._getAppliedCloneSymbol(i,t)}catch{throw o.getLogger(this).warn("Fetching web-style failed!"),new Error}}return this._getAppliedCloneSymbol(e,t)}_getAppliedCloneSymbol(e,s){if(!e||!s)return e;const i=e.clone(),l=s&&s.toRgba();return i.type.includes("3d")?this._applyColorTo3dSymbol(i,l):"cim"===i.type?O(i,s):i.color&&(i.color=new t(l||i.color)),i}_applyColorTo3dSymbol(e,s){s&&e.symbolLayers.forEach(e=>{e&&(e.material||(e.material={}),e.material.color=new t(s))})}async _getVisualVariableLegendElements(e,t){if(!("visualVariables"in e)||"vector-field"===e.type)return null;const s=e.visualVariables??[],i=[],l=[],n=[],a=te(e,"reference-size")??te(e,"spike");let o;if(2===a?.sizeStops?.length&&(Ee(e)||Ce(e))){const[e,t]=a.sizeStops;o=new D({field:a.field??void 0,normalizationField:a.normalizationField,minSize:u(e.size,10,100),maxSize:u(t.size,50,150),minDataValue:e.value,maxDataValue:t.value}),l.push(o)}for(const r of s)"color"===r.type?i.push(r):"size"===r.type?l.push(r):"opacity"===r.type&&n.push(r);const c=[...i,...l,...n];let d,y;if(0===i.length&&Ee(e)&&e.classBreakInfos&&1===e.classBreakInfos.length){const t=e.classBreakInfos[0];d=t&&t.symbol}if(0===i.length&&Le(e)&&(d=e.symbol),d)if(d.type.includes("3d")){const e=d.symbolLayers.at(0);"water"===e.type?null!=e.color&&(y=e.color):null!=e.material?.color&&(y=e.material.color)}else d.url||(y=d.color);const h=this.effectList;return(await Promise.all(c.map(async s=>{if(!s.legendOptions||!1!==s.legendOptions.showLegend){const i=be(e)?s.field:this._getRampTitle(s,t);let l=null;const r=re(t,s,this.view.timeZone);if("color"===s.type){const e=await W(s,null,r)??[];l={type:"color-ramp",title:i,infos:e,preview:M(e.map(e=>e.color),{effectList:h,ariaLabel:await Ze("previewColorRampAriaLabel")})},this._hasColorRamp||(this._hasColorRamp=e.length>0)}else if("size"===s.type&&"outline"!==s.target)me.test(s.valueExpression)?this._hasClusterSizeVariable||(this._scaleDrivenSizeVariable=s):(l=await this._getSizeLegendElement(i,s,e,r),o===s&&"spike"===a?.theme&&(l.theme=a.theme),this._hasSizeRamp||(this._hasSizeRamp=!(null==l.infos||!l.infos.length)));else if("opacity"===s.type){const e=await W(s,y,r)??[];l={type:"opacity-ramp",title:i,infos:e,preview:M(e.map(e=>e.color),{effectList:h,ariaLabel:await Ze("previewColorRampAriaLabel")})},this._hasOpacityRamp||(this._hasOpacityRamp=e.length>0)}return l?.infos?l:null}}))).filter(r)}_getDomainName(e,t,s){if(e&&"function"!=typeof e){const i="getField"in s&&s.getField?.(e),l=i&&"getFieldDomain"in s&&s.getFieldDomain?s.getFieldDomain(i.name,{excludeImpliedDomains:has("esri-widget-legacy-field-domain-calculation")}):null;return"coded-value"===l?.type?l.getName(t):null}return null}_getClusterTitle(e){const t=this.layer,s=e.field;if("featureReduction"in t&&t.featureReduction&&"cluster"===t.featureReduction.type){const e=t.featureReduction,i="popupTemplate"in e&&e.popupTemplate,l=i&&i.fieldInfos;if(l)for(const t of l)if(t.fieldName===s)return"cluster_count"===s?t.label||{showCount:!0}:t.label}return{showCount:!0}}_getRampTitle(e,t){let s=e.field,i=e.normalizationField,l=!1,r=!1,n=!1,a=null;s="function"==typeof s?null:s,i="function"==typeof i?null:i;const o=e.legendOptions?.title;if(null!=o)a=o;else if(e.valueExpressionTitle)a=e.valueExpressionTitle;else{if("renderer"in t&&t.renderer&&"authoringInfo"in t.renderer&&t.renderer.authoringInfo?.visualVariables){const e=t.renderer.authoringInfo.visualVariables;for(let t=0;t<e.length;t++){const s=e[t];if("color"===s.type){if("ratio"===s.style){l=!0;break}if("percent"===s.style){r=!0;break}if("percent-of-total"===s.style){n=!0;break}}}}a={field:s&&this._getFieldAlias(s,t),normField:i&&this._getFieldAlias(i,t),ratio:l,ratioPercent:r,ratioPercentTotal:n}}return a}_getRendererTitle(e,t){const s=e;if(s.legendOptions?.title)return s.legendOptions.title;if(s.valueExpressionTitle)return s.valueExpressionTitle;let i=s.field,l=null,r=null;if(Ee(s)&&(l=s.normalizationField,r="percent-of-total"===s.normalizationType),i="function"==typeof i?null:i,l="function"==typeof l?null:l,Ce(s)){const{field2:e,field3:l,fieldDelimiter:r}=s;let n=i&&this._getFieldAlias(i,t);return e&&(n=`<${n}>${r}<${this._getFieldAlias(e,t)}>`,l&&(n=`${n}${r}<${this._getFieldAlias(l,t)}>`)),n}let n=null;return(i||l)&&(n={field:i&&this._getFieldAlias(i,t),normField:l&&this._getFieldAlias(l,t),normByPct:r}),n}_getFieldAlias(e,t){const s="popupTemplate"in t?t.popupTemplate:null,i=s?.fieldInfos;let l=i?.find(t=>e===t.fieldName),r=null;"getField"in t&&t.getField?r=t.getField(e):"fieldsIndex"in t&&t.fieldsIndex&&(r=t.fieldsIndex.get(e));let n=null;const a="featureReduction"in t&&t.featureReduction;a&&(l??="popupTemplate"in a?a.popupTemplate?.fieldInfos?.find(t=>e?.toLowerCase()===t.fieldName?.toLowerCase()):void 0,"fields"in a&&a.fields&&(n=a.fields.find(t=>t.name?.toLowerCase()===e?.toLowerCase())));const o=l||r||n;let u=null;return o&&(u=l?.label||r?.alias||n?.alias||"name"in o&&o.name||"fieldName"in o&&o.fieldName||null),u}_isUnclassedRenderer(e){const t=e.visualVariables;let s=!1;return Ee(e)&&e.classBreakInfos&&1===e.classBreakInfos.length&&t&&(s=e.field?t.some(t=>!(!t||e.field!==t.field||(e.normalizationField||t.normalizationField)&&e.normalizationField!==t.normalizationField)):!!t.length),s}};e([b()],et.prototype,"children",void 0),e([b({readOnly:!0})],et.prototype,"effectList",null),e([b()],et.prototype,"layerView",void 0),e([b()],et.prototype,"layer",void 0),e([b()],et.prototype,"legendElements",void 0),e([b({readOnly:!0})],et.prototype,"opacity",null),e([b()],et.prototype,"parent",void 0),e([b({readOnly:!0,dependsOn:[]})],et.prototype,"ready",null),e([b()],et.prototype,"hideLayersNotInCurrentView",void 0),e([b()],et.prototype,"keepCacheOnDestroy",void 0),e([b()],et.prototype,"respectLayerDefinitionExpression",void 0),e([b()],et.prototype,"respectLayerVisibility",void 0),e([b({readOnly:!0})],et.prototype,"scale",null),e([b()],et.prototype,"sublayerIds",void 0),e([b({readOnly:!0})],et.prototype,"isScaleDriven",null),e([b()],et.prototype,"title",void 0),e([b({readOnly:!0,dependsOn:["ready"],value:0})],et.prototype,"version",null),e([b()],et.prototype,"view",void 0),et=e([S("esri.widgets.Legend.support.ActiveLayerInfo")],et);export{et as default};
5
+ import{__decorate as e}from"tslib";import t from"../../../Color.js";import"../../../intl.js";import{addTokenParameter as s}from"../../../kernel.js";import i from"../../../request.js";import l from"../../../core/Accessor.js";import{isSome as r}from"../../../core/arrayUtils.js";import n from"../../../core/Collection.js";import has from"../../../core/has.js";import{JSONMap as a}from"../../../core/jsonMap.js";import o from"../../../core/Logger.js";import{clamp as u}from"../../../core/mathUtils.js";import{debounce as c}from"../../../core/promiseUtils.js";import{on as d,watch as y,initial as h,whenOnce as m}from"../../../core/reactiveUtils.js";import{px2pt as f}from"../../../core/screenUtils.js";import{parseWhereClause as p}from"../../../core/sql.js";import{addQueryParameters as g}from"../../../core/urlUtils.js";import{property as b}from"../../../core/accessorSupport/decorators/property.js";import{subclass as S}from"../../../core/accessorSupport/decorators/subclass.js";import{EffectView as _}from"../../../layers/effects/EffectView.js";import{effectFunctionsFromJSON as w}from"../../../layers/effects/jsonUtils.js";import{getEffectiveDisplayFilter as v}from"../../../layers/support/displayFilterUtils.js";import{ExportImageParameters as L}from"../../../layers/support/ExportImageParameters.js";import{collectFields as E,collectArcadeFieldNames as C}from"../../../layers/support/fieldUtils.js";import{isFeatureLayer as F}from"../../../layers/support/layerUtils.js";import{getPixelValueRange as I}from"../../../layers/support/rasterFormats/pixelRangeUtils.js";import{fromJSON as R}from"../../../renderers/support/jsonUtils.js";import{isSupportedRenderer3D as V}from"../../../renderers/support/rendererConversion.js";import D from"../../../renderers/visualVariables/SizeVariable.js";import x from"../../../renderers/visualVariables/support/SizeVariableLegendOptions.js";import{updateReferenceSizeSymbol as z}from"../../../smartMapping/renderers/support/referenceSizeUtils.js";import T from"../../../symbols/SimpleFillSymbol.js";import j from"../../../symbols/SimpleMarkerSymbol.js";import{applyCIMSymbolColor as O}from"../../../symbols/support/cimSymbolUtils.js";import{renderSymbol as P}from"../../../symbols/support/renderUtils.js";import{renderColorRampPreviewHTML as M,renderDotDensityPreviewHTML as A,renderPieChartPreviewHTML as k,renderPreviewHTML as U}from"../../../symbols/support/symbolUtils.js";import{isVolumetricSymbol as B}from"../../../symbols/support/utils.js";import{getEffectiveClusterSizeVariable as N}from"./clusterUtils.js";import{getColorFromPointCloudStops as q,getRampStopsForPointCloud as $,getStretchRampStops as H,getRampStops as W}from"./colorRampUtils.js";import{getHeatmapRampStops as G}from"./heatmapRampUtils.js";import{getRotationAngleForFocus as J,getRelationshipRampElement as Q}from"./relationshipRampUtils.js";import{getRampStops as Z,realWorldMaxSize as K,realWorldMinSize as X}from"./sizeRampUtils.js";import{specialCharsLessThan as Y,specialCharsGreaterThan as ee,getAuthoringInfoVisualVariableByTheme as te,getSymbolForFlowRenderer as se,getMedianColor as ie,rgbImgSource as le,getDateFormatOptions as re}from"./utils.js";import{formatNumberLabel as ne}from"../../smartMapping/support/utils.js";import{fetchMessageBundle as ae}from"../../../intl/messages.js";import{substitute as oe}from"../../../intl/substitute.js";const ue=16,ce="https://utility.arcgis.com/sharing/tools/legend",de="esri.layers.ImageryLayer",ye="esri.layers.ImageryTileLayer",he="esri.layers.WCSLayer",me=/^\s*(return\s+)?\$view\.scale\s*(;)?\s*$/i,fe=new a({esriGeometryPoint:"point",esriGeometryMultipoint:"multipoint",esriGeometryPolyline:"polyline",esriGeometryPolygon:"polygon",esriGeometryMultiPatch:"multipatch"}),pe=new j({size:6,outline:{color:[128,128,128,.5],width:.5}}),ge=new T({style:"solid"});function be(e){return"flow"===e.type}function Se(e){return"vector-field"===e.type}function _e(e){return"raster-colormap"===e.type}function we(e){return"raster-stretch"===e.type}function ve(e){return"raster-shaded-relief"===e.type}function Le(e){return"esri.renderers.SimpleRenderer"===e.declaredClass}function Ee(e){return"esri.renderers.ClassBreaksRenderer"===e.declaredClass}function Ce(e){return"esri.renderers.UniqueValueRenderer"===e.declaredClass}function Fe(e){return"esri.renderers.HeatmapRenderer"===e.declaredClass}function Ie(e){return Ve(e)||De(e)||xe(e)||Re(e)}function Re(e){return"esri.renderers.PointCloudRGBRenderer"===e.declaredClass}function Ve(e){return"esri.renderers.PointCloudClassBreaksRenderer"===e.declaredClass}function De(e){return"esri.renderers.PointCloudStretchRenderer"===e.declaredClass}function xe(e){return"esri.renderers.PointCloudUniqueValueRenderer"===e.declaredClass}function ze(e){return"esri.renderers.DotDensityRenderer"===e.declaredClass}function Te(e){return"esri.renderers.PieChartRenderer"===e.declaredClass}function je(e,t){return Le(e)||Ee(e)||Ce(e)||Fe(e)||ze(e)||Te(e)?"2d"===t.type||V(e):we(e)||_e(e)||ve(e)||Ve(e)||De(e)||xe(e)||Se(e)||be(e)}function Oe(e){return"esri.layers.BuildingSceneLayer"===e.declaredClass}function Pe(e){return"esri.layers.SubtypeGroupLayer"===e.declaredClass}function Me(e){return"esri.layers.VoxelLayer"===e.declaredClass}function Ae(e){return"esri.layers.WMSLayer"===e.declaredClass}function ke(e){return"esri.layers.WMTSLayer"===e.declaredClass}function Ue(e){return"esri.layers.MapImageLayer"===e.declaredClass}function Be(e){return"esri.layers.TileLayer"===e.declaredClass}function Ne(e){return e.declaredClass===de}function qe(e){return e.declaredClass===ye}function $e(e){return e.declaredClass===he}function He(e){return"stretch-ramp"===e.type}function We(e){const t="authoringInfo"in e?e?.authoringInfo:null;return"univariate-color-size"===t?.type}function Ge(e){const t="authoringInfo"in e?e?.authoringInfo:null;return"univariate-color-size"===t?.type&&"above-and-below"===t?.univariateTheme}function Je(e){return"sublayers"in e}function Qe(e){return e&&"symbol"in e}async function Ze(e,t){const s=await ae("esri/widgets/Legend/t9n/Legend");return"previewTemplateAriaLabel"!==e||t||(e="previewAriaLabel"),oe(s[e],{label:t})}function Ke(e,t){const{field:s,field2:i,field3:l,fieldDelimiter:r,valueExpression:n}=e;if(!s)return null;const a=!(!s&&!n||!i&&!l)?t?.toString().split(r||""):[t],o=s?{[s]:a?.[0]}:null;return o&&(i&&(o[i]=a?.[1]),l&&(o[l]=a?.[2])),o}const Xe=new j({style:"path",path:"M10,5 L5,0 0,5 M5,0 L5,15",size:15,outline:{width:1,color:[85,85,85,1]}});let Ye={},et=class extends l{constructor(e){super(e),this._hasColorRamp=!1,this._hasOpacityRamp=!1,this._hasSizeRamp=!1,this._webStyleSymbolCache=new Map,this._dotDensityUrlCache=new Map,this._scaleDrivenSizeVariable=null,this._hasClusterSizeVariable=!1,this._layerDefinitionExpression=null,this._layerDefinitionExpressionClause=null,this._layerDisplayFilterId=null,this._layerDisplayFilterClause=null,this.children=new n,this.layerView=null,this.layer=null,this.legendElements=[],this.parent=null,this.hideLayersNotInCurrentView=!1,this.keepCacheOnDestroy=!1,this.respectLayerDefinitionExpression=!1,this.respectLayerVisibility=!0,this.sublayerIds=[],this.title=null,this.view=null}initialize(){const e=()=>this.notifyChange("ready");this.addHandles([d(()=>this.children,"change",t=>{const{added:s,removed:i}=t;s.forEach(t=>{const s=`activeLayerInfo-ready-watcher-${t.layer.uid}`;this.addHandles(y(()=>t.ready,e,h),s)}),i.forEach(e=>this.removeHandles(e.layer.uid)),e()})]),this.keepCacheOnDestroy||(Ye={})}destroy(){this._webStyleSymbolCache=null,this._dotDensityUrlCache=null,this._scaleDrivenSizeVariable=null,this.keepCacheOnDestroy||(Ye=null),this._layerDefinitionExpressionClause=null}get effectList(){const e=this.layer;let t=null;return"effect"in e&&e.effect&&(t=new _,t.effect=e.effect,t.endTransition(),t.scale=this.scale),t}get opacity(){const e=this.layer.opacity,t=this.parent?.opacity,s=this.layer.parent,i=s&&"uid"in s?this._getParentLayerOpacity(s):null;return null!=t?t*e:null!=i?i*e:e}get ready(){return null===this.layer||(this.children.length>0?this._isGroupActive():this.legendElements.length>0)}get scale(){return this.view?.scale??0}get isScaleDriven(){const e=this.layer;if(null===e)return!1;if("effect"in e&&e.effect&&Array.isArray(e.effect))return!0;if("featureReduction"in e&&e.featureReduction){if("cluster"===e.featureReduction.type)return!0;if("binning"===e.featureReduction.type&&"renderer"in e.featureReduction&&e.featureReduction.renderer)return this._isRendererScaleDriven(e.featureReduction.renderer)}return"renderer"in e&&e.renderer?!!("displayFilterInfo"in e&&e.displayFilterInfo&&Ce(e.renderer))||this._isRendererScaleDriven(e.renderer):this._isLayerScaleDriven(this.layer)}get version(){return this._get("version")+1}async buildLegendElementsForFeatureCollections(e){if(!(!this.hideLayersNotInCurrentView||await this._isLayerInCurrentView()))return this.legendElements=[],void this.notifyChange("ready");const t=Array.from(e,e=>{if(F(e))return this._getRendererLegendElements(e.renderer,{title:e.title});if(e.featureSet?.features.length){const t=e.layerDefinition,s=t?.drawingInfo,i=s&&R(s.renderer),l=fe.read(t.geometryType);return i?this._getRendererLegendElements(i,{title:e.name,geometryType:l}):(o.getLogger(this).warn("drawingInfo not available!"),null)}return null});try{const e=[],s=await Promise.allSettled(t);for(const t of s)if("fulfilled"===t.status)for(const s of t.value??[])e.push(s);this.legendElements=e,this.notifyChange("ready")}catch(s){o.getLogger(this).warn("error while building legend for layer!",s)}}async buildLegendElementsForRenderer(e){try{const t=!this.hideLayersNotInCurrentView||await this._isLayerInCurrentView();this.legendElements=t?await this._getRendererLegendElements(e):[],this.notifyChange("ready")}catch(t){o.getLogger(this).warn("error while building legend for layer!",t)}}async buildLegendElementsForFeatureReduction(e){try{const t=!this.hideLayersNotInCurrentView||await this._isLayerInCurrentView();this.legendElements=t?await this._getLegendElementsForFeatureReduction(e):[],this.notifyChange("ready")}catch(t){o.getLogger(this).warn("error while building legend for layer!",t)}}async buildLegendElementsForTools(){const e=this.layer;if(Me(e))await this._constructLegendElementsForVoxelLayer();else if(ke(e))this._constructLegendElementsForWMTSlayer();else if(Ae(e))await this._constructLegendElementsForWMSSublayers();else if(Oe(e))await this._constructLegendElementsForBuildingSceneLayer();else if(Ue(e)||Be(e)||Pe(e))await this._constructLegendElementsForSublayers();else{this.removeHandles("imageryLayers-watcher");let t="default";if(Ne(e)){const s=e;t=(s?.rasterFunction?.functionName||"default")+"_"+(e.bandIds?.length?e.bandIds.join(""):"###")}if(qe(e)||"link-chart"===e.type)return;await this._getLegendLayers(`${e.uid}-${t}`).then(async t=>{this.legendElements=[],this.notifyChange("ready");const s=t.map(async t=>{if(Ne(e)){const t=y(()=>[e.rasterFunction,e.bandIds],()=>c(async()=>{Ye.default=null,e.renderer?await this.buildLegendElementsForRenderer(e.renderer):await this.buildLegendElementsForTools()})());this.addHandles(t,"imageryLayers-watcher")}const s=this._generateSymbolTableElementForLegendLayer(t);s?.infos.length&&(Ne(e)&&(s.title=e.title),this.legendElements.push(s)),this.notifyChange("ready")});await Promise.allSettled(s)}).catch(e=>{o.getLogger(this).warn("Request to server for legend has failed!",e)})}}async _isLayerInCurrentView(){const e=this.layer,t=this.layerView,s=t&&"createQuery"in t&&"queryFeatureCount"in t;if(!s&&!(t&&"createQuery"in e&&"queryFeatureCount"in e))return!0;await m(()=>!t.updating);const i=s?"createQuery"in t&&t.createQuery():"createQuery"in e&&e.createQuery();if(!i)return!0;i.geometry=this.view.extent;return 0!==(s?"queryFeatureCount"in t&&await t.queryFeatureCount(i):"queryFeatureCount"in e&&await e.queryFeatureCount(i))}_getParentLayerOpacity(e){let t=1;const s=e.parent;return s&&"uid"in s&&(t=this._getParentLayerOpacity(s)),e.opacity*t}_isGroupActive(){return this.children.some(e=>e.ready)}_isRendererScaleDriven(e){if("dot-density"===e.type)return!0;const t="valueExpression"in e?e.valueExpression:null;if(me.test(t))return!0;const s="visualVariables"in e?e.visualVariables:null;return!!s?.some(e=>this._isScaleDrivenSizeVariable(e))||this._hasScaleDrivenSymbols(e)}_hasScaleDrivenSymbols(e){switch(e.type){case"simple":return this._isScaleDrivenSymbol(e.symbol);case"class-breaks":return this._isScaleDrivenSymbol(e.defaultSymbol)||e.classBreakInfos.some(e=>this._isScaleDrivenSymbol(e.symbol));case"unique-value":return this._isScaleDrivenSymbol(e.defaultSymbol)||!!e.uniqueValueInfos?.some(e=>this._isScaleDrivenSymbol(e.symbol))}return!1}_isScaleDrivenSymbol(e){if("cim"===e?.type){const{primitiveOverrides:t,minScale:s,maxScale:i}=e.data,l=t?.some(e=>/\$view\.scale/.test(e.valueExpressionInfo?.expression||""))??!1;return null!=s||null!=i||l}return!1}_isScaleDrivenSizeVariable(e){if(e&&"size"!==e.type)return!1;const t=e,s=t.minSize,i=t.maxSize;return!("object"!=typeof s||!s||!this._isScaleDrivenSizeVariable(s))||(!("object"!=typeof i||!i||!this._isScaleDrivenSizeVariable(i))||me.test(t.valueExpression))}_isLayerScaleDriven(e){if("minScale"in e&&e.minScale>0||"maxScale"in e&&e.maxScale>0)return!0;if("sublayers"in e&&e.sublayers)return e.sublayers.some(e=>this._isLayerScaleDriven(e));const t=e.parent;if(!1===e.loaded&&t&&Ue(t)&&"source"in e&&e.source&&"map-layer"===e.source.type)for(const s of t.sourceJSON.layers??[])if(s.id===e.source.mapLayerId&&(s.minScale>0||s.maxScale>0))return!0;return!1}async _constructLegendElementsForVoxelLayer(){this.legendElements=[],this.removeHandles("voxel-style-watcher"),this.removeHandles("voxel-current-variable");const e=this.layer;this.addHandles(y(()=>e.currentVariableId,()=>this._constructLegendElementsForVoxelLayer()),"voxel-current-variable"),this.addHandles(y(()=>e.getVariableStyles(),()=>this._constructLegendElementsForVoxelLayer()),"voxel-style-watcher");const t=e.getVariableStyle(null),s=[];if(t)if(t.uniqueValues?.length){const e=[];t.uniqueValues.forEach(t=>{t.enabled&&e.push({label:t.label||`${t.value}`,value:t.value,symbol:new T({color:t.color,outline:null})})}),e.length&&s.push({type:"symbol-table",title:t.label,infos:e})}else if(t.transferFunction){const{colorStops:e,stretchRange:i}=t.transferFunction,l=e.toArray().reverse(),r=i.map((e,t)=>`${0===t?Y:ee} ${ne(e)}`).reverse(),n=l.map(e=>({color:e.color,value:null,label:null}));n[0].label=r[0],n[n.length-1].label=r[1],s.push({type:"color-ramp",title:t.label,infos:n,preview:M(l.map(e=>e.color),{ariaLabel:await Ze("previewColorRampAriaLabel")})})}await this._generatePreviewsForLegendElements(s,{opacity:e.opacity}),this.legendElements=s,this.notifyChange("ready")}_constructLegendElementsForWMTSlayer(){this.legendElements=[],this.removeHandles("wmts-activeLayer-watcher");const e=this.layer.activeLayer;this.addHandles(y(()=>{const{layer:e}=this;return e&&"activeLayer"in e&&e.activeLayer},()=>this._constructLegendElementsForWMTSlayer()),"wmts-activeLayer-watcher");const t=e.styleId?e.styles?.find(({id:t})=>t===e.styleId)?.legendUrl:void 0;t&&(this.legendElements=[{type:"symbol-table",title:e.title,infos:[{src:t,opacity:this.opacity}]}]),this.notifyChange("ready")}async _constructLegendElementsForWMSSublayers(){this.legendElements=[],this.removeHandles("wms-sublayers-watcher");const e=this.layer;let t=null;(e.customParameters||e.customLayerParameters)&&(t={...e.customParameters,...e.customLayerParameters}),this.addHandles(y(()=>{const{layer:e}=this;return e&&"sublayers"in e&&e.sublayers},()=>this._constructLegendElementsForWMSSublayers()),"wms-sublayers-watcher"),this.legendElements=await this._generateLegendElementsForWMSSublayers(e.sublayers,t),this.notifyChange("ready")}async _generateLegendElementsForWMSSublayers(e,t){const s=this.layer,i=[];this.addHandles(e.on("change",()=>this._constructLegendElementsForWMSSublayers()),"wms-sublayers-watcher");const l=this.sublayerIds?.map(e=>s.findSublayerById(e))?.filter(r)??[],n=l.length?l:e.toArray();for(const r of n){const e=y(()=>[r.title,r.visible,r.legendEnabled],()=>this._constructLegendElementsForWMSSublayers());if(this.addHandles(e,"wms-sublayers-watcher"),!this.respectLayerVisibility||r.visible&&r.legendEnabled){const e=await this._generateSymbolTableElementForWMSSublayer(r,t);e?.infos.length&&i.unshift(e)}}return i}async _generateSymbolTableElementForWMSSublayer(e,t){if(!e.legendUrl&&e.sublayers){const s=(await this._generateLegendElementsForWMSSublayers(e.sublayers,t)).filter(e=>e);return{type:"symbol-table",title:e.title,infos:s}}return this._generateSymbolTableElementForLegendUrl(e,t)}async _generateSymbolTableElementForLegendUrl(e,t){let s=e.legendUrl;if(!s)return;const l={type:"symbol-table",title:e.title||e.name||String(e.id??""),infos:[]};t&&(s=g(s,t));let r=null;const n=e.layer?.opacity;try{r=(await i(s,{responseType:"image"})).data,r&&(r.style.opacity=n)}catch{}return l.infos.push({src:s,preview:r,opacity:n}),l}_getLegendLayers(e,t){const s=Ye&&Ye[e];return s?Promise.resolve(s):this._legendRequest(t).then(t=>{const s=t.layers;return Ye[e]=s,s})}_legendRequest(e){const t=this.layer;let s={f:"json",dynamicLayers:e};if(Ne(t)){const e=t.exportImageServiceParameters.rasterFunction;if(e&&(s.renderingRule=JSON.stringify(e.functionDefinition?.toJSON()||e.toJSON())),t.bandIds&&(s.bandIds=t.bandIds.join()),t.raster||t.viewId||t.customParameters){const{raster:e,viewId:i,customParameters:l}=t;s={raster:e,viewId:i,...s,...l}}}let l=t.url.replace(/(\/)+$/,"");if("version"in t&&+t.version>=10.01){const e=l.indexOf("?");e>-1?l=l.slice(0,e)+"/legend"+l.slice(e):l+="/legend"}else{const e=l.toLowerCase().indexOf("/rest/"),t=-1===e?l:l.slice(0,e)+l.slice(e+5);l=ce+"?soapUrl="+encodeURI(t)+"&returnbytes=true"}return i(l,{query:s}).then(e=>e.data)}async _constructLegendElementsForBuildingSceneLayer(){this.legendElements=[],this.removeHandles("sublayers-watcher");const e=this.layer;this.addHandles(y(()=>e.sublayers,()=>this._constructLegendElementsForBuildingSceneLayer()),"sublayers-watcher");try{this.legendElements=await this._generateLegendElementsForBuildingSublayers(e.sublayers,this.opacity),this.notifyChange("ready")}catch(t){o.getLogger(this).warn("Request to server for legend has failed!",t)}}async _generateLegendElementsForBuildingSublayers(e,t){let s=[];this.addHandles(e.on("change",()=>this._constructLegendElementsForBuildingSceneLayer()),"sublayers-watcher");const i=e.toArray();for(const l of i){const e=y(()=>["renderer"in l&&l.renderer,l.opacity,l.title,l.visible],()=>this._constructLegendElementsForBuildingSceneLayer());if(this.addHandles(e,"sublayers-watcher"),!this.respectLayerVisibility||l.visible){const e=null!=l?.opacity?l.opacity:null,i=null!=e?e*t:t;if("building-group"===l.type){const e={type:"symbol-table",title:l.title,infos:[]},t=await this._generateLegendElementsForBuildingSublayers(l.sublayers,i);e.infos.push(...t),s=[e,...s]}else if(l.renderer){s=[...await this._getRendererLegendElements(l.renderer,{title:l.title,opacity:i,sublayer:l}),...s]}}}return s.filter(e=>!!e&&(!("infos"in e)||!e.infos||e.infos.length>0))}async _constructLegendElementsForSublayers(){this.legendElements=[],this.removeHandles("sublayers-watcher");const e=this.layer;if(Ue(e)||Be(e)||Pe(e)){this.addHandles(y(()=>e.sublayers,()=>this._constructLegendElementsForSublayers),"sublayers-watcher");try{this.legendElements=await this._generateLegendElementsForSublayers(e.sublayers,this.opacity),this.notifyChange("ready")}catch(t){o.getLogger(this).warn("Request to server for legend has failed!",t)}}}async _generateLegendElementsForSublayers(e,t,s){const i=this.layer;let l=[];this.addHandles(e.on("change",()=>this._constructLegendElementsForSublayers()),"sublayers-watcher");let n=e.toArray();!s&&this.sublayerIds&&this.sublayerIds.length&&(n=Pe(i)?this.sublayerIds.map(e=>i.findSublayerForSubtypeCode(e)).filter(r):this.sublayerIds.map(e=>i.findSublayerById(e)).filter(r));for(const r of n){const e=y(()=>[r.renderer,r.opacity,r.title,r.visible,r.legendEnabled],()=>this._constructLegendElementsForSublayers());if(this.addHandles(e,"sublayers-watcher"),!this.respectLayerVisibility||r.visible&&r.legendEnabled&&this._isSublayerInScale(r)){const e=null!=r?.opacity?r.opacity:null,i=null!=e?e*t:t,n=!Je(r)||r.originIdOf("renderer")>2&&!r.sublayers;if(r.renderer&&n){await r.load();l=[...await this._getRendererLegendElements(r.renderer,{title:r.title,opacity:i,sublayer:r}),...l]}else if(Je(r)){const e=await this._generateSymbolTableElementForSublayer(r,i,s);e&&l.unshift(e)}}}return l.filter(e=>!!e&&(!("infos"in e)||!e.infos||e.infos.length>0))}async _generateSymbolTableElementForSublayer(e,t,s){if(!s){s=new Map;const t=this.layer,i=e.source;let l=null;if(!(!i||"map-layer"===i.type&&i.mapLayerId===e.id&&(!i.gdbVersion||i.gdbVersion===("gdbVersion"in t&&t.gdbVersion)))||e.originIdOf("renderer")>2||e.originIdOf("labelingInfo")>2||e.originIdOf("labelsVisible")>2){const e=new L({layer:this.layer});l=e.hasDynamicLayers?e.dynamicLayers:null,e.destroy()}const r=l||`${t.uid}-default`;(await this._getLegendLayers(r,l)).forEach(e=>s.set(e.layerId,e))}const i=s.get(e.id);if((!i||i?.subLayerIds&&i.defaultVisibility)&&e.sublayers){const i=await this._generateLegendElementsForSublayers(e.sublayers,t,s);return{type:"symbol-table",title:e.title,infos:i}}return this._generateSymbolTableElementForLegendLayer(i,e,t)}_generateSymbolTableElementForLegendLayer(e,t,s){if(!e?.legend||this.respectLayerVisibility&&!this._isLegendLayerInScale(e,t))return null;const i=t?.renderer;let l=t?.title||e.layerName;if(i&&(!t||t?.originIdOf("renderer")>2)){const e=t?.title||this._getRendererTitle(i,t);e&&(l&&"string"!=typeof e&&"title"in e&&(e.title=l),l=e)}const r={type:"symbol-table",title:l,legendType:e.legendType||null,infos:[]},n=t?this._sanitizeLegendForSublayer(e.legend.slice(),t):e.legend;return e.legendGroups&&e.legendGroups.length>0?e.legendGroups.forEach(t=>{const i={type:"symbol-table",title:t.heading,legendType:e.legendType||null,infos:this._generateSymbolTableElementInfosForLegendLayer(n.filter(e=>e.groupId===t.id),e.layerId,s)};i.infos?.length>0&&r.infos.push(i)}):r.infos=this._generateSymbolTableElementInfosForLegendLayer(n,e.layerId,s),r.infos.length>0?r:null}_generateSymbolTableElementInfosForLegendLayer(e,t,i){return e.map(e=>{let l=e.url;if(e.imageData&&e.imageData.length>0)l=`data:image/png;base64,${e.imageData}`;else{if(0===l.indexOf("http"))return null;l=s(`${this.layer.url}/${t}/images/${l}`)}return{label:e.label,src:l,opacity:i??this.opacity,width:e.width,height:e.height}}).filter(r)}_isSublayerInScale(e){const t=e.minScale||0,s=e.maxScale||0;return!(t>0&&t<this.scale||s>this.scale)}_isLegendLayerInScale(e,t){const s=t||this.layer;let i=null,l=null,r=!0;return!s.minScale&&0!==s.minScale||!s.maxScale&&0!==s.maxScale?(0===e.minScale&&s.tileInfo&&(i=s.tileInfo.lods[0].scale),0===e.maxScale&&s.tileInfo&&(l=s.tileInfo.lods[s.tileInfo.lods.length-1].scale)):(i=Math.min(s.minScale,e.minScale)||s.minScale||e.minScale,l=Math.max(s.maxScale,e.maxScale)),(i>0&&i<this.scale||l>this.scale)&&(r=!1),r}_sanitizeLegendForSublayer(e,t){if("version"in this.layer&&+this.layer.version<10.1||0===e.length)return e;const s=t.renderer,i=e.some(e=>e.values);let l=0,r=null;return i&&e.some((e,t)=>(e.values||(l=t,r=e,r.label||(r.label="others")),null!=r)),s?"unique-value"===s.type?r&&(e.splice(l,1),e.push(r)):"class-breaks"===s.type&&(r&&e.splice(l,1),s.legendOptions?.order||e.reverse(),r&&e.push(r)):r&&(e.splice(l,1),e.push(r)),e}async _getRendererLegendElements(e,t={}){if(!je(e,this.view))return o.getLogger(this).warn(`Renderer of type '${e.type}' not supported!`),[];if(Ie(e))return this._constructPointCloudRendererLegendElements(e,t);if(ze(e))return this._constructDotDensityRendererLegendElements(e);const s=await this._loadRenderer(e);return Te(s)?this._constructPieChartRendererLegendElements(s):this._constructRendererLegendElements(s,t)}async _getLegendElementsForFeatureReduction(e){let t=null;return"binning"===e.type?t=e.renderer:"cluster"===e.type&&(t=this._getClusterRenderer(e)),t?this._getRendererLegendElements(t):[]}_getPointCloudRendererTitle(e){return(e.legendOptions?.title||e.field)??""}async _constructPointCloudRendererLegendElements(e,t={}){const s=t.title,i=[];let l=null,r=null;if(Ve(e))l={type:"symbol-table",title:s||this._getPointCloudRendererTitle(e),infos:[]},e.colorClassBreakInfos.forEach(e=>{l.infos.unshift({label:e.label||e.minValue+" - "+e.maxValue,value:[e.minValue,e.maxValue],symbol:this._getAppliedCloneSymbol(pe,e.color)})});else if(De(e)){const t=e.stops;let i=null;if(t?.length&&(1===t.length&&(i=t[0].color),!i)){const e=t[0].value,s=t[t.length-1].value;if(null!=e&&null!=s){i=q(e+(s-e)/2,t)}}l={type:"symbol-table",title:null,infos:[{label:null,value:null,symbol:this._getAppliedCloneSymbol(pe,i||pe.color)}]};const n=$(e.stops??[])??[];r={type:"color-ramp",title:s||this._getPointCloudRendererTitle(e),infos:n,preview:M(n.map(e=>e.color),{ariaLabel:await Ze("previewColorRampAriaLabel")})}}else xe(e)&&(l={type:"symbol-table",title:s||this._getPointCloudRendererTitle(e),infos:[]},e.colorUniqueValueInfos?.forEach(e=>{l.infos.push({label:e.label||e.values.join(", "),value:e.values.join(", "),symbol:this._getAppliedCloneSymbol(pe,e.color)})}));return l?.infos.length&&i.push(l),r?.infos.length&&i.push(r),await this._generatePreviewsForLegendElements(i,{opacity:this.opacity,symbolConfig:{applyColorModulation:!!e.colorModulation}}),i}async _getElementInfoForDotDensity(e,t){const{color:s,label:i,valueExpressionTitle:l}=t,{backgroundColor:r,outline:n,dotSize:a}=e,o=this.effectList,u=o?.effects.map(e=>e.toJSON()),c=w(u),d=await Ze("previewTemplateAriaLabel",i||l),y=a+"-"+s+"-"+r+"-"+(n&&JSON.stringify(n.toJSON()))+"-"+c,h=this._dotDensityUrlCache,m=h.has(y)?h.get(y):A(e,s,{ariaLabel:d});h.set(y,m);const f={shape:{type:"image",x:0,y:0,width:m.width,height:m.height,src:m.src},fill:null,stroke:null,offset:[0,0]},p=P([[f]],[m.width,m.height],{effectView:this.effectList,ariaLabel:d});return{opacity:1,src:m.src,preview:p,width:m.width,height:m.height}}async _constructDotDensityRendererLegendElements(e){const t=e.calculateDotValue(this.view.scale),s=e.legendOptions?.unit,i={type:"symbol-table",title:{value:t&&Math.round(t),unit:s||""},infos:[]};for(const l of e.attributes){const t=await this._getElementInfoForDotDensity(e,l);t.label=l.label||l.valueExpressionTitle||l.field,i.infos.push(t)}return[i]}async _constructPieChartRendererLegendElements(e){const t=[];let s=null;const i=e.outline;e.attributes.forEach(e=>{const s=new j({color:e.color,outline:i}),l=e.label||e.valueExpressionTitle||e.field;t.push({label:l,symbol:s})});const l=t.length?[...t]:[];if(e.othersCategory?.color&&0!==e.othersCategory?.threshold){const l=new j({color:e.othersCategory.color,outline:i});s=e.othersCategory.label||"Other",t.push({label:s,symbol:l})}if(e.defaultColor?.a){const s=new j({color:e.defaultColor,outline:i});t.push({label:e.defaultLabel,symbol:s})}const r=await this._getVisualVariableLegendElements(e,this.layer)||[];if(t.length){r.unshift({type:"symbol-table",title:null,infos:t});const n=l.filter(e=>e.label!==s).map(e=>e.symbol.color).filter(Boolean),a=k(n,{holePercentage:e.holePercentage,backgroundColor:e.backgroundFillSymbol?.color,effectList:this.effectList,outline:i,ariaLabel:await Ze("previewPieChartAriaLabel")});r.unshift({type:"pie-chart-ramp",title:this._getRendererTitle(e,this.layer),infos:t,preview:a})}return await this._generatePreviewsForLegendElements(r,{opacity:this.layer.opacity,effectView:this.effectList}),r}async _getWhereClause(e,t,s){const i=await p(e,s),l=new Set,{field:r,field2:n,field3:a}=t;E(l,s,[r,n,a]),await C(l,s,t.valueExpression);const o=new Set(Array.from(l,e=>e.toLowerCase())),u=i?.fieldNames.map(e=>e.toLowerCase());return u?.some(e=>!o.has(e))?null:i}async _processDefinitionExpression(e,t){if(!("definitionExpression"in e))return;const s=e.definitionExpression;s&&this.respectLayerDefinitionExpression?this._layerDefinitionExpression!==s&&(this._layerDefinitionExpressionClause=await this._getWhereClause(s,t,e.fieldsIndex)):this._layerDefinitionExpressionClause=null,this._layerDefinitionExpression=s}async _processDisplayFilter(e,t){if(!("displayFilterInfo"in e))return;const s=e.displayFilterInfo?v(e.displayFilterInfo,this.view):null;return s?.where?this._layerDisplayFilterId!==s?.id&&(this._layerDisplayFilterClause=await this._getWhereClause(s.where,t,e.fieldsIndex)):this._layerDisplayFilterClause=null,this._layerDisplayFilterId=s?.id,s}async _constructRendererLegendElements(e,t={}){const{title:s,sublayer:i}=t,l=i||this.layer,r=te(e,"reference-size"),n=te(e,"spike");let a=null;Ce(e)&&(await this._processDefinitionExpression(l,e),a=await this._processDisplayFilter(l,e)),this._hasColorRamp=!1,this._hasOpacityRamp=!1,this._hasSizeRamp=!1,this._scaleDrivenSizeVariable=null;const o=await this._getVisualVariableLegendElements(e,l)||[],u={type:"symbol-table",title:s||this._getRendererTitle(e,l),infos:[]};let c=null,d=!1;const y=new Set;if(be(e)&&!this._hasSizeRamp){const t=await se(e);u.infos.push({label:null,symbol:t})}else if(We(e)){let t=s;const i=Ge(e)?"univariate-above-and-below-ramp":"univariate-color-size-ramp",l=o.findIndex(e=>"color-ramp"===e.type),r=-1!==l?o.splice(l,1)[0]:null,n=o.findIndex(e=>"size-ramp"===e.type),a=-1!==n?o.splice(n,1)[0]:null,u=[];r&&(t=r.title,u.push(r)),a&&(t=a.title,u.push(a)),u.length>0&&o.push({type:i,title:t,infos:u})}else if(Fe(e)){const t=G(e);o.push({type:"heatmap-ramp",title:s||this._getRendererTitle(e,l),infos:t,preview:M(t.map(e=>e.color),{effectList:this.effectList,ariaLabel:await Ze("previewColorRampAriaLabel")})})}else if(Ce(e)){const t=e.authoringInfo;if(t&&"relationship"===t.type){const{numClasses:s,field1:i,field2:r}=t,n=t.focus;if(s&&i&&r){const t=[i,r];let a=J(n)||0;for(const e of t){const{field:t,normalizationField:s,label:i}=e,r=i||{field:this._getFieldAlias(t,l),normField:s&&this._getFieldAlias(s,l)},n=Xe.clone();n.angle=a,u.infos.push({label:r,symbol:n}),y.add(n),a+=90}const c=Q({focus:n,numClasses:s,infos:e.uniqueValueInfos??[]});o.unshift(c)}}else if(Ne(this.layer)||qe(this.layer))e.uniqueValueInfos?.forEach(t=>{t.symbol&&this._checkClausesForUVR(e,t.value)&&u.infos.push({label:t.label||t.value,value:t.value,symbol:t.symbol})});else{const{field:t,field2:i,field3:n,fieldDelimiter:o,valueExpression:c,defaultSymbol:y}=e,h=!(!t&&!c||!i&&!n),m=this._layerDisplayFilterClause?a?.title:null,f=[];if(e.uniqueValueGroups?.forEach(s=>{const a={type:"symbol-table",title:m||s.heading,infos:[]};s.classes?.forEach(s=>{const{symbol:u,values:d}=s;if(u){const y=[],m=[];for(const e of d??[]){const{value:s,value2:r,value3:a}=e,u=[],d=[];(t||c)&&(u.push(s),d.push(this._getDomainName(t,s,l))),i&&(u.push(r),d.push(this._getDomainName(i,r,l))),n&&(u.push(a),d.push(this._getDomainName(n,a,l))),y.push(h?u.join(o||""):u[0]),m.push(d.join(" - "))}const f=y.join(", ");let p=s.label;if(!p){const e=m.filter(Boolean);p=e.length?e.join(", "):f}const g=u.clone();"cim"===g.type&&r&&z(g,{innerDotSize:.5*ue,outerRingSize:ue}),y.some(t=>this._checkClausesForUVR(e,t))&&a.infos.push({label:p,value:f,symbol:g})}}),a.infos.length&&f.push(a)}),f.length){const t=f[0];if(1===f.length&&"title"in t&&!t.title){const e=t.infos?.filter(Qe)??[];u.infos.push(...e)}else y&&(f.push({type:"symbol-table",infos:[{label:e.defaultLabel||"others",symbol:y}]}),d=!0),u.infos.push(...f);s||e.legendOptions?.title||e.valueExpressionTitle||(u.title=null)}}e.defaultSymbol&&!d&&(u.infos.push({label:e.defaultLabel||"others",symbol:e.defaultSymbol}),d=!0)}else if(Ee(e)){if(!r&&!n){c=this._isUnclassedRenderer(e);if(!c||!this._hasSizeRamp){const t=e.classBreakInfos.filter(({symbol:e})=>e),s="ascending-values"===e.legendOptions?.order;for(const{label:e,minValue:i,maxValue:l,symbol:r}of t){const t={label:e||(c?null:`${i} - ${l}`),value:[i,l],symbol:r};s?u.infos.push(t):u.infos.unshift(t)}c&&(u.title=null),this._updateInfosForClassedSizeRenderer(e,u.infos)}e.defaultSymbol&&!c&&(u.infos.push({label:e.defaultLabel||"others",symbol:e.defaultSymbol}),d=!0)}}else if(we(e))if(qe(this.layer)||$e(this.layer)){const t=await this._constructTileImageryStretchRendererElements(e);He(t)?o.push(t):u.infos=t}else{const t=this.layer;let s,i;e.customStatistics?.length&&({min:s,max:i}=e.customStatistics[0]);let l=[],r=t.serviceRasterInfo;if(t.rasterFunction)try{r=await t.generateRasterInfo(t.rasterFunction)}catch{}const n=I(r.pixelType);if(1===r.bandCount){const l=t.bandIds?.[0]||0;s=null!=s?s:r.statistics?r.statistics[l].min:n[0],i=null!=i?i:r.statistics?r.statistics[l].max:n[1],s||i?o.push(await this._getStretchLegendElements(e,{min:s,max:i})):this._getServerSideLegend()}else if(t.bandIds&&1===t.bandIds.length)s=null!=s?s:r.statistics?r.statistics[t.bandIds[0]].min:n[0],i=null!=i?i:r.statistics?r.statistics[t.bandIds[0]].max:n[1],s||i?o.push(await this._getStretchLegendElements(e,{min:s,max:i})):this._getServerSideLegend();else if(r.bandCount>=3){const{bandInfos:e}=r,{bandIds:s}=t;e.length>=r.bandCount?3===s?.length?(l=s.map(t=>e[t].name),u.infos=this._createSymbolTableElementMultiBand(l)):"lerc"===t.format?(l=[0,1,2].map(t=>e[t].name),u.infos=this._createSymbolTableElementMultiBand(l)):this._getServerSideLegend():"lerc"===t.format?(l=["band1","band2","band3"],u.infos=this._createSymbolTableElementMultiBand(l)):this._getServerSideLegend()}else this._getServerSideLegend()}else if(_e(e))e.colormapInfos.forEach(e=>{u.infos.push({label:e.label,value:e.value,symbol:this._getAppliedCloneSymbol(ge,e.color)})});else if(Le(e)){let s=e.symbol;switch(t.geometryType){case"point":s="pointSymbol"in l?l.pointSymbol:null;break;case"polyline":s="lineSymbol"in l?l.lineSymbol:null;break;case"polygon":s="polygonSymbol"in l?l.polygonSymbol:null}const i=this._hasClusterSizeVariable&&this._getClusterSymbol()||!this._hasSizeRamp;e.symbol&&i&&u.infos.push({label:e.label,symbol:s})}else if(Se(e)){e.outputUnit&&(this.title="("+e.toJSON().outputUnit+")"),u.title=e.attributeField;const t=e.getClassBreakInfos();t?.length?t.forEach(e=>{u.infos.push({label:e.minValue+" - "+e.maxValue,symbol:e.symbol})}):u.infos.push({label:e.attributeField,symbol:e.getDefaultSymbol()})}else ve(e)&&o.push(await this._getStretchLegendElements(e,{min:0,max:255}));const h=e.defaultSymbol;!h||d||Le(e)||c&&!this._hasColorRamp&&!this._hasSizeRamp&&!this._hasOpacityRamp||o.push({type:"symbol-table",infos:[{label:e.defaultLabel||"others",symbol:h}]}),u.infos.length&&o.unshift(u);const m=null==t.opacity?this.opacity:t.opacity,f=this._isTallSymbol("visualVariables"in e?e.visualVariables:null),p=Ne(this.layer)||qe(this.layer);return await this._generatePreviewsForLegendElements(o,{opacity:m,symbolConfig:{isTall:f,isSquareFill:p},effectView:this.effectList},{defaultSymbol:h,arrowMarkerSymbols:y}),e=null,o}_checkClausesForUVR(e,t){const s=Ke(e,t);return!s||(!this._layerDefinitionExpressionClause||this._layerDefinitionExpressionClause.testFeature(s))&&(!this._layerDisplayFilterClause||this._layerDisplayFilterClause.testFeature(s))}_getServerSideLegend(){setTimeout(()=>this.buildLegendElementsForTools(),0)}_getAllInfos(e){const t=e?.infos;return t?t.reduce((e,t)=>e.concat(this._getAllInfos(t)),[]):[e]}async _constructTileImageryStretchRendererElements(e){const t=this.layer,s=t.symbolizer.rasterInfo??t.raster.rasterInfo;let i,l;const r=e?.customStatistics?.length?e.customStatistics:s?.statistics;if(r)({min:i,max:l}=r[0]);else{const e=I(s.pixelType);i=e[0],l=e[1]}if(t.hasStandardTime()&&(i=t.getStandardTimeValue(i),l=t.getStandardTimeValue(l)),1===s.bandCount||1===t.bandIds?.length)return this._getStretchLegendElements(e,{min:i,max:l});const n=(t?.bandIds?.length?t.bandIds:Array.from(Array(Math.min(s.bandCount,3)).keys())).map(e=>s.bandInfos[e].name);return n.length<3?n.push(n[1]):n.length>3&&n.splice(3),this._createSymbolTableElementMultiBand(n)}async _getStretchLegendElements(e,t){const s=e.colorRamp,i=H(s,t);return{type:"stretch-ramp",title:"",infos:i,preview:M(i.map(e=>e.color),{ariaLabel:await Ze("previewColorRampAriaLabel")})}}_getClusterSymbol(){const e=this.layer,t="featureReduction"in e&&e.featureReduction,s=t&&"symbol"in t&&t.renderer;return s&&!0!==s?.authoringInfo?.isAutoGenerated?null:t&&"symbol"in t?t.symbol:null}async _getSizeLegendElement(e,t,s,i){return{type:"size-ramp",title:this._hasClusterSizeVariable?this._getClusterTitle(t):e,infos:await Z(s,t,await ie(s),this.scale,this.view,i,this._hasClusterSizeVariable?this._getClusterSymbol():null)}}_createSymbolTableElementMultiBand(e){const t=[],s=["red","green","blue"];return e.forEach((e,i)=>{t.push({label:{colorName:s[i],bandName:e},src:le[i],opacity:this.opacity??1})}),t}_updateInfosForClassedSizeRenderer(e,t){const s=e.authoringInfo&&"class-breaks-size"===e.authoringInfo.type,i=e.classBreakInfos.some(e=>B(e.symbol));if(s&&i){const s=K,i=X,l=e.classBreakInfos.length,r=(s-i)/(l>1?l-1:l);t.forEach((e,t)=>{e.size=s-r*t})}}_isTallSymbol(e){let t=!1,s=!1;if(e)for(let i=0;i<e.length&&(!t||!s);i++){const l=e[i];"size"===l.type&&("height"===l.axis&&(t=!0),"width-and-depth"===l.axis&&(s=!0))}return t&&s}async _generatePreviewsForLegendElements(e,t,s){const i=[];for(const l of e)for(const e of l.infos??[])if("infos"in e&&e.infos&&i.push(this._generatePreviewsForLegendElements([e],t,s)),Qe(e)&&e.symbol&&!e.preview){let r=!0;if("cim"===e.symbol.type){const{minScale:t,maxScale:s}=e.symbol.data;(t&&t<this.scale||s&&s>this.scale)&&(r=!1)}r&&i.push(this._generateSymbolPreviewForInfo(e,{...t,clipBloomEffect:"theme"in l&&"spike"===l.theme,effectView:s?.arrowMarkerSymbols?.has(e.symbol)?null:t.effectView},s?{isDefault:e.symbol===s.defaultSymbol,applyScaleDrivenSize:!s.arrowMarkerSymbols?.has(e.symbol)}:void 0))}await Promise.all(i)}async _generateSymbolPreviewForInfo(e,t,s){try{let i=!s?.isDefault&&null==e.size&&this._hasSizeRamp?f(22):e.size;if(this._scaleDrivenSizeVariable&&s?.applyScaleDrivenSize){const{getSize:t}=await import("../../../renderers/visualVariables/support/visualVariableUtils.js");i=t(this._scaleDrivenSizeVariable,null,{view:this.view.type,scale:this.scale,shape:"simple-marker"===e.symbol.type?e.symbol.style:null})}const l="cim"===e.symbol.type?{style:"legend",cimOptions:{allowScalingUp:!s?.isDefault&&this._hasSizeRamp||!(!this._scaleDrivenSizeVariable||!s?.applyScaleDrivenSize),viewParams:this.isScaleDriven?{viewingMode:"2d"===this.view?.type?"map":this.view?.viewingMode,scale:this.view?.scale}:null}}:{},r=e.label&&"string"!=typeof e.label?null:await Ze("previewTemplateAriaLabel",e.label);e.preview=await U(e.symbol,{size:i,scale:!1,ariaLabel:r,...t,...l})}catch{e.preview=null,o.getLogger(this).warn(`Generating symbol preview failed for symbol type: ${e.symbol?.type}`)}}_getClusterRenderer(e){this._hasClusterSizeVariable=!1;const t="renderer"in this.layer?this.layer.renderer:null,s=e.renderer?.clone()||t?.clone(),i=N(e,this.layerView,this.view);if(i&&null!=s&&"visualVariables"in s){const t=s.visualVariables?.some(e=>"size"===e.type&&"outline"!==e.target&&!me.test(e.valueExpression));if(!t){if("clusterMinSize"in e&&"clusterMaxSize"in e){const{clusterMinSize:t,clusterMaxSize:s}=e;i.legendOptions=new x({showLegend:t!==s})}const t=s.visualVariables||[];s.visualVariables=t.concat([i]),this._hasClusterSizeVariable=!0}}return s}async _loadRenderer(e){const t=[],s=e.clone(),i=await ie(s);if(Ee(s)||Ce(s)){const e=(s.classBreakInfos||s.uniqueValueInfos).map(e=>this._fetchSymbol(e.symbol,i).then(t=>{e.symbol=t}).catch(()=>{e.symbol=null}));Array.prototype.push.apply(t,e)}return t.push(this._fetchSymbol(s.symbol||s.defaultSymbol,s.defaultSymbol?null:i).then(e=>{this._applySymbolToRenderer(s,e,Le(s))}).catch(()=>{this._applySymbolToRenderer(s,null,Le(s))})),await Promise.allSettled(t),s}_applySymbolToRenderer(e,t,s){s?e.symbol=t:e.defaultSymbol=t}async _fetchSymbol(e,t){if(!e)throw new Error;if("web-style"===e.type){const s=this._webStyleSymbolCache;try{const i=await e.fetchSymbol({cache:s});return this._getAppliedCloneSymbol(i,t)}catch{throw o.getLogger(this).warn("Fetching web-style failed!"),new Error}}return this._getAppliedCloneSymbol(e,t)}_getAppliedCloneSymbol(e,s){if(!e||!s)return e;const i=e.clone(),l=s&&s.toRgba();return i.type.includes("3d")?this._applyColorTo3dSymbol(i,l):"cim"===i.type?O(i,s):i.color&&(i.color=new t(l||i.color)),i}_applyColorTo3dSymbol(e,s){s&&e.symbolLayers.forEach(e=>{e&&(e.material||(e.material={}),e.material.color=new t(s))})}async _getVisualVariableLegendElements(e,t){if(!("visualVariables"in e)||"vector-field"===e.type)return null;const s=e.visualVariables??[],i=[],l=[],n=[],a=te(e,"reference-size")??te(e,"spike");let o;if(2===a?.sizeStops?.length&&(Ee(e)||Ce(e))){const[e,t]=a.sizeStops;o=new D({field:a.field??void 0,normalizationField:a.normalizationField,minSize:u(e.size,10,100),maxSize:u(t.size,50,150),minDataValue:e.value,maxDataValue:t.value}),l.push(o)}for(const r of s)"color"===r.type?i.push(r):"size"===r.type?l.push(r):"opacity"===r.type&&n.push(r);const c=[...i,...l,...n];let d,y;if(0===i.length&&Ee(e)&&e.classBreakInfos&&1===e.classBreakInfos.length){const t=e.classBreakInfos[0];d=t&&t.symbol}if(0===i.length&&Le(e)&&(d=e.symbol),d)if(d.type.includes("3d")){const e=d.symbolLayers.at(0);"water"===e.type?null!=e.color&&(y=e.color):null!=e.material?.color&&(y=e.material.color)}else d.url||(y=d.color);const h=this.effectList;return(await Promise.all(c.map(async s=>{if(!s.legendOptions||!1!==s.legendOptions.showLegend){const i=be(e)?s.field:this._getRampTitle(s,t);let l=null;const r=re(t,s,this.view.timeZone);if("color"===s.type){const e=await W(s,null,r)??[];l={type:"color-ramp",title:i,infos:e,preview:M(e.map(e=>e.color),{effectList:h,ariaLabel:await Ze("previewColorRampAriaLabel")})},this._hasColorRamp||(this._hasColorRamp=e.length>0)}else if("size"===s.type&&"outline"!==s.target)me.test(s.valueExpression)?this._hasClusterSizeVariable||(this._scaleDrivenSizeVariable=s):(l=await this._getSizeLegendElement(i,s,e,r),o===s&&"spike"===a?.theme&&(l.theme=a.theme),this._hasSizeRamp||(this._hasSizeRamp=!(null==l.infos||!l.infos.length)));else if("opacity"===s.type){const e=await W(s,y,r)??[];l={type:"opacity-ramp",title:i,infos:e,preview:M(e.map(e=>e.color),{effectList:h,ariaLabel:await Ze("previewColorRampAriaLabel")})},this._hasOpacityRamp||(this._hasOpacityRamp=e.length>0)}return l?.infos?l:null}}))).filter(r)}_getDomainName(e,t,s){if(e&&"function"!=typeof e){const i="getField"in s&&s.getField?.(e),l=i&&"getFieldDomain"in s&&s.getFieldDomain?s.getFieldDomain(i.name,{excludeImpliedDomains:has("esri-widget-legacy-field-domain-calculation")}):null;return"coded-value"===l?.type?l.getName(t):null}return null}_getClusterTitle(e){const t=this.layer,s=e.field;if("featureReduction"in t&&t.featureReduction&&"cluster"===t.featureReduction.type){const e=t.featureReduction,i="popupTemplate"in e&&e.popupTemplate,l=i&&i.fieldInfos;if(l)for(const t of l)if(t.fieldName===s)return"cluster_count"===s?t.label||{showCount:!0}:t.label}return{showCount:!0}}_getRampTitle(e,t){let s=e.field,i=e.normalizationField,l=!1,r=!1,n=!1,a=null;s="function"==typeof s?null:s,i="function"==typeof i?null:i;const o=e.legendOptions?.title;if(null!=o)a=o;else if(e.valueExpressionTitle)a=e.valueExpressionTitle;else{if("renderer"in t&&t.renderer&&"authoringInfo"in t.renderer&&t.renderer.authoringInfo?.visualVariables){const e=t.renderer.authoringInfo.visualVariables;for(let t=0;t<e.length;t++){const s=e[t];if("color"===s.type){if("ratio"===s.style){l=!0;break}if("percent"===s.style){r=!0;break}if("percent-of-total"===s.style){n=!0;break}}}}a={field:s&&this._getFieldAlias(s,t),normField:i&&this._getFieldAlias(i,t),ratio:l,ratioPercent:r,ratioPercentTotal:n}}return a}_getRendererTitle(e,t){const s=e;if(s.legendOptions?.title)return s.legendOptions.title;if(s.valueExpressionTitle)return s.valueExpressionTitle;let i=s.field,l=null,r=null;if(Ee(s)&&(l=s.normalizationField,r="percent-of-total"===s.normalizationType),i="function"==typeof i?null:i,l="function"==typeof l?null:l,Ce(s)){const{field2:e,field3:l,fieldDelimiter:r}=s;let n=i&&this._getFieldAlias(i,t);return e&&(n=`<${n}>${r}<${this._getFieldAlias(e,t)}>`,l&&(n=`${n}${r}<${this._getFieldAlias(l,t)}>`)),n}let n=null;return(i||l)&&(n={field:i&&this._getFieldAlias(i,t),normField:l&&this._getFieldAlias(l,t),normByPct:r}),n}_getFieldAlias(e,t){const s="popupTemplate"in t?t.popupTemplate:null,i=s?.fieldInfos;let l=i?.find(t=>e===t.fieldName),r=null;"getField"in t&&t.getField?r=t.getField(e):"fieldsIndex"in t&&t.fieldsIndex&&(r=t.fieldsIndex.get(e));let n=null;const a="featureReduction"in t&&t.featureReduction;a&&(l??="popupTemplate"in a?a.popupTemplate?.fieldInfos?.find(t=>e?.toLowerCase()===t.fieldName?.toLowerCase()):void 0,"fields"in a&&a.fields&&(n=a.fields.find(t=>t.name?.toLowerCase()===e?.toLowerCase())));const o=l||r||n;let u=null;return o&&(u=l?.label||r?.alias||n?.alias||"name"in o&&o.name||"fieldName"in o&&o.fieldName||null),u}_isUnclassedRenderer(e){const t=e.visualVariables;let s=!1;return Ee(e)&&e.classBreakInfos&&1===e.classBreakInfos.length&&t&&(s=e.field?t.some(t=>!(!t||e.field!==t.field||(e.normalizationField||t.normalizationField)&&e.normalizationField!==t.normalizationField)):!!t.length),s}};e([b()],et.prototype,"children",void 0),e([b({readOnly:!0})],et.prototype,"effectList",null),e([b()],et.prototype,"layerView",void 0),e([b()],et.prototype,"layer",void 0),e([b()],et.prototype,"legendElements",void 0),e([b({readOnly:!0})],et.prototype,"opacity",null),e([b()],et.prototype,"parent",void 0),e([b({readOnly:!0,dependsOn:[]})],et.prototype,"ready",null),e([b()],et.prototype,"hideLayersNotInCurrentView",void 0),e([b()],et.prototype,"keepCacheOnDestroy",void 0),e([b()],et.prototype,"respectLayerDefinitionExpression",void 0),e([b()],et.prototype,"respectLayerVisibility",void 0),e([b({readOnly:!0})],et.prototype,"scale",null),e([b()],et.prototype,"sublayerIds",void 0),e([b({readOnly:!0})],et.prototype,"isScaleDriven",null),e([b()],et.prototype,"title",void 0),e([b({readOnly:!0,dependsOn:["ready"],value:0})],et.prototype,"version",null),e([b()],et.prototype,"view",void 0),et=e([S("esri.widgets.Legend.support.ActiveLayerInfo")],et);export{et as default};