@arcgis/core 4.25.2 → 4.25.4

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 (44) hide show
  1. package/assets/esri/core/workers/RemoteClient.js +1 -1
  2. package/assets/esri/core/workers/chunks/07605077ef508206668a.js +1 -0
  3. package/assets/esri/core/workers/chunks/{04dbebaeb2d4d778f0e1.js → 5028c10cb621bc1d0412.js} +1 -1
  4. package/assets/esri/core/workers/chunks/50a96ea72049d68bb8d9.js +1 -0
  5. package/assets/esri/core/workers/chunks/7136855af8b8f8595448.js +1 -0
  6. package/assets/esri/core/workers/chunks/{1556e74845e521154fe8.js → 78ed65b7669747a48b28.js} +2 -2
  7. package/assets/esri/core/workers/chunks/{1556e74845e521154fe8.js.LICENSE.txt → 78ed65b7669747a48b28.js.LICENSE.txt} +1 -1
  8. package/assets/esri/core/workers/chunks/8b240e5173bbdee38025.js +1 -0
  9. package/assets/esri/core/workers/chunks/{85f56a2bc01b611533d9.js → 8f86efd4bc2164699a2a.js} +1 -1
  10. package/assets/esri/core/workers/chunks/913ee3922213cdd1fbde.js +1 -0
  11. package/assets/esri/core/workers/chunks/94044fbeea16313ec193.js +1 -0
  12. package/assets/esri/core/workers/chunks/{77cc27d60c79df45dbc2.js → d2e4bdf1567bc27681eb.js} +1 -1
  13. package/assets/esri/core/workers/chunks/e7a2ae5717c1b3b88ca2.js +1 -0
  14. package/assets/esri/core/workers/chunks/fabddb860fa16e2b6d4d.js +1 -0
  15. package/assets/esri/themes/base/widgets/_Sketch.scss +7 -4
  16. package/assets/esri/themes/dark/main.css +1 -1
  17. package/assets/esri/themes/light/main.css +1 -1
  18. package/assets/esri/themes/light/view.css +1 -1
  19. package/config.js +1 -1
  20. package/core/workers/workerFactory.js +1 -1
  21. package/interfaces.d.ts +190 -0
  22. package/layers/CSVLayer.js +1 -1
  23. package/layers/MapNotesLayer.js +1 -1
  24. package/layers/graphics/sources/support/CSVSourceWorker.js +1 -1
  25. package/package.json +2 -2
  26. package/rest/networks/queryAssociations.d.ts +4 -0
  27. package/rest/networks/support/QueryAssociationsParameters.d.ts +4 -0
  28. package/rest/networks/support/QueryAssociationsResult.d.ts +4 -0
  29. package/support/revision.js +1 -1
  30. package/views/2d/layers/FeatureLayerView2D.js +1 -1
  31. package/views/2d/layers/features/sources/SnapshotFeatureSource.js +1 -1
  32. package/views/support/imageReprojection.js +1 -1
  33. package/widgets/Editor/CreateFeaturesWorkflow.js +1 -1
  34. package/widgets/Editor.js +1 -1
  35. package/widgets/Sketch.js +1 -1
  36. package/widgets/TimeSlider/TimeSliderViewModel.js +1 -1
  37. package/assets/esri/core/workers/chunks/2ca1f23cfad22f0999d1.js +0 -1
  38. package/assets/esri/core/workers/chunks/30f0ab816d40fb908d4f.js +0 -1
  39. package/assets/esri/core/workers/chunks/3a0268b5d0bb8ead8622.js +0 -1
  40. package/assets/esri/core/workers/chunks/6ea2f9328cff3d948a13.js +0 -1
  41. package/assets/esri/core/workers/chunks/7b229e36e754923f461b.js +0 -1
  42. package/assets/esri/core/workers/chunks/ae2bec0b83a8c4bc493b.js +0 -1
  43. package/assets/esri/core/workers/chunks/f775b535abf3f2c8ec7e.js +0 -1
  44. package/assets/esri/core/workers/chunks/ffdb5c1133a45787cd63.js +0 -1
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.25/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../AggregateGraphic.js";import"../../../geometry.js";import r from"../../../Graphic.js";import i from"../../../core/Collection.js";import s from"../../../core/Error.js";import has from"../../../core/has.js";import{clone as a}from"../../../core/lang.js";import n from"../../../core/Logger.js";import{applySome as o,isSome as l,unwrap as u,isNone as h}from"../../../core/maybe.js";import{debounce as d,isAbortError as p}from"../../../core/promiseUtils.js";import{watch as c,whenOnce as y,syncAndInitial as g,initial as f}from"../../../core/reactiveUtils.js";import{property as m}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/accessorSupport/ensureType.js";import{subclass as _}from"../../../core/accessorSupport/decorators/subclass.js";import v from"../../../layers/effects/FeatureEffectView.js";import b from"../../../layers/support/FeatureFilter.js";import R from"../../../rest/support/AggregateFeatureSet.js";import S from"../../../rest/support/FeatureSet.js";import w from"../../../rest/support/Query.js";import{MAX_FILTERS as x}from"../engine/webgl/definitions.js";import{LayerView2DMixin as U}from"./LayerView2D.js";import{createSchema as C}from"./features/schemaUtils.js";import{createOrReuseTileRenderer as F}from"./features/tileRenderers.js";import{isRendererSupported as q}from"./features/support/rendererUtils.js";import{findSizeVV as I,createClusterCountSizeVariable as O,injectDynamicLevelDependentSizeVisualVariable as E,isClusterCompatibleRenderer as T,createClusterRenderer as V}from"./support/clusterUtils.js";import j from"./support/FeatureCommandQueue.js";import A from"./support/FeatureLayerProxy.js";import{toJSONGeometryType as Q}from"./support/util.js";import{TileManager as k}from"../tiling/TileManager.js";import L from"../../layers/FeatureLayerView.js";import N from"../../layers/LayerView.js";import z from"../../layers/RefreshableLayerView.js";import{getWebGLCapabilities as P}from"../../webgl/capabilities.js";import H from"../../../geometry/Extent.js";function J(e){return e&&"openPorts"in e}let M=class extends(L(z(U(N)))){constructor(){super(...arguments),this._pipelineIsUpdating=!0,this._commandsQueue=new j({process:e=>{switch(e.type){case"processed-edit":return this._doEdit(e);case"refresh":return this._doRefresh(e.dataChanged);case"update":return this._doUpdate()}}}),this._visibilityOverrides=new Set,this._highlightIds=new Map,this._updateHighlight=d((async()=>this._proxy.setHighlight(Array.from(this._highlightIds.keys())))),this._uploadsLocked=!1,this._needsClusterSizeUpdate=!1,this.featureEffectView=new v,this._lastDefinitionExpression=null}destroy(){o(this._updateClusterSizeTask,(e=>e.remove())),this._proxy?.destroy(),this._commandsQueue.destroy()}initialize(){this.addResolvingPromise(Promise.all([this._initProxy(),this._initServiceOptions()])),this.handles.add([this.on("valueRangesChanged",(e=>{this._set("_aggregateValueRanges",e.valueRanges)})),c((()=>this.featureEffect),(e=>{this.featureEffectView.featureEffect=e}),g)]),this.featureEffectView.endTransitions()}async _initProxy(){const e=this.layer;if("isTable"in e&&e.isTable)throw new s("featurelayerview:table-not-supported","table feature layer can't be displayed",{layer:this.layer});const t="feature"===e.type||"subtype-group"===e.type,r="capabilities"in e&&e.capabilities.operations.supportsQuery;if(t&&!r)throw new s("featurelayerview:query-not-supported","layer view requires a layer with query capability",{layer:e});this._proxy&&this._proxy.destroy();const i=this._createClientOptions();return this._set("_proxy",new A({client:i})),this._proxy.when()}async _initServiceOptions(){return this._set("_serviceOptions",await this._createServiceOptions()),this._serviceOptions}get orderByFields(){return"stream"!==this._serviceOptions.type&&this._serviceOptions.orderByFields}get labelsVisible(){const e="subtype-group"===this.layer.type?this.layer.sublayers.items:[this.layer];return!this.suspended&&e.some((e=>e.labelingInfo&&e.labelsVisible))}get queryMode(){return this._serviceOptions.type}get renderingConfigHash(){if(!this.layer)return null;const e=this.availableFields,t=this.layer,r=this.view.floors,{definitionExpression:i}=t,s="subtype-group"!==this.layer.type&&this.layer.labelsVisible&&this.layer.labelingInfo,a="renderer"in t&&t.renderer,n="gdbVersion"in t?t.gdbVersion:void 0,o="historicMoment"in t?t.historicMoment?.getTime():void 0,{timeExtent:u}=this,h="customParameters"in t?JSON.stringify(t.customParameters):void 0,d="apiKey"in t?t.apiKey:void 0,p="stream"===t.type?`${JSON.stringify(t.geometryDefinition)}${t.definitionExpression}`:null,c=JSON.stringify(this.clips),y="featureReduction"in t?t.featureReduction?.toJSON():null,g="orderBy"in this.layer&&JSON.stringify(this.layer.orderBy),f="sublayers"in this.layer&&this.layer.sublayers.items.reduce(((e,t)=>e+`${t.visible?1:0}.${JSON.stringify(t.renderer)}.${t.labelsVisible}\n.${JSON.stringify(t.labelingInfo)}`),""),m="subtypeCode"in this.layer&&this.layer.subtypeCode;return JSON.stringify({orderBy:g,sublayerHash:f,subtypeCode:m,filterHash:l(this.filter)&&this.filter.toJSON(),effectHash:l(this.featureEffect)&&this.featureEffect.toJSON(),streamFilter:p,gdbVersion:n,definitionExpression:i,historicMoment:o,availableFields:e,renderer:a,labelingInfo:s,timeExtent:u,floors:r,clipsHash:c,featureReduction:y,customParameters:h,apiKey:d})}highlight(e){let t;return e instanceof r?t=[e.getObjectId()]:"number"==typeof e||"string"==typeof e?t=[e]:i.isCollection(e)&&e.length>0?t=e.map((e=>e?.getObjectId())).toArray():Array.isArray(e)&&e.length>0&&(t="number"==typeof e[0]||"string"==typeof e[0]?e:e.map((e=>e?.getObjectId()))),t=t?.filter((e=>null!=e)),t&&t.length?(this._addHighlight(t),{remove:()=>this._removeHighlight(t)}):{remove:()=>{}}}hasHighlight(){return!!this._highlightIds.size}async hitTest(e,i){if(!this.tileRenderer)return null;const s=await this.tileRenderer.hitTest(i);if(0===s.length)return null;const{features:a,aggregates:n}=await this._proxy.getFeatures(s);return[...n.map((r=>this._createGraphicHit(e,t.fromJSON(r)))),...a.map((t=>this._createGraphicHit(e,r.fromJSON(t))))]}queryStatistics(){return this._proxy.queryStatistics()}async querySummaryStatistics(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.querySummaryStatistics(this._cleanUpQuery(e),i,r)}async queryAggregateSummaryStatistics(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryAggregateSummaryStatistics(this._cleanUpAggregateQuery(e),i,r)}async queryUniqueValues(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryUniqueValues(this._cleanUpQuery(e),i,r)}async queryAggregateUniqueValues(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryAggregateUniqueValues(this._cleanUpAggregateQuery(e),i,r)}async queryClassBreaks(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryClassBreaks(this._cleanUpQuery(e),i,r)}async queryAggregateClassBreaks(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryAggregateClassBreaks(this._cleanUpAggregateQuery(e),i,r)}async queryHistogram(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryHistogram(this._cleanUpQuery(e),i,r)}async queryAggregateHistogram(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryAggregateHistogram(this._cleanUpAggregateQuery(e),i,r)}queryFeatures(e,t){return this.queryFeaturesJSON(e,t).then((e=>{const t=S.fromJSON(e);return t.features.forEach((e=>this._setLayersForFeature(e))),t}))}queryVisibleFeatures(e,t){return this._proxy.queryVisibleFeatures(this._cleanUpQuery(e),t).then((e=>{const t=S.fromJSON(e);return t.features.forEach((e=>this._setLayersForFeature(e))),t}))}async queryAggregates(e,t){const r=await this._proxy.queryAggregates(this._cleanUpAggregateQuery(e),t),i=R.fromJSON(r);return i.features.forEach((e=>this._setLayersForFeature(e))),i}queryAggregateIds(e,t){return this._proxy.queryAggregateIds(this._cleanUpAggregateQuery(e),t)}queryAggregateCount(e,t){return this._proxy.queryAggregateCount(this._cleanUpAggregateQuery(e),t)}queryAggregateJSON(e,t){return this._proxy.queryAggregates(this._cleanUpAggregateQuery(e),t)}queryFeaturesJSON(e,t){return this._proxy.queryFeatures(this._cleanUpQuery(e),t)}queryObjectIds(e,t){return this._proxy.queryObjectIds(this._cleanUpQuery(e),t)}queryFeatureCount(e,t){return this._proxy.queryFeatureCount(this._cleanUpQuery(e),t)}queryExtent(e,t){return this._proxy.queryExtent(this._cleanUpQuery(e),t).then((e=>({count:e.count,extent:H.fromJSON(e.extent)})))}setVisibility(e,t){t?this._visibilityOverrides.delete(e):this._visibilityOverrides.add(e),this._update()}update(e){if(!this._tileStrategy||!this.tileRenderer)return;const{hasMissingTiles:t,added:r,removed:i}=this._tileStrategy.update(e);(r.length||i.length)&&this._proxy.updateTiles({added:r,removed:i}),t&&this.requestUpdate(),this.notifyChange("updating")}attach(){this.view.timeline.record(`${this.layer.title} (FeatureLayer) Attach`),this._tileStrategy=new k({acquireTile:e=>this._acquireTile(e),releaseTile:e=>this._releaseTile(e),tileInfoView:this.view.featuresTilingScheme,buffer:0}),this.handles.add(c((()=>this.renderingConfigHash),(()=>this._update()),f),"attach"),"stream"!==this.layer.type&&this.handles.add(this.layer.on("edits",(e=>this._edit(e))),"attach")}detach(){this._commandsQueue.clear(),this._proxy?.stop(),this.container.removeAllChildren(),this.handles.remove("attach"),this.tileRenderer&&(this.tileRenderer.uninstall(this.container),this.tileRenderer=null),this._tileStrategy&&(this._tileStrategy.destroy(),this._tileStrategy=null),this._tileRendererHash=null}moveStart(){this.requestUpdate()}viewChange(){this.requestUpdate()}moveEnd(){this.requestUpdate()}isUpdating(){const e="renderer"in this.layer&&null!=this.layer.renderer,t=this._commandsQueue.updating,r=null!=this._updatingRequiredFieldsPromise,i=!this._proxy||!this._proxy.isReady,s=this._pipelineIsUpdating,a=null==this.tileRenderer||this.tileRenderer?.updating,n=e&&(t||r||i||s||a);return has("esri-2d-log-updating")&&console.log(`Updating FLV2D: ${n}\n -> hasRenderer ${e}\n -> hasPendingCommand ${t}\n -> updatingRequiredFields ${r}\n -> updatingProxy ${i}\n -> updatingPipeline ${s}\n -> updatingTileRenderer ${a}\n`),n}_createClientOptions(){return{setUpdating:e=>{this._set("_pipelineIsUpdating",e)},emitEvent:e=>{this.emit(e.name,e.event)}}}async _detectQueryMode(e){const t="path"in e,r="editingInfo"in this.layer&&this.layer.editingInfo?.lastEditDate,i=!!this.layer.refreshInterval,s=!r&&i;if(t&&("feature"===this.layer.type||"subtype-group"===this.layer.type)&&"point"===this.layer.geometryType&&this.layer.capabilities.query.supportsPagination&&!this.layer.capabilities.operations.supportsEditing&&!s&&has("featurelayer-snapshot-enabled"))try{const e=await this.layer.queryFeatureCount();if(e<=has("featurelayer-snapshot-point-min-threshold"))return{mode:"snapshot",featureCount:e};const t=has("featurelayer-snapshot-point-max-threshold"),r=has("featurelayer-snapshot-point-coverage"),i=this.view.extent,s=u(this.layer.fullExtent),a=s?.clone().intersection(i),n=l(a)?a.width*a.height:0,o=s?.width*s?.height,h=0===o?0:n/o;if(e<=t&&h>=r)return{mode:"snapshot",featureCount:e}}catch(a){n.getLogger(this.declaredClass).warn("mapview-feature-layer","Encountered an error when querying for featureCount",{error:a})}return{mode:"on-demand"}}async _createServiceOptions(){const e=this.layer;if("stream"===e.type)return null;const{capabilities:t,objectIdField:r}=e,i=e.fields.map((e=>e.toJSON())),s=l(e.fullExtent)&&e.fullExtent.toJSON(),n=Q(e.geometryType),o=e.timeInfo&&e.timeInfo.toJSON()||null,u=e.spatialReference?e.spatialReference.toJSON():null,h="feature"===e.type?e.globalIdField:null;let d;"ogc-feature"===e.type?d=e.source.getSource():J(e.source)?d=await e.source.openPorts():e.parsedUrl&&(d=a(e.parsedUrl),"dynamicDataSource"in e&&e.dynamicDataSource&&(d.query={layer:JSON.stringify({source:e.dynamicDataSource})}));const p="datesInUnknownTimezone"in this.layer&&this.layer.datesInUnknownTimezone,c=("subtypeField"in this.layer&&this.layer.subtypeField)??null,{mode:y,featureCount:g}=await this._detectQueryMode(d);let f=this.layer.objectIdField;if("feature"===this.layer.type&&l(this.layer.orderBy)&&this.layer.orderBy.length){const e=!this.layer.orderBy[0].valueExpression&&this.layer.orderBy[0].field;e&&(f=e)}return{type:y,timeReferenceUnknownClient:p,subtypeField:c,featureCount:g,globalIdField:h,maxRecordCount:t.query.maxRecordCount,tileMaxRecordCount:t.query.tileMaxRecordCount,capabilities:t,fields:i,fullExtent:s,geometryType:n,objectIdField:r,source:d,timeInfo:o,spatialReference:u,orderByFields:f}}async _createMemoryServiceOptions(e){const t=await e.openPorts();return{...this._createServiceOptions(),type:"memory",source:t}}_cleanUpQuery(e){const t=w.from(e)||this.createQuery();return t.outSpatialReference||(t.outSpatialReference=this.view.spatialReference),t}_cleanUpAggregateQuery(e){const t=w.from(e)||this.createAggregateQuery();return t.outSpatialReference||(t.outSpatialReference=this.view.spatialReference),t}async _update(){return this._commandsQueue.push({type:"update"})}async _edit(e){if(this.suspended)return void this._clearTiles();return this._validateEdit(e)?this._commandsQueue.push({type:"edit",edits:e}):void 0}async doRefresh(e){if(this.attached&&this._tileStrategy.tileKeys().length)return this.suspended&&e?void this._clearTiles():this._commandsQueue.push({type:"refresh",dataChanged:e})}_clearTiles(){this._tileStrategy.tileKeys().length&&(this._proxy.updateTiles({added:[],removed:this._tileStrategy.tileKeys()}),this._tileStrategy.clear(),this.requestUpdate(),this._commandsQueue.clear(),this._update())}_validateEdit(e){const t="globalIdField"in this.layer&&this.layer.globalIdField,r=e.deletedFeatures.some((e=>-1===e.objectId||!e.objectId)),i=t&&this.availableFields.includes(t);return r&&!i?(n.getLogger(this.declaredClass).error(new s("mapview-apply-edits",`Editing the specified service requires the layer's globalIdField, ${t} to be included the layer's outFields for updates to be reflected on the map`)),null):e}async _doUpdate(){try{if(this.destroyed||!this._hasRequiredSupport(this.layer)||!this._tileStrategy)return;const{featureEffectView:t,filter:r}=this;await this._updateRequiredFields();const{renderer:i}=this._getEffectiveRenderer();this._set("_effectiveRenderer",i);const s=this._createSchemaConfig(),a=this._createConfiguration(s,r,t.filter),o=this._lastDefinitionExpression!==a.schema.source.definitionExpression;this._lastDefinitionExpression=a.schema.source.definitionExpression;const l=a.schema.tileRenderer,u=this._createTileRendererHash(l);if("snapshot"===this._serviceOptions.type&&(a.schema.source.initialFeatureCount=this._serviceOptions.featureCount),u!==this._tileRendererHash){await this._initTileRenderer(l,i);const e=this.layer,t="stream"===e.type?await this._initServiceOptions():this._serviceOptions;this.tileRenderer.onConfigUpdate(i),"stream"!==e.type&&J(e.source)&&(t.source=await e.source.openPorts());const r={added:this._tileStrategy.tileKeys(),removed:[]};await this._proxy.startup(this.view.featuresTilingScheme,a,t,r),this.hasHighlight()&&await this._proxy.setHighlight(Array.from(this._highlightIds.keys())),await this._onceTilesUpdated(),this.tileRenderer.onConfigUpdate(i)}else{"snapshot"===this._serviceOptions.type&&o&&(a.schema.source.initialFeatureCount=await this.layer.queryFeatureCount());const t=await this._proxy.update(a);(t.mesh||t.targets.aggregate)&&this._lockGPUUploads();try{await this._proxy.applyUpdate(t)}catch(e){p(e)||n.getLogger(this.declaredClass).error(e)}(t.mesh||t.targets.aggregate)&&this._unlockGPUUploads(),this.tileRenderer.onConfigUpdate(i),this._updateClusterSizeVariable(),this._forceAttributeTextureUpload()}this._tileRendererHash=u,this.tileRenderer.invalidateLabels(),this.requestUpdate()}catch(e){}}async _doEdit(e){try{await this._proxy.onEdits(e)}catch(t){p(t),0}}async _doRefresh(e){this._lockGPUUploads();try{let t;e&&"snapshot"===this.queryMode&&"queryFeatureCount"in this.layer&&(t=await this.layer.queryFeatureCount()),await this._proxy.refresh({dataChanged:e,featureCount:t})}catch(r){p(r),0}this._unlockGPUUploads();const t=this.layer;t&&"featureReduction"in t&&t.featureReduction&&this._updateClusterSizeVariable()}_updateClusterSizeVariable(){this._needsClusterSizeUpdate&&(this.tileRenderer.onConfigUpdate(this._effectiveRenderer),this._needsClusterSizeUpdate=!1)}_createUpdateClusterSizeTask(e,t){return c((()=>this._aggregateValueRanges),(r=>{this._updateClusterEffectiveRendererSizeVariable(e,t,r),this._needsClusterSizeUpdate=!0,this._uploadsLocked||this._updateClusterSizeVariable()}))}async _updateClusterEffectiveRendererSizeVariable(e,t,r){if(e.dynamicClusterSize&&"visualVariables"in e&&e.visualVariables){const i=I(e.visualVariables);if(l(i)&&"cluster_count"===i.field){const s=e.visualVariables.indexOf(i);e.visualVariables[s]=O(t,r);const a=e.clone();a.dynamicClusterSize=!0,this._set("_effectiveRenderer",a)}}}_getEffectiveRenderer(){const e=this.layer,t="renderer"in e?e.renderer:null,r="featureReduction"in e?e.featureReduction:null;if(l(this._updateClusterSizeTask)&&(this._updateClusterSizeTask.remove(),this._updateClusterSizeTask=null),r&&"renderer"in r&&r.renderer&&!r.renderer.authoringInfo?.isAutoGenerated){const e=r.fields;if("cluster"===r.type){const{renderer:t,didInject:i}=E(r.renderer,r,this._aggregateValueRanges);return i&&(o(this._updateClusterSizeTask,(e=>e.remove())),this._updateClusterSizeTask=this._createUpdateClusterSizeTask(t,r)),{renderer:t,aggregateFields:e,featureReduction:r}}return{renderer:r.renderer,aggregateFields:e,featureReduction:r}}if(r&&"cluster"===r.type&&T(t)){const e=r,i=[],s=V(i,t,e,this._aggregateValueRanges,!0);return o(this._updateClusterSizeTask,(e=>e.remove())),this._updateClusterSizeTask=this._createUpdateClusterSizeTask(s,e),{renderer:s,aggregateFields:i,featureReduction:r}}return{renderer:t,aggregateFields:[],featureReduction:null}}_acquireTile(e){const t=this.tileRenderer.acquireTile(e);return t.once("attach",(()=>{this.requestUpdate()})),t}_releaseTile(e){this.tileRenderer.releaseTile(e)}async _initTileRenderer(e,t){const r=await F(e,{layerView:this,tileInfoView:this.view.featuresTilingScheme,layer:this.layer});return this.tileRenderer&&(this._tileStrategy.clear(),this.tileRenderer.uninstall(this.container),this.tileRenderer.destroy(),this.tileRenderer=null),this.destroyed?null:(this._proxy.tileRenderer=r,this._set("tileRenderer",r),this.tileRenderer.install(this.container),this.tileRenderer.onConfigUpdate(t),this.requestUpdate(),this.tileRenderer)}_createTileRendererHash(e){return`${e.type}`}get hasFilter(){const e=!!("floorInfo"in this.layer&&this.layer.floorInfo&&this.view.floors&&this.view.floors.length);return!!this.filter||e||!!this._visibilityOverrides.size||!!this.timeExtent}_injectOverrides(e){const t=l(e)?e.timeExtent:null,r=l(this.timeExtent)&&l(t)?this.timeExtent.intersection(t):this.timeExtent||t;let i=null;const s="floorInfo"in this.layer&&this.layer.floorInfo;if(s){const t=l(e)&&e.where;i=this._addFloorFilterClause(t)}if(!this._visibilityOverrides.size&&!r&&!s)return l(e)?e.toJSON():null;(e=l(e)&&e.clone()||new b).timeExtent=r,i&&(e.where=i);const a=e.toJSON();return a.hiddenIds=Array.from(this._visibilityOverrides),a}_addFloorFilterClause(e){const t=this.layer;let r=e||"";if("floorInfo"in t&&t.floorInfo){let e=this.view.floors;if(!e||!e.length)return r;t.floorInfo.viewAllLevelIds?.length&&(e=t.floorInfo.viewAllLevelIds);const i=e.filter((e=>""!==e)).map((e=>"'"+e+"'"));i.push("''");const s=t.floorInfo.floorField;let a="("+s+" IN ({ids}) OR "+s+" IS NULL)";if(a=a.replace("{ids}",i.join(", ")),l(r)&&r.includes(s)){let e=new RegExp("AND \\("+s+".*NULL\\)","g");r=r.replace(e,""),e=new RegExp("\\("+s+".*NULL\\)","g"),r=r.replace(e,""),r=r.replace(/\s+/g," ").trim()}r=""!==r?"("+r+") AND "+a:a}return""!==r?r:null}_createConfiguration(e,t,r){const i="feature"===this.layer.type&&this.layer.historicMoment?this.layer.historicMoment.getTime():void 0,s="feature"===this.layer.type?this.layer.gdbVersion:void 0,a=new Array(x),n=this._injectOverrides(t);a[0]=n,a[1]=l(r)?r.toJSON():null;const o=C(e);if(h(o))return null;const u=P("2d");return{availableFields:this.availableFields,gdbVersion:s,historicMoment:i,devicePixelRatio:window.devicePixelRatio||1,filters:a,schema:o,supportsTextureFloat:u.supportsTextureFloat,maxTextureSize:u.maxTextureSize}}_hasRequiredSupport(e){return!("renderer"in e)||q(e.renderer)}_onceTilesUpdated(){return this.requestUpdate(),y((()=>!this._pipelineIsUpdating))}_lockGPUUploads(){this.tileRenderer&&(this._uploadsLocked=!0,this.tileRenderer.lockGPUUploads())}_unlockGPUUploads(){this.tileRenderer&&(this._uploadsLocked=!1,this.tileRenderer.unlockGPUUploads())}_forceAttributeTextureUpload(){this.tileRenderer&&this.tileRenderer.forceAttributeTextureUpload()}_createSchemaConfig(){const e=this.layer;return{renderer:"renderer"in e?e.renderer:null,spatialReference:e.spatialReference,timeExtent:e.timeExtent,definitionExpression:e.definitionExpression,featureReduction:"featureReduction"in e?e.featureReduction:null,fields:e.fields,geometryType:e.geometryType,historicMoment:"historicMoment"in e?e.historicMoment:null,labelsVisible:"labelsVisible"in e&&e.labelsVisible,labelingInfo:"labelingInfo"in e&&e.labelingInfo,availableFields:this.availableFields,featureEffect:this.featureEffect,filter:this.filter,gdbVersion:"gdbVersion"in e?e.gdbVersion:null,pixelBuffer:0,orderBy:"orderBy"in e&&e.orderBy?e.orderBy:null,customParameters:{..."customParameters"in e?e.customParameters:void 0,token:"apiKey"in e?e.apiKey:void 0},subtypeCode:"subtypeCode"in e?e.subtypeCode:void 0,subtypeField:"subtypeField"in e?e.subtypeField:void 0}}_addHighlight(e){for(const t of e)if(this._highlightIds.has(t)){const e=this._highlightIds.get(t);this._highlightIds.set(t,e+1)}else this._highlightIds.set(t,1);this._updateHighlight().catch((e=>{p(e)||n.getLogger(this.declaredClass).error(e)}))}_removeHighlight(e){for(const t of e)if(this._highlightIds.has(t)){const e=this._highlightIds.get(t)-1;0===e?this._highlightIds.delete(t):this._highlightIds.set(t,e)}this._updateHighlight().catch((e=>{p(e)||n.getLogger(this.declaredClass).error(e)}))}_setLayersForFeature(e){const t=this.layer;e.layer=t,e.sourceLayer=t}_createGraphicHit(e,t){return this._setLayersForFeature(t),l(t.geometry)&&(t.geometry.spatialReference=this.view.spatialReference),{type:"graphic",graphic:t,layer:this.layer,mapPoint:e}}};e([m()],M.prototype,"_serviceOptions",void 0),e([m()],M.prototype,"_proxy",void 0),e([m()],M.prototype,"_pipelineIsUpdating",void 0),e([m()],M.prototype,"_effectiveRenderer",void 0),e([m()],M.prototype,"_aggregateValueRanges",void 0),e([m()],M.prototype,"_commandsQueue",void 0),e([m()],M.prototype,"featureEffectView",void 0),e([m()],M.prototype,"labelsVisible",null),e([m({readOnly:!0})],M.prototype,"queryMode",null),e([m()],M.prototype,"renderingConfigHash",null),e([m()],M.prototype,"tileRenderer",void 0),e([m()],M.prototype,"updating",void 0),M=e([_("esri.views.2d.layers.FeatureLayerView2D")],M);const B=M;export{B as default};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../AggregateGraphic.js";import"../../../geometry.js";import r from"../../../Graphic.js";import i from"../../../core/Collection.js";import s from"../../../core/Error.js";import has from"../../../core/has.js";import{clone as a}from"../../../core/lang.js";import n from"../../../core/Logger.js";import{applySome as o,isSome as l,unwrap as u,isNone as h}from"../../../core/maybe.js";import{debounce as d,isAbortError as p}from"../../../core/promiseUtils.js";import{watch as c,whenOnce as y,syncAndInitial as g,initial as f}from"../../../core/reactiveUtils.js";import{property as m}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/accessorSupport/ensureType.js";import{subclass as _}from"../../../core/accessorSupport/decorators/subclass.js";import v from"../../../layers/effects/FeatureEffectView.js";import b from"../../../layers/support/FeatureFilter.js";import R from"../../../rest/support/AggregateFeatureSet.js";import S from"../../../rest/support/FeatureSet.js";import w from"../../../rest/support/Query.js";import{MAX_FILTERS as x}from"../engine/webgl/definitions.js";import{LayerView2DMixin as U}from"./LayerView2D.js";import{createSchema as C}from"./features/schemaUtils.js";import{createOrReuseTileRenderer as F}from"./features/tileRenderers.js";import{isRendererSupported as q}from"./features/support/rendererUtils.js";import{findSizeVV as I,createClusterCountSizeVariable as O,injectDynamicLevelDependentSizeVisualVariable as E,isClusterCompatibleRenderer as T,createClusterRenderer as V}from"./support/clusterUtils.js";import j from"./support/FeatureCommandQueue.js";import A from"./support/FeatureLayerProxy.js";import{toJSONGeometryType as Q}from"./support/util.js";import{TileManager as k}from"../tiling/TileManager.js";import L from"../../layers/FeatureLayerView.js";import N from"../../layers/LayerView.js";import z from"../../layers/RefreshableLayerView.js";import{getWebGLCapabilities as P}from"../../webgl/capabilities.js";import H from"../../../geometry/Extent.js";function J(e){return e&&"openPorts"in e}let M=class extends(L(z(U(N)))){constructor(){super(...arguments),this._pipelineIsUpdating=!0,this._commandsQueue=new j({process:e=>{switch(e.type){case"processed-edit":return this._doEdit(e);case"refresh":return this._doRefresh(e.dataChanged);case"update":return this._doUpdate()}}}),this._visibilityOverrides=new Set,this._highlightIds=new Map,this._updateHighlight=d((async()=>this._proxy.setHighlight(Array.from(this._highlightIds.keys())))),this._uploadsLocked=!1,this._needsClusterSizeUpdate=!1,this.featureEffectView=new v,this._lastDefinitionExpression=null}destroy(){o(this._updateClusterSizeTask,(e=>e.remove())),this._proxy?.destroy(),this._commandsQueue.destroy()}initialize(){this.addResolvingPromise(Promise.all([this._initProxy(),this._initServiceOptions()])),this.handles.add([this.on("valueRangesChanged",(e=>{this._set("_aggregateValueRanges",e.valueRanges)})),c((()=>this.featureEffect),(e=>{this.featureEffectView.featureEffect=e}),g)]),this.featureEffectView.endTransitions()}async _initProxy(){const e=this.layer;if("isTable"in e&&e.isTable)throw new s("featurelayerview:table-not-supported","table feature layer can't be displayed",{layer:this.layer});const t="feature"===e.type||"subtype-group"===e.type,r="capabilities"in e&&e.capabilities.operations.supportsQuery;if(t&&!r)throw new s("featurelayerview:query-not-supported","layer view requires a layer with query capability",{layer:e});this._proxy&&this._proxy.destroy();const i=this._createClientOptions();return this._set("_proxy",new A({client:i})),this._proxy.when()}async _initServiceOptions(){return this._set("_serviceOptions",await this._createServiceOptions()),this._serviceOptions}get orderByFields(){return"stream"!==this._serviceOptions.type&&this._serviceOptions.orderByFields}get labelsVisible(){const e="subtype-group"===this.layer.type?this.layer.sublayers.items:[this.layer];return!this.suspended&&e.some((e=>e.labelingInfo&&e.labelsVisible))}get queryMode(){return this._serviceOptions.type}get renderingConfigHash(){if(!this.layer)return null;const e=this.availableFields,t=this.layer,r=this.view.floors,{definitionExpression:i}=t,s="subtype-group"!==this.layer.type&&this.layer.labelsVisible&&this.layer.labelingInfo,a="renderer"in t&&t.renderer,n="gdbVersion"in t?t.gdbVersion:void 0,o="historicMoment"in t?t.historicMoment?.getTime():void 0,{timeExtent:u}=this,h="customParameters"in t?JSON.stringify(t.customParameters):void 0,d="apiKey"in t?t.apiKey:void 0,p="stream"===t.type?`${JSON.stringify(t.geometryDefinition)}${t.definitionExpression}`:null,c=JSON.stringify(this.clips),y="featureReduction"in t?t.featureReduction?.toJSON():null,g="orderBy"in this.layer&&JSON.stringify(this.layer.orderBy),f="sublayers"in this.layer&&this.layer.sublayers.items.reduce(((e,t)=>e+`${t.visible?1:0}.${JSON.stringify(t.renderer)}.${t.labelsVisible}\n.${JSON.stringify(t.labelingInfo)}`),""),m="subtypeCode"in this.layer&&this.layer.subtypeCode;return JSON.stringify({orderBy:g,sublayerHash:f,subtypeCode:m,filterHash:l(this.filter)&&this.filter.toJSON(),effectHash:l(this.featureEffect)&&this.featureEffect.toJSON(),streamFilter:p,gdbVersion:n,definitionExpression:i,historicMoment:o,availableFields:e,renderer:a,labelingInfo:s,timeExtent:u,floors:r,clipsHash:c,featureReduction:y,customParameters:h,apiKey:d})}highlight(e){let t;return e instanceof r?t=[e.getObjectId()]:"number"==typeof e||"string"==typeof e?t=[e]:i.isCollection(e)&&e.length>0?t=e.map((e=>e?.getObjectId())).toArray():Array.isArray(e)&&e.length>0&&(t="number"==typeof e[0]||"string"==typeof e[0]?e:e.map((e=>e?.getObjectId()))),t=t?.filter((e=>null!=e)),t&&t.length?(this._addHighlight(t),{remove:()=>this._removeHighlight(t)}):{remove:()=>{}}}hasHighlight(){return!!this._highlightIds.size}async hitTest(e,i){if(!this.tileRenderer)return null;const s=await this.tileRenderer.hitTest(i);if(0===s.length)return null;const{features:a,aggregates:n}=await this._proxy.getFeatures(s);return[...n.map((r=>this._createGraphicHit(e,t.fromJSON(r)))),...a.map((t=>this._createGraphicHit(e,r.fromJSON(t))))]}queryStatistics(){return this._proxy.queryStatistics()}async querySummaryStatistics(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.querySummaryStatistics(this._cleanUpQuery(e),i,r)}async queryAggregateSummaryStatistics(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryAggregateSummaryStatistics(this._cleanUpAggregateQuery(e),i,r)}async queryUniqueValues(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryUniqueValues(this._cleanUpQuery(e),i,r)}async queryAggregateUniqueValues(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryAggregateUniqueValues(this._cleanUpAggregateQuery(e),i,r)}async queryClassBreaks(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryClassBreaks(this._cleanUpQuery(e),i,r)}async queryAggregateClassBreaks(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryAggregateClassBreaks(this._cleanUpAggregateQuery(e),i,r)}async queryHistogram(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryHistogram(this._cleanUpQuery(e),i,r)}async queryAggregateHistogram(e,t,r){const i={...t,scale:this.view.scale};return this._proxy.queryAggregateHistogram(this._cleanUpAggregateQuery(e),i,r)}queryFeatures(e,t){return this.queryFeaturesJSON(e,t).then((e=>{const t=S.fromJSON(e);return t.features.forEach((e=>this._setLayersForFeature(e))),t}))}queryVisibleFeatures(e,t){return this._proxy.queryVisibleFeatures(this._cleanUpQuery(e),t).then((e=>{const t=S.fromJSON(e);return t.features.forEach((e=>this._setLayersForFeature(e))),t}))}async queryAggregates(e,t){const r=await this._proxy.queryAggregates(this._cleanUpAggregateQuery(e),t),i=R.fromJSON(r);return i.features.forEach((e=>this._setLayersForFeature(e))),i}queryAggregateIds(e,t){return this._proxy.queryAggregateIds(this._cleanUpAggregateQuery(e),t)}queryAggregateCount(e,t){return this._proxy.queryAggregateCount(this._cleanUpAggregateQuery(e),t)}queryAggregateJSON(e,t){return this._proxy.queryAggregates(this._cleanUpAggregateQuery(e),t)}queryFeaturesJSON(e,t){return this._proxy.queryFeatures(this._cleanUpQuery(e),t)}queryObjectIds(e,t){return this._proxy.queryObjectIds(this._cleanUpQuery(e),t)}queryFeatureCount(e,t){return this._proxy.queryFeatureCount(this._cleanUpQuery(e),t)}queryExtent(e,t){return this._proxy.queryExtent(this._cleanUpQuery(e),t).then((e=>({count:e.count,extent:H.fromJSON(e.extent)})))}setVisibility(e,t){t?this._visibilityOverrides.delete(e):this._visibilityOverrides.add(e),this._update()}update(e){if(!this._tileStrategy||!this.tileRenderer)return;const{hasMissingTiles:t,added:r,removed:i}=this._tileStrategy.update(e);(r.length||i.length)&&this._proxy.updateTiles({added:r,removed:i}),t&&this.requestUpdate(),this.notifyChange("updating")}attach(){this.view.timeline.record(`${this.layer.title} (FeatureLayer) Attach`),this._tileStrategy=new k({acquireTile:e=>this._acquireTile(e),releaseTile:e=>this._releaseTile(e),tileInfoView:this.view.featuresTilingScheme,buffer:0}),this.handles.add(c((()=>this.renderingConfigHash),(()=>this._update()),f),"attach"),"stream"!==this.layer.type&&this.handles.add(this.layer.on("edits",(e=>this._edit(e))),"attach")}detach(){this._commandsQueue.clear(),this._proxy?.stop(),this.container.removeAllChildren(),this.handles.remove("attach"),this.tileRenderer&&(this.tileRenderer.uninstall(this.container),this.tileRenderer=null),this._tileStrategy&&(this._tileStrategy.destroy(),this._tileStrategy=null),this._tileRendererHash=null}moveStart(){this.requestUpdate()}viewChange(){this.requestUpdate()}moveEnd(){this.requestUpdate()}isUpdating(){const e="renderer"in this.layer&&null!=this.layer.renderer,t=this._commandsQueue.updating,r=null!=this._updatingRequiredFieldsPromise,i=!this._proxy||!this._proxy.isReady,s=this._pipelineIsUpdating,a=null==this.tileRenderer||this.tileRenderer?.updating,n=e&&(t||r||i||s||a);return has("esri-2d-log-updating")&&console.log(`Updating FLV2D: ${n}\n -> hasRenderer ${e}\n -> hasPendingCommand ${t}\n -> updatingRequiredFields ${r}\n -> updatingProxy ${i}\n -> updatingPipeline ${s}\n -> updatingTileRenderer ${a}\n`),n}_createClientOptions(){return{setUpdating:e=>{this._set("_pipelineIsUpdating",e)},emitEvent:e=>{this.emit(e.name,e.event)}}}async _detectQueryMode(e){const t="path"in e,r="editingInfo"in this.layer&&this.layer.editingInfo?.lastEditDate,i=!!this.layer.refreshInterval,s=!r&&i;if(t&&("feature"===this.layer.type||"subtype-group"===this.layer.type)&&"point"===this.layer.geometryType&&this.layer.capabilities.query.supportsPagination&&!this.layer.capabilities.operations.supportsEditing&&!s&&has("featurelayer-snapshot-enabled"))try{const e=await this.layer.queryFeatureCount();if(e<=has("featurelayer-snapshot-point-min-threshold"))return{mode:"snapshot",featureCount:e};const t=has("featurelayer-snapshot-point-max-threshold"),r=has("featurelayer-snapshot-point-coverage"),i=this.view.extent,s=u(this.layer.fullExtent),a=s?.clone().intersection(i),n=l(a)?a.width*a.height:0,o=s?.width*s?.height,h=0===o?0:n/o;if(e<=t&&h>=r)return{mode:"snapshot",featureCount:e}}catch(a){n.getLogger(this.declaredClass).warn("mapview-feature-layer","Encountered an error when querying for featureCount",{error:a})}return{mode:"on-demand"}}async _createServiceOptions(){const e=this.layer;if("stream"===e.type)return null;const{capabilities:t,objectIdField:r}=e,i=e.fields.map((e=>e.toJSON())),s=l(e.fullExtent)&&e.fullExtent.toJSON(),n=Q(e.geometryType),o=e.timeInfo&&e.timeInfo.toJSON()||null,u=e.spatialReference?e.spatialReference.toJSON():null,h="feature"===e.type?e.globalIdField:null;let d;"ogc-feature"===e.type?d=e.source.getSource():J(e.source)?d=await e.source.openPorts():e.parsedUrl&&(d=a(e.parsedUrl),"dynamicDataSource"in e&&e.dynamicDataSource&&(d.query={layer:JSON.stringify({source:e.dynamicDataSource})}));const p="datesInUnknownTimezone"in this.layer&&this.layer.datesInUnknownTimezone,c=("subtypeField"in this.layer&&this.layer.subtypeField)??null,{mode:y,featureCount:g}=await this._detectQueryMode(d);let f=this.layer.objectIdField;if("feature"===this.layer.type&&l(this.layer.orderBy)&&this.layer.orderBy.length){const e=!this.layer.orderBy[0].valueExpression&&this.layer.orderBy[0].field;e&&(f=e)}return{type:y,timeReferenceUnknownClient:p,subtypeField:c,featureCount:g,globalIdField:h,maxRecordCount:t.query.maxRecordCount,tileMaxRecordCount:t.query.tileMaxRecordCount,capabilities:t,fields:i,fullExtent:s,geometryType:n,objectIdField:r,source:d,timeInfo:o,spatialReference:u,orderByFields:f}}async _createMemoryServiceOptions(e){const t=await e.openPorts();return{...this._createServiceOptions(),type:"memory",source:t}}_cleanUpQuery(e){const t=w.from(e)||this.createQuery();return t.outSpatialReference||(t.outSpatialReference=this.view.spatialReference),t}_cleanUpAggregateQuery(e){const t=w.from(e)||this.createAggregateQuery();return t.outSpatialReference||(t.outSpatialReference=this.view.spatialReference),t}async _update(){return this._commandsQueue.push({type:"update"})}async _edit(e){if(this.suspended)return void this._clearTiles();return this._validateEdit(e)?this._commandsQueue.push({type:"edit",edits:e}):void 0}async doRefresh(e){if(this.attached&&this._tileStrategy.tileKeys().length)return this.suspended&&e?void this._clearTiles():this._commandsQueue.push({type:"refresh",dataChanged:e})}_clearTiles(){this._tileStrategy.tileKeys().length&&(this._proxy.updateTiles({added:[],removed:this._tileStrategy.tileKeys()}),this._tileStrategy.clear(),this.requestUpdate(),this._commandsQueue.clear(),this._update())}_validateEdit(e){const t="globalIdField"in this.layer&&this.layer.globalIdField,r=e.deletedFeatures.some((e=>-1===e.objectId||!e.objectId)),i=t&&this.availableFields.includes(t);return r&&!i?(n.getLogger(this.declaredClass).error(new s("mapview-apply-edits",`Editing the specified service requires the layer's globalIdField, ${t} to be included the layer's outFields for updates to be reflected on the map`)),null):e}async _doUpdate(){try{if(this.destroyed||!this._hasRequiredSupport(this.layer)||!this._tileStrategy)return;const{featureEffectView:t,filter:r}=this;await this._updateRequiredFields();const{renderer:i}=this._getEffectiveRenderer();this._set("_effectiveRenderer",i);const s=this._createSchemaConfig(),a=this._createConfiguration(s,r,t.filter),o=this._lastDefinitionExpression!==a.schema.source.definitionExpression;this._lastDefinitionExpression=a.schema.source.definitionExpression;const l=a.schema.tileRenderer,u=this._createTileRendererHash(l);if("snapshot"===this._serviceOptions.type&&(a.schema.source.initialFeatureCount=this._serviceOptions.featureCount),u!==this._tileRendererHash){await this._initTileRenderer(l,i);const e=this.layer,t="stream"===e.type?await this._initServiceOptions():this._serviceOptions;this.tileRenderer.onConfigUpdate(i),"stream"!==e.type&&J(e.source)&&(t.source=await e.source.openPorts());const r={added:this._tileStrategy.tileKeys(),removed:[]};await this._proxy.startup(this.view.featuresTilingScheme,a,t,r),this.hasHighlight()&&await this._proxy.setHighlight(Array.from(this._highlightIds.keys())),await this._onceTilesUpdated(),this.tileRenderer.onConfigUpdate(i)}else{"snapshot"===this._serviceOptions.type&&o&&(a.schema.source.changedFeatureCount=await this.layer.queryFeatureCount());const t=await this._proxy.update(a);(t.mesh||t.targets.aggregate)&&this._lockGPUUploads();try{await this._proxy.applyUpdate(t)}catch(e){p(e)||n.getLogger(this.declaredClass).error(e)}(t.mesh||t.targets.aggregate)&&this._unlockGPUUploads(),this.tileRenderer.onConfigUpdate(i),this._updateClusterSizeVariable(),this._forceAttributeTextureUpload()}this._tileRendererHash=u,this.tileRenderer.invalidateLabels(),this.requestUpdate()}catch(e){}}async _doEdit(e){try{await this._proxy.onEdits(e)}catch(t){p(t),0}}async _doRefresh(e){this._lockGPUUploads();try{let t;e&&"snapshot"===this.queryMode&&"queryFeatureCount"in this.layer&&(t=await this.layer.queryFeatureCount()),await this._proxy.refresh({dataChanged:e,featureCount:t})}catch(r){p(r),0}this._unlockGPUUploads();const t=this.layer;t&&"featureReduction"in t&&t.featureReduction&&this._updateClusterSizeVariable()}_updateClusterSizeVariable(){this._needsClusterSizeUpdate&&(this.tileRenderer.onConfigUpdate(this._effectiveRenderer),this._needsClusterSizeUpdate=!1)}_createUpdateClusterSizeTask(e,t){return c((()=>this._aggregateValueRanges),(r=>{this._updateClusterEffectiveRendererSizeVariable(e,t,r),this._needsClusterSizeUpdate=!0,this._uploadsLocked||this._updateClusterSizeVariable()}))}async _updateClusterEffectiveRendererSizeVariable(e,t,r){if(e.dynamicClusterSize&&"visualVariables"in e&&e.visualVariables){const i=I(e.visualVariables);if(l(i)&&"cluster_count"===i.field){const s=e.visualVariables.indexOf(i);e.visualVariables[s]=O(t,r);const a=e.clone();a.dynamicClusterSize=!0,this._set("_effectiveRenderer",a)}}}_getEffectiveRenderer(){const e=this.layer,t="renderer"in e?e.renderer:null,r="featureReduction"in e?e.featureReduction:null;if(l(this._updateClusterSizeTask)&&(this._updateClusterSizeTask.remove(),this._updateClusterSizeTask=null),r&&"renderer"in r&&r.renderer&&!r.renderer.authoringInfo?.isAutoGenerated){const e=r.fields;if("cluster"===r.type){const{renderer:t,didInject:i}=E(r.renderer,r,this._aggregateValueRanges);return i&&(o(this._updateClusterSizeTask,(e=>e.remove())),this._updateClusterSizeTask=this._createUpdateClusterSizeTask(t,r)),{renderer:t,aggregateFields:e,featureReduction:r}}return{renderer:r.renderer,aggregateFields:e,featureReduction:r}}if(r&&"cluster"===r.type&&T(t)){const e=r,i=[],s=V(i,t,e,this._aggregateValueRanges,!0);return o(this._updateClusterSizeTask,(e=>e.remove())),this._updateClusterSizeTask=this._createUpdateClusterSizeTask(s,e),{renderer:s,aggregateFields:i,featureReduction:r}}return{renderer:t,aggregateFields:[],featureReduction:null}}_acquireTile(e){const t=this.tileRenderer.acquireTile(e);return t.once("attach",(()=>{this.requestUpdate()})),t}_releaseTile(e){this.tileRenderer.releaseTile(e)}async _initTileRenderer(e,t){const r=await F(e,{layerView:this,tileInfoView:this.view.featuresTilingScheme,layer:this.layer});return this.tileRenderer&&(this._tileStrategy.clear(),this.tileRenderer.uninstall(this.container),this.tileRenderer.destroy(),this.tileRenderer=null),this.destroyed?null:(this._proxy.tileRenderer=r,this._set("tileRenderer",r),this.tileRenderer.install(this.container),this.tileRenderer.onConfigUpdate(t),this.requestUpdate(),this.tileRenderer)}_createTileRendererHash(e){return`${e.type}`}get hasFilter(){const e=!!("floorInfo"in this.layer&&this.layer.floorInfo&&this.view.floors&&this.view.floors.length);return!!this.filter||e||!!this._visibilityOverrides.size||!!this.timeExtent}_injectOverrides(e){const t=l(e)?e.timeExtent:null,r=l(this.timeExtent)&&l(t)?this.timeExtent.intersection(t):this.timeExtent||t;let i=null;const s="floorInfo"in this.layer&&this.layer.floorInfo;if(s){const t=l(e)&&e.where;i=this._addFloorFilterClause(t)}if(!this._visibilityOverrides.size&&!r&&!s)return l(e)?e.toJSON():null;(e=l(e)&&e.clone()||new b).timeExtent=r,i&&(e.where=i);const a=e.toJSON();return a.hiddenIds=Array.from(this._visibilityOverrides),a}_addFloorFilterClause(e){const t=this.layer;let r=e||"";if("floorInfo"in t&&t.floorInfo){let e=this.view.floors;if(!e||!e.length)return r;t.floorInfo.viewAllLevelIds?.length&&(e=t.floorInfo.viewAllLevelIds);const i=e.filter((e=>""!==e)).map((e=>"'"+e+"'"));i.push("''");const s=t.floorInfo.floorField;let a="("+s+" IN ({ids}) OR "+s+" IS NULL)";if(a=a.replace("{ids}",i.join(", ")),l(r)&&r.includes(s)){let e=new RegExp("AND \\("+s+".*NULL\\)","g");r=r.replace(e,""),e=new RegExp("\\("+s+".*NULL\\)","g"),r=r.replace(e,""),r=r.replace(/\s+/g," ").trim()}r=""!==r?"("+r+") AND "+a:a}return""!==r?r:null}_createConfiguration(e,t,r){const i="feature"===this.layer.type&&this.layer.historicMoment?this.layer.historicMoment.getTime():void 0,s="feature"===this.layer.type?this.layer.gdbVersion:void 0,a=new Array(x),n=this._injectOverrides(t);a[0]=n,a[1]=l(r)?r.toJSON():null;const o=C(e);if(h(o))return null;const u=P("2d");return{availableFields:this.availableFields,gdbVersion:s,historicMoment:i,devicePixelRatio:window.devicePixelRatio||1,filters:a,schema:o,supportsTextureFloat:u.supportsTextureFloat,maxTextureSize:u.maxTextureSize}}_hasRequiredSupport(e){return!("renderer"in e)||q(e.renderer)}_onceTilesUpdated(){return this.requestUpdate(),y((()=>!this._pipelineIsUpdating))}_lockGPUUploads(){this.tileRenderer&&(this._uploadsLocked=!0,this.tileRenderer.lockGPUUploads())}_unlockGPUUploads(){this.tileRenderer&&(this._uploadsLocked=!1,this.tileRenderer.unlockGPUUploads())}_forceAttributeTextureUpload(){this.tileRenderer&&this.tileRenderer.forceAttributeTextureUpload()}_createSchemaConfig(){const e=this.layer;return{renderer:"renderer"in e?e.renderer:null,spatialReference:e.spatialReference,timeExtent:e.timeExtent,definitionExpression:e.definitionExpression,featureReduction:"featureReduction"in e?e.featureReduction:null,fields:e.fields,geometryType:e.geometryType,historicMoment:"historicMoment"in e?e.historicMoment:null,labelsVisible:"labelsVisible"in e&&e.labelsVisible,labelingInfo:"labelingInfo"in e&&e.labelingInfo,availableFields:this.availableFields,featureEffect:this.featureEffect,filter:this.filter,gdbVersion:"gdbVersion"in e?e.gdbVersion:null,pixelBuffer:0,orderBy:"orderBy"in e&&e.orderBy?e.orderBy:null,customParameters:{..."customParameters"in e?e.customParameters:void 0,token:"apiKey"in e?e.apiKey:void 0},subtypeCode:"subtypeCode"in e?e.subtypeCode:void 0,subtypeField:"subtypeField"in e?e.subtypeField:void 0}}_addHighlight(e){for(const t of e)if(this._highlightIds.has(t)){const e=this._highlightIds.get(t);this._highlightIds.set(t,e+1)}else this._highlightIds.set(t,1);this._updateHighlight().catch((e=>{p(e)||n.getLogger(this.declaredClass).error(e)}))}_removeHighlight(e){for(const t of e)if(this._highlightIds.has(t)){const e=this._highlightIds.get(t)-1;0===e?this._highlightIds.delete(t):this._highlightIds.set(t,e)}this._updateHighlight().catch((e=>{p(e)||n.getLogger(this.declaredClass).error(e)}))}_setLayersForFeature(e){const t=this.layer;e.layer=t,e.sourceLayer=t}_createGraphicHit(e,t){return this._setLayersForFeature(t),l(t.geometry)&&(t.geometry.spatialReference=this.view.spatialReference),{type:"graphic",graphic:t,layer:this.layer,mapPoint:e}}};e([m()],M.prototype,"_serviceOptions",void 0),e([m()],M.prototype,"_proxy",void 0),e([m()],M.prototype,"_pipelineIsUpdating",void 0),e([m()],M.prototype,"_effectiveRenderer",void 0),e([m()],M.prototype,"_aggregateValueRanges",void 0),e([m()],M.prototype,"_commandsQueue",void 0),e([m()],M.prototype,"featureEffectView",void 0),e([m()],M.prototype,"labelsVisible",null),e([m({readOnly:!0})],M.prototype,"queryMode",null),e([m()],M.prototype,"renderingConfigHash",null),e([m()],M.prototype,"tileRenderer",void 0),e([m()],M.prototype,"updating",void 0),M=e([_("esri.views.2d.layers.FeatureLayerView2D")],M);const B=M;export{B 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.25/esri/copyright.txt for details.
4
4
  */
5
- import"../../../../../core/has.js";import t from"../../../../../core/Logger.js";import{unwrapOrThrow as e,isSome as s,isNone as r}from"../../../../../core/maybe.js";import{throwIfAborted as o,after as i}from"../../../../../core/promiseUtils.js";import a from"../../../../../core/RandomLCG.js";import{BaseFeatureSource as n}from"./BaseFeatureSource.js";import{FeatureSetReaderIndirect as d}from"../support/FeatureSetReaderPBFIndirect.js";import{UpdateToken as u}from"../support/UpdateToken.js";function h(t,e,s){const r=t.getXHydrated(),o=t.getYHydrated(),i=e.getColumnForX(r),a=Math.floor(e.normalizeCol(i));return`${s}/${Math.floor(e.getRowForY(o))}/${a}`}function l(t,e){if(r(t))return null;const s=e.transform,o=t.getQuantizationTransform();if(r(o)){const[e,r]=s.scale,[o,i]=s.translate,a=-o/e,n=1/e,d=i/r,u=1/-r;return t.transform(a,d,n,u)}const[i,a]=o.scale,[n,d]=o.translate,[u,h]=s.scale,[l,c]=s.translate,_=i/u,g=(n-l)/u,p=a/h,f=(-d+c)/h;return t.transform(g,f,_,p)}class c extends n{constructor(t){super(t),this.mode="snapshot",this._loading=!0,this._controller=new AbortController,this._downloadPromise=null,this._didSendEnd=!1,this._queries=new Array,this._invalidated=!1,this._hasAggregates=!1,this._random=new a(1e3),this._store=t.store,this._markedIdsBufId=this._store.storage.createBitset()}destroy(){super.destroy(),this._controller.abort()}get loading(){return this._loading}get _signal(){return this._controller.signal}update(t,e){super.update(t,e),null==this._featureCount&&(this._featureCount=e.initialFeatureCount),this._hasAggregates=t.targets.aggregate}async resend(t=!1){if(await this._downloadPromise,this._invalidated||t){const t=e(this._featureCount,"Expected featureCount to be defined");return this._invalidated=!1,this._subscriptions.forEach((t=>t.clear())),this._downloadPromise=this._download(t),void await this._downloadPromise}const s=this._queries.map((({query:t,reader:e})=>this._sendPatchQuery(t,e)));await Promise.all(s),this._subscriptions.forEach((t=>{t.requests.done.forEach((t=>this._onMessage(t.message)))}))}async refresh(t,e){e&&(this._featureCount=e.featureCount),await this.resend(!0)}async _sendPatchQuery(t,e){const r=s(t.outFields)?t.outFields:[],i=this._queryInfo.outFields,a=i.filter((t=>!r.includes(t)));if(!a.length)return;const n=t.clone(),d=this._signal;n.returnGeometry=!1,n.returnCentroid=!1,n.outFields=a,t.outFields=i;const u=await this._queue.push({query:n,depth:0,signal:d});o({signal:d}),e.joinAttributes(u)}async _fetchDataTile(t){if(!this._downloadPromise){const t=e(this._featureCount,"Expected featureCount to be defined");this._downloadPromise=this._download(t)}const s=this._store.search(t),r=this._subscriptions.get(t.key.id),o=s.length-1;for(let e=0;e<o;e++){const o=l(s[e],t),a={type:"append",id:t.id,addOrUpdate:o,end:!1,status:u.empty()};r.add({query:null,message:a}),this._hasAggregates||await i(1),this._onMessage(a)}const a=l(o>=0?s[o]:null,t),n=this._didSendEnd,d={type:"append",id:t.id,addOrUpdate:a,end:n,status:u.empty()};r.add({query:null,message:d}),this._onMessage(d)}async _download(e){try{await this.whenInitialized();const t=this._store.storage.getBitset(this._markedIdsBufId),s=new Set;t.clear();const r=Math.ceil(e/this.pageSize),o=Array.from({length:r},((t,e)=>e)).sort(((t,e)=>this._random.getInt()-this._random.getInt())).map((e=>this._downloadPage(e,t,s)));await Promise.all(o),this._store.sweepFeatures(t,this._store.storage),this._store.sweepFeatureSets(s)}catch(s){t.getLogger("esri.views.2d.layers.features.sources.SnapshotFeatureSource").error("mapview-snapshot-source","Encountered and error when downloading feature snapshot",s)}this._sendEnd(),this._loading=!1}async _downloadPage(t,e,r){const i=this.pageSize,a={start:t*i,num:i,cacheHint:!0};s(this.maxRecordCountFactor)&&(a.maxRecordCountFactor=this.maxRecordCountFactor);const n=this.createQuery(a),d=this._signal,u=await this._queue.push({query:n,depth:t,signal:d});o({signal:d}),this._queries.push({query:n,reader:u}),this._store.insert(u),r.add(u.instance);const h=u.getCursor();for(;h.next();)e.set(h.getDisplayId());this._send(u)}_send(t){if(!this._subscriptions.size)return;let e=null;const o=new Map,i=new Set,a=new Map;this._subscriptions.forEach((t=>{const s=t.tile;o.set(s.key.id,null),e=s.tileInfoView,i.add(s.level);const{row:r,col:n}=s.key,d=`${s.level}/${r}/${n}`,u=a.get(d)??[];u.push(t),a.set(d,u)}));for(const s of i){const i=e.getLODInfoAt(s),n=t.getCursor();for(;n.next();){const t=h(n,i,s),e=n.getIndex();if(a.has(t))for(const s of a.get(t)){const t=s.tile.id;let i=o.get(t);r(i)&&(i=[],o.set(t,i)),i.push(e)}}}o.forEach(((e,r)=>{if(s(e)){const s=this._subscriptions.get(r),o={type:"append",id:r,addOrUpdate:l(d.from(t,e),s.tile),end:!1,status:u.empty()};s.add({query:null,message:o}),this._onMessage(o)}}))}_sendEnd(){this._subscriptions.forEach((t=>{const e={type:"append",id:t.tile.id,addOrUpdate:null,end:!0,status:u.empty()};t.add({query:null,message:e}),this._onMessage(e)})),this._didSendEnd=!0}}export{c as SnapshotFeatureSource};
5
+ import"../../../../../core/has.js";import t from"../../../../../core/Logger.js";import{isSome as e,unwrapOrThrow as s,isNone as r}from"../../../../../core/maybe.js";import{throwIfAborted as o,after as a}from"../../../../../core/promiseUtils.js";import n from"../../../../../core/RandomLCG.js";import{BaseFeatureSource as i}from"./BaseFeatureSource.js";import{FeatureSetReaderIndirect as d}from"../support/FeatureSetReaderPBFIndirect.js";import{UpdateToken as u}from"../support/UpdateToken.js";function h(t,e,s){const r=t.getXHydrated(),o=t.getYHydrated(),a=e.getColumnForX(r),n=Math.floor(e.normalizeCol(a));return`${s}/${Math.floor(e.getRowForY(o))}/${n}`}function l(t,e){if(r(t))return null;const s=e.transform,o=t.getQuantizationTransform();if(r(o)){const[e,r]=s.scale,[o,a]=s.translate,n=-o/e,i=1/e,d=a/r,u=1/-r;return t.transform(n,d,i,u)}const[a,n]=o.scale,[i,d]=o.translate,[u,h]=s.scale,[l,c]=s.translate,g=a/u,_=(i-l)/u,p=n/h,f=(-d+c)/h;return t.transform(_,f,g,p)}class c extends i{constructor(t){super(t),this.mode="snapshot",this._loading=!0,this._controller=new AbortController,this._downloadPromise=null,this._didSendEnd=!1,this._queries=new Array,this._invalidated=!1,this._hasAggregates=!1,this._random=new n(1e3),this._store=t.store,this._markedIdsBufId=this._store.storage.createBitset()}destroy(){super.destroy(),this._controller.abort()}get loading(){return this._loading}get _signal(){return this._controller.signal}update(t,s){super.update(t,s),null==this._featureCount&&(this._featureCount=s.initialFeatureCount),e(s.changedFeatureCount)&&(this._featureCount=s.changedFeatureCount),this._hasAggregates=t.targets.aggregate}async resend(t=!1){if(await this._downloadPromise,this._invalidated||t){const t=s(this._featureCount,"Expected featureCount to be defined");return this._invalidated=!1,this._subscriptions.forEach((t=>t.clear())),this._downloadPromise=this._download(t),void await this._downloadPromise}const e=this._queries.map((({query:t,reader:e})=>this._sendPatchQuery(t,e)));await Promise.all(e),this._subscriptions.forEach((t=>{t.requests.done.forEach((t=>this._onMessage(t.message)))}))}async refresh(t,e){e&&(this._featureCount=e.featureCount),await this.resend(!0)}async _sendPatchQuery(t,s){const r=e(t.outFields)?t.outFields:[],a=this._queryInfo.outFields,n=a.filter((t=>!r.includes(t)));if(!n.length)return;const i=t.clone(),d=this._signal;i.returnGeometry=!1,i.returnCentroid=!1,i.outFields=n,t.outFields=a;const u=await this._queue.push({query:i,depth:0,signal:d});o({signal:d}),s.joinAttributes(u)}async _fetchDataTile(t){if(!this._downloadPromise){const t=s(this._featureCount,"Expected featureCount to be defined");this._downloadPromise=this._download(t)}const e=this._store.search(t),r=this._subscriptions.get(t.key.id),o=e.length-1;for(let s=0;s<o;s++){const o=l(e[s],t),n={type:"append",id:t.id,addOrUpdate:o,end:!1,status:u.empty()};r.add({query:null,message:n}),this._hasAggregates||await a(1),this._onMessage(n)}const n=l(o>=0?e[o]:null,t),i=this._didSendEnd,d={type:"append",id:t.id,addOrUpdate:n,end:i,status:u.empty()};r.add({query:null,message:d}),this._onMessage(d)}async _download(e){try{await this.whenInitialized();const t=this._store.storage.getBitset(this._markedIdsBufId),s=new Set;t.clear();const r=Math.ceil(e/this.pageSize),o=Array.from({length:r},((t,e)=>e)).sort(((t,e)=>this._random.getInt()-this._random.getInt())).map((e=>this._downloadPage(e,t,s)));await Promise.all(o),this._store.sweepFeatures(t,this._store.storage),this._store.sweepFeatureSets(s)}catch(s){t.getLogger("esri.views.2d.layers.features.sources.SnapshotFeatureSource").error("mapview-snapshot-source","Encountered and error when downloading feature snapshot",s)}this._sendEnd(),this._loading=!1}async _downloadPage(t,s,r){const a=this.pageSize,n={start:t*a,num:a,cacheHint:!0};e(this.maxRecordCountFactor)&&(n.maxRecordCountFactor=this.maxRecordCountFactor);const i=this.createQuery(n),d=this._signal,u=await this._queue.push({query:i,depth:t,signal:d});o({signal:d}),this._queries.push({query:i,reader:u}),this._store.insert(u),r.add(u.instance);const h=u.getCursor();for(;h.next();)s.set(h.getDisplayId());this._send(u)}_send(t){if(!this._subscriptions.size)return;let s=null;const o=new Map,a=new Set,n=new Map;this._subscriptions.forEach((t=>{const e=t.tile;o.set(e.key.id,null),s=e.tileInfoView,a.add(e.level);const{row:r,col:i}=e.key,d=`${e.level}/${r}/${i}`,u=n.get(d)??[];u.push(t),n.set(d,u)}));for(const e of a){const a=s.getLODInfoAt(e),i=t.getCursor();for(;i.next();){const t=h(i,a,e),s=i.getIndex();if(n.has(t))for(const e of n.get(t)){const t=e.tile.id;let a=o.get(t);r(a)&&(a=[],o.set(t,a)),a.push(s)}}}o.forEach(((s,r)=>{if(e(s)){const e=this._subscriptions.get(r),o={type:"append",id:r,addOrUpdate:l(d.from(t,s),e.tile),end:!1,status:u.empty()};e.add({query:null,message:o}),this._onMessage(o)}}))}_sendEnd(){this._subscriptions.forEach((t=>{const e={type:"append",id:t.tile.id,addOrUpdate:null,end:!0,status:u.empty()};t.add({query:null,message:e}),this._onMessage(e)})),this._didSendEnd=!0}}export{c as SnapshotFeatureSource};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.25/esri/copyright.txt for details.
4
4
  */
5
- import t from"../../request.js";import e from"../../geometry/Point.js";import{project as r}from"../../geometry/projection.js";import{projectResolution as i,getProjectionOffsetGrid as a}from"../../layers/support/rasterFunctions/rasterProjectionHelper.js";import{isImageSource as s,rasterize as o}from"../2d/engine/Bitmap.js";import n from"../2d/engine/webgl/VertexStream.js";import{createProgramTemplate as m}from"../2d/engine/webgl/shaders/MaterialPrograms.js";import{PixelFormat as p,PixelType as h,TextureWrapMode as c,TextureSamplingMode as x,TargetType as d,DepthStencilTargetType as g,ColorAttachment as u}from"../webgl/enums.js";import{FramebufferObject as _}from"../webgl/FramebufferObject.js";import{createTransformTexture as f}from"../webgl/rasterUtils.js";import{RenderingContext as l}from"../webgl/RenderingContext.js";import{Texture as w}from"../webgl/Texture.js";class b{constructor(t){if(t)this._ownsRctx=!1,this._rctx=t;else{this._ownsRctx=!0;const t=document.createElement("canvas").getContext("webgl");t.getExtension("OES_texture_float"),this._rctx=new l(t,{})}const e={applyProjection:!0,bilinear:!1,bicubic:!1},r=m("raster/reproject","raster/reproject",new Map([["a_position",0]]),e);this._program=this._rctx.programCache.acquire(r.shaders.vertexShader,r.shaders.fragmentShader,r.attributes),this._rctx.useProgram(this._program),this._program.setUniform1f("u_opacity",1),this._program.setUniform1i("u_image",0),this._program.setUniform1i("u_flipY",0),this._program.setUniform1i("u_transformGrid",1),this._quad=new n(this._rctx,[0,0,1,0,0,1,1,1])}reprojectTexture(t,s,o=!1){const n=r(t.extent,s),m=new e({x:(t.extent.xmax-t.extent.xmin)/t.texture.descriptor.width,y:(t.extent.ymax-t.extent.ymin)/t.texture.descriptor.height,spatialReference:t.extent.spatialReference}),{x:l,y:b}=i(m,s,t.extent);let D=(l+b)/2;const T=Math.round((n.xmax-n.xmin)/D),j=Math.round((n.ymax-n.ymin)/D);D=(n.width/T+n.height/j)/2;const E=new e({x:D,y:D,spatialReference:n.spatialReference}),R=a({projectedExtent:n,srcBufferExtent:t.extent,pixelSize:E,hasWrapAround:!0,spacing:[16,16]}),y=f(this._rctx,R),M=new w(this._rctx,{width:T,height:j,pixelFormat:p.RGBA,dataType:h.UNSIGNED_BYTE,wrapMode:c.CLAMP_TO_EDGE,samplingMode:x.LINEAR,hasMipmap:!1}),A=new _(this._rctx,{colorTarget:d.TEXTURE,depthStencilTarget:g.NONE,width:T,height:j},M);if(this._rctx.bindFramebuffer(A),this._rctx.setViewport(0,0,T,j),this._rctx.useProgram(this._program),this._rctx.bindTexture(t.texture,0),this._rctx.bindTexture(y,1),this._quad.bind(),this._program.setUniform2f("u_srcImageSize",t.texture.descriptor.width,t.texture.descriptor.height),this._program.setUniform2fv("u_transformSpacing",R.spacing),this._program.setUniform2fv("u_transformGridSize",R.size),this._program.setUniform2f("u_targetImageSize",T,j),this._quad.draw(),this._quad.unbind(),this._rctx.useProgram(null),this._rctx.bindFramebuffer(null),y.dispose(),o){const t=new ImageData(A.descriptor.width,A.descriptor.height);return A.readPixels(0,0,A.descriptor.width,A.descriptor.height,p.RGBA,h.UNSIGNED_BYTE,t.data),A.detachColorTexture(u.COLOR_ATTACHMENT0),A.dispose(),{texture:M,extent:n,imageData:t}}return A.detachColorTexture(u.COLOR_ATTACHMENT0),A.dispose(),{texture:M,extent:n}}reprojectBitmapData(t,e){const r=s(t.bitmapData)?o(t.bitmapData):t.bitmapData,i=new w(this._rctx,{width:t.bitmapData.width,height:t.bitmapData.height,pixelFormat:p.RGBA,dataType:h.UNSIGNED_BYTE,wrapMode:c.CLAMP_TO_EDGE,samplingMode:x.LINEAR,hasMipmap:!1},r),a=this.reprojectTexture({texture:i,extent:t.extent},e,!0);a.texture.dispose();const n=document.createElement("canvas");n.width=a.imageData.width,n.height=a.imageData.height;return n.getContext("2d").putImageData(a.imageData,0,0),{bitmapData:n,extent:a.extent}}async loadAndReprojectBitmapData(e,r,i){const a=(await t(e,{responseType:"image"})).data,s=document.createElement("canvas");s.width=a.width,s.height=a.height;const o=s.getContext("2d");o.drawImage(a,0,0);const n=o.getImageData(0,0,s.width,s.height);if(r.spatialReference.equals(i))return{bitmapData:n,extent:r};const m=this.reprojectBitmapData({bitmapData:n,extent:r},i);return{bitmapData:m.bitmapData,extent:m.extent}}destroy(){this._quad.dispose(),this._program.dispose(),this._ownsRctx&&this._rctx.dispose()}}export{b as ImageReprojector};
5
+ import t from"../../request.js";import e from"../../geometry/Point.js";import{project as r}from"../../geometry/projection.js";import{projectResolution as i,getProjectionOffsetGrid as a}from"../../layers/support/rasterFunctions/rasterProjectionHelper.js";import{isImageSource as s,rasterize as n}from"../2d/engine/Bitmap.js";import o from"../2d/engine/webgl/VertexStream.js";import{createProgramTemplate as m}from"../2d/engine/webgl/shaders/MaterialPrograms.js";import{PixelFormat as p,PixelType as h,TextureWrapMode as c,TextureSamplingMode as d,TargetType as x,DepthStencilTargetType as g,ColorAttachment as u}from"../webgl/enums.js";import{FramebufferObject as _}from"../webgl/FramebufferObject.js";import{createTransformTexture as f}from"../webgl/rasterUtils.js";import{RenderingContext as l}from"../webgl/RenderingContext.js";import{Texture as w}from"../webgl/Texture.js";class b{constructor(t){if(t)this._ownsRctx=!1,this._rctx=t;else{if(b._instance)return b._instanceRefCount++,b._instance;b._instanceRefCount=1,b._instance=this,this._ownsRctx=!0;const t=document.createElement("canvas").getContext("webgl");t.getExtension("OES_texture_float"),this._rctx=new l(t,{})}const e={applyProjection:!0,bilinear:!1,bicubic:!1},r=m("raster/reproject","raster/reproject",new Map([["a_position",0]]),e);this._program=this._rctx.programCache.acquire(r.shaders.vertexShader,r.shaders.fragmentShader,r.attributes),this._rctx.useProgram(this._program),this._program.setUniform1f("u_opacity",1),this._program.setUniform1i("u_image",0),this._program.setUniform1i("u_flipY",0),this._program.setUniform1i("u_transformGrid",1),this._quad=new o(this._rctx,[0,0,1,0,0,1,1,1])}reprojectTexture(t,s,n=!1){const o=r(t.extent,s),m=new e({x:(t.extent.xmax-t.extent.xmin)/t.texture.descriptor.width,y:(t.extent.ymax-t.extent.ymin)/t.texture.descriptor.height,spatialReference:t.extent.spatialReference}),{x:l,y:b}=i(m,s,t.extent);let D=(l+b)/2;const T=Math.round((o.xmax-o.xmin)/D),j=Math.round((o.ymax-o.ymin)/D);D=(o.width/T+o.height/j)/2;const E=new e({x:D,y:D,spatialReference:o.spatialReference}),R=a({projectedExtent:o,srcBufferExtent:t.extent,pixelSize:E,hasWrapAround:!0,spacing:[16,16]}),C=f(this._rctx,R),y=new w(this._rctx,{width:T,height:j,pixelFormat:p.RGBA,dataType:h.UNSIGNED_BYTE,wrapMode:c.CLAMP_TO_EDGE,samplingMode:d.LINEAR,hasMipmap:!1}),M=new _(this._rctx,{colorTarget:x.TEXTURE,depthStencilTarget:g.NONE,width:T,height:j},y);if(this._rctx.bindFramebuffer(M),this._rctx.setViewport(0,0,T,j),this._rctx.useProgram(this._program),this._rctx.bindTexture(t.texture,0),this._rctx.bindTexture(C,1),this._quad.bind(),this._program.setUniform2f("u_srcImageSize",t.texture.descriptor.width,t.texture.descriptor.height),this._program.setUniform2fv("u_transformSpacing",R.spacing),this._program.setUniform2fv("u_transformGridSize",R.size),this._program.setUniform2f("u_targetImageSize",T,j),this._quad.draw(),this._quad.unbind(),this._rctx.useProgram(null),this._rctx.bindFramebuffer(null),C.dispose(),n){const t=new ImageData(M.descriptor.width,M.descriptor.height);return M.readPixels(0,0,M.descriptor.width,M.descriptor.height,p.RGBA,h.UNSIGNED_BYTE,t.data),M.detachColorTexture(u.COLOR_ATTACHMENT0),M.dispose(),{texture:y,extent:o,imageData:t}}return M.detachColorTexture(u.COLOR_ATTACHMENT0),M.dispose(),{texture:y,extent:o}}reprojectBitmapData(t,e){const r=s(t.bitmapData)?n(t.bitmapData):t.bitmapData,i=new w(this._rctx,{width:t.bitmapData.width,height:t.bitmapData.height,pixelFormat:p.RGBA,dataType:h.UNSIGNED_BYTE,wrapMode:c.CLAMP_TO_EDGE,samplingMode:d.LINEAR,hasMipmap:!1},r),a=this.reprojectTexture({texture:i,extent:t.extent},e,!0);a.texture.dispose();const o=document.createElement("canvas");o.width=a.imageData.width,o.height=a.imageData.height;return o.getContext("2d").putImageData(a.imageData,0,0),{bitmapData:o,extent:a.extent}}async loadAndReprojectBitmapData(e,r,i){const a=(await t(e,{responseType:"image"})).data,s=document.createElement("canvas");s.width=a.width,s.height=a.height;const n=s.getContext("2d");n.drawImage(a,0,0);const o=n.getImageData(0,0,s.width,s.height);if(r.spatialReference.equals(i))return{bitmapData:o,extent:r};const m=this.reprojectBitmapData({bitmapData:o,extent:r},i);return{bitmapData:m.bitmapData,extent:m.extent}}destroy(){this._ownsRctx?(b._instanceRefCount--,0===b._instanceRefCount&&(this._quad.dispose(),this._program.dispose(),this._rctx.dispose(),b._instance=null)):(this._quad.dispose(),this._program.dispose())}}b._instanceRefCount=0;export{b as ImageReprojector};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.25/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../chunks/tslib.es6.js";import{remove as t}from"../../core/arrayUtils.js";import{makeHandle as a,handlesGroup as i}from"../../core/handleUtils.js";import{unwrap as r,removeMaybe as o,isSome as n,isNone as s,destroyMaybe as l}from"../../core/maybe.js";import{watch as c,syncAndInitial as d}from"../../core/reactiveUtils.js";import{generateUUID as u}from"../../core/uuid.js";import"../../core/Logger.js";import"../../core/accessorSupport/ensureType.js";import"../../core/Error.js";import"../../core/has.js";import{subclass as h}from"../../core/accessorSupport/decorators/subclass.js";import f from"../../views/interactive/snapping/FeatureSnappingLayerSource.js";import{CreateFeaturesWorkflowData as p}from"./CreateFeaturesWorkflowData.js";import m from"./Workflow.js";import{startCreatingNewFeature as w,findLayerInfo as g,updateGraphicSymbolWhenRequired as v,isTerminalUpdateEventType as _,getVisualVariableAttributes as y,startUpdatingFeature as M,createWorkflowSteps as b,avoidFeatureTemplateSelectionWithOnlyOneItem as F,visualVariableInteractiveUpdate as A}from"./workflowUtils.js";var V;let I=V=class extends m{constructor(e){super(e),this.type="create-features",this.createFeatureState="create-new",this._featureFormHandle=null,this._visualVariableAttributes={rotation:null,size:null},this._attachmentFileInfos=new Map,this._highlightHandles=new Map,this._preventDefaultActionOnCancel=!1}get numPendingFeatures(){return this.data.viewModel.sketchViewModel.layer.graphics.length}get pendingFeatures(){return this.data.viewModel.sketchViewModel.layer.graphics}async updatePendingFeature(e,a){return this._preventDefaultActionOnCancel=!0,this.data.viewModel.sketchViewModel.cancel(),t(this._lastActiveGraphics,e),this._startUpdating(e,a)}static create(e,t,a,i,o){const n=new V({data:new p({creationInfo:r(t),viewModel:e}),onCommit:async e=>{const t=e.viewModel.sketchViewModel.layer.graphics.toArray(),a=e.creationInfo.layer,r=a.capabilities.editing.supportsGlobalId&&"globalIdField"in a,s=n._attachmentFileInfos;if(0===s.size)return void await i(a,{addFeatures:t});if(r){const e=n._getAttachmentEditsWithGlobalIds(t,a,s),r="addAttachments"in e?{globalIdUsed:!0}:void 0;return void await i(a,e,r)}const{addFeatureResults:l}=await i(a,{addFeatures:t}),c=n._getAddAttachmentsData(t,l,a,s);await o(a,c)}});return n._set("steps",this._createWorkflowSteps(n,a)),n}_fadeExistingFeatures(e){if("effect"in e){const t=e.effect;return e.effect="saturate(0.6) opacity(0.8)",a((()=>e.effect=t))}const t=e.opacity;return e.opacity=.7,a((()=>e.opacity=t))}_highlight(e){const t=this.data.viewModel.view;"3d"===t.type&&this._highlightHandles.set(e,t.highlight(e))}_removeHighlight(e){o(this._highlightHandles.get(e)),this._highlightHandles.delete(e)}async _startCreating(e){return this.createFeatureState="create-new",w(this.data.viewModel.sketchViewModel,this.data.creationInfo,e)}async _startUpdating(e,t){const{featureFormViewModel:a,layerInfos:r,sketchViewModel:s,view:l}=this.data.viewModel,c=this.data.creationInfo.layer,d=g(r,c)?.formTemplate,u=l.spatialReference;return a.set({arcadeEditType:"INSERT",feature:e,formTemplate:d,spatialReference:u,view:l}),o(this._featureFormHandle),this._featureFormHandle=i([a.on("value-change",(async()=>{e.attributes=a.getValues(),await v(e,t)})),s.on(["update","undo","redo"],(e=>{("undo"===e.type||"redo"===e.type||"update"===e.type&&n(e.toolEventInfo)&&_(e.toolEventInfo.type))&&a.notifyFeatureGeometryChanged()}))]),this._removeHighlight(e),this.createFeatureState="update-pending",this._visualVariableAttributes=y(e),M(s,e,c,this._visualVariableAttributes,t)}static _createWorkflowSteps(e,a="awaiting-feature-creation-info"){const{data:i,handles:r}=e;let u=null,h=!0;const p=new Map,m=b(["awaiting-feature-creation-info","creating-features","adding-attachment","editing-attachment"],a,{"awaiting-feature-creation-info":()=>({id:"awaiting-feature-creation-info",async setUp(){i.creationInfo=null,r.add(i.viewModel.featureTemplatesViewModel.on("select",(({item:e})=>{i.creationInfo={layer:e.layer,template:e.template},i.viewModel.activeWorkflow.next()})),this.id)},async tearDown(){r.remove(this.id)}}),"creating-features":()=>({id:"creating-features",async setUp(){if(r.has(this.id))return;const a=i.viewModel.view,m=i.viewModel.sketchViewModel;h=m.updateOnGraphicClick,m.updateOnGraphicClick=!1,e._lastActiveGraphics=[],e._featureFormHandle=o(e._featureFormHandle),e._visualVariableAttributes={rotation:null,size:null};const w="2d"===a.type?e._fadeExistingFeatures(i.creationInfo.layer):null,g=m.on("create",(async t=>{if("cancel"===t.state){if(e._preventDefaultActionOnCancel)return void(e._preventDefaultActionOnCancel=!1);if(e._lastActiveGraphics.length<1)return e._startCreating(p);const t=e._lastActiveGraphics.pop();return e._startUpdating(t,p)}if("complete"===t.state)return e._startUpdating(t.graphic,p)})),v=m.on("update",(async t=>{const r=t.graphics[0];if("complete"===t.state)return r!==u&&(e._lastActiveGraphics.push(r),e._highlight(r)),u=null,"add"!==i.viewModel.attachmentsViewModel.mode&&"edit"!==i.viewModel.attachmentsViewModel.mode||i.viewModel.activeWorkflow.previous(),t.aborted&&e._preventDefaultActionOnCancel?void(e._preventDefaultActionOnCancel=!1):e._startCreating(p);if("start"===t.state){e._removeHighlight(r);const t=i.viewModel.attachmentsViewModel;"add"!==t.mode&&"edit"!==t.mode||i.viewModel.activeWorkflow.previous(),t.fileInfos.removeAll(),t.graphic=r,t.mode="view";(e._attachmentFileInfos.get(r)||[]).forEach((({file:e,form:a})=>t.addFile(e,a)))}await A(a,r,t,e._visualVariableAttributes,p);const o=r.attributes;if(n(e._visualVariableAttributes.rotation)){const{field:t}=e._visualVariableAttributes.rotation;i.viewModel.featureFormViewModel.setValue(t,o[t])}if(n(e._visualVariableAttributes.size)){const{field:t}=e._visualVariableAttributes.size;i.viewModel.featureFormViewModel.setValue(t,o[t])}})),_=m.on("delete",(async a=>{const i=a.graphics[0];t(e._lastActiveGraphics,i),u=i}));let y=null;const M=c((()=>{const e=m.snappingOptions.featureSources.find((e=>e.layer===i.creationInfo.layer));return{hasFeatureLayerSource:!!e,enabled:e?.enabled??!1}}),(({hasFeatureLayerSource:e,enabled:t})=>{const a=m.snappingOptions.featureSources;e?(s(y)&&(y=new f({layer:m.layer,enabled:t}),a.add(y)),y.enabled=t):(n(y)&&a.remove(y),y=l(y))}),d),b=a.on("immediate-click",(async t=>{const{results:i}=await a.hitTest(t,{include:m.layer}),r=i.find((e=>"graphic"===e.type));if(r){const t=r.graphic;if("transform"===m.activeTool||"reshape"===m.activeTool){if(m.updateGraphics.getItemAt(0)===t)return;await e.updatePendingFeature(t,p)}}})),F=c((()=>i.viewModel.attachmentsViewModel.mode),(e=>{"add"===e&&i.viewModel.activeWorkflow.go("adding-attachment"),"edit"===e&&i.viewModel.activeWorkflow.go("editing-attachment")}));await e._startCreating(p);const V={remove:()=>{o(e._featureFormHandle),g.remove(),v.remove(),_.remove(),M.remove(),n(y)&&m.snappingOptions.featureSources.remove(y),y=l(y),m.cancel(),b.remove(),F.remove(),o(w)}};r.add(V,this.id)},async tearDown(t){t.cancelled&&(i.viewModel.sketchViewModel.layer.removeAll(),r.remove(this.id),i.viewModel.attachmentsViewModel.fileInfos.removeAll(),e._attachmentFileInfos.clear(),i.viewModel.sketchViewModel.updateOnGraphicClick=h)}}),"adding-attachment":()=>({id:"adding-attachment",parent:"creating-features",async setUp(){},async tearDown(){const{graphic:t,fileInfos:a}=i.viewModel.attachmentsViewModel;e._attachmentFileInfos.set(t,a.toArray()),i.viewModel.attachmentsViewModel.mode="view"}}),"editing-attachment":()=>({id:"editing-attachment",parent:"creating-features",async setUp(){},async tearDown(){const{graphic:t,fileInfos:a}=i.viewModel.attachmentsViewModel;e._attachmentFileInfos.set(t,a.toArray()),i.viewModel.attachmentsViewModel.mode="view"}})});return F(i,m)}_getAddAttachmentsData(e,t,a,i){const r=[];return t.forEach(((t,o)=>{if(!t.error){const n=e[o],s=i.get(n)||[];n.attributes[a.objectIdField]=t.objectId,s.forEach((({form:e})=>r.push({feature:n,attachment:e})))}})),r}_getAttachmentEditsWithGlobalIds(e,t,a){const i=[];return e.forEach(((r,o)=>{const n=a.get(r)||[];let l=r.attributes[t.globalIdField];s(l)&&(l=u(),e[o].attributes[t.globalIdField]=l),n.forEach((({file:e})=>i.push({feature:r,attachment:{globalId:u(),data:e}})))})),i.length?{addFeatures:e,addAttachments:i}:{addFeatures:e}}};I=V=e([h("esri.widgets.Editor.CreateFeaturesWorkflow")],I);const k=I;export{k as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import{remove as t}from"../../core/arrayUtils.js";import{makeHandle as a,handlesGroup as i}from"../../core/handleUtils.js";import{unwrap as r,removeMaybe as o,isSome as n,isNone as s,destroyMaybe as l}from"../../core/maybe.js";import{whenOnce as c,watch as d,syncAndInitial as u}from"../../core/reactiveUtils.js";import{generateUUID as h}from"../../core/uuid.js";import"../../core/Logger.js";import"../../core/accessorSupport/ensureType.js";import"../../core/Error.js";import"../../core/has.js";import{subclass as f}from"../../core/accessorSupport/decorators/subclass.js";import p from"../../views/interactive/snapping/FeatureSnappingLayerSource.js";import{CreateFeaturesWorkflowData as m}from"./CreateFeaturesWorkflowData.js";import w from"./Workflow.js";import{startCreatingNewFeature as g,findLayerInfo as v,updateGraphicSymbolWhenRequired as _,isTerminalUpdateEventType as y,getVisualVariableAttributes as M,startUpdatingFeature as b,createWorkflowSteps as F,avoidFeatureTemplateSelectionWithOnlyOneItem as A,visualVariableInteractiveUpdate as V}from"./workflowUtils.js";var I;const k=Symbol();let j=I=class extends w{constructor(e){super(e),this.type="create-features",this.createFeatureState="create-new",this._featureFormHandle=null,this._visualVariableAttributes={rotation:null,size:null},this._attachmentFileInfos=new Map,this._highlightHandles=new Map,this._preventDefaultActionOnCancel=!1}get numPendingFeatures(){return this.data.viewModel.sketchViewModel.layer.graphics.length}get pendingFeatures(){return this.data.viewModel.sketchViewModel.layer.graphics}async updatePendingFeature(e,a){return this._preventDefaultActionOnCancel=!0,this.data.viewModel.sketchViewModel.cancel(),t(this._lastActiveGraphics,e),this._startUpdating(e,a)}static create(e,t,a,i,o){const n=new I({data:new m({creationInfo:r(t),viewModel:e}),onCommit:async e=>{const t=e.viewModel.sketchViewModel.layer.graphics.toArray(),a=e.creationInfo.layer,r=a.capabilities.editing.supportsGlobalId&&"globalIdField"in a,s=n._attachmentFileInfos;if(0===s.size)return void await i(a,{addFeatures:t});if(r){const e=n._getAttachmentEditsWithGlobalIds(t,a,s),r="addAttachments"in e?{globalIdUsed:!0}:void 0;return void await i(a,e,r)}const{addFeatureResults:l}=await i(a,{addFeatures:t}),c=n._getAddAttachmentsData(t,l,a,s);await o(a,c)}});return n._set("steps",this._createWorkflowSteps(n,a)),n}_fadeExistingFeatures(e){if("effect"in e){const t=e.effect;return e.effect="saturate(0.6) opacity(0.8)",a((()=>e.effect=t))}const t=e.opacity;return e.opacity=.7,a((()=>e.opacity=t))}_highlight(e){const t=this.data.viewModel.view;"3d"===t.type&&this._highlightHandles.set(e,t.highlight(e))}_removeHighlight(e){o(this._highlightHandles.get(e)),this._highlightHandles.delete(e)}async _startCreating(e){return this.createFeatureState="create-new",g(this.data.viewModel.sketchViewModel,this.data.creationInfo,e)}async _startUpdating(e,t){const{featureFormViewModel:a,layerInfos:r,sketchViewModel:s,view:l}=this.data.viewModel,c=this.data.creationInfo.layer,d=v(r,c)?.formTemplate,u=l.spatialReference;return a.set({arcadeEditType:"INSERT",feature:e,formTemplate:d,spatialReference:u,view:l}),o(this._featureFormHandle),this._featureFormHandle=i([a.on("value-change",(async()=>{e.attributes=a.getValues(),await _(e,t)})),s.on(["update","undo","redo"],(e=>{("undo"===e.type||"redo"===e.type||"update"===e.type&&n(e.toolEventInfo)&&y(e.toolEventInfo.type))&&a.notifyFeatureGeometryChanged()}))]),this._removeHighlight(e),this.createFeatureState="update-pending",this._visualVariableAttributes=M(e),b(s,e,c,this._visualVariableAttributes,t)}static _createWorkflowSteps(e,i="awaiting-feature-creation-info"){const{data:r,handles:h}=e;let f=null,m=!0;const w=new Map,g=F(["awaiting-feature-creation-info","creating-features","adding-attachment","editing-attachment"],i,{"awaiting-feature-creation-info":()=>({id:"awaiting-feature-creation-info",async setUp(){r.creationInfo=null,h.add(r.viewModel.featureTemplatesViewModel.on("select",(({item:e})=>{r.creationInfo={layer:e.layer,template:e.template},r.viewModel.activeWorkflow.next()})),this.id)},async tearDown(){h.remove(this.id)}}),"creating-features":()=>({id:"creating-features",async setUp(){if(h.has(this.id))return;const i=r.viewModel.view,g=r.viewModel.sketchViewModel;m=g.updateOnGraphicClick,g.updateOnGraphicClick=!1,e._lastActiveGraphics=[],e._featureFormHandle=o(e._featureFormHandle),e._visualVariableAttributes={rotation:null,size:null};const v="2d"===i.type?e._fadeExistingFeatures(r.creationInfo.layer):null,_=g.on("create",(async t=>{if("cancel"===t.state){if(e._preventDefaultActionOnCancel)return void(e._preventDefaultActionOnCancel=!1);if(e._lastActiveGraphics.length<1)return e._startCreating(w);const t=e._lastActiveGraphics.pop();return e._startUpdating(t,w)}if("complete"===t.state)return e._startUpdating(t.graphic,w)})),y=g.on("update",(async t=>{const o=t.graphics[0];if("complete"===t.state){if(o!==f&&(e._lastActiveGraphics.push(o),e._highlight(o)),f=null,"add"!==r.viewModel.attachmentsViewModel.mode&&"edit"!==r.viewModel.attachmentsViewModel.mode||r.viewModel.activeWorkflow.previous(),t.aborted&&e._preventDefaultActionOnCancel)return void(e._preventDefaultActionOnCancel=!1);const n=i.cursor;return i.cursor="progress",h.add([a((()=>i.cursor=n)),i.on("click",(e=>e.preventDefault()))],k),c((()=>!r.viewModel.featureFormViewModel.updating)).then((()=>{h.remove(k),e._startCreating(w)}))}if("start"===t.state){e._removeHighlight(o);const t=r.viewModel.attachmentsViewModel;"add"!==t.mode&&"edit"!==t.mode||r.viewModel.activeWorkflow.previous(),t.fileInfos.removeAll(),t.graphic=o,t.mode="view";(e._attachmentFileInfos.get(o)||[]).forEach((({file:e,form:a})=>t.addFile(e,a)))}await V(i,o,t,e._visualVariableAttributes,w);const s=o.attributes;if(n(e._visualVariableAttributes.rotation)){const{field:t}=e._visualVariableAttributes.rotation;r.viewModel.featureFormViewModel.setValue(t,s[t])}if(n(e._visualVariableAttributes.size)){const{field:t}=e._visualVariableAttributes.size;r.viewModel.featureFormViewModel.setValue(t,s[t])}})),M=g.on("delete",(async a=>{const i=a.graphics[0];t(e._lastActiveGraphics,i),f=i}));let b=null;const F=d((()=>{const e=g.snappingOptions.featureSources.find((e=>e.layer===r.creationInfo.layer));return{hasFeatureLayerSource:!!e,enabled:e?.enabled??!1}}),(({hasFeatureLayerSource:e,enabled:t})=>{const a=g.snappingOptions.featureSources;e?(s(b)&&(b=new p({layer:g.layer,enabled:t}),a.add(b)),b.enabled=t):(n(b)&&a.remove(b),b=l(b))}),u),A=i.on("immediate-click",(async t=>{const{results:a}=await i.hitTest(t,{include:g.layer}),r=a.find((e=>"graphic"===e.type));if(r){const t=r.graphic;if("transform"===g.activeTool||"reshape"===g.activeTool){if(g.updateGraphics.getItemAt(0)===t)return;await e.updatePendingFeature(t,w)}}})),I=d((()=>r.viewModel.attachmentsViewModel.mode),(e=>{"add"===e&&r.viewModel.activeWorkflow.go("adding-attachment"),"edit"===e&&r.viewModel.activeWorkflow.go("editing-attachment")}));await e._startCreating(w);const j={remove:()=>{o(e._featureFormHandle),_.remove(),y.remove(),M.remove(),F.remove(),n(b)&&g.snappingOptions.featureSources.remove(b),b=l(b),g.cancel(),A.remove(),I.remove(),o(v)}};h.add(j,this.id)},async tearDown(t){t.cancelled&&(r.viewModel.sketchViewModel.layer.removeAll(),h.remove([this.id,k]),r.viewModel.attachmentsViewModel.fileInfos.removeAll(),e._attachmentFileInfos.clear(),r.viewModel.sketchViewModel.updateOnGraphicClick=m)}}),"adding-attachment":()=>({id:"adding-attachment",parent:"creating-features",async setUp(){},async tearDown(){const{graphic:t,fileInfos:a}=r.viewModel.attachmentsViewModel;e._attachmentFileInfos.set(t,a.toArray()),r.viewModel.attachmentsViewModel.mode="view"}}),"editing-attachment":()=>({id:"editing-attachment",parent:"creating-features",async setUp(){},async tearDown(){const{graphic:t,fileInfos:a}=r.viewModel.attachmentsViewModel;e._attachmentFileInfos.set(t,a.toArray()),r.viewModel.attachmentsViewModel.mode="view"}})});return A(r,g)}_getAddAttachmentsData(e,t,a,i){const r=[];return t.forEach(((t,o)=>{if(!t.error){const n=e[o],s=i.get(n)||[];n.attributes[a.objectIdField]=t.objectId,s.forEach((({form:e})=>r.push({feature:n,attachment:e})))}})),r}_getAttachmentEditsWithGlobalIds(e,t,a){const i=[];return e.forEach(((r,o)=>{const n=a.get(r)||[];let l=r.attributes[t.globalIdField];s(l)&&(l=h(),e[o].attributes[t.globalIdField]=l),n.forEach((({file:e})=>i.push({feature:r,attachment:{globalId:h(),data:e}})))})),i.length?{addFeatures:e,addAttachments:i}:{addFeatures:e}}};j=I=e([f("esri.widgets.Editor.CreateFeaturesWorkflow")],j);const C=j;export{C as default};
package/widgets/Editor.js CHANGED
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.25/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../chunks/tslib.es6.js";import"../intl.js";import{HandleOwnerMixin as t}from"../core/HandleOwner.js";import s from"../core/Logger.js";import{isSome as a}from"../core/maybe.js";import{watch as i,on as n,when as o,initial as r}from"../core/reactiveUtils.js";import{property as l}from"../core/accessorSupport/decorators/property.js";import"../core/arrayUtils.js";import{cast as d}from"../core/accessorSupport/decorators/cast.js";import{subclass as c}from"../core/accessorSupport/decorators/subclass.js";import{getDisplayFieldName as p}from"../layers/support/fieldUtils.js";import h from"./Attachments.js";import u from"./FeatureForm.js";import m from"./FeatureTemplates.js";import g from"./Spinner.js";import v from"./Widget.js";import{workflowDeprecation as w}from"./Editor/deprecationUtils.js";import f from"./Editor/EditorViewModel.js";import{ItemList as _}from"./FeatureTemplates/ItemList.js";import{Heading as k,incrementHeadingLevel as b}from"./support/Heading.js";import y from"./support/SnappingControls.js";import{accessibleHandler as C}from"./support/decorators/accessibleHandler.js";import{messageBundle as M}from"./support/decorators/messageBundle.js";import{vmEvent as F}from"./support/decorators/vmEvent.js";import{tsx as A}from"./support/jsxFactory.js";import"./support/widgetUtils.js";import{substitute as W}from"../intl/substitute.js";const T={base:"esri-editor esri-widget esri-widget--panel",message:"esri-editor__message",controls:"esri-editor__controls",controlButton:"esri-editor__control-button",progressBar:"esri-editor__progress-bar",panelToolbar:"esri-editor__panel-toolbar",panelToolbarSnappingButton:"esri-editor__panel-toolbar__snapping-button",panelContent:"esri-editor__panel-content",panelContentMessage:"esri-editor__panel-content__message",panelContentSection:"esri-editor__panel-content__section",panelContentSectionGroup:"esri-editor__panel-content__section__group",snappingControlsPopover:"esri-editor__snapping-controls-popover",updateFeaturesActionButtons:"esri-editor__update-features-action-buttons",updateFeaturesActionButtonsButton:"esri-editor__update-features-action-buttons--button",featureTemplatesContainer:"esri-editor__feature-templates-container",promptContainer:"esri-editor__prompt",promptHeader:"esri-editor__prompt__header",promptHeading:"esri-editor__prompt__header__heading",promptMessage:"esri-editor__prompt__message",promptDivider:"esri-editor__prompt__divider",promptActions:"esri-editor__prompt__actions",warningIcon:"esri-icon-notice-triangle",widgetIcon:"esri-icon-edit",button:"esri-button",buttonDisabled:"esri-button--disabled",buttonSecondary:"esri-button--secondary",buttonTertiary:"esri-button--tertiary"},E={undoRedoButtons:!1,snappingControls:!0,snappingControlsElements:{header:!1,enabledToggle:!0,selfEnabledToggle:!0,featureEnabledToggle:!0,layerList:!0}};function S(e){e.focus()}const B="esri.widgets.Editor",L=s.getLogger(B);let P=class extends(t(v)){constructor(e,t){super(e,t),this._candidateCommitted=!1,this._featureForm=new u,this._stateStack=[],this._attachments=new h({visibleElements:{addSubmitButton:!1,cancelAddButton:!1,cancelUpdateButton:!1,deleteButton:!1,errorMessage:!1,progressBar:!1,updateButton:!1}}),this._featureTemplates=new m({enableListScroll:!1}),this._filterText="",this._prompt=null,this._spinner=new g,this._snappingButton=null,this._snappingPopover=null,this.useDeprecatedCreateWorkflow=!1,this.headingLevel=4,this.iconClass=T.widgetIcon,this.messages=null,this.messagesCommon=null,this.messagesTemplates=null,this.supportingWidgetDefaults=null,this.viewModel=new f,this.visibleElements={...E},this._setCandidateFeature=(e,t=!1)=>{if(this._candidateCommitted)return;const s=this._assertActiveUpdateWorkflow();s.data.edits.feature=e,t&&(s.next(),this._candidateCommitted=!0)},this._handleSave=this._handleSave.bind(this),this._handleBack=this._handleBack.bind(this),this._handleDone=this._handleDone.bind(this),this._handleDelete=this._handleDelete.bind(this),this._handleAdd=this._handleAdd.bind(this),this._handleEdit=this._handleEdit.bind(this),this._handleAttachmentAdd=this._handleAttachmentAdd.bind(this),this._handleAttachmentUpdate=this._handleAttachmentUpdate.bind(this),this._handleAttachmentDelete=this._handleAttachmentDelete.bind(this),this.EditorPanel=this.EditorPanel.bind(this)}initialize(){const{view:e,snappingOptions:t}=this;this._snappingControls=new y({snappingOptions:t,view:e,visibleElements:this.visibleElements.snappingControlsElements}),this.addHandles([i((()=>this.headingLevel),(e=>{this._featureForm.headingLevel=b(e),this._featureTemplates.headingLevel=b(e)}),r),this.viewModel.featureTemplatesViewModel.on("select",(({item:e})=>this.useDeprecatedCreateWorkflow?this.startCreateWorkflowAtFeatureCreation(e):this.startCreateFeaturesWorkflowAtFeatureCreation(e))),i((()=>this.viewModel.state),((e,t)=>{const s=this._stateStack.indexOf(e);-1===s?this._stateStack.push(t):this._stateStack.splice(s)})),i((()=>this.viewModel),(e=>{this._featureForm.viewModel=e?e.featureFormViewModel:null,this._attachments.viewModel=e?e.attachmentsViewModel:null,this._featureTemplates.viewModel=e?e.featureTemplatesViewModel:null,this._spinner.viewModel=e?e.spinnerViewModel:null}),r),i((()=>this.view),((e,t)=>{const s=`editor-${this.id}-spinner`;t&&t.ui.remove(this._spinner,s),e&&e.ui.add(this._spinner,{key:s,position:"manual"})}),r),n((()=>this.viewModel?.sketchViewModel),"create",(()=>{this.scheduleRender()})),n((()=>this.viewModel?.activeWorkflow),"cancel-request",(({controller:e})=>{const{messages:t,messagesCommon:s}=this;this._prompt={title:t.cancelRequestTitle,message:t.cancelRequestWarningMessage,context:"danger",actions:{primary:{label:s.form.yes,action:()=>{e.allow(),this._prompt=null}},secondary:{label:s.form.no,action:()=>(e.deny(),this._prompt=null)}}},this.scheduleRender()})),i((()=>this.supportingWidgetDefaults),(e=>{e&&(this._featureForm.set(e.featureForm),this._attachments.set(e.attachments),this._featureTemplates.set(e.featureTemplates),this.viewModel.sketchViewModel.set(e.sketch))}),r),i((()=>this._attachments?.error),(e=>{if(!e)return;const{messages:t,messagesCommon:s}=this;this._prompt={title:t.errorWarningTitle,message:e.message,context:"warning",actions:{primary:{label:s.form.ok,action:()=>{this._prompt=null}}}}})),i((()=>this.viewModel?.failures),(e=>{if(!e)return;const{messages:t}=this,[{error:s,retry:a,cancel:i}]=e;this._prompt={title:t.errorWarningTitle,message:W(t.errorWarningMessageTemplate,{errorMessage:s.message}),context:"warning",actions:{primary:{label:t.retry,action:()=>{a(),this._prompt=null}},secondary:{label:t.ignore,action:()=>(i(),this._prompt=null)}}}})),i((()=>this.viewModel?.state),(e=>{if("awaiting-feature-to-update"===e&&(this._filterText=""),"awaiting-update-feature-candidate"===e&&(this._candidateCommitted=!1),"editing-existing-feature"===e){const{activeWorkflow:e}=this.viewModel;this._featureForm.disabled="update"===e?.type&&!1===e?.data.editableItem.attributeUpdatesEnabled}})),i((()=>[this._attachments?.selectedFile,this._attachments?.submitting]),(()=>this.scheduleRender())),i((()=>this.viewModel?.activeWorkflow),(()=>this._featureForm.disabled=!1)),o((()=>!this.viewModel?.activeWorkflow),(()=>this._featureTemplates.filterText="")),n((()=>this.view),"key-down",(e=>{"Escape"===e.key&&this.viewModel?.activeWorkflow&&this._handleBack()}))])}destroy(){this._attachments.destroy(),this._featureForm.destroy(),this._featureTemplates.destroy(),this._snappingControls.destroy()}loadDependencies(){return Promise.all([import("@esri/calcite-components/dist/components/calcite-action.js"),import("@esri/calcite-components/dist/components/calcite-button.js"),import("@esri/calcite-components/dist/components/calcite-flow.js"),import("@esri/calcite-components/dist/components/calcite-icon.js"),import("@esri/calcite-components/dist/components/calcite-flow-item.js"),import("@esri/calcite-components/dist/components/calcite-popover.js"),import("@esri/calcite-components/dist/components/calcite-scrim.js")])}get activeWorkflow(){return this.viewModel.activeWorkflow}get allowedWorkflows(){return this.viewModel.allowedWorkflows}set allowedWorkflows(e){this.viewModel.allowedWorkflows=e}get label(){return this.messages?.widgetLabel??""}set label(e){this._overrideIfSome("label",e)}get labelOptions(){return this.viewModel.labelOptions}set labelOptions(e){this.viewModel.labelOptions=e}get layerInfos(){return this.viewModel.layerInfos}set layerInfos(e){this.viewModel.layerInfos=e}get snappingOptions(){return this.viewModel.snappingOptions}set snappingOptions(e){this.viewModel.snappingOptions=e}get tooltipOptions(){return this.viewModel.tooltipOptions}set tooltipOptions(e){this.viewModel.tooltipOptions=e}get view(){return this.viewModel.view}set view(e){this.viewModel.view=e}castVisibleElements(e){const t={...E,...e,snappingControlsElements:{...E.snappingControlsElements,...e?.snappingControlsElements}};return a(this._snappingControls)&&(this._snappingControls.visibleElements=t.snappingControlsElements),t}startCreateWorkflowAtFeatureTypeSelection(){return w(L,"startCreateWorkflowAtFeatureTypeSelection","startCreateFeaturesWorkflowAtFeatureTypeSelection"),this.viewModel.startCreateWorkflowAtFeatureTypeSelection()}startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.viewModel.startCreateFeaturesWorkflowAtFeatureTypeSelection()}startCreateWorkflowAtFeatureCreation(e){return w(L,"startCreateWorkflowAtFeatureCreation","startCreateFeaturesWorkflowAtFeatureCreation"),this.viewModel.startCreateWorkflowAtFeatureCreation(e)}startCreateFeaturesWorkflowAtFeatureCreation(e){return this.viewModel.startCreateFeaturesWorkflowAtFeatureCreation(e)}startCreateWorkflowAtFeatureEdit(e){return w(L,"startCreateWorkflowAtFeatureEdit"),this.viewModel.startCreateWorkflowAtFeatureEdit(e)}startUpdateWorkflowAtFeatureSelection(){return this.viewModel.startUpdateWorkflowAtFeatureSelection()}startUpdateWorkflowAtMultipleFeatureSelection(e){return this.viewModel.startUpdateWorkflowAtMultipleFeatureSelection(e)}startUpdateWorkflowAtFeatureEdit(e){return this.viewModel.startUpdateWorkflowAtFeatureEdit(e)}deleteFeatureFromWorkflow(){return this.viewModel.deleteFeatureFromWorkflow()}cancelWorkflow(e){return this.viewModel.cancelWorkflow(e)}render(){const{_attachments:e,_prompt:t,viewModel:s}=this;if(!s)return A("div",{class:T.base});const{state:i}=s,n=a(t)?A("calcite-scrim",null,this.renderPrompt(t)):null;return A("div",{class:T.base},s.syncing||e.submitting?this.renderProgressBar():null,A("calcite-flow",null,this._stateStack.map((e=>this.renderState(e))),this.renderState(i)),n)}renderState(e){switch(e){case"disabled":break;case"ready":return this.renderLanding(e);case"awaiting-feature-creation-info":return this.renderTemplates(e);case"creating-features":case"editing-new-feature":case"editing-existing-feature":return this.renderAttributeEditing(e);case"awaiting-feature-to-update":return this.renderFeatureUpdating(e);case"awaiting-update-feature-candidate":return this.renderFeatureList(e);case"awaiting-feature-to-create":return this.renderFeatureCreation(e);case"adding-attachment":return this.renderAttachmentAdding(e);case"editing-attachment":return this.renderAttachmentEditing(e)}return A("div",null)}isPanelActive(e){return this.viewModel.state===e}renderTemplates(e){const{EditorPanel:t,headingLevel:s,messages:a,messagesCommon:i,_handleBack:n,_snappingControls:o,viewModel:{sketchViewModel:r}}=this;return A(t,{active:this.isPanelActive(e),key:"templates-panel",handleBack:n,heading:a.selectTemplate,headingLevel:s,messages:a,messagesCommon:i,sketchViewModel:r,snappingControls:o},A("div",{class:T.panelContent},this._featureTemplates.render()))}renderAttributeEditing(e){const{activeWorkflow:t,EditorPanel:s,messages:a,messagesCommon:i,headingLevel:n,_handleBack:o,_snappingControls:r,viewModel:l}=this,{sketchViewModel:d}=l,c=l.featureFormViewModel;if("create-features"===t.type&&t.pendingFeatures.length<1)return this.renderFeatureCreation(e);const p="update"===t.type&&!t.data.edits.modified||l.syncing,h="update"===t.type?a.editFeature:a.createFeatures,u="update"===t.type?i.update:i.create,m="create-features"===t.type&&"create-new"===t.createFeatureState,g="update"===t.type&&t.data.editableItem.supports.includes("delete"),v=this._shouldShowAttachmentsForWorkflow(t),w=[{label:"create-features"===t.type&&t.numPendingFeatures>1?W(a.createFeaturesTemplate,{numFeatures:t.numPendingFeatures}):u,type:"primary",disabled:p,clickHandler:this._handleSave,width:g?"half":"full"}];g&&w.push({label:i.delete,type:"tertiary",clickHandler:this._handleDelete,disabled:l.syncing,appearance:"outline",width:"half"});const f=c.inputFields.every((e=>!e.visible))&&!v?this.renderMessage(W(a.clickToFinishTemplate,{button:u})):A("div",{class:T.panelContentSection},A("div",{class:T.panelContentSectionGroup},this._featureForm.render(),v?A("div",{key:"attachments"},A(k,{level:b(n)},a.attachments),this._attachments.render()):null));return A(s,{active:this.isPanelActive(e),key:"attribute-editing-panel",heading:h,headingLevel:n,handleBack:o,messages:a,messagesCommon:i,sketchViewModel:d,snappingControls:r},A("div",{class:T.panelContent},f,m?A("calcite-scrim",null):null),this.renderFooterActions(w))}renderAttachmentAdding(e){const{_attachments:t,EditorPanel:s,_handleBack:a,headingLevel:i,messages:n,messagesCommon:o,_snappingControls:r,viewModel:{sketchViewModel:l}}=this,d=[{label:t.submitting?o.cancel:o.add,disabled:t.submitting||!t.selectedFile,type:"primary",clickHandler:this._handleAttachmentAdd,width:"full"}];return A(s,{active:this.isPanelActive(e),key:"attachment-adding-panel",heading:n.addAttachment,headingLevel:i,handleBack:a,messages:n,messagesCommon:o,sketchViewModel:l,snappingControls:r},A("div",{class:T.panelContent},t.render()),this.renderFooterActions(d))}renderAttachmentEditing(e){const{_attachments:t,EditorPanel:s,_handleBack:a,headingLevel:i,messages:n,messagesCommon:o,_snappingControls:r,viewModel:{sketchViewModel:l}}=this,d=[{label:o.update,disabled:t.submitting||!t.selectedFile,type:"primary",clickHandler:this._handleAttachmentUpdate,width:"half"},{label:o.delete,disabled:t.submitting,type:"tertiary",clickHandler:this._handleAttachmentDelete,width:"half",appearance:"outline"}];return A(s,{active:this.isPanelActive(e),key:"attachment-editing-panel",heading:n.editAttachment,headingLevel:i,handleBack:a,messages:n,messagesCommon:o,sketchViewModel:l,snappingControls:r},A("div",{class:T.panelContent},t.render()),this.renderFooterActions(d))}renderFeatureUpdating(e){const{EditorPanel:t,_handleBack:s,headingLevel:a,messages:i,messagesCommon:n,_snappingControls:o,viewModel:{sketchViewModel:r}}=this;return A(t,{active:this.isPanelActive(e),key:"feature-updating-panel",heading:i.selectFeature,headingLevel:a,handleBack:s,messages:i,messagesCommon:n,sketchViewModel:r,snappingControls:o},A("div",{class:T.panelContent},this.renderMessage(i.selectFeatureToEdit)))}renderMessage(e){return A("div",{class:T.panelContentMessage},e)}renderFeatureCreation(e){const{EditorPanel:t,_handleBack:s,headingLevel:a,messages:i,messagesCommon:n,_snappingControls:o,viewModel:r}=this,{sketchViewModel:l}=r,d=r.sketchViewModel,c=this._assertActiveCreateWorkflow().data.creationInfo.layer,p=d.canUndo()&&d.createGraphic?d.createGraphic:null,h=this._getSketchingTip(c.geometryType,p);return A(t,{active:this.isPanelActive(e),key:"feature-creation-panel",heading:i.placeFeature,headingLevel:a,handleBack:s,messages:i,messagesCommon:n,sketchViewModel:l,snappingControls:o},A("div",{class:T.panelContent},this.renderMessage(h)))}renderFooterActions(e){return e.map((({type:e,disabled:t,class:s,...a},i)=>this.renderButton({class:this.classes(T.controlButton,"secondary"===e?T.buttonSecondary:"tertiary"===e?T.buttonTertiary:null,t?T.buttonDisabled:null,s),disabled:t??!1,key:i,slot:"footer-actions",...a})))}renderPrompt({title:e,message:t,context:s,actions:a}){const i=!!a.secondary,n=A("calcite-button",{appearance:"solid",color:"danger"===s?"red":"blue",width:i?"half":"full",onclick:a.primary.action,key:"prompt-primary-button",afterCreate:S},a.primary.label),o=i?A("calcite-button",{appearance:"clear",color:"danger"===s?"red":"blue",width:"half",onclick:a.secondary.action,key:"prompt-secondary-button"},a.secondary.label):null;return A("div",{class:`${T.promptContainer}--${s}`},A("div",{class:T.promptHeader},A("calcite-icon",{icon:"exclamation-mark-triangle"}),A(k,{class:T.promptHeading,level:this.headingLevel},e)),A("div",{class:T.promptMessage},t),A("div",{class:T.promptDivider}),A("div",{class:T.promptActions},o,n))}renderProgressBar(){return A("div",{class:this.classes(T.progressBar),key:"progress-bar"})}renderButton(e){const{disabled:t,class:s,key:a,clickHandler:i,label:n,...o}=e;return A("calcite-button",{class:s,disabled:t,key:a,onclick:i,type:"button",...o},n)}renderLanding(e){const{EditorPanel:t,headingLevel:s,messages:a,messagesCommon:i,_snappingControls:n,_featureTemplates:{viewModel:{numberOfFeatureTemplates:o}},viewModel:{canUpdate:r,sketchViewModel:l}}=this,d=!r&&0===o;return A(t,{active:this.isPanelActive(e),key:"landing-panel",heading:a.widgetLabel,headingLevel:s,showBackButton:!1,messages:a,messagesCommon:i,sketchViewModel:l,snappingControls:n},A("div",{class:T.panelContent},r?A("div",{key:"edit-actions",class:T.panelContentSection},this.renderUpdateActions()):void 0,o>0?A("div",{key:"create-actions",class:T.panelContentSection},this.renderCreateActions()):void 0,d?A("div",{key:"no-content",class:T.panelContentSection},a.noEditableLayers):void 0))}renderUpdateActions(){const{messages:e,messagesCommon:t}=this;return A("div",null,A(k,{level:b(this.headingLevel)},e.editFeatures),A("div",{class:T.updateFeaturesActionButtons},A("calcite-action",{text:t.select,textEnabled:!0,icon:"cursor",alignment:"start",class:T.updateFeaturesActionButtonsButton,onclick:this._handleEdit})))}renderCreateActions(){const{_featureTemplates:e,headingLevel:t,messages:s}=this;return A("div",null,A(k,{level:b(t)},s.createFeatures),A("div",{key:"templates",class:T.featureTemplatesContainer},e.render()))}renderFeatureList(e){const{EditorPanel:t,_handleBack:s,headingLevel:a,messages:i,messagesCommon:n,messagesTemplates:o,_snappingControls:r,viewModel:{editableItems:l,sketchViewModel:d}}=this,c=this._assertActiveUpdateWorkflow().data.candidates,p=W(i.multipleFeaturesTemplate,{total:c.length}),h=new Map;let u=0;c.map((e=>({label:this._getLabel(e),id:e.attributes[e.layer.objectIdField],data:e}))).filter((e=>{const{label:t,data:s}=e,a=this._filterText.toLowerCase(),{title:i}=s.layer,n=this.viewModel.editableItems.find((e=>e.layer===s.layer));return n.supports.includes("update")&&(!a||t.toLowerCase().includes(a)||i.toLowerCase().includes(a))})).forEach((e=>{u++;const t=e.data.layer;h.has(t)?h.get(t).items.push(e):h.set(t,{id:`${t.id}`,label:t.title,items:[e]})}));const m=l.filter((({layer:e})=>h.has(e))).map((({layer:e})=>h.get(e))).toArray(),g=u>10||this._filterText.length>0;return A(t,{active:this.isPanelActive(e),key:"feature-list",heading:p,headingLevel:a,handleBack:s,messages:i,messagesCommon:n,sketchViewModel:d,snappingControls:r},A("div",{class:T.panelContent},A("div",{class:T.panelContentSection},_({id:this.id,enableListScroll:!1,filterEnabled:g,filterText:this._filterText,items:m,messages:{filterPlaceholder:o.filterPlaceholder,noItems:o.noItems,noMatches:o.noMatches},onItemMouseEnter:({data:e})=>this._setCandidateFeature(e),onItemMouseLeave:()=>this._setCandidateFeature(null),onItemSelect:({data:e})=>this._setCandidateFeature(e,!0),onFilterChange:e=>this._filterText=e}))))}EditorPanel(e,...t){const{active:s,handleBack:a,heading:i,headingLevel:n,key:o,messages:r,messagesCommon:l,showBackButton:d,sketchViewModel:c,snappingControls:p}=e,{snappingControls:h,undoRedoButtons:u}=this.visibleElements;return A("calcite-flow-item",{bind:this,key:o,heading:i,headingLevel:n,showBackButton:d??!0,"intl-back":l.back,closable:!1,onCalciteFlowItemScroll:this._closeSnappingPopover,onCalciteFlowItemBackClick:a??null},A("div",{class:T.panelToolbar},h?[A("calcite-popover",{autoClose:s,afterCreate:this._setSnappingPopover,afterUpdate:this._setSnappingPopover,bind:this,label:r.snappingSettings,heading:r.snappingSettings,referenceElement:this._snappingButton||null,"overlay-positioning":"fixed",placement:"bottom"},A("div",{class:T.snappingControlsPopover},p.render())),A("calcite-button",{id:`${o}__snappingButton`,afterCreate:this._setSnappingButton,afterUpdate:this._setSnappingButton,bind:this,text:r.snapping,appearance:"transparent",color:"neutral",alignment:"icon-end-space-between","icon-start":"vertex-gps","icon-end":"caret-down",width:"full",class:T.panelToolbarSnappingButton,onkeydown:e=>{"Escape"===e.key&&this._closeSnappingPopover()}},r.snapping)]:null,u?[A("calcite-button",{key:"undo-button",text:l.undo,appearance:"transparent",color:"neutral",alignment:"center","icon-start":"undo",scale:"l",disabled:!c.canUndo(),onclick:c.undo.bind(c)}),A("calcite-button",{key:"redo-button",text:l.redo,appearance:"transparent",color:"neutral",alignment:"center","icon-start":"redo",scale:"l",disabled:!c.canRedo(),onclick:c.redo.bind(c)})]:null),t)}_closeSnappingPopover(){this._snappingPopover?.open&&this._snappingPopover.toggle()}_setSnappingPopover(e){this._snappingPopover=e}_setSnappingButton(e){this._snappingButton=e,this.scheduleRender()}_getSketchingTip(e,t){const{messages:s}=this;if("point"===e)return s.tips.clickToAddPoint;if("polygon"===e||"polyline"===e){if(!t)return s.tips.clickToStart;const a=t.geometry,i="polygon"===e?"rings":"paths",[n]=a[i];return"polygon"===e&&n<4?s.tips.clickToContinue:s.tips.clickToContinueThenDoubleClickToEnd}return s.tips.clickToAddFeature}_getLabel(e){const t=e.layer;if(!t)return null;const{objectIdField:s}=t,{attributes:a}=e,i=p(t);return i&&a[i]&&`${a[i]}`||W(this.messages.untitledFeatureTemplate,{id:a[s]})}_handleDelete(){const{messages:e,messagesCommon:t}=this;this._prompt={title:e.deleteWarningTitle,message:e.deleteWarningMessage,context:"danger",actions:{primary:{label:t.delete,action:()=>{this.viewModel.deleteFeatureFromWorkflow(),this._prompt=null}},secondary:{label:e.keepFeature,action:()=>this._prompt=null}}}}_handleSave(){const{featureFormViewModel:e}=this.viewModel;e.submit(),!e.submittable||e.validateContingencyConstraints(e.getValues(),{includeIncompleteViolations:!0}).length>0||this.viewModel.activeWorkflow.commit()}_handleAttachmentAdd(){const{_attachments:e}=this,{activeWorkflow:t}=this.viewModel;"create-features"===t.type?(e.addFile(),t.previous()):e.addAttachment().then((()=>t.previous()))}_handleAttachmentUpdate(){const{_attachments:e}=this,{activeWorkflow:t}=this.viewModel;"create-features"===t.type?(e.updateFile(),t.previous()):e.updateAttachment().then((()=>t.previous()))}_handleAttachmentDelete(){const{messages:e,messagesCommon:t}=this;this._prompt={title:e.deleteAttachmentWarningTitle,message:e.deleteAttachmentWarningMessage,context:"danger",actions:{primary:{label:t.delete,action:()=>{const{_attachments:e}=this,{activeWorkflow:t}=this.viewModel;"create-features"===t.type?(e.deleteFile(),t.previous(),this._prompt=null):e.deleteAttachment(e.viewModel.activeAttachmentInfo).then((()=>{t.previous(),this._prompt=null}))}},secondary:{label:e.keepAttachment,action:()=>this._prompt=null}}}}_handleAdd(){this.viewModel.canCreate}_handleEdit(){this.viewModel.canUpdate&&this.viewModel.startUpdateWorkflowAtFeatureSelection()}_handleDone(){this.viewModel.cancelWorkflow({force:!0})}async _handleBack(e){if(!this.activeWorkflow)return;const t=this.activeWorkflow;if(e?.stopPropagation(),this.viewModel.syncing)return;const s=()=>{t.hasPreviousStep?t.previous({cancelCurrentStep:!0}):this.viewModel.cancelWorkflow({force:!0})};if("create"===t.type||"create-features"===t.type&&t.numPendingFeatures>0||"editing-existing-feature"===t.stepId&&t.data.edits.modified){const{messages:e}=this,{type:a}=t,i="create"===a?e.cancelAddWarningMessage:e.cancelEditWarningMessage,n="create"===a?e.cancelAddTitle:e.cancelEditTitle,o="create"===a?e.continueAdding:e.continueEditing,r="create"===a?e.discardFeature:e.discardEdits;return this._prompt={title:n,message:i,context:"danger",actions:{primary:{label:r,action:()=>{this._prompt=null,s()}},secondary:{label:o,action:()=>this._prompt=null}}},void this.scheduleRender()}s()}_assertActiveCreateWorkflow(){const{type:e}=this.viewModel.activeWorkflow;if("create"===e||"create-features"===e)return this.viewModel.activeWorkflow;throw new Error("Expected activeWorkflow to be instance of CreateWorkflow or CreateFeaturesWorkflow")}_assertActiveUpdateWorkflow(){if("update"===this.viewModel.activeWorkflow.type)return this.viewModel.activeWorkflow;throw new Error("Expected activeWorkflow to be an UpdateWorkflow")}_shouldShowAttachmentsForWorkflow(e){const t="create-features"===e.type&&e.data.creationInfo;let s=!1;if(t){const{layerInfos:e}=this,{layer:a}=t,{data:i}=a.capabilities,n=e&&e.find((e=>e.layer===a));s="supportsAttachment"in i&&i.supportsAttachment&&(!n||!1!==n.allowAttachments)}return s||"update"===e.type&&e.data.editableItem.hasAttachments}};e([l()],P.prototype,"_attachments",void 0),e([l({readOnly:!0})],P.prototype,"activeWorkflow",null),e([l()],P.prototype,"allowedWorkflows",null),e([l()],P.prototype,"useDeprecatedCreateWorkflow",void 0),e([l()],P.prototype,"headingLevel",void 0),e([l()],P.prototype,"iconClass",void 0),e([l()],P.prototype,"label",null),e([l()],P.prototype,"labelOptions",null),e([l()],P.prototype,"layerInfos",null),e([l(),M("esri/widgets/Editor/t9n/Editor")],P.prototype,"messages",void 0),e([l(),M("esri/t9n/common")],P.prototype,"messagesCommon",void 0),e([l(),M("esri/widgets/FeatureTemplates/t9n/FeatureTemplates")],P.prototype,"messagesTemplates",void 0),e([l()],P.prototype,"snappingOptions",null),e([l()],P.prototype,"tooltipOptions",null),e([l()],P.prototype,"supportingWidgetDefaults",void 0),e([l()],P.prototype,"view",null),e([l(),F(["workflow-cancel","workflow-commit"])],P.prototype,"viewModel",void 0),e([l()],P.prototype,"visibleElements",void 0),e([d("visibleElements")],P.prototype,"castVisibleElements",null),e([C()],P.prototype,"_handleDelete",null),e([C()],P.prototype,"_handleAttachmentAdd",null),e([C()],P.prototype,"_handleAttachmentUpdate",null),e([C()],P.prototype,"_handleAttachmentDelete",null),e([C()],P.prototype,"_handleAdd",null),e([C()],P.prototype,"_handleEdit",null),e([C()],P.prototype,"_handleDone",null),P=e([c(B)],P);const j=P;export{j as default};
5
+ import{_ as e}from"../chunks/tslib.es6.js";import"../intl.js";import{HandleOwnerMixin as t}from"../core/HandleOwner.js";import s from"../core/Logger.js";import{isSome as a}from"../core/maybe.js";import{watch as i,on as n,when as o,initial as r}from"../core/reactiveUtils.js";import{property as l}from"../core/accessorSupport/decorators/property.js";import"../core/arrayUtils.js";import{cast as d}from"../core/accessorSupport/decorators/cast.js";import{subclass as c}from"../core/accessorSupport/decorators/subclass.js";import{getDisplayFieldName as p}from"../layers/support/fieldUtils.js";import h from"./Attachments.js";import u from"./FeatureForm.js";import m from"./FeatureTemplates.js";import g from"./Spinner.js";import v from"./Widget.js";import{workflowDeprecation as w}from"./Editor/deprecationUtils.js";import f from"./Editor/EditorViewModel.js";import{ItemList as _}from"./FeatureTemplates/ItemList.js";import{Heading as k,incrementHeadingLevel as b}from"./support/Heading.js";import y from"./support/SnappingControls.js";import{accessibleHandler as C}from"./support/decorators/accessibleHandler.js";import{messageBundle as M}from"./support/decorators/messageBundle.js";import{vmEvent as F}from"./support/decorators/vmEvent.js";import{tsx as A}from"./support/jsxFactory.js";import"./support/widgetUtils.js";import{substitute as W}from"../intl/substitute.js";const T={base:"esri-editor esri-widget esri-widget--panel",message:"esri-editor__message",controls:"esri-editor__controls",controlButton:"esri-editor__control-button",progressBar:"esri-editor__progress-bar",panelToolbar:"esri-editor__panel-toolbar",panelToolbarSnappingButton:"esri-editor__panel-toolbar__snapping-button",panelContent:"esri-editor__panel-content",panelContentMessage:"esri-editor__panel-content__message",panelContentSection:"esri-editor__panel-content__section",panelContentSectionGroup:"esri-editor__panel-content__section__group",snappingControlsPopover:"esri-editor__snapping-controls-popover",updateFeaturesActionButtons:"esri-editor__update-features-action-buttons",updateFeaturesActionButtonsButton:"esri-editor__update-features-action-buttons--button",featureTemplatesContainer:"esri-editor__feature-templates-container",promptContainer:"esri-editor__prompt",promptHeader:"esri-editor__prompt__header",promptHeading:"esri-editor__prompt__header__heading",promptMessage:"esri-editor__prompt__message",promptDivider:"esri-editor__prompt__divider",promptActions:"esri-editor__prompt__actions",warningIcon:"esri-icon-notice-triangle",widgetIcon:"esri-icon-edit",button:"esri-button",buttonDisabled:"esri-button--disabled",buttonSecondary:"esri-button--secondary",buttonTertiary:"esri-button--tertiary"},E={undoRedoButtons:!1,snappingControls:!0,snappingControlsElements:{header:!1,enabledToggle:!0,selfEnabledToggle:!0,featureEnabledToggle:!0,layerList:!0}};function S(e){e.focus()}const B="esri.widgets.Editor",L=s.getLogger(B);let P=class extends(t(v)){constructor(e,t){super(e,t),this._candidateCommitted=!1,this._featureForm=new u,this._stateStack=[],this._attachments=new h({visibleElements:{addSubmitButton:!1,cancelAddButton:!1,cancelUpdateButton:!1,deleteButton:!1,errorMessage:!1,progressBar:!1,updateButton:!1}}),this._featureTemplates=new m({enableListScroll:!1}),this._filterText="",this._prompt=null,this._spinner=new g,this._snappingButton=null,this._snappingPopover=null,this.useDeprecatedCreateWorkflow=!1,this.headingLevel=4,this.iconClass=T.widgetIcon,this.messages=null,this.messagesCommon=null,this.messagesTemplates=null,this.supportingWidgetDefaults=null,this.viewModel=new f,this.visibleElements={...E},this._setCandidateFeature=(e,t=!1)=>{if(this._candidateCommitted)return;const s=this._assertActiveUpdateWorkflow();s.data.edits.feature=e,t&&(s.next(),this._candidateCommitted=!0)},this._handleSave=this._handleSave.bind(this),this._handleBack=this._handleBack.bind(this),this._handleDone=this._handleDone.bind(this),this._handleDelete=this._handleDelete.bind(this),this._handleAdd=this._handleAdd.bind(this),this._handleEdit=this._handleEdit.bind(this),this._handleAttachmentAdd=this._handleAttachmentAdd.bind(this),this._handleAttachmentUpdate=this._handleAttachmentUpdate.bind(this),this._handleAttachmentDelete=this._handleAttachmentDelete.bind(this),this.EditorPanel=this.EditorPanel.bind(this)}initialize(){const{view:e,snappingOptions:t}=this;this._snappingControls=new y({snappingOptions:t,view:e,visibleElements:this.visibleElements.snappingControlsElements}),this.addHandles([i((()=>this.headingLevel),(e=>{this._featureForm.headingLevel=b(e),this._featureTemplates.headingLevel=b(e)}),r),this.viewModel.featureTemplatesViewModel.on("select",(({item:e})=>this.useDeprecatedCreateWorkflow?this.startCreateWorkflowAtFeatureCreation(e):this.startCreateFeaturesWorkflowAtFeatureCreation(e))),i((()=>this.viewModel.state),((e,t)=>{const s=this._stateStack.indexOf(e);-1===s?this._stateStack.push(t):this._stateStack.splice(s)})),i((()=>this.viewModel),(e=>{this._featureForm.viewModel=e?e.featureFormViewModel:null,this._attachments.viewModel=e?e.attachmentsViewModel:null,this._featureTemplates.viewModel=e?e.featureTemplatesViewModel:null,this._spinner.viewModel=e?e.spinnerViewModel:null}),r),i((()=>this.view),((e,t)=>{const s=`editor-${this.id}-spinner`;t&&t.ui.remove(this._spinner,s),e&&e.ui.add(this._spinner,{key:s,position:"manual"})}),r),n((()=>this.viewModel?.sketchViewModel),"create",(()=>{this.scheduleRender()})),n((()=>this.viewModel?.activeWorkflow),"cancel-request",(({controller:e})=>{const{messages:t,messagesCommon:s}=this;this._prompt={title:t.cancelRequestTitle,message:t.cancelRequestWarningMessage,context:"danger",actions:{primary:{label:s.form.yes,action:()=>{e.allow(),this._prompt=null}},secondary:{label:s.form.no,action:()=>(e.deny(),this._prompt=null)}}},this.scheduleRender()})),i((()=>this.supportingWidgetDefaults),(e=>{e&&(this._featureForm.set(e.featureForm),this._attachments.set(e.attachments),this._featureTemplates.set(e.featureTemplates),this.viewModel.sketchViewModel.set(e.sketch))}),r),i((()=>this._attachments?.error),(e=>{if(!e)return;const{messages:t,messagesCommon:s}=this;this._prompt={title:t.errorWarningTitle,message:e.message,context:"warning",actions:{primary:{label:s.form.ok,action:()=>{this._prompt=null}}}}})),i((()=>this.viewModel?.failures),(e=>{if(!e)return;const{messages:t}=this,[{error:s,retry:a,cancel:i}]=e;this._prompt={title:t.errorWarningTitle,message:W(t.errorWarningMessageTemplate,{errorMessage:s.message}),context:"warning",actions:{primary:{label:t.retry,action:()=>{a(),this._prompt=null}},secondary:{label:t.ignore,action:()=>(i(),this._prompt=null)}}}})),i((()=>this.viewModel?.state),(e=>{if("awaiting-feature-to-update"===e&&(this._filterText=""),"awaiting-update-feature-candidate"===e&&(this._candidateCommitted=!1),"editing-existing-feature"===e){const{activeWorkflow:e}=this.viewModel;this._featureForm.disabled="update"===e?.type&&!1===e?.data.editableItem.attributeUpdatesEnabled}})),i((()=>[this._attachments?.selectedFile,this._attachments?.submitting]),(()=>this.scheduleRender())),i((()=>this.viewModel?.activeWorkflow),(()=>this._featureForm.disabled=!1)),o((()=>!this.viewModel?.activeWorkflow),(()=>this._featureTemplates.filterText="")),n((()=>this.view),"key-down",(e=>{"Escape"===e.key&&this.viewModel?.activeWorkflow&&this._handleBack()}))])}destroy(){this._attachments.destroy(),this._featureForm.destroy(),this._featureTemplates.destroy(),this._snappingControls.destroy()}loadDependencies(){return Promise.all([import("@esri/calcite-components/dist/components/calcite-action.js"),import("@esri/calcite-components/dist/components/calcite-button.js"),import("@esri/calcite-components/dist/components/calcite-flow.js"),import("@esri/calcite-components/dist/components/calcite-icon.js"),import("@esri/calcite-components/dist/components/calcite-flow-item.js"),import("@esri/calcite-components/dist/components/calcite-popover.js"),import("@esri/calcite-components/dist/components/calcite-scrim.js")])}get activeWorkflow(){return this.viewModel.activeWorkflow}get allowedWorkflows(){return this.viewModel.allowedWorkflows}set allowedWorkflows(e){this.viewModel.allowedWorkflows=e}get label(){return this.messages?.widgetLabel??""}set label(e){this._overrideIfSome("label",e)}get labelOptions(){return this.viewModel.labelOptions}set labelOptions(e){this.viewModel.labelOptions=e}get layerInfos(){return this.viewModel.layerInfos}set layerInfos(e){this.viewModel.layerInfos=e}get snappingOptions(){return this.viewModel.snappingOptions}set snappingOptions(e){this.viewModel.snappingOptions=e}get tooltipOptions(){return this.viewModel.tooltipOptions}set tooltipOptions(e){this.viewModel.tooltipOptions=e}get view(){return this.viewModel.view}set view(e){this.viewModel.view=e}castVisibleElements(e){const t={...E,...e,snappingControlsElements:{...E.snappingControlsElements,...e?.snappingControlsElements}};return a(this._snappingControls)&&(this._snappingControls.visibleElements=t.snappingControlsElements),t}startCreateWorkflowAtFeatureTypeSelection(){return w(L,"startCreateWorkflowAtFeatureTypeSelection","startCreateFeaturesWorkflowAtFeatureTypeSelection"),this.viewModel.startCreateWorkflowAtFeatureTypeSelection()}startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.viewModel.startCreateFeaturesWorkflowAtFeatureTypeSelection()}startCreateWorkflowAtFeatureCreation(e){return w(L,"startCreateWorkflowAtFeatureCreation","startCreateFeaturesWorkflowAtFeatureCreation"),this.viewModel.startCreateWorkflowAtFeatureCreation(e)}startCreateFeaturesWorkflowAtFeatureCreation(e){return this.viewModel.startCreateFeaturesWorkflowAtFeatureCreation(e)}startCreateWorkflowAtFeatureEdit(e){return w(L,"startCreateWorkflowAtFeatureEdit"),this.viewModel.startCreateWorkflowAtFeatureEdit(e)}startUpdateWorkflowAtFeatureSelection(){return this.viewModel.startUpdateWorkflowAtFeatureSelection()}startUpdateWorkflowAtMultipleFeatureSelection(e){return this.viewModel.startUpdateWorkflowAtMultipleFeatureSelection(e)}startUpdateWorkflowAtFeatureEdit(e){return this.viewModel.startUpdateWorkflowAtFeatureEdit(e)}deleteFeatureFromWorkflow(){return this.viewModel.deleteFeatureFromWorkflow()}cancelWorkflow(e){return this.viewModel.cancelWorkflow(e)}render(){const{_attachments:e,_prompt:t,viewModel:s}=this;if(!s)return A("div",{class:T.base});const{state:i}=s,n=a(t)?A("calcite-scrim",null,this.renderPrompt(t)):null;return A("div",{class:T.base},s.syncing||e.submitting?this.renderProgressBar():null,A("calcite-flow",null,this._stateStack.map((e=>this.renderState(e))),this.renderState(i)),n)}renderState(e){switch(e){case"disabled":break;case"ready":return this.renderLanding(e);case"awaiting-feature-creation-info":return this.renderTemplates(e);case"creating-features":case"editing-new-feature":case"editing-existing-feature":return this.renderAttributeEditing(e);case"awaiting-feature-to-update":return this.renderFeatureUpdating(e);case"awaiting-update-feature-candidate":return this.renderFeatureList(e);case"awaiting-feature-to-create":return this.renderFeatureCreation(e);case"adding-attachment":return this.renderAttachmentAdding(e);case"editing-attachment":return this.renderAttachmentEditing(e)}return A("div",null)}isPanelActive(e){return this.viewModel.state===e}renderTemplates(e){const{EditorPanel:t,headingLevel:s,messages:a,messagesCommon:i,_handleBack:n,_snappingControls:o,viewModel:{sketchViewModel:r}}=this;return A(t,{active:this.isPanelActive(e),key:"templates-panel",handleBack:n,heading:a.selectTemplate,headingLevel:s,messages:a,messagesCommon:i,sketchViewModel:r,snappingControls:o},A("div",{class:T.panelContent},this._featureTemplates.render()))}renderAttributeEditing(e){const{activeWorkflow:t,EditorPanel:s,messages:a,messagesCommon:i,headingLevel:n,_handleBack:o,_snappingControls:r,viewModel:l}=this,{sketchViewModel:d}=l,c=l.featureFormViewModel;if("create-features"===t.type&&t.pendingFeatures.length<1)return this.renderFeatureCreation(e);const p="update"===t.type&&!t.data.edits.modified||l.syncing||c.updating,h="update"===t.type?a.editFeature:a.createFeatures,u="update"===t.type?i.update:i.create,m="create-features"===t.type&&"create-new"===t.createFeatureState,g="update"===t.type&&t.data.editableItem.supports.includes("delete"),v=this._shouldShowAttachmentsForWorkflow(t),w=[{label:"create-features"===t.type&&t.numPendingFeatures>1?W(a.createFeaturesTemplate,{numFeatures:t.numPendingFeatures}):u,type:"primary",disabled:p,clickHandler:this._handleSave,width:g?"half":"full"}];g&&w.push({label:i.delete,type:"tertiary",clickHandler:this._handleDelete,disabled:l.syncing,appearance:"outline",width:"half"});const f=c.inputFields.every((e=>!e.visible))&&!v?this.renderMessage(W(a.clickToFinishTemplate,{button:u})):A("div",{class:T.panelContentSection},A("div",{class:T.panelContentSectionGroup},this._featureForm.render(),v?A("div",{key:"attachments"},A(k,{level:b(n)},a.attachments),this._attachments.render()):null));return A(s,{active:this.isPanelActive(e),key:"attribute-editing-panel",heading:h,headingLevel:n,handleBack:o,messages:a,messagesCommon:i,sketchViewModel:d,snappingControls:r},A("div",{class:T.panelContent},f,m?A("calcite-scrim",null):null),this.renderFooterActions(w))}renderAttachmentAdding(e){const{_attachments:t,EditorPanel:s,_handleBack:a,headingLevel:i,messages:n,messagesCommon:o,_snappingControls:r,viewModel:{sketchViewModel:l}}=this,d=[{label:t.submitting?o.cancel:o.add,disabled:t.submitting||!t.selectedFile,type:"primary",clickHandler:this._handleAttachmentAdd,width:"full"}];return A(s,{active:this.isPanelActive(e),key:"attachment-adding-panel",heading:n.addAttachment,headingLevel:i,handleBack:a,messages:n,messagesCommon:o,sketchViewModel:l,snappingControls:r},A("div",{class:T.panelContent},t.render()),this.renderFooterActions(d))}renderAttachmentEditing(e){const{_attachments:t,EditorPanel:s,_handleBack:a,headingLevel:i,messages:n,messagesCommon:o,_snappingControls:r,viewModel:{sketchViewModel:l}}=this,d=[{label:o.update,disabled:t.submitting||!t.selectedFile,type:"primary",clickHandler:this._handleAttachmentUpdate,width:"half"},{label:o.delete,disabled:t.submitting,type:"tertiary",clickHandler:this._handleAttachmentDelete,width:"half",appearance:"outline"}];return A(s,{active:this.isPanelActive(e),key:"attachment-editing-panel",heading:n.editAttachment,headingLevel:i,handleBack:a,messages:n,messagesCommon:o,sketchViewModel:l,snappingControls:r},A("div",{class:T.panelContent},t.render()),this.renderFooterActions(d))}renderFeatureUpdating(e){const{EditorPanel:t,_handleBack:s,headingLevel:a,messages:i,messagesCommon:n,_snappingControls:o,viewModel:{sketchViewModel:r}}=this;return A(t,{active:this.isPanelActive(e),key:"feature-updating-panel",heading:i.selectFeature,headingLevel:a,handleBack:s,messages:i,messagesCommon:n,sketchViewModel:r,snappingControls:o},A("div",{class:T.panelContent},this.renderMessage(i.selectFeatureToEdit)))}renderMessage(e){return A("div",{class:T.panelContentMessage},e)}renderFeatureCreation(e){const{EditorPanel:t,_handleBack:s,headingLevel:a,messages:i,messagesCommon:n,_snappingControls:o,viewModel:r}=this,{sketchViewModel:l}=r,d=r.sketchViewModel,c=this._assertActiveCreateWorkflow().data.creationInfo.layer,p=d.canUndo()&&d.createGraphic?d.createGraphic:null,h=this._getSketchingTip(c.geometryType,p);return A(t,{active:this.isPanelActive(e),key:"feature-creation-panel",heading:i.placeFeature,headingLevel:a,handleBack:s,messages:i,messagesCommon:n,sketchViewModel:l,snappingControls:o},A("div",{class:T.panelContent},this.renderMessage(h)))}renderFooterActions(e){return e.map((({type:e,disabled:t,class:s,...a},i)=>this.renderButton({class:this.classes(T.controlButton,"secondary"===e?T.buttonSecondary:"tertiary"===e?T.buttonTertiary:null,t?T.buttonDisabled:null,s),disabled:t??!1,key:i,slot:"footer-actions",...a})))}renderPrompt({title:e,message:t,context:s,actions:a}){const i=!!a.secondary,n=A("calcite-button",{appearance:"solid",color:"danger"===s?"red":"blue",width:i?"half":"full",onclick:a.primary.action,key:"prompt-primary-button",afterCreate:S},a.primary.label),o=i?A("calcite-button",{appearance:"clear",color:"danger"===s?"red":"blue",width:"half",onclick:a.secondary.action,key:"prompt-secondary-button"},a.secondary.label):null;return A("div",{class:`${T.promptContainer}--${s}`},A("div",{class:T.promptHeader},A("calcite-icon",{icon:"exclamation-mark-triangle"}),A(k,{class:T.promptHeading,level:this.headingLevel},e)),A("div",{class:T.promptMessage},t),A("div",{class:T.promptDivider}),A("div",{class:T.promptActions},o,n))}renderProgressBar(){return A("div",{class:this.classes(T.progressBar),key:"progress-bar"})}renderButton(e){const{disabled:t,class:s,key:a,clickHandler:i,label:n,...o}=e;return A("calcite-button",{class:s,disabled:t,key:a,onclick:i,type:"button",...o},n)}renderLanding(e){const{EditorPanel:t,headingLevel:s,messages:a,messagesCommon:i,_snappingControls:n,_featureTemplates:{viewModel:{numberOfFeatureTemplates:o}},viewModel:{canUpdate:r,sketchViewModel:l}}=this,d=!r&&0===o;return A(t,{active:this.isPanelActive(e),key:"landing-panel",heading:a.widgetLabel,headingLevel:s,showBackButton:!1,messages:a,messagesCommon:i,sketchViewModel:l,snappingControls:n},A("div",{class:T.panelContent},r?A("div",{key:"edit-actions",class:T.panelContentSection},this.renderUpdateActions()):void 0,o>0?A("div",{key:"create-actions",class:T.panelContentSection},this.renderCreateActions()):void 0,d?A("div",{key:"no-content",class:T.panelContentSection},a.noEditableLayers):void 0))}renderUpdateActions(){const{messages:e,messagesCommon:t}=this;return A("div",null,A(k,{level:b(this.headingLevel)},e.editFeatures),A("div",{class:T.updateFeaturesActionButtons},A("calcite-action",{text:t.select,textEnabled:!0,icon:"cursor",alignment:"start",class:T.updateFeaturesActionButtonsButton,onclick:this._handleEdit})))}renderCreateActions(){const{_featureTemplates:e,headingLevel:t,messages:s}=this;return A("div",null,A(k,{level:b(t)},s.createFeatures),A("div",{key:"templates",class:T.featureTemplatesContainer},e.render()))}renderFeatureList(e){const{EditorPanel:t,_handleBack:s,headingLevel:a,messages:i,messagesCommon:n,messagesTemplates:o,_snappingControls:r,viewModel:{editableItems:l,sketchViewModel:d}}=this,c=this._assertActiveUpdateWorkflow().data.candidates,p=W(i.multipleFeaturesTemplate,{total:c.length}),h=new Map;let u=0;c.map((e=>({label:this._getLabel(e),id:e.attributes[e.layer.objectIdField],data:e}))).filter((e=>{const{label:t,data:s}=e,a=this._filterText.toLowerCase(),{title:i}=s.layer,n=this.viewModel.editableItems.find((e=>e.layer===s.layer));return n.supports.includes("update")&&(!a||t.toLowerCase().includes(a)||i.toLowerCase().includes(a))})).forEach((e=>{u++;const t=e.data.layer;h.has(t)?h.get(t).items.push(e):h.set(t,{id:`${t.id}`,label:t.title,items:[e]})}));const m=l.filter((({layer:e})=>h.has(e))).map((({layer:e})=>h.get(e))).toArray(),g=u>10||this._filterText.length>0;return A(t,{active:this.isPanelActive(e),key:"feature-list",heading:p,headingLevel:a,handleBack:s,messages:i,messagesCommon:n,sketchViewModel:d,snappingControls:r},A("div",{class:T.panelContent},A("div",{class:T.panelContentSection},_({id:this.id,enableListScroll:!1,filterEnabled:g,filterText:this._filterText,items:m,messages:{filterPlaceholder:o.filterPlaceholder,noItems:o.noItems,noMatches:o.noMatches},onItemMouseEnter:({data:e})=>this._setCandidateFeature(e),onItemMouseLeave:()=>this._setCandidateFeature(null),onItemSelect:({data:e})=>this._setCandidateFeature(e,!0),onFilterChange:e=>this._filterText=e}))))}EditorPanel(e,...t){const{active:s,handleBack:a,heading:i,headingLevel:n,key:o,messages:r,messagesCommon:l,showBackButton:d,sketchViewModel:c,snappingControls:p}=e,{snappingControls:h,undoRedoButtons:u}=this.visibleElements;return A("calcite-flow-item",{bind:this,key:o,heading:i,headingLevel:n,showBackButton:d??!0,"intl-back":l.back,closable:!1,onCalciteFlowItemScroll:this._closeSnappingPopover,onCalciteFlowItemBackClick:a??null},A("div",{class:T.panelToolbar},h?[A("calcite-popover",{autoClose:s,afterCreate:this._setSnappingPopover,afterUpdate:this._setSnappingPopover,bind:this,label:r.snappingSettings,heading:r.snappingSettings,referenceElement:this._snappingButton||null,"overlay-positioning":"fixed",placement:"bottom"},A("div",{class:T.snappingControlsPopover},p.render())),A("calcite-button",{id:`${o}__snappingButton`,afterCreate:this._setSnappingButton,afterUpdate:this._setSnappingButton,bind:this,text:r.snapping,appearance:"transparent",color:"neutral",alignment:"icon-end-space-between","icon-start":"vertex-gps","icon-end":"caret-down",width:"full",class:T.panelToolbarSnappingButton,onkeydown:e=>{"Escape"===e.key&&this._closeSnappingPopover()}},r.snapping)]:null,u?[A("calcite-button",{key:"undo-button",text:l.undo,appearance:"transparent",color:"neutral",alignment:"center","icon-start":"undo",scale:"l",disabled:!c.canUndo(),onclick:c.undo.bind(c)}),A("calcite-button",{key:"redo-button",text:l.redo,appearance:"transparent",color:"neutral",alignment:"center","icon-start":"redo",scale:"l",disabled:!c.canRedo(),onclick:c.redo.bind(c)})]:null),t)}_closeSnappingPopover(){this._snappingPopover?.open&&this._snappingPopover.toggle()}_setSnappingPopover(e){this._snappingPopover=e}_setSnappingButton(e){this._snappingButton=e,this.scheduleRender()}_getSketchingTip(e,t){const{messages:s}=this;if("point"===e)return s.tips.clickToAddPoint;if("polygon"===e||"polyline"===e){if(!t)return s.tips.clickToStart;const a=t.geometry,i="polygon"===e?"rings":"paths",[n]=a[i];return"polygon"===e&&n<4?s.tips.clickToContinue:s.tips.clickToContinueThenDoubleClickToEnd}return s.tips.clickToAddFeature}_getLabel(e){const t=e.layer;if(!t)return null;const{objectIdField:s}=t,{attributes:a}=e,i=p(t);return i&&a[i]&&`${a[i]}`||W(this.messages.untitledFeatureTemplate,{id:a[s]})}_handleDelete(){const{messages:e,messagesCommon:t}=this;this._prompt={title:e.deleteWarningTitle,message:e.deleteWarningMessage,context:"danger",actions:{primary:{label:t.delete,action:()=>{this.viewModel.deleteFeatureFromWorkflow(),this._prompt=null}},secondary:{label:e.keepFeature,action:()=>this._prompt=null}}}}_handleSave(){const{featureFormViewModel:e}=this.viewModel;e.submit(),!e.submittable||e.validateContingencyConstraints(e.getValues(),{includeIncompleteViolations:!0}).length>0||this.viewModel.activeWorkflow.commit()}_handleAttachmentAdd(){const{_attachments:e}=this,{activeWorkflow:t}=this.viewModel;"create-features"===t.type?(e.addFile(),t.previous()):e.addAttachment().then((()=>t.previous()))}_handleAttachmentUpdate(){const{_attachments:e}=this,{activeWorkflow:t}=this.viewModel;"create-features"===t.type?(e.updateFile(),t.previous()):e.updateAttachment().then((()=>t.previous()))}_handleAttachmentDelete(){const{messages:e,messagesCommon:t}=this;this._prompt={title:e.deleteAttachmentWarningTitle,message:e.deleteAttachmentWarningMessage,context:"danger",actions:{primary:{label:t.delete,action:()=>{const{_attachments:e}=this,{activeWorkflow:t}=this.viewModel;"create-features"===t.type?(e.deleteFile(),t.previous(),this._prompt=null):e.deleteAttachment(e.viewModel.activeAttachmentInfo).then((()=>{t.previous(),this._prompt=null}))}},secondary:{label:e.keepAttachment,action:()=>this._prompt=null}}}}_handleAdd(){this.viewModel.canCreate}_handleEdit(){this.viewModel.canUpdate&&this.viewModel.startUpdateWorkflowAtFeatureSelection()}_handleDone(){this.viewModel.cancelWorkflow({force:!0})}async _handleBack(e){if(!this.activeWorkflow)return;const t=this.activeWorkflow;if(e?.stopPropagation(),this.viewModel.syncing)return;const s=()=>{t.hasPreviousStep?t.previous({cancelCurrentStep:!0}):this.viewModel.cancelWorkflow({force:!0})};if("create"===t.type||"create-features"===t.type&&t.numPendingFeatures>0||"editing-existing-feature"===t.stepId&&t.data.edits.modified){const{messages:e}=this,{type:a}=t,i="create"===a?e.cancelAddWarningMessage:e.cancelEditWarningMessage,n="create"===a?e.cancelAddTitle:e.cancelEditTitle,o="create"===a?e.continueAdding:e.continueEditing,r="create"===a?e.discardFeature:e.discardEdits;return this._prompt={title:n,message:i,context:"danger",actions:{primary:{label:r,action:()=>{this._prompt=null,s()}},secondary:{label:o,action:()=>this._prompt=null}}},void this.scheduleRender()}s()}_assertActiveCreateWorkflow(){const{type:e}=this.viewModel.activeWorkflow;if("create"===e||"create-features"===e)return this.viewModel.activeWorkflow;throw new Error("Expected activeWorkflow to be instance of CreateWorkflow or CreateFeaturesWorkflow")}_assertActiveUpdateWorkflow(){if("update"===this.viewModel.activeWorkflow.type)return this.viewModel.activeWorkflow;throw new Error("Expected activeWorkflow to be an UpdateWorkflow")}_shouldShowAttachmentsForWorkflow(e){const t="create-features"===e.type&&e.data.creationInfo;let s=!1;if(t){const{layerInfos:e}=this,{layer:a}=t,{data:i}=a.capabilities,n=e&&e.find((e=>e.layer===a));s="supportsAttachment"in i&&i.supportsAttachment&&(!n||!1!==n.allowAttachments)}return s||"update"===e.type&&e.data.editableItem.hasAttachments}};e([l()],P.prototype,"_attachments",void 0),e([l({readOnly:!0})],P.prototype,"activeWorkflow",null),e([l()],P.prototype,"allowedWorkflows",null),e([l()],P.prototype,"useDeprecatedCreateWorkflow",void 0),e([l()],P.prototype,"headingLevel",void 0),e([l()],P.prototype,"iconClass",void 0),e([l()],P.prototype,"label",null),e([l()],P.prototype,"labelOptions",null),e([l()],P.prototype,"layerInfos",null),e([l(),M("esri/widgets/Editor/t9n/Editor")],P.prototype,"messages",void 0),e([l(),M("esri/t9n/common")],P.prototype,"messagesCommon",void 0),e([l(),M("esri/widgets/FeatureTemplates/t9n/FeatureTemplates")],P.prototype,"messagesTemplates",void 0),e([l()],P.prototype,"snappingOptions",null),e([l()],P.prototype,"tooltipOptions",null),e([l()],P.prototype,"supportingWidgetDefaults",void 0),e([l()],P.prototype,"view",null),e([l(),F(["workflow-cancel","workflow-commit"])],P.prototype,"viewModel",void 0),e([l()],P.prototype,"visibleElements",void 0),e([d("visibleElements")],P.prototype,"castVisibleElements",null),e([C()],P.prototype,"_handleDelete",null),e([C()],P.prototype,"_handleAttachmentAdd",null),e([C()],P.prototype,"_handleAttachmentUpdate",null),e([C()],P.prototype,"_handleAttachmentDelete",null),e([C()],P.prototype,"_handleAdd",null),e([C()],P.prototype,"_handleEdit",null),e([C()],P.prototype,"_handleDone",null),P=e([c(B)],P);const j=P;export{j as default};
package/widgets/Sketch.js CHANGED
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.25/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../chunks/tslib.es6.js";import"../intl.js";import{handlesGroup as t}from"../core/handleUtils.js";import{removeMaybe as o,destroyMaybe as i,isNone as s,isSome as n}from"../core/maybe.js";import{when as l,watch as r}from"../core/reactiveUtils.js";import{property as a}from"../core/accessorSupport/decorators/property.js";import"../core/arrayUtils.js";import{cast as c}from"../core/accessorSupport/decorators/cast.js";import{subclass as d}from"../core/accessorSupport/decorators/subclass.js";import p from"./Widget.js";import u from"./Sketch/SketchViewModel.js";import h from"./support/SelectionToolbar.js";import g from"./support/SnappingControls.js";import{isRTL as v}from"./support/widgetUtils.js";import{messageBundle as m}from"./support/decorators/messageBundle.js";import{vmEvent as _}from"./support/decorators/vmEvent.js";import{tsx as b}from"./support/jsxFactory.js";import{substitute as w}from"../intl/substitute.js";const f={base:"esri-sketch",verticalLayout:"esri-sketch--vertical",panel:"esri-sketch__panel",infoPanel:"esri-sketch__info-panel",section:"esri-sketch__section",toolSection:"esri-sketch__tool-section",infoSection:"esri-sketch__info-section",infoCountSection:"esri-sketch__info-count-section",menuContainer:"esri-sketch__menu-container",menuHeader:"esri-sketch__menu-header",menuTitle:"esri-sketch__menu-title",featureCountBadge:"esri-sketch__feature-count-badge",featureCountText:"esri-sketch__feature-count-text",featureCountNumber:"esri-sketch__feature-count-number",actionToggle:"esri-sketch__action-toggle",actionToggleOn:"esri-sketch__action-toggle--on",actionTitle:"esri-sketch__item-action-title",actionIcon:"esri-sketch__item-action-icon",disabled:"esri-disabled",esriWidget:"esri-widget",rotating:"esri-rotating",widgetIcon:"esri-icon-edit"},y={createTools:{point:!0,polyline:!0,polygon:!0,rectangle:!0,circle:!0},selectionTools:{"rectangle-selection":!0,"lasso-selection":!0},undoRedoMenu:!0,settingsMenu:!0,snappingControls:!0,snappingControlsElements:{header:!1,enabledToggle:!0,selfEnabledToggle:!0,featureEnabledToggle:!0,layerList:!0}};let C=class extends p{constructor(e,t){super(e,t),this._activeCreateOptions=null,this._defaultViewModel=null,this._menuOpen=!1,this._selectionToolbar=null,this._selectionHandlesGroup=null,this._snappingControls=null,this._viewModelHandlesGroup=null,this.availableCreateTools=["point","polyline","polygon","rectangle","circle"],this.creationMode="continuous",this.iconClass=f.widgetIcon,this.layout="horizontal",this.messages=null,this.visibleElements={...y},this._activateCreateTool=this._activateCreateTool.bind(this),e?.viewModel||(this._defaultViewModel=new u,this.viewModel=this._defaultViewModel)}initialize(){const{layer:e,view:o}=this,i=new h({view:"2d"===o?.type?o:null,layers:e?[e]:null});this._selectionHandlesGroup=t([l((()=>i.activeToolInfo),(()=>this.viewModel.cancel())),i.on("complete",(e=>this._onSelectionOperationComplete(e)))]),this._selectionToolbar=i,this._setUpSnappingControls()}loadDependencies(){return Promise.all([import("@esri/calcite-components/dist/components/calcite-action.js"),import("@esri/calcite-components/dist/components/calcite-icon.js")])}destroy(){this._selectionToolbar.destroy(),this._cleanupViewModel(),this._selectionHandlesGroup=o(this._selectionHandlesGroup),this._snappingControls=i(this._snappingControls)}get activeTool(){const e=this._selectionToolbar.activeToolInfo;if(e)switch(e.toolName){case"lasso":return"lasso-selection";case"rectangle":return"rectangle-selection";case"default":return"custom-selection"}return this.viewModel.activeTool}get createGraphic(){return this.viewModel.createGraphic}get defaultCreateOptions(){return this.viewModel.defaultCreateOptions}set defaultCreateOptions(e){this.viewModel.defaultCreateOptions=e}get defaultUpdateOptions(){return this.viewModel.defaultUpdateOptions}set defaultUpdateOptions(e){this.viewModel.defaultUpdateOptions=e}get label(){return this.messages?.widgetLabel??""}set label(e){this._overrideIfSome("label",e)}get labelOptions(){return this.viewModel.labelOptions}set labelOptions(e){this.viewModel.labelOptions=e}get layer(){return this.viewModel.layer}set layer(e){this.viewModel.layer=e}get snappingOptions(){return this.viewModel.snappingOptions}set snappingOptions(e){this.viewModel.snappingOptions=e}get state(){return this._selectionToolbar.activeToolInfo?"active":this.viewModel.state}get tooltipOptions(){return this.viewModel.tooltipOptions}set tooltipOptions(e){this.viewModel.tooltipOptions=e}get updateGraphics(){return this.viewModel.updateGraphics}get view(){return this.viewModel.view}set view(e){this.viewModel.view=e}set viewModel(e){e!==this._get("viewModel")&&((s(this._defaultViewModel)||this._defaultViewModel!==e)&&this._cleanupViewModel(),this._set("viewModel",e),e&&(this._viewModelHandlesGroup=t([e.on("create",(e=>{this.scheduleRender(),this._onCreateOperation(e)})),e.on("update",(()=>this.scheduleRender())),e.on("delete",(e=>this.emit("delete",e))),e.on("undo",(()=>this.scheduleRender())),e.on("redo",(()=>this.scheduleRender())),r((()=>e.layer),(e=>{this._selectionToolbar.layers=e?[e]:null})),r((()=>e.view),(e=>{this._selectionToolbar.view="2d"===e?.type?e:null,this._setUpSnappingControls()})),r((()=>e.state),(()=>this.notifyChange("state")))])))}castVisibleElements(e){const t={...y,...e,createTools:{...y.createTools,...e?.createTools},selectionTools:{...y.selectionTools,...e?.selectionTools},snappingControlsElements:{...y.snappingControlsElements,...e?.snappingControlsElements}};return n(this._snappingControls)&&(this._snappingControls.visibleElements=t.snappingControlsElements),t}create(e,t){this._activeCreateOptions=t||null,this.viewModel.create(e,t)}update(e,t){return this.viewModel.update(e,t)}complete(){this.viewModel.complete()}cancel(){this._selectionToolbar.cancel(),this.viewModel.cancel()}undo(){this.viewModel.undo(),this.view?.focus()}redo(){this.viewModel.redo(),this.view?.focus()}delete(){this.viewModel.delete()}render(){const{label:e,layout:t,viewModel:{state:o}}=this;return b("div",{"aria-label":e,class:this.classes(f.base,f.esriWidget,{[f.disabled]:"disabled"===o,[f.verticalLayout]:"vertical"===t})},b("div",{role:"toolbar",class:f.panel},this.renderTopPanelContents()),b("div",{class:this.classes(f.panel,f.infoPanel)},this.renderInfoPanelContents()))}renderTopPanelContents(){const e=this.classes(f.section,f.toolSection),{availableCreateTools:t,visibleElements:o}=this;return[b("div",{role:"menu",key:"selection-button-container",class:e},this.renderDefaultSelectionButton(),this.renderSelectionToolbar()),t&&t.length?b("div",{role:"menu",class:e},this.renderDrawButtons()):null,o.undoRedoMenu?b("div",{role:"menu",key:"undo-redo-menu-button-container",class:e},this.renderUndoRedoMenuButtons()):null,o.settingsMenu?b("div",{key:"settings-menu-button-container",class:f.section},this.renderSettingsMenuButton()):null]}renderInfoPanelContents(){return this._menuOpen?this.renderSettingsMenu():this.updateGraphics.length?[b("div",{class:this.classes(f.section,f.infoSection,f.infoCountSection),key:"feature-count-container"},this.renderFeatureCount()),b("div",{class:this.classes(f.section,f.infoSection),key:"delete-button-container"},this.renderDeleteButton())]:void 0}renderSettingsMenu(){const{settings:e}=this.messages;return[b("div",{role:"menu",class:f.menuContainer,key:"settings-menu-container"},b("header",{class:f.menuHeader,key:"settings-menu-header"},b("span",{class:f.menuTitle},e)),this.renderSnappingControls())]}renderSnappingControls(){const{snappingControls:e}=this.visibleElements;if(n(this._snappingControls)&&e)return this._snappingControls.render()}renderFeatureCount(){const{layout:e,messages:t,updateGraphics:{length:o}}=this,i=w(1===o?t.featureCount:t.featuresCount,{count:o});return b("div",{class:f.featureCountBadge,"aria-label":i},b("span",{class:f.featureCountNumber},"vertical"===e?o:i))}renderDeleteButton(){const e=this.messages.deleteFeature;return b("calcite-action",{bind:this,label:e,onclick:this.delete,scale:"s",text:e,title:e},b("calcite-icon",{scale:"s",icon:"trash"}))}renderDefaultSelectionButton(){if(!this.viewModel.updateOnGraphicClick)return;const e=this.messages.selectFeature;return b("calcite-action",{active:"ready"===this.state,bind:this,label:e,onclick:this._activateDefaultSelectTool,scale:"s",text:e,title:e},b("calcite-icon",{scale:"s",icon:"cursor"}))}renderSelectionToolbar(){if("2d"!==this.view?.type)return;const e=this.visibleElements.selectionTools;return this._selectionToolbar.visibleElements={lassoTool:!!e["lasso-selection"],rectangleTool:!!e["rectangle-selection"]},this._selectionToolbar.render()}renderDrawButtons(){const e=this.visibleElements.createTools;return this.availableCreateTools.map((t=>"point"===t&&e.point?this.renderPointButton():"polyline"===t&&e.polyline?this.renderPolylineButton():"polygon"===t&&e.polygon?this.renderPolygonButton():"rectangle"===t&&e.rectangle?this.renderRectangleButton():"circle"===t&&e.circle?this.renderCircleButton():void 0))}renderPointButton(){const e="point",t=this.messages.drawPoint;return b("calcite-action",{active:this.activeTool===e,bind:this,label:t,onclick:()=>this._activateCreateTool(e),scale:"s",text:t,title:t},b("calcite-icon",{scale:"s",icon:"pin"}))}renderPolygonButton(){const e="polygon",t=this.messages.drawPolygon;return b("calcite-action",{active:this.activeTool===e,bind:this,label:t,onclick:()=>this._activateCreateTool(e),scale:"s",text:t,title:t},b("calcite-icon",{scale:"s",icon:"polygon"}))}renderPolylineButton(){const e="polyline",t=this.messages.drawPolyline;return b("calcite-action",{active:this.activeTool===e,bind:this,label:t,onclick:()=>this._activateCreateTool(e),scale:"s",text:t,title:t},b("calcite-icon",{scale:"s",icon:"line"}))}renderCircleButton(){const e="circle",t=this.messages.drawCircle;return b("calcite-action",{active:this.activeTool===e,bind:this,label:t,onclick:()=>this._activateCreateTool(e),scale:"s",text:t,title:t},b("calcite-icon",{scale:"s",icon:"circle"}))}renderRectangleButton(){const e="rectangle",t=this.messages.drawRectangle;return b("calcite-action",{active:this.activeTool===e,bind:this,label:t,onclick:()=>this._activateCreateTool(e),scale:"s",text:t,title:t},b("calcite-icon",{scale:"s",icon:"rectangle"}))}renderUndoRedoMenuButtons(){return[this.renderUndoButton(),this.renderRedoButton()]}renderUndoButton(){const e=this.messages.undo;return b("calcite-action",{disabled:!this.viewModel.canUndo(),bind:this,label:e,onclick:this.undo,scale:"s",text:e,title:e},b("calcite-icon",{scale:"s",icon:v(this.container)?"redo":"undo"}))}renderRedoButton(){const e=this.messages.redo;return b("calcite-action",{disabled:!this.viewModel.canRedo(),bind:this,label:e,onclick:this.redo,scale:"s",text:e,title:e},b("calcite-icon",{scale:"s",icon:v(this.container)?"undo":"redo"}))}renderSettingsMenuButton(){const e=this.messages.settings;return b("calcite-action",{active:this._menuOpen,bind:this,label:e,onclick:this._toggleMenu,scale:"s",text:e,title:e},b("calcite-icon",{scale:"s",icon:"gear"}))}_activateCreateTool(e){this.activeTool!==e?(this._selectionToolbar.cancel(),this.create(e)):this.cancel()}_onCreateOperation(e){if("complete"!==e.state)return;const{creationMode:t}=this,{type:o}=e;if("create"===o){const{tool:o,graphic:i}=e,s=this._activeCreateOptions;this._activeCreateOptions=null,"continuous"===t?this.create(o,s):"update"===t&&this.update([i])}}_toggleMenu(){this._menuOpen=!this._menuOpen,this.scheduleRender()}_onSelectionOperationComplete(e){const{viewModel:{defaultUpdateOptions:t}}=this,{selection:o}=e;if(!e.aborted&&o.length){const e=t.tool,i=o.length>1&&"reshape"===e?"transform":e;this.update(o,{...t,tool:i})}this.notifyChange("state")}_activateDefaultSelectTool(){this.cancel(),this.view?.focus()}_cleanupViewModel(){this._defaultViewModel=i(this._defaultViewModel),this._viewModelHandlesGroup=o(this._viewModelHandlesGroup)}_setUpSnappingControls(){const{snappingOptions:e,view:t}=this;if(this._snappingControls=i(this._snappingControls),!e||!t)return;const o=new g({snappingOptions:e,view:t,visibleElements:this.visibleElements.snappingControlsElements});this._snappingControls=o}};e([a()],C.prototype,"activeTool",null),e([a({cast:e=>{if(!e||!e.length)return null;const t=new Set(["point","polyline","polygon","rectangle","circle"]);return e.filter((e=>t.has(e)))}})],C.prototype,"availableCreateTools",void 0),e([a({readOnly:!0})],C.prototype,"createGraphic",null),e([a()],C.prototype,"creationMode",void 0),e([a()],C.prototype,"defaultCreateOptions",null),e([a()],C.prototype,"defaultUpdateOptions",null),e([a()],C.prototype,"iconClass",void 0),e([a()],C.prototype,"label",null),e([a()],C.prototype,"labelOptions",null),e([a()],C.prototype,"layer",null),e([a({type:["horizontal","vertical"]})],C.prototype,"layout",void 0),e([a(),m("esri/widgets/Sketch/t9n/Sketch")],C.prototype,"messages",void 0),e([a()],C.prototype,"snappingOptions",null),e([a()],C.prototype,"state",null),e([a()],C.prototype,"tooltipOptions",null),e([a({readOnly:!0})],C.prototype,"updateGraphics",null),e([a()],C.prototype,"view",null),e([a(),_(["create","update","undo","redo"])],C.prototype,"viewModel",null),e([a()],C.prototype,"visibleElements",void 0),e([c("visibleElements")],C.prototype,"castVisibleElements",null),C=e([d("esri.widgets.Sketch")],C);const M=C;export{M as default};
5
+ import{_ as e}from"../chunks/tslib.es6.js";import"../intl.js";import{handlesGroup as t}from"../core/handleUtils.js";import{removeMaybe as o,destroyMaybe as i,isSome as s}from"../core/maybe.js";import{watch as n,syncAndInitial as l,when as r}from"../core/reactiveUtils.js";import{property as a}from"../core/accessorSupport/decorators/property.js";import"../core/arrayUtils.js";import{cast as c}from"../core/accessorSupport/decorators/cast.js";import{subclass as p}from"../core/accessorSupport/decorators/subclass.js";import d from"./Widget.js";import u from"./Sketch/SketchViewModel.js";import h from"./support/SelectionToolbar.js";import g from"./support/SnappingControls.js";import{isRTL as v}from"./support/widgetUtils.js";import{messageBundle as m}from"./support/decorators/messageBundle.js";import{vmEvent as _}from"./support/decorators/vmEvent.js";import{tsx as b}from"./support/jsxFactory.js";import{substitute as w}from"../intl/substitute.js";const f={base:"esri-sketch",verticalLayout:"esri-sketch--vertical",panel:"esri-sketch__panel",infoPanel:"esri-sketch__info-panel",section:"esri-sketch__section",toolSection:"esri-sketch__tool-section",infoSection:"esri-sketch__info-section",infoCountSection:"esri-sketch__info-count-section",menuContainer:"esri-sketch__menu-container",menuHeader:"esri-sketch__menu-header",menuTitle:"esri-sketch__menu-title",featureCountBadge:"esri-sketch__feature-count-badge",featureCountText:"esri-sketch__feature-count-text",featureCountNumber:"esri-sketch__feature-count-number",actionToggle:"esri-sketch__action-toggle",actionToggleOn:"esri-sketch__action-toggle--on",actionTitle:"esri-sketch__item-action-title",actionIcon:"esri-sketch__item-action-icon",disabled:"esri-disabled",esriWidget:"esri-widget",rotating:"esri-rotating",widgetIcon:"esri-icon-edit"},y={createTools:{point:!0,polyline:!0,polygon:!0,rectangle:!0,circle:!0},selectionTools:{"rectangle-selection":!0,"lasso-selection":!0},undoRedoMenu:!0,settingsMenu:!0,snappingControls:!0,snappingControlsElements:{header:!1,enabledToggle:!0,selfEnabledToggle:!0,featureEnabledToggle:!0,layerList:!0}};let C=class extends d{constructor(e,t){super(e,t),this._activeCreateOptions=null,this._menuOpen=!1,this._selectionToolbar=null,this._snappingControls=null,this._viewModelHandlesGroup=null,this.availableCreateTools=["point","polyline","polygon","rectangle","circle"],this.creationMode="continuous",this.iconClass=f.widgetIcon,this.layout="horizontal",this.messages=null,this.visibleElements={...y},this._activateCreateTool=this._activateCreateTool.bind(this),this.viewModel=e?.viewModel||new u}initialize(){const{layer:e,view:i}=this,s=new h({view:"2d"===i?.type?i:null,layers:e?[e]:null});this.addHandles([n((()=>this.viewModel),(e=>{this._viewModelHandlesGroup=o(this._viewModelHandlesGroup),e&&(this._viewModelHandlesGroup=t([e.on("create",(e=>{this.scheduleRender(),this._onCreateOperation(e)})),e.on("update",(()=>this.scheduleRender())),e.on("delete",(e=>this.emit("delete",e))),e.on("undo",(()=>this.scheduleRender())),e.on("redo",(()=>this.scheduleRender())),n((()=>e.layer),(e=>{this._selectionToolbar.layers=e?[e]:null})),n((()=>e.view),(e=>{this._selectionToolbar.view="2d"===e?.type?e:null,this._setUpSnappingControls()})),n((()=>e.state),(()=>this.notifyChange("state")))]))}),l),r((()=>s.activeToolInfo),(()=>this.viewModel.cancel())),s.on("complete",(e=>this._onSelectionOperationComplete(e)))]),this._selectionToolbar=s,this._setUpSnappingControls()}loadDependencies(){return Promise.all([import("@esri/calcite-components/dist/components/calcite-action.js"),import("@esri/calcite-components/dist/components/calcite-icon.js")])}destroy(){this._selectionToolbar.destroy(),this._viewModelHandlesGroup=o(this._viewModelHandlesGroup),this._snappingControls=i(this._snappingControls)}get activeTool(){const e=this._selectionToolbar.activeToolInfo;if(e)switch(e.toolName){case"lasso":return"lasso-selection";case"rectangle":return"rectangle-selection";case"default":return"custom-selection"}return this.viewModel.activeTool}get createGraphic(){return this.viewModel.createGraphic}get defaultCreateOptions(){return this.viewModel.defaultCreateOptions}set defaultCreateOptions(e){this.viewModel.defaultCreateOptions=e}get defaultUpdateOptions(){return this.viewModel.defaultUpdateOptions}set defaultUpdateOptions(e){this.viewModel.defaultUpdateOptions=e}get label(){return this.messages?.widgetLabel??""}set label(e){this._overrideIfSome("label",e)}get labelOptions(){return this.viewModel.labelOptions}set labelOptions(e){this.viewModel.labelOptions=e}get layer(){return this.viewModel.layer}set layer(e){this.viewModel.layer=e}get snappingOptions(){return this.viewModel.snappingOptions}set snappingOptions(e){this.viewModel.snappingOptions=e}get state(){return this._selectionToolbar.activeToolInfo?"active":this.viewModel.state}get tooltipOptions(){return this.viewModel.tooltipOptions}set tooltipOptions(e){this.viewModel.tooltipOptions=e}get updateGraphics(){return this.viewModel.updateGraphics}get view(){return this.viewModel.view}set view(e){this.viewModel.view=e}set viewModel(e){const t=this._get("viewModel");e!==t&&(t&&i(t),this._set("viewModel",e))}castVisibleElements(e){const t={...y,...e,createTools:{...y.createTools,...e?.createTools},selectionTools:{...y.selectionTools,...e?.selectionTools},snappingControlsElements:{...y.snappingControlsElements,...e?.snappingControlsElements}};return s(this._snappingControls)&&(this._snappingControls.visibleElements=t.snappingControlsElements),t}create(e,t){this._activeCreateOptions=t||null,this.viewModel.create(e,t)}update(e,t){return this.viewModel.update(e,t)}complete(){this.viewModel.complete()}cancel(){this._selectionToolbar.cancel(),this.viewModel.cancel()}undo(){this.viewModel.undo(),this.view?.focus()}redo(){this.viewModel.redo(),this.view?.focus()}delete(){this.viewModel.delete()}render(){const{label:e,layout:t,viewModel:{state:o}}=this;return b("div",{"aria-label":e,class:this.classes(f.base,f.esriWidget,{[f.disabled]:"disabled"===o,[f.verticalLayout]:"vertical"===t})},b("div",{role:"toolbar",class:f.panel},this.renderTopPanelContents()),b("div",{class:this.classes(f.panel,f.infoPanel)},this.renderInfoPanelContents()))}renderTopPanelContents(){const e=this.classes(f.section,f.toolSection),{availableCreateTools:t,visibleElements:o}=this;return[b("div",{role:"menu",key:"selection-button-container",class:e},this.renderDefaultSelectionButton(),this.renderSelectionToolbar()),t&&t.length?b("div",{role:"menu",class:e},this.renderDrawButtons()):null,o.undoRedoMenu?b("div",{role:"menu",key:"undo-redo-menu-button-container",class:e},this.renderUndoRedoMenuButtons()):null,o.settingsMenu?b("div",{key:"settings-menu-button-container",class:f.section},this.renderSettingsMenuButton()):null]}renderInfoPanelContents(){return this._menuOpen?this.renderSettingsMenu():this.updateGraphics.length?[b("div",{class:this.classes(f.section,f.infoSection,f.infoCountSection),key:"feature-count-container"},this.renderFeatureCount()),b("div",{class:this.classes(f.section,f.infoSection),key:"delete-button-container"},this.renderDeleteButton())]:void 0}renderSettingsMenu(){const{settings:e}=this.messages;return[b("div",{role:"menu",class:f.menuContainer,key:"settings-menu-container"},b("header",{class:f.menuHeader,key:"settings-menu-header"},b("span",{class:f.menuTitle},e)),this.renderSnappingControls())]}renderSnappingControls(){const{snappingControls:e}=this.visibleElements;if(s(this._snappingControls)&&e)return this._snappingControls.render()}renderFeatureCount(){const{layout:e,messages:t,updateGraphics:{length:o}}=this,i=w(1===o?t.featureCount:t.featuresCount,{count:o});return b("div",{class:f.featureCountBadge,"aria-label":i},b("span",{class:f.featureCountNumber},"vertical"===e?o:i))}renderDeleteButton(){const e=this.messages.deleteFeature;return b("calcite-action",{bind:this,label:e,onclick:this.delete,scale:"s",text:e,title:e},b("calcite-icon",{scale:"s",icon:"trash"}))}renderDefaultSelectionButton(){if(!this.viewModel.updateOnGraphicClick)return;const e=this.messages.selectFeature;return b("calcite-action",{active:"ready"===this.state,bind:this,label:e,onclick:this._activateDefaultSelectTool,scale:"s",text:e,title:e},b("calcite-icon",{scale:"s",icon:"cursor"}))}renderSelectionToolbar(){if("2d"!==this.view?.type)return;const e=this.visibleElements.selectionTools;return this._selectionToolbar.visibleElements={lassoTool:!!e["lasso-selection"],rectangleTool:!!e["rectangle-selection"]},this._selectionToolbar.render()}renderDrawButtons(){const e=this.visibleElements.createTools;return this.availableCreateTools.map((t=>"point"===t&&e.point?this.renderPointButton():"polyline"===t&&e.polyline?this.renderPolylineButton():"polygon"===t&&e.polygon?this.renderPolygonButton():"rectangle"===t&&e.rectangle?this.renderRectangleButton():"circle"===t&&e.circle?this.renderCircleButton():void 0))}renderPointButton(){const e="point",t=this.messages.drawPoint;return b("calcite-action",{active:this.activeTool===e,bind:this,label:t,onclick:()=>this._activateCreateTool(e),scale:"s",text:t,title:t},b("calcite-icon",{scale:"s",icon:"pin"}))}renderPolygonButton(){const e="polygon",t=this.messages.drawPolygon;return b("calcite-action",{active:this.activeTool===e,bind:this,label:t,onclick:()=>this._activateCreateTool(e),scale:"s",text:t,title:t},b("calcite-icon",{scale:"s",icon:"polygon"}))}renderPolylineButton(){const e="polyline",t=this.messages.drawPolyline;return b("calcite-action",{active:this.activeTool===e,bind:this,label:t,onclick:()=>this._activateCreateTool(e),scale:"s",text:t,title:t},b("calcite-icon",{scale:"s",icon:"line"}))}renderCircleButton(){const e="circle",t=this.messages.drawCircle;return b("calcite-action",{active:this.activeTool===e,bind:this,label:t,onclick:()=>this._activateCreateTool(e),scale:"s",text:t,title:t},b("calcite-icon",{scale:"s",icon:"circle"}))}renderRectangleButton(){const e="rectangle",t=this.messages.drawRectangle;return b("calcite-action",{active:this.activeTool===e,bind:this,label:t,onclick:()=>this._activateCreateTool(e),scale:"s",text:t,title:t},b("calcite-icon",{scale:"s",icon:"rectangle"}))}renderUndoRedoMenuButtons(){return[this.renderUndoButton(),this.renderRedoButton()]}renderUndoButton(){const e=this.messages.undo;return b("calcite-action",{disabled:!this.viewModel.canUndo(),bind:this,label:e,onclick:this.undo,scale:"s",text:e,title:e},b("calcite-icon",{scale:"s",icon:v(this.container)?"redo":"undo"}))}renderRedoButton(){const e=this.messages.redo;return b("calcite-action",{disabled:!this.viewModel.canRedo(),bind:this,label:e,onclick:this.redo,scale:"s",text:e,title:e},b("calcite-icon",{scale:"s",icon:v(this.container)?"undo":"redo"}))}renderSettingsMenuButton(){const e=this.messages.settings;return b("calcite-action",{active:this._menuOpen,bind:this,label:e,onclick:this._toggleMenu,scale:"s",text:e,title:e},b("calcite-icon",{scale:"s",icon:"gear"}))}_activateCreateTool(e){this.activeTool!==e?(this._selectionToolbar.cancel(),this.create(e)):this.cancel()}_onCreateOperation(e){if("complete"!==e.state)return;const{creationMode:t}=this,{type:o}=e;if("create"===o){const{tool:o,graphic:i}=e,s=this._activeCreateOptions;this._activeCreateOptions=null,"continuous"===t?this.create(o,s):"update"===t&&this.update([i])}}_toggleMenu(){this._menuOpen=!this._menuOpen,this.scheduleRender()}_onSelectionOperationComplete(e){const{viewModel:{defaultUpdateOptions:t}}=this,{selection:o}=e;if(!e.aborted&&o.length){const e=t.tool,i=o.length>1&&"reshape"===e?"transform":e;this.update(o,{...t,tool:i})}this.notifyChange("state")}_activateDefaultSelectTool(){this.cancel(),this.view?.focus()}_setUpSnappingControls(){const{snappingOptions:e,view:t}=this;if(this._snappingControls=i(this._snappingControls),!e||!t)return;const o=new g({snappingOptions:e,view:t,visibleElements:this.visibleElements.snappingControlsElements});this._snappingControls=o}};e([a()],C.prototype,"activeTool",null),e([a({cast:e=>{if(!e||!e.length)return null;const t=new Set(["point","polyline","polygon","rectangle","circle"]);return e.filter((e=>t.has(e)))}})],C.prototype,"availableCreateTools",void 0),e([a({readOnly:!0})],C.prototype,"createGraphic",null),e([a()],C.prototype,"creationMode",void 0),e([a()],C.prototype,"defaultCreateOptions",null),e([a()],C.prototype,"defaultUpdateOptions",null),e([a()],C.prototype,"iconClass",void 0),e([a()],C.prototype,"label",null),e([a()],C.prototype,"labelOptions",null),e([a()],C.prototype,"layer",null),e([a({type:["horizontal","vertical"]})],C.prototype,"layout",void 0),e([a(),m("esri/widgets/Sketch/t9n/Sketch")],C.prototype,"messages",void 0),e([a()],C.prototype,"snappingOptions",null),e([a()],C.prototype,"state",null),e([a()],C.prototype,"tooltipOptions",null),e([a({readOnly:!0})],C.prototype,"updateGraphics",null),e([a()],C.prototype,"view",null),e([a(),_(["create","update","undo","redo"])],C.prototype,"viewModel",null),e([a()],C.prototype,"visibleElements",void 0),e([c("visibleElements")],C.prototype,"castVisibleElements",null),C=e([p("esri.widgets.Sketch")],C);const T=C;export{T 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.25/esri/copyright.txt for details.
4
4
  */
5
- import{_ as t}from"../../chunks/tslib.es6.js";import e from"../../TimeExtent.js";import i from"../../TimeInterval.js";import n from"../../core/Collection.js";import s from"../../core/Evented.js";import{HandleOwnerMixin as r}from"../../core/HandleOwner.js";import o from"../../core/Logger.js";import{isSome as l,isNone as a,unwrap as m,applySome as u}from"../../core/maybe.js";import{after as p,isAbortError as d}from"../../core/promiseUtils.js";import{watch as h,whenOnce as c,initial as f,syncAndInitial as g}from"../../core/reactiveUtils.js";import{offsetDate as w}from"../../core/timeUtils.js";import{property as T}from"../../core/accessorSupport/decorators/property.js";import"../../core/arrayUtils.js";import{ensureType as v}from"../../core/accessorSupport/ensureType.js";import{subclass as x}from"../../core/accessorSupport/decorators/subclass.js";import E from"../../webdoc/Widgets.js";import y from"../../webdoc/widgets/TimeSlider.js";const _=1e4;function b(t){return l(t)&&void 0!==t.count}function C(t){return l(t)&&void 0!==t.interval}function S(t){return l(t)&&void 0!==t.dates}function j(t){return"esri.WebMap"===t.declaredClass}let A=class extends(r(s.EventedAccessor)){constructor(t){super(t),this._animationController=null,this._isViewTimeExtentInitialized=!1,this._timerId=null,this.actions=new n,this.fullTimeExtent=null,this.loop=!1,this.mode="time-window",this.stops={count:10},this.timeExtent=null,this.view=null}initialize(){this.handles.add([h((()=>this.effectiveStops),(()=>{a(this.timeExtent)&&(this.timeExtent=this._getDefaultTimeExtent())}),f),h((()=>this.view),((t,e)=>{this._unregisterWidget(e),this._registerWidget(t)}),g),h((()=>this.timeExtent),(t=>{if(a(this.view))return;const e=this.view.timeExtent;(a(t)||t.isAllTime)&&(a(e)||e.isAllTime)||l(t)&&l(e)&&t.equals(e)||(this.view.timeExtent=m(t))}),f),h((()=>u(this.view,(t=>t.timeExtent))),(t=>{this._isViewTimeExtentInitialized?(a(t)||t.isAllTime)&&(a(this.timeExtent)||this.timeExtent.isAllTime)||l(t)&&l(this.timeExtent)&&t.equals(this.timeExtent)||(this.timeExtent=t):this._isViewTimeExtentInitialized=!0}))])}destroy(){l(this._timerId)&&(clearInterval(this._timerId),this._timerId=null),this._unregisterWidget(this.view),this.view=null,l(this._animationController)&&(this._animationController.abort(),this._animationController=null)}get effectiveStops(){const{fullTimeExtent:t,stops:e}=this;if(S(e)){const{dates:i}=e;if(null==i||0===i.length)return null;const n=i.sort(((t,e)=>t.getTime()-e.getTime()));if(a(t))return n;const{start:s,end:r}=t;if(a(s)||a(r))return n;return n.filter((t=>!(t.getTime()<s.getTime()||t.getTime()>r.getTime())))}if(b(e)){const i=e.timeExtent??m(t);return this._divideTimeExtentByCount(i,e.count)}if(C(e)){const i=e.timeExtent??m(t);return this._divideTimeExtentByInterval(i,e.interval)}return[]}set playRate(t){t<=0||t>36e5||("playing"===this.state&&this._startAnimation(),this._set("playRate",t))}get state(){return a(this.fullTimeExtent)?"disabled":l(this._animationController)?"playing":"ready"}get timeExtentValues(){const{mode:t,timeExtent:e}=this;if(a(e)||e.isAllTime||e.isEmpty)return null;const{start:i,end:n}=e;switch(t){case"cumulative-from-end":case"instant":return l(i)?[i.getTime()]:null;case"cumulative-from-start":return l(n)?[n.getTime()]:null;case"time-window":return l(i)&&l(n)?[i.getTime(),n.getTime()]:null}}static async getPropertiesFromWebMap(t,e){if(a(t)||!j(t))return null;await t.load({signal:e});const i=t?.widgets?.timeSlider;if(!i)return null;const{getFullTimeExtentFromWebDocument:n,getModeFromTimeSlider:s,getStopsFromTimeSlider:r,getTimeExtentFromTimeSlider:o}=await import("./utils.js"),l=await n(t,e),m=i.loop,u=s(i);return{fullTimeExtent:l,loop:m,mode:u,playRate:i.stopDelay??2e3,stops:r(i),timeExtent:o(i,u)}}next(){this._step({forward:!0,allowRestart:!1})}play(){this._startAnimation()}previous(){this._step({forward:!1,allowRestart:!1})}stop(){this._stopAnimation()}triggerAction(t){this.emit("trigger-action",{action:t})}updateWebDocument(t){if(j(t)){const e=new y({currentTimeExtent:this.timeExtent,fullTimeExtent:this.fullTimeExtent,loop:this.loop,numStops:b(this.stops)?this.stops.count:null,numThumbs:"time-window"===this.mode?2:1,stopDelay:this.playRate,stopInterval:C(this.stops)?this.stops.interval:null,stops:S(this.stops)?this.stops.dates:null});t.widgets?t.widgets.timeSlider=e:t.widgets=new E({timeSlider:e})}}valuesToTimeExtent(t){if(a(t))return null;const i=t.sort(((t,e)=>t-e)).map((t=>new Date(t))),n=i.length>0?i[0]:null,s=i.length>1?i[1]:null;switch(this.mode){case"time-window":return new e({start:n,end:s});case"instant":return new e({start:n,end:n});case"cumulative-from-start":return new e({start:null,end:n});case"cumulative-from-end":return new e({start:n,end:null});default:return e.allTime}}async _animate(){try{const t=this.view,e=u(this._animationController,(t=>t.signal));await Promise.all([p(this.playRate,null,e),l(t)&&c((()=>!1===t.updating),e)])}catch(t){return d(t)||o.getLogger(this.declaredClass).error(t),void(this._animationController=null)}this._step({forward:!0,allowRestart:!1}),a(this._animationController)||this._animate()}_divideTimeExtentByCount(t,e=10){if(!t||!e)return[];const{start:i,end:n}=t;if(a(i)||a(n))return[];if(e>_)return this._divideTimeExtentByCount(t);const s=[],r=i.getTime(),o=n.getTime()-r;for(let l=0;l<=e;l++)s.push(new Date(r+l/e*o));return s}_divideTimeExtentByInterval(t,e,i=_){if(!t||!e)return[];const{start:n,end:s}=t;if(a(n)||a(s))return[];if((s.getTime()-n.getTime())/e.toMilliseconds()>i)return this._divideTimeExtentByCount(t);const r=[],{value:o,unit:l}=e;let m=n;for(;m.getTime()<=s.getTime();)r.push(new Date(m.getTime())),m=w(m,o,l);return r}_getDefaultTimeExtent(){const{effectiveStops:t,mode:i}=this;if(a(t)||!i)return null;switch(i){case"time-window":return t.length>1?new e({start:t[0],end:t[1]}):null;case"cumulative-from-start":return t.length>0?new e({start:null,end:t[0]}):null;case"cumulative-from-end":return t.length>0?new e({start:t[0],end:null}):null;case"instant":return t.length>0?new e({start:t[0],end:t[0]}):null;default:return null}}_registerWidget(t){if(l(t)){t.persistableViewModels.includes(this)||t.persistableViewModels.add(this)}}_startAnimation(){this._stopAnimation(),this._animationController=new AbortController,this._step({forward:!0,allowRestart:!0}),this._animate()}_step(t){const{forward:e,allowRestart:i}=t,{effectiveStops:n}=this;if(a(this.timeExtentValues)||a(n))return;const s=n.map((t=>t.getTime())),r=this.timeExtentValues.map((t=>{const e=s.indexOf(t);if(-1!==e)return e;const i=s.reduce(((e,i)=>Math.abs(i-t)<Math.abs(e-t)?i:e));return s.indexOf(i)})),o=r.map((t=>t+(e?1:-1))),l=o.some((t=>t<0||t>s.length-1)),{loop:m,state:u}=this;if(l)if(m||i){const t=Math.min(...r),i=Math.max(...r),n=(e?r.map((e=>e-t)):r.map((t=>t+(s.length-1-i)))).map((t=>s[t]));this.timeExtent=this.valuesToTimeExtent(n)}else"playing"===u&&this.stop();else{const t=o.map((t=>s[t]));this.timeExtent=this.valuesToTimeExtent(t)}}_stopAnimation(){l(this._animationController)&&(this._animationController.abort(),this._animationController=null)}_unregisterWidget(t){l(t)&&t.persistableViewModels.remove(this)}};t([T()],A.prototype,"_animationController",void 0),t([T({type:n})],A.prototype,"actions",void 0),t([T({readOnly:!0})],A.prototype,"effectiveStops",null),t([T({type:e})],A.prototype,"fullTimeExtent",void 0),t([T({nonNullable:!0})],A.prototype,"loop",void 0),t([T({nonNullable:!0})],A.prototype,"mode",void 0),t([T({nonNullable:!0,value:1e3})],A.prototype,"playRate",null),t([T({readOnly:!0})],A.prototype,"state",null),t([T({cast:t=>a(t)?null:(C(t)&&(t.interval=v(i,t.interval)),(C(t)||b(t))&&(t.timeExtent=v(e,t.timeExtent)),t)})],A.prototype,"stops",void 0),t([T({type:e})],A.prototype,"timeExtent",void 0),t([T({readOnly:!0})],A.prototype,"timeExtentValues",null),t([T()],A.prototype,"view",void 0),t([T()],A.prototype,"next",null),t([T()],A.prototype,"play",null),t([T()],A.prototype,"previous",null),t([T()],A.prototype,"stop",null),t([T()],A.prototype,"updateWebDocument",null),A=t([x("esri.widgets.TimeSlider.TimeSliderViewModel")],A);const I=A;export{I as default};
5
+ import{_ as t}from"../../chunks/tslib.es6.js";import e from"../../TimeExtent.js";import i from"../../TimeInterval.js";import n from"../../core/Collection.js";import s from"../../core/Evented.js";import{HandleOwnerMixin as r}from"../../core/HandleOwner.js";import o from"../../core/Logger.js";import{isSome as l,isNone as a,unwrap as m,applySome as u}from"../../core/maybe.js";import{after as p,isAbortError as d}from"../../core/promiseUtils.js";import{watch as h,whenOnce as c,initial as f,syncAndInitial as g}from"../../core/reactiveUtils.js";import{offsetDate as w}from"../../core/timeUtils.js";import{property as T}from"../../core/accessorSupport/decorators/property.js";import"../../core/arrayUtils.js";import{ensureType as v}from"../../core/accessorSupport/ensureType.js";import{subclass as x}from"../../core/accessorSupport/decorators/subclass.js";import E from"../../webdoc/Widgets.js";import y from"../../webdoc/widgets/TimeSlider.js";const _=1e4;function b(t){return l(t)&&void 0!==t.count}function C(t){return l(t)&&void 0!==t.interval}function S(t){return l(t)&&void 0!==t.dates}function j(t){return"esri.WebMap"===t.declaredClass}let A=class extends(r(s.EventedAccessor)){constructor(t){super(t),this._animationController=null,this._isViewTimeExtentInitialized=!1,this._timerId=null,this.actions=new n,this.fullTimeExtent=null,this.loop=!1,this.mode="time-window",this.stops={count:10},this.timeExtent=null,this.view=null}initialize(){this.handles.add([h((()=>this.effectiveStops),(()=>{a(this.timeExtent)&&(this.timeExtent=this._getDefaultTimeExtent())}),f),h((()=>this.view),((t,e)=>{this._unregisterWidget(e),this._registerWidget(t)}),g),h((()=>this.timeExtent),(t=>{if(a(this.view))return;const e=this.view.timeExtent;(a(t)||t.isAllTime)&&(a(e)||e.isAllTime)||l(t)&&l(e)&&t.equals(e)||(this.view.timeExtent=m(t))}),f),h((()=>u(this.view,(t=>t.timeExtent))),(t=>{this._isViewTimeExtentInitialized?(a(t)||t.isAllTime)&&(a(this.timeExtent)||this.timeExtent.isAllTime)||l(t)&&l(this.timeExtent)&&t.equals(this.timeExtent)||(this.timeExtent=t):this._isViewTimeExtentInitialized=!0}))])}destroy(){l(this._timerId)&&(clearInterval(this._timerId),this._timerId=null),this._unregisterWidget(this.view),this.view=null,l(this._animationController)&&(this._animationController.abort(),this._animationController=null)}get effectiveStops(){const{fullTimeExtent:t,stops:e}=this;if(S(e)){const{dates:i}=e;if(null==i||0===i.length)return null;const n=i.sort(((t,e)=>t.getTime()-e.getTime()));if(a(t))return n;const{start:s,end:r}=t;if(a(s)||a(r))return n;return n.filter((t=>!(t.getTime()<s.getTime()||t.getTime()>r.getTime())))}if(b(e)){const i=e.timeExtent??m(t);return this._divideTimeExtentByCount(i,e.count)}if(C(e)){const i=e.timeExtent??m(t);return this._divideTimeExtentByInterval(i,e.interval)}return[]}set playRate(t){t<=0||t>36e5||("playing"===this.state&&this._startAnimation(),this._set("playRate",t))}get state(){return a(this.fullTimeExtent)?"disabled":l(this._animationController)?"playing":"ready"}get timeExtentValues(){const{mode:t,timeExtent:e}=this;if(a(e)||e.isAllTime||e.isEmpty)return null;const{start:i,end:n}=e;switch(t){case"cumulative-from-end":case"instant":return l(i)?[i.getTime()]:null;case"cumulative-from-start":return l(n)?[n.getTime()]:null;case"time-window":return l(i)&&l(n)?[i.getTime(),n.getTime()]:null}}static async getPropertiesFromWebMap(t,e){if(a(t)||!j(t))return null;await t.load({signal:e});const i=t?.widgets?.timeSlider;if(!i)return null;const{getFullTimeExtentFromWebDocument:n,getModeFromTimeSlider:s,getStopsFromTimeSlider:r,getTimeExtentFromTimeSlider:o}=await import("./utils.js"),l=await n(t,e),m=i.loop,u=s(i);return{fullTimeExtent:l,loop:m,mode:u,playRate:i.stopDelay??2e3,stops:r(i),timeExtent:o(i,u)}}next(){this._step({forward:!0,allowRestart:!1})}play(){this._startAnimation()}previous(){this._step({forward:!1,allowRestart:!1})}stop(){this._stopAnimation()}triggerAction(t){this.emit("trigger-action",{action:t})}updateWebDocument(t){if(j(t)){const e=new y({currentTimeExtent:this.timeExtent,fullTimeExtent:this.fullTimeExtent,loop:this.loop,numStops:b(this.stops)?this.stops.count:null,numThumbs:"time-window"===this.mode?2:1,stopDelay:this.playRate,stopInterval:C(this.stops)?this.stops.interval:null,stops:S(this.stops)?this.stops.dates:null});t.widgets?t.widgets.timeSlider=e:t.widgets=new E({timeSlider:e})}}valuesToTimeExtent(t){if(a(t))return null;const i=t.sort(((t,e)=>t-e)).map((t=>new Date(t))),n=i.length>0?i[0]:null,s=i.length>1?i[1]:null;switch(this.mode){case"time-window":return new e({start:n,end:s});case"instant":return new e({start:n,end:n});case"cumulative-from-start":return new e({start:null,end:n});case"cumulative-from-end":return new e({start:n,end:null});default:return e.allTime}}async _animate(){try{const t=this.view,e=u(this._animationController,(t=>t.signal));await Promise.all([p(this.playRate,null,e),l(t)&&c((()=>!1===t.updating),e)])}catch(t){return d(t)||o.getLogger(this.declaredClass).error(t),void(this._animationController=null)}this._step({forward:!0,allowRestart:!1}),a(this._animationController)||this._animate()}_divideTimeExtentByCount(t,e=10){if(!t||!e)return[];const{start:i,end:n}=t;if(a(i)||a(n))return[];if(e>_)return this._divideTimeExtentByCount(t);const s=[],r=i.getTime(),o=n.getTime()-r;for(let l=0;l<=e;l++)s.push(new Date(r+l/e*o));return s}_divideTimeExtentByInterval(t,e,i=_){if(!t||!e)return[];const{start:n,end:s}=t;if(a(n)||a(s))return[];const r=s.getTime()-n.getTime(),o=e.toMilliseconds();if(o<=0||r/o>i)return this._divideTimeExtentByCount(t);const l=[],{value:m,unit:u}=e;let p=n;for(;p.getTime()<=s.getTime();)l.push(new Date(p.getTime())),p=w(p,m,u);return l}_getDefaultTimeExtent(){const{effectiveStops:t,mode:i}=this;if(a(t)||!i)return null;switch(i){case"time-window":return t.length>1?new e({start:t[0],end:t[1]}):null;case"cumulative-from-start":return t.length>0?new e({start:null,end:t[0]}):null;case"cumulative-from-end":return t.length>0?new e({start:t[0],end:null}):null;case"instant":return t.length>0?new e({start:t[0],end:t[0]}):null;default:return null}}_registerWidget(t){if(l(t)){t.persistableViewModels.includes(this)||t.persistableViewModels.add(this)}}_startAnimation(){this._stopAnimation(),this._animationController=new AbortController,this._step({forward:!0,allowRestart:!0}),this._animate()}_step(t){const{forward:e,allowRestart:i}=t,{effectiveStops:n}=this;if(a(this.timeExtentValues)||a(n))return;const s=n.map((t=>t.getTime())),r=this.timeExtentValues.map((t=>{const e=s.indexOf(t);if(-1!==e)return e;const i=s.reduce(((e,i)=>Math.abs(i-t)<Math.abs(e-t)?i:e));return s.indexOf(i)})),o=r.map((t=>t+(e?1:-1))),l=o.some((t=>t<0||t>s.length-1)),{loop:m,state:u}=this;if(l)if(m||i){const t=Math.min(...r),i=Math.max(...r),n=(e?r.map((e=>e-t)):r.map((t=>t+(s.length-1-i)))).map((t=>s[t]));this.timeExtent=this.valuesToTimeExtent(n)}else"playing"===u&&this.stop();else{const t=o.map((t=>s[t]));this.timeExtent=this.valuesToTimeExtent(t)}}_stopAnimation(){l(this._animationController)&&(this._animationController.abort(),this._animationController=null)}_unregisterWidget(t){l(t)&&t.persistableViewModels.remove(this)}};t([T()],A.prototype,"_animationController",void 0),t([T({type:n})],A.prototype,"actions",void 0),t([T({readOnly:!0})],A.prototype,"effectiveStops",null),t([T({type:e})],A.prototype,"fullTimeExtent",void 0),t([T({nonNullable:!0})],A.prototype,"loop",void 0),t([T({nonNullable:!0})],A.prototype,"mode",void 0),t([T({nonNullable:!0,value:1e3})],A.prototype,"playRate",null),t([T({readOnly:!0})],A.prototype,"state",null),t([T({cast:t=>a(t)?null:(C(t)&&(t.interval=v(i,t.interval)),(C(t)||b(t))&&(t.timeExtent=v(e,t.timeExtent)),t)})],A.prototype,"stops",void 0),t([T({type:e})],A.prototype,"timeExtent",void 0),t([T({readOnly:!0})],A.prototype,"timeExtentValues",null),t([T()],A.prototype,"view",void 0),t([T()],A.prototype,"next",null),t([T()],A.prototype,"play",null),t([T()],A.prototype,"previous",null),t([T()],A.prototype,"stop",null),t([T()],A.prototype,"updateWebDocument",null),A=t([x("esri.widgets.TimeSlider.TimeSliderViewModel")],A);const I=A;export{I as default};