@arcgis/core 4.23.2 → 4.23.3

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.
package/config.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.23/esri/copyright.txt for details.
4
4
  */
5
- import"./core/has.js";import{deepMerge as e}from"./core/object.js";var r;const s={apiKey:void 0,applicationUrl:null==(r=globalThis.location)?void 0:r.href,assetsPath:"",fontsUrl:"https://static.arcgis.com/fonts",geometryServiceUrl:"https://utility.arcgisonline.com/arcgis/rest/services/Geometry/GeometryServer",geoRSSServiceUrl:"https://utility.arcgis.com/sharing/rss",kmlServiceUrl:"https://utility.arcgis.com/sharing/kml",portalUrl:"https://www.arcgis.com",routeServiceUrl:"https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",workers:{loaderConfig:{has:{},paths:{},map:{},packages:[]}},request:{httpsDomains:["arcgis.com","arcgisonline.com","esrikr.com","premiumservices.blackbridge.com","esripremium.accuweather.com","gbm.digitalglobe.com","firstlook.digitalglobe.com","msi.digitalglobe.com"],interceptors:[],maxUrlLength:2e3,proxyRules:[],proxyUrl:null,timeout:6e4,trustedServers:[],useIdentity:!0},log:{interceptors:[],level:null}};if(globalThis.esriConfig&&(e(s,globalThis.esriConfig,!0),delete s.has),!s.assetsPath){const e="4.23.2";s.assetsPath=`https://js.arcgis.com/${e.slice(0,-2)}/@arcgis/core/assets`}s.baseUrl&&console.warn("[esri.config]","baseUrl has been replaced by assetsPath"),Object.defineProperty(s,"baseUrl",{set(){console.warn("[esri.config]","baseUrl has been replaced by assetsPath")}}),s.request.corsEnabledServers=[],s.request.corsEnabledServers.push=function(){return console.warn("[esri.config]","request.corsEnabledServers is not supported and will be removed in a future release. See http://esriurl.com/cors8664"),0};export{s as default};
5
+ import"./core/has.js";import{deepMerge as e}from"./core/object.js";var r;const s={apiKey:void 0,applicationUrl:null==(r=globalThis.location)?void 0:r.href,assetsPath:"",fontsUrl:"https://static.arcgis.com/fonts",geometryServiceUrl:"https://utility.arcgisonline.com/arcgis/rest/services/Geometry/GeometryServer",geoRSSServiceUrl:"https://utility.arcgis.com/sharing/rss",kmlServiceUrl:"https://utility.arcgis.com/sharing/kml",portalUrl:"https://www.arcgis.com",routeServiceUrl:"https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",workers:{loaderConfig:{has:{},paths:{},map:{},packages:[]}},request:{httpsDomains:["arcgis.com","arcgisonline.com","esrikr.com","premiumservices.blackbridge.com","esripremium.accuweather.com","gbm.digitalglobe.com","firstlook.digitalglobe.com","msi.digitalglobe.com"],interceptors:[],maxUrlLength:2e3,proxyRules:[],proxyUrl:null,timeout:6e4,trustedServers:[],useIdentity:!0},log:{interceptors:[],level:null}};if(globalThis.esriConfig&&(e(s,globalThis.esriConfig,!0),delete s.has),!s.assetsPath){const e="4.23.3";s.assetsPath=`https://js.arcgis.com/${e.slice(0,-2)}/@arcgis/core/assets`}s.baseUrl&&console.warn("[esri.config]","baseUrl has been replaced by assetsPath"),Object.defineProperty(s,"baseUrl",{set(){console.warn("[esri.config]","baseUrl has been replaced by assetsPath")}}),s.request.corsEnabledServers=[],s.request.corsEnabledServers.push=function(){return console.warn("[esri.config]","request.corsEnabledServers is not supported and will be removed in a future release. See http://esriurl.com/cors8664"),0};export{s as default};
package/interfaces.d.ts CHANGED
@@ -79832,12 +79832,6 @@ declare namespace __esri {
79832
79832
  * [Read more...](https://developers.arcgis.com/javascript/latest/api-reference/esri-widgets-Directions-DirectionsViewModel.html#state)
79833
79833
  */
79834
79834
  readonly state: "disabled" | "ready";
79835
- /**
79836
- * An array of graphics that define the stop locations along the route.
79837
- *
79838
- * [Read more...](https://developers.arcgis.com/javascript/latest/api-reference/esri-widgets-Directions-DirectionsViewModel.html#stops)
79839
- */
79840
- stops: Collection<Stop>;
79841
79835
  /**
79842
79836
  * The default stop symbols used to display locations between the origin and final destination.
79843
79837
  *
@@ -79970,12 +79964,6 @@ declare namespace __esri {
79970
79964
  * [Read more...](https://developers.arcgis.com/javascript/latest/api-reference/esri-widgets-Directions-DirectionsViewModel.html#selectedTravelMode)
79971
79965
  */
79972
79966
  selectedTravelMode?: TravelModeProperties;
79973
- /**
79974
- * An array of graphics that define the stop locations along the route.
79975
- *
79976
- * [Read more...](https://developers.arcgis.com/javascript/latest/api-reference/esri-widgets-Directions-DirectionsViewModel.html#stops)
79977
- */
79978
- stops?: CollectionProperties<StopProperties> | CollectionProperties<GraphicProperties>;
79979
79967
  /**
79980
79968
  * The default stop symbols used to display locations between the origin and final destination.
79981
79969
  *
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.23/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../chunks/tslib.es6.js";import t from"../config.js";import"../geometry.js";import r from"../Graphic.js";import o from"../PopupTemplate.js";import"../renderers/ClassBreaksRenderer.js";import"../renderers/DictionaryRenderer.js";import"../renderers/DotDensityRenderer.js";import"../renderers/HeatmapRenderer.js";import"../renderers/Renderer.js";import"../renderers/SimpleRenderer.js";import"../renderers/UniqueValueRenderer.js";import{read as i}from"../renderers/support/jsonUtils.js";import s from"../core/Collection.js";import n from"../core/Error.js";import{HandleOwnerMixin as l}from"../core/HandleOwner.js";import a from"../core/Logger.js";import{isSome as p,isNone as u,unwrapOrValue as m}from"../core/maybe.js";import{MultiOriginJSONMixin as y}from"../core/MultiOriginJSONSupport.js";import{setDeepValue as f}from"../core/object.js";import{convertUnit as c}from"../core/unitUtils.js";import{urlToObject as d}from"../core/urlUtils.js";import{property as h}from"../core/accessorSupport/decorators/property.js";import"../core/arrayUtils.js";import"../core/has.js";import"../core/accessorSupport/ensureType.js";import{reader as S}from"../core/accessorSupport/decorators/reader.js";import{subclass as g}from"../core/accessorSupport/decorators/subclass.js";import{writer as w}from"../core/accessorSupport/decorators/writer.js";import{updateOrigins as v}from"../core/accessorSupport/originUtils.js";import b from"../geometry/Extent.js";import{initializeProjection as P,project as B}from"../geometry/projection.js";import{WGS84 as I}from"../geometry/support/spatialReferenceUtils.js";import N from"./Layer.js";import{BlendLayer as j}from"./mixins/BlendLayer.js";import{OperationalLayer as O}from"./mixins/OperationalLayer.js";import{PortalLayer as D}from"./mixins/PortalLayer.js";import{ScaleRangeLayer as L}from"./mixins/ScaleRangeLayer.js";import{sanitizeUrl as _}from"./support/arcgisLayerUrl.js";import C from"./support/DefaultSymbols.js";import T from"../portal/Portal.js";import R from"../portal/PortalItem.js";import{fetchServiceDescription as J}from"../rest/networkService.js";import{solve as A}from"../rest/route.js";import x from"../rest/support/DirectionLine.js";import F from"../rest/support/DirectionPoint.js";import{directionsTimeUnitJsonMap as k,directionsLengthUnitJsonMap as G}from"../rest/support/networkEnums.js";import M from"../rest/support/PointBarrier.js";import U from"../rest/support/PolygonBarrier.js";import q from"../rest/support/PolylineBarrier.js";import E from"../rest/support/RouteInfo.js";import W from"../rest/support/RouteParameters.js";import V from"../rest/support/RouteSettings.js";import H from"../rest/support/Stop.js";import K from"../geometry/SpatialReference.js";import Q from"../geometry/Multipoint.js";function Y(e){return e.length?e:null}function Z(e){return"layers"in e}function $(e){return"esri.rest.support.FeatureSet"===e.declaredClass}function z(e){return"esri.rest.support.NetworkFeatureSet"===e.declaredClass}function X(e,t,r){var o,i,s,l,a,u,m,y,f,c,d;const h=t.networkDataset.networkAttributes.filter((e=>"esriNAUTCost"===e.usageType)),S=t.supportedTravelModes.find((e=>e.id===t.defaultTravelMode)),g=null!=(o=r.travelMode)?o:S,{timeAttributeName:w,distanceAttributeName:v}=g,b=h.find((e=>e.name===w)),P=h.find((e=>e.name===v)),B=null!=(i=null!=(s=null==(l=r.travelMode)?void 0:l.impedanceAttributeName)?s:r.impedanceAttribute)?i:t.impedance,I=k.fromJSON(null==b?void 0:b.units),N=G.fromJSON(null==P?void 0:P.units);if(!I||!N)throw new n("routelayer:unknown-impedance-units","the units of either the distance or time impedance are unknown");const j=null!=(a=r.directionsLanguage)?a:t.directionsLanguage,O=null!=(u=null!=(m=r.accumulateAttributes)?m:t.accumulateAttributeNames)?u:[],D=new Set(h.filter((({name:e})=>e===w||e===v||e===B||O.includes(e))).map((({name:e})=>e))),L=e=>{for(const t in e)D.has(t)||delete e[t]};for(const n of e.pointBarriers){var _;if(p(n.costs))n.addedCost=null!=(_=n.costs[B])?_:0,L(n.costs)}for(const n of e.polygonBarriers){var C;if(p(n.costs))n.scaleFactor=null!=(C=n.costs[B])?C:1,L(n.costs)}for(const n of e.polylineBarriers){var T;if(p(n.costs))n.scaleFactor=null!=(T=n.costs[B])?T:1,L(n.costs)}const{routeInfo:R}=e,{findBestSequence:J,preserveFirstStop:A,preserveLastStop:x,startTimeIsUTC:F,timeWindowsAreUTC:M}=r;R.analysisSettings=new V({accumulateAttributes:O,directionsLanguage:j,findBestSequence:J,preserveFirstStop:A,preserveLastStop:x,startTimeIsUTC:F,timeWindowsAreUTC:M,travelMode:g}),R.totalDuration=te(null!=(y=R.totalCosts[w])?y:0,I),R.totalDistance=re(null!=(f=R.totalCosts[v])?f:0,N),R.totalLateDuration=te(null!=(c=R.totalViolations[w])?c:0,I),R.totalWaitDuration=te(null!=(d=R.totalWait[w])?d:0,I),p(R.totalCosts)&&L(R.totalCosts),p(R.totalViolations)&&L(R.totalViolations),p(R.totalWait)&&L(R.totalWait);for(const n of e.stops){var U,q,E,W,H,K;if(p(n.serviceCosts))n.serviceDuration=te(null!=(U=n.serviceCosts[w])?U:0,I),n.serviceDistance=re(null!=(q=n.serviceCosts[v])?q:0,N),L(n.serviceCosts);if(p(n.cumulativeCosts))n.cumulativeDuration=te(null!=(E=n.cumulativeCosts[w])?E:0,I),n.cumulativeDistance=re(null!=(W=n.cumulativeCosts[v])?W:0,N),L(n.cumulativeCosts);if(p(n.violations))n.lateDuration=te(null!=(H=n.violations[w])?H:0,I),L(n.violations);if(p(n.wait))n.waitDuration=te(null!=(K=n.wait[w])?K:0,I),L(n.wait)}}async function ee(e){const t=K.WGS84;return await P(e.spatialReference,t),B(e,t)}function te(e,t){switch(t){case"seconds":return e/60;case"hours":return 60*e;case"days":return 60*e*24;default:return e}}function re(e,t){return"decimal-degrees"===t||"points"===t||"unknown"===t?e:c(e,t,"meters")}const oe=s.ofType(x),ie=s.ofType(F),se=s.ofType(M),ne=s.ofType(U),le=s.ofType(q),ae=s.ofType(H);let pe=class extends(j(L(O(D(y(l(N))))))){constructor(...e){super(...e),this._featureCollection=null,this._type="Feature Collection",this.defaultSymbols=new C,this.directionLines=null,this.directionPoints=null,this.featureCollectionType="route",this.legendEnabled=!1,this.maxScale=0,this.minScale=0,this.pointBarriers=new se,this.polygonBarriers=new ne,this.polylineBarriers=new le,this.routeInfo=null,this.spatialReference=K.WGS84,this.stops=new ae,this.type="route"}writeFeatureCollectionWebmap(e,t,r,o){const i=[this._writePolygonBarriers(),this._writePolylineBarriers(),this._writePointBarriers(),this._writeRouteInfo(),this._writeDirectionLines(),this._writeDirectionPoints(),this._writeStops()].filter((e=>!!e)),s=i.map(((e,t)=>t)),n="web-map"===o.origin?"featureCollection.layers":"layers";f(n,i,t),t.opacity=this.opacity,t.visibility=this.visible,t.visibleLayers=s}readDirectionLines(e,t){return this._getNetworkFeatures(t,"DirectionLines",(e=>x.fromPortalJSON(e)))}readDirectionPoints(e,t){return this._getNetworkFeatures(t,"DirectionPoints",(e=>F.fromPortalJSON(e)))}get fullExtent(){if(p(this.routeInfo)&&p(this.routeInfo.geometry))return this.routeInfo.geometry.extent;if(this.stops.length>1){const{spatialReference:e}=this.stops[0],t=new Q({spatialReference:e}),r=this.stops.toArray().map((e=>e.geometry));for(const o of r)p(o)&&t.addPoint(o);return t.extent}return new b({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:K.WGS84})}readMaxScale(e,t){var r;const o=(Z(t)?t.layers:t.featureCollection.layers).find((e=>p(e.layerDefinition.maxScale)));return null!=(r=null==o?void 0:o.layerDefinition.maxScale)?r:0}readMinScale(e,t){var r;const o=(Z(t)?t.layers:t.featureCollection.layers).find((e=>p(e.layerDefinition.minScale)));return null!=(r=null==o?void 0:o.layerDefinition.minScale)?r:0}readPointBarriers(e,t){return this._getNetworkFeatures(t,"Barriers",(e=>M.fromPortalJSON(e)))}readPolygonBarriers(e,t){return this._getNetworkFeatures(t,"PolygonBarriers",(e=>U.fromPortalJSON(e)))}readPolylineBarriers(e,t){return this._getNetworkFeatures(t,"PolylineBarriers",(e=>q.fromPortalJSON(e)))}readRouteInfo(e,t){const r=this._getNetworkFeatures(t,"RouteInfo",(e=>E.fromPortalJSON(e)));return r.length>0?r.getItemAt(0):null}readSpatialReference(e,t){var r,o;const i=Z(t)?t.layers:t.featureCollection.layers;if(!i.length)return K.WGS84;const{layerDefinition:s}=i[0],n=null!=(r=null!=(o=s.spatialReference)?o:s.extent.spatialReference)?r:I;return K.fromJSON(n)}readStops(e,t){return this._getNetworkFeatures(t,"Stops",(e=>H.fromPortalJSON(e)),(e=>this._setStopSymbol(e)))}get title(){return p(this.routeInfo)&&p(this.routeInfo.name)?this.routeInfo.name:"Route"}set title(e){e?this._override("title",e):this._clearOverride("title")}get url(){return t.routeServiceUrl}set url(e){null!=e?this._set("url",_(e,a.getLogger(this.declaredClass))):this._set("url",t.routeServiceUrl)}load(e){return this.addResolvingPromise(this.loadFromPortal({supportedTypes:["Feature Collection"]},e)),Promise.resolve(this)}removeAll(){p(this.directionLines)&&(this.directionLines.removeAll(),this._set("directionLines",null)),p(this.directionPoints)&&(this.directionPoints.removeAll(),this._set("directionPoints",null)),p(this.routeInfo)&&this._set("routeInfo",null),this.pointBarriers.removeAll(),this.polygonBarriers.removeAll(),this.polylineBarriers.removeAll(),this.stops.removeAll()}async save(){await this.load();const{fullExtent:e,portalItem:t}=this;if(!t)throw new n("routelayer:portal-item-not-set","save() requires to the layer to have a portal item");if(!t.id)throw new n("routelayer:portal-item-not-saved","Please use saveAs() first to save the routelayer");if("Feature Collection"!==t.type)throw new n("routelayer:portal-item-wrong-type",'Portal item needs to have type "Feature Collection"');if(u(this.routeInfo))throw new n("routelayer:route-unsolved","save() requires a solved route");const{portal:r}=t;if(await r._signIn(),r.user||await t.reload(),r.user.username!==t.owner)throw new n("routelayer:not-portal-item-owner","You can only overwrite your portal items");const{itemUrl:o}=t,i={messages:[],origin:"portal-item",portal:r,url:o&&d(o),writtenProperties:[]},s=this.write(null,i);return t.extent=await ee(e),t.title=this.title,await t.update({data:s}),t}async saveAs(e,t={}){if(await this.load(),u(this.routeInfo))throw new n("routelayer:route-unsolved","saveAs() requires a solved route");const r=R.from(e).clone();null!=r.extent||(r.extent=await ee(this.fullExtent)),r.id=null,null!=r.portal||(r.portal=T.getDefault()),null!=r.title||(r.title=this.title),r.type="Feature Collection",r.typeKeywords=["Data","Feature Collection","Multilayer","Route Layer"];const{portal:o}=r,i={messages:[],origin:"portal-item",portal:o,url:null,writtenProperties:[]};await o._signIn();const s=null==t?void 0:t.folder,l=this.write(null,i);return await o.user.addItem({item:r,folder:s,data:l}),this.portalItem=r,v(i),i.portalItem=r,r}async solve(e,t){var r,o,i,l,a,p;const y=null!=(r=null==e?void 0:e.stops)?r:this.stops,f=null!=(o=null==e?void 0:e.pointBarriers)?o:Y(this.pointBarriers),c=null!=(i=null==e?void 0:e.polylineBarriers)?i:Y(this.polylineBarriers),d=null!=(l=null==e?void 0:e.polygonBarriers)?l:Y(this.polygonBarriers);if(u(y))throw new n("routelayer:undefined-stops","the route layer must have stops defined in the route parameters.");if(($(y)||z(y))&&y.features.length<2||s.isCollection(y)&&y.length<2)throw new n("routelayer:insufficent-stops","the route layer must have two or more stops to solve a route.");const h=await J(this.url,null==e?void 0:e.apiKey,t),S=h.supportedTravelModes.find((e=>e.id===h.defaultTravelMode)),g=null!=(a=null==e?void 0:e.travelMode)?a:S,{distanceAttributeName:w}=g,v=null!=(p=null==e?void 0:e.accumulateAttributes)?p:[];v.push(w);const b={startTime:new Date},P={accumulateAttributes:v,directionsOutputType:"featuresets",ignoreInvalidLocations:!0,pointBarriers:f,polylineBarriers:c,polygonBarriers:d,preserveFirstStop:!0,preserveLastStop:!0,returnBarriers:!!f,returnDirections:!0,returnPolygonBarriers:!!d,returnPolylineBarriers:!!c,returnRoutes:!0,returnStops:!0,stops:y},B=e?W.from(e):new W;for(const s in b)null==B[s]&&(B[s]=b[s]);B.set(P);const I=await A(this.url,B,t),N=this._toRouteLayerSolution(I);return this._isOverridden("title")||(this.title=m(N.routeInfo.name,"Route")),X(N,h,B),N}update(e){const{stops:t,directionLines:r,directionPoints:o,pointBarriers:i,polylineBarriers:s,polygonBarriers:n,routeInfo:l}=e;this.set({stops:t,pointBarriers:i,polylineBarriers:s,polygonBarriers:n}),this._set("directionLines",r),this._set("directionPoints",o),this._set("routeInfo",l)}_getLayerDefinition(){return{capabilities:"Query,Update,Editing",extent:this.fullExtent.toJSON(),hasM:!1,hasZ:!1,maxScale:this.maxScale,minScale:this.minScale,objectIdField:"__OBJECTID",spatialReference:this.spatialReference.toJSON(),type:"Feature Layer",typeIdField:""}}_getNetworkFeatures(e,t,n,l){const a=(Z(e)?e.layers:e.featureCollection.layers).find((e=>e.layerDefinition.name===t));if(u(a))return new s;const{layerDefinition:p,popupInfo:m,featureSet:y}=a,f=p.drawingInfo.renderer,{features:c}=y,d=f&&i(f),h=c.map((e=>{var i;const s=n(e),{attributes:l}=e,a=new r({attributes:l});return null!=s.symbol||(s.symbol=null!=(i=null==d?void 0:d.getSymbol(a))?i:this._getNetworkSymbol(t)),null!=s.popupTemplate||(s.popupTemplate=m&&o.fromJSON(m)),s}));return l&&h.some((e=>!e.symbol))&&l(h),new s(h)}_getNetworkSymbol(e){switch(e){case"Barriers":return this.defaultSymbols.pointBarriers;case"DirectionPoints":return this.defaultSymbols.directionPoints;case"DirectionLines":return this.defaultSymbols.directionLines;case"PolylineBarriers":return this.defaultSymbols.polylineBarriers;case"PolygonBarriers":return this.defaultSymbols.polygonBarriers;case"RouteInfo":return this.defaultSymbols.routeInfo;case"Stops":return null}}_setStopSymbol(e){if(!e)return;if(e.length<2){for(const t of e)t.symbol=this.defaultSymbols.invalidStop;return}const t=e.map((e=>e.sequence)).filter((e=>p(e))),r=Math.min(...t),o=Math.max(...t);for(const i of e)i.sequence!==r?i.sequence!==o?"ok"===i.status||"not-located-on-closest"===i.status?"waypoint"!==i.locationType?"break"!==i.locationType?i.symbol=this.defaultSymbols.middleStop:i.symbol=this.defaultSymbols.breakStop:i.symbol=this.defaultSymbols.waypointStop:i.symbol=this.defaultSymbols.invalidStop:i.symbol=this.defaultSymbols.lastStop:i.symbol=this.defaultSymbols.firstStop}_toRouteLayerSolution(e){var t,r,o;const i=e.routeResults[0].stops.map((e=>H.fromJSON(e.toJSON())));this._setStopSymbol(i);const s=new ae(i),n=new ne(null==(t=e.polygonBarriers)?void 0:t.map((e=>{const t=U.fromJSON(e.toJSON());return t.symbol=this.defaultSymbols.polygonBarriers,t}))),l=new le(null==(r=e.polylineBarriers)?void 0:r.map((e=>{const t=q.fromJSON(e.toJSON());return t.symbol=this.defaultSymbols.polylineBarriers,t}))),a=new se(null==(o=e.pointBarriers)?void 0:o.map((e=>{const t=M.fromJSON(e.toJSON());return t.symbol=this.defaultSymbols.pointBarriers,t}))),p=E.fromJSON(e.routeResults[0].route.toJSON());p.symbol=this.defaultSymbols.routeInfo;const u=new ie(e.routeResults[0].directionPoints.features.map((e=>{const t=F.fromJSON(e.toJSON());return t.symbol=this.defaultSymbols.directionPoints,t})));return{directionLines:new oe(e.routeResults[0].directionLines.features.map((e=>{const t=x.fromJSON(e.toJSON());return t.symbol=this.defaultSymbols.directionLines,t}))),directionPoints:u,pointBarriers:a,polygonBarriers:n,polylineBarriers:l,routeInfo:p,stops:s}}_writeDirectionLines(){return u(this.directionLines)||!this.directionLines.length?null:{featureSet:{features:this.directionLines.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPolyline"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.directionLines.toJSON()}},fields:x.fields,geometryType:"esriGeometryPolyline",name:"DirectionLines",title:"Direction Lines"},popupInfo:x.popupInfo}}_writeDirectionPoints(){return u(this.directionPoints)||!this.directionPoints.length?null:{featureSet:{features:this.directionPoints.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPoint"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.directionPoints.toJSON()}},fields:F.fields,geometryType:"esriGeometryPoint",name:"DirectionPoints",title:"Direction Points"},popupInfo:F.popupInfo}}_writePointBarriers(){return u(this.pointBarriers)||!this.pointBarriers.length?null:{featureSet:{features:this.pointBarriers.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPoint"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.pointBarriers.toJSON()}},fields:M.fields,geometryType:"esriGeometryPoint",name:"Barrier",title:"Point Barrier"},popupInfo:M.popupInfo}}_writePolygonBarriers(){return u(this.polygonBarriers)||!this.polygonBarriers.length?null:{featureSet:{features:this.polygonBarriers.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPolygon"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.polygonBarriers.toJSON()}},fields:U.fields,geometryType:"esriGeometryPolygon",name:"PolygonBarriers",title:"Polygon Barriers"},popupInfo:U.popupInfo}}_writePolylineBarriers(){return u(this.polylineBarriers)||!this.polylineBarriers.length?null:{featureSet:{features:this.polylineBarriers.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPolyline"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.polylineBarriers.toJSON()}},fields:q.fields,geometryType:"esriGeometryPolyline",name:"PolylineBarriers",title:"Line Barriers"},popupInfo:q.popupInfo}}_writeRouteInfo(){return u(this.routeInfo)?null:{featureSet:{features:[this.routeInfo.toPortalJSON()],geometryType:"esriGeometryPolyline"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.routeInfo.toJSON()}},fields:E.fields,geometryType:"esriGeometryPolyline",name:"RouteInfo",title:"Route Details"},popupInfo:E.popupInfo}}_writeStops(){return u(this.stops)||!this.stops.length?null:{featureSet:{features:this.stops.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPoint"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"uniqueValue",field1:"Sequence",defaultSymbol:this.defaultSymbols.middleStop.toJSON(),uniqueValueInfos:[{value:"1",symbol:this.defaultSymbols.firstStop.toJSON(),label:"First Stop"},{value:`${this.stops.length}`,symbol:this.defaultSymbols.lastStop.toJSON(),label:"Last Stop"}]}},fields:H.fields,geometryType:"esriGeometryPoint",name:"Stops",title:"Stops"},popupInfo:H.popupInfo}}};e([h({readOnly:!0,json:{read:!1,origins:{"portal-item":{write:{allowNull:!0,ignoreOrigin:!0}},"web-map":{write:{overridePolicy(){return{allowNull:!0,ignoreOrigin:null==this.portalItem}}}}}}})],pe.prototype,"_featureCollection",void 0),e([w(["web-map","portal-item"],"_featureCollection")],pe.prototype,"writeFeatureCollectionWebmap",null),e([h({readOnly:!0,json:{read:!1,origins:{"web-map":{write:{target:"type",overridePolicy(){return{ignoreOrigin:null!=this.portalItem}}}}}}})],pe.prototype,"_type",void 0),e([h({nonNullable:!0,type:C})],pe.prototype,"defaultSymbols",void 0),e([h({readOnly:!0})],pe.prototype,"directionLines",void 0),e([S(["web-map","portal-item"],"directionLines",["layers","featureCollection.layers"])],pe.prototype,"readDirectionLines",null),e([h({readOnly:!0})],pe.prototype,"directionPoints",void 0),e([S(["web-map","portal-item"],"directionPoints",["layers","featureCollection.layers"])],pe.prototype,"readDirectionPoints",null),e([h({readOnly:!0,json:{read:!1,origins:{"web-map":{write:{ignoreOrigin:!0}}}}})],pe.prototype,"featureCollectionType",void 0),e([h({readOnly:!0})],pe.prototype,"fullExtent",null),e([h({json:{origins:{"web-map":{name:"featureCollection.showLegend"}},write:!0}})],pe.prototype,"legendEnabled",void 0),e([h({type:["show","hide"]})],pe.prototype,"listMode",void 0),e([h({type:Number,nonNullable:!0,json:{write:!1}})],pe.prototype,"maxScale",void 0),e([S(["web-map","portal-item"],"maxScale",["layers","featureCollection.layers"])],pe.prototype,"readMaxScale",null),e([h({type:Number,nonNullable:!0,json:{write:!1}})],pe.prototype,"minScale",void 0),e([S(["web-map","portal-item"],"minScale",["layers","featureCollection.layers"])],pe.prototype,"readMinScale",null),e([h({type:["ArcGISFeatureLayer"],value:"ArcGISFeatureLayer"})],pe.prototype,"operationalLayerType",void 0),e([h({nonNullable:!0,type:s.ofType(M)})],pe.prototype,"pointBarriers",void 0),e([S(["web-map","portal-item"],"pointBarriers",["layers","featureCollection.layers"])],pe.prototype,"readPointBarriers",null),e([h({nonNullable:!0,type:s.ofType(U)})],pe.prototype,"polygonBarriers",void 0),e([S(["web-map","portal-item"],"polygonBarriers",["layers","featureCollection.layers"])],pe.prototype,"readPolygonBarriers",null),e([h({nonNullable:!0,type:s.ofType(q)})],pe.prototype,"polylineBarriers",void 0),e([S(["web-map","portal-item"],"polylineBarriers",["layers","featureCollection.layers"])],pe.prototype,"readPolylineBarriers",null),e([h({readOnly:!0})],pe.prototype,"routeInfo",void 0),e([S(["web-map","portal-item"],"routeInfo",["layers","featureCollection.layers"])],pe.prototype,"readRouteInfo",null),e([h({type:K})],pe.prototype,"spatialReference",void 0),e([S(["web-map","portal-item"],"spatialReference",["layers","featureCollection.layers"])],pe.prototype,"readSpatialReference",null),e([h({nonNullable:!0,type:s.ofType(H)})],pe.prototype,"stops",void 0),e([S(["web-map","portal-item"],"stops",["layers","featureCollection.layers"])],pe.prototype,"readStops",null),e([h()],pe.prototype,"title",null),e([h({readOnly:!0,json:{read:!1}})],pe.prototype,"type",void 0),e([h()],pe.prototype,"url",null),pe=e([g("esri.layers.RouteLayer")],pe);const ue=pe;export{ue as default};
5
+ import{_ as e}from"../chunks/tslib.es6.js";import t from"../config.js";import"../geometry.js";import r from"../Graphic.js";import o from"../PopupTemplate.js";import"../renderers/ClassBreaksRenderer.js";import"../renderers/DictionaryRenderer.js";import"../renderers/DotDensityRenderer.js";import"../renderers/HeatmapRenderer.js";import"../renderers/Renderer.js";import"../renderers/SimpleRenderer.js";import"../renderers/UniqueValueRenderer.js";import{read as i}from"../renderers/support/jsonUtils.js";import s from"../core/Collection.js";import n from"../core/Error.js";import{HandleOwnerMixin as l}from"../core/HandleOwner.js";import a from"../core/Logger.js";import{isSome as p,isNone as u,unwrapOrValue as m}from"../core/maybe.js";import{MultiOriginJSONMixin as y}from"../core/MultiOriginJSONSupport.js";import{setDeepValue as f}from"../core/object.js";import{watch as c}from"../core/reactiveUtils.js";import{convertUnit as d}from"../core/unitUtils.js";import{urlToObject as h}from"../core/urlUtils.js";import{property as S}from"../core/accessorSupport/decorators/property.js";import"../core/arrayUtils.js";import"../core/has.js";import"../core/accessorSupport/ensureType.js";import{reader as g}from"../core/accessorSupport/decorators/reader.js";import{subclass as w}from"../core/accessorSupport/decorators/subclass.js";import{writer as v}from"../core/accessorSupport/decorators/writer.js";import{updateOrigins as b}from"../core/accessorSupport/originUtils.js";import P from"../geometry/Extent.js";import{initializeProjection as B,project as I}from"../geometry/projection.js";import{WGS84 as N}from"../geometry/support/spatialReferenceUtils.js";import j from"./Layer.js";import{BlendLayer as O}from"./mixins/BlendLayer.js";import{OperationalLayer as L}from"./mixins/OperationalLayer.js";import{PortalLayer as D}from"./mixins/PortalLayer.js";import{ScaleRangeLayer as _}from"./mixins/ScaleRangeLayer.js";import{sanitizeUrl as C}from"./support/arcgisLayerUrl.js";import T from"./support/DefaultSymbols.js";import R from"../portal/Portal.js";import J from"../portal/PortalItem.js";import{fetchServiceDescription as A}from"../rest/networkService.js";import{solve as x}from"../rest/route.js";import F from"../rest/support/DirectionLine.js";import k from"../rest/support/DirectionPoint.js";import{directionsTimeUnitJsonMap as G,directionsLengthUnitJsonMap as M}from"../rest/support/networkEnums.js";import U from"../rest/support/PointBarrier.js";import E from"../rest/support/PolygonBarrier.js";import q from"../rest/support/PolylineBarrier.js";import W from"../rest/support/RouteInfo.js";import V from"../rest/support/RouteParameters.js";import H from"../rest/support/RouteSettings.js";import K from"../rest/support/Stop.js";import Q from"../geometry/SpatialReference.js";import Y from"../geometry/Multipoint.js";function Z(e){return e.length?e:null}function $(e){return"layers"in e}function z(e){return"esri.rest.support.FeatureSet"===e.declaredClass}function X(e){return"esri.rest.support.NetworkFeatureSet"===e.declaredClass}function ee(e,t,r){var o,i,s,l,a,m,y,f,c,d,h;const{impedance:S,networkDataset:g,supportedTravelModes:w,defaultTravelMode:v}=t,b=g.networkAttributes.filter((e=>"esriNAUTCost"===e.usageType)),P=w.find((e=>e.id===v)),B=null!=(o=r.travelMode)?o:P;if(u(B))return void ue.warn("route-layer:missing-travel-mode","The routing service must have a default travel mode or one must be specified in the route parameter.");const{timeAttributeName:I,distanceAttributeName:N}=B,j=b.find((e=>e.name===I)),O=b.find((e=>e.name===N)),L=null!=(i=null!=(s=null==(l=r.travelMode)?void 0:l.impedanceAttributeName)?s:r.impedanceAttribute)?i:S,D=G.fromJSON(null==j?void 0:j.units),_=M.fromJSON(null==O?void 0:O.units);if(!D||!_)throw new n("routelayer:unknown-impedance-units","the units of either the distance or time impedance are unknown");const C=null!=(a=r.directionsLanguage)?a:t.directionsLanguage,T=null!=(m=null!=(y=r.accumulateAttributes)?y:t.accumulateAttributeNames)?m:[],R=new Set(b.filter((({name:e})=>e===I||e===N||e===L||T.includes(e))).map((({name:e})=>e))),J=e=>{for(const t in e)R.has(t)||delete e[t]};for(const n of e.pointBarriers){var A;if(p(n.costs))n.addedCost=null!=(A=n.costs[L])?A:0,J(n.costs)}for(const n of e.polygonBarriers){var x;if(p(n.costs))n.scaleFactor=null!=(x=n.costs[L])?x:1,J(n.costs)}for(const n of e.polylineBarriers){var F;if(p(n.costs))n.scaleFactor=null!=(F=n.costs[L])?F:1,J(n.costs)}const{routeInfo:k}=e,{findBestSequence:U,preserveFirstStop:E,preserveLastStop:q,startTimeIsUTC:W,timeWindowsAreUTC:V}=r;k.analysisSettings=new H({accumulateAttributes:T,directionsLanguage:C,findBestSequence:U,preserveFirstStop:E,preserveLastStop:q,startTimeIsUTC:W,timeWindowsAreUTC:V,travelMode:B}),k.totalDuration=re(null!=(f=k.totalCosts[I])?f:0,D),k.totalDistance=oe(null!=(c=k.totalCosts[N])?c:0,_),k.totalLateDuration=re(null!=(d=k.totalViolations[I])?d:0,D),k.totalWaitDuration=re(null!=(h=k.totalWait[I])?h:0,D),p(k.totalCosts)&&J(k.totalCosts),p(k.totalViolations)&&J(k.totalViolations),p(k.totalWait)&&J(k.totalWait);for(const n of e.stops){var K,Q,Y,Z,$,z;if(p(n.serviceCosts))n.serviceDuration=re(null!=(K=n.serviceCosts[I])?K:0,D),n.serviceDistance=oe(null!=(Q=n.serviceCosts[N])?Q:0,_),J(n.serviceCosts);if(p(n.cumulativeCosts))n.cumulativeDuration=re(null!=(Y=n.cumulativeCosts[I])?Y:0,D),n.cumulativeDistance=oe(null!=(Z=n.cumulativeCosts[N])?Z:0,_),J(n.cumulativeCosts);if(p(n.violations))n.lateDuration=re(null!=($=n.violations[I])?$:0,D),J(n.violations);if(p(n.wait))n.waitDuration=re(null!=(z=n.wait[I])?z:0,D),J(n.wait)}}async function te(e){const t=Q.WGS84;return await B(e.spatialReference,t),I(e,t)}function re(e,t){switch(t){case"seconds":return e/60;case"hours":return 60*e;case"days":return 60*e*24;default:return e}}function oe(e,t){return"decimal-degrees"===t||"points"===t||"unknown"===t?e:d(e,t,"meters")}const ie=s.ofType(F),se=s.ofType(k),ne=s.ofType(U),le=s.ofType(E),ae=s.ofType(q),pe=s.ofType(K),ue=a.getLogger("esri.layers.RouteLayer");let me=class extends(O(_(L(D(y(l(j))))))){constructor(...e){super(...e),this._featureCollection=null,this._type="Feature Collection",this.defaultSymbols=new T,this.directionLines=null,this.directionPoints=null,this.featureCollectionType="route",this.legendEnabled=!1,this.maxScale=0,this.minScale=0,this.pointBarriers=new ne,this.polygonBarriers=new le,this.polylineBarriers=new ae,this.routeInfo=null,this.spatialReference=Q.WGS84,this.stops=new pe,this.type="route",this.handles.add(c((()=>this.stops.toArray()),(()=>{u(this.routeInfo)&&this._setStopSymbol(this.stops)}),{sync:!0}))}writeFeatureCollectionWebmap(e,t,r,o){const i=[this._writePolygonBarriers(),this._writePolylineBarriers(),this._writePointBarriers(),this._writeRouteInfo(),this._writeDirectionLines(),this._writeDirectionPoints(),this._writeStops()].filter((e=>!!e)),s=i.map(((e,t)=>t)),n="web-map"===o.origin?"featureCollection.layers":"layers";f(n,i,t),t.opacity=this.opacity,t.visibility=this.visible,t.visibleLayers=s}readDirectionLines(e,t){return this._getNetworkFeatures(t,"DirectionLines",(e=>F.fromPortalJSON(e)))}readDirectionPoints(e,t){return this._getNetworkFeatures(t,"DirectionPoints",(e=>k.fromPortalJSON(e)))}get fullExtent(){if(p(this.routeInfo)&&p(this.routeInfo.geometry))return this.routeInfo.geometry.extent;if(this.stops.length>1){const{spatialReference:e}=this.stops[0],t=new Y({spatialReference:e}),r=this.stops.toArray().map((e=>e.geometry));for(const o of r)p(o)&&t.addPoint(o);return t.extent}return new P({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:Q.WGS84})}readMaxScale(e,t){var r;const o=($(t)?t.layers:t.featureCollection.layers).find((e=>p(e.layerDefinition.maxScale)));return null!=(r=null==o?void 0:o.layerDefinition.maxScale)?r:0}readMinScale(e,t){var r;const o=($(t)?t.layers:t.featureCollection.layers).find((e=>p(e.layerDefinition.minScale)));return null!=(r=null==o?void 0:o.layerDefinition.minScale)?r:0}readPointBarriers(e,t){return this._getNetworkFeatures(t,"Barriers",(e=>U.fromPortalJSON(e)))}readPolygonBarriers(e,t){return this._getNetworkFeatures(t,"PolygonBarriers",(e=>E.fromPortalJSON(e)))}readPolylineBarriers(e,t){return this._getNetworkFeatures(t,"PolylineBarriers",(e=>q.fromPortalJSON(e)))}readRouteInfo(e,t){const r=this._getNetworkFeatures(t,"RouteInfo",(e=>W.fromPortalJSON(e)));return r.length>0?r.getItemAt(0):null}readSpatialReference(e,t){var r,o;const i=$(t)?t.layers:t.featureCollection.layers;if(!i.length)return Q.WGS84;const{layerDefinition:s}=i[0],n=null!=(r=null!=(o=s.spatialReference)?o:s.extent.spatialReference)?r:N;return Q.fromJSON(n)}readStops(e,t){return this._getNetworkFeatures(t,"Stops",(e=>K.fromPortalJSON(e)),(e=>this._setStopSymbol(e)))}get title(){return p(this.routeInfo)&&p(this.routeInfo.name)?this.routeInfo.name:"Route"}set title(e){e?this._override("title",e):this._clearOverride("title")}get url(){return t.routeServiceUrl}set url(e){null!=e?this._set("url",C(e,ue)):this._set("url",t.routeServiceUrl)}load(e){return this.addResolvingPromise(this.loadFromPortal({supportedTypes:["Feature Collection"]},e)),Promise.resolve(this)}removeAll(){p(this.directionLines)&&(this.directionLines.removeAll(),this._set("directionLines",null)),p(this.directionPoints)&&(this.directionPoints.removeAll(),this._set("directionPoints",null)),p(this.routeInfo)&&this._set("routeInfo",null),this.pointBarriers.removeAll(),this.polygonBarriers.removeAll(),this.polylineBarriers.removeAll(),this.stops.removeAll()}async save(){await this.load();const{fullExtent:e,portalItem:t}=this;if(!t)throw new n("routelayer:portal-item-not-set","save() requires to the layer to have a portal item");if(!t.id)throw new n("routelayer:portal-item-not-saved","Please use saveAs() first to save the routelayer");if("Feature Collection"!==t.type)throw new n("routelayer:portal-item-wrong-type",'Portal item needs to have type "Feature Collection"');if(u(this.routeInfo))throw new n("routelayer:route-unsolved","save() requires a solved route");const{portal:r}=t;if(await r._signIn(),r.user||await t.reload(),r.user.username!==t.owner)throw new n("routelayer:not-portal-item-owner","You can only overwrite your portal items");const{itemUrl:o}=t,i={messages:[],origin:"portal-item",portal:r,url:o&&h(o),writtenProperties:[]},s=this.write(null,i);return t.extent=await te(e),t.title=this.title,await t.update({data:s}),t}async saveAs(e,t={}){if(await this.load(),u(this.routeInfo))throw new n("routelayer:route-unsolved","saveAs() requires a solved route");const r=J.from(e).clone();null!=r.extent||(r.extent=await te(this.fullExtent)),r.id=null,null!=r.portal||(r.portal=R.getDefault()),null!=r.title||(r.title=this.title),r.type="Feature Collection",r.typeKeywords=["Data","Feature Collection","Multilayer","Route Layer"];const{portal:o}=r,i={messages:[],origin:"portal-item",portal:o,url:null,writtenProperties:[]};await o._signIn();const s=null==t?void 0:t.folder,l=this.write(null,i);return await o.user.addItem({item:r,folder:s,data:l}),this.portalItem=r,b(i),i.portalItem=r,r}async solve(e,t){var r,o,i,l,a,y;const f=null!=(r=null==e?void 0:e.stops)?r:this.stops,c=null!=(o=null==e?void 0:e.pointBarriers)?o:Z(this.pointBarriers),d=null!=(i=null==e?void 0:e.polylineBarriers)?i:Z(this.polylineBarriers),h=null!=(l=null==e?void 0:e.polygonBarriers)?l:Z(this.polygonBarriers);if(u(f))throw new n("routelayer:undefined-stops","the route layer must have stops defined in the route parameters.");if((z(f)||X(f))&&f.features.length<2||s.isCollection(f)&&f.length<2)throw new n("routelayer:insufficent-stops","the route layer must have two or more stops to solve a route.");const S=await A(this.url,null==e?void 0:e.apiKey,t),{defaultTravelMode:g,supportedTravelModes:w}=S,v=w.find((e=>e.id===g)),b=null!=(a=null==e?void 0:e.travelMode)?a:v,P=null!=(y=null==e?void 0:e.accumulateAttributes)?y:[];p(b)&&P.push(b.distanceAttributeName);const B={startTime:new Date},I={accumulateAttributes:P,directionsOutputType:"featuresets",ignoreInvalidLocations:!0,pointBarriers:c,polylineBarriers:d,polygonBarriers:h,preserveFirstStop:!0,preserveLastStop:!0,returnBarriers:!!c,returnDirections:!0,returnPolygonBarriers:!!h,returnPolylineBarriers:!!d,returnRoutes:!0,returnStops:!0,stops:f},N=e?V.from(e):new V;for(const s in B)null==N[s]&&(N[s]=B[s]);N.set(I);const j=await x(this.url,N,t),O=this._toRouteLayerSolution(j);return this._isOverridden("title")||(this.title=m(O.routeInfo.name,"Route")),ee(O,S,N),O}update(e){const{stops:t,directionLines:r,directionPoints:o,pointBarriers:i,polylineBarriers:s,polygonBarriers:n,routeInfo:l}=e;this.set({stops:t,pointBarriers:i,polylineBarriers:s,polygonBarriers:n}),this._set("directionLines",r),this._set("directionPoints",o),this._set("routeInfo",l)}_getLayerDefinition(){return{capabilities:"Query,Update,Editing",extent:this.fullExtent.toJSON(),hasM:!1,hasZ:!1,maxScale:this.maxScale,minScale:this.minScale,objectIdField:"__OBJECTID",spatialReference:this.spatialReference.toJSON(),type:"Feature Layer",typeIdField:""}}_getNetworkFeatures(e,t,n,l){const a=($(e)?e.layers:e.featureCollection.layers).find((e=>e.layerDefinition.name===t));if(u(a))return new s;const{layerDefinition:p,popupInfo:m,featureSet:y}=a,f=p.drawingInfo.renderer,{features:c}=y,d=f&&i(f),h=c.map((e=>{var i;const s=n(e),{attributes:l}=e,a=new r({attributes:l});return null!=s.symbol||(s.symbol=null!=(i=null==d?void 0:d.getSymbol(a))?i:this._getNetworkSymbol(t)),null!=s.popupTemplate||(s.popupTemplate=m&&o.fromJSON(m)),s}));return l&&h.some((e=>!e.symbol))&&l(h),new s(h)}_getNetworkSymbol(e){switch(e){case"Barriers":return this.defaultSymbols.pointBarriers;case"DirectionPoints":return this.defaultSymbols.directionPoints;case"DirectionLines":return this.defaultSymbols.directionLines;case"PolylineBarriers":return this.defaultSymbols.polylineBarriers;case"PolygonBarriers":return this.defaultSymbols.polygonBarriers;case"RouteInfo":return this.defaultSymbols.routeInfo;case"Stops":return null}}_setStopSymbol(e){if(!e||0===e.length)return;if(u(this.routeInfo)||1===e.length)return void e.forEach(((t,r)=>{switch(r){case 0:t.symbol=this.defaultSymbols.firstStop;break;case e.length-1:t.symbol=this.defaultSymbols.lastStop;break;default:t.symbol=this.defaultSymbols.middleStop}}));const t=e.map((e=>e.sequence)).filter((e=>p(e))),r=Math.min(...t),o=Math.max(...t);for(const i of e)i.sequence!==r?i.sequence!==o?"ok"===i.status||"not-located-on-closest"===i.status?"waypoint"!==i.locationType?"break"!==i.locationType?i.symbol=this.defaultSymbols.middleStop:i.symbol=this.defaultSymbols.breakStop:i.symbol=this.defaultSymbols.waypointStop:i.symbol=this.defaultSymbols.invalidStop:i.symbol=this.defaultSymbols.lastStop:i.symbol=this.defaultSymbols.firstStop}_toRouteLayerSolution(e){var t,r,o,i,s;const n=e.routeResults[0].stops.map((e=>K.fromJSON(e.toJSON())));this._setStopSymbol(n);const l=new pe(n),a=new le(null==(t=e.polygonBarriers)?void 0:t.map((e=>{const t=E.fromJSON(e.toJSON());return t.symbol=this.defaultSymbols.polygonBarriers,t}))),p=new ae(null==(r=e.polylineBarriers)?void 0:r.map((e=>{const t=q.fromJSON(e.toJSON());return t.symbol=this.defaultSymbols.polylineBarriers,t}))),u=new ne(null==(o=e.pointBarriers)?void 0:o.map((e=>{const t=U.fromJSON(e.toJSON());return t.symbol=this.defaultSymbols.pointBarriers,t}))),m=W.fromJSON(e.routeResults[0].route.toJSON());m.symbol=this.defaultSymbols.routeInfo;const y=new se(null==(i=e.routeResults[0].directionPoints)?void 0:i.features.map((e=>{const t=k.fromJSON(e.toJSON());return t.symbol=this.defaultSymbols.directionPoints,t})));return{directionLines:new ie(null==(s=e.routeResults[0].directionLines)?void 0:s.features.map((e=>{const t=F.fromJSON(e.toJSON());return t.symbol=this.defaultSymbols.directionLines,t}))),directionPoints:y,pointBarriers:u,polygonBarriers:a,polylineBarriers:p,routeInfo:m,stops:l}}_writeDirectionLines(){return u(this.directionLines)||!this.directionLines.length?null:{featureSet:{features:this.directionLines.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPolyline"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.directionLines.toJSON()}},fields:F.fields,geometryType:"esriGeometryPolyline",name:"DirectionLines",title:"Direction Lines"},popupInfo:F.popupInfo}}_writeDirectionPoints(){return u(this.directionPoints)||!this.directionPoints.length?null:{featureSet:{features:this.directionPoints.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPoint"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.directionPoints.toJSON()}},fields:k.fields,geometryType:"esriGeometryPoint",name:"DirectionPoints",title:"Direction Points"},popupInfo:k.popupInfo}}_writePointBarriers(){return u(this.pointBarriers)||!this.pointBarriers.length?null:{featureSet:{features:this.pointBarriers.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPoint"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.pointBarriers.toJSON()}},fields:U.fields,geometryType:"esriGeometryPoint",name:"Barrier",title:"Point Barrier"},popupInfo:U.popupInfo}}_writePolygonBarriers(){return u(this.polygonBarriers)||!this.polygonBarriers.length?null:{featureSet:{features:this.polygonBarriers.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPolygon"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.polygonBarriers.toJSON()}},fields:E.fields,geometryType:"esriGeometryPolygon",name:"PolygonBarriers",title:"Polygon Barriers"},popupInfo:E.popupInfo}}_writePolylineBarriers(){return u(this.polylineBarriers)||!this.polylineBarriers.length?null:{featureSet:{features:this.polylineBarriers.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPolyline"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.polylineBarriers.toJSON()}},fields:q.fields,geometryType:"esriGeometryPolyline",name:"PolylineBarriers",title:"Line Barriers"},popupInfo:q.popupInfo}}_writeRouteInfo(){return u(this.routeInfo)?null:{featureSet:{features:[this.routeInfo.toPortalJSON()],geometryType:"esriGeometryPolyline"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"simple",symbol:this.defaultSymbols.routeInfo.toJSON()}},fields:W.fields,geometryType:"esriGeometryPolyline",name:"RouteInfo",title:"Route Details"},popupInfo:W.popupInfo}}_writeStops(){return u(this.stops)||!this.stops.length?null:{featureSet:{features:this.stops.toArray().map((e=>e.toPortalJSON())),geometryType:"esriGeometryPoint"},layerDefinition:{...this._getLayerDefinition(),drawingInfo:{renderer:{type:"uniqueValue",field1:"Sequence",defaultSymbol:this.defaultSymbols.middleStop.toJSON(),uniqueValueInfos:[{value:"1",symbol:this.defaultSymbols.firstStop.toJSON(),label:"First Stop"},{value:`${this.stops.length}`,symbol:this.defaultSymbols.lastStop.toJSON(),label:"Last Stop"}]}},fields:K.fields,geometryType:"esriGeometryPoint",name:"Stops",title:"Stops"},popupInfo:K.popupInfo}}};e([S({readOnly:!0,json:{read:!1,origins:{"portal-item":{write:{allowNull:!0,ignoreOrigin:!0}},"web-map":{write:{overridePolicy(){return{allowNull:!0,ignoreOrigin:null==this.portalItem}}}}}}})],me.prototype,"_featureCollection",void 0),e([v(["web-map","portal-item"],"_featureCollection")],me.prototype,"writeFeatureCollectionWebmap",null),e([S({readOnly:!0,json:{read:!1,origins:{"web-map":{write:{target:"type",overridePolicy(){return{ignoreOrigin:null!=this.portalItem}}}}}}})],me.prototype,"_type",void 0),e([S({nonNullable:!0,type:T})],me.prototype,"defaultSymbols",void 0),e([S({readOnly:!0})],me.prototype,"directionLines",void 0),e([g(["web-map","portal-item"],"directionLines",["layers","featureCollection.layers"])],me.prototype,"readDirectionLines",null),e([S({readOnly:!0})],me.prototype,"directionPoints",void 0),e([g(["web-map","portal-item"],"directionPoints",["layers","featureCollection.layers"])],me.prototype,"readDirectionPoints",null),e([S({readOnly:!0,json:{read:!1,origins:{"web-map":{write:{ignoreOrigin:!0}}}}})],me.prototype,"featureCollectionType",void 0),e([S({readOnly:!0})],me.prototype,"fullExtent",null),e([S({json:{origins:{"web-map":{name:"featureCollection.showLegend"}},write:!0}})],me.prototype,"legendEnabled",void 0),e([S({type:["show","hide"]})],me.prototype,"listMode",void 0),e([S({type:Number,nonNullable:!0,json:{write:!1}})],me.prototype,"maxScale",void 0),e([g(["web-map","portal-item"],"maxScale",["layers","featureCollection.layers"])],me.prototype,"readMaxScale",null),e([S({type:Number,nonNullable:!0,json:{write:!1}})],me.prototype,"minScale",void 0),e([g(["web-map","portal-item"],"minScale",["layers","featureCollection.layers"])],me.prototype,"readMinScale",null),e([S({type:["ArcGISFeatureLayer"],value:"ArcGISFeatureLayer"})],me.prototype,"operationalLayerType",void 0),e([S({nonNullable:!0,type:s.ofType(U)})],me.prototype,"pointBarriers",void 0),e([g(["web-map","portal-item"],"pointBarriers",["layers","featureCollection.layers"])],me.prototype,"readPointBarriers",null),e([S({nonNullable:!0,type:s.ofType(E)})],me.prototype,"polygonBarriers",void 0),e([g(["web-map","portal-item"],"polygonBarriers",["layers","featureCollection.layers"])],me.prototype,"readPolygonBarriers",null),e([S({nonNullable:!0,type:s.ofType(q)})],me.prototype,"polylineBarriers",void 0),e([g(["web-map","portal-item"],"polylineBarriers",["layers","featureCollection.layers"])],me.prototype,"readPolylineBarriers",null),e([S({readOnly:!0})],me.prototype,"routeInfo",void 0),e([g(["web-map","portal-item"],"routeInfo",["layers","featureCollection.layers"])],me.prototype,"readRouteInfo",null),e([S({type:Q})],me.prototype,"spatialReference",void 0),e([g(["web-map","portal-item"],"spatialReference",["layers","featureCollection.layers"])],me.prototype,"readSpatialReference",null),e([S({nonNullable:!0,type:s.ofType(K)})],me.prototype,"stops",void 0),e([g(["web-map","portal-item"],"stops",["layers","featureCollection.layers"])],me.prototype,"readStops",null),e([S()],me.prototype,"title",null),e([S({readOnly:!0,json:{read:!1}})],me.prototype,"type",void 0),e([S()],me.prototype,"url",null),me=e([w("esri.layers.RouteLayer")],me);const ye=me;export{ye as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcgis/core",
3
- "version": "4.23.2",
3
+ "version": "4.23.3",
4
4
  "homepage": "https://js.arcgis.com",
5
5
  "description": "ArcGIS API for JavaScript: A complete 2D and 3D mapping and data visualization API",
6
6
  "keywords": [
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.23/esri/copyright.txt for details.
4
4
  */
5
- const c="20220325",d="bd365f30c3ec9889ec50c6d6f51a1c6ac3877d35";export{c as buildDate,d as commitHash};
5
+ const e="20220328",c="51a3612853ce5d4fd13e137106d6e5c54e7354c7";export{e as buildDate,c as commitHash};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.23/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../Color.js";import r from"../../config.js";import o from"../../Graphic.js";import"../../symbols.js";import i from"../../core/Collection.js";import s from"../../core/Error.js";import l from"../../core/Evented.js";import{HandleOwnerMixin as n}from"../../core/HandleOwner.js";import{isNone as a,isSome as u}from"../../core/maybe.js";import{isAbortError as c}from"../../core/promiseUtils.js";import{on as d,watch as p,initial as h,syncAndInitial as m}from"../../core/reactiveUtils.js";import{aliasOf as v}from"../../core/accessorSupport/decorators/aliasOf.js";import"../../core/arrayUtils.js";import"../../core/has.js";import{cast as y}from"../../core/accessorSupport/decorators/cast.js";import{property as g}from"../../core/accessorSupport/decorators/property.js";import{subclass as f}from"../../core/accessorSupport/decorators/subclass.js";import{getLocale as w}from"../../intl/locale.js";import _ from"../../layers/GraphicsLayer.js";import S from"../../layers/RouteLayer.js";import b from"../../layers/support/DefaultSymbols.js";import{fetchServiceDescription as C}from"../../rest/networkService.js";import D from"../../rest/support/RouteParameters.js";import T from"../../rest/support/Stop.js";import{GoToMixin as j}from"../support/GoTo.js";import L from"../../symbols/SimpleLineSymbol.js";import M from"../../symbols/SimpleMarkerSymbol.js";import A from"../../symbols/PictureMarkerSymbol.js";function z(e){return e.length>0&&e.getItemAt(0)instanceof o}const P=i.ofType(T),U=[105,220,255],R=new L({color:U,width:7,cap:"round",join:"round"}),x={first:new M({color:U,size:19,outline:{color:[51,51,51],width:3}}),middle:new M({color:[51,51,51],size:12,outline:{color:U,width:3}}),last:new A({width:23,height:23,url:`data:image/svg+xml;base64,${btoa('<svg width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg"><g fill-rule="nonzero" fill="none"><path d="M15.15.3C6.9.3.3 6.9.3 15.15S6.9 29.7 15.15 29.7 29.7 23.1 29.7 15.15C29.7 6.9 23.25.3 15.15.3z" fill="#333"/><path d="M15 4.8C9.3 4.8 4.8 9.45 4.8 15c0 5.55 4.65 10.2 10.2 10.2 5.55 0 10.2-4.5 10.2-10.2 0-5.55-4.5-10.2-10.2-10.2z" fill="#69DCFF"/><path fill="#333" d="M10.5 10.5h9v9h-9z"/></g></svg>')}`}),unlocated:new A({height:18,width:18,url:`data:image/svg+xml;base64,${btoa('<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><path d="M10.1.2C4.6.2.2 4.6.2 10.1s4.4 9.7 9.9 9.7 9.7-4.4 9.7-9.7c0-5.5-4.3-9.9-9.7-9.9z" fill="#333" fill-rule="nonzero"/><path d="M10 2.7c-4.08 0-7.3 3.328-7.3 7.3s3.328 7.3 7.3 7.3 7.3-3.22 7.3-7.3c0-3.972-3.22-7.3-7.3-7.3z" fill="#69DCFF" fill-rule="nonzero"/><path d="M11.414 10l5.304-5.303-1.415-1.415L10 8.586 4.697 3.282 3.282 4.697 8.586 10l-5.304 5.303 1.415 1.415L10 11.414l5.303 5.304 1.415-1.415L11.414 10z" fill="#333"/></g></svg>')}`}),waypoint:new M({color:[255,255,255],size:10,outline:{color:[20,89,127],width:2.5}})};var O;!function(e){e[e.Active=0]="Active",e[e.Complete=1]="Complete",e[e.Failed=2]="Failed",e[e.Idle=3]="Idle",e[e.Suspended=4]="Suspended"}(O||(O={}));let I=class extends(n(j(l.EventedAccessor))){constructor(e){super(e),this._highlightLayer=new _({listMode:"hide"}),this._loadPromise=null,this._loadController=null,this._routeLayer=new S({listMode:"hide",defaultSymbols:new b({directionLines:R,directionPoints:new M({size:0}),routeInfo:new L({width:0}),firstStop:x.first,middleStop:x.middle,lastStop:x.last,invalidStop:x.unlocated,waypointStop:x.waypoint,breakStop:x.waypoint}),url:this.routeServiceUrl}),this._routeController=null,this._serviceDescriptionStatus=O.Idle,this.apiKey=void 0,this.departureTime="now",this.lastRoute=null,this.routeParameters=new D({directionsLengthUnits:"kilometers",findBestSequence:!1,restrictUTurns:"at-dead-ends-and-intersections",returnZ:!0,startTime:null,startTimeIsUTC:!0,useHierarchy:!0,useTimeWindows:!1}),this.routeSymbol=R,this.serviceDescription=null,this.error=null,this.stops=new P,this.view=null}initialize(){this.handles.add([d((()=>this.stops),"change",(()=>{this.clearResults()})),p((()=>{var e;return null==(e=this.view)?void 0:e.map}),((e,t)=>{const r=[this._routeLayer,this._highlightLayer];t&&t.removeMany(r),e&&e.addMany(r)}),h),p((()=>this.routeServiceUrl),(e=>{if(this._routeLayer.url=e,u(this._loadController))return this._loadController.abort(),this._loadController=null,this._loadPromise=null,this._set("serviceDescription",null),void this.load();this._set("serviceDescription",null)}),m)])}destroy(){var e;null==(e=this.view)||e.map.removeMany([this._routeLayer,this._highlightLayer])}get _directionsLanguage(){var e;if(a(this.serviceDescription))return;const t=this.serviceDescription.directionsSupportedLanguages;if(!t)return;const r=(null!=(e=this.routeParameters.directionsLanguage)?e:w()).slice(0,2);return t.find((e=>e.toLowerCase().slice(0,2)===r))}get impedanceAttribute(){var e,t,r;const o=u(this.serviceDescription)?this.serviceDescription.impedance:null,i=null!=(e=null!=(t=null==(r=this.routeParameters.travelMode)?void 0:r.impedanceAttributeName)?t:this.routeParameters.impedanceAttribute)?e:o;return this.getCostAttribute(i)}set maxStops(e){const t=50,r=2;e=e<=r?r:e>t?t:e,this._set("maxStops",e)}get routeLayer(){return this._routeLayer}get routeServiceUrl(){return r.routeServiceUrl}set routeServiceUrl(e){null!=e?this._override("routeServiceUrl",e):this._clearOverride("routeServiceUrl")}get selectedTravelMode(){const{serviceDescription:e}=this;if(a(e))return null;const{defaultTravelMode:t,supportedTravelModes:r=[]}=e;return r.find((e=>e.id===t))||r[0]||null}set selectedTravelMode(e){void 0!==e?this._override("selectedTravelMode",e):this._clearOverride("selectedTravelMode")}get state(){if(u(this._routeController))return"routing";if(u(this.error))return"error";switch(this._serviceDescriptionStatus){case O.Suspended:return"unauthenticated";case O.Idle:return"disabled";case O.Active:return"initializing";case O.Failed:return"error";default:return"ready"}}castStops(e){return z(e)?new i(e.map((e=>T.fromJSON(e.toJSON())))):e}set stopSymbols(e){const t={...x,...e};this._set("stopSymbols",t)}get timeAttribute(){var e,t,r;const o=null!=(e=null!=(t=null==(r=this.routeParameters.travelMode)?void 0:r.timeAttributeName)?t:this.routeParameters.directionsTimeAttribute)?e:u(this.serviceDescription)?this.serviceDescription.directionsTimeAttribute:null;return this.getCostAttribute(o)}get travelModes(){return u(this.serviceDescription)?this.serviceDescription.supportedTravelModes:[]}async load(){if(u(this._loadPromise))return this._loadPromise;this._loadPromise=this._load(),await this._loadPromise,this._loadPromise=null}highlightSegment(e){const{geometry:r,symbol:i}=e;if(a(this.view)||a(r)||a(i))return;this.clearHighlights();const s=i.clone();s.color=new t([0,0,0,.8]),s.width=Math.ceil(s.width/2);const l=new o({geometry:r,symbol:s});this._highlightLayer.add(l)}clearHighlights(){this._highlightLayer.removeAll()}centerAt(e){a(this.view)||this.callGoTo({target:e})}clearResults(){this._set("lastRoute",null)}async getDirections(){const{state:e}=this;if("unauthenticated"===e||"initializing"===e||"disabled"===e||this._serviceDescriptionStatus===O.Failed)return Promise.reject(new s("directions-view-model:not-loaded","Cannot get directions until view model loads."));this._set("error",null),u(this._routeController)&&(this._routeController.abort(),this._routeController=null);const{apiKey:t,departureTime:r}=this,o="now"===r,i="now"===r?new Date:r;if(i&&!o){const e=60*i.getTimezoneOffset()*1e3;i.setTime(i.getTime()-e)}const l=u(this.view)?this.view.spatialReference:null,n=this.routeParameters.clone();if(n.set({startTime:i,startTimeIsUTC:o,directionsLanguage:this._directionsLanguage,apiKey:t,outSpatialReference:l}),u(this.selectedTravelMode)&&(n.travelMode=this.selectedTravelMode),this.stops.length<2){const e=new s("directions-view-model:not-enough-stops","Not enough stops for routing");return this._set("error",e),Promise.reject(e)}this._routeController=new AbortController;const{signal:a}=this._routeController;let d=null;try{d=await this._routeLayer.solve(n,{signal:a}),this._routeLayer.update(d),this._set("lastRoute",d)}catch(p){if(!c(p)){const e=new s("directions-view-model:unable-to-route","Unable to route to these addresses",{error:p});throw this._set("error",e),this._set("lastRoute",null),e}}finally{this._routeController=null}return this.zoomToRoute(),d}getCostAttribute(e){const t=(u(this.serviceDescription)?this.serviceDescription.networkDataset.networkAttributes:[]).find((t=>t.name===e&&"esriNAUTCost"===t.usageType));return null!=t?t:null}reset(){this.clearHighlights(),this.clearResults(),this._routeLayer.removeAll()}zoomToRoute(){const{view:e,lastRoute:t}=this;if(a(e)||a(t))return;const{routeInfo:r}=t;if(a(r))return;const{geometry:o}=r;if(a(o))return;const{extent:i}=o,s=i.width>i.height,l=i.clone().expand(s?2:1);this.callGoTo({target:l})}async _load(){if(u(this.serviceDescription))return;u(this._loadController)&&(this._loadController.abort(),this._loadController=null),this._loadController=new AbortController;const{signal:e}=this._loadController;try{this._serviceDescriptionStatus=O.Active;const t=await C(this.routeServiceUrl,this.apiKey,{signal:e});this._set("serviceDescription",t),this._serviceDescriptionStatus=O.Complete}catch(t){if(c(t))return void(this._serviceDescriptionStatus=O.Idle);if("identity-manager:user-aborted"===t.name)return void(this._serviceDescriptionStatus=O.Suspended);const e=new s("directions-view-model:service-metadata-unavailable","Cannot load route service metadata",{error:t});throw this._serviceDescriptionStatus=O.Failed,this._set("error",e),e}finally{this._loadController=null}}};e([g()],I.prototype,"_directionsLanguage",null),e([g()],I.prototype,"_routeController",void 0),e([g()],I.prototype,"_serviceDescriptionStatus",void 0),e([g()],I.prototype,"apiKey",void 0),e([g()],I.prototype,"departureTime",void 0),e([g({readOnly:!0})],I.prototype,"impedanceAttribute",null),e([g({readOnly:!0})],I.prototype,"lastRoute",void 0),e([g({value:50})],I.prototype,"maxStops",null),e([g()],I.prototype,"routeLayer",null),e([g({type:D,nonNullable:!0})],I.prototype,"routeParameters",void 0),e([g()],I.prototype,"routeServiceUrl",null),e([g()],I.prototype,"routeSymbol",void 0),e([g()],I.prototype,"selectedTravelMode",null),e([g({readOnly:!0})],I.prototype,"serviceDescription",void 0),e([g({readOnly:!0})],I.prototype,"state",null),e([g()],I.prototype,"error",void 0),e([g({type:P,nonNullable:!0}),v("routeLayer.stops")],I.prototype,"stops",void 0),e([y("stops")],I.prototype,"castStops",null),e([g({value:x})],I.prototype,"stopSymbols",null),e([g({readOnly:!0})],I.prototype,"timeAttribute",null),e([g()],I.prototype,"travelModes",null),e([g()],I.prototype,"view",void 0),e([g()],I.prototype,"getDirections",null),e([g()],I.prototype,"zoomToRoute",null),I=e([f("esri.widgets.Directions.DirectionsViewModel")],I);const F=I;export{F as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../Color.js";import r from"../../config.js";import o from"../../Graphic.js";import"../../symbols.js";import i from"../../core/Collection.js";import s from"../../core/Error.js";import l from"../../core/Evented.js";import{HandleOwnerMixin as n}from"../../core/HandleOwner.js";import{isNone as a,isSome as u,unwrap as c}from"../../core/maybe.js";import{isAbortError as d}from"../../core/promiseUtils.js";import{on as p,watch as h,initial as m,syncAndInitial as v}from"../../core/reactiveUtils.js";import{aliasOf as y}from"../../core/accessorSupport/decorators/aliasOf.js";import"../../core/arrayUtils.js";import"../../core/has.js";import{cast as g}from"../../core/accessorSupport/decorators/cast.js";import{property as f}from"../../core/accessorSupport/decorators/property.js";import{subclass as w}from"../../core/accessorSupport/decorators/subclass.js";import{getLocale as _}from"../../intl/locale.js";import S from"../../layers/GraphicsLayer.js";import b from"../../layers/RouteLayer.js";import C from"../../layers/support/DefaultSymbols.js";import{fetchServiceDescription as D}from"../../rest/networkService.js";import T from"../../rest/support/RouteParameters.js";import j from"../../rest/support/Stop.js";import{GoToMixin as L}from"../support/GoTo.js";import M from"../../symbols/SimpleLineSymbol.js";import A from"../../symbols/SimpleMarkerSymbol.js";import P from"../../symbols/PictureMarkerSymbol.js";function z(e){return Array.isArray(e)&&e.length>0&&e[0]instanceof o}function U(e){return i.isCollection(e)&&e.length>0&&e.getItemAt(0)instanceof o}function R(e){return"esri.rest.support.Stop"===(null==e?void 0:e.declaredClass)}const x=[105,220,255],O=new M({color:x,width:7,cap:"round",join:"round"}),I={first:new A({color:x,size:19,outline:{color:[51,51,51],width:3}}),middle:new A({color:[51,51,51],size:12,outline:{color:x,width:3}}),last:new P({width:23,height:23,url:`data:image/svg+xml;base64,${btoa('<svg width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg"><g fill-rule="nonzero" fill="none"><path d="M15.15.3C6.9.3.3 6.9.3 15.15S6.9 29.7 15.15 29.7 29.7 23.1 29.7 15.15C29.7 6.9 23.25.3 15.15.3z" fill="#333"/><path d="M15 4.8C9.3 4.8 4.8 9.45 4.8 15c0 5.55 4.65 10.2 10.2 10.2 5.55 0 10.2-4.5 10.2-10.2 0-5.55-4.5-10.2-10.2-10.2z" fill="#69DCFF"/><path fill="#333" d="M10.5 10.5h9v9h-9z"/></g></svg>')}`}),unlocated:new P({height:18,width:18,url:`data:image/svg+xml;base64,${btoa('<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><path d="M10.1.2C4.6.2.2 4.6.2 10.1s4.4 9.7 9.9 9.7 9.7-4.4 9.7-9.7c0-5.5-4.3-9.9-9.7-9.9z" fill="#333" fill-rule="nonzero"/><path d="M10 2.7c-4.08 0-7.3 3.328-7.3 7.3s3.328 7.3 7.3 7.3 7.3-3.22 7.3-7.3c0-3.972-3.22-7.3-7.3-7.3z" fill="#69DCFF" fill-rule="nonzero"/><path d="M11.414 10l5.304-5.303-1.415-1.415L10 8.586 4.697 3.282 3.282 4.697 8.586 10l-5.304 5.303 1.415 1.415L10 11.414l5.303 5.304 1.415-1.415L11.414 10z" fill="#333"/></g></svg>')}`}),waypoint:new A({color:[255,255,255],size:10,outline:{color:[20,89,127],width:2.5}})};var F;!function(e){e[e.Active=0]="Active",e[e.Complete=1]="Complete",e[e.Failed=2]="Failed",e[e.Idle=3]="Idle",e[e.Suspended=4]="Suspended"}(F||(F={}));let k=class extends(n(L(l.EventedAccessor))){constructor(e){super(e),this._highlightLayer=new S({listMode:"hide"}),this._loadPromise=null,this._loadController=null,this._routeLayer=new b({listMode:"hide",defaultSymbols:new C({directionLines:O,directionPoints:new A({size:0}),routeInfo:new M({width:0}),firstStop:I.first,middleStop:I.middle,lastStop:I.last,invalidStop:I.unlocated,waypointStop:I.waypoint,breakStop:I.waypoint}),url:this.routeServiceUrl}),this._routeController=null,this._serviceDescriptionStatus=F.Idle,this.apiKey=void 0,this.departureTime="now",this.lastRoute=null,this.routeParameters=new T({directionsLengthUnits:"kilometers",findBestSequence:!1,restrictUTurns:"at-dead-ends-and-intersections",returnZ:!0,startTime:null,startTimeIsUTC:!0,useHierarchy:!0,useTimeWindows:!1}),this.routeSymbol=O,this.serviceDescription=null,this.error=null,this.view=null}initialize(){this.handles.add([p((()=>this.stops),"change",(()=>{this.clearResults()})),h((()=>{var e;return null==(e=this.view)?void 0:e.map}),((e,t)=>{const r=[this._routeLayer,this._highlightLayer];t&&t.removeMany(r),e&&e.addMany(r)}),m),h((()=>this.routeServiceUrl),(e=>{if(this._routeLayer.url=e,u(this._loadController))return this._loadController.abort(),this._loadController=null,this._loadPromise=null,this._set("serviceDescription",null),void this.load();this._set("serviceDescription",null)}),v)])}destroy(){var e;null==(e=this.view)||e.map.removeMany([this._routeLayer,this._highlightLayer])}get _directionsLanguage(){var e;if(a(this.serviceDescription))return;const t=this.serviceDescription.directionsSupportedLanguages;if(!t)return;const r=(null!=(e=this.routeParameters.directionsLanguage)?e:_()).slice(0,2);return t.find((e=>e.toLowerCase().slice(0,2)===r))}get impedanceAttribute(){var e,t,r;const o=u(this.serviceDescription)?this.serviceDescription.impedance:null,i=null!=(e=null!=(t=null==(r=this.routeParameters.travelMode)?void 0:r.impedanceAttributeName)?t:this.routeParameters.impedanceAttribute)?e:o;return this.getCostAttribute(i)}set maxStops(e){const t=50,r=2;e=e<=r?r:e>t?t:e,this._set("maxStops",e)}get routeLayer(){return this._routeLayer}get routeServiceUrl(){return r.routeServiceUrl}set routeServiceUrl(e){null!=e?this._override("routeServiceUrl",e):this._clearOverride("routeServiceUrl")}get selectedTravelMode(){const{serviceDescription:e}=this;if(a(e))return null;const{defaultTravelMode:t,supportedTravelModes:r=[]}=e;return r.find((e=>e.id===t))||r[0]||null}set selectedTravelMode(e){void 0!==e?this._override("selectedTravelMode",e):this._clearOverride("selectedTravelMode")}get state(){if(u(this._routeController))return"routing";if(u(this.error))return"error";switch(this._serviceDescriptionStatus){case F.Suspended:return"unauthenticated";case F.Idle:return"disabled";case F.Active:return"initializing";case F.Failed:return"error";default:return"ready"}}castStops(e){return z(e)||U(e)?e.map((e=>j.fromPortalJSON(e.toJSON()))):e}set stopSymbols(e){const t={...I,...e};this._set("stopSymbols",t)}get timeAttribute(){var e,t,r;const o=null!=(e=null!=(t=null==(r=this.routeParameters.travelMode)?void 0:r.timeAttributeName)?t:this.routeParameters.directionsTimeAttribute)?e:u(this.serviceDescription)?this.serviceDescription.directionsTimeAttribute:null;return this.getCostAttribute(o)}get travelModes(){return u(this.serviceDescription)?this.serviceDescription.supportedTravelModes:[]}async load(){if(u(this._loadPromise))return this._loadPromise;this._loadPromise=this._load(),await this._loadPromise,this._loadPromise=null}highlightSegment(e){const{geometry:r,symbol:i}=e;if(a(this.view)||a(r)||a(i))return;this.clearHighlights();const s=i.clone();s.color=new t([0,0,0,.8]),s.width=Math.ceil(s.width/2);const l=new o({geometry:r,symbol:s});this._highlightLayer.add(l)}clearHighlights(){this._highlightLayer.removeAll()}centerAt(e){if(a(this.view))return;const t=R(e)?c(e.geometry):e;this.callGoTo({target:t})}clearResults(){this._set("lastRoute",null)}async getDirections(){const{state:e}=this;if("unauthenticated"===e||"initializing"===e||"disabled"===e||this._serviceDescriptionStatus===F.Failed)return Promise.reject(new s("directions-view-model:not-loaded","Cannot get directions until view model loads."));this._set("error",null),u(this._routeController)&&(this._routeController.abort(),this._routeController=null);const{apiKey:t,departureTime:r}=this,o="now"===r,i="now"===r?new Date:r;if(i&&!o){const e=60*i.getTimezoneOffset()*1e3;i.setTime(i.getTime()-e)}const l=u(this.view)?this.view.spatialReference:null,n=this.routeParameters.clone();if(n.set({startTime:i,startTimeIsUTC:o,directionsLanguage:this._directionsLanguage,apiKey:t,outSpatialReference:l}),u(this.selectedTravelMode)&&(n.travelMode=this.selectedTravelMode),this.stops.length<2){const e=new s("directions-view-model:not-enough-stops","Not enough stops for routing");return this._set("error",e),Promise.reject(e)}this._routeController=new AbortController;const{signal:a}=this._routeController;let c=null;try{c=await this._routeLayer.solve(n,{signal:a}),this._routeLayer.update(c),this._set("lastRoute",c)}catch(p){if(!d(p)){const e=new s("directions-view-model:unable-to-route","Unable to route to these addresses",{error:p});throw this._set("error",e),this._set("lastRoute",null),e}}finally{this._routeController=null}return this.zoomToRoute(),c}getCostAttribute(e){const t=(u(this.serviceDescription)?this.serviceDescription.networkDataset.networkAttributes:[]).find((t=>t.name===e&&"esriNAUTCost"===t.usageType));return null!=t?t:null}reset(){this.clearHighlights(),this.clearResults(),this._routeLayer.removeAll()}zoomToRoute(){const{view:e,lastRoute:t}=this;if(a(e)||a(t))return;const{routeInfo:r}=t;if(a(r))return;const{geometry:o}=r;if(a(o))return;const{extent:i}=o,s=i.width>i.height,l=i.clone().expand(s?2:1);this.callGoTo({target:l})}async _load(){if(u(this.serviceDescription))return;u(this._loadController)&&(this._loadController.abort(),this._loadController=null),this._loadController=new AbortController;const{signal:e}=this._loadController;try{this._serviceDescriptionStatus=F.Active;const t=await D(this.routeServiceUrl,this.apiKey,{signal:e});this._set("serviceDescription",t),this._serviceDescriptionStatus=F.Complete}catch(t){if(d(t))return void(this._serviceDescriptionStatus=F.Idle);if("identity-manager:user-aborted"===t.name)return void(this._serviceDescriptionStatus=F.Suspended);const e=new s("directions-view-model:service-metadata-unavailable","Cannot load route service metadata",{error:t});throw this._serviceDescriptionStatus=F.Failed,this._set("error",e),e}finally{this._loadController=null}}};e([f()],k.prototype,"_directionsLanguage",null),e([f()],k.prototype,"_routeController",void 0),e([f()],k.prototype,"_serviceDescriptionStatus",void 0),e([f()],k.prototype,"apiKey",void 0),e([f()],k.prototype,"departureTime",void 0),e([f({readOnly:!0})],k.prototype,"impedanceAttribute",null),e([f({readOnly:!0})],k.prototype,"lastRoute",void 0),e([f({value:50})],k.prototype,"maxStops",null),e([f()],k.prototype,"routeLayer",null),e([f({type:T,nonNullable:!0})],k.prototype,"routeParameters",void 0),e([f()],k.prototype,"routeServiceUrl",null),e([f()],k.prototype,"routeSymbol",void 0),e([f()],k.prototype,"selectedTravelMode",null),e([f({readOnly:!0})],k.prototype,"serviceDescription",void 0),e([f({readOnly:!0})],k.prototype,"state",null),e([f()],k.prototype,"error",void 0),e([y("routeLayer.stops")],k.prototype,"stops",void 0),e([g("stops")],k.prototype,"castStops",null),e([f({value:I})],k.prototype,"stopSymbols",null),e([f({readOnly:!0})],k.prototype,"timeAttribute",null),e([f()],k.prototype,"travelModes",null),e([f()],k.prototype,"view",void 0),e([f()],k.prototype,"getDirections",null),e([f()],k.prototype,"zoomToRoute",null),k=e([w("esri.widgets.Directions.DirectionsViewModel")],k);const N=k;export{N as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.23/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 s from"../core/Collection.js";import{on as i,pausable as o}from"../core/events.js";import r from"../core/Handles.js";import{isNone as n,isSome as a,unwrap as l,unwrapOrValue as c}from"../core/maybe.js";import{watch as d,initial as h,when as u,on as p}from"../core/reactiveUtils.js";import{aliasOf as m}from"../core/accessorSupport/decorators/aliasOf.js";import"../core/arrayUtils.js";import"../core/has.js";import"../core/accessorSupport/ensureType.js";import{property as v}from"../core/accessorSupport/decorators/property.js";import{subclass as _}from"../core/accessorSupport/decorators/subclass.js";import g from"../rest/support/Stop.js";import S from"./Search.js";import w from"./Widget.js";import y from"./Directions/DirectionsViewModel.js";import{formatDistance as b,formatTime as M,isTimeUnits as f}from"./Directions/support/directionsUtils.js";import{DepartureTime as T,CSS as C,getIconPath as I}from"./Directions/support/resources.js";import{isArcGISWorldGeocoder as k,meteredArcGISLocatorUrl as R}from"./Search/support/locatorUtils.js";import D from"./support/DatePicker.js";import{Heading as P,incrementHeadingLevel as j}from"./support/Heading.js";import x from"./support/TimePicker.js";import{accessibleHandler as H}from"./support/decorators/accessibleHandler.js";import{messageBundle as U}from"./support/decorators/messageBundle.js";import"../core/Logger.js";import{tsx as L}from"./support/jsxFactory.js";import"./support/widgetUtils.js";import A from"sortablejs";import{substitute as z}from"../intl/substitute.js";import{formatDate as E,convertDateFormatToIntlOptions as O}from"../intl/date.js";import{formatNumber as $}from"../intl/number.js";function N(e){const t=e.getTimezoneOffset(),s=t>0?"-":"+",i=60,o=Math.abs(Math.floor(t/i)),r=Math.abs(Math.floor(t)%i),n={minimumIntegerDigits:2};return`GMT${s}${$(o,n)}${$(r,n)}`}function B(){return[{},{}]}function F(e){return e.results[0].results[0]}function V(e){return!(null==e.composedPath||!e.composedPath().find((e=>{var t;return null==(t=e.classList)?void 0:t.contains("esri-search__suggestions-list")})))}const W={awaitingViewClickStop:"awaiting-view-click-stop"},K=100,q=500;let Y=class extends w{constructor(e,t){super(e,t),this._autoStopRemovalDelay=K,this._departureTime=T.NOW,this._datePicker=new D,this._handles=new r,this._newPlaceholderStop=null,this._pointerPressedSearchSuggestionStop=null,this._sections=null,this._stops=new s(B()),this._stopsToSearches=new Map,this._timePicker=new x,this.apiKey=null,this.goToOverride=null,this.headingLevel=2,this.iconClass=C.widgetIcon,this.label=void 0,this.lastRoute=null,this.maxStops=null,this.messages=null,this.messagesCommon=null,this.messagesUnits=null,this.routeServiceUrl=void 0,this.routeSymbol=null,this.searchProperties=null,this.stopSymbols=null,this.view=null,this.viewModel=new y,this._setUpDragAndDropStops=e=>{this._sortable=A.create(e,{draggable:`.${C.validStopRow}`,ghostClass:C.stopRowGhost,handle:`.${C.stopHandle}`,onEnd:this._handleStopInputDragEnd})},this._handleDragHandlePointerDown=()=>this._stops.forEach((e=>this._acquireSearch(e).activeMenu="none")),this._handleStopInputDragEnd=({oldIndex:e,newIndex:t,target:s})=>{if(e===t)return;const{children:i}=s,o=i[t],r=i[e],n=t-e<0;s.insertBefore(o,n?r.nextElementSibling:r);const a=this._stops;a.reorder(a.getItemAt(e),t),this._processStops()}}initialize(){this.own([d((()=>this.viewModel.lastRoute),(()=>{this._activeManeuver=null,this._focusedManeuver=null,this._sections=this._getSections(),this.scheduleRender()}),h),d((()=>[this.viewModel.selectedTravelMode,this.viewModel.departureTime]),(()=>{this.viewModel.stops.length>1&&this.getDirections()}),h),u((()=>this.view),((e,t)=>{if(t&&(this._viewClickHandle=null,this._handles.remove(t)),e){const t=this._prepPointerDownUpClick(),s=this._prepViewClick();t.pause(),s.pause(),this._handles.add([i(e.surface,"mousedown",(()=>this._autoStopRemovalDelay=q)),i(e.surface,"mouseup",(()=>this._autoStopRemovalDelay=K)),t,s],this.view.surface),this._pointerDownUpHandle=t,this._viewClickHandle=s}}),h),u((()=>0===this.viewModel.stops.length),(()=>{this._stops.drain((e=>{this._disposeSearch(e)})),this._stops.addMany(B()),this.scheduleRender()})),u((()=>n(this.viewModel.serviceDescription)),(()=>{this.viewModel.load()}),h)])}destroy(){this._datePicker.destroy(),this._timePicker.destroy(),this._stopsToSearches.forEach((e=>e.destroy())),this._sortable&&this._sortable.destroy()}getDirections(){return null}zoomToRoute(){}render(){return L("div",{class:this.classes(C.base,C.scroller)},this._renderPanelContent())}_renderPanelContent(){const{viewModel:{state:e}}=this,t="initializing"===e,s="error"===e&&!this.viewModel.serviceDescription,i="unauthenticated"===e,o={[C.panelContentLoading]:t,[C.panelContentError]:s,[C.panelContentSignIn]:i},r=t?"presentation":"group",n=i?this._renderSignIn():s?this._renderMessage(this._getErrorMessage()):t?this._renderLoader():this._renderReadyContent();return L("div",{class:this.classes(C.panelContent,o),role:r},n)}_renderReadyContent(){return[this._renderStopsContainer(),this._renderTravelModeOptions(),this._renderDepartureTimeControls(),this._renderSectionSplitter(),this._renderDirectionsContainer()]}_renderSignIn(){return L("div",{key:"sign-in",class:C.signInContent},L(P,{class:C.contentTitle,level:this.headingLevel},this.messages.widgetLabel),this._renderPlaceholder(),L(P,{level:j(this.headingLevel)},this.messages.signInRequired),L("button",{class:this.classes(C.button,C.buttonSecondary,C.signInButton),tabIndex:0,onclick:this._handleSignInClick,bind:this,type:"button"},this.messagesCommon.auth.signIn))}_handleSignInClick(){this.viewModel.load().catch((()=>{}))}_renderTravelModeOptions(){const{selectedTravelMode:e,travelModes:t}=this.viewModel;if(0===t.length)return null;const s=a(e)?e.name:this.messages.travelMode;return L("select",{"aria-label":s,bind:this,class:this.classes(C.travelModeSelect,C.select),key:"esri-directions__travel-mode-options",onchange:this._handleTravelModeChange,title:s},t.map((t=>{const s=a(e)&&t.id===e.id;return L("option",{key:t,"data-mode":t,selected:s,value:t.id},t.name)})))}_handleTravelModeChange(e){const t=e.currentTarget,s=t.item(t.selectedIndex);this.viewModel.selectedTravelMode=s["data-mode"]}_renderStopsContainer(){return L("div",{class:C.section,key:"esri-directions__stops-container",role:"group"},this._renderStops())}_renderDepartureTimeControls(){const e=this._departureTime,{messages:t}=this,s=t.departureTime;return L("div",{class:C.departureTime,key:"esri-directions__departure-time-controls",role:"group"},L("select",{"aria-label":s,bind:this,class:this.classes(C.departureTimeSelect,C.select),onchange:this._handleDepartureOptionChange,title:s},L("option",{value:T.NOW,selected:e===T.NOW},t.leaveNow),L("option",{value:T.DEPART_BY,selected:e===T.DEPART_BY},t.departBy),L("option",{value:T.UNSPECIFIED,selected:e===T.UNSPECIFIED},t.timeUnspecified)),e===T.DEPART_BY?this._renderTimeControls():null)}_renderStops(){const e=this._stops;let t=0;e.forEach((e=>{"none"!==this._acquireSearch(e).activeMenu&&(t+=1)}));const s=e.toArray().map(((s,i)=>{const o=e.length,r=i>1&&!s.result,n={[C.stopsIcon]:i>=0&&i<o-1,[C.lastStopIcon]:i===o-1},a={[C.lastStopIconContainer]:i===o-1},l={[C.validStopRow]:!r},c=e.getItemAt(o-1),d=c&&c.result,h=e.getItemAt(i+1),u=h&&h.result,p=i===o-1,m=i===o-2,v=2===o&&0===i||o>2&&!p&&!m||o>2&&m&&u||o>2&&p&&!s.result,_=2===o||3===o&&!d||r,g=this._acquireSearch(s),{messages:S}=this,{removeStop:w,reverseStops:y,unlocated:b}=S,M=z(S.stopLabelTemplate,{number:i+1,label:s.result?s.result.name:b}),f=`${this.id}__stop--${i}`,T=!!g.searchTerm&&!!g.selectedResult&&!!s.result&&g.selectedResult===s.result,I={zIndex:"none"!==g.activeMenu?""+t--:""};return L("li",{"aria-label":M,afterCreate:this._handleStopFieldCreation,bind:this,class:this.classes(C.stopRow,l),id:f,key:i,"data-stop-index":i,styles:I},L("div",{class:C.stopHandle},L("span",{"aria-hidden":"true",class:this.classes(C.stopIcon,C.handleIcon,C.stopHandleIcon,C.interactiveStopIcon),onpointerdown:this._handleDragHandlePointerDown}),L("div",{bind:this,"aria-labelledby":f,class:this.classes(C.stopIconContainer,a),"data-stop-index":i,onclick:this._handleStopIconClick,onkeydown:this._handleStopIconClick,role:"button"},L("span",{class:this.classes(C.stopIcon,n),tabindex:T?"0":null}))),L("div",{class:C.stopInput},g.render()),L("div",{class:C.stopOptions,role:"group"},L("div",{"aria-label":w,class:C.removeStopButton,bind:this,"data-stop-index":i,hidden:_,onkeydown:this._handleRemoveStop,onclick:this._handleRemoveStop,role:"button",tabIndex:0,title:w},L("span",{"aria-hidden":"true",class:this.classes(C.stopIcon,C.removeStop,C.removeStopIcon,C.interactiveStopIcon)}),L("span",{class:C.screenReaderText},"removeStopTitle")),L("div",{"aria-label":y,class:C.reverseStops,bind:this,hidden:v,onkeydown:this._handleReverseStops,onclick:this._handleReverseStops,role:"button",tabIndex:0,title:y},L("span",{"aria-hidden":"true",class:this.classes(C.stopIcon,C.reverseStopIcon,C.interactiveStopIcon)}),L("span",{class:C.screenReaderText},"removeStopTitle"))))})),i=e.every((e=>{const t=this._stopsToSearches.get(e);return e.result&&t.selectedResult===e.result})),o=this._stops.length>=this.maxStops,r=this.messages.addStop,n=e.length>=2&&i&&!o?L("div",{"aria-label":r,bind:this,class:C.addStop,key:"esri-directions__add-stop",onfocus:this._handleAddStopFocus,tabIndex:0},L("span",{"aria-hidden":"true",class:this.classes(C.addStopIcon,C.stopIcon,C.interactiveStopIcon)}),L("div",{"aria-hidden":"true",class:C.addStopText},r)):null;return L("div",null,L("ol",{class:C.stops,role:"group",afterCreate:this._setUpDragAndDropStops},s),n)}_handleStopIconClick(e){const t=e.currentTarget["data-stop-index"],s=this._stops.getItemAt(t);s&&s.result&&this._centerAtStop(s)}_handleClearRouteClick(){this.viewModel.reset()}_centerAtStop(e){this.viewModel.centerAt(e.result.feature)}_handleStopFieldCreation(e){const t=this._newPlaceholderStop;if(!t)return;const s=e["data-stop-index"],i=this._stops.getItemAt(s);if(t===i){const e=this._acquireSearch(i);e.when((()=>{this.renderNow(),e.focus()}))}this._newPlaceholderStop=null}_handleStopInputBlur(e,t){this._handles.remove(W.awaitingViewClickStop),this.view.cursor=this._previousCursor;if(!e.selectedResult||!t.result||e.selectedResult!==t.result)return"none"!==e.activeMenu||!e.searchTerm||e.selectedResult===t.result&&(e.selectedResult||t.result)?void(e.searchTerm||(this._viewClickHandle.resume(),clearTimeout(this._autoStopRemovalTimeoutId),this._autoStopRemovalTimeoutId=setTimeout((()=>{if(this.destroyed)return;if(this._viewClickHandle.pause(),"searching"===e.viewModel.state)return void this._pointerDownUpHandle.pause();if(this._pointerPressedSearchSuggestionStop)return;!!t.result&&(t.result=null,this._processStops()),this.scheduleRender()}),this._autoStopRemovalDelay))):(e.search(),void this._pointerDownUpHandle.pause());this._pointerDownUpHandle.pause()}_handleStopInputFocus(e,t){if(this._pointerDownUpHandle.resume(),this._handles.has(W.awaitingViewClickStop))return;const{view:s,view:{cursor:i}}=this;this._previousCursor=i,this._handles.add(d((()=>e.searchTerm),(e=>{s.cursor=0===e.length?"copy":i}),h),W.awaitingViewClickStop),this._activeStop=t}_prepViewClick(){const{view:e}=this.viewModel,t=o(e,"click",this._handleViewClick.bind(this)),s=o(e.surface,"click",(()=>{clearTimeout(this._autoStopRemovalTimeoutId),s.pause()}));return{remove(){s.remove(),t.remove()},pause(){s.pause(),t.pause()},resume(){s.resume(),t.resume()}}}_prepPointerDownUpClick(){const e=o(document,"pointerdown",(e=>{this._pointerPressedSearchSuggestionStop=V(e)?this._activeStop:null})),t=o(document,"pointerup",(e=>{this._pointerDownUpHandle.pause();const t=V(e),s=this._activeStop;t||s!==this._pointerPressedSearchSuggestionStop||this._removeStop(s),this.scheduleRender(),this._pointerPressedSearchSuggestionStop=t?this._activeStop:null}));return{remove(){t.remove(),e.remove()},pause(){t.pause(),e.pause()},resume(){e.resume()}}}_handleViewClick(e){const t=this._stopsToSearches.get(this._activeStop);t&&!t.searchTerm&&(t.search(e.mapPoint).then((e=>{const s=F(e),i=this._activeStop;i.result=s,i.result.feature.attributes.Name=s.name,t.searchTerm=s.name})),this.scheduleRender()),this._viewClickHandle.pause(),clearTimeout(this._autoStopRemovalTimeoutId)}_handleAddStopFocus(){this._addNewPlaceholder()}_addNewPlaceholder(){if(this._pointerDownUpHandle.pause(),this._newPlaceholderStop)return;const e={};this._stops.add(e),this._newPlaceholderStop=e}_handleReverseStops(){this._reverseStops()}_reverseStops(){this._stops.reverse(),this._processStops()}_handleRemoveStop(e){const t=e.currentTarget["data-stop-index"];this._removeStop(this._stops.getItemAt(t)),this._processStops()}_removeStop(e){this._stops.length<=2||(this._disposeSearch(e),this._stops.remove(e))}_handleDepartureOptionChange(e){const t=e.currentTarget,s=t.item(t.selectedIndex);s.value===T.NOW?(this._departureTime=T.NOW,this.viewModel.departureTime=T.NOW,this._handles.remove("departure-time-controls")):s.value===T.DEPART_BY?(this._departureTime=T.DEPART_BY,this._handles.add([d((()=>this._datePicker.value),(()=>this._updateDepartureTime()),h),d((()=>this._timePicker.value),(()=>this._updateDepartureTime()),h)],"departure-time-controls")):(this._departureTime=T.UNSPECIFIED,this.viewModel.departureTime=null)}_updateDepartureTime(){const e=this._datePicker.value,t=this._timePicker.value;e&&t&&(this.viewModel.departureTime=new Date(e.getFullYear(),e.getMonth(),e.getDate(),t.getHours(),t.getMinutes()))}_renderTimeControls(){return L("div",{class:C.departureTimeControls,key:"esri-directions__time-controls",role:"group"},this._datePicker.render(),this._timePicker.render())}_renderSectionSplitter(){return L("div",{class:C.sectionSplitter})}_renderDirectionsContainer(){return L("div",{class:this.classes(C.directionsSection,C.section),key:"esri-directions__container"},this._renderDirectionsContainerContent())}_renderLoader(){return L("div",{class:C.loader,key:"loader"})}_renderWarningCard(){return L("div",{class:C.warningCard,role:"alert"},L("div",{class:C.warningHeader},L("span",{class:C.warningIcon,"aria-hidden":"true"}),L(P,{class:C.warningHeading,level:this.headingLevel},this.messagesCommon.warning)),L("div",{class:C.warningMessage},this._getErrorMessage()))}_renderDirectionsContainerContent(){const{lastRoute:e,viewModel:{state:t}}=this,s="routing"===t;return"error"===t?this._renderWarningCard():s?this._renderLoader():a(e)&&a(e.directionLines)?L("div",{class:C.summary,key:"esri-directions__summary",role:"group"},this._renderCosts(),this._renderRouteActions(),this._renderManeuverSections()):L("div",{key:"esri-directions__placeholder",class:C.emptyContent},this._renderPlaceholder(),L(P,{class:C.message,level:this.headingLevel},this.messages.directionsPlaceholder))}_renderPlaceholder(){return L("svg",{class:C.emptyIllustration,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256"},L("path",{fill:"currentcolor",d:"M192 36c-15.477 0-24 6.034-24 16.99v45.822l24 24 24-24v-45.82C216 42.033 207.477 36 192 36zm20 61.155l-20 20-20-20V52.99c0-8.62 6.73-12.99 20-12.99s20 4.37 20 12.99zM192 52a12 12 0 1 0 12 12 12.013 12.013 0 0 0-12-12zm0 20a8 8 0 1 1 8-8 8.008 8.008 0 0 1-8 8zM92 140.99C92 130.035 83.477 124 68 124s-24 6.034-24 16.99v45.822l24 24 24-24zm-4 44.165l-20 20-20-20V140.99c0-8.62 6.73-12.99 20-12.99s20 4.37 20 12.99zM68 140a12 12 0 1 0 12 12 12.013 12.013 0 0 0-12-12zm0 20a8 8 0 1 1 8-8 8.008 8.008 0 0 1-8 8zm84-44h16v4h-16zm-24 80h4v12h-12v-4h8zm0-28h4v16h-4zm0-52h12v4h-8v8h-4zm0 24h4v16h-4zm-36 64h16v4H92z"}))}_renderMessage(e){return L(P,{level:this.headingLevel},e)}_renderRouteActions(){return L("div",{class:C.routeActions},L("button",{"aria-label":this.messages.clearRoute,class:this.classes(C.clearRouteButton,C.button,C.buttonTertiary),tabIndex:0,onclick:this._handleClearRouteClick,bind:this,type:"button"},this.messages.clearRoute))}_getSections(){if(n(this.lastRoute))return null;const{directionPoints:e,directionLines:t,stops:s}=this.lastRoute;if(n(e)||n(t))return null;const i=[];let o=null;for(const r of e){const{objectId:e,stopId:l}=r;if(a(l)){const e=s.find((e=>e.objectId===l)),t=0===i.length;(n(o)||o.stop!==e)&&(o={stop:e,directions:[],open:t},i.push(o));continue}if(n(o))continue;const c=t.find((t=>t.directionPointId===e));n(c)||o.directions.push({directionPoint:r,directionLine:c})}return i}_renderManeuverSections(){return n(this._sections)?null:L("div",{class:C.maneuvers,role:"group"},this._sections.map(((e,t)=>{const{open:s}=e;let i;e.directions.length>0&&s&&(i=L("ol",{class:C.maneuverList},e.directions.map((e=>this._renderManeuver(e)))));const o=l(this._sections).length>2,r=t===l(this._sections).length-1,n={[C.collapsibleSection]:o},a={[C.openIcon]:!s,[C.closeIcon]:s};let c;if(o&&!r){const t=s?this.messagesCommon.open:this.messagesCommon.close;c=L("header",{class:this.classes(C.maneuverSectionHeader,C.maneuverSectionToggle),key:"esri-directions__maneuver-section-header"},L("div",{"aria-expanded":s.toString(),"aria-label":t,bind:this,class:C.maneuverSectionHeaderButton,"data-maneuver-section":e,onkeydown:this._handleSectionToggle,onclick:this._handleSectionToggle,role:"button",tabIndex:0,title:t},L(P,{class:C.maneuverSectionTitle,level:this.headingLevel},e.stop.name),L("span",{"aria-hidden":"true",class:this.classes(a)})))}else c=L("header",{class:C.maneuverSectionHeader,key:"esri-directions__maneuver-section-header"},L(P,{class:C.maneuverSectionTitle,level:this.headingLevel},e.stop.name));return L("section",{class:this.classes(C.maneuverSection,n),key:t},c,i)})))}_handleSectionToggle(e){const t=e.currentTarget["data-maneuver-section"];t.open=!t.open}_renderCosts(){const{lastRoute:e}=this;if(n(e))return null;const t=this._getCostSummary(),{directionPoints:s}=e;if(n(s)||n(t))return null;const i=s.getItemAt(s.length-1).arrivalTime,{primary:o,secondary:r}=t,{eta:l,etaTemplate:c,primaryCosts:d,secondaryCosts:h,zoomToRoute:u}=this.messages,p=O("short-time"),m=a(i)?`<strong>${E(i,p)}</strong>`:null,v=a(i)?`${N(i)}`:null,_=z(c,{time:m,gmt:v});return L("div",{"aria-label":u,bind:this,class:C.directionCosts,onkeydown:this._handleSummaryInteraction,onclick:this._handleSummaryInteraction,role:"button",tabIndex:0,title:u},L("div",{class:C.costsDetails,role:"group"},L("div",{"aria-label":d,class:C.primaryCosts,title:d},o),L("div",{class:C.verticalSplitter}),L("div",{"aria-label":h,class:C.secondaryCosts,title:h},r)),L("div",{"aria-label":l,innerHTML:_,title:l}))}_handleSummaryInteraction(){this._activeManeuver=null,this._focusedManeuver=null,this.viewModel.clearHighlights(),this.zoomToRoute()}_getErrorMessage(){const{messages:e,viewModel:{error:t}}=this;if(a(t))switch(t.name){case"directions-view-model:unable-to-route":return e.errors.unableToRoute;case"directions-view-model:service-metadata-unavailable":return e.errors.unableToLoadServiceMetadata}return e.errors.unknownError}_normalizeSearchSources(e){this._overrideDefaultSources(e),this._applyLocatorSourceOverrides(e)}_overrideDefaultSources(e){e.viewModel.defaultSources.forEach((e=>{e.autoNavigate=!1}))}_applyLocatorSourceOverrides({allSources:e}){0!==e.length&&e.forEach((e=>{"url"in e&&e.url&&(null===e.locationType&&(e.locationType="street"),k(e.url)&&this.apiKey&&null==e.apiKey&&(e.apiKey=this.apiKey,e.url=R))}))}_acquireSearch(e){const t=this.get("viewModel.view");if(this._stopsToSearches.has(e)){const s=this._stopsToSearches.get(e);return s.view=t,this._overrideDefaultSources(s),s}const s=new S({view:t,resultGraphicEnabled:!1,popupEnabled:!1,...this.searchProperties});return this._normalizeSearchSources(s),this._handles.add([p((()=>s.allSources),"change",(()=>this._normalizeSearchSources(s))),s.on("select-result",(()=>{e.result=s.selectedResult,e.result.feature.attributes.Name=s.selectedResult.name,this._processStops(),this.scheduleRender()})),s.on("search-focus",(()=>this._handleStopInputFocus(s,e))),s.on("search-blur",(()=>this._handleStopInputBlur(s,e)))],s),this._stopsToSearches.set(e,s),s}_disposeSearch(e){this._stopsToSearches.get(e).destroy(),this._stopsToSearches.delete(e)}_processStops(){const e=this._stops.filter((e=>!!e.result)).map((e=>g.fromJSON(e.result.feature.toJSON())));switch(e.length){case 0:break;case 1:e.getItemAt(0).symbol=this.stopSymbols.first;break;case 2:e.getItemAt(0).symbol=this.stopSymbols.first,e.getItemAt(1).symbol=this.stopSymbols.last;break;default:e.forEach(((t,s)=>{switch(s){case 0:t.symbol=this.stopSymbols.first;break;case e.length-1:t.symbol=this.stopSymbols.last;break;default:t.symbol=this.stopSymbols.middle}}))}this.viewModel.stops=e,e.length>1&&this.getDirections()}_renderManeuver(e){const t="",{directionsLengthUnits:s}=this.viewModel.routeParameters,{directionPoint:i,directionLine:o}=e,{distance:r,duration:n}=o,{messages:l,messagesUnits:d}=this,h=b(l,d,c(r,0),{fromUnits:"meters",toUnits:s}),u=M(c(n,0),"minutes"),p=h&&u?`${h}&nbsp;&middot;&nbsp;${u}`:`${h}${u}`,m=this._getFormattedManeuverText(i),{objectId:v,directionPointType:_}=i,g=I(_),S=`esri-directions__maneuver-${v}`,w=`esri-directions__cumulative-costs-${v}`,y=`esri-directions__intermediate-costs-${v}`,f={[C.maneuverActive]:this._activeManeuver===o};return L("li",{"aria-labelledby":`${S} ${w} ${y}`,bind:this,class:this.classes(C.maneuver,f),"data-maneuver":o,key:o,onclick:this._handleManeuverClick,onkeydown:this._handleManeuverClick,onfocus:this._handleManeuverFocus,onmouseover:this._handleManeuverMouseOver,onmouseout:this._handleManeuverMouseOut,onblur:this._handleManeuverBlur,tabIndex:0},a(g)&&L("img",{alt:"",class:C.maneuverIcon,src:g}),L("div",{class:C.maneuverCostsContainer},L("span",{id:S,innerHTML:c(m,"")}),L("div",{class:C.maneuverCosts},L("div",{class:C.horizontalSplitter}),L("div",{id:w,"aria-label":l.cumulativeCosts,class:C.cumulativeCost,innerHTML:t,title:l.cumulativeCosts}),L("div",{id:y,"aria-label":l.intermediateCosts,class:C.intermediateCost,innerHTML:p,title:l.intermediateCosts}))))}_handleManeuverClick(e){const s=e.currentTarget["data-maneuver"];if(this._activeManeuver===s)return this._activeManeuver=null,void this.zoomToRoute();this._activeManeuver=s;const{geometry:i,symbol:o}=s,r=new t({geometry:i,symbol:o});this.viewModel.centerAt(r),this.viewModel.highlightSegment(r)}_handleManeuverMouseOver(e){if(this._activeManeuver||this._focusedManeuver)return;const s=e.currentTarget["data-maneuver"],{geometry:i,symbol:o}=s,r=new t({geometry:i,symbol:o});this.viewModel.highlightSegment(r)}_handleManeuverMouseOut(){this._activeManeuver||this._focusedManeuver||this.viewModel.clearHighlights()}_handleManeuverBlur(){this._activeManeuver||(this._focusedManeuver=null,this.viewModel.clearHighlights())}_handleManeuverFocus(e){if(this._activeManeuver)return;const s=e.currentTarget["data-maneuver"];this._focusedManeuver=s;const{geometry:i,symbol:o}=s,r=new t({geometry:i,symbol:o});this.viewModel.highlightSegment(r)}_getFormattedManeuverText(e){const{displayText:t,name:s,intersectingName:i}=e;if(n(t))return"";let o=t;return a(s)&&o.includes(s)&&(o=o.replace(s,`<strong>${s}</strong>`)),a(i)&&o.includes(i)&&(o=o.replace(i,`<strong>${i}</strong>`)),o}_getCostSummary(){const{viewModel:{impedanceAttribute:e,routeParameters:t},lastRoute:s}=this;if(n(e)||n(s))return null;const{routeInfo:i}=s;let{totalDuration:o,totalDistance:r}=i;const{directionsLengthUnits:l}=t;r=a(r)?r:0,o=a(o)?o:0;const c=b(this.messages,this.messagesUnits,r,{fromUnits:"meters",toUnits:l}),d=M(o,"minutes"),[h,u]=f(e.units)?[d,c]:[c,d];return{primary:h,secondary:u}}};e([m("viewModel.apiKey")],Y.prototype,"apiKey",void 0),e([m("viewModel.goToOverride")],Y.prototype,"goToOverride",void 0),e([v()],Y.prototype,"headingLevel",void 0),e([v()],Y.prototype,"iconClass",void 0),e([v({aliasOf:{source:"messages.widgetLabel",overridable:!0}})],Y.prototype,"label",void 0),e([m("viewModel.lastRoute")],Y.prototype,"lastRoute",void 0),e([m("viewModel.maxStops")],Y.prototype,"maxStops",void 0),e([v(),U("esri/widgets/Directions/t9n/Directions")],Y.prototype,"messages",void 0),e([v(),U("esri/t9n/common")],Y.prototype,"messagesCommon",void 0),e([v(),U("esri/core/t9n/Units")],Y.prototype,"messagesUnits",void 0),e([m("viewModel.routeServiceUrl")],Y.prototype,"routeServiceUrl",void 0),e([m("viewModel.routeSymbol")],Y.prototype,"routeSymbol",void 0),e([v()],Y.prototype,"searchProperties",void 0),e([m("viewModel.stopSymbols")],Y.prototype,"stopSymbols",void 0),e([m("viewModel.view")],Y.prototype,"view",void 0),e([v({type:y})],Y.prototype,"viewModel",void 0),e([m("viewModel.getDirections")],Y.prototype,"getDirections",null),e([m("viewModel.zoomToRoute")],Y.prototype,"zoomToRoute",null),e([H()],Y.prototype,"_handleStopIconClick",null),e([H()],Y.prototype,"_handleClearRouteClick",null),e([H()],Y.prototype,"_handleReverseStops",null),e([H()],Y.prototype,"_handleRemoveStop",null),e([H()],Y.prototype,"_handleSectionToggle",null),e([H()],Y.prototype,"_handleSummaryInteraction",null),e([H()],Y.prototype,"_handleManeuverClick",null),Y=e([_("esri.widgets.Directions")],Y);const G=Y;export{G as default};
5
+ import{_ as e}from"../chunks/tslib.es6.js";import t from"../Graphic.js";import"../intl.js";import s from"../core/Collection.js";import{on as i,pausable as o}from"../core/events.js";import r from"../core/Handles.js";import{isNone as n,isSome as a,unwrap as l,unwrapOrValue as c}from"../core/maybe.js";import{watch as d,initial as h,when as u,on as p}from"../core/reactiveUtils.js";import{aliasOf as m}from"../core/accessorSupport/decorators/aliasOf.js";import"../core/arrayUtils.js";import"../core/has.js";import"../core/accessorSupport/ensureType.js";import{property as v}from"../core/accessorSupport/decorators/property.js";import{subclass as _}from"../core/accessorSupport/decorators/subclass.js";import g from"../rest/support/Stop.js";import S from"./Search.js";import w from"./Widget.js";import y from"./Directions/DirectionsViewModel.js";import{formatDistance as M,formatTime as b,isTimeUnits as f}from"./Directions/support/directionsUtils.js";import{DepartureTime as T,CSS as C,getIconPath as I}from"./Directions/support/resources.js";import{isArcGISWorldGeocoder as k,meteredArcGISLocatorUrl as R}from"./Search/support/locatorUtils.js";import D from"./support/DatePicker.js";import{Heading as P,incrementHeadingLevel as j}from"./support/Heading.js";import x from"./support/TimePicker.js";import{accessibleHandler as H}from"./support/decorators/accessibleHandler.js";import{messageBundle as U}from"./support/decorators/messageBundle.js";import"../core/Logger.js";import{tsx as L}from"./support/jsxFactory.js";import"./support/widgetUtils.js";import z from"sortablejs";import{substitute as E}from"../intl/substitute.js";import{formatDate as A,convertDateFormatToIntlOptions as O}from"../intl/date.js";import{formatNumber as $}from"../intl/number.js";function N(e){const t=e.getTimezoneOffset(),s=t>0?"-":"+",i=60,o=Math.abs(Math.floor(t/i)),r=Math.abs(Math.floor(t)%i),n={minimumIntegerDigits:2};return`GMT${s}${$(o,n)}${$(r,n)}`}function B(){return[{},{}]}function F(e){return e.results[0].results[0]}function V(e){return!(null==e.composedPath||!e.composedPath().find((e=>{var t;return null==(t=e.classList)?void 0:t.contains("esri-search__suggestions-list")})))}const W={awaitingViewClickStop:"awaiting-view-click-stop"},K=100,q=500;let Y=class extends w{constructor(e,t){super(e,t),this._autoStopRemovalDelay=K,this._departureTime=T.NOW,this._datePicker=new D,this._handles=new r,this._newPlaceholderStop=null,this._pointerPressedSearchSuggestionStop=null,this._sections=null,this._stops=new s(B()),this._stopsToSearches=new Map,this._timePicker=new x,this.apiKey=null,this.goToOverride=null,this.headingLevel=2,this.iconClass=C.widgetIcon,this.label=void 0,this.lastRoute=null,this.maxStops=null,this.messages=null,this.messagesCommon=null,this.messagesUnits=null,this.routeServiceUrl=void 0,this.routeSymbol=null,this.searchProperties=null,this.stopSymbols=null,this.view=null,this.viewModel=new y,this._setUpDragAndDropStops=e=>{this._sortable=z.create(e,{draggable:`.${C.validStopRow}`,ghostClass:C.stopRowGhost,handle:`.${C.stopHandle}`,onEnd:this._handleStopInputDragEnd})},this._handleDragHandlePointerDown=()=>this._stops.forEach((e=>this._acquireSearch(e).activeMenu="none")),this._handleStopInputDragEnd=({oldIndex:e,newIndex:t,target:s})=>{if(e===t)return;const{children:i}=s,o=i[t],r=i[e],n=t-e<0;s.insertBefore(o,n?r.nextElementSibling:r);const a=this._stops;a.reorder(a.getItemAt(e),t),this._processStops()}}initialize(){this.own([d((()=>this.viewModel.lastRoute),(()=>{this._activeManeuver=null,this._focusedManeuver=null,this._sections=this._getSections(),this.scheduleRender()}),h),d((()=>[this.viewModel.selectedTravelMode,this.viewModel.departureTime]),(()=>{this.viewModel.stops.length>1&&this.getDirections()}),h),u((()=>this.view),((e,t)=>{if(t&&(this._viewClickHandle=null,this._handles.remove(t)),e){const t=this._prepPointerDownUpClick(),s=this._prepViewClick();t.pause(),s.pause(),this._handles.add([i(e.surface,"mousedown",(()=>this._autoStopRemovalDelay=q)),i(e.surface,"mouseup",(()=>this._autoStopRemovalDelay=K)),t,s],this.view.surface),this._pointerDownUpHandle=t,this._viewClickHandle=s}}),h),u((()=>0===this.viewModel.stops.length),(()=>{this._stops.drain((e=>{this._disposeSearch(e)})),this._stops.addMany(B()),this.scheduleRender()})),u((()=>n(this.viewModel.serviceDescription)),(()=>{this.viewModel.load()}),h)])}destroy(){this._datePicker.destroy(),this._timePicker.destroy(),this._stopsToSearches.forEach((e=>e.destroy())),this._sortable&&this._sortable.destroy()}getDirections(){return null}zoomToRoute(){}render(){return L("div",{class:this.classes(C.base,C.scroller)},this._renderPanelContent())}_renderPanelContent(){const{viewModel:{state:e}}=this,t="initializing"===e,s="error"===e&&!this.viewModel.serviceDescription,i="unauthenticated"===e,o={[C.panelContentLoading]:t,[C.panelContentError]:s,[C.panelContentSignIn]:i},r=t?"presentation":"group",n=i?this._renderSignIn():s?this._renderMessage(this._getErrorMessage()):t?this._renderLoader():this._renderReadyContent();return L("div",{class:this.classes(C.panelContent,o),role:r},n)}_renderReadyContent(){return[this._renderStopsContainer(),this._renderTravelModeOptions(),this._renderDepartureTimeControls(),this._renderSectionSplitter(),this._renderDirectionsContainer()]}_renderSignIn(){return L("div",{key:"sign-in",class:C.signInContent},L(P,{class:C.contentTitle,level:this.headingLevel},this.messages.widgetLabel),this._renderPlaceholder(),L(P,{level:j(this.headingLevel)},this.messages.signInRequired),L("button",{class:this.classes(C.button,C.buttonSecondary,C.signInButton),tabIndex:0,onclick:this._handleSignInClick,bind:this,type:"button"},this.messagesCommon.auth.signIn))}_handleSignInClick(){this.viewModel.load().catch((()=>{}))}_renderTravelModeOptions(){const{selectedTravelMode:e,travelModes:t}=this.viewModel;if(0===t.length)return null;const s=a(e)?e.name:this.messages.travelMode;return L("select",{"aria-label":s,bind:this,class:this.classes(C.travelModeSelect,C.select),key:"esri-directions__travel-mode-options",onchange:this._handleTravelModeChange,title:s},t.map((t=>{const s=a(e)&&t.id===e.id;return L("option",{key:t,"data-mode":t,selected:s,value:t.id},t.name)})))}_handleTravelModeChange(e){const t=e.currentTarget,s=t.item(t.selectedIndex);this.viewModel.selectedTravelMode=s["data-mode"]}_renderStopsContainer(){return L("div",{class:C.section,key:"esri-directions__stops-container",role:"group"},this._renderStops())}_renderDepartureTimeControls(){const e=this._departureTime,{messages:t}=this,s=t.departureTime;return L("div",{class:C.departureTime,key:"esri-directions__departure-time-controls",role:"group"},L("select",{"aria-label":s,bind:this,class:this.classes(C.departureTimeSelect,C.select),onchange:this._handleDepartureOptionChange,title:s},L("option",{value:T.NOW,selected:e===T.NOW},t.leaveNow),L("option",{value:T.DEPART_BY,selected:e===T.DEPART_BY},t.departBy),L("option",{value:T.UNSPECIFIED,selected:e===T.UNSPECIFIED},t.timeUnspecified)),e===T.DEPART_BY?this._renderTimeControls():null)}_renderStops(){const e=this._stops;let t=0;e.forEach((e=>{"none"!==this._acquireSearch(e).activeMenu&&(t+=1)}));const s=e.toArray().map(((s,i)=>{const o=e.length,r=i>1&&!s.result,n={[C.stopsIcon]:i>=0&&i<o-1,[C.lastStopIcon]:i===o-1},a={[C.lastStopIconContainer]:i===o-1},l={[C.validStopRow]:!r},c=e.getItemAt(o-1),d=c&&c.result,h=e.getItemAt(i+1),u=h&&h.result,p=i===o-1,m=i===o-2,v=2===o&&0===i||o>2&&!p&&!m||o>2&&m&&u||o>2&&p&&!s.result,_=2===o||3===o&&!d||r,g=this._acquireSearch(s),{messages:S}=this,{removeStop:w,reverseStops:y,unlocated:M}=S,b=E(S.stopLabelTemplate,{number:i+1,label:s.result?s.result.name:M}),f=`${this.id}__stop--${i}`,T=!!g.searchTerm&&!!g.selectedResult&&!!s.result&&g.selectedResult===s.result,I={zIndex:"none"!==g.activeMenu?""+t--:""};return L("li",{"aria-label":b,afterCreate:this._handleStopFieldCreation,bind:this,class:this.classes(C.stopRow,l),id:f,key:i,"data-stop-index":i,styles:I},L("div",{class:C.stopHandle},L("span",{"aria-hidden":"true",class:this.classes(C.stopIcon,C.handleIcon,C.stopHandleIcon,C.interactiveStopIcon),onpointerdown:this._handleDragHandlePointerDown}),L("div",{bind:this,"aria-labelledby":f,class:this.classes(C.stopIconContainer,a),"data-stop-index":i,onclick:this._handleStopIconClick,onkeydown:this._handleStopIconClick,role:"button"},L("span",{class:this.classes(C.stopIcon,n),tabindex:T?"0":null}))),L("div",{class:C.stopInput},g.render()),L("div",{class:C.stopOptions,role:"group"},L("div",{"aria-label":w,class:C.removeStopButton,bind:this,"data-stop-index":i,hidden:_,onkeydown:this._handleRemoveStop,onclick:this._handleRemoveStop,role:"button",tabIndex:0,title:w},L("span",{"aria-hidden":"true",class:this.classes(C.stopIcon,C.removeStop,C.removeStopIcon,C.interactiveStopIcon)}),L("span",{class:C.screenReaderText},"removeStopTitle")),L("div",{"aria-label":y,class:C.reverseStops,bind:this,hidden:v,onkeydown:this._handleReverseStops,onclick:this._handleReverseStops,role:"button",tabIndex:0,title:y},L("span",{"aria-hidden":"true",class:this.classes(C.stopIcon,C.reverseStopIcon,C.interactiveStopIcon)}),L("span",{class:C.screenReaderText},"removeStopTitle"))))})),i=e.every((e=>{const t=this._stopsToSearches.get(e);return e.result&&t.selectedResult===e.result})),o=this._stops.length>=this.maxStops,r=this.messages.addStop,n=e.length>=2&&i&&!o?L("div",{"aria-label":r,bind:this,class:C.addStop,key:"esri-directions__add-stop",onfocus:this._handleAddStopFocus,tabIndex:0},L("span",{"aria-hidden":"true",class:this.classes(C.addStopIcon,C.stopIcon,C.interactiveStopIcon)}),L("div",{"aria-hidden":"true",class:C.addStopText},r)):null;return L("div",null,L("ol",{class:C.stops,role:"group",afterCreate:this._setUpDragAndDropStops},s),n)}_handleStopIconClick(e){const t=e.currentTarget["data-stop-index"],s=this._stops.getItemAt(t);s&&s.result&&this._centerAtStop(s)}_handleClearRouteClick(){this.viewModel.reset()}_centerAtStop(e){this.viewModel.centerAt(e.result.feature)}_handleStopFieldCreation(e){const t=this._newPlaceholderStop;if(!t)return;const s=e["data-stop-index"],i=this._stops.getItemAt(s);if(t===i){const e=this._acquireSearch(i);e.when((()=>{this.renderNow(),e.focus()}))}this._newPlaceholderStop=null}_handleStopInputBlur(e,t){this._handles.remove(W.awaitingViewClickStop),this.view.cursor=this._previousCursor;if(!e.selectedResult||!t.result||e.selectedResult!==t.result)return"none"!==e.activeMenu||!e.searchTerm||e.selectedResult===t.result&&(e.selectedResult||t.result)?void(e.searchTerm||(this._viewClickHandle.resume(),clearTimeout(this._autoStopRemovalTimeoutId),this._autoStopRemovalTimeoutId=setTimeout((()=>{if(this.destroyed)return;if(this._viewClickHandle.pause(),"searching"===e.viewModel.state)return void this._pointerDownUpHandle.pause();if(this._pointerPressedSearchSuggestionStop)return;!!t.result&&(t.result=null,this._processStops()),this.scheduleRender()}),this._autoStopRemovalDelay))):(e.search(),void this._pointerDownUpHandle.pause());this._pointerDownUpHandle.pause()}_handleStopInputFocus(e,t){if(this._pointerDownUpHandle.resume(),this._handles.has(W.awaitingViewClickStop))return;const{view:s,view:{cursor:i}}=this;this._previousCursor=i,this._handles.add(d((()=>e.searchTerm),(e=>{s.cursor=0===e.length?"copy":i}),h),W.awaitingViewClickStop),this._activeStop=t}_prepViewClick(){const{view:e}=this.viewModel,t=o(e,"click",this._handleViewClick.bind(this)),s=o(e.surface,"click",(()=>{clearTimeout(this._autoStopRemovalTimeoutId),s.pause()}));return{remove(){s.remove(),t.remove()},pause(){s.pause(),t.pause()},resume(){s.resume(),t.resume()}}}_prepPointerDownUpClick(){const e=o(document,"pointerdown",(e=>{this._pointerPressedSearchSuggestionStop=V(e)?this._activeStop:null})),t=o(document,"pointerup",(e=>{this._pointerDownUpHandle.pause();const t=V(e),s=this._activeStop;t||s!==this._pointerPressedSearchSuggestionStop||this._removeStop(s),this.scheduleRender(),this._pointerPressedSearchSuggestionStop=t?this._activeStop:null}));return{remove(){t.remove(),e.remove()},pause(){t.pause(),e.pause()},resume(){e.resume()}}}_handleViewClick(e){const t=this._stopsToSearches.get(this._activeStop);t&&!t.searchTerm&&(t.search(e.mapPoint).then((e=>{const s=F(e),i=this._activeStop;i.result=s,i.result.feature.attributes.Name=s.name,t.searchTerm=s.name})),this.scheduleRender()),this._viewClickHandle.pause(),clearTimeout(this._autoStopRemovalTimeoutId)}_handleAddStopFocus(){this._addNewPlaceholder()}_addNewPlaceholder(){if(this._pointerDownUpHandle.pause(),this._newPlaceholderStop)return;const e={};this._stops.add(e),this._newPlaceholderStop=e}_handleReverseStops(){this._reverseStops()}_reverseStops(){this._stops.reverse(),this._processStops()}_handleRemoveStop(e){const t=e.currentTarget["data-stop-index"];this._removeStop(this._stops.getItemAt(t)),this._processStops()}_removeStop(e){this._stops.length<=2||(this._disposeSearch(e),this._stops.remove(e))}_handleDepartureOptionChange(e){const t=e.currentTarget,s=t.item(t.selectedIndex);s.value===T.NOW?(this._departureTime=T.NOW,this.viewModel.departureTime=T.NOW,this._handles.remove("departure-time-controls")):s.value===T.DEPART_BY?(this._departureTime=T.DEPART_BY,this._handles.add([d((()=>this._datePicker.value),(()=>this._updateDepartureTime()),h),d((()=>this._timePicker.value),(()=>this._updateDepartureTime()),h)],"departure-time-controls")):(this._departureTime=T.UNSPECIFIED,this.viewModel.departureTime=null)}_updateDepartureTime(){const e=this._datePicker.value,t=this._timePicker.value;e&&t&&(this.viewModel.departureTime=new Date(e.getFullYear(),e.getMonth(),e.getDate(),t.getHours(),t.getMinutes()))}_renderTimeControls(){return L("div",{class:C.departureTimeControls,key:"esri-directions__time-controls",role:"group"},this._datePicker.render(),this._timePicker.render())}_renderSectionSplitter(){return L("div",{class:C.sectionSplitter})}_renderDirectionsContainer(){return L("div",{class:this.classes(C.directionsSection,C.section),key:"esri-directions__container"},this._renderDirectionsContainerContent())}_renderLoader(){return L("div",{class:C.loader,key:"loader"})}_renderWarningCard(){return L("div",{class:C.warningCard,role:"alert"},L("div",{class:C.warningHeader},L("span",{class:C.warningIcon,"aria-hidden":"true"}),L(P,{class:C.warningHeading,level:this.headingLevel},this.messagesCommon.warning)),L("div",{class:C.warningMessage},this._getErrorMessage()))}_renderDirectionsContainerContent(){const{lastRoute:e,viewModel:{state:t}}=this,s="routing"===t;return"error"===t?this._renderWarningCard():s?this._renderLoader():a(e)&&a(e.directionLines)?L("div",{class:C.summary,key:"esri-directions__summary",role:"group"},this._renderCosts(),this._renderRouteActions(),this._renderManeuverSections()):L("div",{key:"esri-directions__placeholder",class:C.emptyContent},this._renderPlaceholder(),L(P,{class:C.message,level:this.headingLevel},this.messages.directionsPlaceholder))}_renderPlaceholder(){return L("svg",{class:C.emptyIllustration,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256"},L("path",{fill:"currentcolor",d:"M192 36c-15.477 0-24 6.034-24 16.99v45.822l24 24 24-24v-45.82C216 42.033 207.477 36 192 36zm20 61.155l-20 20-20-20V52.99c0-8.62 6.73-12.99 20-12.99s20 4.37 20 12.99zM192 52a12 12 0 1 0 12 12 12.013 12.013 0 0 0-12-12zm0 20a8 8 0 1 1 8-8 8.008 8.008 0 0 1-8 8zM92 140.99C92 130.035 83.477 124 68 124s-24 6.034-24 16.99v45.822l24 24 24-24zm-4 44.165l-20 20-20-20V140.99c0-8.62 6.73-12.99 20-12.99s20 4.37 20 12.99zM68 140a12 12 0 1 0 12 12 12.013 12.013 0 0 0-12-12zm0 20a8 8 0 1 1 8-8 8.008 8.008 0 0 1-8 8zm84-44h16v4h-16zm-24 80h4v12h-12v-4h8zm0-28h4v16h-4zm0-52h12v4h-8v8h-4zm0 24h4v16h-4zm-36 64h16v4H92z"}))}_renderMessage(e){return L(P,{level:this.headingLevel},e)}_renderRouteActions(){return L("div",{class:C.routeActions},L("button",{"aria-label":this.messages.clearRoute,class:this.classes(C.clearRouteButton,C.button,C.buttonTertiary),tabIndex:0,onclick:this._handleClearRouteClick,bind:this,type:"button"},this.messages.clearRoute))}_getSections(){if(n(this.lastRoute))return null;const{directionPoints:e,directionLines:t,stops:s}=this.lastRoute;if(n(e)||n(t))return null;const i=[];let o=null;for(const r of e){const{objectId:e,stopId:l}=r;if(a(l)){const e=s.find((e=>e.objectId===l)),t=0===i.length;(n(o)||o.stop!==e)&&(o={stop:e,directions:[],open:t},i.push(o));continue}if(n(o))continue;const c=t.find((t=>t.directionPointId===e));n(c)||o.directions.push({directionPoint:r,directionLine:c})}return i}_renderManeuverSections(){return n(this._sections)?null:L("div",{class:C.maneuvers,role:"group"},this._sections.map(((e,t)=>{const{open:s}=e;let i;e.directions.length>0&&s&&(i=L("ol",{class:C.maneuverList},e.directions.map((e=>this._renderManeuver(e)))));const o=l(this._sections).length>2,r=t===l(this._sections).length-1,n={[C.collapsibleSection]:o},a={[C.openIcon]:!s,[C.closeIcon]:s};let c;if(o&&!r){const t=s?this.messagesCommon.open:this.messagesCommon.close;c=L("header",{class:this.classes(C.maneuverSectionHeader,C.maneuverSectionToggle),key:"esri-directions__maneuver-section-header"},L("div",{"aria-expanded":s.toString(),"aria-label":t,bind:this,class:C.maneuverSectionHeaderButton,"data-maneuver-section":e,onkeydown:this._handleSectionToggle,onclick:this._handleSectionToggle,role:"button",tabIndex:0,title:t},L(P,{class:C.maneuverSectionTitle,level:this.headingLevel},e.stop.name),L("span",{"aria-hidden":"true",class:this.classes(a)})))}else c=L("header",{class:C.maneuverSectionHeader,key:"esri-directions__maneuver-section-header"},L(P,{class:C.maneuverSectionTitle,level:this.headingLevel},e.stop.name));return L("section",{class:this.classes(C.maneuverSection,n),key:t},c,i)})))}_handleSectionToggle(e){const t=e.currentTarget["data-maneuver-section"];t.open=!t.open}_renderCosts(){const{lastRoute:e}=this;if(n(e))return null;const t=this._getCostSummary(),{directionPoints:s}=e;if(n(s)||n(t))return null;const i=s.getItemAt(s.length-1).arrivalTime,{primary:o,secondary:r}=t,{eta:l,etaTemplate:c,primaryCosts:d,secondaryCosts:h,zoomToRoute:u}=this.messages,p=O("short-time"),m=a(i)?`<strong>${A(i,p)}</strong>`:null,v=a(i)?`${N(i)}`:null,_=E(c,{time:m,gmt:v});return L("div",{"aria-label":u,bind:this,class:C.directionCosts,onkeydown:this._handleSummaryInteraction,onclick:this._handleSummaryInteraction,role:"button",tabIndex:0,title:u},L("div",{class:C.costsDetails,role:"group"},L("div",{"aria-label":d,class:C.primaryCosts,title:d},o),L("div",{class:C.verticalSplitter}),L("div",{"aria-label":h,class:C.secondaryCosts,title:h},r)),L("div",{"aria-label":l,innerHTML:_,title:l}))}_handleSummaryInteraction(){this._activeManeuver=null,this._focusedManeuver=null,this.viewModel.clearHighlights(),this.zoomToRoute()}_getErrorMessage(){const{messages:e,viewModel:{error:t}}=this;if(a(t))switch(t.name){case"directions-view-model:unable-to-route":return e.errors.unableToRoute;case"directions-view-model:service-metadata-unavailable":return e.errors.unableToLoadServiceMetadata}return e.errors.unknownError}_normalizeSearchSources(e){this._overrideDefaultSources(e),this._applyLocatorSourceOverrides(e)}_overrideDefaultSources(e){e.viewModel.defaultSources.forEach((e=>{e.autoNavigate=!1}))}_applyLocatorSourceOverrides({allSources:e}){0!==e.length&&e.forEach((e=>{"url"in e&&e.url&&(null===e.locationType&&(e.locationType="street"),k(e.url)&&this.apiKey&&null==e.apiKey&&(e.apiKey=this.apiKey,e.url=R))}))}_acquireSearch(e){const t=this.get("viewModel.view");if(this._stopsToSearches.has(e)){const s=this._stopsToSearches.get(e);return s.view=t,this._overrideDefaultSources(s),s}const s=new S({view:t,resultGraphicEnabled:!1,popupEnabled:!1,...this.searchProperties});return this._normalizeSearchSources(s),this._handles.add([p((()=>s.allSources),"change",(()=>this._normalizeSearchSources(s))),s.on("select-result",(()=>{e.result=s.selectedResult,e.result.feature.attributes.Name=s.selectedResult.name,this._processStops(),this.scheduleRender()})),s.on("search-focus",(()=>this._handleStopInputFocus(s,e))),s.on("search-blur",(()=>this._handleStopInputBlur(s,e)))],s),this._stopsToSearches.set(e,s),s}_disposeSearch(e){this._stopsToSearches.get(e).destroy(),this._stopsToSearches.delete(e)}_processStops(){const e=this._stops.filter((e=>!!e.result)).map((e=>g.fromJSON(e.result.feature.toJSON())));this.viewModel.stops=e,e.length>1&&this.getDirections()}_renderManeuver(e){const t="",{directionsLengthUnits:s}=this.viewModel.routeParameters,{directionPoint:i,directionLine:o}=e,{distance:r,duration:n}=o,{messages:l,messagesUnits:d}=this,h=M(l,d,c(r,0),{fromUnits:"meters",toUnits:s}),u=b(c(n,0),"minutes"),p=h&&u?`${h}&nbsp;&middot;&nbsp;${u}`:`${h}${u}`,m=this._getFormattedManeuverText(i),{objectId:v,directionPointType:_}=i,g=I(_),S=`esri-directions__maneuver-${v}`,w=`esri-directions__cumulative-costs-${v}`,y=`esri-directions__intermediate-costs-${v}`,f={[C.maneuverActive]:this._activeManeuver===o};return L("li",{"aria-labelledby":`${S} ${w} ${y}`,bind:this,class:this.classes(C.maneuver,f),"data-maneuver":o,key:o,onclick:this._handleManeuverClick,onkeydown:this._handleManeuverClick,onfocus:this._handleManeuverFocus,onmouseover:this._handleManeuverMouseOver,onmouseout:this._handleManeuverMouseOut,onblur:this._handleManeuverBlur,tabIndex:0},a(g)&&L("img",{alt:"",class:C.maneuverIcon,src:g}),L("div",{class:C.maneuverCostsContainer},L("span",{id:S,innerHTML:c(m,"")}),L("div",{class:C.maneuverCosts},L("div",{class:C.horizontalSplitter}),L("div",{id:w,"aria-label":l.cumulativeCosts,class:C.cumulativeCost,innerHTML:t,title:l.cumulativeCosts}),L("div",{id:y,"aria-label":l.intermediateCosts,class:C.intermediateCost,innerHTML:p,title:l.intermediateCosts}))))}_handleManeuverClick(e){const s=e.currentTarget["data-maneuver"];if(this._activeManeuver===s)return this._activeManeuver=null,void this.zoomToRoute();this._activeManeuver=s;const{geometry:i,symbol:o}=s,r=new t({geometry:i,symbol:o});this.viewModel.centerAt(r),this.viewModel.highlightSegment(r)}_handleManeuverMouseOver(e){if(this._activeManeuver||this._focusedManeuver)return;const s=e.currentTarget["data-maneuver"],{geometry:i,symbol:o}=s,r=new t({geometry:i,symbol:o});this.viewModel.highlightSegment(r)}_handleManeuverMouseOut(){this._activeManeuver||this._focusedManeuver||this.viewModel.clearHighlights()}_handleManeuverBlur(){this._activeManeuver||(this._focusedManeuver=null,this.viewModel.clearHighlights())}_handleManeuverFocus(e){if(this._activeManeuver)return;const s=e.currentTarget["data-maneuver"];this._focusedManeuver=s;const{geometry:i,symbol:o}=s,r=new t({geometry:i,symbol:o});this.viewModel.highlightSegment(r)}_getFormattedManeuverText(e){const{displayText:t,name:s,intersectingName:i}=e;if(n(t))return"";let o=t;return a(s)&&o.includes(s)&&(o=o.replace(s,`<strong>${s}</strong>`)),a(i)&&o.includes(i)&&(o=o.replace(i,`<strong>${i}</strong>`)),o}_getCostSummary(){const{viewModel:{impedanceAttribute:e,routeParameters:t},lastRoute:s}=this;if(n(e)||n(s))return null;const{routeInfo:i}=s;let{totalDuration:o,totalDistance:r}=i;const{directionsLengthUnits:l}=t;r=a(r)?r:0,o=a(o)?o:0;const c=M(this.messages,this.messagesUnits,r,{fromUnits:"meters",toUnits:l}),d=b(o,"minutes"),[h,u]=f(e.units)?[d,c]:[c,d];return{primary:h,secondary:u}}};e([m("viewModel.apiKey")],Y.prototype,"apiKey",void 0),e([m("viewModel.goToOverride")],Y.prototype,"goToOverride",void 0),e([v()],Y.prototype,"headingLevel",void 0),e([v()],Y.prototype,"iconClass",void 0),e([v({aliasOf:{source:"messages.widgetLabel",overridable:!0}})],Y.prototype,"label",void 0),e([m("viewModel.lastRoute")],Y.prototype,"lastRoute",void 0),e([m("viewModel.maxStops")],Y.prototype,"maxStops",void 0),e([v(),U("esri/widgets/Directions/t9n/Directions")],Y.prototype,"messages",void 0),e([v(),U("esri/t9n/common")],Y.prototype,"messagesCommon",void 0),e([v(),U("esri/core/t9n/Units")],Y.prototype,"messagesUnits",void 0),e([m("viewModel.routeServiceUrl")],Y.prototype,"routeServiceUrl",void 0),e([m("viewModel.routeSymbol")],Y.prototype,"routeSymbol",void 0),e([v()],Y.prototype,"searchProperties",void 0),e([m("viewModel.stopSymbols")],Y.prototype,"stopSymbols",void 0),e([m("viewModel.view")],Y.prototype,"view",void 0),e([v({type:y})],Y.prototype,"viewModel",void 0),e([m("viewModel.getDirections")],Y.prototype,"getDirections",null),e([m("viewModel.zoomToRoute")],Y.prototype,"zoomToRoute",null),e([H()],Y.prototype,"_handleStopIconClick",null),e([H()],Y.prototype,"_handleClearRouteClick",null),e([H()],Y.prototype,"_handleReverseStops",null),e([H()],Y.prototype,"_handleRemoveStop",null),e([H()],Y.prototype,"_handleSectionToggle",null),e([H()],Y.prototype,"_handleSummaryInteraction",null),e([H()],Y.prototype,"_handleManeuverClick",null),Y=e([_("esri.widgets.Directions")],Y);const G=Y;export{G 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.23/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 s from"../../core/Logger.js";import{destroyMaybe as o,isSome as l,isNone as r}from"../../core/maybe.js";import{EsriPromiseMixin as a}from"../../core/Promise.js";import{watch as u}from"../../core/reactiveUtils.js";import{ReentrantObjectPool as c}from"../../core/ReentrantObjectPool.js";import{property as d}from"../../core/accessorSupport/decorators/property.js";import"../../core/arrayUtils.js";import"../../core/has.js";import"../../core/accessorSupport/ensureType.js";import{subclass as p}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 v}from"../../intl/locale.js";import{fetchMessageBundle as F}from"../../intl/messages.js";function C(e){return!!e.inputFields}const E=new t({attributes:{}}),I="esri.widgets.FeatureForm.FeatureFormViewModel",V=s.getLogger(I),b="#JSAPI_CONTINGENT_VALUE_EMPTY_HASH",j="#JSAPI_CONTINGENT_VALUE_ANY_HASH",A="#JSAPI_CONTINGENT_VALUE_NULL_HASH";let w=class extends(n(a(i.EventedAccessor))){constructor(e){super(e),this._arcade=null,this._compiledExpressions=new Map,this._contingentValuesCache=null,this._fieldPool=new c(y,(e=>this.handles.add(u((()=>e.value),(()=>{e.isUsingValueExpression&&this._afterValueChange(e)})),e.id)),(({id:e})=>this.handles.remove(e))),this._fieldGroupPool=new c(_),this._featureClone=E.clone(),this._initialFeature=E.clone(),this._needsArcade=!1,this._inputFieldCache=new Map,this._inputFieldGroupCache=new Map,this.contingencyConstraintViolations=new Map,this.messages=null,this.strict=!1}initialize(){const e=async()=>this.messages=await F("esri/widgets/FeatureForm/t9n/FeatureForm");e();const t=u((()=>this.layer),(e=>{"feature"===(null==e?void 0:e.type)&&this.addResolvingPromise(m.createLoadedLayerContingentValuesCache(e).then((e=>{this._contingentValuesCache=e,this.notifyChange("fieldsWithContingentValues")})))}),{initial:!0}),i=u((()=>{var e,t;const{formTemplate:i}=this;if(r(i))return null;const n=null!=(e=i.expressionInfos)?e:[],s=null!=(t=i.elements)?t:[];return[...n.map((e=>e.expression)),...null==s?void 0:s.map((e=>this._getExpressionsFromElementRecursive(e))).flat()]}),(async e=>{if(e.length<1)return;const t=new Set(e),n=new Map;if(l(this.formTemplate)&&l(this.formTemplate.expressionInfos))for(const i of this.formTemplate.expressionInfos)t.delete(i.name),n.set(i.expression,i.name);for(const i of this._compiledExpressions.keys())t.delete(i);if(t.size<1)return;this._needsArcade=!0;const s=await g();this._arcade=s;const{arcadeUtils:o}=s;for(const l of t.values()){var r;o.hasGeometryOperations(l)&&(await o.enableGeometryOperations(),i.remove()),this._setFunctionForExpression(null!=(r=n.get(l))?r:l,l)}this.notifyChange("inputFields")})),n=u((()=>this.formTemplate),(()=>this._compiledExpressions.clear()));this.handles.add([v(e),i,n,t])}destroy(){this.feature=null,this.layer=null,this._contingentValuesCache=o(this._contingentValuesCache),this._fieldPool.destroy(),this._fieldGroupPool.destroy()}get allInputFields(){return this.inputFields.reduce(((e,t)=>C(t)?[...e,...t.inputFields]:[...e,t]),[])}get _layerFieldsByName(){return new Map(this.layer.fields.map((e=>[e.name,e])))}get description(){const{formTemplate:e}=this;return l(e)?e.description:""}set description(e){void 0===e?this._clearOverride("description"):this._override("description",e)}get feature(){return this._get("feature")}set feature(e){this._featureClone=e?e.clone():E.clone(),this._initialFeature=this._featureClone.clone(),this._inputFieldCache.clear(),this._inputFieldGroupCache.clear(),this._set("feature",e)}get fieldsWithContingentValues(){if(r(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){void 0===e?this._clearOverride("formTemplate"):this._override("formTemplate",e)}get inputFields(){const{_arcade:e,_featureClone:t,_initialFeature:i,_inputFieldCache:n,_needsArcade:s,formTemplate:o,messages:r,layer:a,state:u}=this;if("ready"!==u||s&&!e)return[];const c=t.clone(),d=Array.from(n.keys()),p={arcade:e,feature:c,initialFeature:i,layer:a,messages:r},h=l(o)&&o.elements.length>0?this._generateInputFieldsFromElements(o.elements,p):this._generateInputFieldsFromLayerFields(null==a?void 0:a.fields,p);return this._cullInputFieldCache(this._flattenGroups(h).map((e=>e.name)),d),this._releasePreviousInputFields(),h.filter((e=>e.visible))}get joinedContingentValues(){return this._joinContingentValues()}get layer(){var e;return null!=(e=this.feature)&&e.sourceLayer&&"applyEdits"in this.feature.sourceLayer?this.feature.sourceLayer:null}set layer(e){e?this._override("layer",e):this._clearOverride("layer")}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 title(){const{formTemplate:e}=this;return l(e)?e.title:""}set title(e){void 0===e?this._clearOverride("title"):this._override("title",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){var t;const{_featureClone:i,layer:n}=this,s=!(null==n||!n.getField(e));return null!=(t=i.getAttribute(e))?t:s?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,r(i))return[];const{invalid:s,incomplete:o}=i.validateContingencyConstraints(e),l=[...s,...null!=t&&t.includeIncompleteViolations?o:[]];for(const r of l)for(const e of r.fieldGroup.fields)n.set(e,r);return l}_cullInputFieldCache(e,t){const i=t.filter((t=>!e.includes(t)));for(const n in i)this._inputFieldCache.delete(n)}_flattenGroups(e){return e.flatMap((e=>"groupElement"in e?e.inputFields:e))}_releasePreviousInputFields(){const e=this._get("inputFields");if(e&&!(e.length<1))for(const t of e)"groupElement"in t?this._releaseInputFieldGroup(t):this._releaseInputField(t)}_releaseInputFieldGroup(e){e.inputFields.forEach((e=>this._releaseInputField(e))),this._fieldGroupPool.release(e)}_releaseInputField(e){this._fieldPool.release(e)}_emitChangeEvent({name:e,valid:t,value:i}){this.emit("value-change",{layer:this.layer,feature:this.feature,fieldName:e,value:i,valid:t})}_generateInputFieldsFromElements(e,t){const i=[];for(const n of e)this._isSupportedElement(n)&&i.push("group"===n.type?this._acquireAndInitializeInputFieldGroup(n,t):this._acquireAndInitializeInputField({field:this._layerFieldsByName.get(n.fieldName),fieldElement:n,...t}));return i}_generateInputFieldsFromLayerFields(e,t){return Array.isArray(e)?e.map((e=>this._acquireAndInitializeInputField({field:e,fieldElement:null,...t}))):(V.warn(I,"No attribute fields found."),[])}_acquireAndInitializeInputField(e){var t,i,n,s,o,l;const{arcade:r,feature:a,field:u,fieldElement:c,group:d,initialFeature:p,layer:h,messages:f}=e,m=null!=(t=this._compiledExpressions.get(null==c?void 0:c.requiredExpression))?t:void 0,g=null!=(i=this._compiledExpressions.get(null==c?void 0:c.visibilityExpression))?i:void 0,y=null!=(n=this._compiledExpressions.get(null==c?void 0:c.valueExpression))?n:void 0,_=null!=(s=this._compiledExpressions.get(null==c?void 0:c.editableExpression))?s:void 0,v=u.name,F=null!=(o=null==(l=this._inputFieldCache.get(v))?void 0:l.value)?o:this.getValue(v),C=this._fieldPool.acquire();return this._inputFieldCache.set(v,C),C.set({field:u,fieldElement:c,arcade:r,feature:a,group:d,initialFeature:p,layer:h,messages:f,requiredFunction:m,visibilityFunction:g,editableFunction:_,valueFunction:y,value:F})}_acquireAndInitializeInputFieldGroup(e,t){const i=this._fieldGroupPool.acquire(),n=[];for(const r of e.elements)this._isSupportedElement(r)&&n.push(this._acquireAndInitializeInputField({field:this._layerFieldsByName.get(r.fieldName),fieldElement:r,group:i,...t}));const{arcade:s,feature:o}=t,l=this._compiledExpressions.get(e.visibilityExpression);return i.set({arcade:s,feature:o,groupElement:e,inputFields:n,visibilityFunction:l})}_afterValueChange(e){const{name:t,value:i}=e;if(this.get("layer.typeIdField")===e.name&&"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),this.notifyChange("inputFields"),this._emitChangeEvent(e)}_getExpressionsFromElementRecursive(e){const t=[];if(e.visibilityExpression&&t.push(e.visibilityExpression),"field"===e.type){const i=["requiredExpression","valueExpression","editableExpression"];for(const n of i)e[n]&&t.push(e[n])}if("group"===e.type&&e.elements)for(const i of e.elements)t.push(...this._getExpressionsFromElementRecursive(i));return t}_setFunctionForExpression(e,t){const{_arcade:{arcadeUtils:i},_compiledExpressions:n}=this;n.set(e,i.createFunction(t))}_isSupportedElement(e){return"field"===e.type||"group"===e.type||(V.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(r(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 a of e)for(const e of a.fields)if(t.has(e)){const s=t.get(e),o=a,l=[s.name,o.name].sort().join("|");if(n.has(l))continue;i.push([s,o]),n.add(l),t.set(e,o)}else t.set(e,a);const s=new Set(i.flat()),o=new Set(e);for(const a of s)o.delete(a);const l=new Map,r=new Map;for(const a of new Set(i.flat())){const e=Symbol(a.name);l.set(e,new Set([a])),r.set(a,e)}for(const[a,u]of i){const e=r.get(a),t=r.get(u);if(e===t)continue;const i=l.get(e),n=l.get(t);for(const s of n)i.add(s),r.set(s,e);l.delete(t)}return[[...l.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]),a=new Map;for(const l of i.contingencies){const[e]=this._hashContingency(l,s.codedValueFields,!0);a.has(e)?a.get(e).push(l):a.set(e,[l])}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(a,i):a.get(i);if(a.has(j)&&o.push(...this._findMatchingContingenciesContainingAny(t,a.get(j),s.codedValueFields)),!r(o))for(const a of o){const i=s.rangeFields.length>0?this._joinContingenciesWithRangeDomains(a,t,s.rangeFields):this._joinContingencies(a,t);if(r(i))break;const[n]=this._hashContingency(i,l.codedValueFields,!0);e.has(n)?e.get(n).push(i):e.set(n,[i])}}a=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(a,e):a.get(e);if(a.has(j)&&i.push(...this._findMatchingContingenciesContainingAny(c,a.get(j),s.codedValueFields)),!r(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:l,rightIsNull:r,bothAreNull:a,leftIsAny:u,rightIsAny:c,bothAreAny:d,leftIsRange:p,rightIsRange:h}=this._compareObjectTypes(i.objectType,o.objectType);if(a||d)continue;if(l&&c||r&&u){n.values[s]=new f({objectType:"null"});continue}if(l&&h||r&&p)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=>{var n,s;const o=t.values[i],l=e.values[i];return"any"===o.objectType||"any"===l.objectType||(null==(n=o.codedValue)?void 0:n.code)===(null==(s=l.codedValue)?void 0:s.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,l=new Set,a=new Set;for(const u of s)if(o.has(u)){const e=this.layer.getFieldDomain(u,{feature:this.feature});if(r(e))continue;switch(e.type){case"coded-value":l.add(u);break;case"range":a.add(u)}}return{codedValueFields:[...l],rangeFields:[...a]}}_hashContingency(e,t,i=!1){if(t.length<1)return[b,!1];const n=[];let s=!1;for(const l of t){const t=e.values[l];if("any"===t.objectType){if(i)return[j,!0];s=!0,n.push(`${l}:.*`)}else if("null"===t.objectType)n.push(`${l}:${A}`);else{var o;n.push(`${l}:${null==(o=t.codedValue)?void 0:o.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([d({readOnly:!0})],w.prototype,"allInputFields",null),e([d()],w.prototype,"_layerFieldsByName",null),e([d({readOnly:!0})],w.prototype,"_inputFieldCache",void 0),e([d({readOnly:!0})],w.prototype,"_inputFieldGroupCache",void 0),e([d()],w.prototype,"contingencyConstraintViolations",void 0),e([d()],w.prototype,"description",null),e([d()],w.prototype,"feature",null),e([d()],w.prototype,"fieldsWithContingentValues",null),e([d({type:h})],w.prototype,"formTemplate",null),e([d({readOnly:!0,dependsOn:["formTemplate","messages","feature","layer.fields","layer.loaded","state"]})],w.prototype,"inputFields",null),e([d()],w.prototype,"joinedContingentValues",null),e([d()],w.prototype,"layer",null),e([d()],w.prototype,"messages",void 0),e([d()],w.prototype,"state",null),e([d()],w.prototype,"strict",void 0),e([d()],w.prototype,"submittable",null),e([d()],w.prototype,"title",null),e([d()],w.prototype,"valid",null),e([d()],w.prototype,"getValues",null),e([d()],w.prototype,"submit",null),w=e([p(I)],w);const x=w;export{x 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 s from"../../core/Logger.js";import{destroyMaybe as o,isSome as l,isNone as r}from"../../core/maybe.js";import{EsriPromiseMixin as a}from"../../core/Promise.js";import{watch as u}from"../../core/reactiveUtils.js";import{ReentrantObjectPool as c}from"../../core/ReentrantObjectPool.js";import{property as d}from"../../core/accessorSupport/decorators/property.js";import"../../core/arrayUtils.js";import"../../core/has.js";import"../../core/accessorSupport/ensureType.js";import{subclass as p}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 v}from"../../intl/locale.js";import{fetchMessageBundle as F}from"../../intl/messages.js";function C(e){return!!e.inputFields}const V=new t({attributes:{}}),E="esri.widgets.FeatureForm.FeatureFormViewModel",I=s.getLogger(E),b="#JSAPI_CONTINGENT_VALUE_EMPTY_HASH",j="#JSAPI_CONTINGENT_VALUE_ANY_HASH",A="#JSAPI_CONTINGENT_VALUE_NULL_HASH";let w=class extends(n(a(i.EventedAccessor))){constructor(e){super(e),this._arcade=null,this._compiledExpressions=new Map,this._contingentValuesCache=null,this._fieldPool=new c(y,(e=>this.handles.add(u((()=>e.value),(()=>{e.isUsingValueExpression&&this._afterValueChange(e)})),e.id)),(({id:e})=>this.handles.remove(e))),this._fieldGroupPool=new c(_),this._featureClone=V.clone(),this._initialFeature=V.clone(),this._needsArcade=!1,this._inputFieldCache=new Map,this._inputFieldGroupCache=new Map,this.contingencyConstraintViolations=new Map,this.messages=null,this.strict=!1}initialize(){const e=async()=>this.messages=await F("esri/widgets/FeatureForm/t9n/FeatureForm");e();const t=u((()=>this.layer),(e=>{"feature"===(null==e?void 0:e.type)&&this.addResolvingPromise(m.createLoadedLayerContingentValuesCache(e).then((e=>{this._contingentValuesCache=e,this.notifyChange("fieldsWithContingentValues")})))}),{initial:!0}),i=u((()=>{var e,t;const{formTemplate:i}=this;if(r(i))return null;const n=null!=(e=i.expressionInfos)?e:[],s=null!=(t=i.elements)?t:[];return[...n.map((e=>e.expression)),...null==s?void 0:s.map((e=>this._getExpressionsFromElementRecursive(e))).flat()]}),(async e=>{if(e.length<1)return;const t=new Set(e),n=new Map;if(l(this.formTemplate)&&l(this.formTemplate.expressionInfos))for(const i of this.formTemplate.expressionInfos)t.delete(i.name),n.set(i.expression,i.name);for(const i of this._compiledExpressions.keys())t.delete(i);if(t.size<1)return;this._needsArcade=!0;const s=await g();this._arcade=s;const{arcadeUtils:o}=s;for(const l of t.values()){var r;o.hasGeometryOperations(l)&&(await o.enableGeometryOperations(),i.remove()),this._setFunctionForExpression(null!=(r=n.get(l))?r:l,l)}this.notifyChange("inputFields")})),n=u((()=>this.formTemplate),(()=>this._compiledExpressions.clear()));this.handles.add([v(e),i,n,t])}destroy(){this.feature=null,this.layer=null,this._contingentValuesCache=o(this._contingentValuesCache),this._fieldPool.destroy(),this._fieldGroupPool.destroy()}get allInputFields(){return this.inputFields.reduce(((e,t)=>C(t)?[...e,...t.inputFields]:[...e,t]),[])}get _layerFieldsByName(){return new Map(this.layer.fields.map((e=>[e.name,e])))}get description(){const{formTemplate:e}=this;return l(e)?e.description:""}set description(e){void 0===e?this._clearOverride("description"):this._override("description",e)}get feature(){return this._get("feature")}set feature(e){this._featureClone=e?e.clone():V.clone(),this._initialFeature=this._featureClone.clone(),this._inputFieldCache.clear(),this._inputFieldGroupCache.clear(),this.contingencyConstraintViolations.clear(),this._set("feature",e)}get fieldsWithContingentValues(){if(r(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){void 0===e?this._clearOverride("formTemplate"):this._override("formTemplate",e)}get inputFields(){const{_arcade:e,_featureClone:t,_initialFeature:i,_inputFieldCache:n,_needsArcade:s,formTemplate:o,messages:r,layer:a,state:u}=this;if("ready"!==u||s&&!e)return[];const c=t.clone(),d=Array.from(n.keys()),p={arcade:e,feature:c,initialFeature:i,layer:a,messages:r},h=l(o)&&o.elements.length>0?this._generateInputFieldsFromElements(o.elements,p):this._generateInputFieldsFromLayerFields(null==a?void 0:a.fields,p);return this._cullInputFieldCache(this._flattenGroups(h).map((e=>e.name)),d),this._releasePreviousInputFields(),h.filter((e=>e.visible))}get joinedContingentValues(){return this._joinContingentValues()}get layer(){var e;return null!=(e=this.feature)&&e.sourceLayer&&"applyEdits"in this.feature.sourceLayer?this.feature.sourceLayer:null}set layer(e){e?this._override("layer",e):this._clearOverride("layer")}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 title(){const{formTemplate:e}=this;return l(e)?e.title:""}set title(e){void 0===e?this._clearOverride("title"):this._override("title",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){var t;const{_featureClone:i,layer:n}=this,s=!(null==n||!n.getField(e));return null!=(t=i.getAttribute(e))?t:s?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,r(i))return[];const{invalid:s,incomplete:o}=i.validateContingencyConstraints(e),l=[...s,...null!=t&&t.includeIncompleteViolations?o:[]];for(const r of l)for(const e of r.fieldGroup.fields)n.set(e,r);return l}_cullInputFieldCache(e,t){const i=t.filter((t=>!e.includes(t)));for(const n in i)this._inputFieldCache.delete(n)}_flattenGroups(e){return e.flatMap((e=>"groupElement"in e?e.inputFields:e))}_releasePreviousInputFields(){const e=this._get("inputFields");if(e&&!(e.length<1))for(const t of e)"groupElement"in t?this._releaseInputFieldGroup(t):this._releaseInputField(t)}_releaseInputFieldGroup(e){e.inputFields.forEach((e=>this._releaseInputField(e))),this._fieldGroupPool.release(e)}_releaseInputField(e){this._fieldPool.release(e)}_emitChangeEvent({name:e,valid:t,value:i}){this.emit("value-change",{layer:this.layer,feature:this.feature,fieldName:e,value:i,valid:t})}_generateInputFieldsFromElements(e,t){const i=[];for(const n of e)this._isSupportedElement(n)&&i.push("group"===n.type?this._acquireAndInitializeInputFieldGroup(n,t):this._acquireAndInitializeInputField({field:this._layerFieldsByName.get(n.fieldName),fieldElement:n,...t}));return i}_generateInputFieldsFromLayerFields(e,t){return Array.isArray(e)?e.map((e=>this._acquireAndInitializeInputField({field:e,fieldElement:null,...t}))):(I.warn(E,"No attribute fields found."),[])}_acquireAndInitializeInputField(e){var t,i,n,s,o,l;const{arcade:r,feature:a,field:u,fieldElement:c,group:d,initialFeature:p,layer:h,messages:f}=e,m=null!=(t=this._compiledExpressions.get(null==c?void 0:c.requiredExpression))?t:void 0,g=null!=(i=this._compiledExpressions.get(null==c?void 0:c.visibilityExpression))?i:void 0,y=null!=(n=this._compiledExpressions.get(null==c?void 0:c.valueExpression))?n:void 0,_=null!=(s=this._compiledExpressions.get(null==c?void 0:c.editableExpression))?s:void 0,v=u.name,F=null!=(o=null==(l=this._inputFieldCache.get(v))?void 0:l.value)?o:this.getValue(v),C=this._fieldPool.acquire();return this._inputFieldCache.set(v,C),C.set({field:u,fieldElement:c,arcade:r,feature:a,group:d,initialFeature:p,layer:h,messages:f,requiredFunction:m,visibilityFunction:g,editableFunction:_,valueFunction:y,value:F})}_acquireAndInitializeInputFieldGroup(e,t){const i=this._fieldGroupPool.acquire(),n=[];for(const r of e.elements)this._isSupportedElement(r)&&n.push(this._acquireAndInitializeInputField({field:this._layerFieldsByName.get(r.fieldName),fieldElement:r,group:i,...t}));const{arcade:s,feature:o}=t,l=this._compiledExpressions.get(e.visibilityExpression);return i.set({arcade:s,feature:o,groupElement:e,inputFields:n,visibilityFunction:l})}_afterValueChange(e){const{name:t,value:i}=e;if(this.get("layer.typeIdField")===e.name&&"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),this.notifyChange("inputFields"),this._emitChangeEvent(e)}_getExpressionsFromElementRecursive(e){const t=[];if(e.visibilityExpression&&t.push(e.visibilityExpression),"field"===e.type){const i=["requiredExpression","valueExpression","editableExpression"];for(const n of i)e[n]&&t.push(e[n])}if("group"===e.type&&e.elements)for(const i of e.elements)t.push(...this._getExpressionsFromElementRecursive(i));return t}_setFunctionForExpression(e,t){const{_arcade:{arcadeUtils:i},_compiledExpressions:n}=this;n.set(e,i.createFunction(t))}_isSupportedElement(e){return"field"===e.type||"group"===e.type||(I.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(r(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 a of e)for(const e of a.fields)if(t.has(e)){const s=t.get(e),o=a,l=[s.name,o.name].sort().join("|");if(n.has(l))continue;i.push([s,o]),n.add(l),t.set(e,o)}else t.set(e,a);const s=new Set(i.flat()),o=new Set(e);for(const a of s)o.delete(a);const l=new Map,r=new Map;for(const a of new Set(i.flat())){const e=Symbol(a.name);l.set(e,new Set([a])),r.set(a,e)}for(const[a,u]of i){const e=r.get(a),t=r.get(u);if(e===t)continue;const i=l.get(e),n=l.get(t);for(const s of n)i.add(s),r.set(s,e);l.delete(t)}return[[...l.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]),a=new Map;for(const l of i.contingencies){const[e]=this._hashContingency(l,s.codedValueFields,!0);a.has(e)?a.get(e).push(l):a.set(e,[l])}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(a,i):a.get(i);if(a.has(j)&&o.push(...this._findMatchingContingenciesContainingAny(t,a.get(j),s.codedValueFields)),!r(o))for(const a of o){const i=s.rangeFields.length>0?this._joinContingenciesWithRangeDomains(a,t,s.rangeFields):this._joinContingencies(a,t);if(r(i))break;const[n]=this._hashContingency(i,l.codedValueFields,!0);e.has(n)?e.get(n).push(i):e.set(n,[i])}}a=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(a,e):a.get(e);if(a.has(j)&&i.push(...this._findMatchingContingenciesContainingAny(c,a.get(j),s.codedValueFields)),!r(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:l,rightIsNull:r,bothAreNull:a,leftIsAny:u,rightIsAny:c,bothAreAny:d,leftIsRange:p,rightIsRange:h}=this._compareObjectTypes(i.objectType,o.objectType);if(a||d)continue;if(l&&c||r&&u){n.values[s]=new f({objectType:"null"});continue}if(l&&h||r&&p)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=>{var n,s;const o=t.values[i],l=e.values[i];return"any"===o.objectType||"any"===l.objectType||(null==(n=o.codedValue)?void 0:n.code)===(null==(s=l.codedValue)?void 0:s.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,l=new Set,a=new Set;for(const u of s)if(o.has(u)){const e=this.layer.getFieldDomain(u,{feature:this.feature});if(r(e))continue;switch(e.type){case"coded-value":l.add(u);break;case"range":a.add(u)}}return{codedValueFields:[...l],rangeFields:[...a]}}_hashContingency(e,t,i=!1){if(t.length<1)return[b,!1];const n=[];let s=!1;for(const l of t){const t=e.values[l];if("any"===t.objectType){if(i)return[j,!0];s=!0,n.push(`${l}:.*`)}else if("null"===t.objectType)n.push(`${l}:${A}`);else{var o;n.push(`${l}:${null==(o=t.codedValue)?void 0:o.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([d({readOnly:!0})],w.prototype,"allInputFields",null),e([d()],w.prototype,"_layerFieldsByName",null),e([d({readOnly:!0})],w.prototype,"_inputFieldCache",void 0),e([d({readOnly:!0})],w.prototype,"_inputFieldGroupCache",void 0),e([d()],w.prototype,"contingencyConstraintViolations",void 0),e([d()],w.prototype,"description",null),e([d()],w.prototype,"feature",null),e([d()],w.prototype,"fieldsWithContingentValues",null),e([d({type:h})],w.prototype,"formTemplate",null),e([d({readOnly:!0,dependsOn:["formTemplate","messages","feature","layer.fields","layer.loaded","state"]})],w.prototype,"inputFields",null),e([d()],w.prototype,"joinedContingentValues",null),e([d()],w.prototype,"layer",null),e([d()],w.prototype,"messages",void 0),e([d()],w.prototype,"state",null),e([d()],w.prototype,"strict",void 0),e([d()],w.prototype,"submittable",null),e([d()],w.prototype,"title",null),e([d()],w.prototype,"valid",null),e([d()],w.prototype,"getValues",null),e([d()],w.prototype,"submit",null),w=e([p(E)],w);const x=w;export{x as default};