@arcgis/core 4.23.1 → 4.23.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/esri/core/workers/RemoteClient.js +1 -1
- package/assets/esri/core/workers/chunks/{d209d82484aa725c5aa9.js → d006b4a239e93eeb9619.js} +1 -1
- package/assets/esri/core/workers/chunks/fcd87df3909e94410950.js +1 -0
- package/assets/esri/themes/base/widgets/_BasemapLayerList.scss +1 -1
- package/assets/esri/themes/base/widgets/_LayerList.scss +1 -1
- package/assets/esri/themes/dark/main.css +1 -1
- package/assets/esri/themes/dark-blue/main.css +1 -1
- package/assets/esri/themes/dark-green/main.css +1 -1
- package/assets/esri/themes/dark-purple/main.css +1 -1
- package/assets/esri/themes/dark-red/main.css +1 -1
- package/assets/esri/themes/light/main.css +1 -1
- package/assets/esri/themes/light/view.css +1 -1
- package/assets/esri/themes/light-blue/main.css +1 -1
- package/assets/esri/themes/light-green/main.css +1 -1
- package/assets/esri/themes/light-purple/main.css +1 -1
- package/assets/esri/themes/light-red/main.css +1 -1
- package/config.js +1 -1
- package/interfaces.d.ts +12 -9
- package/layers/RouteLayer.js +1 -1
- package/package.json +1 -1
- package/support/revision.js +1 -1
- package/symbols/cim/CIMSymbolDrawHelper.js +1 -1
- package/views/2d/engine/webgl/brushes/WGLGeometryBrush.js +1 -1
- package/views/2d/engine/webgl/brushes/WGLGeometryBrushFill.js +1 -1
- package/views/2d/engine/webgl/brushes/WGLGeometryBrushLine.js +1 -1
- package/views/2d/engine/webgl/shaders/sources/shaderRepository.js +1 -1
- package/widgets/Directions/DirectionsViewModel.js +1 -1
- package/widgets/Directions.js +1 -1
- package/widgets/FeatureForm/FeatureFormViewModel.js +1 -1
- package/widgets/FeatureForm/InputField.js +1 -1
- package/widgets/FeatureForm.js +1 -1
- package/assets/esri/core/workers/chunks/b04af5e4a9ae0c90a1de.js +0 -1
package/widgets/Directions.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{_ 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} · ${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} · ${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};
|
|
@@ -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"../../intl.js";import t from"../../core/Accessor.js";import{HandleOwnerMixin as i}from"../../core/HandleOwner.js";import{isSome as l,isNone as r,get as n}from"../../core/maybe.js";import{watch as o}from"../../core/reactiveUtils.js";import{generateUID as s}from"../../core/uid.js";import{property as a}from"../../core/accessorSupport/decorators/property.js";import"../../core/arrayUtils.js";import"../../core/has.js";import"../../core/accessorSupport/ensureType.js";import{subclass as u}from"../../core/accessorSupport/decorators/subclass.js";import d from"../../layers/support/CodedValueDomain.js";import"../../layers/support/Domain.js";import"../../layers/support/InheritedDomain.js";import"../../layers/support/RangeDomain.js";import{validateDomainValue as p,DomainValidationError as c,getDomainRange as
|
|
5
|
+
import{_ as e}from"../../chunks/tslib.es6.js";import"../../intl.js";import t from"../../core/Accessor.js";import{HandleOwnerMixin as i}from"../../core/HandleOwner.js";import{isSome as l,isNone as r,get as n}from"../../core/maybe.js";import{watch as o}from"../../core/reactiveUtils.js";import{generateUID as s}from"../../core/uid.js";import{property as a}from"../../core/accessorSupport/decorators/property.js";import"../../core/arrayUtils.js";import"../../core/has.js";import"../../core/accessorSupport/ensureType.js";import{subclass as u}from"../../core/accessorSupport/decorators/subclass.js";import d from"../../layers/support/CodedValueDomain.js";import"../../layers/support/Domain.js";import"../../layers/support/InheritedDomain.js";import"../../layers/support/RangeDomain.js";import{validateDomainValue as p,DomainValidationError as c,getDomainRange as m}from"../../layers/support/domainUtils.js";import{isNumericField as h,isStringField as y,isDateField as f,TypeValidationError as v,validateFieldValue as g,getFeatureEditFields as E,getFeatureGeometryFields as b,NumericRangeValidationError as _,getFieldRange as x}from"../../layers/support/fieldUtils.js";import{substitute as F}from"../../intl/substitute.js";var V,O;!function(e){e.Text="text",e.Number="number",e.Date="date",e.Unsupported="unsupported"}(V||(V={})),function(e){e.TOO_SHORT="length-validation-error::too-short"}(O||(O={}));const U={type:"number"},T={type:"number",intlOptions:{notation:"scientific"}},j={type:"date",intlOptions:{day:"2-digit",month:"2-digit",year:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}};function A(e){return e>=1e7||e<=-1e7}let D=class extends(i(t)){constructor(e){super(e),this._storedValue=null,this.arcade=null,this.editableFunction=null,this.id=s().toString(),this.requiredFunction=null,this.valueFunction=null,this.visibilityFunction=null,this.feature=null,this.field=null,this.fieldElement=null,this.layer=null,this.description=null,this.inputType=null,this.error=null,this.group=null,this.hint=null,this.messages=null,this.name=null}initialize(){this.handles.add(o((()=>this.value),((e,t)=>{if(e!==t){const{feature:e,name:t,value:i}=this;e.setAttribute(t,i)}})))}get _configAllowsEdits(){var e,t,i;const{fieldElement:r,layer:n,name:o}=this;if(l(r))return!1!==r.editable;const s="subtype-group"!==(null==n?void 0:n.type)?null==n||null==(e=n.popupTemplate)||null==(t=e.fieldInfos)?void 0:t.find((({fieldName:e})=>e===o)):null;return null==(i=null==s?void 0:s.isEditable)||i}get _layerFieldAllowsEdits(){const{field:e,layer:t}=this;return(null==t?void 0:t.capabilities.operations.supportsEditing)&&(null==e?void 0:e.editable)}get isUsingValueExpression(){return this._shouldUseValueExpression()}get evaluatedEditableExpression(){const{editableFunction:e}=this;if(r(e))return null;const{arcade:t}=this;return t.arcadeUtils.executeFunction(e,t.arcadeUtils.createExecContext(this.feature))}get evaluatedRequiredExpression(){const{requiredFunction:e}=this;if(r(e))return null;const{arcade:t}=this;return t.arcadeUtils.executeFunction(e,t.arcadeUtils.createExecContext(this.feature))}get evaluatedVisibilityExpression(){const{visibilityFunction:e}=this;if(r(e))return null;const{arcade:t}=this;return t.arcadeUtils.executeFunction(e,t.arcadeUtils.createExecContext(this.feature))}get evaluatedValueExpression(){const{valueFunction:e}=this;if(r(e))return null;const{arcade:t}=this;return t.arcadeUtils.executeFunction(e,t.arcadeUtils.createExecContext(this.feature))}set initialFeature(e){this._set("initialFeature",e),this.notifyChange("valid")}get domain(){var e;const{typeIdField:t}=this.layer,i=t===this.name,r=null==(e=this.field)?void 0:e.domain;if(i&&!r){const{layer:e}=this,t="subtype-group"===e.type?e.sublayers.map((({subtypeCode:e,title:t})=>({id:e,name:t}))):e.types.map((({id:e,name:t})=>({code:e,name:t})));return new d({name:"__internal-type-based-coded-value-domain__",codedValues:t})}const{feature:o}=this,s=t&&this.layer.getFieldDomain(this.name,{feature:o})||r,a=n(this.fieldElement,"domain");return l(a)&&this._isDomainCompatible(a)?a:s}get editable(){var e;return!!this._layerFieldAllowsEdits&&(null!=(e=this.evaluatedEditableExpression)?e:this._configAllowsEdits)}get errorMessage(){return this._toErrorMessage()}get includeTime(){var e;const{fieldElement:t}=this,i=l(t)&&"datetime-picker"===(null==(e=t.input)?void 0:e.type)?t.input.includeTime:void 0;return void 0===i||i}get label(){return l(this.fieldElement)&&this.fieldElement.label||this.field.alias||this.field.name}get maxLength(){const e=-1;if(this.type===V.Date)return e;const{field:t,fieldElement:i}=this,r=null==t?void 0:t.length,n=l(i)&&N(i.input)?i.input.maxLength:NaN;return!isNaN(n)&&n>=e&&(r===e||n<=r)?n:r}get minLength(){const e=-1;if(this.type===V.Date)return e;const{field:t,fieldElement:i}=this,r=null==t?void 0:t.length,n=l(i)&&N(i.input)?i.input.minLength:NaN;return!isNaN(n)&&n>=e&&(r===e||n<=r)?n:e}get required(){var e,t;return!!this.editable&&(!1===(null==(e=this.field)?void 0:e.nullable)||null!=(t=this.evaluatedRequiredExpression)&&t)}get submittable(){return!!this.valid||this.initialFeature.getAttribute(this.field.name)===this.value}get type(){const{field:e}=this;return h(e)?V.Number:y(e)?V.Text:f(e)?V.Date:V.Unsupported}get valid(){const e=this._validate();return this._set("error",e),null===e}get value(){return this._shouldUseValueExpression()?this.evaluatedValueExpression:this.get("_storedValue")}set value(e){this.notifyChange("evaluatedVisibilityExpression"),this.set("_storedValue",e)}get visible(){return!this._isEditorField()&&(l(this.fieldElement)?null==(e=this.evaluatedVisibilityExpression)||e:this._isVisibleByDefault());var e}_isDomainCompatible(e){const{field:t}=this;if("coded-value"===(null==e?void 0:e.type)){const i=typeof e.codedValues[0].code;if("string"===i&&y(t)||"number"===i&&h(t))return!0}return!!("range"===(null==e?void 0:e.type)&&h(t)||f(t))}_validate(){const{domain:e,field:t,initialFeature:i,minLength:l,required:r,type:n,valid:o,value:s}=this,a=r&&null===s,u=void 0!==o;return!a&&i.getAttribute(t.name)===s&&u?null:"text"===n&&l>-1&&"string"==typeof s&&s.length<l?O.TOO_SHORT:e?null!==s||r?p(e,s):null:a?v.INVALID_TYPE:g(t,s)}_isVisibleByDefault(){var e;const t=null==(e=this.field)?void 0:e.type;return"oid"!==t&&"global-id"!==t&&!this._isGeometryField()}_isEditorField(){return E(this.layer).indexOf(this.name)>-1}_isGeometryField(){return b(this.layer).indexOf(this.name)>-1}_shouldUseValueExpression(){return this._layerFieldAllowsEdits&&!this._configAllowsEdits&&l(this.valueFunction)}_toErrorMessage(){const{domain:e,field:t,messages:i,minLength:l,value:r,required:n,type:o}=this,s=this.error;if(n&&null===r)return i.validationErrors.cannotBeNull;if(s===c.VALUE_OUT_OF_RANGE||s===_.OUT_OF_RANGE){const l=m(e)||x(t);return F(i.validationErrors.outsideRange,l,{format:{max:"date"===o?j:A(l.max)?T:U,min:"date"===o?j:A(l.min)?T:U}})}return s===c.INVALID_CODED_VALUE?i.validationErrors.invalidCodedValue:s===v.INVALID_TYPE?i.validationErrors.invalidType:s===O.TOO_SHORT?F(i.validationErrors.tooShort,{min:l}):null}};function N(e){return!!e&&"maxLength"in e}e([a()],D.prototype,"_storedValue",void 0),e([a()],D.prototype,"_configAllowsEdits",null),e([a()],D.prototype,"_layerFieldAllowsEdits",null),e([a()],D.prototype,"arcade",void 0),e([a()],D.prototype,"editableFunction",void 0),e([a()],D.prototype,"requiredFunction",void 0),e([a()],D.prototype,"valueFunction",void 0),e([a()],D.prototype,"isUsingValueExpression",null),e([a()],D.prototype,"visibilityFunction",void 0),e([a()],D.prototype,"evaluatedEditableExpression",null),e([a()],D.prototype,"evaluatedRequiredExpression",null),e([a()],D.prototype,"evaluatedVisibilityExpression",null),e([a()],D.prototype,"evaluatedValueExpression",null),e([a()],D.prototype,"feature",void 0),e([a()],D.prototype,"field",void 0),e([a()],D.prototype,"fieldElement",void 0),e([a()],D.prototype,"initialFeature",null),e([a()],D.prototype,"layer",void 0),e([a({aliasOf:"fieldElement.description"})],D.prototype,"description",void 0),e([a()],D.prototype,"domain",null),e([a()],D.prototype,"editable",null),e([a({aliasOf:"fieldElement.input.type"})],D.prototype,"inputType",void 0),e([a({readOnly:!0})],D.prototype,"error",void 0),e([a({dependsOn:["error","messages","value"]})],D.prototype,"errorMessage",null),e([a()],D.prototype,"group",void 0),e([a({aliasOf:"fieldElement.hint"})],D.prototype,"hint",void 0),e([a()],D.prototype,"includeTime",null),e([a()],D.prototype,"label",null),e([a()],D.prototype,"maxLength",null),e([a()],D.prototype,"minLength",null),e([a()],D.prototype,"messages",void 0),e([a({aliasOf:"field.name"})],D.prototype,"name",void 0),e([a()],D.prototype,"required",null),e([a()],D.prototype,"submittable",null),e([a()],D.prototype,"type",null),e([a()],D.prototype,"valid",null),e([a({value:null})],D.prototype,"value",null),e([a()],D.prototype,"visible",null),D=e([u("esri.widgets.FeatureForm.InputField")],D);const L=D;export{L as default};
|
package/widgets/FeatureForm.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{_ as e}from"../chunks/tslib.es6.js";import"../intl.js";import{neverReached as t}from"../core/compilerUtils.js";import{isNone as i,isSome as a}from"../core/maybe.js";import{aliasOf as n}from"../core/accessorSupport/decorators/aliasOf.js";import"../core/arrayUtils.js";import"../core/has.js";import"../core/accessorSupport/ensureType.js";import{property as l}from"../core/accessorSupport/decorators/property.js";import{subclass as s}from"../core/accessorSupport/decorators/subclass.js";import{getDomainRange as r}from"../layers/support/domainUtils.js";import{getFieldRange as o}from"../layers/support/fieldUtils.js";import u from"./Widget.js";import d from"./FeatureForm/FeatureFormViewModel.js";import{Heading as p,incrementHeadingLevel as c}from"./support/Heading.js";import"./support/widgetUtils.js";import{messageBundle as m}from"./support/decorators/messageBundle.js";import"../core/Logger.js";import{vmEvent as h}from"./support/decorators/vmEvent.js";import{tsx as f}from"./support/jsxFactory.js";import{DateTime as _}from"luxon";import{getLocale as v}from"../intl/locale.js";const g={base:"esri-feature-form",form:"esri-feature-form__form",formHeader:"esri-feature-form__form-header",label:"esri-feature-form__label",inputField:"esri-feature-form__input",inputDate:"esri-feature-form__input--date",inputTime:"esri-feature-form__input--time",inputRadioGroup:"esri-feature-form__input--radio-group",inputRadio:"esri-feature-form__input--radio",inputRadioLabel:"esri-feature-form__input--radio-label",inputDisabled:"esri-feature-form__input--disabled",inputSwitch:"esri-feature-form__input--switch",inputInvalid:"esri-feature-form__input--invalid",inputIconInvalid:"esri-feature-form__input-icon--invalid",errorMessage:"esri-feature-form__field-error-message",description:"esri-feature-form__description-text",dateInputPart:"esri-feature-form__date-input-part",loneDateInputPart:"esri-feature-form__date-input-part--lone",dateInputContainer:"esri-feature-form__date-input-container",dateFormatHint:"esri-feature-form__date-format-hint",group:"esri-feature-form__group",groupLabel:"esri-feature-form__group-label",groupHeader:"esri-feature-form__group-header",groupHeading:"esri-feature-form__group-header",groupTitle:"esri-feature-form__group-title",groupDescription:"esri-feature-form__group-description",groupToggleIcon:"esri-feature-form__group-toggle-icon",groupCollapsed:"esri-feature-form__group--collapsed",groupSequential:"esri-feature-form__group--sequential",groupActive:"esri-feature-form__group--active",collapseIcon:"esri-icon-up",errorIcon:"esri-icon-notice-triangle",expandIcon:"esri-icon-down",widget:"esri-widget",panel:"esri-widget--panel",input:"esri-input",select:"esri-select"},b={datePattern:"D",timePattern:"tt"};function y(e){return e&&e.inputFields}let I=class extends u{constructor(e,t){super(e,t),this._activeDateFieldEdit=null,this._activeInputName=null,this._fieldFocusNeeded=!1,this._fieldToInitialIncompatibleDomainValue=new Map,this._switchFieldsWithInitialIncompatibleValue=new Set,this._userUpdatedInputFieldNames=new Set,this.description=null,this.feature=null,this.fieldConfig=null,this.formTemplate=null,this.groupDisplay="all",this.headingLevel=2,this.label=void 0,this.layer=null,this.messages=null,this.messagesTemplates=null,this.strict=null,this.title=null,this.viewModel=new d,this._handleSwitchClick=e=>{e.target===e.currentTarget&&e.stopImmediatePropagation()},this._handleRadioInputChange=e=>{this._commitInputValue(e.target)},this._handleInputInput=e=>{this._commitInputValue(e.currentTarget,!0)},this._handleFormKeyDown=this._handleFormKeyDown.bind(this),this._handleInputBlur=this._handleInputBlur.bind(this),this._handleInputFocus=this._handleInputFocus.bind(this),this._handleNumberInputMouseDown=this._handleNumberInputMouseDown.bind(this),this._handleInputKeyDown=this._handleInputKeyDown.bind(this),this._handleOptionChange=this._handleOptionChange.bind(this),this._handleGroupClick=this._handleGroupClick.bind(this),this._handleSubmit=this._handleSubmit.bind(this),this._afterInputCreateOrUpdate=this._afterInputCreateOrUpdate.bind(this)}initialize(){this.own(this.watch("feature",(()=>{const e=this._getFocusableInput("forward");this._activeInputName=e&&e.name,this._userUpdatedInputFieldNames.clear(),this._fieldToInitialIncompatibleDomainValue.clear(),this._switchFieldsWithInitialIncompatibleValue.clear(),this._fieldFocusNeeded=!0})),this.on("submit",(e=>{if(e.invalid.length>0){const[t]=e.invalid;e.invalid.forEach((e=>this._userUpdatedInputFieldNames.add(e))),this._activeInputName=t,this._fieldFocusNeeded=!0,this.scheduleRender()}})))}loadDependencies(){return Promise.all([import("@esri/calcite-components/dist/components/calcite-combobox.js"),import("@esri/calcite-components/dist/components/calcite-combobox-item.js"),import("@esri/calcite-components/dist/components/calcite-combobox-item-group.js"),import("@esri/calcite-components/dist/components/calcite-input-message.js"),import("@esri/calcite-components/dist/components/calcite-switch.js")])}destroy(){this._userUpdatedInputFieldNames.clear(),this._userUpdatedInputFieldNames=null}getValues(){return null}submit(){return null}render(){const{state:e}=this.viewModel;return f("div",{class:this.classes(g.base,g.widget,g.panel)},"ready"===e?this.renderForm():null)}renderForm(){const e=this.title?f(p,{key:"title",level:this.headingLevel},this.title):null,t=this.description?f("p",{class:g.description,key:"description"},this.description):null,i=e||t?f("div",{class:g.formHeader},e,t):null;return f("form",{class:g.form,novalidate:!0,onsubmit:this._handleSubmit,onkeydown:this._handleFormKeyDown},i,this.renderFields())}renderFields(){const{viewModel:{inputFields:e}}=this;return e.map(((e,t)=>y(e)?this.renderGroup(e,t):this.renderLabeledField(e)))}renderGroup(e,t){const{description:i,inputFields:a,label:n,state:l}=e,s=this.viewModel.findField(this._activeInputName),r=!(!s||s.group!==e),o=`${this.id}_group_${t}`,u=`${this.id}_group-label_${t}`,d=`${this.id}_group-description_${t}`,m=i?f("p",{class:this.classes(g.groupDescription,g.description),id:d},i):null,h="sequential"===this.groupDisplay,_=h?r:"expanded"===l,v=_?g.collapseIcon:g.expandIcon;return f("fieldset",{"aria-expanded":_.toString(),"aria-labelledby":u,"aria-describedby":i?d:"",class:this.classes(g.group,h?g.groupSequential:null,_?null:g.groupCollapsed,r?g.groupActive:null),"data-group":e,id:o,key:t,onclick:this._handleGroupClick},f("button",{role:h?"presentation":void 0,class:g.groupHeader,type:"button",tabIndex:h?-1:0},f("div",{class:g.groupTitle},f(p,{class:g.groupLabel,id:u,level:this.title?c(this.headingLevel):this.headingLevel},n),m),h?null:f("span",{class:this.classes(v,g.groupToggleIcon)})),a.map((e=>this.renderLabeledField(e))))}_getFocusableInput(e,t){const i=this.viewModel.allInputFields,a="forward"===e?i:i.slice().reverse();let n;if(t)if(y(t))n=a.indexOf(t.inputFields[0]);else{let i;if(this._isInputFieldInGroup(t)&&"collapsed"===t.group.state){const{inputFields:a}=t.group;i="forward"===e?a[a.length-1]:a[0]}else i=t;n=a.indexOf(i)+1}else n=0;for(let l=n;l<a.length;l++){const e=a[l];if(e.visible)return e}return null}renderLabeledField(e){const{label:t,layer:i,type:a}=e;return f("label",{key:`${i.id}-${e.name}`,class:g.label},[t,"unsupported"!==a?this.renderInputField(e):this.renderUnsupportedField(e),this.renderAuxiliaryText(e)])}renderInputField(e){const{domain:t,name:i,type:a,value:n}=e,l=this.getCommonInputProps(e);if("coded-value"===(null==t?void 0:t.type)){if(this._inputFieldHasInputType(e,"switch")){const{fieldElement:t}=e;if(!(this._switchFieldsWithInitialIncompatibleValue.has(i)||null==n||t.input.onValue!==n&&t.input.offValue!==n))return this.renderSwitchInputField(n,l);this._switchFieldsWithInitialIncompatibleValue.add(i)}return"radio-buttons"===e.inputType?this.renderRadioButtonsInputField(n,t.codedValues.map((({code:e,name:t})=>({value:e,name:t}))),l):this.renderSelectInputField(n,this._getFieldValueOptions(i,t),l)}return"text"===a&&"text-area"===e.inputType?f("textarea",{...l}):"datetime-picker"===e.inputType||"date"===a?this.renderDateInputField(n,l):f("input",{type:"text"===a?"text":"number",...l})}_parseDateTime(e,t,i){if(i){var a;let n=_.fromJSDate(this._parseDate(e,i));const l=_.fromMillis(null!=(a=t.value)?a:Date.now());return n="date"===i?n.set({hour:l.hour,minute:l.minute,second:l.second}):n.set({day:l.day,month:l.month,year:l.year}),n.isValid?n.toMillis():null}const n=_.fromJSDate(this._parseDate(e));return n.isValid?n.toMillis():null}renderDateInputField(e,t){const{date:i,time:a}=this._formatDate(0),n=`${this.id}-${t.key}`,l=`${n}-date`,s=`${n}-time`,r=t["data-field"],{includeTime:o}=r,{_activeDateFieldEdit:u}=this;let{date:d,time:p}=this._formatDate(e);var c,m,h,_;(null==u?void 0:u.fieldName)===r.name&&(d=null!=(c=null==(m=u.date.input)?void 0:m.value)?c:d,p=null!=(h=null==(_=u.time.input)?void 0:_.value)?h:p);return f("div",{key:`${t.key}-date`,class:g.dateInputContainer},f("div",{class:this.classes(g.dateInputPart,o?null:g.loneDateInputPart)},f("input",{"aria-label":r.label,"aria-describedby":l,type:"text",...t,"data-date-part":"date",class:this.classes(t.class,g.inputDate),value:d}),f("div",{class:g.dateFormatHint,id:l},i)),o?f("div",{class:g.dateInputPart,key:"time-input"},f("input",{"aria-describedby":s,"aria-label":r.label,type:"text",...t,"data-date-part":"time",class:this.classes(t.class,g.inputTime),value:p}),f("div",{class:g.dateFormatHint,id:s},a)):null)}renderUnsupportedField(e){const t=this.getCommonInputProps(e);return f("input",{afterCreate:t.afterCreate,afterUpdate:t.afterUpdate,class:this.classes(g.input,g.inputField,g.inputDisabled),"data-field":t["data-field"],onfocus:t.onfocus,readOnly:!0,tabIndex:t.tabIndex,type:"text",value:t.value})}renderSelectInputField(e,t,a){const{messages:n,messagesTemplates:l}=this,s=t.map((t=>t.map((t=>f("calcite-combobox-item",{value:t.value,"text-label":t.name,key:t.value,selected:e===t.value}))))),r=a["data-field"],[o,u]=s;this._registerIncompatibleValue(e,t.flat(),r,(e=>{u.unshift(f("calcite-combobox-item",{value:`${e}`,"text-label":`${e}`,key:"incompatible-option",readOnly:!0}))}));const d=u.length>0?[f("calcite-combobox-item-group",{key:"recommended",label:n.recommended},o),f("calcite-combobox-item-group",{key:"other",label:l.other},u)]:o,p=i(r.fieldElement)||this._inputFieldHasInputType(r,"combo-box")&&r.fieldElement.input.showNoValueOption;if(!r.required&&p){const e="",t=this._inputFieldHasInputType(r,"combo-box")&&r.fieldElement.input.noValueOptionLabel||this.messages.empty;d.unshift(f("calcite-combobox-item",{value:e,"text-label":this.messages.empty,key:"empty-option"},t))}return f("calcite-combobox",{...a,"selection-mode":"single",disabled:a.readOnly,allowCustomValues:!1,onCalciteComboboxChange:e=>this._handleOptionChange(e.target)},d)}_registerIncompatibleValue(e,t,i,a){const n=this._fieldToInitialIncompatibleDomainValue,l=n.has(i.name);(l||null!=e&&""!==e&&!t.find((t=>t.value===e))||l)&&(l||n.set(i.name,e),null==a||a(n.get(i.name)))}renderRadioButtonsInputField(e,t,a){const n=a["data-field"],l=t.map((t=>this.renderRadioButton({key:t.name,label:t.name,name:n.name,value:t.value,selected:t.value===e,props:a})));this._registerIncompatibleValue(e,t,n);const s=i(n.fieldElement)||this._inputFieldHasInputType(n,"radio-buttons")&&n.fieldElement.input.showNoValueOption;if(!n.required&&s){const t="",i=this._inputFieldHasInputType(n,"radio-buttons")&&n.fieldElement.input.noValueOptionLabel||this.messages.empty,s=e===t||null===e;l.unshift(this.renderRadioButton({key:"empty-option",label:i,name:n.name,value:t,selected:s,props:a}))}return f("div",{key:`${a.key}-radio`,class:g.inputRadioGroup},l)}renderSwitchInputField(e,t){const i=t["data-field"],a=!!this._inputFieldHasInputType(i,"switch")&&e===i.fieldElement.input.onValue;return f("calcite-switch",{...t,class:g.inputSwitch,onclick:this._handleSwitchClick,checked:a,disabled:t.readOnly})}renderRadioButton({key:e,name:t,value:i,selected:a,label:n,props:l}){return f("label",{key:e,class:g.inputRadioLabel},f("input",{...l,class:g.inputRadio,name:t,type:"radio",value:i,checked:a,onchange:this._handleRadioInputChange}),n)}renderAuxiliaryText(e){const t=this._userUpdatedInputFieldNames.has(e.name)&&!e.valid?e.errorMessage:a(this.viewModel.contingencyConstraintViolations.get(e.name))?this.messages.validationErrors.valuesIncompatible:null;return a(t)?f("calcite-input-message",{status:"invalid",icon:!0,active:!0},t):e.description?f("div",{key:"description",class:g.description},e.description):void 0}getCommonInputProps(e){const{groupDisplay:t}=this,{editable:i,group:n,hint:l,maxLength:s,minLength:r,name:o,required:u,type:d,valid:p,value:c}=e,m=this._userUpdatedInputFieldNames.has(o),h=!i,f="all"===t&&a(n)&&"collapsed"===n.state;return{afterCreate:this._afterInputCreateOrUpdate,afterUpdate:this._afterInputCreateOrUpdate,"aria-invalid":p?"false":"true",class:this.classes(g.input,g.inputField,h?g.inputDisabled:null,m&&!p?g.inputInvalid:null),key:o,label:o,minlength:r>-1?`${r}`:"",maxlength:s>-1?`${s}`:"",...this._getNumberFieldConstraints(e),readOnly:h,value:null==c?"":`${c}`,"data-field":e,onfocus:this._handleInputFocus,oninput:this._handleInputInput,onblur:this._handleInputBlur,onkeydown:this._handleInputKeyDown,onmousedown:"number"===d?this._handleNumberInputMouseDown:null,placeholder:"number"===d||"text"===d?l:"",required:u,tabIndex:f?-1:0}}_isInputFieldInGroup(e){return!y(e)&&a(e.group)}_handleNumberInputMouseDown({target:e}){e.focus(),this.scheduleRender()}_getFieldValueOptions(e,t){const i=t.codedValues.map((({code:e,name:t})=>({value:e,name:t}))),a=this.viewModel.fieldsWithContingentValues.has(e)?this._getContingentValueOptions(e):[];if(a.length>0){const e=new Set(a.map((e=>e.value)));return[a,i.filter((t=>!e.has(t.value)))]}return[i,[]]}_getContingentValueOptions(e){const t={};for(const l of this.viewModel.allInputFields){const{name:a,value:n}=l;!i(n)&&a!==e&&this.viewModel.fieldsWithContingentValues.has(a)&&(t[a]=n)}const a=this.viewModel.joinedContingentValues.slice(),n=new Map;for(const l of a){const a=l.values[e];if(i(a)||"code"!==a.objectType&&"null"!==a.objectType)continue;const{code:s,name:r}="null"===a.objectType?{code:"",name:this.messages.empty}:a.codedValue;if(n.has(s))continue;Object.entries(t).every((([e,t])=>!l.values.hasOwnProperty(e)||this._valueIsValidContingentValue(t,l.values[e])))&&n.set(s,{name:r,value:s})}return[...n.values()]}_getNumberFieldConstraints(e){const t=r(e.domain)||o(e.field);return t&&t.max!==Number.MAX_VALUE&&t.min!==Number.MIN_VALUE?t:{min:null,max:null}}_afterInputCreateOrUpdate(e){const t=e["data-field"],i=this.viewModel.findField(this._activeInputName),a=this._fieldToInitialIncompatibleDomainValue.get(t.name)===t.value;this._fieldFocusNeeded&&i===t&&("radio-buttons"!==t.inputType||a||e.checked)&&(this._fieldFocusNeeded=!1,e.focus())}_handleInputFocus(e){const t=e.target,i=t["data-field"];this._activeInputName=i.name,"date"===i.type&&this._syncDateFieldEdits(t)}_handleInputBlur(e){const t=e.target,i=t["data-field"];if("date"===i.type){const n=e.relatedTarget,l=n&&n["data-field"];if(l&&"date"===i.type&&"date"===l.type&&i.field===l.field){if(""!==t.value&&""===n.value){var a;const l=n.getAttribute("data-date-part");n.value=this._formatDate(null!=(a=i.value)?a:Date.now())[l],this._parseDate(t.value,t.getAttribute("data-date-part"))&&this._commitInputValue(e.target,!0,!1)}return}}this._commitInputValue(t),this.scheduleRender()}_commitInputValue(e,t=!1,i=!0){const a=e["data-field"];if(this._activeDateFieldEdit){const{date:o,time:u}=this._activeDateFieldEdit,d=this._parseDateTime(e.value,a,o.active?"date":"time"),p=null!==this.viewModel.getValue(a.name),c=o.input&&(u.input||!a.includeTime),m=null===d;if(t){if(m)return;(c||!i||p)&&this._updateDateFieldValue(a,d)}else{var n,l;if(""===(null==(n=o.input)?void 0:n.value)||""===(null==(l=u.input)?void 0:l.value))this._updateDateFieldValue(a,null);else if(c){var s,r;const e=`${o.input.value} ${null!=(s=null==(r=u.input)?void 0:r.value)?s:""}`,t=this._parseDateTime(e,a);!(null!==t)&&p||this._updateDateFieldValue(a,t)}this._activeDateFieldEdit=null}}else this._updateFieldValue(e)}_handleInputKeyDown(e){const{key:t,altKey:i,ctrlKey:a,metaKey:n}=e,l=e.target["data-field"];if("Enter"===t)this._isInputFieldInGroup(l)&&"collapsed"===l.group.state&&(l.group.state="expanded");else{const{type:s}=l.field,r="single"===s||"double"===s,o=!i&&!a&&!n;if(("integer"===s||"small-integer"===s||r)&&o&&1===t.length){const i=Number(t),a=["-","+"],n=["e","."],l=r?[...a,...n]:a;isNaN(i)&&-1===l.indexOf(t)&&e.preventDefault()}}}_syncDateFieldEdits(e){var t,i;const a=e["data-field"];if("date"!==a.type)return;const n=e.getAttribute("data-date-part"),l="date"===n?{value:e.value,input:e,active:!0}:{...null==(t=this._activeDateFieldEdit)?void 0:t.date,active:!1},s="time"===n?{value:e.value,input:e,active:!0}:{...null==(i=this._activeDateFieldEdit)?void 0:i.time,active:!1};this._activeDateFieldEdit={fieldName:a.name,date:l,time:s}}_updateFieldValue(e){const t=e["data-field"],{name:i}=t;if(this.viewModel.setValue(i,this._parseValue(e)),this._userUpdatedInputFieldNames.add(i),this.viewModel.fieldsWithContingentValues.has(i)){const e=Object.fromEntries(Object.entries(this.getValues()).filter((([e,t])=>a(t))));this.viewModel.validateContingencyConstraints(e)}}_updateDateFieldValue(e,t){this.viewModel.setValue(e.name,t),this._userUpdatedInputFieldNames.add(e.name)}_parseValue(e){const t=e["data-field"],i=e.value;if(this._inputFieldHasInputType(t,"switch")&&!(e instanceof HTMLCalciteComboboxElement))return e.checked?t.fieldElement.input.onValue:t.fieldElement.input.offValue;if("radio-buttons"===t.inputType&&"radio"===e.type&&!e.checked)return t.value;const{type:a}=t;if("number"===a)return i?parseFloat(i):null;if("date"===a){if(!i)return null;const a=Number(i);if(!isNaN(a))return a;const n=e.getAttribute("data-date-part"),l=this._parseDate(i,n);if(!l)return null;let s=_.fromJSDate(l);const r=t.domain,o=_.now();let u=o;if(r&&"range"===r.type){const e=_.fromMillis(r.maxValue);o<e&&(u=e)}const d=this.viewModel.getValue(t.name),p=null!=d?_.fromMillis(d):u;return s="date"===n?s.set({hour:p.hour,minute:p.minute,second:p.second}):s.set({day:p.day,month:p.month,year:p.year}),s.toMillis()}return i}_handleOptionChange(e){this._commitInputValue(e),this.scheduleRender()}_handleGroupClick(e){var t;const i=e.currentTarget["data-group"],a="expanded"===i.state,n="sequential"===this.groupDisplay,l=`.${g.groupHeader}`;if(!(a&&!e.target.closest(l))){if(this._activeInputName=null==(t=this._getFocusableInput("forward",i))?void 0:t.name,n){const t=e.target.closest(l);if(a&&!t)return;this.viewModel.inputFields.forEach((e=>{y(e)&&e!==i&&(e.state="collapsed")}))}i.state=a?"collapsed":"expanded",this._fieldFocusNeeded=n,this.scheduleRender()}}_handleSubmit(e){e.preventDefault()}_handleFormKeyDown(e){"Enter"===e.key&&this.viewModel.submit()}_formatDate(e){if(null==e)return{date:"",time:""};const t=_.fromMillis(e,{locale:v(),numberingSystem:"latn"});return{date:t.toLocaleString({year:"numeric",month:"2-digit",day:"2-digit"}),time:t.toFormat(b.timePattern)}}_parseDate(e,t){if(null==e||""===e)return null;const{timePattern:i,datePattern:a}=b,n=t?"date"===t?a:i:`${a} ${i}`,l=_.fromFormat(e,n,{locale:v(),numberingSystem:"latn"});return l.isValid?l.toJSDate():null}_inputFieldHasInputType(e,t){var i;return a(e.fieldElement)&&(null==(i=e.fieldElement.input)?void 0:i.type)===t}_valueIsValidContingentValue(e,i){var a;switch(i.objectType){case"any":return!0;case"null":return null==e;case"code":return e===(null==(a=i.codedValue)?void 0:a.code);case"range":return e>=i.minValue&&e<=i.maxValue;default:return t(i.objectType),!1}}};e([n("viewModel.description")],I.prototype,"description",void 0),e([n("viewModel.feature")],I.prototype,"feature",void 0),e([n("viewModel.fieldConfig")],I.prototype,"fieldConfig",void 0),e([n("viewModel.formTemplate")],I.prototype,"formTemplate",void 0),e([l()],I.prototype,"groupDisplay",void 0),e([l()],I.prototype,"headingLevel",void 0),e([l({aliasOf:{source:"messages.widgetLabel",overridable:!0}})],I.prototype,"label",void 0),e([n("viewModel.layer")],I.prototype,"layer",void 0),e([l(),m("esri/widgets/FeatureForm/t9n/FeatureForm")],I.prototype,"messages",void 0),e([l(),m("esri/widgets/FeatureTemplates/t9n/FeatureTemplates")],I.prototype,"messagesTemplates",void 0),e([n("viewModel.strict")],I.prototype,"strict",void 0),e([n("viewModel.title")],I.prototype,"title",void 0),e([l(),h(["value-change","submit"])],I.prototype,"viewModel",void 0),e([n("viewModel.getValues")],I.prototype,"getValues",null),e([n("viewModel.submit")],I.prototype,"submit",null),I=e([s("esri.widgets.FeatureForm")],I);const F=I;export{F as default};
|
|
5
|
+
import{_ as e}from"../chunks/tslib.es6.js";import"../intl.js";import{neverReached as t}from"../core/compilerUtils.js";import{isSome as i,isNone as a}from"../core/maybe.js";import{aliasOf as l}from"../core/accessorSupport/decorators/aliasOf.js";import"../core/arrayUtils.js";import"../core/has.js";import"../core/accessorSupport/ensureType.js";import{property as n}from"../core/accessorSupport/decorators/property.js";import{subclass as s}from"../core/accessorSupport/decorators/subclass.js";import{getDomainRange as r}from"../layers/support/domainUtils.js";import{getFieldRange as o}from"../layers/support/fieldUtils.js";import u from"./Widget.js";import d from"./FeatureForm/FeatureFormViewModel.js";import{Heading as p,incrementHeadingLevel as c}from"./support/Heading.js";import"./support/widgetUtils.js";import{messageBundle as m}from"./support/decorators/messageBundle.js";import"../core/Logger.js";import{vmEvent as h}from"./support/decorators/vmEvent.js";import{tsx as f}from"./support/jsxFactory.js";import{DateTime as _}from"luxon";import{getLocale as v}from"../intl/locale.js";const g={base:"esri-feature-form",form:"esri-feature-form__form",formHeader:"esri-feature-form__form-header",label:"esri-feature-form__label",inputField:"esri-feature-form__input",inputDate:"esri-feature-form__input--date",inputTime:"esri-feature-form__input--time",inputRadioGroup:"esri-feature-form__input--radio-group",inputRadio:"esri-feature-form__input--radio",inputRadioLabel:"esri-feature-form__input--radio-label",inputDisabled:"esri-feature-form__input--disabled",inputSwitch:"esri-feature-form__input--switch",inputInvalid:"esri-feature-form__input--invalid",inputIconInvalid:"esri-feature-form__input-icon--invalid",errorMessage:"esri-feature-form__field-error-message",description:"esri-feature-form__description-text",dateInputPart:"esri-feature-form__date-input-part",loneDateInputPart:"esri-feature-form__date-input-part--lone",dateInputContainer:"esri-feature-form__date-input-container",dateFormatHint:"esri-feature-form__date-format-hint",group:"esri-feature-form__group",groupLabel:"esri-feature-form__group-label",groupHeader:"esri-feature-form__group-header",groupHeading:"esri-feature-form__group-header",groupTitle:"esri-feature-form__group-title",groupDescription:"esri-feature-form__group-description",groupToggleIcon:"esri-feature-form__group-toggle-icon",groupCollapsed:"esri-feature-form__group--collapsed",groupSequential:"esri-feature-form__group--sequential",groupActive:"esri-feature-form__group--active",collapseIcon:"esri-icon-up",errorIcon:"esri-icon-notice-triangle",expandIcon:"esri-icon-down",widget:"esri-widget",panel:"esri-widget--panel",input:"esri-input",select:"esri-select"},b={datePattern:"D",timePattern:"tt"};function y(e){return e&&e.inputFields}let I=class extends u{constructor(e,t){super(e,t),this._activeDateFieldEdit=null,this._activeInputName=null,this._activeNumberFieldEdit=null,this._fieldFocusNeeded=!1,this._fieldToInitialIncompatibleDomainValue=new Map,this._switchFieldsWithInitialIncompatibleValue=new Set,this._userUpdatedInputFieldNames=new Set,this.description=null,this.feature=null,this.fieldConfig=null,this.formTemplate=null,this.groupDisplay="all",this.headingLevel=2,this.label=void 0,this.layer=null,this.messages=null,this.messagesTemplates=null,this.strict=null,this.title=null,this.viewModel=new d,this._handleSwitchClick=e=>{e.target===e.currentTarget&&e.stopImmediatePropagation()},this._handleRadioInputChange=e=>{this._commitInputValue(e.target)},this._handleInputInput=e=>{this._commitInputValue(e.currentTarget,!0)},this._handleFormKeyDown=this._handleFormKeyDown.bind(this),this._handleInputBlur=this._handleInputBlur.bind(this),this._handleInputFocus=this._handleInputFocus.bind(this),this._handleNumberInputMouseDown=this._handleNumberInputMouseDown.bind(this),this._handleInputKeyDown=this._handleInputKeyDown.bind(this),this._handleOptionChange=this._handleOptionChange.bind(this),this._handleGroupClick=this._handleGroupClick.bind(this),this._handleSubmit=this._handleSubmit.bind(this),this._afterInputCreateOrUpdate=this._afterInputCreateOrUpdate.bind(this)}initialize(){this.own(this.watch("feature",(()=>{const e=this._getFocusableInput("forward");this._activeInputName=e&&e.name,this._userUpdatedInputFieldNames.clear(),this._fieldToInitialIncompatibleDomainValue.clear(),this._switchFieldsWithInitialIncompatibleValue.clear(),this._fieldFocusNeeded=!0})),this.on("submit",(e=>{if(e.invalid.length>0){const[t]=e.invalid;e.invalid.forEach((e=>this._userUpdatedInputFieldNames.add(e))),this._activeInputName=t,this._fieldFocusNeeded=!0,this.scheduleRender()}})))}loadDependencies(){return Promise.all([import("@esri/calcite-components/dist/components/calcite-combobox.js"),import("@esri/calcite-components/dist/components/calcite-combobox-item.js"),import("@esri/calcite-components/dist/components/calcite-combobox-item-group.js"),import("@esri/calcite-components/dist/components/calcite-input-message.js"),import("@esri/calcite-components/dist/components/calcite-switch.js")])}destroy(){this._userUpdatedInputFieldNames.clear(),this._userUpdatedInputFieldNames=null}getValues(){return null}submit(){return null}render(){const{state:e}=this.viewModel;return f("div",{class:this.classes(g.base,g.widget,g.panel)},"ready"===e?this.renderForm():null)}renderForm(){const e=this.title?f(p,{key:"title",level:this.headingLevel},this.title):null,t=this.description?f("p",{class:g.description,key:"description"},this.description):null,i=e||t?f("div",{class:g.formHeader},e,t):null;return f("form",{class:g.form,novalidate:!0,onsubmit:this._handleSubmit,onkeydown:this._handleFormKeyDown},i,this.renderFields())}renderFields(){const{viewModel:{inputFields:e}}=this;return e.map(((e,t)=>y(e)?this.renderGroup(e,t):this.renderLabeledField(e)))}renderGroup(e,t){const{description:i,inputFields:a,label:l,state:n}=e,s=a.filter((e=>e.visible)),r=this.viewModel.findField(this._activeInputName),o=!(!r||r.group!==e),u=`${this.id}_group_${t}`,d=`${this.id}_group-label_${t}`,m=`${this.id}_group-description_${t}`,h=i?f("p",{class:this.classes(g.groupDescription,g.description),id:m},i):null,_="sequential"===this.groupDisplay,v=_?o:"expanded"===n,b=v?g.collapseIcon:g.expandIcon;return f("fieldset",{"aria-expanded":v.toString(),"aria-labelledby":d,"aria-describedby":i?m:"",class:this.classes(g.group,_?g.groupSequential:null,v?null:g.groupCollapsed,o?g.groupActive:null),"data-group":e,id:u,key:t,onclick:this._handleGroupClick},f("button",{role:_?"presentation":void 0,class:g.groupHeader,type:"button",tabIndex:_?-1:0},f("div",{class:g.groupTitle},f(p,{class:g.groupLabel,id:d,level:this.title?c(this.headingLevel):this.headingLevel},l),h),_?null:f("span",{class:this.classes(b,g.groupToggleIcon)})),s.map((e=>this.renderLabeledField(e))))}_getFocusableInput(e,t){const i=this.viewModel.allInputFields,a="forward"===e?i:i.slice().reverse();let l;if(t)if(y(t))l=a.indexOf(t.inputFields[0]);else{let i;if(this._isInputFieldInGroup(t)&&"collapsed"===t.group.state){const{inputFields:a}=t.group;i="forward"===e?a[a.length-1]:a[0]}else i=t;l=a.indexOf(i)+1}else l=0;for(let n=l;n<a.length;n++){const e=a[n];if(e.visible)return e}return null}renderLabeledField(e){const{label:t,layer:i,type:a}=e;return f("label",{key:`${i.id}-${e.name}`,class:g.label},[t,"unsupported"!==a?this.renderInputField(e):this.renderUnsupportedField(e),this.renderAuxiliaryText(e)])}renderInputField(e){const{domain:t,name:a,type:l,value:n}=e,s=this.getCommonInputProps(e);if("coded-value"===(null==t?void 0:t.type)){if(this._inputFieldHasInputType(e,"switch")){const{fieldElement:t}=e;if(!(this._switchFieldsWithInitialIncompatibleValue.has(a)||null==n||t.input.onValue!==n&&t.input.offValue!==n))return this.renderSwitchInputField(n,s);this._switchFieldsWithInitialIncompatibleValue.add(a)}return"radio-buttons"===e.inputType?this.renderRadioButtonsInputField(n,t.codedValues.map((({code:e,name:t})=>({value:e,name:t}))),s):this.renderSelectInputField(n,this._getFieldValueOptions(a,t),s)}return"datetime-picker"===e.inputType||"date"===l?this.renderDateInputField(n,s):"number"===l?f("input",{type:"number",...s,value:i(this._activeNumberFieldEdit)&&this._activeNumberFieldEdit.fieldName===e.name?this._activeNumberFieldEdit.value:`${s.value}`}):"text-area"===e.inputType?f("textarea",{...s}):f("input",{type:"text",...s})}_parseDateTime(e,t,i){if(i){var a;let l=_.fromJSDate(this._parseDate(e,i));const n=_.fromMillis(null!=(a=t.value)?a:Date.now());return l="date"===i?l.set({hour:n.hour,minute:n.minute,second:n.second}):l.set({day:n.day,month:n.month,year:n.year}),l.isValid?l.toMillis():null}const l=_.fromJSDate(this._parseDate(e));return l.isValid?l.toMillis():null}renderDateInputField(e,t){const{date:i,time:a}=this._formatDate(0),l=`${this.id}-${t.key}`,n=`${l}-date`,s=`${l}-time`,r=t["data-field"],{includeTime:o}=r,{_activeDateFieldEdit:u}=this;let{date:d,time:p}=this._formatDate(e);var c,m,h,_;(null==u?void 0:u.fieldName)===r.name&&(d=null!=(c=null==(m=u.date.input)?void 0:m.value)?c:d,p=null!=(h=null==(_=u.time.input)?void 0:_.value)?h:p);return f("div",{key:`${t.key}-date`,class:g.dateInputContainer},f("div",{class:this.classes(g.dateInputPart,o?null:g.loneDateInputPart)},f("input",{"aria-label":r.label,"aria-describedby":n,type:"text",...t,"data-date-part":"date",class:this.classes(t.class,g.inputDate),value:d}),f("div",{class:g.dateFormatHint,id:n},i)),o?f("div",{class:g.dateInputPart,key:"time-input"},f("input",{"aria-describedby":s,"aria-label":r.label,type:"text",...t,"data-date-part":"time",class:this.classes(t.class,g.inputTime),value:p}),f("div",{class:g.dateFormatHint,id:s},a)):null)}renderUnsupportedField(e){const t=this.getCommonInputProps(e);return f("input",{afterCreate:t.afterCreate,afterUpdate:t.afterUpdate,class:this.classes(g.input,g.inputField,g.inputDisabled),"data-field":t["data-field"],onfocus:t.onfocus,readOnly:!0,tabIndex:t.tabIndex,type:"text",value:t.value})}renderSelectInputField(e,t,i){const{messages:l,messagesTemplates:n}=this,s=t.map((t=>t.map((t=>f("calcite-combobox-item",{value:`${t.value}`,"text-label":t.name,key:`#${t.value}`,selected:e===t.value}))))),r=i["data-field"],[o,u]=s;this._registerIncompatibleValue(e,t.flat(),r,(e=>{u.unshift(f("calcite-combobox-item",{value:`${e}`,"text-label":`${e}`,key:"incompatible-option",readOnly:!0}))}));const d=u.length>0?[f("calcite-combobox-item-group",{key:"recommended",label:l.recommended},o),f("calcite-combobox-item-group",{key:"other",label:n.other},u)]:o,p=a(r.fieldElement)||this._inputFieldHasInputType(r,"combo-box")&&r.fieldElement.input.showNoValueOption;if(!r.required&&p){const e="",t=this._inputFieldHasInputType(r,"combo-box")&&r.fieldElement.input.noValueOptionLabel||this.messages.empty;d.unshift(f("calcite-combobox-item",{value:e,"text-label":this.messages.empty,key:"empty-option"},t))}return f("calcite-combobox",{...i,"selection-mode":"single",disabled:i.readOnly,allowCustomValues:!1,onCalciteComboboxChange:e=>this._handleOptionChange(e.target)},d)}_registerIncompatibleValue(e,t,i,a){const l=this._fieldToInitialIncompatibleDomainValue,n=l.has(i.name);(n||null!=e&&""!==e&&!t.find((t=>t.value===e))||n)&&(n||l.set(i.name,e),null==a||a(l.get(i.name)))}renderRadioButtonsInputField(e,t,i){const l=i["data-field"],n=t.map((t=>this.renderRadioButton({key:t.name,label:t.name,name:l.name,value:t.value,selected:t.value===e,props:i})));this._registerIncompatibleValue(e,t,l);const s=a(l.fieldElement)||this._inputFieldHasInputType(l,"radio-buttons")&&l.fieldElement.input.showNoValueOption;if(!l.required&&s){const t="",a=this._inputFieldHasInputType(l,"radio-buttons")&&l.fieldElement.input.noValueOptionLabel||this.messages.empty,s=e===t||null===e;n.unshift(this.renderRadioButton({key:"empty-option",label:a,name:l.name,value:t,selected:s,props:i}))}return f("div",{key:`${i.key}-radio`,class:g.inputRadioGroup},n)}renderSwitchInputField(e,t){const i=t["data-field"],a=!!this._inputFieldHasInputType(i,"switch")&&e===i.fieldElement.input.onValue;return f("calcite-switch",{...t,class:g.inputSwitch,onclick:this._handleSwitchClick,checked:a,disabled:t.readOnly})}renderRadioButton({key:e,name:t,value:i,selected:a,label:l,props:n}){return f("label",{key:e,class:g.inputRadioLabel},f("input",{...n,class:g.inputRadio,name:t,type:"radio",value:i,checked:a,onchange:this._handleRadioInputChange}),l)}renderAuxiliaryText(e){const t=this._userUpdatedInputFieldNames.has(e.name)&&!e.valid?e.errorMessage:i(this.viewModel.contingencyConstraintViolations.get(e.name))?this.messages.validationErrors.valuesIncompatible:null;return i(t)?f("calcite-input-message",{status:"invalid",icon:!0,active:!0},t):e.description?f("div",{key:"description",class:g.description},e.description):void 0}getCommonInputProps(e){const{groupDisplay:t}=this,{editable:a,group:l,hint:n,maxLength:s,minLength:r,name:o,required:u,type:d,valid:p,value:c}=e,m=this._userUpdatedInputFieldNames.has(o),h=!a,f="all"===t&&i(l)&&"collapsed"===l.state;return{afterCreate:this._afterInputCreateOrUpdate,afterUpdate:this._afterInputCreateOrUpdate,"aria-invalid":p?"false":"true",class:this.classes(g.input,g.inputField,h?g.inputDisabled:null,m&&!p?g.inputInvalid:null),key:o,label:o,minlength:r>-1?`${r}`:"",maxlength:s>-1?`${s}`:"",...this._getNumberFieldConstraints(e),readOnly:h,value:null==c?"":`${c}`,"data-field":e,onfocus:this._handleInputFocus,oninput:this._handleInputInput,onblur:this._handleInputBlur,onkeydown:this._handleInputKeyDown,onmousedown:"number"===d?this._handleNumberInputMouseDown:null,placeholder:"number"===d||"text"===d?n:"",required:u,tabIndex:f?-1:0}}_isInputFieldInGroup(e){return!y(e)&&i(e.group)}_handleNumberInputMouseDown({target:e}){e.focus(),this.scheduleRender()}_getFieldValueOptions(e,t){const i=t.codedValues.map((({code:e,name:t})=>({value:e,name:t}))),a=this.viewModel.fieldsWithContingentValues.has(e)?this._getContingentValueOptions(e):[];if(a.length>0){const e=new Set(a.map((e=>e.value)));return[a,i.filter((t=>!e.has(t.value)))]}return[i,[]]}_getContingentValueOptions(e){const t={};for(const n of this.viewModel.allInputFields){const{name:i,value:l}=n;!a(l)&&i!==e&&this.viewModel.fieldsWithContingentValues.has(i)&&(t[i]=l)}const i=this.viewModel.joinedContingentValues.slice(),l=new Map;for(const n of i){const i=n.values[e];if(a(i)||"code"!==i.objectType&&"null"!==i.objectType)continue;const{code:s,name:r}="null"===i.objectType?{code:"",name:this.messages.empty}:i.codedValue;if(l.has(s))continue;Object.entries(t).every((([e,t])=>!n.values.hasOwnProperty(e)||this._valueIsValidContingentValue(t,n.values[e])))&&l.set(s,{name:r,value:s})}return[...l.values()]}_getNumberFieldConstraints(e){const t=r(e.domain)||o(e.field);return t&&t.max!==Number.MAX_VALUE&&t.min!==Number.MIN_VALUE?t:{min:null,max:null}}_afterInputCreateOrUpdate(e){const t=e["data-field"],i=this.viewModel.findField(this._activeInputName),a=this._fieldToInitialIncompatibleDomainValue.get(t.name)===t.value;this._fieldFocusNeeded&&i===t&&("radio-buttons"!==t.inputType||a||e.checked)&&(this._fieldFocusNeeded=!1,e.focus())}_handleInputFocus(e){const t=e.target,i=t["data-field"];this._activeInputName=i.name,"date"===i.type?this._syncDateFieldEdits(t):this._isNumberInputField(i)&&this._setUpNumberFieldEdit(t)}_isNumberInputField({domain:e,inputType:t="text-box",type:i}){return"number"===i&&"text-box"===t&&(!e||"coded-value"!==e.type)}_handleInputBlur(e){const t=e.target,a=t["data-field"];if("date"===a.type){const i=e.relatedTarget,n=i&&i["data-field"];if(n&&"date"===a.type&&"date"===n.type&&a.field===n.field){if(""!==t.value&&""===i.value){var l;const n=i.getAttribute("data-date-part");i.value=this._formatDate(null!=(l=a.value)?l:Date.now())[n],this._parseDate(t.value,t.getAttribute("data-date-part"))&&this._commitInputValue(e.target,!0,!1)}return}}"number"===a.type&&i(this._activeNumberFieldEdit)&&(this._activeNumberFieldEdit.input.value=`${a.value}`,this._activeNumberFieldEdit=null),this._commitInputValue(t),this.scheduleRender()}_commitInputValue(e,t=!1,a=!0){const l=e["data-field"];if(this._activeDateFieldEdit){const{date:i,time:u}=this._activeDateFieldEdit,d=this._parseDateTime(e.value,l,i.active?"date":"time"),p=null!==this.viewModel.getValue(l.name),c=i.input&&(u.input||!l.includeTime),m=null===d;if(t){if(m)return;(c||!a||p)&&this._updateDateFieldValue(l,d)}else{var n,s;if(""===(null==(n=i.input)?void 0:n.value)||""===(null==(s=u.input)?void 0:s.value))this._updateDateFieldValue(l,null);else if(c){var r,o;const e=`${i.input.value} ${null!=(r=null==(o=u.input)?void 0:o.value)?r:""}`,t=this._parseDateTime(e,l);!(null!==t)&&p||this._updateDateFieldValue(l,t)}this._activeDateFieldEdit=null}}else i(this._activeNumberFieldEdit)&&this._isNumberInputField(l)&&(this._activeNumberFieldEdit.value=e.value),this._updateFieldValue(e)}_handleInputKeyDown(e){const{key:t,altKey:i,ctrlKey:a,metaKey:l}=e,n=e.target["data-field"];if("Enter"===t)this._isInputFieldInGroup(n)&&"collapsed"===n.group.state&&(n.group.state="expanded");else{const{type:s}=n.field,r="single"===s||"double"===s,o=!i&&!a&&!l;if(("integer"===s||"small-integer"===s||r)&&o&&1===t.length){const i=Number(t),a=["-","+"],l=["e","."],n=r?[...a,...l]:a;isNaN(i)&&-1===n.indexOf(t)&&e.preventDefault()}}}_setUpNumberFieldEdit(e){const t=e["data-field"];this._activeNumberFieldEdit={fieldName:t.name,input:e,value:e.value}}_syncDateFieldEdits(e){var t,i;const a=e["data-field"];if("date"!==a.type)return;const l=e.getAttribute("data-date-part"),n="date"===l?{value:e.value,input:e,active:!0}:{...null==(t=this._activeDateFieldEdit)?void 0:t.date,active:!1},s="time"===l?{value:e.value,input:e,active:!0}:{...null==(i=this._activeDateFieldEdit)?void 0:i.time,active:!1};this._activeDateFieldEdit={fieldName:a.name,date:n,time:s}}_updateFieldValue(e){const t=e["data-field"],{name:a}=t;if(this.viewModel.setValue(a,this._parseValue(e)),this._userUpdatedInputFieldNames.add(a),this.viewModel.fieldsWithContingentValues.has(a)){const e=Object.fromEntries(Object.entries(this.getValues()).filter((([e,t])=>i(t))));this.viewModel.validateContingencyConstraints(e)}}_updateDateFieldValue(e,t){this.viewModel.setValue(e.name,t),this._userUpdatedInputFieldNames.add(e.name)}_parseValue(e){const t=e["data-field"],i=e.value;if(this._inputFieldHasInputType(t,"switch")&&"CALCITE-COMBOBOX"!==e.tagName)return e.checked?t.fieldElement.input.onValue:t.fieldElement.input.offValue;if("radio-buttons"===t.inputType&&"radio"===e.type&&!e.checked)return t.value;const{type:a}=t;if("number"===a)return i?parseFloat(i):null;if("date"===a){if(!i)return null;const a=Number(i);if(!isNaN(a))return a;const l=e.getAttribute("data-date-part"),n=this._parseDate(i,l);if(!n)return null;let s=_.fromJSDate(n);const r=t.domain,o=_.now();let u=o;if(r&&"range"===r.type){const e=_.fromMillis(r.maxValue);o<e&&(u=e)}const d=this.viewModel.getValue(t.name),p=null!=d?_.fromMillis(d):u;return s="date"===l?s.set({hour:p.hour,minute:p.minute,second:p.second}):s.set({day:p.day,month:p.month,year:p.year}),s.toMillis()}return i}_handleOptionChange(e){this._commitInputValue(e),this.scheduleRender()}_handleGroupClick(e){var t;const i=e.currentTarget["data-group"],a="expanded"===i.state,l="sequential"===this.groupDisplay,n=`.${g.groupHeader}`;if(!(a&&!e.target.closest(n))){if(this._activeInputName=null==(t=this._getFocusableInput("forward",i))?void 0:t.name,l){const t=e.target.closest(n);if(a&&!t)return;this.viewModel.inputFields.forEach((e=>{y(e)&&e!==i&&(e.state="collapsed")}))}i.state=a?"collapsed":"expanded",this._fieldFocusNeeded=l,this.scheduleRender()}}_handleSubmit(e){e.preventDefault()}_handleFormKeyDown(e){"Enter"===e.key&&this.viewModel.submit()}_formatDate(e){if(null==e)return{date:"",time:""};const t=_.fromMillis(e,{locale:v(),numberingSystem:"latn"});return{date:t.toLocaleString({year:"numeric",month:"2-digit",day:"2-digit"}),time:t.toFormat(b.timePattern)}}_parseDate(e,t){if(null==e||""===e)return null;const{timePattern:i,datePattern:a}=b,l=t?"date"===t?a:i:`${a} ${i}`,n=_.fromFormat(e,l,{locale:v(),numberingSystem:"latn"});return n.isValid?n.toJSDate():null}_inputFieldHasInputType(e,t){var a;return i(e.fieldElement)&&(null==(a=e.fieldElement.input)?void 0:a.type)===t}_valueIsValidContingentValue(e,i){var a;switch(i.objectType){case"any":return!0;case"null":return null==e;case"code":return e===(null==(a=i.codedValue)?void 0:a.code);case"range":return e>=i.minValue&&e<=i.maxValue;default:return t(i.objectType),!1}}};e([l("viewModel.description")],I.prototype,"description",void 0),e([l("viewModel.feature")],I.prototype,"feature",void 0),e([l("viewModel.fieldConfig")],I.prototype,"fieldConfig",void 0),e([l("viewModel.formTemplate")],I.prototype,"formTemplate",void 0),e([n()],I.prototype,"groupDisplay",void 0),e([n()],I.prototype,"headingLevel",void 0),e([n({aliasOf:{source:"messages.widgetLabel",overridable:!0}})],I.prototype,"label",void 0),e([l("viewModel.layer")],I.prototype,"layer",void 0),e([n(),m("esri/widgets/FeatureForm/t9n/FeatureForm")],I.prototype,"messages",void 0),e([n(),m("esri/widgets/FeatureTemplates/t9n/FeatureTemplates")],I.prototype,"messagesTemplates",void 0),e([l("viewModel.strict")],I.prototype,"strict",void 0),e([l("viewModel.title")],I.prototype,"title",void 0),e([n(),h(["value-change","submit"])],I.prototype,"viewModel",void 0),e([l("viewModel.getValues")],I.prototype,"getValues",null),e([l("viewModel.submit")],I.prototype,"submit",null),I=e([s("esri.widgets.FeatureForm")],I);const F=I;export{F as default};
|