@arcgis/core 4.24.0-next.20220622 → 4.24.2

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 (68) hide show
  1. package/assets/esri/core/workers/RemoteClient.js +1 -1
  2. package/assets/esri/core/workers/chunks/{aa14e999e03ccb770455.js → 48576ac3dd2efaa25141.js} +1 -1
  3. package/assets/esri/core/workers/chunks/{6a02a75e935af0fc2b2b.js → a68428fde8bc960da276.js} +1 -1
  4. package/assets/esri/core/workers/chunks/{e5c8584ae764892c324d.js → d1bc85b78d6f217b022a.js} +1 -1
  5. package/assets/esri/themes/base/widgets/_Editor.scss +6 -0
  6. package/assets/esri/themes/base/widgets/_SnappingControls.scss +4 -0
  7. package/assets/esri/themes/dark/main.css +1 -1
  8. package/assets/esri/themes/light/main.css +1 -1
  9. package/assets/esri/themes/light/view.css +1 -1
  10. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_ar.json +1 -1
  11. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_bg.json +1 -1
  12. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_bs.json +1 -1
  13. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_ca.json +1 -1
  14. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_cs.json +1 -1
  15. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_da.json +1 -1
  16. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_de.json +1 -1
  17. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_el.json +1 -1
  18. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_es.json +1 -1
  19. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_et.json +1 -1
  20. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_fi.json +1 -1
  21. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_fr.json +1 -1
  22. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_he.json +1 -1
  23. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_hr.json +1 -1
  24. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_hu.json +1 -1
  25. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_id.json +1 -1
  26. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_it.json +1 -1
  27. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_ja.json +1 -1
  28. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_ko.json +1 -1
  29. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_lt.json +1 -1
  30. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_lv.json +1 -1
  31. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_nb.json +1 -1
  32. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_nl.json +1 -1
  33. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_pl.json +1 -1
  34. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_pt-BR.json +1 -1
  35. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_pt-PT.json +1 -1
  36. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_ro.json +1 -1
  37. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_ru.json +1 -1
  38. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_sk.json +1 -1
  39. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_sl.json +1 -1
  40. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_sr.json +1 -1
  41. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_sv.json +1 -1
  42. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_th.json +1 -1
  43. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_tr.json +1 -1
  44. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_uk.json +1 -1
  45. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_vi.json +1 -1
  46. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_zh-CN.json +1 -1
  47. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_zh-HK.json +1 -1
  48. package/assets/esri/widgets/BasemapToggle/t9n/BasemapToggle_zh-TW.json +1 -1
  49. package/config.js +1 -1
  50. package/package.json +1 -1
  51. package/support/revision.js +1 -1
  52. package/views/2d/engine/webgl/WorldExtentClipRenderer.js +1 -1
  53. package/views/3d/analysis/Slice/SliceTool.js +1 -1
  54. package/views/3d/interactive/editingTools/manipulations/MoveXYAxisManipulation.js +1 -1
  55. package/views/3d/interactive/editingTools/transformGraphic/GraphicScaleRotateTransform.js +1 -1
  56. package/views/3d/state/utils/navigationUtils.js +1 -1
  57. package/views/3d/terrain/Tile.js +1 -1
  58. package/views/3d/terrain/TileCompositor.js +1 -1
  59. package/views/3d/terrain/TileRenderer.js +1 -1
  60. package/views/webgl/context-util.js +1 -1
  61. package/widgets/Editor/UpdateWorkflow.js +1 -1
  62. package/widgets/Editor.js +1 -1
  63. package/widgets/FeatureForm/FeatureFormViewModel.js +1 -1
  64. package/widgets/FeatureForm/InputField.js +1 -1
  65. package/widgets/FeatureForm.js +1 -1
  66. package/widgets/support/SnappingControls/SnappingControlsViewModel.js +1 -1
  67. package/widgets/support/SnappingControls/SnappingLayerListViewModel.js +1 -1
  68. package/widgets/support/SnappingControls/SnappingListItem.js +1 -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.24/esri/copyright.txt for details.
4
4
  */
5
- import{clamp as e}from"../../../core/mathUtils.js";import{isNone as t,isSome as i,abortMaybe as s}from"../../../core/maybe.js";import n from"../../../core/ObjectPool.js";import{c as r,a}from"../../../chunks/vec2.js";import{a as o}from"../../../chunks/vec2f64.js";import{b as h,p as l,e as d,g as u,a as c,l as g}from"../../../chunks/vec3.js";import{c as f,u as p}from"../../../chunks/vec3f64.js";import{E as m}from"../../../chunks/common.js";import{getReferenceEllipsoid as _}from"../../../geometry/projectionEllipsoid.js";import{create as A,equals as y}from"../../../geometry/support/aaBoundingRect.js";import{c as E}from"../../../chunks/sphere.js";import{VectorTile as v}from"../../2d/engine/vectorTiles/VectorTile.js";import{ImageWithType as T}from"../support/StreamDataLoader.js";import{ElevationBounds as L}from"./ElevationBounds.js";import{ElevationTileAgent as M}from"./ElevationTileAgent.js";import{LODSnapping as I,TextureUpdate as D,NeighborIndex as N}from"./interfaces.js";import{LayerClass as b,LayerClasses as S}from"./LayerClass.js";import{MapTileAgent as x}from"./MapTileAgent.js";import{RasterTile as j}from"./RasterTile.js";import{MAX_PATCH_TESSELATION as O,getElevationDesiredResolutionLevel as U}from"./TerrainConst.js";import{weakAssert as C,getLayerWithExtentRange as R,isBlendableLayerView as P,oppositeCorner as B,neighborCornerIndices as G,neighborEdgeIndices as V,oppositeEdge as W,internalAssert as w,isNorth as q,isSouth as H,isWest as F,isEast as k,ENABLE_WATERPROOFNESS_TESTS as X,isWestCorner as z,isNorthCorner as J}from"./terrainUtils.js";import{TILE_AGENT_DONE as Y}from"./TileAgent.js";import{TilePerLayerInfo as $}from"./TilePerLayerInfo.js";import Q from"./TileTexture.js";import{TileUpdate as K}from"./TileUpdate.js";import{fallsWithinLayer as Z}from"./tileUtils.js";import{getGpuMemoryUsage as ee}from"../../webgl/Util.js";const te=f(),ie=f(),se=f(),ne=.1;class re{constructor(){this.fovX=0,this.fovY=0,this.relativeWidthLimit=0,this.relativeHeightLimit=0,this.maxLod=0,this.angledSplitBias=0,this.aboveGround=!0}}class ae{constructor(){this.lij=[0,0,0],this._children=[null,null,null,null],this._pendingUpdates=0,this._dirty=!0,this._previouslyRendered=!1,this.extent=A(),this._elevationBounds=o(),this.layerInfo=[[],[]],this.extentInRadians=A(),this.centerAtSeaLevel=f(),this._center=[f(),E(),f()],this.up=p(),this._isWithinClippingArea=!0,this._intersectsClippingArea=!0,this._maxTesselation=0,this._usedMemory=null,this._mapTileMemory=0,this._mapDataRefCount=0,this._screenDepth=0,this.renderOrder=0,this._edgeLen=0,this._edgeLen2=0,this._curvatureHeight=0}static prune(){le.prune(0),de.prune(0),$.prune()}get usedMemory(){return t(this._usedMemory)&&this._updateMemoryUsed(),i(this._usedMemory)?this._usedMemory:0+(this.isCached?0:this.mapTileMemory)}get cachedMemory(){return this.isCached?this.mapTileMemory:0}get mapTileMemory(){t(this._usedMemory)&&this._updateMemoryUsed();let e=this._mapTileMemory;for(const{data:t}of this.layerInfo[b.MAP])t instanceof v&&(e+=t.memoryUsage);return e}get isCached(){return!this.shouldLoad&&this._mapDataRefCount<=0}get maxTesselation(){return this._maxTesselation}get isWithinClippingArea(){return this._isWithinClippingArea}get intersectsClippingArea(){return this._intersectsClippingArea}get clippingArea(){return this._clippingArea}get parent(){return this._parent}get children(){return this._children}get surface(){return this._surface}get elevationBounds(){return this._elevationBounds}get level(){return this.lij[0]}get key(){return`${this.lij[0]}/${this.lij[1]}/${this.lij[2]}`}get edgeLen(){return this._edgeLen}get radius(){return this._center[ce.MIDDLE][3]}get screenDepth(){return this._screenDepth}get visible(){return this._dirty&&this.computeVisibility(),this._visible}computeVisibility(){this._dirty=!1;const e=this._intersectsClippingArea&&this._isVisible(this.surface.frustum);return e!==this._visible&&(this._visible=e,this._surface.emit("tiles-visibility-changed"),this._surface.renderer.setNeedsRender(),this.updateAgentSuspension()),this._visible}get loadable(){return this.visible||this._surface.view.state.fixedContentCamera}get rendered(){const e=!!this.renderData;return e!==this._previouslyRendered&&(this._surface.emit("tiles-visibility-changed"),this._previouslyRendered=e,this._surface.renderer.setNeedsRender()),e}get shouldLoad(){if(this._surface.lodSnapping===I.ON){const e=this.level-this._surface.snapLevel;if(0===e)return!0;if(1===e)return!1}return this.isLeaf}init(e,t,i){this.lij[0]=e[0],this.lij[1]=e[1],this.lij[2]=e[2],this.ellipsoid=_(i.tilingScheme.spatialReference),i.tilingScheme.getExtent(e[0],e[1],e[2],this.extent),i.tilingScheme.convertExtentToRadians(this.extent,this.extentInRadians),this._isWithinClippingArea=!0,this._intersectsClippingArea=!0,this._clippingArea=null,this._mapDataRefCount=0,i.upsampleMapCache.pop(this.key),this._edgeLen=0,this._edgeLen2=0,this._center[ce.MIDDLE][3]=0,this.vlevel=e?e[0]:0,t&&t.elevationBounds?r(this._elevationBounds,t.elevationBounds):a(this._elevationBounds,0,0),this._pendingUpdates=0,this.renderData=null,this._screenDepth=0,this._visible=!1,this._previouslyRendered=!1,this._parent=t,this.unsetChildren(),this._surface=i,this.updateVisibility();for(const s of S){const e=i.numLayers(s),t=this.layerInfo[s];for(const i of t)i.release();t.length=e;for(let i=0;i<e;i++)t[i]=$.acquire(this._surface.upsampleInfoPool),s===b.ELEVATION&&this.findElevationBoundsForLayer(i,-1)}this.computeElevationBounds(),this._maxTesselation=Math.min(i.tilingScheme.pixelSize,O)}release(){C(!this.renderData,"tile.renderData was not unloaded"),this._surface.upsampleMapCache.pop(this.key);for(const e of S){for(const t of this.layerInfo[e])t.release();this.layerInfo[e].length=0}this._parent=null,this._surface=null,this._usedMemory=null}refMapData(){++this._mapDataRefCount,this.isCached||this._surface.upsampleMapCache.pop(this.key)}unrefMapData(){if(--this._mapDataRefCount,this.isCached){const e=this.cachedMemory;e>0&&(this._surface.upsampleMapCache.put(this.key,this,e),this.setMemoryDirty())}}setMemoryDirty(){this._usedMemory=null}get cpuImageMemorySize(){const e=4,t=this._surface.tilingScheme.pixelSize;return t*t*e}_updateMemoryUsed(){this._usedMemory=0,this._mapTileMemory=0;const e=this.layerInfo[b.MAP];for(let i=0;i<e.length;i++)this._mapTileMemory+=this.getUsedMemoryForLayer(b.MAP,i);const t=this.cpuImageMemorySize;for(const i of this.layerInfo[b.ELEVATION])this._usedMemory+=i.data?t:0;this.renderData&&(this._usedMemory+=this.renderData.estimatedGeometryMemoryUsage,this._mapTileMemory+=ee(this.renderData.textureDescriptor)),this.isCached&&this._surface.upsampleMapCache.updateSize(this.key,this,this.cachedMemory)}getUsedMemoryForLayer(e,t){const i=this.layerInfo[e][t];if(!i||!i.data)return 0;if(e!==b.MAP||this.isCached){if(e===b.ELEVATION)return this.cpuImageMemorySize}else{const e=i.data;if(e instanceof Q)return ee(e.texture);if(e instanceof HTMLImageElement||e instanceof T)return this.cpuImageMemorySize;if(e instanceof v||e instanceof j)return e.memoryUsage}return 0}updateScreenDepth(e){const t=this._center[ce.MIDDLE],i=e,s=t[0],n=t[1],r=t[2],a=i[2]*s+i[6]*n+i[10]*r+i[14];this._screenDepth=a<0?0:a/(i[3]*s+i[7]*n+i[11]*r+i[15])}shouldSplit(e,t,s){if(i(e.frustum)&&(!this._intersectsClippingArea||!this._isVisible(e.frustum)))return K.NONE;const n=this.level;h(te,this._center[ce.MIDDLE],t);let r=l(te),a=ce.MIDDLE;h(ie,this._center[ce.TOP],t);const o=l(ie);o<r&&(r=o,a=ce.TOP),h(ie,this._center[ce.BOTTOM],t);const f=l(ie);if(f<r&&(r=f,a=ce.BOTTOM),this._edgeLen2>r&&n<e.maxLod)return K.SPLIT;const p=Math.sqrt(r),m=e.fovX*p*2,_=this._edgeLen/m,A=()=>{const t=n+Math.ceil(-Math.log2(e.relativeWidthLimit/_));return t!==this.vlevel?(this.vlevel=t,K.VSPLITMERGE):K.NONE_HIT_MAXLOD};if(s===I.ON){if(1===this._surface.snapLevel-n)return n>=e.maxLod?A():K.SPLIT}const y=d(this.up,te),E=this._elevationBounds[1]-this._elevationBounds[0],v=E/this.edgeLen;if(e.aboveGround&&y>0&&v<.001){if(y/p-Math.sin(this._curvatureHeight/(this.edgeLen*Math.SQRT1_2)*Math.PI)-v>0)return K.NONE}if(_<e.relativeWidthLimit)return this.vlevel!==this.level?(this.vlevel=this.level,K.VSPLITMERGE):K.NONE;if(n>=e.maxLod)return A();if(n>6){h(ie,this._center[a],t),u(se,this.up,y),h(se,se,ie);const i=l(se);if(i>this.radius*this.radius){u(se,se,this.radius/Math.sqrt(i)),c(se,se,this._center[a]),h(se,t,se);const s=Math.min(1,(Math.abs(d(se,this.up))+.5*E+this._curvatureHeight)/g(se)),n=ne/e.angledSplitBias,r=e.fovY*p*2;if(s*(this._edgeLen/r)<n*e.relativeHeightLimit)return K.NONE}}return K.SPLIT}setChildren(e,t,i,s){C(!!(e&&t&&i&&s),"Null child passed"),this._children[0]=e,this._children[1]=t,this._children[2]=i,this._children[3]=s}unsetChildren(){this._children[0]=null,this._children[1]=null,this._children[2]=null,this._children[3]=null}get isLoaded(){return this.renderData?.hasGeometry??!1}prepareToLoad(e){this.refMapData();for(const t of S)this._createOrUpdateAgents(0,t);e.updateTileGeometryState(this)}load(e){this.prepareToLoad(e),this.loadPrepared(e)}loadPrepared(e){e.loadTile(this)}unload(e){e.unloadTile(this);for(const t of S){const e=this.layerInfo[t];for(const t of e)t.loadingAgent&&t.loadingAgent!==Y&&(he(t.loadingAgent),t.loadingAgent=null),t.pendingUpdates=0}this.resetPendingUpdate(K.GEOMETRY),this.resetPendingUpdate(K.TEXTURE_NOFADING),this.resetPendingUpdate(K.TEXTURE_FADING),this.unrefMapData()}unloadMapData(){const e=this.layerInfo[b.MAP];for(const t of e)t.loadingAgent&&t.loadingAgent!==Y&&(he(t.loadingAgent),t.loadingAgent=null),t.pendingUpdates=0;this.renderData&&this.renderData.releaseTexture(),this.setMemoryDirty()}updateClippingStatus(e){if(y(e,this._clippingArea))return!1;const t=this._intersectsClippingArea,s=this._isWithinClippingArea;i(e)?(this._intersectsClippingArea=this.intersectsExtent(e),this._isWithinClippingArea=this._isWithinExtent(e)):(this._intersectsClippingArea=!0,this._isWithinClippingArea=!0),this._clippingArea=e,this.updateVisibility();const n=s&&this._isWithinClippingArea,r=!(s||t||this._isWithinClippingArea||this._intersectsClippingArea);return!this.renderData||n||r||this.setPendingUpdate(K.GEOMETRY),!0}updateVisibility(){this._dirty=!0,this._surface.setTileTreeDirty()}getLayerInfo(e,t){return this.layerInfo[t][e]}hasLayerData(e,t){const i=this.layerInfo[t][e];return!(!i||!i.data||i.dataInvalidated)}get updating(){if(this.hasPendingUpdates)return!0;for(const e of S){const t=this.layerInfo[e];for(const e of t)if(e.loadingAgent&&e.loadingAgent!==Y&&e.loadingAgent.updating)return!0}return!1}_isSuspended(e){return!!this.hasPendingUpdate(K.SPLIT)||e!==b.ELEVATION&&!this.loadable}get hasPendingUpdates(){return 0!==this._pendingUpdates}hasPendingUpdate(e){return(this._pendingUpdates&e)===e}setPendingUpdate(e){this._pendingUpdates|=e,e===K.SPLIT||e===K.MERGE?this._surface.setTileTreeDirty():this._surface.requestUpdate()}resetPendingUpdate(e){return!!this.hasPendingUpdate(e)&&(this._pendingUpdates&=~e,!0)}requestLayerData(e,t,i){const n=this.layerInfo[t][e];if(n.waitingAgents.has(i))return console.warn("agent already requested this piece of map data (tile %s, agent tile %s, layer: %d/%d)",this.lij.toString(),i.tile.lij.toString(),t,e),!0;if(n.waitingAgents.push(i),n.data&&!n.dataInvalidated)return console.warn("agent requested existing data (tile %s, agent tile %s, layer: %d/%d)",this.lij.toString(),i.tile.lij.toString(),t,e),i.dataArrived(this),!0;if(n.requestPromise)return!0;s(n.requestAbort),n.requestAbort=new AbortController;const r=this._surface.requestTileData(this,e,t,n.requestAbort);if(!r)return n.requestAbort=null,!1;const a=()=>{n.requestPromise===r&&(n.requestPromise=null,n.requestAbort=null)};return n.requestPromise=r,r.then(a,a),!0}get isLeaf(){return null==this._children[0]}hasLij(e){return this.lij[0]===e[0]&&this.lij[1]===e[1]&&this.lij[2]===e[2]}findByLij(e){if(this.hasLij(e))return this;if(this.isLeaf)return null;const t=this._children[0].findByLij(e)||this._children[1].findByLij(e)||this._children[2].findByLij(e)||this._children[3].findByLij(e);return t||null}distanceToSquared(e){return l(h(se,this._center[ce.MIDDLE],e))}containsPoint(e){const t=this.extent;return e[0]>=t[0]&&e[1]>=t[1]&&e[0]<=t[2]&&e[1]<=t[3]}unrequestLayerData(e,t,i){const s=this.layerInfo[t][e],n=s.waitingAgents,r=null!=n.removeUnordered(i);C(r,"agent has not requested this piece of map data"),n.length<1&&(s.abortRequest(),this._updateMemoryUsed())}dataArrived(e,t,i){const s=this.layerInfo[t][e];s.data=i,s.dataInvalidated=!1,s.waitingAgents.forAll((e=>e.dataArrived(this))),s.waitingAgents.clear(),this._updateMemoryUsed()}dataMissing(e,t,i){i.notInTilemap||console.error(`Tile ${this.lij.toString()} layer ${t}/${e} error ${i}`);const s=this.layerInfo[t][e];s.dataMissing=!0,s.waitingAgents.forAll((e=>e.dataMissing())),s.waitingAgents.clear(),this._updateMemoryUsed()}updateRenderData(e,t){switch(e){case b.MAP:return this._updateTexture(t);case b.ELEVATION:return this._updateGeometry()}}_updateTexture(e){this.renderData&&(this.resetPendingUpdate(e===D.FADING?K.TEXTURE_NOFADING:K.TEXTURE_FADING),this.setPendingUpdate(e===D.FADING?K.TEXTURE_FADING:K.TEXTURE_NOFADING))}_updateGeometry(){this.setPendingUpdate(K.GEOMETRY);for(const e of this.layerInfo[b.ELEVATION])e.pendingUpdates|=K.GEOMETRY}invalidateLayerData(e,t){this.layerInfo[t][e].invalidateSourceData(),this.restartAgents(t)}computeElevationBounds(){const e=this._elevationBounds;a(e,Number.MAX_VALUE,-Number.MAX_VALUE);const t=this.layerInfo[b.ELEVATION];let s=!0;for(const n of t)i(n.elevationBounds)&&(e[0]=Math.min(e[0],n.elevationBounds.min),e[1]=Math.max(e[1],n.elevationBounds.max),n.elevationBounds.hasNoDataValues||(s=!1));s&&(e[0]=Math.min(e[0],0),e[1]=Math.max(e[1],0)),this.updateRadiusAndCenter(),this._surface.setTileTreeDirty()}_updateCenter(){const e=this._elevationBounds,t=.5*(e[0]+e[1]);u(se,this.up,t),c(this._center[ce.MIDDLE],this.centerAtSeaLevel,se),u(se,this.up,e[0]),c(this._center[ce.TOP],this.centerAtSeaLevel,se),u(se,this.up,e[1]),c(this._center[ce.BOTTOM],this.centerAtSeaLevel,se)}findElevationBoundsForLayer(e,s){const n=this.layerInfo[b.ELEVATION][e];if(i(n.elevationBounds)&&n.elevationBounds.level>=s)return;const r=this._surface.layerViewByIndex(e,b.ELEVATION),a=R(r);if(!Z(this,a,!1))return;const o=ue;let h=!1;if(n.data){const e=n.data;o.min=e.bounds[0],o.max=e.bounds[1],o.hasNoDataValues=e.hasNoDataValues,o.level=this.level,h=!0}else{let t,i,s=0;for(let n=this._parent;n&&(!i||s<U(this.level))&&(s=this.vlevel-n.level,t=i||t,i=n.layerInfo[b.ELEVATION][e].data,!(!i&&t&&s>=U(this.level)));n=n.parent);i=i||t,i&&(i.computeMinMaxValue(this.lij[0],this.lij[1],this.lij[2],o),o.min!==1/0&&(o.level=i.level,h=!0))}h&&(t(n.elevationBounds)&&(n.elevationBounds=new L),n.elevationBounds.copyFrom(o))}modifyLayers(e,t,i){const s=this.layerInfo[i];for(const a of s)a.loadingAgent&&a.loadingAgent!==Y&&(he(a.loadingAgent),a.loadingAgent=null),a.waitingAgents.clear();for(let a=0;a<s.length;++a)void 0===e[a]&&s[a].release();const n=new Array(...s),r=t.length;s.length=r;for(let a=0;a<r;a++){const e=t[a];s[a]=e>-1?n[e]:$.acquire(this._surface.upsampleInfoPool)}this._updateMemoryUsed()}restartAgents(e){this.renderData&&(this._createOrUpdateAgents(0,e),this.updateRenderData(e,D.FADING))}updateAgents(e){if(this.renderData){const t=this.layerInfo[e];for(const e of t)e.loadingAgent===Y&&(e.loadingAgent=null);this._createOrUpdateAgents(0,e)}}updateAgentSuspension(){for(const e of S){const t=this._isSuspended(e);for(const i of this.layerInfo[e])i.loadingAgent&&i.loadingAgent!==Y&&(i.loadingAgent.setSuspension(t),i.loadingAgent===Y&&this.updateRenderData(e,D.FADING))}}removeLayerAgent(e,t){const i=this.layerInfo[t][e];i.loadingAgent&&i.loadingAgent!==Y&&i.loadingAgent.dispose(),i.loadingAgent=null}agentDone(e,i){const s=this.layerInfo[i][e];s.loadingAgent=Y,!s.data&&t(s.upsampleInfo)&&this._createOrUpdateAgents(e+1,i)}_createOrUpdateAgents(e,t){const i=this.layerInfo[t];if(0===i.length)return;const s=(()=>{for(let s=e;s<i.length;++s){const e=this._surface.layerViewByIndex(s,t);if(P(e)&&"normal"!==e.layer.blendMode)return!0}return!1})(),n=this._isSuspended(t);for(let r=e;r<i.length;++r){const e=i[r];let a=!1;const o=this._surface.layerViewByIndex(r,t),h=R(o);if(e.loadingAgent?Z(this,h,!1)?(e.loadingAgent!==Y&&e.loadingAgent.setSuspension(n),e.loadingAgent!==Y&&(a=e.loadingAgent.update())):e.dispose():Z(this,h,!1)&&(e.loadingAgent=oe(this,r,t,n),a=e.loadingAgent.startLoading(),a?e.loadingAgent===Y&&this.setPendingUpdate(K.GEOMETRY):(he(e.loadingAgent),e.loadingAgent=Y)),e.loadingAgent===Y&&this.updateRenderData(t,D.FADING),!s&&a&&o.isOpaque)return}}_isWithinExtent(e){const t=this.extent;return t[0]>=e[0]&&e[2]>=t[2]&&t[1]>=e[1]&&e[3]>=t[3]}intersectsExtent(e){const t=this.extent;return t[2]>=e[0]&&e[2]>=t[0]&&t[3]>=e[1]&&e[3]>=t[1]}getElevationBasedVerticesPerSide(t){const i=this.vlevel-this.level,s=Math.max(this.level-t,U(this.level)-i);return e(1+(this.maxTesselation>>s),2,this.maxTesselation+1)}get test(){return{cachedMemory:this.cachedMemory}}_findLIJ(e,t){if(!e)return null;const s=this.surface.rootTiles;if(i(s))for(const i of s)if(ge(i,e)){let s=i,n=e[0]-s.level-1;for(;n>=0&&!s.isLeaf&&!t(s);){const t=e[1]>>n&1,i=e[2]>>n&1;s=s.children[2*t+i],n--}return t(s)?s:null}return null}findNeighborTile(e,t){const i=this.lij,s=this.getNeighborLIJ(i,e);return s?fe(i,s)?t(this)?this:null:this._findLIJ(s,t):null}findCorner(e,t){const i=e===N.NORTH_EAST?1:e===N.NORTH_WEST?0:e===N.SOUTH_WEST?2:3;let s=this;for(;!(s.isLeaf||t&&t(s));)s=s.children[i];return s}findNeighborCornerTileExact(e,t){return this.findNeighborTile(e,(e=>t(e)||e.level===this.level))?.findCorner(B(e),t)}forAllSubtreeOnSide(e,t){const i=e===N.NORTH?[0,1]:e===N.NORTH_EAST?[1]:e===N.EAST?[1,3]:e===N.SOUTH_EAST?[3]:e===N.SOUTH?[2,3]:e===N.SOUTH_WEST?[2]:e===N.WEST?[0,2]:[0],s=e=>{t(e)||e.isLeaf||i.forEach((t=>s(e.children[t])))};s(this)}forallNeighbors(e){G.forEach((t=>this.findNeighborCornerTileExact(t,e))),V.forEach((t=>this.findNeighborTile(t,(t=>t.level===this.level||e(t)))?.forAllSubtreeOnSide(W(t),e)))}getNeighborEdgeStartVertexIndex(e,t){const i=t??this.findNeighborTile(V[e],(e=>e.isLoaded));if(!i||!this.isLoaded||!i.isLoaded)return 0;const s=this.level-i.level;if(0===s)return 0;const n=2**s,r=1==(1&e),a=r?0:1,o=i.lij[a+1]*n,h=this.lij[a+1]-o;return r?n-1-h:h}_updateNeighborsWithChangedEdgeResolution(){for(let e=0;e<4;++e)if(this.renderData.geometryState.neighborData.modifiedEdgeResolutions[e]){const t=V[e],i=this.findNeighborTile(t,(e=>e.isLoaded||e.level===this.level));if(!i)continue;if(!i.isLoaded){w(!i.isLeaf);const s=(e+2)%4,n=W(t);i.forAllSubtreeOnSide(n,(e=>e.isLoaded?(e.updateEdgeAfterResolutionChange(s),!0):(w(!e.isLeaf),!1)))}this.renderData.geometryState.neighborData.modifiedEdgeResolutions[e]=!1}}updateNeighborDataAndGeometryIfNeeded(){this.isLoaded&&this.renderData.updateNeighborDataAndGeometryIfNeeded()}updateNeighborsAfterGeometryChange(e=this.level){this.forEachLoadedNeighbor((e=>this._updateNeighbor(e))),V.forEach((t=>{this.findNeighborTile(t,(t=>t.isLoaded&&t.level<e))?.updateNeighborsWithChangedEdgeResolution()}))}updateNeighborsWithChangedEdgeResolution(){this.isLoaded&&this._updateNeighborsWithChangedEdgeResolution()}updateEdgeAfterResolutionChange(e){this.renderData.updateEdgeAfterResolutionChange(e)}forEachLoadedNeighbor(e){const t=this.level,i=e=>e.level===t||e.isLoaded;V.forEach(((t,s)=>{const n=this.findNeighborTile(t,i);null!=n&&n!==this&&n.forAllSubtreeOnSide(W(t),(t=>!!t.isLoaded&&(e(t),!0)));const r=this.renderData?.geometryState?.neighborData;r&&(r.modifiedEdgeResolutions[s]=!1)})),G.forEach((t=>{const s=this.findNeighborTile(t,i)?.findCorner(B(t),(e=>e.isLoaded));w(!s||_e(this,s,t)),s?.isLoaded&&e(s)}))}_updateNeighbor(e){e?.isLoaded&&e.updateNeighborDataAndGeometryIfNeeded()}getNeighborLIJ(e,t){const i=q(t)?-1:H(t)?1:0,s=F(t)?-1:k(t)?1:0,n=[e[0],e[1]+i,e[2]+s];return n[1]<0?null:this.surface.isGlobal?this.wrapLIJ(n):n[2]<0?null:n}wrapLIJ(e){return!e||e[1]<0||e[1]>=2**e[0]?null:this.surface.wrapEastWest(e)}get westNeighborWestExtent(){return this.extent[0]*(this.isWestEnd?-1:1)}get eastNeighborEastExtent(){return this.extent[2]*(this.isEastEnd?-1:1)}get isEastEnd(){return this.lij[2]===this.surface.lijEastEnd(this.level)-1}get isWestEnd(){return 0===this.lij[2]}get isNorthEnd(){return 0===this.lij[1]}get isSouthEnd(){return this.extent[1]+m>=this.surface.extent[1]}compareLIJs(e){const t=this.lij,i=t[0],s=e[0];if(i===s)return[t,e];const n=i-s;if(n<0){const i=2**-n;return[[s,t[1]*i,t[2]*i],e]}{const s=2**n;return[t,[i,e[1]*s,e[2]*s]]}}checkGeometryWaterproofness(){X&&(w(this.isLoaded),this.renderData.checkGeometryWaterproofness())}shouldHaveNeighbor(e){const t=this.extent,i=this.surface.rootTilesExtent,s=.25*(t[2]-t[0]);if(q(e)&&t[3]+s>=i[3])return!1;if(H(e)&&t[1]-s<=i[1])return!1;const n=this.surface.isGlobal;return!(!n&&F(e)&&t[0]-s<=i[0])&&!(!n&&k(e)&&t[2]+s>=i[2])}}function oe(e,t,i,s){const n=i===b.ELEVATION?de.acquire():le.acquire();return n.init(e,t,i,s),n}function he(e){e.dispose(),e instanceof M?de.release(e):e instanceof x&&le.release(e)}const le=new n(x),de=new n(M),ue=new L;var ce;function ge(e,t){const i=e.level,s=t[0];if(i>s)return!1;const n=s-i,r=Math.floor(t[1]/2**n),a=Math.floor(t[2]/2**n);return r===e.lij[1]&&a===e.lij[2]}function fe(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function pe(e,t,i){return Math.abs(e-t)<=i}function me(e,i,s){if(t(e)||t(i))return!1;if(0===e.level&&0===i.level){if(e.isEastEnd&&i.isWestEnd&&s===N.EAST)return!0;if(e.isWestEnd&&i.isEastEnd&&s===N.WEST)return!0}const n=1e-6*(e.extent[2]-e.extent[0]);switch(s){case N.NORTH:return pe(e.extent[3],i.extent[1],n);case N.SOUTH:return pe(e.extent[1],i.extent[3],n);case N.EAST:return pe(e.extent[2],i.extent[0],n)||pe(e.extent[2],-i.extent[0],n);case N.WEST:return pe(e.extent[0],i.extent[2],n)||pe(e.extent[0],-i.extent[2],n)}}function _e(e,i,s){return!t(e)&&!t(i)&&i!==e&&(e.level>=i.level?Ae(e,i,s):Ae(i,e,B(s)))}function Ae(e,t,i){w(e.level>=t.level);const s=z(i),n=J(i),r=e.extent,a=t.extent,o=[s?r[0]:r[2],n?r[3]:r[1]],h=[s?a[2]:a[0],n?a[1]:a[3]],l=1e-5*(r[2]-r[0]),d=pe(o[0],h[0],l)||e.surface.isGlobal&&pe(o[0],-h[0],l),u=pe(o[1],h[1],l);if(d&&u)return!0;if(e.level===t.level)return!1;if(!d&&!u)return!1;return d?ye(a[1],a[3],r[1],r[3],l):ye(a[0],a[2],r[0],r[2],l)}function ye(e,t,i,s,n=m){return e-n<=i&&i<=s&&s<=t+n}!function(e){e[e.TOP=0]="TOP",e[e.MIDDLE=1]="MIDDLE",e[e.BOTTOM=2]="BOTTOM"}(ce||(ce={}));export{ce as CenterPosition,re as SplitLimits,ae as Tile,pe as almostEquals,_e as isCornerNeighbor,me as isEdgeNeighbor};
5
+ import{clamp as e}from"../../../core/mathUtils.js";import{isSome as t,abortMaybe as i,isNone as s}from"../../../core/maybe.js";import n from"../../../core/ObjectPool.js";import{c as r,a}from"../../../chunks/vec2.js";import{a as o}from"../../../chunks/vec2f64.js";import{b as h,p as l,e as d,g as u,a as c,l as g}from"../../../chunks/vec3.js";import{c as f,u as p}from"../../../chunks/vec3f64.js";import{E as m}from"../../../chunks/common.js";import{getReferenceEllipsoid as _}from"../../../geometry/projectionEllipsoid.js";import{create as y,equals as A}from"../../../geometry/support/aaBoundingRect.js";import{c as E}from"../../../chunks/sphere.js";import{VectorTile as T}from"../../2d/engine/vectorTiles/VectorTile.js";import{ImageWithType as v}from"../support/StreamDataLoader.js";import{ElevationBounds as L}from"./ElevationBounds.js";import{ElevationTileAgent as M}from"./ElevationTileAgent.js";import{TextureUpdate as D,LODSnapping as I,NeighborIndex as N}from"./interfaces.js";import{LayerClasses as b,LayerClass as S}from"./LayerClass.js";import{MapTileAgent as x}from"./MapTileAgent.js";import{RasterTile as j}from"./RasterTile.js";import{MAX_PATCH_TESSELATION as O,getElevationDesiredResolutionLevel as C}from"./TerrainConst.js";import{weakAssert as U,getLayerWithExtentRange as R,isBlendableLayerView as P,oppositeCorner as B,neighborCornerIndices as G,neighborEdgeIndices as V,oppositeEdge as W,internalAssert as w,isNorth as q,isSouth as H,isWest as F,isEast as k,ENABLE_WATERPROOFNESS_TESTS as X,isWestCorner as z,isNorthCorner as J}from"./terrainUtils.js";import{TILE_AGENT_DONE as Y}from"./TileAgent.js";import{TilePerLayerInfo as $}from"./TilePerLayerInfo.js";import Q from"./TileTexture.js";import{TileUpdate as K}from"./TileUpdate.js";import{fallsWithinLayer as Z}from"./tileUtils.js";import{getGpuMemoryUsage as ee}from"../../webgl/Util.js";const te=f(),ie=f(),se=f(),ne=.1;class re{constructor(){this.fovX=0,this.fovY=0,this.relativeWidthLimit=0,this.relativeHeightLimit=0,this.maxLod=0,this.angledSplitBias=0,this.aboveGround=!0}}class ae{constructor(){this.lij=[0,0,0],this._children=[null,null,null,null],this._pendingUpdates=0,this._dirty=!0,this._previouslyRendered=!1,this.extent=y(),this._elevationBounds=o(),this.layerInfo=[[],[]],this.extentInRadians=y(),this.centerAtSeaLevel=f(),this._center=[f(),E(),f()],this.up=p(),this._isWithinClippingArea=!0,this._intersectsClippingArea=!0,this._maxTesselation=0,this._usedMemory=null,this._mapTileMemory=0,this._mapDataRefCount=0,this._screenDepth=0,this.renderOrder=0,this._edgeLen=0,this._edgeLen2=0,this._curvatureHeight=0}static prune(){le.prune(0),de.prune(0),$.prune()}get isCached(){return!this.shouldLoad&&this._mapDataRefCount<=0}get maxTesselation(){return this._maxTesselation}get isWithinClippingArea(){return this._isWithinClippingArea}get intersectsClippingArea(){return this._intersectsClippingArea}get clippingArea(){return this._clippingArea}get parent(){return this._parent}get children(){return this._children}get surface(){return this._surface}get elevationBounds(){return this._elevationBounds}get level(){return this.lij[0]}get key(){return`${this.lij[0]}/${this.lij[1]}/${this.lij[2]}`}get edgeLen(){return this._edgeLen}get radius(){return this._center[ce.MIDDLE][3]}get screenDepth(){return this._screenDepth}get visible(){return this._dirty&&this.computeVisibility(),this._visible}computeVisibility(){this._dirty=!1;const e=this._intersectsClippingArea&&this._isVisible(this.surface.frustum);return e!==this._visible&&(this._visible=e,this._surface.emit("tiles-visibility-changed"),this._surface.renderer.setNeedsRender(),this._updateTexture(e?D.FADING:D.UNFADED),this.updateAgentSuspension()),this._visible}get loadable(){return this.visible||this._surface.view.state.fixedContentCamera}get rendered(){const e=!!this.renderData;return e!==this._previouslyRendered&&(this._surface.emit("tiles-visibility-changed"),this._previouslyRendered=e,this._surface.renderer.setNeedsRender()),e}get shouldLoad(){if(this._surface.lodSnapping===I.ON){const e=this.level-this._surface.snapLevel;if(0===e)return!0;if(1===e)return!1}return this.isLeaf}init(e,t,i){this.lij[0]=e[0],this.lij[1]=e[1],this.lij[2]=e[2],this.ellipsoid=_(i.tilingScheme.spatialReference),i.tilingScheme.getExtent(e[0],e[1],e[2],this.extent),i.tilingScheme.convertExtentToRadians(this.extent,this.extentInRadians),this._isWithinClippingArea=!0,this._intersectsClippingArea=!0,this._clippingArea=null,this._mapDataRefCount=0,i.upsampleMapCache.pop(this.key),this._edgeLen=0,this._edgeLen2=0,this._center[ce.MIDDLE][3]=0,this.vlevel=e?e[0]:0,t&&t.elevationBounds?r(this._elevationBounds,t.elevationBounds):a(this._elevationBounds,0,0),this._pendingUpdates=0,this.renderData=null,this._screenDepth=0,this._visible=!1,this._previouslyRendered=!1,this._parent=t,this.unsetChildren(),this._surface=i,this.updateVisibility();for(const s of b){const e=i.numLayers(s),t=this.layerInfo[s];for(const i of t)i.release();t.length=e;for(let i=0;i<e;i++)t[i]=$.acquire(this._surface.upsampleInfoPool),s===S.ELEVATION&&this.findElevationBoundsForLayer(i,-1)}this.computeElevationBounds(),this._maxTesselation=Math.min(i.tilingScheme.pixelSize,O)}release(){U(!this.renderData,"tile.renderData was not unloaded"),this._surface.upsampleMapCache.pop(this.key);for(const e of b){for(const t of this.layerInfo[e])t.release();this.layerInfo[e].length=0}this._parent=null,this._surface=null,this.setMemoryDirty()}refMapData(){++this._mapDataRefCount,this.isCached||this._surface.upsampleMapCache.pop(this.key)}unrefMapData(){if(--this._mapDataRefCount,this.isCached){this.setMemoryDirty();const e=this.cachedMemory;e>0&&this._surface.upsampleMapCache.put(this.key,this,e)}}setMemoryDirty(){this._usedMemory=null}get usedMemory(){return this._ensureUsedMemory()+(this.isCached?0:this._mapTileMemory)}get cachedMemory(){return this.isCached?this.mapTileMemory:0}get mapTileMemory(){return this._ensureUsedMemory(),this.layerInfo[S.MAP].reduce(((e,t)=>e+(t instanceof T?t.memoryUsage:0)),this._mapTileMemory)}get cpuImageMemorySize(){const e=4,t=this._surface.tilingScheme.pixelSize;return t*t*e}_ensureUsedMemory(){if(t(this._usedMemory))return this._usedMemory;this._usedMemory=0,this._mapTileMemory=0;let e=0;for(const{data:t}of this.layerInfo[S.MAP])t instanceof T?e+=this._getTerrainDataMemory(t):this._mapTileMemory+=this._getTerrainDataMemory(t);const i=this.cpuImageMemorySize;for(const t of this.layerInfo[S.ELEVATION])this._usedMemory+=t.data?i:0;return this.renderData&&(this._usedMemory+=this.renderData.estimatedGeometryMemoryUsage,this._mapTileMemory+=ee(this.renderData.textureDescriptor)),this.isCached&&this._surface.upsampleMapCache.updateSize(this.key,this,this._mapTileMemory+e),this._usedMemory}getUsedMemoryForLayer(e,t){const i=this.layerInfo[e][t];return i?.data?e===S.MAP?this.isCached?0:this._getTerrainDataMemory(i.data):e===S.ELEVATION?this.cpuImageMemorySize:0:0}_getTerrainDataMemory(e){return e instanceof Q?ee(e.texture):e instanceof HTMLImageElement||e instanceof v?this.cpuImageMemorySize:e instanceof T||e instanceof j?e.memoryUsage:0}updateScreenDepth(e){const t=this._center[ce.MIDDLE],i=e,s=t[0],n=t[1],r=t[2],a=i[2]*s+i[6]*n+i[10]*r+i[14];this._screenDepth=a<0?0:a/(i[3]*s+i[7]*n+i[11]*r+i[15])}shouldSplit(e,i,s){if(t(e.frustum)&&(!this._intersectsClippingArea||!this._isVisible(e.frustum)))return K.NONE;const n=this.level;h(te,this._center[ce.MIDDLE],i);let r=l(te),a=ce.MIDDLE;h(ie,this._center[ce.TOP],i);const o=l(ie);o<r&&(r=o,a=ce.TOP),h(ie,this._center[ce.BOTTOM],i);const f=l(ie);if(f<r&&(r=f,a=ce.BOTTOM),this._edgeLen2>r&&n<e.maxLod)return K.SPLIT;const p=Math.sqrt(r),m=e.fovX*p*2,_=this._edgeLen/m,y=()=>{const t=n+Math.ceil(-Math.log2(e.relativeWidthLimit/_));return t!==this.vlevel?(this.vlevel=t,K.VSPLITMERGE):K.NONE_HIT_MAXLOD};if(s===I.ON){if(1===this._surface.snapLevel-n)return n>=e.maxLod?y():K.SPLIT}const A=d(this.up,te),E=this._elevationBounds[1]-this._elevationBounds[0],T=E/this.edgeLen;if(e.aboveGround&&A>0&&T<.001){if(A/p-Math.sin(this._curvatureHeight/(this.edgeLen*Math.SQRT1_2)*Math.PI)-T>0)return K.NONE}if(_<e.relativeWidthLimit)return this.vlevel!==this.level?(this.vlevel=this.level,K.VSPLITMERGE):K.NONE;if(n>=e.maxLod)return y();if(n>6){h(ie,this._center[a],i),u(se,this.up,A),h(se,se,ie);const t=l(se);if(t>this.radius*this.radius){u(se,se,this.radius/Math.sqrt(t)),c(se,se,this._center[a]),h(se,i,se);const s=Math.min(1,(Math.abs(d(se,this.up))+.5*E+this._curvatureHeight)/g(se)),n=ne/e.angledSplitBias,r=e.fovY*p*2;if(s*(this._edgeLen/r)<n*e.relativeHeightLimit)return K.NONE}}return K.SPLIT}setChildren(e,t,i,s){U(!!(e&&t&&i&&s),"Null child passed"),this._children[0]=e,this._children[1]=t,this._children[2]=i,this._children[3]=s}unsetChildren(){this._children[0]=null,this._children[1]=null,this._children[2]=null,this._children[3]=null}get isLoaded(){return this.renderData?.hasGeometry??!1}prepareToLoad(e){this.refMapData();for(const t of b)this._createOrUpdateAgents(0,t);e.updateTileGeometryState(this)}load(e){this.prepareToLoad(e),this.loadPrepared(e)}loadPrepared(e){e.loadTile(this)}unload(e){e.unloadTile(this);for(const t of b){const e=this.layerInfo[t];for(const t of e)t.loadingAgent&&t.loadingAgent!==Y&&(he(t.loadingAgent),t.loadingAgent=null),t.pendingUpdates=0}this.resetPendingUpdate(K.GEOMETRY),this.resetPendingUpdate(K.TEXTURE_NOFADING),this.resetPendingUpdate(K.TEXTURE_FADING),this.unrefMapData()}unloadMapData(){const e=this.layerInfo[S.MAP];for(const t of e)t.loadingAgent&&t.loadingAgent!==Y&&(he(t.loadingAgent),t.loadingAgent=null),t.pendingUpdates=0;this.renderData&&this.renderData.releaseTexture(),this.setMemoryDirty()}updateClippingStatus(e){if(A(e,this._clippingArea))return!1;const i=this._intersectsClippingArea,s=this._isWithinClippingArea;t(e)?(this._intersectsClippingArea=this.intersectsExtent(e),this._isWithinClippingArea=this._isWithinExtent(e)):(this._intersectsClippingArea=!0,this._isWithinClippingArea=!0),this._clippingArea=e,this.updateVisibility();const n=s&&this._isWithinClippingArea,r=!(s||i||this._isWithinClippingArea||this._intersectsClippingArea);return!this.renderData||n||r||this.setPendingUpdate(K.GEOMETRY),!0}updateVisibility(){this._dirty=!0,this._surface.setTileTreeDirty()}getLayerInfo(e,t){return this.layerInfo[t][e]}hasLayerData(e,t){const i=this.layerInfo[t][e];return!(!i||!i.data||i.dataInvalidated)}get updating(){if(this.hasPendingUpdates)return!0;for(const e of b){const t=this.layerInfo[e];for(const e of t)if(e.loadingAgent&&e.loadingAgent!==Y&&e.loadingAgent.updating)return!0}return!1}_isSuspended(e){return!!this.hasPendingUpdate(K.SPLIT)||e!==S.ELEVATION&&!this.loadable}get hasPendingUpdates(){return 0!==this._pendingUpdates}hasPendingUpdate(e){return(this._pendingUpdates&e)===e}setPendingUpdate(e){this._pendingUpdates|=e,e===K.SPLIT||e===K.MERGE?this._surface.setTileTreeDirty():this._surface.requestUpdate()}resetPendingUpdate(e){return!!this.hasPendingUpdate(e)&&(this._pendingUpdates&=~e,!0)}requestLayerData(e,t,s){const n=this.layerInfo[t][e];if(n.waitingAgents.has(s))return console.warn("agent already requested this piece of map data (tile %s, agent tile %s, layer: %d/%d)",this.lij.toString(),s.tile.lij.toString(),t,e),!0;if(n.waitingAgents.push(s),n.data&&!n.dataInvalidated)return console.warn("agent requested existing data (tile %s, agent tile %s, layer: %d/%d)",this.lij.toString(),s.tile.lij.toString(),t,e),s.dataArrived(this),!0;if(n.requestPromise)return!0;i(n.requestAbort),n.requestAbort=new AbortController;const r=this._surface.requestTileData(this,e,t,n.requestAbort);if(!r)return n.requestAbort=null,!1;const a=()=>{n.requestPromise===r&&(n.requestPromise=null,n.requestAbort=null)};return n.requestPromise=r,r.then(a,a),!0}get isLeaf(){return null==this._children[0]}hasLij(e){return this.lij[0]===e[0]&&this.lij[1]===e[1]&&this.lij[2]===e[2]}findByLij(e){if(this.hasLij(e))return this;if(this.isLeaf)return null;const t=this._children[0].findByLij(e)||this._children[1].findByLij(e)||this._children[2].findByLij(e)||this._children[3].findByLij(e);return t||null}distanceToSquared(e){return l(h(se,this._center[ce.MIDDLE],e))}containsPoint(e){const t=this.extent;return e[0]>=t[0]&&e[1]>=t[1]&&e[0]<=t[2]&&e[1]<=t[3]}unrequestLayerData(e,t,i){const s=this.layerInfo[t][e],n=s.waitingAgents,r=null!=n.removeUnordered(i);U(r,"agent has not requested this piece of map data"),n.length<1&&(s.abortRequest(),this.setMemoryDirty())}dataArrived(e,t,i){const s=this.layerInfo[t][e];s.data=i,s.dataInvalidated=!1,s.waitingAgents.forAll((e=>e.dataArrived(this))),s.waitingAgents.clear(),this.setMemoryDirty()}dataMissing(e,t,i){i.notInTilemap||console.error(`Tile ${this.lij.toString()} layer ${t}/${e} error ${i}`);const s=this.layerInfo[t][e];s.dataMissing=!0,s.waitingAgents.forAll((e=>e.dataMissing())),s.waitingAgents.clear(),this.setMemoryDirty()}updateRenderData(e,t){switch(e){case S.MAP:return this._updateTexture(t);case S.ELEVATION:return this._updateGeometry()}}_updateTexture(e){this.renderData&&(this.resetPendingUpdate(e===D.FADING?K.TEXTURE_NOFADING:K.TEXTURE_FADING),this.setPendingUpdate(e===D.FADING?K.TEXTURE_FADING:K.TEXTURE_NOFADING))}_updateGeometry(){this.setPendingUpdate(K.GEOMETRY);for(const e of this.layerInfo[S.ELEVATION])e.pendingUpdates|=K.GEOMETRY}invalidateLayerData(e,t){this.layerInfo[t][e].invalidateSourceData(),this.restartAgents(t)}computeElevationBounds(){const e=this._elevationBounds;a(e,Number.MAX_VALUE,-Number.MAX_VALUE);const i=this.layerInfo[S.ELEVATION];let s=!0;for(const n of i)t(n.elevationBounds)&&(e[0]=Math.min(e[0],n.elevationBounds.min),e[1]=Math.max(e[1],n.elevationBounds.max),n.elevationBounds.hasNoDataValues||(s=!1));s&&(e[0]=Math.min(e[0],0),e[1]=Math.max(e[1],0)),this.updateRadiusAndCenter(),this._surface.setTileTreeDirty()}_updateCenter(){const e=this._elevationBounds,t=.5*(e[0]+e[1]);u(se,this.up,t),c(this._center[ce.MIDDLE],this.centerAtSeaLevel,se),u(se,this.up,e[0]),c(this._center[ce.TOP],this.centerAtSeaLevel,se),u(se,this.up,e[1]),c(this._center[ce.BOTTOM],this.centerAtSeaLevel,se)}findElevationBoundsForLayer(e,i){const n=this.layerInfo[S.ELEVATION][e];if(t(n.elevationBounds)&&n.elevationBounds.level>=i)return;const r=this._surface.layerViewByIndex(e,S.ELEVATION),a=R(r);if(!Z(this,a,!1))return;const o=ue;let h=!1;if(n.data){const e=n.data;o.min=e.bounds[0],o.max=e.bounds[1],o.hasNoDataValues=e.hasNoDataValues,o.level=this.level,h=!0}else{let t,i,s=0;for(let n=this._parent;n&&(!i||s<C(this.level))&&(s=this.vlevel-n.level,t=i||t,i=n.layerInfo[S.ELEVATION][e].data,!(!i&&t&&s>=C(this.level)));n=n.parent);i=i||t,i&&(i.computeMinMaxValue(this.lij[0],this.lij[1],this.lij[2],o),o.min!==1/0&&(o.level=i.level,h=!0))}h&&(s(n.elevationBounds)&&(n.elevationBounds=new L),n.elevationBounds.copyFrom(o))}modifyLayers(e,t,i){const s=this.layerInfo[i];for(const a of s)a.loadingAgent&&a.loadingAgent!==Y&&(he(a.loadingAgent),a.loadingAgent=null),a.waitingAgents.clear();for(let a=0;a<s.length;++a)void 0===e[a]&&s[a].release();const n=new Array(...s),r=t.length;s.length=r;for(let a=0;a<r;a++){const e=t[a];s[a]=e>-1?n[e]:$.acquire(this._surface.upsampleInfoPool)}this.setMemoryDirty()}restartAgents(e){this.renderData&&(this._createOrUpdateAgents(0,e),this.updateRenderData(e,D.FADING))}updateAgents(e){if(this.renderData){const t=this.layerInfo[e];for(const e of t)e.loadingAgent===Y&&(e.loadingAgent=null);this._createOrUpdateAgents(0,e)}}updateAgentSuspension(){for(const e of b){const t=this._isSuspended(e);for(const i of this.layerInfo[e])i.loadingAgent&&i.loadingAgent!==Y&&(i.loadingAgent.setSuspension(t),i.loadingAgent===Y&&this.updateRenderData(e,D.FADING))}}removeLayerAgent(e,t){const i=this.layerInfo[t][e];i.loadingAgent&&i.loadingAgent!==Y&&i.loadingAgent.dispose(),i.loadingAgent=null}agentDone(e,t){const i=this.layerInfo[t][e];i.loadingAgent=Y,!i.data&&s(i.upsampleInfo)&&this._createOrUpdateAgents(e+1,t)}_createOrUpdateAgents(e,t){const i=this.layerInfo[t];if(0===i.length)return;const s=(()=>{for(let s=e;s<i.length;++s){const e=this._surface.layerViewByIndex(s,t);if(P(e)&&"normal"!==e.layer.blendMode)return!0}return!1})(),n=this._isSuspended(t);for(let r=e;r<i.length;++r){const e=i[r];let a=!1;const o=this._surface.layerViewByIndex(r,t),h=R(o);if(e.loadingAgent?Z(this,h,!1)?(e.loadingAgent!==Y&&e.loadingAgent.setSuspension(n),e.loadingAgent!==Y&&(a=e.loadingAgent.update())):e.dispose():Z(this,h,!1)&&(e.loadingAgent=oe(this,r,t,n),a=e.loadingAgent.startLoading(),a?e.loadingAgent===Y&&this.setPendingUpdate(K.GEOMETRY):(he(e.loadingAgent),e.loadingAgent=Y)),e.loadingAgent===Y&&this.updateRenderData(t,D.FADING),!s&&a&&o.isOpaque)return}}_isWithinExtent(e){const t=this.extent;return t[0]>=e[0]&&e[2]>=t[2]&&t[1]>=e[1]&&e[3]>=t[3]}intersectsExtent(e){const t=this.extent;return t[2]>=e[0]&&e[2]>=t[0]&&t[3]>=e[1]&&e[3]>=t[1]}getElevationBasedVerticesPerSide(t){const i=this.vlevel-this.level,s=Math.max(this.level-t,C(this.level)-i);return e(1+(this.maxTesselation>>s),2,this.maxTesselation+1)}get test(){return{cachedMemory:this.cachedMemory}}_findLIJ(e,i){if(!e)return null;const s=this.surface.rootTiles;if(t(s))for(const t of s)if(ge(t,e)){let s=t,n=e[0]-s.level-1;for(;n>=0&&!s.isLeaf&&!i(s);){const t=e[1]>>n&1,i=e[2]>>n&1;s=s.children[2*t+i],n--}return i(s)?s:null}return null}findNeighborTile(e,t){const i=this.lij,s=this.getNeighborLIJ(i,e);return s?fe(i,s)?t(this)?this:null:this._findLIJ(s,t):null}findCorner(e,t){const i=e===N.NORTH_EAST?1:e===N.NORTH_WEST?0:e===N.SOUTH_WEST?2:3;let s=this;for(;!(s.isLeaf||t&&t(s));)s=s.children[i];return s}findNeighborCornerTileExact(e,t){return this.findNeighborTile(e,(e=>t(e)||e.level===this.level))?.findCorner(B(e),t)}forAllSubtreeOnSide(e,t){const i=e===N.NORTH?[0,1]:e===N.NORTH_EAST?[1]:e===N.EAST?[1,3]:e===N.SOUTH_EAST?[3]:e===N.SOUTH?[2,3]:e===N.SOUTH_WEST?[2]:e===N.WEST?[0,2]:[0],s=e=>{t(e)||e.isLeaf||i.forEach((t=>s(e.children[t])))};s(this)}forallNeighbors(e){G.forEach((t=>this.findNeighborCornerTileExact(t,e))),V.forEach((t=>this.findNeighborTile(t,(t=>t.level===this.level||e(t)))?.forAllSubtreeOnSide(W(t),e)))}getNeighborEdgeStartVertexIndex(e,t){const i=t??this.findNeighborTile(V[e],(e=>e.isLoaded));if(!i||!this.isLoaded||!i.isLoaded)return 0;const s=this.level-i.level;if(0===s)return 0;const n=2**s,r=1==(1&e),a=r?0:1,o=i.lij[a+1]*n,h=this.lij[a+1]-o;return r?n-1-h:h}_updateNeighborsWithChangedEdgeResolution(){for(let e=0;e<4;++e)if(this.renderData.geometryState.neighborData.modifiedEdgeResolutions[e]){const t=V[e],i=this.findNeighborTile(t,(e=>e.isLoaded||e.level===this.level));if(!i)continue;if(!i.isLoaded){w(!i.isLeaf);const s=(e+2)%4,n=W(t);i.forAllSubtreeOnSide(n,(e=>e.isLoaded?(e.updateEdgeAfterResolutionChange(s),!0):(w(!e.isLeaf),!1)))}this.renderData.geometryState.neighborData.modifiedEdgeResolutions[e]=!1}}updateNeighborDataAndGeometryIfNeeded(){this.isLoaded&&this.renderData.updateNeighborDataAndGeometryIfNeeded()}updateNeighborsAfterGeometryChange(e=this.level){this.forEachLoadedNeighbor((e=>this._updateNeighbor(e))),V.forEach((t=>{this.findNeighborTile(t,(t=>t.isLoaded&&t.level<e))?.updateNeighborsWithChangedEdgeResolution()}))}updateNeighborsWithChangedEdgeResolution(){this.isLoaded&&this._updateNeighborsWithChangedEdgeResolution()}updateEdgeAfterResolutionChange(e){this.renderData.updateEdgeAfterResolutionChange(e)}forEachLoadedNeighbor(e){const t=this.level,i=e=>e.level===t||e.isLoaded;V.forEach(((t,s)=>{const n=this.findNeighborTile(t,i);null!=n&&n!==this&&n.forAllSubtreeOnSide(W(t),(t=>!!t.isLoaded&&(e(t),!0)));const r=this.renderData?.geometryState?.neighborData;r&&(r.modifiedEdgeResolutions[s]=!1)})),G.forEach((t=>{const s=this.findNeighborTile(t,i)?.findCorner(B(t),(e=>e.isLoaded));w(!s||_e(this,s,t)),s?.isLoaded&&e(s)}))}_updateNeighbor(e){e?.isLoaded&&e.updateNeighborDataAndGeometryIfNeeded()}getNeighborLIJ(e,t){const i=q(t)?-1:H(t)?1:0,s=F(t)?-1:k(t)?1:0,n=[e[0],e[1]+i,e[2]+s];return n[1]<0?null:this.surface.isGlobal?this.wrapLIJ(n):n[2]<0?null:n}wrapLIJ(e){return!e||e[1]<0||e[1]>=2**e[0]?null:this.surface.wrapEastWest(e)}get westNeighborWestExtent(){return this.extent[0]*(this.isWestEnd?-1:1)}get eastNeighborEastExtent(){return this.extent[2]*(this.isEastEnd?-1:1)}get isEastEnd(){return this.lij[2]===this.surface.lijEastEnd(this.level)-1}get isWestEnd(){return 0===this.lij[2]}get isNorthEnd(){return 0===this.lij[1]}get isSouthEnd(){return this.extent[1]+m>=this.surface.extent[1]}compareLIJs(e){const t=this.lij,i=t[0],s=e[0];if(i===s)return[t,e];const n=i-s;if(n<0){const i=2**-n;return[[s,t[1]*i,t[2]*i],e]}{const s=2**n;return[t,[i,e[1]*s,e[2]*s]]}}checkGeometryWaterproofness(){X&&(w(this.isLoaded),this.renderData.checkGeometryWaterproofness())}shouldHaveNeighbor(e){const t=this.extent,i=this.surface.rootTilesExtent,s=.25*(t[2]-t[0]);if(q(e)&&t[3]+s>=i[3])return!1;if(H(e)&&t[1]-s<=i[1])return!1;const n=this.surface.isGlobal;return!(!n&&F(e)&&t[0]-s<=i[0])&&!(!n&&k(e)&&t[2]+s>=i[2])}}function oe(e,t,i,s){const n=i===S.ELEVATION?de.acquire():le.acquire();return n.init(e,t,i,s),n}function he(e){e.dispose(),e instanceof M?de.release(e):e instanceof x&&le.release(e)}const le=new n(x),de=new n(M),ue=new L;var ce;function ge(e,t){const i=e.level,s=t[0];if(i>s)return!1;const n=s-i,r=Math.floor(t[1]/2**n),a=Math.floor(t[2]/2**n);return r===e.lij[1]&&a===e.lij[2]}function fe(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function pe(e,t,i){return Math.abs(e-t)<=i}function me(e,t,i){if(s(e)||s(t))return!1;if(0===e.level&&0===t.level){if(e.isEastEnd&&t.isWestEnd&&i===N.EAST)return!0;if(e.isWestEnd&&t.isEastEnd&&i===N.WEST)return!0}const n=1e-6*(e.extent[2]-e.extent[0]);switch(i){case N.NORTH:return pe(e.extent[3],t.extent[1],n);case N.SOUTH:return pe(e.extent[1],t.extent[3],n);case N.EAST:return pe(e.extent[2],t.extent[0],n)||pe(e.extent[2],-t.extent[0],n);case N.WEST:return pe(e.extent[0],t.extent[2],n)||pe(e.extent[0],-t.extent[2],n)}}function _e(e,t,i){return!s(e)&&!s(t)&&t!==e&&(e.level>=t.level?ye(e,t,i):ye(t,e,B(i)))}function ye(e,t,i){w(e.level>=t.level);const s=z(i),n=J(i),r=e.extent,a=t.extent,o=[s?r[0]:r[2],n?r[3]:r[1]],h=[s?a[2]:a[0],n?a[1]:a[3]],l=1e-5*(r[2]-r[0]),d=pe(o[0],h[0],l)||e.surface.isGlobal&&pe(o[0],-h[0],l),u=pe(o[1],h[1],l);if(d&&u)return!0;if(e.level===t.level)return!1;if(!d&&!u)return!1;return d?Ae(a[1],a[3],r[1],r[3],l):Ae(a[0],a[2],r[0],r[2],l)}function Ae(e,t,i,s,n=m){return e-n<=i&&i<=s&&s<=t+n}!function(e){e[e.TOP=0]="TOP",e[e.MIDDLE=1]="MIDDLE",e[e.BOTTOM=2]="BOTTOM"}(ce||(ce={}));export{ce as CenterPosition,re as SplitLimits,ae as Tile,pe as almostEquals,_e as isCornerNeighbor,me as isEdgeNeighbor};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.24/esri/copyright.txt for details.
4
4
  */
5
- import{disposeMaybe as e,releaseMaybe as r,isNone as t,isSome as i}from"../../../core/maybe.js";import{Z as o}from"../../../chunks/vec2f64.js";import{RasterColorizerStretchType as s}from"../../2d/engine/imagery/enums.js";import{VectorTileRendererHelper3D as l}from"../../2d/engine/vectorTiles/VectorTileRendererHelper3D.js";import{BlendLayersTechniqueConfiguration as n,BlendLayersTechnique as a}from"./BlendLayersTechnique.js";import{LayerClass as h}from"./LayerClass.js";import{RasterColorizerTechniqueConfiguration as u,RasterColorizerTechnique as c}from"./RasterColorizerTechnique.js";import{FBOPool as _}from"./support/FBOPool.js";import{LayerBlendMode as d}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{TileBlendInput as b}from"../webgl-engine/core/shaderLibrary/terrain/TileBlendInput.js";import{B as f,a as p}from"../../../chunks/BlendLayers.glsl.js";import{BindParameters as T}from"../webgl-engine/lib/BindParameters.js";import{Pos2Tex as m}from"../webgl-engine/lib/DefaultVertexBufferLayouts.js";import{createQuadVAO as y}from"../webgl-engine/lib/glUtil3D.js";import{PrimitiveType as g,ClearBufferBit as B,TextureType as C}from"../../webgl/enums.js";import{Texture as x}from"../../webgl/Texture.js";import{vertexCount as O}from"../../webgl/Util.js";class F{constructor(e,r){this._rctx=e,this._techniqueRepository=r,this._fboPools=[],this._doubleBufferFbo=[],this._vectorTileHelper=new l,this._bindParameters=new T(null,null,null),this._blendLayersTechniqueConfig=new n,this._poolToWrite=0,this._vaoQuad=y(this._rctx,m),this._fboPools.push(new _(this._rctx)),this._fboPools.push(new _(this._rctx))}dispose(){this._fboPools.forEach((e=>{e.clear(),e=null})),this._fboPools=null,this._doubleBufferFbo.forEach((r=>e(r))),this._vaoQuad=e(this._vaoQuad),this._vectorTileHelper=e(this._vectorTileHelper),this._backgroundTechnique=r(this._backgroundTechnique),this._applyOpacityTechnique=r(this._applyOpacityTechnique),this._blendLayersTechnique=r(this._blendLayersTechnique)}_getBlendLayersTechnique(e,r,t,i=!1){return this._blendLayersTechniqueConfig.output=r,this._blendLayersTechniqueConfig.blendMode=e,this._blendLayersTechniqueConfig.baseOpacityMode=t?r===f.Composite?p.OnBaseLayer:p.OnBackground:p.One,this._blendLayersTechniqueConfig.premultipliedSource=i,this._blendLayersTechnique=this._techniqueRepository.releaseAndAcquire(a,this._blendLayersTechniqueConfig,this._blendLayersTechnique),this._blendLayersTechnique}drawBackground(e,r){const t=this._getBlendLayersTechnique(d.Normal,r,!1),i=this._rctx.bindTechnique(t,e,this._bindParameters);this._render(i)}_render(e){this._rctx.bindVAO(this._vaoQuad),e.assertCompatibleVertexAttributeLocations(this._vaoQuad),this._rctx.drawArrays(g.TRIANGLE_STRIP,0,O(this._vaoQuad,"geometry"))}drawRasterData(e,r,i=!1){if(t(r.texture))return;const o=r.baseOpacity<1;r.blendMode!==d.Normal||o||i?(r.fboTexture=this._currentFBO.colorTexture,this._switchPool(this._currentFBO.width)):r.fboTexture=null;const s=this._getBlendLayersTechnique(r.blendMode,e,o,i),l=this._rctx.bindTechnique(s,r,this._bindParameters);this._render(l)}drawImageryTileData(e,r,t){const i=e.sourceLayerInfo.data;if(!i.source)return;e.tile.surface.layerViewByIndex(e.layerIndex,h.MAP).ensureSymbolizerParameters(i);const o=t.baseOpacity<1;t.blendMode!==d.Normal||o?(t.fboTexture=this._currentFBO.colorTexture,this._switchPool(this._currentFBO.width)):t.fboTexture=null;const s=this._getRasterColorizerTechnique(i,r,t.blendMode,o),l=this._rctx.bindTechnique(s);if(!i.bind(this._rctx))return;i.opacity=t.opacity;const n=i.getUniforms();n.scale=e.scale,n.offset=e.offset,n.backgroundColor=t.backgroundColor,n.fboTexture=t.fboTexture,n.baseOpacity=t.baseOpacity,s.bindPass(n,null),this._render(l)}_getRasterColorizerTechnique(e,r,i,o){const l=e.symbolizerParameters,n=["stretch","lut","hillshade"].indexOf(l.type);return t(this._rasterColorizerConfig)&&(this._rasterColorizerConfig=new u,this._rctx.gl.getExtension("WEBGL_color_buffer_float"),this._rctx.gl.getExtension("OES_texture_float")),this._rasterColorizerConfig.tileBlendInput=r===f.ColorComposite?b.ColorComposite:r===f.GridComposite?b.GridComposite:b.LayerOnly,this._rasterColorizerConfig.blendMode=i,this._rasterColorizerConfig.baseOpacityMode=o?r===f.Composite?p.OnBaseLayer:p.OnBackground:p.One,this._rasterColorizerConfig.colorizerType=n,this._rasterColorizerConfig.applyColormap=!!l.colormap,this._rasterColorizerConfig.stretchType=e.hasStretchTypeNone()?s.Noop:s.PerBand,this._rasterColorizerTechnique=this._techniqueRepository.releaseAndAcquire(c,this._rasterColorizerConfig,this._rasterColorizerTechnique),this._rasterColorizerTechnique}drawVectorData(e,r,t,s,l,n,a){const u=this._rctx,c=r.sourceLayerInfo.data,_=r.tile.surface.layerViewByIndex(r.layerIndex,h.MAP),b=e.baseOpacity<1||e.opacity<1||e.blendMode!==d.Normal||a!==f.Composite;let p;return this._getBlendLayersTechnique(e.blendMode,a,e.baseOpacity<1,b).bindPipelineState(u),b?(p=this._acquire(l),u.bindFramebuffer(p),u.setClearColor(0,0,0,0),u.clearSafe(B.COLOR_BUFFER_BIT|B.DEPTH_BUFFER_BIT)):n&&u.clearSafe(B.DEPTH_BUFFER_BIT),this._vectorTileHelper.render(u,r.sourceLod,c,_.painter,_.layer.styleRepository,_.schemaHelper,Math.round(1/r.scale),r.offset,s,t),!i(p)||(u.bindFramebuffer(this._currentFBO),e.texture=p.colorTexture,e.offset=o,e.scale=1,this.drawRasterData(a,e,b),p.release(),n)}copyFBOToTexture(e){const r=this._rctx,t=r.bindTexture(e.texture,x.TEXTURE_UNIT_FOR_UPDATES),i=e.descriptor;r.gl.copyTexImage2D(C.TEXTURE_2D,0,i.pixelFormat,0,0,i.width,i.height,0),e.generateMipmap(),r.bindTexture(t,x.TEXTURE_UNIT_FOR_UPDATES)}_initFBO(e,r){this._rctx.bindFramebuffer(e),this._rctx.setViewport(0,0,r,r),this._rctx.setClearColor(0,0,0,0),this._rctx.setClearDepth(1),this._rctx.clearSafe(B.COLOR_BUFFER_BIT|B.DEPTH_BUFFER_BIT)}_acquire(e){return this._fboPools[this._poolToWrite].acquire(e)}bindPool(e,r){this._poolToWrite=e,null==this._doubleBufferFbo[e]&&(this._doubleBufferFbo[e]=this._acquire(r),this._initFBO(this._doubleBufferFbo[e],r))}_switchPool(e){this._releaseCurrentFBO(),this._doubleBufferFbo[this._poolToWrite]=null,this._poolToWrite=0===this._poolToWrite?1:0,this.bindPool(this._poolToWrite,e)}get _currentFBO(){return this._doubleBufferFbo[this._poolToWrite]}_releaseCurrentFBO(){this._doubleBufferFbo[this._poolToWrite].release(),this._doubleBufferFbo[this._poolToWrite]=null}releasePool(){this._rctx.bindFramebuffer(null),this._releaseCurrentFBO()}cleanupFBOPool(e,r){e===this._lastPixelRatio&&r===this._lastNumLayers||(this._fboPools.forEach((e=>e.clear())),this._lastPixelRatio=e,this._lastNumLayers=r)}}export{F as TileCompositor};
5
+ import e from"../../../core/Logger.js";import{disposeMaybe as r,releaseMaybe as t,isNone as i,isSome as o}from"../../../core/maybe.js";import{Z as s}from"../../../chunks/vec2f64.js";import{RasterColorizerStretchType as n}from"../../2d/engine/imagery/enums.js";import{VectorTileRendererHelper3D as l}from"../../2d/engine/vectorTiles/VectorTileRendererHelper3D.js";import{BlendLayersTechniqueConfiguration as a,BlendLayersTechnique as h}from"./BlendLayersTechnique.js";import{LayerClass as c}from"./LayerClass.js";import{RasterColorizerTechniqueConfiguration as u,RasterColorizerTechnique as _}from"./RasterColorizerTechnique.js";import{FBOPool as d}from"./support/FBOPool.js";import{LayerBlendMode as b}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{TileBlendInput as f}from"../webgl-engine/core/shaderLibrary/terrain/TileBlendInput.js";import{B as p,a as T}from"../../../chunks/BlendLayers.glsl.js";import{BindParameters as m}from"../webgl-engine/lib/BindParameters.js";import{Pos2Tex as y}from"../webgl-engine/lib/DefaultVertexBufferLayouts.js";import{createQuadVAO as g}from"../webgl-engine/lib/glUtil3D.js";import{PrimitiveType as B,ClearBufferBit as C,TextureType as x}from"../../webgl/enums.js";import{Texture as O}from"../../webgl/Texture.js";import{vertexCount as F}from"../../webgl/Util.js";const q=e.getLogger("esri.views.3d.terrain");class L{constructor(e,r){this._rctx=e,this._techniqueRepository=r,this._fboPools=[],this._doubleBufferFbo=[],this._vectorTileHelper=new l,this._bindParameters=new m(null,null,null),this._blendLayersTechniqueConfig=new a,this._poolToWrite=0,this._vaoQuad=g(this._rctx,y),this._fboPools.push(new d(this._rctx)),this._fboPools.push(new d(this._rctx))}dispose(){this._fboPools.forEach((e=>{e.clear(),e=null})),this._fboPools=null,this._doubleBufferFbo.forEach((e=>r(e))),this._vaoQuad=r(this._vaoQuad),this._vectorTileHelper=r(this._vectorTileHelper),this._backgroundTechnique=t(this._backgroundTechnique),this._applyOpacityTechnique=t(this._applyOpacityTechnique),this._blendLayersTechnique=t(this._blendLayersTechnique)}_getBlendLayersTechnique(e,r,t,i=!1){return this._blendLayersTechniqueConfig.output=r,this._blendLayersTechniqueConfig.blendMode=e,this._blendLayersTechniqueConfig.baseOpacityMode=t?r===p.Composite?T.OnBaseLayer:T.OnBackground:T.One,this._blendLayersTechniqueConfig.premultipliedSource=i,this._blendLayersTechnique=this._techniqueRepository.releaseAndAcquire(h,this._blendLayersTechniqueConfig,this._blendLayersTechnique),this._blendLayersTechnique}drawBackground(e,r){const t=this._getBlendLayersTechnique(b.Normal,r,!1),i=this._rctx.bindTechnique(t,e,this._bindParameters);this._render(i)}_render(e){this._rctx.bindVAO(this._vaoQuad),e.assertCompatibleVertexAttributeLocations(this._vaoQuad),this._rctx.drawArrays(B.TRIANGLE_STRIP,0,F(this._vaoQuad,"geometry"))}drawRasterData(e,r,t=!1){if(i(r.texture))return;const o=r.baseOpacity<1;r.blendMode!==b.Normal||o||t?(r.fboTexture=this._currentFBO.colorTexture,this._switchPool(this._currentFBO.width)):r.fboTexture=null;const s=this._getBlendLayersTechnique(r.blendMode,e,o,t),n=this._rctx.bindTechnique(s,r,this._bindParameters);this._render(n)}drawImageryTileData(e,r,t){const i=e.sourceLayerInfo.data;if(!i.source)return;e.tile.surface.layerViewByIndex(e.layerIndex,c.MAP).ensureSymbolizerParameters(i);const o=t.baseOpacity<1;t.blendMode!==b.Normal||o?(t.fboTexture=this._currentFBO.colorTexture,this._switchPool(this._currentFBO.width)):t.fboTexture=null;const s=this._getRasterColorizerTechnique(i,r,t.blendMode,o),n=this._rctx.bindTechnique(s);if(!i.bind(this._rctx))return;i.opacity=t.opacity;const l=i.getUniforms();l.scale=e.scale,l.offset=e.offset,l.backgroundColor=t.backgroundColor,l.fboTexture=t.fboTexture,l.baseOpacity=t.baseOpacity,s.bindPass(l,null),this._render(n)}_getRasterColorizerTechnique(e,r,t,o){const s=e.symbolizerParameters,l=["stretch","lut","hillshade"].indexOf(s.type);return i(this._rasterColorizerConfig)&&(this._rasterColorizerConfig=new u,this._rctx.gl.getExtension("WEBGL_color_buffer_float"),this._rctx.gl.getExtension("OES_texture_float")),this._rasterColorizerConfig.tileBlendInput=r===p.ColorComposite?f.ColorComposite:r===p.GridComposite?f.GridComposite:f.LayerOnly,this._rasterColorizerConfig.blendMode=t,this._rasterColorizerConfig.baseOpacityMode=o?r===p.Composite?T.OnBaseLayer:T.OnBackground:T.One,this._rasterColorizerConfig.colorizerType=l,this._rasterColorizerConfig.applyColormap=!!s.colormap,this._rasterColorizerConfig.stretchType=e.hasStretchTypeNone()?n.Noop:n.PerBand,this._rasterColorizerTechnique=this._techniqueRepository.releaseAndAcquire(_,this._rasterColorizerConfig,this._rasterColorizerTechnique),this._rasterColorizerTechnique}drawVectorData(e,r,t,i,n,l,a){const h=this._rctx,u=r.sourceLayerInfo.data,_=r.tile.surface.layerViewByIndex(r.layerIndex,c.MAP),d=e.baseOpacity<1||e.opacity<1||e.blendMode!==b.Normal||a!==p.Composite;let f;this._getBlendLayersTechnique(e.blendMode,a,e.baseOpacity<1,d).bindPipelineState(h),d?(f=this._acquire(n),h.bindFramebuffer(f),h.setClearColor(0,0,0,0),h.clearSafe(C.COLOR_BUFFER_BIT|C.DEPTH_BUFFER_BIT)):l&&h.clearSafe(C.DEPTH_BUFFER_BIT);try{this._vectorTileHelper.render(h,r.sourceLod,u,_.painter,_.layer.styleRepository,_.schemaHelper,Math.round(1/r.scale),r.offset,i,t)}catch(T){q.warnOnce("A render call containing vector tiles did not resolve correctly.",T)}return!o(f)||(h.bindFramebuffer(this._currentFBO),e.texture=f.colorTexture,e.offset=s,e.scale=1,this.drawRasterData(a,e,d),f.release(),l)}copyFBOToTexture(e){const r=this._rctx,t=r.bindTexture(e.texture,O.TEXTURE_UNIT_FOR_UPDATES),i=e.descriptor;r.gl.copyTexImage2D(x.TEXTURE_2D,0,i.pixelFormat,0,0,i.width,i.height,0),e.generateMipmap(),r.bindTexture(t,O.TEXTURE_UNIT_FOR_UPDATES)}_initFBO(e,r){this._rctx.bindFramebuffer(e),this._rctx.setViewport(0,0,r,r),this._rctx.setClearColor(0,0,0,0),this._rctx.setClearDepth(1),this._rctx.clearSafe(C.COLOR_BUFFER_BIT|C.DEPTH_BUFFER_BIT)}_acquire(e){return this._fboPools[this._poolToWrite].acquire(e)}bindPool(e,r){this._poolToWrite=e,null==this._doubleBufferFbo[e]&&(this._doubleBufferFbo[e]=this._acquire(r),this._initFBO(this._doubleBufferFbo[e],r))}_switchPool(e){this._releaseCurrentFBO(),this._doubleBufferFbo[this._poolToWrite]=null,this._poolToWrite=0===this._poolToWrite?1:0,this.bindPool(this._poolToWrite,e)}get _currentFBO(){return this._doubleBufferFbo[this._poolToWrite]}_releaseCurrentFBO(){this._doubleBufferFbo[this._poolToWrite].release(),this._doubleBufferFbo[this._poolToWrite]=null}releasePool(){this._rctx.bindFramebuffer(null),this._releaseCurrentFBO()}cleanupFBOPool(e,r){e===this._lastPixelRatio&&r===this._lastNumLayers||(this._fboPools.forEach((e=>e.clear())),this._lastPixelRatio=e,this._lastNumLayers=r)}}export{L as TileCompositor};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.24/esri/copyright.txt for details.
4
4
  */
5
- import{nextHighestPowerOfTwo as e}from"../../../core/mathUtils.js";import{disposeMaybe as t,releaseMaybe as r,isNone as s,isSome as o}from"../../../core/maybe.js";import{a,c as i}from"../../../chunks/vec2.js";import{Z as n}from"../../../chunks/vec2f64.js";import{isBaseLayer as u}from"../../../layers/support/layerUtils.js";import{ImageWithType as c}from"../support/StreamDataLoader.js";import{BlendLayersPassParameters as l}from"./BlendLayersTechnique.js";import{TextureUpdate as p}from"./interfaces.js";import{LayerClass as d}from"./LayerClass.js";import{isBlendableLayerView as h,isGroupLayer as m,isVectorTileLayerView as _,isVectorTileRenderInfo as T,isImageryTileRenderInfo as f,isRasterTileRenderInfo as x,isTextureTileRenderInfo as y}from"./terrainUtils.js";import{ActivationTime as g}from"./TextureFader.js";import{TextureReference as b}from"./TextureReference.js";import{TileCompositor as k}from"./TileCompositor.js";import I from"./TileTexture.js";import{TileUpdate as P}from"./TileUpdate.js";import{LayerBlendMode as D,blendModeFromString as w}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{B as L}from"../../../chunks/BlendLayers.glsl.js";import{createColorTexture as A,createEmptyTexture as E}from"../webgl-engine/lib/glUtil3D.js";import{TextureSamplingMode as R,TextureType as M,PixelFormat as j,PixelType as O,TextureWrapMode as N}from"../../webgl/enums.js";import{Texture as U}from"../../webgl/Texture.js";class C{constructor(e,t,r){this._rctx=e,this.tileSize=t,this._techniqueRepository=r,this._passParameters=new l,this._backgroundTexture=null,this._backgroundColor=null,this._backgroundDirty=!1,this._blackTex=null,this._numTexturedLayer=0,this._maxAnisotropy=this._rctx.parameters.maxMaxAnisotropy,this._composition=new k(this._rctx,this._techniqueRepository),this._blackTex=new I(A(this._rctx,[0,0,0,1])),this._ensureBackgroundTexture(this.tileSize)}dispose(){this._composition=t(this._composition),this._backgroundTexture=r(this._backgroundTexture),this._blackTex=r(this._blackTex)}get backgroundIsGrid(){return s(this._backgroundColor)}get backgroundColor(){return this._backgroundColor}updateTileTexture(e,t){if(!e.renderData)return;const r=e.surface,s=r.baseOpacity;this._numTexturedLayer=0;let o=0,a=this.tileSize,i=!1;const n=r.view.state.pixelRatio;let c=!1;const l=e.layerInfo[d.MAP];let p=l.length,T=0;for(;T<l.length;T++){const t=r.layerViewByIndex(T,d.MAP),f=t.fullOpacity;if(G[T]=f,u(t.layer)&&p>=l.length&&(p=T),0===f){l[T].pendingUpdates&=~(P.TEXTURE_NOFADING&P.TEXTURE_FADING);continue}++o;const x=F(e,T);if(x){if(l[T].pendingUpdates&=~(P.TEXTURE_NOFADING&P.TEXTURE_FADING),h(t)){const e=m(t.layer.parent)?"normal":t.layer.blendMode;S[T]=e;const r="normal"!==e;r&&(c=r,i=!1)}_(t)?a=Math.max(a,this.tileSize*n):1===s&&1===f&&(t.isOpaque||this._dataToTexture(x)&&x.sourceLayerInfo.data.descriptor.isOpaque)&&(i=!0),++this._numTexturedLayer}}this._composition.cleanupFBOPool(n,l.length),a=B(a);const f=a/this.tileSize,x=T-1;this._ensureBackgroundTexture(this.tileSize),0!==this._numTexturedLayer?1===this._numTexturedLayer&&!c&&this._useLayerTexture(e,x,p,G[x])||this._composeMapLayers(e,t,x,p,G,S,a,f,!i||c):this._useBackgroundTexture(e,o)}_ensureBackgroundTexture(e){s(this._backgroundTexture)&&(this._backgroundTexture=this._buildTexture(e),this._backgroundDirty=!0),this._backgroundDirty&&(this._composition.bindPool(0,e),this._passParameters.offset=n,this._passParameters.scale=1,this._passParameters.opacity=1,this._passParameters.blendMode=D.Normal,o(this.backgroundColor)&&(this._passParameters.backgroundColor=this.backgroundColor),this._composition.drawBackground(this._passParameters,o(this.backgroundColor)?L.ColorOnly:L.GridOnly),this._composition.copyFBOToTexture(this._backgroundTexture),this._composition.releasePool(),this._backgroundDirty=!1)}_useBackgroundTexture(e,t){let r=g.Immediate;(e.surface.view.layerViewManager.updating||t>0)&&(r=g.Delayed),this._backgroundTexture&&s(e.renderData.textureReference)&&(r=g.Immediate),e.renderData.setTextureReference(o(this._backgroundTexture)?new b(this._backgroundTexture,p.FADING,z,e.surface.baseOpacity,1,0):null,r)}_useLayerTexture(e,t,r,s){const o=t<r,a=o?1:e.surface.baseOpacity,i=o?e.surface.baseOpacity:1,n=F(e,t);return!!this._dataToTexture(n)&&(e.renderData.setTextureReference(new b(n.sourceLayerInfo.data,p.FADING,n,a,s,i)),!0)}_composeMapLayers(e,t,r,s,o,a,i,n,u){this._composition.bindPool(0,i);const c=e.surface.baseOpacity;let l=!1,p=R.LINEAR_MIPMAP_LINEAR,d=!1,h=0;for(let _=r;_>=0;_--){const t=F(e,_);if(!t)continue;if(0===o[_])continue;const r=_<s&&c<1&&!l;this._passParameters.baseOpacity=r?c:1,r&&(l=!0);const m=0===h,x=u&&m?this.backgroundIsGrid?L.GridComposite:L.ColorComposite:L.Composite;T(t)?(this._passParameters.opacity=o[_],this._passParameters.blendMode=w[a[_]],d=this._composition.drawVectorData(this._passParameters,t,n,this.tileSize,i,d,x)):f(t)?(this._passParameters.opacity=o[_],this._passParameters.blendMode=w[a[_]],this._composition.drawImageryTileData(t,x,this._passParameters),this._hasNearestInterpolation(t)&&(p=R.NEAREST)):this._dataToTexture(t)&&(this._passParameters.texture=t.sourceLayerInfo.data.texture,this._passParameters.offset=t.offset,this._passParameters.scale=t.scale,this._passParameters.opacity=o[_],this._passParameters.blendMode=w[a[_]],this._composition.drawRasterData(x,this._passParameters)),h++}const m=e.renderData.ensureTexture(i,(()=>this._buildTexture(i,p)));this._composition.copyFBOToTexture(m),this._composition.releasePool(),e.renderData.setTextureReference(new b(m,t,z,l?1:c,1,0))}_hasNearestInterpolation(e){const t=e.sourceLayerInfo.data;return!!t.source&&"nearest"===t.interpolation}_dataToTexture(e){return x(e)&&this._rasterDataToTexture(e),y(e)}_rasterDataToTexture(e){const t=e.sourceLayerInfo;t.data=this._buildTexture(t.data),e.tile.setMemoryDirty()}setBackground(e){this._backgroundColor!==e&&(this._backgroundColor=e,this._backgroundDirty=!0)}_buildTexture(e,t=R.LINEAR_MIPMAP_LINEAR){if(s(e))return null;const r={target:M.TEXTURE_2D,pixelFormat:j.RGBA,dataType:O.UNSIGNED_BYTE,wrapMode:N.CLAMP_TO_EDGE,samplingMode:t,maxAnisotropy:this._maxAnisotropy,flipped:!0,hasMipmap:!0},o=this._rctx;let a;if("number"==typeof e)r.width=r.height=e,a=new I(new U(o,r));else if(e instanceof c)r.isOpaque=e.isOpaque,a=new I(new U(o,r,e.image)),e.release();else try{a=new I(new U(o,r,e))}catch(n){a=new I(E(o)),console.warn("TileRenderer: failed to execute 'texImage2D', cross-origin image may not be loaded.")}const i=o.bindTexture(a.texture,U.TEXTURE_UNIT_FOR_UPDATES);return a.generateMipmap(),o.bindTexture(i,U.TEXTURE_UNIT_FOR_UPDATES),a}get test(){return{backgroundTexture:this._backgroundTexture}}}function B(t){const r=e(t),s=r*r,o=t*t;if(s===o)return t;const a=r/2;return s-o<o-a*a?r:a}function F(e,t){q.layerIndex=t;const r=e.layerInfo[d.MAP][t];if(o(r.data))return a(q.offset,0,0),q.tile=e,q.scale=1,q.sourceLod=e.lij,q.sourceLayerInfo=r,q;const s=r.upsampleInfo;if(o(s)){const e=s.tile.layerInfo[d.MAP][t];return q.tile=s.tile,i(q.offset,s.offset),q.scale=s.scale,q.sourceLod=s.tile.lij,q.sourceLayerInfo=e,q}return null}const G=new Array,S=new Array,q={tile:null,sourceLayerInfo:null,sourceLod:null,offset:[0,0],scale:1,layerIndex:0},z={offset:[0,0],scale:1};export{C as TileRenderer};
5
+ import{nextHighestPowerOfTwo as e}from"../../../core/mathUtils.js";import{disposeMaybe as t,releaseMaybe as r,isNone as s,isSome as o}from"../../../core/maybe.js";import{a,c as i}from"../../../chunks/vec2.js";import{Z as n}from"../../../chunks/vec2f64.js";import{isBaseLayer as u}from"../../../layers/support/layerUtils.js";import{ImageWithType as c}from"../support/StreamDataLoader.js";import{BlendLayersPassParameters as l}from"./BlendLayersTechnique.js";import{TextureUpdate as p}from"./interfaces.js";import{LayerClass as d}from"./LayerClass.js";import{isBlendableLayerView as h,isGroupLayer as m,isVectorTileLayerView as _,isVectorTileRenderInfo as f,isImageryTileRenderInfo as T,isRasterTileRenderInfo as x,isTextureTileRenderInfo as y}from"./terrainUtils.js";import{ActivationTime as g}from"./TextureFader.js";import{TextureReference as b}from"./TextureReference.js";import{TileCompositor as k}from"./TileCompositor.js";import I from"./TileTexture.js";import{TileUpdate as P}from"./TileUpdate.js";import{LayerBlendMode as D,blendModeFromString as w}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{B as A}from"../../../chunks/BlendLayers.glsl.js";import{createColorTexture as E,createEmptyTexture as L}from"../webgl-engine/lib/glUtil3D.js";import{TextureSamplingMode as R,TextureType as M,PixelFormat as j,PixelType as O,TextureWrapMode as N}from"../../webgl/enums.js";import{Texture as U}from"../../webgl/Texture.js";class C{constructor(e,t,r){this._rctx=e,this.tileSize=t,this._techniqueRepository=r,this._passParameters=new l,this._backgroundTexture=null,this._backgroundColor=null,this._backgroundDirty=!1,this._blackTex=null,this._maxAnisotropy=this._rctx.parameters.maxMaxAnisotropy,this._composition=new k(this._rctx,this._techniqueRepository),this._blackTex=new I(E(this._rctx,[0,0,0,1])),this._ensureBackgroundTexture(this.tileSize)}dispose(){this._composition=t(this._composition),this._backgroundTexture=r(this._backgroundTexture),this._blackTex=r(this._blackTex)}get backgroundIsGrid(){return s(this._backgroundColor)}get backgroundColor(){return this._backgroundColor}updateTileTexture(e,t){if(!e.renderData)return;const r=e.surface,s=r.baseOpacity;let o=0,a=0,i=this.tileSize,n=!1;const c=r.view.state.pixelRatio;let l=!1;const p=e.layerInfo[d.MAP];let f=p.length,T=0;for(;T<p.length;T++){const t=r.layerViewByIndex(T,d.MAP),x=t.fullOpacity;if(G[T]=x,u(t.layer)&&f>=p.length&&(f=T),0===x){p[T].pendingUpdates&=~(P.TEXTURE_NOFADING&P.TEXTURE_FADING);continue}++a;const y=F(e,T);if(y){if(p[T].pendingUpdates&=~(P.TEXTURE_NOFADING&P.TEXTURE_FADING),h(t)){const e=m(t.layer.parent)?"normal":t.layer.blendMode;S[T]=e;const r="normal"!==e;r&&(l=r,n=!1)}_(t)?i=Math.max(i,this.tileSize*c):1===s&&1===x&&(t.isOpaque||this._dataToTexture(y)&&y.sourceLayerInfo.data.descriptor.isOpaque)&&(n=!0),++o}}this._composition.cleanupFBOPool(c,p.length),i=B(i);const x=i/this.tileSize,y=T-1;this._ensureBackgroundTexture(this.tileSize),e.visible||(o=a=0),0!==o?1===o&&!l&&this._useLayerTexture(e,y,f,G[y])||this._composeMapLayers(e,t,y,f,G,S,i,x,!n||l):this._useBackgroundTexture(e,a)}_ensureBackgroundTexture(e){s(this._backgroundTexture)&&(this._backgroundTexture=this._buildTexture(e),this._backgroundDirty=!0),this._backgroundDirty&&(this._composition.bindPool(0,e),this._passParameters.offset=n,this._passParameters.scale=1,this._passParameters.opacity=1,this._passParameters.blendMode=D.Normal,o(this.backgroundColor)&&(this._passParameters.backgroundColor=this.backgroundColor),this._composition.drawBackground(this._passParameters,o(this.backgroundColor)?A.ColorOnly:A.GridOnly),this._composition.copyFBOToTexture(this._backgroundTexture),this._composition.releasePool(),this._backgroundDirty=!1)}_useBackgroundTexture(e,t){let r=g.Immediate;(e.surface.view.layerViewManager.updating||t>0)&&(r=g.Delayed),this._backgroundTexture&&s(e.renderData.textureReference)&&(r=g.Immediate),e.renderData.setTextureReference(o(this._backgroundTexture)?new b(this._backgroundTexture,p.FADING,z,e.surface.baseOpacity,1,0):null,r)}_useLayerTexture(e,t,r,s){const o=t<r,a=o?1:e.surface.baseOpacity,i=o?e.surface.baseOpacity:1,n=F(e,t);return!!this._dataToTexture(n)&&(e.renderData.setTextureReference(new b(n.sourceLayerInfo.data,p.FADING,n,a,s,i)),!0)}_composeMapLayers(e,t,r,s,o,a,i,n,u){this._composition.bindPool(0,i);const c=e.surface.baseOpacity;let l=!1,p=R.LINEAR_MIPMAP_LINEAR,d=!1,h=0;for(let _=r;_>=0;_--){const t=F(e,_);if(!t)continue;if(0===o[_])continue;const r=_<s&&c<1&&!l;this._passParameters.baseOpacity=r?c:1,r&&(l=!0);const m=0===h,x=u&&m?this.backgroundIsGrid?A.GridComposite:A.ColorComposite:A.Composite;f(t)?(this._passParameters.opacity=o[_],this._passParameters.blendMode=w[a[_]],d=this._composition.drawVectorData(this._passParameters,t,n,this.tileSize,i,d,x)):T(t)?(this._passParameters.opacity=o[_],this._passParameters.blendMode=w[a[_]],this._composition.drawImageryTileData(t,x,this._passParameters),this._hasNearestInterpolation(t)&&(p=R.NEAREST)):this._dataToTexture(t)&&(this._passParameters.texture=t.sourceLayerInfo.data.texture,this._passParameters.offset=t.offset,this._passParameters.scale=t.scale,this._passParameters.opacity=o[_],this._passParameters.blendMode=w[a[_]],this._composition.drawRasterData(x,this._passParameters)),h++}const m=e.renderData.ensureTexture(i,(()=>this._buildTexture(i,p)));this._composition.copyFBOToTexture(m),this._composition.releasePool(),e.renderData.setTextureReference(new b(m,t,z,l?1:c,1,0))}_hasNearestInterpolation(e){const t=e.sourceLayerInfo.data;return!!t.source&&"nearest"===t.interpolation}_dataToTexture(e){return x(e)&&this._rasterDataToTexture(e),y(e)}_rasterDataToTexture(e){const t=e.sourceLayerInfo;t.data=this._buildTexture(t.data),e.tile.setMemoryDirty()}setBackground(e){this._backgroundColor!==e&&(this._backgroundColor=e,this._backgroundDirty=!0)}_buildTexture(e,t=R.LINEAR_MIPMAP_LINEAR){if(s(e))return null;const r={target:M.TEXTURE_2D,pixelFormat:j.RGBA,dataType:O.UNSIGNED_BYTE,wrapMode:N.CLAMP_TO_EDGE,samplingMode:t,maxAnisotropy:this._maxAnisotropy,flipped:!0,hasMipmap:!0},o=this._rctx;let a;if("number"==typeof e)r.width=r.height=e,a=new I(new U(o,r));else if(e instanceof c)r.isOpaque=e.isOpaque,a=new I(new U(o,r,e.image)),e.release();else try{a=new I(new U(o,r,e))}catch(n){a=new I(L(o)),console.warn("TileRenderer: failed to execute 'texImage2D', cross-origin image may not be loaded.")}const i=o.bindTexture(a.texture,U.TEXTURE_UNIT_FOR_UPDATES);return a.generateMipmap(),o.bindTexture(i,U.TEXTURE_UNIT_FOR_UPDATES),a}get test(){return{backgroundTexture:this._backgroundTexture}}}function B(t){const r=e(t),s=r*r,o=t*t;if(s===o)return t;const a=r/2;return s-o<o-a*a?r:a}function F(e,t){q.layerIndex=t;const r=e.layerInfo[d.MAP][t];if(o(r.data))return a(q.offset,0,0),q.tile=e,q.scale=1,q.sourceLod=e.lij,q.sourceLayerInfo=r,q;const s=r.upsampleInfo;if(o(s)){const e=s.tile.layerInfo[d.MAP][t];return q.tile=s.tile,i(q.offset,s.offset),q.scale=s.scale,q.sourceLod=s.tile.lij,q.sourceLayerInfo=e,q}return null}const G=new Array,S=new Array,q={tile:null,sourceLayerInfo:null,sourceLod:null,offset:[0,0],scale:1,layerIndex:0},z={offset:[0,0],scale:1};export{C as TileRenderer};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.24/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../core/has.js";import{isSome as t,isNone as r}from"../../core/maybe.js";var o;function n(e,r,o={}){const n=i(e);for(;n.length>1;){const e=l(r,n.shift(),o);if(t(e))return e}return c(r,n.shift(),o)}function i(t){const r=e("esri-force-webgl");if(r===o.WEBGL1||r===o.WEBGL2)return[r];switch(t){case"2d":case"3d":return[o.WEBGL2,o.WEBGL1]}}function c(e,t,o={}){if(!window.WebGLRenderingContext)return s(e,a),null;const n=l(e,t,o);return r(n)&&s(e,u),n}function l(e,t,r={}){const n=t===o.WEBGL1?["webgl","experimental-webgl","webkit-3d","moz-webgl"]:["webgl2"];let i=null;for(const o of n){try{i=e.getContext(o,r)}catch(c){}if(i)break}return i}function s(e,t){const r=e.parentNode;r&&(r.innerHTML='<table style="background-color: #8CE; width: 100%; height: 100%;"><tr><td align="center"><div style="display: table-cell; vertical-align: middle;"><div style="">'+t+"</div></div></td></tr></table>")}!function(e){e[e.WEBGL1=1]="WEBGL1",e[e.WEBGL2=2]="WEBGL2"}(o||(o={}));const a='This page requires a browser that supports WebGL.<br/><a href="http://get.webgl.org">Click here to upgrade your browser.</a>',u='It doesn\'t appear your computer can support WebGL.<br/><a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>';export{o as ContextType,l as createContext,n as createContextOrErrorHTML,i as getContextTypes};
5
+ import e from"../../core/has.js";import{isSome as t,isNone as r}from"../../core/maybe.js";var o;function n(e,r,o={}){const n=i(e);for(;n.length>1;){const e=l(r,n.shift(),o);if(t(e))return e}return c(r,n.shift(),o)}function i(t){const r=e("esri-force-webgl");if(r===o.WEBGL1||r===o.WEBGL2)return[r];switch(t){case"2d":return e("mac")&&e("chrome")?[o.WEBGL1,o.WEBGL2]:[o.WEBGL2,o.WEBGL1];case"3d":return[o.WEBGL2,o.WEBGL1]}}function c(e,t,o={}){if(!window.WebGLRenderingContext)return a(e,s),null;const n=l(e,t,o);return r(n)&&a(e,u),n}function l(e,t,r={}){const n=t===o.WEBGL1?["webgl","experimental-webgl","webkit-3d","moz-webgl"]:["webgl2"];let i=null;for(const o of n){try{i=e.getContext(o,r)}catch(c){}if(i)break}return i}function a(e,t){const r=e.parentNode;r&&(r.innerHTML='<table style="background-color: #8CE; width: 100%; height: 100%;"><tr><td align="center"><div style="display: table-cell; vertical-align: middle;"><div style="">'+t+"</div></div></td></tr></table>")}!function(e){e[e.WEBGL1=1]="WEBGL1",e[e.WEBGL2=2]="WEBGL2"}(o||(o={}));const s='This page requires a browser that supports WebGL.<br/><a href="http://get.webgl.org">Click here to upgrade your browser.</a>',u='It doesn\'t appear your computer can support WebGL.<br/><a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>';export{o as ContextType,l as createContext,n as createContextOrErrorHTML,i as getContextTypes};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.24/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../chunks/tslib.es6.js";import{makeHandle as t}from"../../core/handleUtils.js";import{isSome as i}from"../../core/maybe.js";import{onAbort as a,createAbortError as s,throwIfAborted as o,isAborted as r}from"../../core/promiseUtils.js";import{watch as d}from"../../core/reactiveUtils.js";import"../../core/Logger.js";import"../../core/accessorSupport/ensureType.js";import"../../core/arrayUtils.js";import"../../core/has.js";import"../../core/accessorSupport/set.js";import{subclass as n}from"../../core/accessorSupport/decorators/subclass.js";import{highlightsSupported as l}from"../../views/support/layerViewUtils.js";import{Edits as c}from"./Edits.js";import u from"./UpdateWorkflowData.js";import m from"./Workflow.js";import{createWorkflowSteps as w,fetchCandidates as h,fetchFullFeature as f,findLayerInfo as p,getVisualVariableAttributes as g,setUpGeometryUpdate as v}from"./workflowUtils.js";var y;const M="candidate-highlight";let b=y=class extends m{constructor(e){super(e),this.type="update"}static create(e,t,i){const a=new y({data:new u({edits:new c,viewModel:e}),onCommit:async e=>{const t=e.edits.feature,a=t.sourceLayer,s=t.clone();if(!e.edits.attributesModified){const{objectIdField:e}=a;s.attributes={[e]:t.getAttribute(e)}}e.edits.geometryModified||(s.geometry=null),await i(a,{updateFeatures:[s]})}});return a._set("steps",this._createWorkflowSteps(a,t)),a}highlight(e){const{data:{viewModel:{view:t}}}=this,i=e&&t.allLayerViews.items.find((({layer:t})=>t===e.layer));l(i)&&this.handles.add(i.highlight(e),M)}unhighlight(){this.handles.remove(M)}static _createWorkflowSteps(e,n="awaiting-feature-to-update"){const{data:l,handles:c}=e,u=new Map;return w(["awaiting-feature-to-update","awaiting-update-feature-candidate","editing-existing-feature","adding-attachment","editing-attachment"],n,{"awaiting-feature-to-update":()=>({id:"awaiting-feature-to-update",async setUp(){const{spinnerViewModel:e,view:t}=l.viewModel;let i=null;c.add({remove(){i&&(i.abort(),i=null)}},this.id),l.edits.feature=null;const r=t.on("immediate-click",(r=>{e.location=r.mapPoint,e.visible=!0,i&&i.abort();const{editableItems:d}=l.viewModel;i=new AbortController,new Promise(((e,o)=>{a(i.signal,(()=>o(s()))),e(h(d,t,r,i.signal))})).then((e=>{if(o(i),l.candidates=e.reduce(((e,t)=>t.error?e:[...e,...t.value]),[]),l.viewModel.spinnerViewModel.visible=1===l.candidates.length,0!==l.candidates.length)if(1===l.candidates.length){const e=l.candidates[0];l.edits.feature=e,l.viewModel.activeWorkflow.go("editing-existing-feature").catch((()=>{})).then((()=>l.viewModel.spinnerViewModel.visible=!1))}else l.viewModel.activeWorkflow.next()}))}));t.focus(),c.add(r,this.id)},async tearDown(){c.remove(this.id)}}),"awaiting-update-feature-candidate":()=>({id:"awaiting-update-feature-candidate",async setUp(){const{edits:t}=l;t.feature=null,c.add(d((()=>t.feature),(t=>{e.unhighlight(),e.highlight(t)})),this.id)},async tearDown(){e.unhighlight(),c.remove(this.id)}}),"editing-existing-feature":()=>({id:"editing-existing-feature",async setUp(){if(c.has("editing-existing-feature"))return;const a=l.edits.feature,s=l.viewModel;l.editableItem=s.editableItems.find((e=>e.layer===a.layer));const o=new AbortController;c.add({remove:()=>o.abort()},this.id);const n=s.view.whenLayerView(a.layer),m=f(a,s.view,o.signal),w=await n,h=await m;if(r(o))return;l.edits.updateGeometry(h.geometry),l.edits.updateAttributes(h.attributes),l.edits.trackChanges(),s.attachmentsViewModel.set({graphic:h,mode:"view"});const y=h.sourceLayer,M=p(s.layerInfos,y)?.formTemplate,b=s.view.spatialReference;s.featureFormViewModel.set({feature:h,formTemplate:M,spatialReference:b});const V="createInteractiveEditSession"in w?w.createInteractiveEditSession(a):null,j=[s.featureFormViewModel.on("value-change",(e=>{l.edits.updateAttributes(s.featureFormViewModel.getValues()),h.attributes=l.edits.feature.attributes,V&&V.setAttribute(e.fieldName,e.value)})),d((()=>s.attachmentsViewModel.mode),(e=>{"add"===e&&l.viewModel.activeWorkflow.go("adding-attachment"),"edit"===e&&l.viewModel.activeWorkflow.go("editing-attachment")}))];V&&(j.push(t((()=>V.rollback()))),c.add(t((()=>V.commit())),e._handleKeys.afterCommit));const{supportsGeometryUpdate:k}=y.capabilities.editing;if(k){s.sketchViewModel.allowDeleteKey=!1;const t=g(h),{interactive:a,visual:o}=await v(h,t,s.sketchViewModel,s.view,(({geometry:e,attributes:a})=>{if(i(t.rotation)){const{field:e}=t.rotation;s.featureFormViewModel.setValue(e,a[e])}if(i(t.size)){const{field:e}=t.size;s.featureFormViewModel.setValue(e,a[e])}l.edits.updateAttributes(a),l.edits.updateGeometry(e)}),u);j.push(a,o),c.add(a,e._handleKeys.beforeCommit),c.add(o,e._handleKeys.afterCommit)}else e.highlight(h);c.add(j,this.id)},async tearDown({cancelled:t}){t&&(e.unhighlight(),c.remove(this.id))}}),"adding-attachment":()=>({id:"adding-attachment",parent:"editing-existing-feature",async setUp(){},async tearDown(){l.viewModel.attachmentsViewModel.mode="view"}}),"editing-attachment":()=>({id:"editing-attachment",parent:"editing-existing-feature",async setUp(){},async tearDown(){l.viewModel.attachmentsViewModel.mode="view"}})})}};b=y=e([n("esri.widgets.Editor.UpdateWorkflow")],b);const V=b;export{V as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import{makeHandle as t}from"../../core/handleUtils.js";import{isSome as i}from"../../core/maybe.js";import{onAbort as a,createAbortError as o,throwIfAborted as s,isAborted as r}from"../../core/promiseUtils.js";import{watch as d}from"../../core/reactiveUtils.js";import"../../core/Logger.js";import"../../core/accessorSupport/ensureType.js";import"../../core/arrayUtils.js";import"../../core/has.js";import"../../core/accessorSupport/set.js";import{subclass as n}from"../../core/accessorSupport/decorators/subclass.js";import{highlightsSupported as l}from"../../views/support/layerViewUtils.js";import{Edits as c}from"./Edits.js";import u from"./UpdateWorkflowData.js";import m from"./Workflow.js";import{createWorkflowSteps as w,fetchCandidates as h,fetchFullFeature as f,findLayerInfo as p,getVisualVariableAttributes as g,setUpGeometryUpdate as v}from"./workflowUtils.js";var y;const M="candidate-highlight";let b=y=class extends m{constructor(e){super(e),this.type="update"}static create(e,t,i){const a=new y({data:new u({edits:new c,viewModel:e}),onCommit:async e=>{const t=e.edits.feature,a=t.sourceLayer,o=t.clone();if(!e.edits.attributesModified){const{objectIdField:e}=a;o.attributes={[e]:t.getAttribute(e)}}e.edits.geometryModified||(o.geometry=null),await i(a,{updateFeatures:[o]})}});return a._set("steps",this._createWorkflowSteps(a,t)),a}highlight(e){const{data:{viewModel:{view:t}}}=this,i=e&&t.allLayerViews.items.find((({layer:t})=>t===e.layer));l(i)&&this.handles.add(i.highlight(e),M)}unhighlight(){this.handles.remove(M)}static _createWorkflowSteps(e,n="awaiting-feature-to-update"){const{data:l,handles:c}=e,u=new Map;return w(["awaiting-feature-to-update","awaiting-update-feature-candidate","editing-existing-feature","adding-attachment","editing-attachment"],n,{"awaiting-feature-to-update":()=>({id:"awaiting-feature-to-update",async setUp(){const{spinnerViewModel:e,view:t}=l.viewModel;let i=null;c.add({remove(){i&&(i.abort(),i=null)}},this.id),l.edits.feature=null;const r=t.on("immediate-click",(r=>{e.location=r.mapPoint,e.visible=!0,i&&i.abort();const{editableItems:d}=l.viewModel;i=new AbortController,new Promise(((e,s)=>{a(i.signal,(()=>s(o()))),e(h(d,t,r,i.signal))})).then((e=>{if(s(i),l.candidates=e.reduce(((e,t)=>t.error?e:[...e,...t.value]),[]),l.viewModel.spinnerViewModel.visible=1===l.candidates.length,0!==l.candidates.length)if(1===l.candidates.length){const e=l.candidates[0];l.edits.feature=e,l.viewModel.activeWorkflow.go("editing-existing-feature").catch((()=>{})).then((()=>l.viewModel.spinnerViewModel.visible=!1))}else l.viewModel.activeWorkflow.next()}))}));t.focus(),c.add(r,this.id)},async tearDown(){c.remove(this.id)}}),"awaiting-update-feature-candidate":()=>({id:"awaiting-update-feature-candidate",async setUp(){const{edits:t}=l;t.feature=null,c.add(d((()=>t.feature),(t=>{e.unhighlight(),e.highlight(t)})),this.id)},async tearDown(){e.unhighlight(),c.remove(this.id)}}),"editing-existing-feature":()=>({id:"editing-existing-feature",async setUp(){if(c.has("editing-existing-feature"))return;const a=l.edits.feature,o=l.viewModel;l.editableItem=o.editableItems.find((e=>e.layer===a.layer));const s=new AbortController;c.add({remove:()=>s.abort()},this.id);const n=o.view.whenLayerView(a.layer),m=f(a,o.view,s.signal),w=await n,h=await m;if(r(s))return;l.edits.updateGeometry(h.geometry),l.edits.updateAttributes(h.attributes),l.edits.trackChanges(),o.attachmentsViewModel.set({graphic:h,mode:"view"});const y=h.sourceLayer,M=p(o.layerInfos,y)?.formTemplate,b=o.view.spatialReference;o.featureFormViewModel.set({feature:h,formTemplate:M,spatialReference:b});const V="createInteractiveEditSession"in w?w.createInteractiveEditSession(a):null,j=[o.featureFormViewModel.on("value-change",(e=>{l.edits.updateAttributes(o.featureFormViewModel.getValues()),h.attributes=l.edits.feature.attributes,V&&V.setAttribute(e.fieldName,e.value)})),d((()=>o.attachmentsViewModel.mode),(e=>{"add"===e&&l.viewModel.activeWorkflow.go("adding-attachment"),"edit"===e&&l.viewModel.activeWorkflow.go("editing-attachment")}))];V&&(j.push(t((()=>V.rollback()))),c.add(t((()=>V.commit())),e._handleKeys.afterCommit));const{supportsGeometryUpdate:k}=y.capabilities.editing;if(k){o.sketchViewModel.allowDeleteKey=!1;const t=g(h),{interactive:a,visual:s}=await v(h,t,o.sketchViewModel,o.view,(({geometry:e,attributes:a})=>{if(i(t.rotation)){const{field:e}=t.rotation;o.featureFormViewModel.setValue(e,a[e])}if(i(t.size)){const{field:e}=t.size;o.featureFormViewModel.setValue(e,a[e])}l.edits.updateAttributes(a),l.edits.updateGeometry(e),o.featureFormViewModel.feature.geometry=e}),u);j.push(a,s),c.add(a,e._handleKeys.beforeCommit),c.add(s,e._handleKeys.afterCommit)}else e.highlight(h);c.add(j,this.id)},async tearDown({cancelled:t}){t&&(e.unhighlight(),c.remove(this.id))}}),"adding-attachment":()=>({id:"adding-attachment",parent:"editing-existing-feature",async setUp(){},async tearDown(){l.viewModel.attachmentsViewModel.mode="view"}}),"editing-attachment":()=>({id:"editing-attachment",parent:"editing-existing-feature",async setUp(){},async tearDown(){l.viewModel.attachmentsViewModel.mode="view"}})})}};b=y=e([n("esri.widgets.Editor.UpdateWorkflow")],b);const V=b;export{V 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.24/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{aliasOf as l}from"../core/accessorSupport/decorators/aliasOf.js";import"../core/arrayUtils.js";import"../core/has.js";import{cast as d}from"../core/accessorSupport/decorators/cast.js";import{property as c}from"../core/accessorSupport/decorators/property.js";import{subclass as p}from"../core/accessorSupport/decorators/subclass.js";import{getDisplayFieldName as h}from"../layers/support/fieldUtils.js";import m from"../views/interactive/sketch/SketchLabelOptions.js";import u from"../views/interactive/sketch/SketchTooltipOptions.js";import g from"../views/interactive/snapping/SnappingOptions.js";import v from"./Attachments.js";import w from"./FeatureForm.js";import _ from"./FeatureTemplates.js";import f from"./Spinner.js";import k from"./Widget.js";import{workflowDeprecation as b}from"./Editor/deprecationUtils.js";import y from"./Editor/EditorViewModel.js";import{ItemList as C}from"./FeatureTemplates/ItemList.js";import{Heading as M,incrementHeadingLevel as A}from"./support/Heading.js";import F from"./support/SnappingControls.js";import{accessibleHandler as W}from"./support/decorators/accessibleHandler.js";import{messageBundle as T}from"./support/decorators/messageBundle.js";import{vmEvent as S}from"./support/decorators/vmEvent.js";import{tsx as E}from"./support/jsxFactory.js";import{classes as B}from"./support/widgetUtils.js";import{substitute as P}from"../intl/substitute.js";const j={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",panelContentSection:"esri-editor__panel-content__section",panelContentSectionGroup:"esri-editor__panel-content__section__group",panelContentMessage:"esri-editor__panel-content__message",scroller:"esri-editor__scroller",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"},L=B(j.scroller,j.panelContent),x={undoRedoButtons:!1};function U(e){e.focus()}const V="esri.widgets.Editor",D=s.getLogger(V);let I=class extends(t(k)){constructor(e,t){super(e,t),this._candidateCommitted=!1,this._featureForm=new w,this._stateStack=[],this._attachments=new v({visibleElements:{addSubmitButton:!1,cancelAddButton:!1,cancelUpdateButton:!1,deleteButton:!1,errorMessage:!1,progressBar:!1,updateButton:!1}}),this._featureTemplates=new _({enableListScroll:!1}),this._filterText="",this._prompt=null,this._spinner=new f,this._snappingPopover=null,this.activeWorkflow=null,this.allowedWorkflows=null,this.useDeprecatedCreateWorkflow=!1,this.headingLevel=4,this.iconClass=j.widgetIcon,this.label=void 0,this.labelOptions=new m,this.layerInfos=null,this.messages=null,this.messagesCommon=null,this.messagesTemplates=null,this.snappingOptions=new g,this.tooltipOptions=new u,this.supportingWidgetDefaults=null,this.view=null,this.viewModel=new y,this.visibleElements={...x},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 F({snappingOptions:t,view:e,visibleElements:{header:!1}}),this.own([i((()=>this.headingLevel),(e=>{this._featureForm.headingLevel=A(e),this._featureTemplates.headingLevel=A(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:P(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=>{"awaiting-feature-to-update"===e&&(this._filterText=""),"awaiting-update-feature-candidate"===e&&(this._candidateCommitted=!1)})),i((()=>[this._attachments?.selectedFile,this._attachments?.submitting]),(()=>this.scheduleRender())),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-action-menu.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-loader.js"),import("@esri/calcite-components/dist/components/calcite-panel.js"),import("@esri/calcite-components/dist/components/calcite-popover.js"),import("@esri/calcite-components/dist/components/calcite-scrim.js")])}castVisibleElements(e){return{...x,...e}}startCreateWorkflowAtFeatureTypeSelection(){return b(D,"startCreateWorkflowAtFeatureTypeSelection","startCreateFeaturesWorkflowAtFeatureTypeSelection"),this.viewModel.startCreateWorkflowAtFeatureTypeSelection()}startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.viewModel.startCreateFeaturesWorkflowAtFeatureTypeSelection()}startCreateWorkflowAtFeatureCreation(e){return b(D,"startCreateWorkflowAtFeatureCreation","startCreateFeaturesWorkflowAtFeatureCreation"),this.viewModel.startCreateWorkflowAtFeatureCreation(e)}startCreateFeaturesWorkflowAtFeatureCreation(e){return this.viewModel.startCreateFeaturesWorkflowAtFeatureCreation(e)}startCreateWorkflowAtFeatureEdit(e){return b(D,"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 E("div",{class:j.base});const{state:i}=s,n=a(t)?E("calcite-scrim",null,this.renderPrompt(t)):null;return E("div",{class:j.base},s.syncing||e.submitting?this.renderProgressBar():null,E("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 E("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 E(t,{active:this.isPanelActive(e),key:"templates-panel",handleBack:n,heading:a.selectTemplate,headingLevel:s,messages:a,messagesCommon:i,sketchViewModel:r,snappingControls:o},E("div",{class:L},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,m="update"===t.type?i.update:i.create,u="create-features"===t.type&&"create-new"===t.createFeatureState,g="update"===t.type&&t.data.editableItem.supports.includes("delete"),v="update"===t.type&&t.data.editableItem.hasAttachments,w=[{label:"create-features"===t.type&&t.numPendingFeatures>1?P(a.createFeaturesTemplate,{numFeatures:t.numPendingFeatures}):m,type:"primary",disabled:p,clickHandler:this._handleSave,width:g?"half":"full"}];return g&&w.push({label:i.delete,type:"tertiary",clickHandler:this._handleDelete,appearance:"outline",width:"half"}),E(s,{active:this.isPanelActive(e),key:"attribute-editing-panel",heading:h,headingLevel:n,handleBack:o,messages:a,messagesCommon:i,sketchViewModel:d,snappingControls:r},E("div",{class:L},E("div",{class:j.panelContentSection},E("div",{class:j.panelContentSectionGroup},c.inputFields.length>0?this._featureForm.render():this.renderMessage(P(a.clickToFinishTemplate,{button:m})),v?E("div",{key:"attachments"},E("div",null,a.attachments),this._attachments.render()):null),u?E("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 E(s,{active:this.isPanelActive(e),key:"attachment-adding-panel",heading:n.addAttachment,headingLevel:i,handleBack:a,messages:n,messagesCommon:o,sketchViewModel:l,snappingControls:r},E("div",{class:L},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 E(s,{active:this.isPanelActive(e),key:"attachment-editing-panel",heading:n.editAttachment,headingLevel:i,handleBack:a,messages:n,messagesCommon:o,sketchViewModel:l,snappingControls:r},E("div",{class:L},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 E(t,{active:this.isPanelActive(e),key:"feature-updating-panel",heading:i.selectFeature,headingLevel:a,handleBack:s,messages:i,messagesCommon:n,sketchViewModel:r,snappingControls:o},E("div",{class:B(L,j.panelContentMessage)},this.renderMessage(i.selectFeatureToEdit)))}renderMessage(e){return E("div",{class:j.message},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 E(t,{active:this.isPanelActive(e),key:"feature-creation-panel",heading:i.placeFeature,headingLevel:a,handleBack:s,messages:i,messagesCommon:n,sketchViewModel:l,snappingControls:o},E("div",{class:B(L,j.panelContentMessage)},this.renderMessage(h)))}renderFooterActions(e){return e.map((({type:e,disabled:t,class:s,...a},i)=>this.renderButton({class:this.classes(j.controlButton,"secondary"===e?j.buttonSecondary:"tertiary"===e?j.buttonTertiary:null,t?j.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=E("calcite-button",{appearance:"solid",color:"danger"===s?"red":"blue",width:i?"half":"full",onclick:a.primary.action,key:"prompt-primary-button",afterCreate:U},a.primary.label),o=i?E("calcite-button",{appearance:"clear",color:"danger"===s?"red":"blue",width:"half",onclick:a.secondary.action,key:"prompt-secondary-button"},a.secondary.label):null;return E("div",{class:`${j.promptContainer}--${s}`},E("div",{class:j.promptHeader},E("calcite-icon",{icon:"exclamation-mark-triangle"}),E(M,{class:j.promptHeading,level:this.headingLevel},e)),E("div",{class:j.promptMessage},t),E("div",{class:j.promptDivider}),E("div",{class:j.promptActions},o,n))}renderProgressBar(){return E("div",{class:this.classes(j.progressBar),key:"progress-bar"})}renderButton(e){const{disabled:t,class:s,key:a,clickHandler:i,label:n,...o}=e;return E("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,viewModel:{sketchViewModel:o}}=this;return E(t,{active:this.isPanelActive(e),key:"landing-panel",heading:a.widgetLabel,headingLevel:s,showBackButton:!1,messages:a,messagesCommon:i,sketchViewModel:o,snappingControls:n},E("div",{class:L},E("div",{key:"edit-actions",class:j.panelContentSection},this.renderUpdateActions()),E("div",{key:"create-actions",class:j.panelContentSection},this.renderCreateActions())))}renderUpdateActions(){const{messages:e,messagesCommon:t}=this;return E("div",null,E(M,{level:A(this.headingLevel)},e.editFeatures),E("div",{class:j.updateFeaturesActionButtons},E("calcite-action",{text:t.select,textEnabled:!0,icon:"cursor",alignment:"start",class:j.updateFeaturesActionButtonsButton,onclick:this._handleEdit})))}renderCreateActions(){const{_featureTemplates:e,headingLevel:t,messages:s}=this;if(0!==e.viewModel.numberOfFeatureTemplates)return E("div",null,E(M,{level:A(t)},s.createFeatures),E("div",{key:"templates",class:j.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=P(i.multipleFeaturesTemplate,{total:c.length}),h=new Map;let m=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=>{m++;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 u=l.filter((({layer:e})=>h.has(e))).map((({layer:e})=>h.get(e))).toArray(),g=m>10||this._filterText.length>0;return E(t,{active:this.isPanelActive(e),key:"feature-list",heading:p,headingLevel:a,handleBack:s,messages:i,messagesCommon:n,sketchViewModel:d,snappingControls:r},E("div",{class:L},C({id:this.id,enableListScroll:!1,filterEnabled:g,filterText:this._filterText,items:u,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;return E("calcite-panel",{bind:this,key:o,heading:i,headingLevel:n,showBackButton:d??!0,beforeBack:a??null,onCalcitePanelScroll:this._onSnappingPopoverPanelScroll},E("div",{class:j.panelToolbar},E("calcite-popover",{autoClose:s,afterCreate:this._afterSnappingPopoverCreated,afterUpdate:this._afterSnappingPopoverUpdated,bind:this,label:r.snappingSettings,heading:r.snappingSettings,"reference-element":`${o}__snappingButton`,"overlay-positioning":"fixed",placement:"bottom"},E("div",{class:j.snappingControlsPopover},p.render())),E("calcite-button",{id:`${o}__snappingButton`,text:r.snapping,appearance:"transparent",color:"neutral",alignment:"icon-end-space-between","icon-start":"vertex-gps","icon-end":"caret-down",width:"full",class:j.panelToolbarSnappingButton},r.snapping),this.visibleElements.undoRedoButtons?[E("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)}),E("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)}_onSnappingPopoverPanelScroll(){this._snappingPopover?.open&&this._snappingPopover.toggle()}_afterSnappingPopoverCreated(e){this._snappingPopover=e}_afterSnappingPopoverUpdated(e){this._snappingPopover=e}_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=h(t);return i&&a[i]&&`${a[i]}`||P(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;e.addAttachment().then((()=>t.previous()))}_handleAttachmentUpdate(){const{_attachments:e}=this,{activeWorkflow:t}=this.viewModel;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;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(){const{messages:e}=this,t=this.activeWorkflow,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{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;throw this._prompt={title:n,message:i,context:"danger",actions:{primary:{label:r,action:()=>{s(),this._prompt=null}},secondary:{label:o,action:()=>this._prompt=null}}},this.scheduleRender(),new Error}s()}_assertActiveCreateWorkflow(){const{type:e}=this.viewModel.activeWorkflow;if("create"===e||"create-features"===e)return this.viewModel.activeWorkflow;throw Error("Expected activeWorkflow to be instance of CreateWorkflow or CreateFeaturesWorkflow")}_assertActiveUpdateWorkflow(){if("update"===this.viewModel.activeWorkflow.type)return this.viewModel.activeWorkflow;throw Error("Expected activeWorkflow to be an UpdateWorkflow")}};e([c()],I.prototype,"_attachments",void 0),e([l("viewModel.activeWorkflow")],I.prototype,"activeWorkflow",void 0),e([l("viewModel.allowedWorkflows")],I.prototype,"allowedWorkflows",void 0),e([c()],I.prototype,"useDeprecatedCreateWorkflow",void 0),e([c()],I.prototype,"headingLevel",void 0),e([c()],I.prototype,"iconClass",void 0),e([c({aliasOf:{source:"messages.widgetLabel",overridable:!0}})],I.prototype,"label",void 0),e([l("viewModel.labelOptions")],I.prototype,"labelOptions",void 0),e([l("viewModel.layerInfos")],I.prototype,"layerInfos",void 0),e([c(),T("esri/widgets/Editor/t9n/Editor")],I.prototype,"messages",void 0),e([c(),T("esri/t9n/common")],I.prototype,"messagesCommon",void 0),e([c(),T("esri/widgets/FeatureTemplates/t9n/FeatureTemplates")],I.prototype,"messagesTemplates",void 0),e([l("viewModel.snappingOptions")],I.prototype,"snappingOptions",void 0),e([l("viewModel.tooltipOptions")],I.prototype,"tooltipOptions",void 0),e([c()],I.prototype,"supportingWidgetDefaults",void 0),e([l("viewModel.view")],I.prototype,"view",void 0),e([c(),S(["workflow-cancel","workflow-commit"])],I.prototype,"viewModel",void 0),e([c()],I.prototype,"visibleElements",void 0),e([d("visibleElements")],I.prototype,"castVisibleElements",null),e([W()],I.prototype,"_handleDelete",null),e([W()],I.prototype,"_handleAttachmentAdd",null),e([W()],I.prototype,"_handleAttachmentUpdate",null),e([W()],I.prototype,"_handleAttachmentDelete",null),e([W()],I.prototype,"_handleAdd",null),e([W()],I.prototype,"_handleEdit",null),e([W()],I.prototype,"_handleDone",null),I=e([p(V)],I);const O=I;export{O 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 o,when as n,initial as r}from"../core/reactiveUtils.js";import{aliasOf as l}from"../core/accessorSupport/decorators/aliasOf.js";import"../core/arrayUtils.js";import"../core/has.js";import{cast as d}from"../core/accessorSupport/decorators/cast.js";import{property as c}from"../core/accessorSupport/decorators/property.js";import{subclass as p}from"../core/accessorSupport/decorators/subclass.js";import{getDisplayFieldName as h}from"../layers/support/fieldUtils.js";import m from"../views/interactive/sketch/SketchLabelOptions.js";import u from"../views/interactive/sketch/SketchTooltipOptions.js";import g from"../views/interactive/snapping/SnappingOptions.js";import v from"./Attachments.js";import w from"./FeatureForm.js";import _ from"./FeatureTemplates.js";import f from"./Spinner.js";import k from"./Widget.js";import{workflowDeprecation as b}from"./Editor/deprecationUtils.js";import y from"./Editor/EditorViewModel.js";import{ItemList as C}from"./FeatureTemplates/ItemList.js";import{Heading as M,incrementHeadingLevel as A}from"./support/Heading.js";import F from"./support/SnappingControls.js";import{accessibleHandler as W}from"./support/decorators/accessibleHandler.js";import{messageBundle as T}from"./support/decorators/messageBundle.js";import{vmEvent as S}from"./support/decorators/vmEvent.js";import{tsx as E}from"./support/jsxFactory.js";import{classes as B}from"./support/widgetUtils.js";import{substitute as P}from"../intl/substitute.js";const j={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",scroller:"esri-editor__scroller",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"},L=B(j.scroller,j.panelContent),x={undoRedoButtons:!1};function U(e){e.focus()}const V="esri.widgets.Editor",D=s.getLogger(V);let I=class extends(t(k)){constructor(e,t){super(e,t),this._candidateCommitted=!1,this._featureForm=new w,this._stateStack=[],this._attachments=new v({visibleElements:{addSubmitButton:!1,cancelAddButton:!1,cancelUpdateButton:!1,deleteButton:!1,errorMessage:!1,progressBar:!1,updateButton:!1}}),this._featureTemplates=new _({enableListScroll:!1}),this._filterText="",this._prompt=null,this._spinner=new f,this._snappingPopover=null,this.activeWorkflow=null,this.allowedWorkflows=null,this.useDeprecatedCreateWorkflow=!1,this.headingLevel=4,this.iconClass=j.widgetIcon,this.label=void 0,this.labelOptions=new m,this.layerInfos=null,this.messages=null,this.messagesCommon=null,this.messagesTemplates=null,this.snappingOptions=new g,this.tooltipOptions=new u,this.supportingWidgetDefaults=null,this.view=null,this.viewModel=new y,this.visibleElements={...x},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 F({snappingOptions:t,view:e,visibleElements:{header:!1}}),this.own([i((()=>this.headingLevel),(e=>{this._featureForm.headingLevel=A(e),this._featureTemplates.headingLevel=A(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),o((()=>this.viewModel?.sketchViewModel),"create",(()=>{this.scheduleRender()})),o((()=>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:P(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=>{"awaiting-feature-to-update"===e&&(this._filterText=""),"awaiting-update-feature-candidate"===e&&(this._candidateCommitted=!1)})),i((()=>[this._attachments?.selectedFile,this._attachments?.submitting]),(()=>this.scheduleRender())),n((()=>!this.viewModel?.activeWorkflow),(()=>this._featureTemplates.filterText="")),o((()=>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-action-menu.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-loader.js"),import("@esri/calcite-components/dist/components/calcite-panel.js"),import("@esri/calcite-components/dist/components/calcite-popover.js"),import("@esri/calcite-components/dist/components/calcite-scrim.js")])}castVisibleElements(e){return{...x,...e}}startCreateWorkflowAtFeatureTypeSelection(){return b(D,"startCreateWorkflowAtFeatureTypeSelection","startCreateFeaturesWorkflowAtFeatureTypeSelection"),this.viewModel.startCreateWorkflowAtFeatureTypeSelection()}startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.viewModel.startCreateFeaturesWorkflowAtFeatureTypeSelection()}startCreateWorkflowAtFeatureCreation(e){return b(D,"startCreateWorkflowAtFeatureCreation","startCreateFeaturesWorkflowAtFeatureCreation"),this.viewModel.startCreateWorkflowAtFeatureCreation(e)}startCreateFeaturesWorkflowAtFeatureCreation(e){return this.viewModel.startCreateFeaturesWorkflowAtFeatureCreation(e)}startCreateWorkflowAtFeatureEdit(e){return b(D,"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 E("div",{class:j.base});const{state:i}=s,o=a(t)?E("calcite-scrim",null,this.renderPrompt(t)):null;return E("div",{class:j.base},s.syncing||e.submitting?this.renderProgressBar():null,E("calcite-flow",null,this._stateStack.map((e=>this.renderState(e))),this.renderState(i)),o)}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 E("div",null)}isPanelActive(e){return this.viewModel.state===e}renderTemplates(e){const{EditorPanel:t,headingLevel:s,messages:a,messagesCommon:i,_handleBack:o,_snappingControls:n,viewModel:{sketchViewModel:r}}=this;return E(t,{active:this.isPanelActive(e),key:"templates-panel",handleBack:o,heading:a.selectTemplate,headingLevel:s,messages:a,messagesCommon:i,sketchViewModel:r,snappingControls:n},E("div",{class:L},this._featureTemplates.render()))}renderAttributeEditing(e){const{activeWorkflow:t,EditorPanel:s,messages:a,messagesCommon:i,headingLevel:o,_handleBack:n,_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,m="update"===t.type?i.update:i.create,u="create-features"===t.type&&"create-new"===t.createFeatureState,g="update"===t.type&&t.data.editableItem.supports.includes("delete"),v="update"===t.type&&t.data.editableItem.hasAttachments,w=[{label:"create-features"===t.type&&t.numPendingFeatures>1?P(a.createFeaturesTemplate,{numFeatures:t.numPendingFeatures}):m,type:"primary",disabled:p,clickHandler:this._handleSave,width:g?"half":"full"}];g&&w.push({label:i.delete,type:"tertiary",clickHandler:this._handleDelete,appearance:"outline",width:"half"});const _=c.inputFields.every((e=>!e.visible))?this.renderMessage(P(a.clickToFinishTemplate,{button:m})):E("div",{class:j.panelContentSection},E("div",{class:j.panelContentSectionGroup},this._featureForm.render(),v?E("div",{key:"attachments"},E("div",null,a.attachments),this._attachments.render()):null));return E(s,{active:this.isPanelActive(e),key:"attribute-editing-panel",heading:h,headingLevel:o,handleBack:n,messages:a,messagesCommon:i,sketchViewModel:d,snappingControls:r},E("div",{class:L},_,u?E("calcite-scrim",null):null),this.renderFooterActions(w))}renderAttachmentAdding(e){const{_attachments:t,EditorPanel:s,_handleBack:a,headingLevel:i,messages:o,messagesCommon:n,_snappingControls:r,viewModel:{sketchViewModel:l}}=this,d=[{label:t.submitting?n.cancel:n.add,disabled:t.submitting||!t.selectedFile,type:"primary",clickHandler:this._handleAttachmentAdd,width:"full"}];return E(s,{active:this.isPanelActive(e),key:"attachment-adding-panel",heading:o.addAttachment,headingLevel:i,handleBack:a,messages:o,messagesCommon:n,sketchViewModel:l,snappingControls:r},E("div",{class:L},t.render()),this.renderFooterActions(d))}renderAttachmentEditing(e){const{_attachments:t,EditorPanel:s,_handleBack:a,headingLevel:i,messages:o,messagesCommon:n,_snappingControls:r,viewModel:{sketchViewModel:l}}=this,d=[{label:n.update,disabled:t.submitting||!t.selectedFile,type:"primary",clickHandler:this._handleAttachmentUpdate,width:"half"},{label:n.delete,disabled:t.submitting,type:"tertiary",clickHandler:this._handleAttachmentDelete,width:"half",appearance:"outline"}];return E(s,{active:this.isPanelActive(e),key:"attachment-editing-panel",heading:o.editAttachment,headingLevel:i,handleBack:a,messages:o,messagesCommon:n,sketchViewModel:l,snappingControls:r},E("div",{class:L},t.render()),this.renderFooterActions(d))}renderFeatureUpdating(e){const{EditorPanel:t,_handleBack:s,headingLevel:a,messages:i,messagesCommon:o,_snappingControls:n,viewModel:{sketchViewModel:r}}=this;return E(t,{active:this.isPanelActive(e),key:"feature-updating-panel",heading:i.selectFeature,headingLevel:a,handleBack:s,messages:i,messagesCommon:o,sketchViewModel:r,snappingControls:n},E("div",{class:L},this.renderMessage(i.selectFeatureToEdit)))}renderMessage(e){return E("div",{class:j.panelContentMessage},e)}renderFeatureCreation(e){const{EditorPanel:t,_handleBack:s,headingLevel:a,messages:i,messagesCommon:o,_snappingControls:n,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 E(t,{active:this.isPanelActive(e),key:"feature-creation-panel",heading:i.placeFeature,headingLevel:a,handleBack:s,messages:i,messagesCommon:o,sketchViewModel:l,snappingControls:n},E("div",{class:L},this.renderMessage(h)))}renderFooterActions(e){return e.map((({type:e,disabled:t,class:s,...a},i)=>this.renderButton({class:this.classes(j.controlButton,"secondary"===e?j.buttonSecondary:"tertiary"===e?j.buttonTertiary:null,t?j.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,o=E("calcite-button",{appearance:"solid",color:"danger"===s?"red":"blue",width:i?"half":"full",onclick:a.primary.action,key:"prompt-primary-button",afterCreate:U},a.primary.label),n=i?E("calcite-button",{appearance:"clear",color:"danger"===s?"red":"blue",width:"half",onclick:a.secondary.action,key:"prompt-secondary-button"},a.secondary.label):null;return E("div",{class:`${j.promptContainer}--${s}`},E("div",{class:j.promptHeader},E("calcite-icon",{icon:"exclamation-mark-triangle"}),E(M,{class:j.promptHeading,level:this.headingLevel},e)),E("div",{class:j.promptMessage},t),E("div",{class:j.promptDivider}),E("div",{class:j.promptActions},n,o))}renderProgressBar(){return E("div",{class:this.classes(j.progressBar),key:"progress-bar"})}renderButton(e){const{disabled:t,class:s,key:a,clickHandler:i,label:o,...n}=e;return E("calcite-button",{class:s,disabled:t,key:a,onclick:i,type:"button",...n},o)}renderLanding(e){const{EditorPanel:t,headingLevel:s,messages:a,messagesCommon:i,_snappingControls:o,viewModel:{sketchViewModel:n}}=this;return E(t,{active:this.isPanelActive(e),key:"landing-panel",heading:a.widgetLabel,headingLevel:s,showBackButton:!1,messages:a,messagesCommon:i,sketchViewModel:n,snappingControls:o},E("div",{class:L},E("div",{key:"edit-actions",class:j.panelContentSection},this.renderUpdateActions()),E("div",{key:"create-actions",class:j.panelContentSection},this.renderCreateActions())))}renderUpdateActions(){const{messages:e,messagesCommon:t}=this;return E("div",null,E(M,{level:A(this.headingLevel)},e.editFeatures),E("div",{class:j.updateFeaturesActionButtons},E("calcite-action",{text:t.select,textEnabled:!0,icon:"cursor",alignment:"start",class:j.updateFeaturesActionButtonsButton,onclick:this._handleEdit})))}renderCreateActions(){const{_featureTemplates:e,headingLevel:t,messages:s}=this;if(0!==e.viewModel.numberOfFeatureTemplates)return E("div",null,E(M,{level:A(t)},s.createFeatures),E("div",{key:"templates",class:j.featureTemplatesContainer},e.render()))}renderFeatureList(e){const{EditorPanel:t,_handleBack:s,headingLevel:a,messages:i,messagesCommon:o,messagesTemplates:n,_snappingControls:r,viewModel:{editableItems:l,sketchViewModel:d}}=this,c=this._assertActiveUpdateWorkflow().data.candidates,p=P(i.multipleFeaturesTemplate,{total:c.length}),h=new Map;let m=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,o=this.viewModel.editableItems.find((e=>e.layer===s.layer));return o.supports.includes("update")&&(!a||t.toLowerCase().includes(a)||i.toLowerCase().includes(a))})).forEach((e=>{m++;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 u=l.filter((({layer:e})=>h.has(e))).map((({layer:e})=>h.get(e))).toArray(),g=m>10||this._filterText.length>0;return E(t,{active:this.isPanelActive(e),key:"feature-list",heading:p,headingLevel:a,handleBack:s,messages:i,messagesCommon:o,sketchViewModel:d,snappingControls:r},E("div",{class:L},C({id:this.id,enableListScroll:!1,filterEnabled:g,filterText:this._filterText,items:u,messages:{filterPlaceholder:n.filterPlaceholder,noItems:n.noItems,noMatches:n.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:o,key:n,messages:r,messagesCommon:l,showBackButton:d,sketchViewModel:c,snappingControls:p}=e;return E("calcite-panel",{bind:this,key:n,heading:i,headingLevel:o,showBackButton:d??!0,beforeBack:a??null,onCalcitePanelScroll:this._onSnappingPopoverPanelScroll},E("div",{class:j.panelToolbar},E("calcite-popover",{autoClose:s,afterCreate:this._afterSnappingPopoverCreated,afterUpdate:this._afterSnappingPopoverUpdated,bind:this,label:r.snappingSettings,heading:r.snappingSettings,"reference-element":`${n}__snappingButton`,"overlay-positioning":"fixed",placement:"bottom"},E("div",{class:j.snappingControlsPopover},p.render())),E("calcite-button",{id:`${n}__snappingButton`,text:r.snapping,appearance:"transparent",color:"neutral",alignment:"icon-end-space-between","icon-start":"vertex-gps","icon-end":"caret-down",width:"full",class:j.panelToolbarSnappingButton},r.snapping),this.visibleElements.undoRedoButtons?[E("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)}),E("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)}_onSnappingPopoverPanelScroll(){this._snappingPopover?.open&&this._snappingPopover.toggle()}_afterSnappingPopoverCreated(e){this._snappingPopover=e}_afterSnappingPopoverUpdated(e){this._snappingPopover=e}_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",[o]=a[i];return"polygon"===e&&o<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=h(t);return i&&a[i]&&`${a[i]}`||P(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;e.addAttachment().then((()=>t.previous()))}_handleAttachmentUpdate(){const{_attachments:e}=this,{activeWorkflow:t}=this.viewModel;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;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(){const{messages:e}=this,t=this.activeWorkflow,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{type:a}=t,i="create"===a?e.cancelAddWarningMessage:e.cancelEditWarningMessage,o="create"===a?e.cancelAddTitle:e.cancelEditTitle,n="create"===a?e.continueAdding:e.continueEditing,r="create"===a?e.discardFeature:e.discardEdits;throw this._prompt={title:o,message:i,context:"danger",actions:{primary:{label:r,action:()=>{s(),this._prompt=null}},secondary:{label:n,action:()=>this._prompt=null}}},this.scheduleRender(),new Error}s()}_assertActiveCreateWorkflow(){const{type:e}=this.viewModel.activeWorkflow;if("create"===e||"create-features"===e)return this.viewModel.activeWorkflow;throw Error("Expected activeWorkflow to be instance of CreateWorkflow or CreateFeaturesWorkflow")}_assertActiveUpdateWorkflow(){if("update"===this.viewModel.activeWorkflow.type)return this.viewModel.activeWorkflow;throw Error("Expected activeWorkflow to be an UpdateWorkflow")}};e([c()],I.prototype,"_attachments",void 0),e([l("viewModel.activeWorkflow")],I.prototype,"activeWorkflow",void 0),e([l("viewModel.allowedWorkflows")],I.prototype,"allowedWorkflows",void 0),e([c()],I.prototype,"useDeprecatedCreateWorkflow",void 0),e([c()],I.prototype,"headingLevel",void 0),e([c()],I.prototype,"iconClass",void 0),e([c({aliasOf:{source:"messages.widgetLabel",overridable:!0}})],I.prototype,"label",void 0),e([l("viewModel.labelOptions")],I.prototype,"labelOptions",void 0),e([l("viewModel.layerInfos")],I.prototype,"layerInfos",void 0),e([c(),T("esri/widgets/Editor/t9n/Editor")],I.prototype,"messages",void 0),e([c(),T("esri/t9n/common")],I.prototype,"messagesCommon",void 0),e([c(),T("esri/widgets/FeatureTemplates/t9n/FeatureTemplates")],I.prototype,"messagesTemplates",void 0),e([l("viewModel.snappingOptions")],I.prototype,"snappingOptions",void 0),e([l("viewModel.tooltipOptions")],I.prototype,"tooltipOptions",void 0),e([c()],I.prototype,"supportingWidgetDefaults",void 0),e([l("viewModel.view")],I.prototype,"view",void 0),e([c(),S(["workflow-cancel","workflow-commit"])],I.prototype,"viewModel",void 0),e([c()],I.prototype,"visibleElements",void 0),e([d("visibleElements")],I.prototype,"castVisibleElements",null),e([W()],I.prototype,"_handleDelete",null),e([W()],I.prototype,"_handleAttachmentAdd",null),e([W()],I.prototype,"_handleAttachmentUpdate",null),e([W()],I.prototype,"_handleAttachmentDelete",null),e([W()],I.prototype,"_handleAdd",null),e([W()],I.prototype,"_handleEdit",null),e([W()],I.prototype,"_handleDone",null),I=e([p(V)],I);const O=I;export{O 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.24/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../Graphic.js";import"../../intl.js";import i from"../../core/Evented.js";import{HandleOwnerMixin as n}from"../../core/HandleOwner.js";import{makeHandle as s}from"../../core/handleUtils.js";import o from"../../core/Logger.js";import{destroyMaybe as r,isNone as a,isSome as l}from"../../core/maybe.js";import{EsriPromiseMixin as u}from"../../core/Promise.js";import{watch as c}from"../../core/reactiveUtils.js";import{property as p}from"../../core/accessorSupport/decorators/property.js";import"../../core/arrayUtils.js";import"../../core/has.js";import"../../core/accessorSupport/ensureType.js";import{subclass as d}from"../../core/accessorSupport/decorators/subclass.js";import h from"../../form/FormTemplate.js";import f from"../../layers/support/ContingentValue.js";import m from"../../layers/support/LayerContingentValuesCache.js";import{loadArcade as g}from"../../support/arcadeOnDemand.js";import y from"./InputField.js";import _ from"./InputFieldGroup.js";import{onLocaleChange as F}from"../../intl/locale.js";import{fetchMessageBundle as C}from"../../intl/messages.js";const v=new t({attributes:{}}),b="esri.widgets.FeatureForm.FeatureFormViewModel",E=o.getLogger(b),V=["editable","required","value","visibility"],x="#JSAPI_CONTINGENT_VALUE_EMPTY_HASH",j="#JSAPI_CONTINGENT_VALUE_ANY_HASH",w="#JSAPI_CONTINGENT_VALUE_NULL_HASH";let I=class extends(n(u(i.EventedAccessor))){constructor(e){super(e),this._arcade=null,this._compiledExpressionLookup=new Map,this._expressionLookup=new Map,this._expressionInvalidationCallbacks=new Set,this._contingentValuesCache=null,this._featureClone=v.clone(),this._initialFeature=v.clone(),this._arcadeGeometryOperationsEnabled=!1,this._inputFieldCache=[],this.contingencyConstraintViolations=new Map,this.messages=null,this.strict=!1}initialize(){const e=async()=>this.messages=await C("esri/widgets/FeatureForm/t9n/FeatureForm");e();const t=c((()=>this.layer),(e=>{"feature"===e?.type&&this.addResolvingPromise(m.createLoadedLayerContingentValuesCache(e).then((e=>{this._contingentValuesCache=e,this.notifyChange("fieldsWithContingentValues")})))}),{initial:!0});this.handles.add([F(e),t])}destroy(){this.feature=null,this.layer=null,this._contingentValuesCache=r(this._contingentValuesCache)}get allInputFields(){return this.inputFields.reduce(((e,t)=>T(t)?[...e,...t.inputFields]:[...e,t]),[])}get _layerFieldsByName(){return new Map(this.layer.fields.map((e=>[e.name,e])))}get feature(){return this._get("feature")}set feature(e){this._featureClone=e?e.clone():v.clone(),this._initialFeature=this._featureClone.clone(),this.contingencyConstraintViolations.clear(),this._clearInputFieldCache(),this._set("feature",e)}get fieldsWithContingentValues(){if(a(this._contingentValuesCache))return new Set;const e=this._contingentValuesCache.fieldGroups.flatMap((e=>e.fields));return new Set(e)}get formTemplate(){return this.layer&&"formTemplate"in this.layer?this.layer.formTemplate:null}set formTemplate(e){null!=e?this._override("formTemplate",e):this._clearOverride("formTemplate")}get inputFields(){const{_arcade:e,_featureClone:t,_initialFeature:i,_inputFieldCache:n,formTemplate:s,messages:o,layer:r,state:a,spatialReference:u}=this;if("ready"!==a)return[];const c={arcade:e,feature:t,initialFeature:i,layer:r,messages:o,expressionTrackingProvider:{registerExpression:this._registerExpression.bind(this)},spatialReference:u},p=l(s)&&s.elements.length>0?this._updateInputFieldsFromElements(n,s.elements,c):this._updateInputFieldsFromLayerFields(n,r?.fields,c);return this._inputFieldCache=p,p}get joinedContingentValues(){return this._joinContingentValues()}get layer(){return this.feature?.sourceLayer&&"applyEdits"in this.feature.sourceLayer?this.feature.sourceLayer:null}set layer(e){e?this._override("layer",e):this._clearOverride("layer")}get spatialReference(){return this.layer?.spatialReference||null}set spatialReference(e){void 0===e?this._clearOverride("spatialReference"):this._override("spatialReference",e)}get state(){return this.messages&&this.get("layer.loaded")?"ready":"disabled"}get submittable(){return!!this.valid||this.allInputFields.filter((e=>!e.valid)).every((({submittable:e})=>e))}get valid(){const e=this.allInputFields;return e.length>0&&e.every((({valid:e})=>e))}findField(e){return this.allInputFields.find((t=>t.name===e))}getValue(e){const{_featureClone:t,layer:i}=this,n=!!i?.getField(e);return t.getAttribute(e)??(n?null:void 0)}setValue(e,t){const{_featureClone:i,strict:n}=this,s=this.findField(e);t=""===t?null:t,s&&i.getAttribute(e)!==t&&(s.value=t,n&&!s.valid||this._afterValueChange(s))}getValues(){return{...this._featureClone.attributes}}submit(){const e=this.allInputFields,t=new Set(e.filter((e=>e.valid)).map((({name:e})=>e))),i=e.filter((e=>!e.valid)).map((({name:e})=>e)),n=this.getValues();if(this.validateContingencyConstraints(n,{includeIncompleteViolations:!0}).length>0)for(const[s,o]of this.contingencyConstraintViolations.entries())"error"===o.type&&(t.delete(s),i.push(s));this.emit("submit",{valid:[...t],invalid:i,values:n})}validateContingencyConstraints(e,t){const{_contingentValuesCache:i}=this,n=new Map;if(this.contingencyConstraintViolations=n,a(i))return[];const{invalid:s,incomplete:o}=i.validateContingencyConstraints(e),r=[...s,...t?.includeIncompleteViolations?o:[]];for(const a of r)for(const e of a.fieldGroup.fields)n.set(e,a);return r}_emitChangeEvent({name:e,valid:t,value:i}){this.emit("value-change",{layer:this.layer,feature:this.feature,fieldName:e,value:i,valid:t})}_updateInputFieldsFromElements(e,t,i){const n=new Map;for(const o of e)if(T(o)){A(n,o.groupElement,o);for(const e of o.inputFields)A(n,e.fieldElement,e)}else A(n,o.fieldElement,o);const s=this._updateInputFieldsRecursive(n,t.filter(this._isSupportedElement),i);for(const[o,r]of n.entries())n.delete(o),r.destroy();return s}_updateInputFieldsRecursive(e,t,i,n=null){const s=[];for(const o of t){const t=e.has(o),r=t?e.get(o):k(o)?this._makeInputFieldGroupFromGroupElement(o,i):this._makeInputFieldFromFieldElement(o,i,n);if(s.push(r),t)if(e.delete(o),T(r)){const{arcade:e,feature:t,expressionTrackingProvider:n,spatialReference:s}=i;r.set({arcade:e,feature:t,expressionTrackingProvider:n,spatialReference:s})}else r.set(i);if(k(o)){const t=o.elements.filter((e=>this._isSupportedElement(e)));r.inputFields=this._updateInputFieldsRecursive(e,t,i,r)}}return s}_updateInputFieldsFromLayerFields(e,t,i){if(!Array.isArray(t))return E.warn(b,"No attribute fields found."),[];const n=new Map;for(const c of e)if(T(c)){for(const e of c.inputFields)e.destroy();c.inputFields.length=0,c.destroy()}else n.set(c.field,c);const s=[],{feature:o,initialFeature:r,layer:a,messages:l,spatialReference:u}=i;for(const c of t){const e=n.get(c)??new y({field:c,feature:o,initialFeature:r,layer:a,messages:l,spatialReference:u,value:o.getAttribute(c.name)});e.set({fieldElement:null,requiredFunction:null,visibilityFunction:null,valueFunction:null,editableFunction:null}),s.push(e),n.delete(c)}for(const[c,p]of n.entries())n.delete(c),p.destroy();return s}_makeInputFieldFromFieldElement(e,t,i=null){const{arcade:n,expressionTrackingProvider:o,feature:r,initialFeature:a,layer:u,messages:p,spatialReference:d}=t,h=new y({fieldElement:e,field:this._layerFieldsByName.get(e.fieldName),requiredFunction:this._getCompiledExpression(e.requiredExpression),visibilityFunction:this._getCompiledExpression(e.visibilityExpression),valueFunction:this._getCompiledExpression(e.valueExpression),editableFunction:this._getCompiledExpression(e.editableExpression),group:i,arcade:n,expressionTrackingProvider:o,feature:r,initialFeature:a,layer:u,messages:p,spatialReference:d,value:r.getAttribute(e.fieldName)}),f=`watch-expression-field-${h.id}`,m=c((()=>h.fieldElement),(e=>{this.handles.remove(f),l(e)&&this.handles.add(V.map((t=>c((()=>e[`${t}Expression`]),(async e=>{e&&""!==e&&(h[`${t}Function`]=await this._getOrMakeCompiledExpression(e),h.arcade=this._arcade)}),{initial:!0,sync:!0}))),f)}),{initial:!0,sync:!0}),g=s((()=>this.handles.remove(f))),_=c((()=>h.value),(()=>this._afterValueChange(h)));return h.own([m,g,_]),h}_makeInputFieldGroupFromGroupElement(e,t){const{arcade:i,feature:n,expressionTrackingProvider:s,spatialReference:o}=t,r=new _({groupElement:e,visibilityFunction:this._getCompiledExpression(e.visibilityExpression),inputFields:[],arcade:i,feature:n,expressionTrackingProvider:s,spatialReference:o});return r.own(c((()=>r.groupElement),(e=>l(e)&&e.own(c((()=>e.visibilityExpression),(async e=>{e&&""!==e&&(r.visibilityFunction=await this._getOrMakeCompiledExpression(e),r.arcade=this._arcade)}),{initial:!0}))),{initial:!0})),r}_clearInputFieldCache(){for(const e of this._inputFieldCache)e.destroy();this._inputFieldCache=[]}_afterValueChange(e){const{name:t,value:i}=e;if(this.get("layer.typeIdField")===t&&"types"in this.layer){const e=new Set;this.layer.types.forEach((t=>Object.keys(t.domains).forEach((t=>e.add(t))))),e.forEach((e=>{const t=this.findField(e);t&&t.notifyChange("domain")}))}this._featureClone.setAttribute(t,i);for(const n of this._expressionInvalidationCallbacks)n();this._emitChangeEvent(e)}_registerExpression(e){const{_expressionInvalidationCallbacks:t}=this;return t.add(e),s((()=>t.delete(e)))}_getCompiledExpression(e){return this._compiledExpressionLookup.get(this._expressionLookup.get(e))}async _getOrMakeCompiledExpression(e){{if(a(e)||""===e)return null;const t=this._expressionLookup.get(e)??this._addToExpressionLookup(e);if(this._compiledExpressionLookup.has(t))return this._compiledExpressionLookup.get(t);this._arcade||(this._arcade=await g());const i=this._arcade.arcadeUtils;return!this._arcadeGeometryOperationsEnabled&&i.hasGeometryOperations(t)&&(await i.enableGeometryOperations(),this._arcadeGeometryOperationsEnabled=!0),this._addToCompiledExpressionLookup(t)}}_addToCompiledExpressionLookup(e){const{_arcade:{arcadeUtils:t},_compiledExpressionLookup:i}=this,n=t.createFunction(e);return i.set(e,n),n}_addToExpressionLookup(e){const{_expressionLookup:t,formTemplate:i}=this,n=(l(i)&&l(i.expressionInfos)?Object.values(i.expressionInfos).find((t=>t.name===e)):null)?.expression??e;return t.set(e,n),e!==n&&t.set(n,n),n}_isSupportedElement(e){return"field"===e.type||"group"===e.type||(E.warn("form-info::unsupported-element-type","Only element types 'field' and 'group' are supported",`Element ${e.label} has unsupported type '${e.type}'`),!1)}_joinContingentValues(){const e=this._contingentValuesCache;if(a(e))return[];const t="typeIdField"in this.layer?this.layer.typeIdField:null,i=t?this.getValue(t):null,n=[];for(const r of e.fieldGroups){const{contingencies:e,fields:t,name:s}=r,o=[];for(const n of e)n.isRetired||l(n.subtype)&&n.subtype.code!==i||o.push({values:n.values});o.length>0&&n.push({name:s,fields:t,contingencies:o})}const[s,o]=this._generateJoinPlan(n);return[...s.flatMap((e=>this._joinFieldGroupContingencies(e))),...o.flatMap((e=>e.contingencies))]}_generateJoinPlan(e){const t=new Map,i=[],n=new Set;for(const l of e)for(const e of l.fields)if(t.has(e)){const s=t.get(e),o=l,r=[s.name,o.name].sort().join("|");if(n.has(r))continue;i.push([s,o]),n.add(r),t.set(e,o)}else t.set(e,l);const s=new Set(i.flat()),o=new Set(e);for(const l of s)o.delete(l);const r=new Map,a=new Map;for(const l of new Set(i.flat())){const e=Symbol(l.name);r.set(e,new Set([l])),a.set(l,e)}for(const[l,u]of i){const e=a.get(l),t=a.get(u);if(e===t)continue;const i=r.get(e),n=r.get(t);for(const s of n)i.add(s),a.set(s,e);r.delete(t)}return[[...r.values()].map((e=>[...e])),[...o]]}_joinFieldGroupContingencies(e){const t=e.slice(),i=t.shift();let n=t.shift(),s=this._generateJoinKey(i.fields,n.fields),o=new Set([...i.fields,...n.fields]),r=new Map;for(const a of i.contingencies){const[e]=this._hashContingency(a,s.codedValueFields,!0);r.has(e)?r.get(e).push(a):r.set(e,[a])}for(;t.length>0;){const e=new Map,i=t.shift(),l=this._generateJoinKey(o,i.fields);for(const t of n.contingencies){const[i,n]=this._hashContingency(t,s.codedValueFields),o=n?this._findMatchingContingenciesWithAnyHashMask(r,i):r.get(i);if(r.has(j)&&o.push(...this._findMatchingContingenciesContainingAny(t,r.get(j),s.codedValueFields)),!a(o))for(const r of o){const i=s.rangeFields.length>0?this._joinContingenciesWithRangeDomains(r,t,s.rangeFields):this._joinContingencies(r,t);if(a(i))break;const[n]=this._hashContingency(i,l.codedValueFields,!0);e.has(n)?e.get(n).push(i):e.set(n,[i])}}r=e,n=i,s=l,o=new Set([...o,...n.fields])}const u=[];for(const c of n.contingencies){const[e,t]=this._hashContingency(c,s.codedValueFields),i=t?this._findMatchingContingenciesWithAnyHashMask(r,e):r.get(e);if(r.has(j)&&i.push(...this._findMatchingContingenciesContainingAny(c,r.get(j),s.codedValueFields)),!a(i))for(const n of i){const e=s.rangeFields.length>0?this._joinContingenciesWithRangeDomains(n,c,s.rangeFields):this._joinContingencies(n,c);l(e)&&u.push(e)}}return u}_joinContingencies(e,t){const i={values:{...e.values,...t.values}};for(const[n,s]of Object.entries(i.values))"any"===s.objectType&&l(e.values[n])&&(i.values[n]=e.values[n]);return i}_joinContingenciesWithRangeDomains(e,t,i){const n=this._joinContingencies(e,t);for(const s of i){const i=e.values[s],o=t.values[s],{leftIsNull:r,rightIsNull:a,bothAreNull:l,leftIsAny:u,rightIsAny:c,bothAreAny:p,leftIsRange:d,rightIsRange:h}=this._compareObjectTypes(i.objectType,o.objectType);if(l||p)continue;if(r&&c||a&&u){n.values[s]=new f({objectType:"null"});continue}if(r&&h||a&&d)return null;u?(i.minValue=-1/0,i.maxValue=1/0):c&&(o.minValue=-1/0,o.maxValue=1/0);const m=Math.max(i.minValue,o.minValue),g=Math.min(i.maxValue,o.maxValue);if(m>g)return null;n.values[s]=new f({objectType:"range",minValue:m,maxValue:g})}return n}_findMatchingContingenciesContainingAny(e,t,i){return t.filter((t=>i.every((i=>{const n=t.values[i],s=e.values[i];return"any"===n.objectType||"any"===s.objectType||n.codedValue?.code===s.codedValue?.code}))))}_findMatchingContingenciesWithAnyHashMask(e,t){const i=RegExp(`${t}$`),n=[];for(const[s,o]of e){if(s===j)break;i.test(s)&&n.push(...o)}return n}_generateJoinKey(e,t){const i=Array.isArray(e)?new Set(e):e,n=Array.isArray(t)?new Set(t):t,s=i.size<n.size?i:n,o=s===i?n:i,r=new Set,l=new Set;for(const u of s)if(o.has(u)){const e=this.layer.getFieldDomain(u,{feature:this.feature});if(a(e))continue;switch(e.type){case"coded-value":r.add(u);break;case"range":l.add(u)}}return{codedValueFields:[...r],rangeFields:[...l]}}_hashContingency(e,t,i=!1){if(t.length<1)return[x,!1];const n=[];let s=!1;for(const o of t){const t=e.values[o];if("any"===t.objectType){if(i)return[j,!0];s=!0,n.push(`${o}:.*`)}else"null"===t.objectType?n.push(`${o}:${w}`):n.push(`${o}:${t.codedValue?.code}`)}return[n.sort().join("&"),s]}_compareObjectTypes(e,t){return{leftIsNull:"null"===e,rightIsNull:"null"===t,bothAreNull:"null"===e&&"null"===t,leftIsAny:"any"===e,rightIsAny:"any"===t,bothAreAny:"any"===e&&"any"===t,leftIsRange:"range"===e,rightIsRange:"range"===t}}};e([p({readOnly:!0})],I.prototype,"allInputFields",null),e([p()],I.prototype,"_layerFieldsByName",null),e([p()],I.prototype,"_inputFieldCache",void 0),e([p()],I.prototype,"contingencyConstraintViolations",void 0),e([p()],I.prototype,"feature",null),e([p()],I.prototype,"fieldsWithContingentValues",null),e([p({type:h})],I.prototype,"formTemplate",null),e([p({readOnly:!0})],I.prototype,"inputFields",null),e([p()],I.prototype,"joinedContingentValues",null),e([p()],I.prototype,"layer",null),e([p()],I.prototype,"messages",void 0),e([p()],I.prototype,"spatialReference",null),e([p()],I.prototype,"state",null),e([p()],I.prototype,"strict",void 0),e([p()],I.prototype,"submittable",null),e([p()],I.prototype,"valid",null),e([p()],I.prototype,"getValues",null),e([p()],I.prototype,"submit",null),I=e([d(b)],I);const T=e=>!!e.inputFields,k=e=>"group"===e.type,A=(e,t,i)=>{l(t)&&e.set(t,i)},M=I;export{M as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../Graphic.js";import"../../intl.js";import i from"../../core/Evented.js";import{HandleOwnerMixin as n}from"../../core/HandleOwner.js";import{makeHandle as s}from"../../core/handleUtils.js";import o from"../../core/Logger.js";import{destroyMaybe as r,isNone as a,isSome as l}from"../../core/maybe.js";import{EsriPromiseMixin as u}from"../../core/Promise.js";import{watch as c}from"../../core/reactiveUtils.js";import{property as p}from"../../core/accessorSupport/decorators/property.js";import"../../core/arrayUtils.js";import"../../core/has.js";import"../../core/accessorSupport/ensureType.js";import{subclass as d}from"../../core/accessorSupport/decorators/subclass.js";import h from"../../form/FormTemplate.js";import f from"../../layers/support/ContingentValue.js";import m from"../../layers/support/LayerContingentValuesCache.js";import{loadArcade as g}from"../../support/arcadeOnDemand.js";import y from"./InputField.js";import _ from"./InputFieldGroup.js";import{onLocaleChange as F}from"../../intl/locale.js";import{fetchMessageBundle as C}from"../../intl/messages.js";const v=new t({attributes:{}}),b="esri.widgets.FeatureForm.FeatureFormViewModel",E=o.getLogger(b),V=["editable","required","value","visibility"],x="#JSAPI_CONTINGENT_VALUE_EMPTY_HASH",j="#JSAPI_CONTINGENT_VALUE_ANY_HASH",w="#JSAPI_CONTINGENT_VALUE_NULL_HASH";let I=class extends(n(u(i.EventedAccessor))){constructor(e){super(e),this._arcade=null,this._compiledExpressionLookup=new Map,this._expressionLookup=new Map,this._expressionInvalidationCallbacks=new Set,this._contingentValuesCache=null,this._featureClone=v.clone(),this._initialFeature=v.clone(),this._arcadeGeometryOperationsEnabled=!1,this._inputFieldCache=[],this.contingencyConstraintViolations=new Map,this.messages=null,this.strict=!1}initialize(){const e=async()=>this.messages=await C("esri/widgets/FeatureForm/t9n/FeatureForm");e();const t=c((()=>this.layer),(e=>{"feature"===e?.type&&this.addResolvingPromise(m.createLoadedLayerContingentValuesCache(e).then((e=>{this._contingentValuesCache=e,this.notifyChange("fieldsWithContingentValues")})))}),{initial:!0}),i=c((()=>this.feature?.geometry),(e=>{this._featureClone.geometry=e;for(const t of this._expressionInvalidationCallbacks)t()}));this.handles.add([F(e),t,i])}destroy(){this.feature=null,this.layer=null,this._contingentValuesCache=r(this._contingentValuesCache)}get allInputFields(){return this.inputFields.reduce(((e,t)=>T(t)?[...e,...t.inputFields]:[...e,t]),[])}get _layerFieldsByName(){return new Map(this.layer.fields.map((e=>[e.name,e])))}get feature(){return this._get("feature")}set feature(e){this._featureClone=e?e.clone():v.clone(),this._initialFeature=this._featureClone.clone(),this.contingencyConstraintViolations.clear(),this._clearInputFieldCache(),this._set("feature",e)}get fieldsWithContingentValues(){if(a(this._contingentValuesCache))return new Set;const e=this._contingentValuesCache.fieldGroups.flatMap((e=>e.fields));return new Set(e)}get formTemplate(){return this.layer&&"formTemplate"in this.layer?this.layer.formTemplate:null}set formTemplate(e){null!=e?this._override("formTemplate",e):this._clearOverride("formTemplate")}get inputFields(){const{_arcade:e,_featureClone:t,_initialFeature:i,_inputFieldCache:n,formTemplate:s,messages:o,layer:r,state:a,spatialReference:u}=this;if("ready"!==a)return[];const c={arcade:e,feature:t,initialFeature:i,layer:r,messages:o,expressionTrackingProvider:{registerExpression:this._registerExpression.bind(this)},spatialReference:u},p=l(s)&&s.elements.length>0?this._updateInputFieldsFromElements(n,s.elements,c):this._updateInputFieldsFromLayerFields(n,r?.fields,c);return this._inputFieldCache=p,p}get joinedContingentValues(){return this._joinContingentValues()}get layer(){return this.feature?.sourceLayer&&"applyEdits"in this.feature.sourceLayer?this.feature.sourceLayer:null}set layer(e){e?this._override("layer",e):this._clearOverride("layer")}get spatialReference(){return this.layer?.spatialReference||null}set spatialReference(e){void 0===e?this._clearOverride("spatialReference"):this._override("spatialReference",e)}get state(){return this.messages&&this.get("layer.loaded")?"ready":"disabled"}get submittable(){return!!this.valid||this.allInputFields.filter((e=>!e.valid)).every((({submittable:e})=>e))}get valid(){const e=this.allInputFields;return e.length>0&&e.every((({valid:e})=>e))}findField(e){return this.allInputFields.find((t=>t.name===e))}getValue(e){const{_featureClone:t,layer:i}=this,n=!!i?.getField(e);return t.getAttribute(e)??(n?null:void 0)}setValue(e,t){const{_featureClone:i,strict:n}=this,s=this.findField(e);t=""===t?null:t,s&&i.getAttribute(e)!==t&&(s.value=t,n&&!s.valid||this._afterValueChange(s))}getValues(){return{...this._featureClone.attributes}}submit(){const e=this.allInputFields,t=new Set(e.filter((e=>e.valid)).map((({name:e})=>e))),i=e.filter((e=>!e.valid)).map((({name:e})=>e)),n=this.getValues();if(this.validateContingencyConstraints(n,{includeIncompleteViolations:!0}).length>0)for(const[s,o]of this.contingencyConstraintViolations.entries())"error"===o.type&&(t.delete(s),i.push(s));this.emit("submit",{valid:[...t],invalid:i,values:n})}validateContingencyConstraints(e,t){const{_contingentValuesCache:i}=this,n=new Map;if(this.contingencyConstraintViolations=n,a(i))return[];const{invalid:s,incomplete:o}=i.validateContingencyConstraints(e),r=[...s,...t?.includeIncompleteViolations?o:[]];for(const a of r)for(const e of a.fieldGroup.fields)n.set(e,a);return r}_emitChangeEvent({name:e,valid:t,value:i}){this.emit("value-change",{layer:this.layer,feature:this.feature,fieldName:e,value:i,valid:t})}_updateInputFieldsFromElements(e,t,i){const n=new Map;for(const o of e)if(T(o)){A(n,o.groupElement,o);for(const e of o.inputFields)A(n,e.fieldElement,e)}else A(n,o.fieldElement,o);const s=this._updateInputFieldsRecursive(n,t.filter(this._isSupportedElement),i);for(const[o,r]of n.entries())n.delete(o),r.destroy();return s}_updateInputFieldsRecursive(e,t,i,n=null){const s=[];for(const o of t){const t=e.has(o),r=t?e.get(o):k(o)?this._makeInputFieldGroupFromGroupElement(o,i):this._makeInputFieldFromFieldElement(o,i,n);if(s.push(r),t)if(e.delete(o),T(r)){const{arcade:e,feature:t,expressionTrackingProvider:n,spatialReference:s}=i;r.set({arcade:e,feature:t,expressionTrackingProvider:n,spatialReference:s})}else r.set(i);if(k(o)){const t=o.elements.filter((e=>this._isSupportedElement(e)));r.inputFields=this._updateInputFieldsRecursive(e,t,i,r)}}return s}_updateInputFieldsFromLayerFields(e,t,i){if(!Array.isArray(t))return E.warn(b,"No attribute fields found."),[];const n=new Map;for(const c of e)if(T(c)){for(const e of c.inputFields)e.destroy();c.inputFields.length=0,c.destroy()}else n.set(c.field,c);const s=[],{feature:o,initialFeature:r,layer:a,messages:l,spatialReference:u}=i;for(const c of t){const e=n.get(c)??new y({field:c,feature:o,initialFeature:r,layer:a,messages:l,spatialReference:u,value:o.getAttribute(c.name)});e.set({fieldElement:null,requiredFunction:null,visibilityFunction:null,valueFunction:null,editableFunction:null}),s.push(e),n.delete(c)}for(const[c,p]of n.entries())n.delete(c),p.destroy();return s}_makeInputFieldFromFieldElement(e,t,i=null){const{arcade:n,expressionTrackingProvider:o,feature:r,initialFeature:a,layer:u,messages:p,spatialReference:d}=t,h=new y({fieldElement:e,field:this._layerFieldsByName.get(e.fieldName),requiredFunction:this._getCompiledExpression(e.requiredExpression),visibilityFunction:this._getCompiledExpression(e.visibilityExpression),valueFunction:this._getCompiledExpression(e.valueExpression),editableFunction:this._getCompiledExpression(e.editableExpression),group:i,arcade:n,expressionTrackingProvider:o,feature:r,initialFeature:a,layer:u,messages:p,spatialReference:d,value:r.getAttribute(e.fieldName)}),f=`watch-expression-field-${h.id}`,m=c((()=>h.fieldElement),(e=>{this.handles.remove(f),l(e)&&this.handles.add(V.map((t=>c((()=>e[`${t}Expression`]),(async e=>{e&&""!==e&&(h[`${t}Function`]=await this._getOrMakeCompiledExpression(e),h.arcade=this._arcade)}),{initial:!0,sync:!0}))),f)}),{initial:!0,sync:!0}),g=s((()=>this.handles.remove(f))),_=c((()=>h.value),(()=>this._afterValueChange(h)));return h.own([m,g,_]),h}_makeInputFieldGroupFromGroupElement(e,t){const{arcade:i,feature:n,expressionTrackingProvider:s,spatialReference:o}=t,r=new _({groupElement:e,visibilityFunction:this._getCompiledExpression(e.visibilityExpression),inputFields:[],arcade:i,feature:n,expressionTrackingProvider:s,spatialReference:o});return r.own(c((()=>r.groupElement),(e=>l(e)&&e.own(c((()=>e.visibilityExpression),(async e=>{e&&""!==e&&(r.visibilityFunction=await this._getOrMakeCompiledExpression(e),r.arcade=this._arcade)}),{initial:!0}))),{initial:!0})),r}_clearInputFieldCache(){for(const e of this._inputFieldCache)e.destroy();this._inputFieldCache=[]}_afterValueChange(e){const{name:t,value:i}=e;if(this.get("layer.typeIdField")===t&&"types"in this.layer){const e=new Set;this.layer.types.forEach((t=>Object.keys(t.domains).forEach((t=>e.add(t))))),e.forEach((e=>{const t=this.findField(e);t&&t.notifyChange("domain")}))}this._featureClone.setAttribute(t,i);for(const n of this._expressionInvalidationCallbacks)n();this._emitChangeEvent(e)}_registerExpression(e){const{_expressionInvalidationCallbacks:t}=this;return t.add(e),s((()=>t.delete(e)))}_getCompiledExpression(e){return this._compiledExpressionLookup.get(this._expressionLookup.get(e))}async _getOrMakeCompiledExpression(e){{if(a(e)||""===e)return null;const t=this._expressionLookup.get(e)??this._addToExpressionLookup(e);if(this._compiledExpressionLookup.has(t))return this._compiledExpressionLookup.get(t);this._arcade||(this._arcade=await g());const i=this._arcade.arcadeUtils;return!this._arcadeGeometryOperationsEnabled&&i.hasGeometryOperations(t)&&(await i.enableGeometryOperations(),this._arcadeGeometryOperationsEnabled=!0),this._addToCompiledExpressionLookup(t)}}_addToCompiledExpressionLookup(e){const{_arcade:{arcadeUtils:t},_compiledExpressionLookup:i}=this,n=t.createFunction(e);return i.set(e,n),n}_addToExpressionLookup(e){const{_expressionLookup:t,formTemplate:i}=this,n=(l(i)&&l(i.expressionInfos)?Object.values(i.expressionInfos).find((t=>t.name===e)):null)?.expression??e;return t.set(e,n),e!==n&&t.set(n,n),n}_isSupportedElement(e){return"field"===e.type||"group"===e.type||(E.warn("form-info::unsupported-element-type","Only element types 'field' and 'group' are supported",`Element ${e.label} has unsupported type '${e.type}'`),!1)}_joinContingentValues(){const e=this._contingentValuesCache;if(a(e))return[];const t="typeIdField"in this.layer?this.layer.typeIdField:null,i=t?this.getValue(t):null,n=[];for(const r of e.fieldGroups){const{contingencies:e,fields:t,name:s}=r,o=[];for(const n of e)n.isRetired||l(n.subtype)&&n.subtype.code!==i||o.push({values:n.values});o.length>0&&n.push({name:s,fields:t,contingencies:o})}const[s,o]=this._generateJoinPlan(n);return[...s.flatMap((e=>this._joinFieldGroupContingencies(e))),...o.flatMap((e=>e.contingencies))]}_generateJoinPlan(e){const t=new Map,i=[],n=new Set;for(const l of e)for(const e of l.fields)if(t.has(e)){const s=t.get(e),o=l,r=[s.name,o.name].sort().join("|");if(n.has(r))continue;i.push([s,o]),n.add(r),t.set(e,o)}else t.set(e,l);const s=new Set(i.flat()),o=new Set(e);for(const l of s)o.delete(l);const r=new Map,a=new Map;for(const l of new Set(i.flat())){const e=Symbol(l.name);r.set(e,new Set([l])),a.set(l,e)}for(const[l,u]of i){const e=a.get(l),t=a.get(u);if(e===t)continue;const i=r.get(e),n=r.get(t);for(const s of n)i.add(s),a.set(s,e);r.delete(t)}return[[...r.values()].map((e=>[...e])),[...o]]}_joinFieldGroupContingencies(e){const t=e.slice(),i=t.shift();let n=t.shift(),s=this._generateJoinKey(i.fields,n.fields),o=new Set([...i.fields,...n.fields]),r=new Map;for(const a of i.contingencies){const[e]=this._hashContingency(a,s.codedValueFields,!0);r.has(e)?r.get(e).push(a):r.set(e,[a])}for(;t.length>0;){const e=new Map,i=t.shift(),l=this._generateJoinKey(o,i.fields);for(const t of n.contingencies){const[i,n]=this._hashContingency(t,s.codedValueFields),o=n?this._findMatchingContingenciesWithAnyHashMask(r,i):r.get(i);if(r.has(j)&&o.push(...this._findMatchingContingenciesContainingAny(t,r.get(j),s.codedValueFields)),!a(o))for(const r of o){const i=s.rangeFields.length>0?this._joinContingenciesWithRangeDomains(r,t,s.rangeFields):this._joinContingencies(r,t);if(a(i))break;const[n]=this._hashContingency(i,l.codedValueFields,!0);e.has(n)?e.get(n).push(i):e.set(n,[i])}}r=e,n=i,s=l,o=new Set([...o,...n.fields])}const u=[];for(const c of n.contingencies){const[e,t]=this._hashContingency(c,s.codedValueFields),i=t?this._findMatchingContingenciesWithAnyHashMask(r,e):r.get(e);if(r.has(j)&&i.push(...this._findMatchingContingenciesContainingAny(c,r.get(j),s.codedValueFields)),!a(i))for(const n of i){const e=s.rangeFields.length>0?this._joinContingenciesWithRangeDomains(n,c,s.rangeFields):this._joinContingencies(n,c);l(e)&&u.push(e)}}return u}_joinContingencies(e,t){const i={values:{...e.values,...t.values}};for(const[n,s]of Object.entries(i.values))"any"===s.objectType&&l(e.values[n])&&(i.values[n]=e.values[n]);return i}_joinContingenciesWithRangeDomains(e,t,i){const n=this._joinContingencies(e,t);for(const s of i){const i=e.values[s],o=t.values[s],{leftIsNull:r,rightIsNull:a,bothAreNull:l,leftIsAny:u,rightIsAny:c,bothAreAny:p,leftIsRange:d,rightIsRange:h}=this._compareObjectTypes(i.objectType,o.objectType);if(l||p)continue;if(r&&c||a&&u){n.values[s]=new f({objectType:"null"});continue}if(r&&h||a&&d)return null;u?(i.minValue=-1/0,i.maxValue=1/0):c&&(o.minValue=-1/0,o.maxValue=1/0);const m=Math.max(i.minValue,o.minValue),g=Math.min(i.maxValue,o.maxValue);if(m>g)return null;n.values[s]=new f({objectType:"range",minValue:m,maxValue:g})}return n}_findMatchingContingenciesContainingAny(e,t,i){return t.filter((t=>i.every((i=>{const n=t.values[i],s=e.values[i];return"any"===n.objectType||"any"===s.objectType||n.codedValue?.code===s.codedValue?.code}))))}_findMatchingContingenciesWithAnyHashMask(e,t){const i=RegExp(`${t}$`),n=[];for(const[s,o]of e){if(s===j)break;i.test(s)&&n.push(...o)}return n}_generateJoinKey(e,t){const i=Array.isArray(e)?new Set(e):e,n=Array.isArray(t)?new Set(t):t,s=i.size<n.size?i:n,o=s===i?n:i,r=new Set,l=new Set;for(const u of s)if(o.has(u)){const e=this.layer.getFieldDomain(u,{feature:this.feature});if(a(e))continue;switch(e.type){case"coded-value":r.add(u);break;case"range":l.add(u)}}return{codedValueFields:[...r],rangeFields:[...l]}}_hashContingency(e,t,i=!1){if(t.length<1)return[x,!1];const n=[];let s=!1;for(const o of t){const t=e.values[o];if("any"===t.objectType){if(i)return[j,!0];s=!0,n.push(`${o}:.*`)}else"null"===t.objectType?n.push(`${o}:${w}`):n.push(`${o}:${t.codedValue?.code}`)}return[n.sort().join("&"),s]}_compareObjectTypes(e,t){return{leftIsNull:"null"===e,rightIsNull:"null"===t,bothAreNull:"null"===e&&"null"===t,leftIsAny:"any"===e,rightIsAny:"any"===t,bothAreAny:"any"===e&&"any"===t,leftIsRange:"range"===e,rightIsRange:"range"===t}}};e([p({readOnly:!0})],I.prototype,"allInputFields",null),e([p()],I.prototype,"_layerFieldsByName",null),e([p()],I.prototype,"_inputFieldCache",void 0),e([p()],I.prototype,"contingencyConstraintViolations",void 0),e([p()],I.prototype,"feature",null),e([p()],I.prototype,"fieldsWithContingentValues",null),e([p({type:h})],I.prototype,"formTemplate",null),e([p({readOnly:!0})],I.prototype,"inputFields",null),e([p()],I.prototype,"joinedContingentValues",null),e([p()],I.prototype,"layer",null),e([p()],I.prototype,"messages",void 0),e([p()],I.prototype,"spatialReference",null),e([p()],I.prototype,"state",null),e([p()],I.prototype,"strict",void 0),e([p()],I.prototype,"submittable",null),e([p()],I.prototype,"valid",null),e([p()],I.prototype,"getValues",null),e([p()],I.prototype,"submit",null),I=e([d(b)],I);const T=e=>!!e.inputFields,k=e=>"group"===e.type,A=(e,t,i)=>{l(t)&&e.set(t,i)},M=I;export{M 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.24/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../chunks/tslib.es6.js";import"../../intl.js";import t from"../../core/Accessor.js";import{HandleOwnerMixin as i}from"../../core/HandleOwner.js";import{makeHandle as r}from"../../core/handleUtils.js";import{isSome as s,isNone as n,get as o}from"../../core/maybe.js";import{watch as l,syncAndInitial as a}from"../../core/reactiveUtils.js";import{generateUID as u}from"../../core/uid.js";import{property as p}from"../../core/accessorSupport/decorators/property.js";import"../../core/arrayUtils.js";import"../../core/has.js";import"../../core/accessorSupport/ensureType.js";import{subclass as d}from"../../core/accessorSupport/decorators/subclass.js";import c from"../../layers/support/CodedValueDomain.js";import"../../layers/support/Domain.js";import"../../layers/support/InheritedDomain.js";import"../../layers/support/RangeDomain.js";import{validateDomainValue as h,DomainValidationError as m,getDomainRange as y}from"../../layers/support/domainUtils.js";import{isNumericField as f,isStringField as g,isDateField as v,TypeValidationError as E,validateFieldValue as x,getFeatureEditFields as b,getFeatureGeometryFields as _,NumericRangeValidationError as F,getFieldRange as T}from"../../layers/support/fieldUtils.js";import{substitute as V}from"../../intl/substitute.js";var U,O;!function(e){e.Text="text",e.Number="number",e.Date="date",e.Unsupported="unsupported"}(U||(U={})),function(e){e.TOO_SHORT="length-validation-error::too-short"}(O||(O={}));const R={type:"number"},j={type:"number",intlOptions:{notation:"scientific"}},A={type:"date",intlOptions:{day:"2-digit",month:"2-digit",year:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}};function D(e){return e>=1e7||e<=-1e7}const w=["editable","required","value","visibility"];let N=class extends(i(t)){constructor(e){super(e),this._storedValue=null,this._expressionTrackingHandles=new Map,this.arcade=null,this.editableFunction=null,this.id=u().toString(),this.requiredFunction=null,this.expressionTrackingProvider={registerExpression:()=>r()},this.valueFunction=null,this.visibilityFunction=null,this.feature=null,this.field=null,this.fieldElement=null,this.layer=null,this.description=null,this.inputType=null,this.error=null,this.group=null,this.hint=null,this.messages=null,this.name=null}initialize(){const e=e=>"value"!==e,t=w.filter(e);this.own(t.map((e=>l((()=>this.get(`${e}Function`)),(t=>{s(t)?this._registerExpressionWithTrackingProvider(e):this._unregisterExpressionWithTrackingProvider(e)}),a))))}get _configAllowsEdits(){const{fieldElement:e,layer:t,name:i}=this;if(s(e))return e.editableExpression?this.evaluatedEditableExpression:!1!==e.editable;return("subtype-group"!==t?.type?t?.popupTemplate?.fieldInfos?.find((({fieldName:e})=>e===i)):null)?.isEditable??!0}get _layerFieldAllowsEdits(){const{field:e,layer:t}=this;return t?.capabilities.operations.supportsEditing&&e?.editable}get isUsingValueExpression(){return this._shouldUseValueExpression()}get evaluatedEditableExpression(){const{editableFunction:e,spatialReference:t}=this;if(n(e))return null;const{arcade:i}=this,r=i.arcadeUtils.getViewInfo({spatialReference:t});return i.arcadeUtils.executeFunction(e,i.arcadeUtils.createExecContext(this.feature,r))}get evaluatedRequiredExpression(){const{requiredFunction:e,spatialReference:t}=this;if(n(e))return null;const{arcade:i}=this,r=i.arcadeUtils.getViewInfo({spatialReference:t});return i.arcadeUtils.executeFunction(e,i.arcadeUtils.createExecContext(this.feature,r))}get evaluatedVisibilityExpression(){const{visibilityFunction:e,spatialReference:t}=this;if(n(e))return null;const{arcade:i}=this,r=i.arcadeUtils.getViewInfo({spatialReference:t});return i.arcadeUtils.executeFunction(e,i.arcadeUtils.createExecContext(this.feature,r))}get evaluatedValueExpression(){const{valueFunction:e,spatialReference:t}=this;if(n(e))return null;const{arcade:i}=this,r=i.arcadeUtils.getViewInfo({spatialReference:t});return i.arcadeUtils.executeFunction(e,i.arcadeUtils.createExecContext(this.feature,r))}set initialFeature(e){this._set("initialFeature",e),this.notifyChange("valid")}get domain(){const{typeIdField:e}=this.layer,t=e===this.name,i=this.field?.domain;if(t&&!i){const{layer:e}=this,t="subtype-group"===e.type?e.sublayers.map((({subtypeCode:e,title:t})=>({id:e,name:t}))):e.types.map((({id:e,name:t})=>({code:e,name:t})));return new c({name:"__internal-type-based-coded-value-domain__",codedValues:t})}const{feature:r}=this,n=e&&this.layer.getFieldDomain(this.name,{feature:r})||i,l=o(this.fieldElement,"domain");return s(l)&&this._isDomainCompatible(l)?l:n}get editable(){return!!this._layerFieldAllowsEdits&&(this.evaluatedEditableExpression??this._configAllowsEdits)}get errorMessage(){return this._toErrorMessage()}get includeTime(){const{fieldElement:e}=this,t=s(e)&&"datetime-picker"===e.input?.type?e.input.includeTime:void 0;return void 0===t||t}get label(){return s(this.fieldElement)&&this.fieldElement.label||this.field.alias||this.field.name}get maxLength(){const e=-1;if(this.type===U.Date)return e;const{field:t,fieldElement:i}=this,r=t?.length,n=s(i)&&k(i.input)?i.input.maxLength:NaN;return!isNaN(n)&&n>=e&&(r===e||n<=r)?n:r}get minLength(){const e=-1;if(this.type===U.Date)return e;const{field:t,fieldElement:i}=this,r=t?.length,n=s(i)&&k(i.input)?i.input.minLength:NaN;return!isNaN(n)&&n>=e&&(r===e||n<=r)?n:e}get required(){return!!this.editable&&(!1===this.field?.nullable||(this.evaluatedRequiredExpression??!1))}get spatialReference(){return this.layer?.spatialReference||null}set spatialReference(e){void 0===e?this._clearOverride("spatialReference"):this._override("spatialReference",e)}get submittable(){const{field:e,required:t,valid:i,value:r}=this;return(!t||!n(r))&&(!!i||this.initialFeature.getAttribute(e.name)===r)}get type(){const{field:e}=this;return f(e)?U.Number:g(e)?U.Text:v(e)?U.Date:U.Unsupported}get valid(){const e=this.editable?this._validate():null;return this._set("error",e),null===e}get value(){return this._shouldUseValueExpression()?this.evaluatedValueExpression:this.get("_storedValue")}set value(e){this.notifyChange("evaluatedVisibilityExpression"),this.set("_storedValue",e)}get visible(){return!this._isEditorField()&&(s(this.fieldElement)?this.evaluatedVisibilityExpression??!0:this._isVisibleByDefault())}_isDomainCompatible(e){const{field:t}=this;if("coded-value"===e?.type){const i=typeof e.codedValues[0].code;if("string"===i&&g(t)||"number"===i&&f(t))return!0}return!!("range"===e?.type&&f(t)||v(t))}_validate(){const{domain:e,field:t,initialFeature:i,minLength:r,required:s,type:n,valid:o,value:l}=this,a=s&&null===l,u=void 0!==o;return!a&&i.getAttribute(t.name)===l&&u?null:a?E.INVALID_TYPE:"text"===n&&r>-1&&"string"==typeof l&&l.length<r?O.TOO_SHORT:e?null!==l||s?h(e,l):null:x(t,l)}_isVisibleByDefault(){const e=this.field?.type;return"oid"!==e&&"global-id"!==e&&!this._isGeometryField()}_isEditorField(){return b(this.layer).includes(this.name)}_isGeometryField(){return _(this.layer).includes(this.name)}_shouldUseValueExpression(){const e=this._layerFieldAllowsEdits&&!this._configAllowsEdits&&s(this.valueFunction);return e?this._registerExpressionWithTrackingProvider("value"):this._unregisterExpressionWithTrackingProvider("value"),e}_toErrorMessage(){const{domain:e,field:t,messages:i,minLength:r,value:s,required:n,type:o}=this,l=this.error;if(n&&null===s)return i.validationErrors.cannotBeNull;if(l===m.VALUE_OUT_OF_RANGE||l===F.OUT_OF_RANGE){const r=y(e)||T(t);return V(i.validationErrors.outsideRange,r,{format:{max:"date"===o?A:D(r.max)?j:R,min:"date"===o?A:D(r.min)?j:R}})}return l===m.INVALID_CODED_VALUE?i.validationErrors.invalidCodedValue:l===E.INVALID_TYPE?i.validationErrors.invalidType:l===O.TOO_SHORT?V(i.validationErrors.tooShort,{min:r}):null}_registerExpressionWithTrackingProvider(e){const{_expressionTrackingHandles:t}=this;if(t.has(e))return;const i=`evaluated${C(e)}Expression`,r=this.expressionTrackingProvider.registerExpression((()=>this.notifyChange(i)));t.set(e,r)}_unregisterExpressionWithTrackingProvider(e){const{_expressionTrackingHandles:t}=this,i=t.get(e);i&&(i.remove(),t.delete(e))}};function k(e){return!!e&&"maxLength"in e}e([p()],N.prototype,"_storedValue",void 0),e([p()],N.prototype,"_configAllowsEdits",null),e([p()],N.prototype,"_layerFieldAllowsEdits",null),e([p()],N.prototype,"arcade",void 0),e([p()],N.prototype,"editableFunction",void 0),e([p()],N.prototype,"requiredFunction",void 0),e([p()],N.prototype,"expressionTrackingProvider",void 0),e([p()],N.prototype,"valueFunction",void 0),e([p()],N.prototype,"isUsingValueExpression",null),e([p()],N.prototype,"visibilityFunction",void 0),e([p()],N.prototype,"evaluatedEditableExpression",null),e([p()],N.prototype,"evaluatedRequiredExpression",null),e([p()],N.prototype,"evaluatedVisibilityExpression",null),e([p()],N.prototype,"evaluatedValueExpression",null),e([p()],N.prototype,"feature",void 0),e([p()],N.prototype,"field",void 0),e([p()],N.prototype,"fieldElement",void 0),e([p()],N.prototype,"initialFeature",null),e([p()],N.prototype,"layer",void 0),e([p({aliasOf:"fieldElement.description"})],N.prototype,"description",void 0),e([p()],N.prototype,"domain",null),e([p()],N.prototype,"editable",null),e([p({aliasOf:"fieldElement.input.type"})],N.prototype,"inputType",void 0),e([p({readOnly:!0})],N.prototype,"error",void 0),e([p({dependsOn:["error","messages","value"]})],N.prototype,"errorMessage",null),e([p()],N.prototype,"group",void 0),e([p({aliasOf:"fieldElement.hint"})],N.prototype,"hint",void 0),e([p()],N.prototype,"includeTime",null),e([p()],N.prototype,"label",null),e([p()],N.prototype,"maxLength",null),e([p()],N.prototype,"minLength",null),e([p()],N.prototype,"messages",void 0),e([p({aliasOf:"field.name"})],N.prototype,"name",void 0),e([p()],N.prototype,"required",null),e([p()],N.prototype,"spatialReference",null),e([p()],N.prototype,"submittable",null),e([p()],N.prototype,"type",null),e([p()],N.prototype,"valid",null),e([p({value:null})],N.prototype,"value",null),e([p()],N.prototype,"visible",null),N=e([d("esri.widgets.FeatureForm.InputField")],N);const C=e=>e.charAt(0).toUpperCase()+e.slice(1),I=N;export{I as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import"../../intl.js";import t from"../../core/Accessor.js";import{HandleOwnerMixin as i}from"../../core/HandleOwner.js";import{makeHandle as r}from"../../core/handleUtils.js";import{isSome as s,isNone as n,get as o}from"../../core/maybe.js";import{watch as l,syncAndInitial as a}from"../../core/reactiveUtils.js";import{generateUID as u}from"../../core/uid.js";import{property as p}from"../../core/accessorSupport/decorators/property.js";import"../../core/arrayUtils.js";import"../../core/has.js";import"../../core/accessorSupport/ensureType.js";import{subclass as d}from"../../core/accessorSupport/decorators/subclass.js";import c from"../../layers/support/CodedValueDomain.js";import"../../layers/support/Domain.js";import"../../layers/support/InheritedDomain.js";import"../../layers/support/RangeDomain.js";import{validateDomainValue as h,DomainValidationError as m,getDomainRange as f}from"../../layers/support/domainUtils.js";import{isNumericField as y,isStringField as g,isDateField as v,TypeValidationError as E,validateFieldValue as x,getFeatureEditFields as b,getFeatureGeometryFields as _,NumericRangeValidationError as F,getFieldRange as T}from"../../layers/support/fieldUtils.js";import{substitute as V}from"../../intl/substitute.js";var U,O;!function(e){e.Text="text",e.Number="number",e.Date="date",e.Unsupported="unsupported"}(U||(U={})),function(e){e.TOO_SHORT="length-validation-error::too-short"}(O||(O={}));const R={type:"number"},j={type:"number",intlOptions:{notation:"scientific"}},D={type:"date",intlOptions:{day:"2-digit",month:"2-digit",year:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}};function A(e){return e>=1e7||e<=-1e7}const w=["editable","required","value","visibility"];let N=class extends(i(t)){constructor(e){super(e),this._storedValue=null,this._expressionTrackingHandles=new Map,this.arcade=null,this.editableFunction=null,this.id=u().toString(),this.requiredFunction=null,this.expressionTrackingProvider={registerExpression:()=>r()},this.valueFunction=null,this.visibilityFunction=null,this.feature=null,this.field=null,this.fieldElement=null,this.layer=null,this.description=null,this.inputType=null,this.error=null,this.group=null,this.hint=null,this.messages=null,this.name=null}initialize(){const e=e=>"value"!==e,t=w.filter(e);this.own(t.map((e=>l((()=>this.get(`${e}Function`)),(t=>{s(t)?this._registerExpressionWithTrackingProvider(e):this._unregisterExpressionWithTrackingProvider(e)}),a))))}get _configAllowsEdits(){const{fieldElement:e,layer:t,name:i}=this;if(s(e))return e.editableExpression?this.evaluatedEditableExpression:!1!==e.editable;return("subtype-group"!==t?.type?t?.popupTemplate?.fieldInfos?.find((({fieldName:e})=>e===i)):null)?.isEditable??!0}get _layerFieldAllowsEdits(){const{field:e,layer:t}=this;return t?.capabilities.operations.supportsEditing&&e?.editable}get isUsingValueExpression(){return this._shouldUseValueExpression()}get evaluatedEditableExpression(){const{editableFunction:e,spatialReference:t}=this;if(n(e))return null;const{arcade:i}=this,r=i.arcadeUtils.getViewInfo({spatialReference:t});return i.arcadeUtils.executeFunction(e,i.arcadeUtils.createExecContext(this.feature,r))}get evaluatedRequiredExpression(){const{requiredFunction:e,spatialReference:t}=this;if(n(e))return null;const{arcade:i}=this,r=i.arcadeUtils.getViewInfo({spatialReference:t});return i.arcadeUtils.executeFunction(e,i.arcadeUtils.createExecContext(this.feature,r))}get evaluatedVisibilityExpression(){const{visibilityFunction:e,spatialReference:t}=this;if(n(e))return null;const{arcade:i}=this,r=i.arcadeUtils.getViewInfo({spatialReference:t});return i.arcadeUtils.executeFunction(e,i.arcadeUtils.createExecContext(this.feature,r))}get evaluatedValueExpression(){const{valueFunction:e,spatialReference:t}=this;if(n(e))return null;const{arcade:i}=this,r=i.arcadeUtils.getViewInfo({spatialReference:t});return i.arcadeUtils.executeFunction(e,i.arcadeUtils.createExecContext(this.feature,r))}set initialFeature(e){this._set("initialFeature",e),this.notifyChange("valid")}get domain(){const{typeIdField:e}=this.layer,t=e===this.name,i=this.field?.domain;if(t&&!i){const{layer:e}=this,t="subtype-group"===e.type?e.sublayers.map((({subtypeCode:e,title:t})=>({id:e,name:t}))):e.types.map((({id:e,name:t})=>({code:e,name:t})));return new c({name:"__internal-type-based-coded-value-domain__",codedValues:t})}const{feature:r}=this,n=e&&this.layer.getFieldDomain(this.name,{feature:r})||i,l=o(this.fieldElement,"domain");return s(l)&&this._isDomainCompatible(l)?l:n}get editable(){return!!this._layerFieldAllowsEdits&&(this.evaluatedEditableExpression??this._configAllowsEdits)}get errorMessage(){return this._toErrorMessage()}get includeTime(){const{fieldElement:e}=this,t=s(e)&&"datetime-picker"===e.input?.type?e.input.includeTime:void 0;return void 0===t||t}get label(){return s(this.fieldElement)&&this.fieldElement.label||this.field.alias||this.field.name}get maxLength(){const e=-1;if(this.type===U.Date)return e;const{field:t,fieldElement:i}=this,r=t?.length,n=s(i)&&k(i.input)?i.input.maxLength:NaN;return!isNaN(n)&&n>=e&&(r===e||n<=r)?n:r}get minLength(){const e=-1;if(this.type===U.Date)return e;const{field:t,fieldElement:i}=this,r=t?.length,n=s(i)&&k(i.input)?i.input.minLength:NaN;return!isNaN(n)&&n>=e&&(r===e||n<=r)?n:e}get required(){return!!this.editable&&(!1===this.field?.nullable||(this.evaluatedRequiredExpression??!1))}get spatialReference(){return this.layer?.spatialReference||null}set spatialReference(e){void 0===e?this._clearOverride("spatialReference"):this._override("spatialReference",e)}get submittable(){const{field:e,required:t,valid:i,value:r}=this;return(!t||!n(r))&&(!!i||this.initialFeature.getAttribute(e.name)===r)}get type(){const{field:e}=this;return y(e)?U.Number:g(e)?U.Text:v(e)?U.Date:U.Unsupported}get valid(){const e=this.editable?this._validate():null;return this._set("error",e),null===e}get value(){if(this._shouldUseValueExpression()){const e=this.evaluatedValueExpression;return this.type===U.Date&&e instanceof Date?e.getTime():s(e)&&"object"==typeof e?e.toString():e}return this.get("_storedValue")}set value(e){this.notifyChange("evaluatedVisibilityExpression"),this.set("_storedValue",e)}get visible(){return!this._isEditorField()&&(s(this.fieldElement)?this.evaluatedVisibilityExpression??!0:this._isVisibleByDefault())}_isDomainCompatible(e){const{field:t}=this;if("coded-value"===e?.type){const i=typeof e.codedValues[0].code;if("string"===i&&g(t)||"number"===i&&y(t))return!0}return!!("range"===e?.type&&y(t)||v(t))}_validate(){const{domain:e,field:t,initialFeature:i,minLength:r,required:s,type:n,valid:o,value:l}=this,a=s&&null===l,u=void 0!==o;return!a&&i.getAttribute(t.name)===l&&u?null:a?E.INVALID_TYPE:"text"===n&&r>-1&&"string"==typeof l&&l.length<r?O.TOO_SHORT:e?null!==l||s?h(e,l):null:x(t,l)}_isVisibleByDefault(){const e=this.field?.type;return"oid"!==e&&"global-id"!==e&&!this._isGeometryField()}_isEditorField(){return b(this.layer).includes(this.name)}_isGeometryField(){return _(this.layer).includes(this.name)}_shouldUseValueExpression(){const e=this._layerFieldAllowsEdits&&!this._configAllowsEdits&&s(this.valueFunction);return e?this._registerExpressionWithTrackingProvider("value"):this._unregisterExpressionWithTrackingProvider("value"),e}_toErrorMessage(){const{domain:e,field:t,messages:i,minLength:r,value:s,required:n,type:o}=this,l=this.error;if(n&&null===s)return i.validationErrors.cannotBeNull;if(l===m.VALUE_OUT_OF_RANGE||l===F.OUT_OF_RANGE){const r=f(e)||T(t);return V(i.validationErrors.outsideRange,r,{format:{max:"date"===o?D:A(r.max)?j:R,min:"date"===o?D:A(r.min)?j:R}})}return l===m.INVALID_CODED_VALUE?i.validationErrors.invalidCodedValue:l===E.INVALID_TYPE?i.validationErrors.invalidType:l===O.TOO_SHORT?V(i.validationErrors.tooShort,{min:r}):null}_registerExpressionWithTrackingProvider(e){const{_expressionTrackingHandles:t}=this;if(t.has(e))return;const i=`evaluated${C(e)}Expression`,r=this.expressionTrackingProvider.registerExpression((()=>this.notifyChange(i)));t.set(e,r)}_unregisterExpressionWithTrackingProvider(e){const{_expressionTrackingHandles:t}=this,i=t.get(e);i&&(i.remove(),t.delete(e))}};function k(e){return!!e&&"maxLength"in e}e([p()],N.prototype,"_storedValue",void 0),e([p()],N.prototype,"_configAllowsEdits",null),e([p()],N.prototype,"_layerFieldAllowsEdits",null),e([p()],N.prototype,"arcade",void 0),e([p()],N.prototype,"editableFunction",void 0),e([p()],N.prototype,"requiredFunction",void 0),e([p()],N.prototype,"expressionTrackingProvider",void 0),e([p()],N.prototype,"valueFunction",void 0),e([p()],N.prototype,"isUsingValueExpression",null),e([p()],N.prototype,"visibilityFunction",void 0),e([p()],N.prototype,"evaluatedEditableExpression",null),e([p()],N.prototype,"evaluatedRequiredExpression",null),e([p()],N.prototype,"evaluatedVisibilityExpression",null),e([p()],N.prototype,"evaluatedValueExpression",null),e([p()],N.prototype,"feature",void 0),e([p()],N.prototype,"field",void 0),e([p()],N.prototype,"fieldElement",void 0),e([p()],N.prototype,"initialFeature",null),e([p()],N.prototype,"layer",void 0),e([p({aliasOf:"fieldElement.description"})],N.prototype,"description",void 0),e([p()],N.prototype,"domain",null),e([p()],N.prototype,"editable",null),e([p({aliasOf:"fieldElement.input.type"})],N.prototype,"inputType",void 0),e([p({readOnly:!0})],N.prototype,"error",void 0),e([p({dependsOn:["error","messages","value"]})],N.prototype,"errorMessage",null),e([p()],N.prototype,"group",void 0),e([p({aliasOf:"fieldElement.hint"})],N.prototype,"hint",void 0),e([p()],N.prototype,"includeTime",null),e([p()],N.prototype,"label",null),e([p()],N.prototype,"maxLength",null),e([p()],N.prototype,"minLength",null),e([p()],N.prototype,"messages",void 0),e([p({aliasOf:"field.name"})],N.prototype,"name",void 0),e([p()],N.prototype,"required",null),e([p()],N.prototype,"spatialReference",null),e([p()],N.prototype,"submittable",null),e([p()],N.prototype,"type",null),e([p()],N.prototype,"valid",null),e([p({value:null})],N.prototype,"value",null),e([p()],N.prototype,"visible",null),N=e([d("esri.widgets.FeatureForm.InputField")],N);const C=e=>e.charAt(0).toUpperCase()+e.slice(1),I=N;export{I as default};