@arcgis/core
Version:
ArcGIS Maps SDK for JavaScript: A complete 2D and 3D mapping and data visualization API
3 lines (2 loc) • 18.2 kB
JavaScript
/* COPYRIGHT Esri - https://js.arcgis.com/5.0.8/LICENSE.txt */
import{__decorate as e}from"tslib";import{getAssetUrl as t}from"../../assets.js";import s from"../../Graphic.js";import r from"../../PopupTemplate.js";import{isSome as o}from"../../core/arrayUtils.js";import i from"../../core/Error.js";import{EventedAccessor as l}from"../../core/Evented.js";import a from"../../core/Logger.js";import{mappedFind as n}from"../../core/maybe.js";import{eachAlways as u,after as c}from"../../core/promiseUtils.js";import{watch as h,initial as p,whenOnce as g}from"../../core/reactiveUtils.js";import{property as d,subclass as m}from"../../core/accessorSupport/decorators.js";import y from"../../geometry/Point.js";import f from"../../geometry/SpatialReference.js";import{getPointFromGeometry as S,getPointWithElevation as _}from"../../geometry/support/geometryUtils.js";import v from"../../portal/Portal.js";import{isApiKeyApplicable as w}from"../../support/apiKeyUtils.js";import b from"../../symbols/PictureMarkerSymbol.js";import x from"../../symbols/SimpleFillSymbol.js";import L from"../../symbols/SimpleLineSymbol.js";import I from"../../symbols/TextSymbol.js";import{highlightsSupported as T}from"../../views/support/layerViewUtils.js";import R from"./LayerSearchSource.js";import E from"./LocatorSearchSource.js";import{SourceCollection as F}from"./types.js";import{isArcGISWorldGeocoder as P,meteredArcGISLocatorUrl as j,isProxiedArcGISWorldGeocoder as C,isMeteredArcGISWorldGeocoder as G}from"./support/locatorUtils.js";import{supported as O,getCurrentPosition as A,positionToPoint as N}from"../support/geolocationUtils.js";import{GoTo as D}from"../support/GoTo.js";function M(e,t){return e.hasOwnProperty(t)&&null!=e[t]&&""!==e[t]}const V="highlight",J=f.WGS84,U="esri/images/search/search-symbol-32.png",H=/<[\s\S]*?>/g,k=-1;let B=class extends(D(l)){constructor(e){super(e),this._defaultPopupTemplate=new r({content:"{Match_addr}"}),this._gotoController=null,this._searching=null,this._updatingPromise=null,this._createdFeatureLayers=[],this.autoNavigate=!0,this.autoSelect=!0,this.defaultSources=new F,this.defaultSymbols={point:new b({url:t(U),size:24,width:24,height:24}),polyline:new L({color:[130,130,130,1],width:2}),polygon:new x({color:[235,235,235,.4],outline:{color:[130,130,130,1],width:2}})},this.includeDefaultSources=!0,this.maxInputLength=128,this.maxResults=6,this.maxSuggestions=6,this.messages=null,this.minSuggestCharacters=3,this.popupEnabled=!0,this.popupTemplate=null,this.portal=v.getDefault(),this.resultCount=null,this.resultGraphicEnabled=!0,this.resultGraphic=null,this.resultLocation=null,this.results=null,this.selectedSuggestion=null,this.searchAllEnabled=!0,this.selectedResult=null,this.sources=new F,this.suggestionDelay=350,this.suggestionCount=null,this.suggestions=null,this.suggestionsEnabled=!0,this.view=null}initialize(){this.addHandles([h(()=>[this.includeDefaultSources,this.view,this.portal],()=>this._update(),p),h(()=>this.messages,()=>{this._defaultPopupTemplate.title=this.messages?.searchResult??"",this._update()},p)])}destroy(){this._destroyFeatureLayers(),this._abortGoTo(),this.clearGraphics()}static{this.ALL_INDEX=k}get activeSource(){return this.allSources.at(this.activeSourceIndex)??null}get activeSourceIndex(){return 1===this.allSources.length||!this.searchAllEnabled?0:k}set activeSourceIndex(e){this._overrideIfSome("activeSourceIndex",e)}get allPlaceholder(){return this.messages?.allPlaceholder}set allPlaceholder(e){this._overrideIfSome("allPlaceholder",e)}get allSources(){const{sources:e,defaultSources:t,includeDefaultSources:s}=this,r="function"==typeof s?s.call(null,{sources:e,defaultSources:t}):s?t.concat(e):e,o=this._get("allSources")||new F;return o.removeAll(),o.addMany(r.filter(Boolean)),o}get defaultPopupTemplate(){return this._defaultPopupTemplate}set defaultPopupTemplate(e){this._overrideIfSome("defaultPopupTemplate",e)}get locationEnabled(){return this._get("locationEnabled")||O()}set locationEnabled(e){if(void 0===e)return void this._clearOverride("locationEnabled");const t=O();if(e&&!t){const e=new i("locationEnabled:geolocation-unsupported","Geolocation API is unsupported.",{geolocation:navigator.geolocation});a.getLogger(this).error(e)}this._override("locationEnabled",!!e&&t)}get placeholder(){const{allSources:e,activeSourceIndex:t,allPlaceholder:s}=this;if(t===k)return s??"";const r=e.at(t);return r?.placeholder??""}set searchTerm(e){this._set("searchTerm",e||""),this.clearGraphics(),this.selectedSuggestion&&this.selectedSuggestion.text!==e&&this._set("selectedSuggestion",null),""===e&&this._clear()}get searchTerm(){return this._get("searchTerm")||""}get state(){return this._searching?"searching":this.updating?"loading":0===this.allSources.length?"disabled":"ready"}get updating(){return null!=this._updatingPromise}clear(){this.searchTerm=""}clearGraphics(){this._removeHighlight();const{view:e,resultGraphic:t}=this;e&&t&&e.graphics.remove(t),this._set("resultLocation",null),this._set("resultGraphic",null)}search(e,t){this.emit("search-start"),this.clearGraphics();const s=this._createSuggestionForSearch(e),r=(async()=>{try{await this.when();const e=await this._getResultsFromSources(s,t);if(t?.signal?.aborted)return null;const r={activeSourceIndex:this.activeSourceIndex,searchTerm:s.text??"",numResults:0,numErrors:0,errors:[],results:[]};this._formatResponse(r,e,s);const o=this._getFirstResult(r.results),i=s.location&&o?o.name:s.text,l=i?.replaceAll(H,"");return this._set("searchTerm",l),(s.key&&"number"==typeof s.sourceIndex||s.location)&&this._set("selectedSuggestion",s),this._set("results",r.results),this._set("resultCount",r.results.reduce((e,t)=>e+(t.results?.length??0),0)),this.emit("search-complete",r),await this._selectFirstResult(o),r}finally{this._clearSearching()}})();return this._searching=r,r}async searchNearby(e){if(!this.locationEnabled){const e=new i("searchNearby:geolocation-unsupported","Geolocation API is unsupported.",{geolocation:navigator.geolocation});throw a.getLogger(this).error(e),e}const t=(async()=>{try{const t=await A(),s=await N({position:t,view:this.view},e);return await this.search(s,e)}finally{this._clearSearching()}})();return this._searching=t,t}async select(e){if(this.clearGraphics(),!e){const t=new i("select:missing-parameter","Cannot select without a searchResult.",{value:e});throw a.getLogger(this).error(t),t}const{view:t}=this,r=M(e,"sourceIndex")?e.sourceIndex:this._getSourceIndexOfResult(e),o=null!=r?this.allSources.at(r):null;if(!o){const e=new i("select:missing-source","Cannot select without a source.",{source:o});throw a.getLogger(this).error(e),e}const l=o instanceof R?this._getLayerSourcePopupTemplate(o):o.popupTemplate,n=o.resultSymbol||this._getDefaultSymbol(e),c=M(o,"resultGraphicEnabled")?!!o.resultGraphicEnabled:this.resultGraphicEnabled,h=M(o,"autoNavigate")?!!o.autoNavigate:this.autoNavigate,p=M(o,"popupEnabled")?!!o.popupEnabled:this.popupEnabled,g=p?l||this.popupTemplate||this.defaultPopupTemplate:null,{feature:d}=e;if(!d){const e=new i("select:missing-feature","Cannot select without a feature.",{feature:d});throw a.getLogger(this).error(e),e}const{attributes:m,geometry:y,layer:f,sourceLayer:v}=d,w=y?S(y):null,b={layerViewQuery:this._getLayerView(d),elevationQuery:t&&null!=w?_(w,t):Promise.resolve(w)},x=await u(b),L=x.layerViewQuery.value,E=x.elevationQuery.value;n instanceof I&&(n.text=e.name);const F=t&&h?e.target||e.extent:null,P=null!=F?this._goToSearchResult(F):Promise.resolve();await P;const j=L?d:new s({geometry:y,symbol:n,attributes:m,layer:f,sourceLayer:v,popupTemplate:g});return L&&T(L)&&!p&&this._highlightFeature({graphic:j,layerView:L}),!L&&c&&t&&t.graphics.push(j),this._setResultFloor(e),this._set("selectedResult",e),this._set("resultGraphic",j),this._set("resultLocation",E),this.emit("select-result",{popupEnabled:p,result:e,source:o,sourceIndex:r}),e}async suggest(e,t,s){const r=e||this.searchTerm;this.emit("suggest-start",{searchTerm:r}),await this._suggestTimer(t,s);const o=await this._suggestImmediate(r,s);return this._set("suggestions",o?.results),this._set("suggestionCount",o?.results.reduce((e,t)=>e+(t.results?.length??0),0)??null),this.emit("suggest-complete",o),o}async when(){await g(()=>!this.updating)}async _update(){const{portal:e,view:t}=this;if(this.includeDefaultSources){const s=this._updatingPromise=u([e?.load(),t?.when()]);if(this.destroyed)return;if(await s,s!==this._updatingPromise)return}this.destroyed||this._updateDefaultSources(),this._updatingPromise=null}_clearSearching(){this._searching=null}_convertHelperServices(){const e=this.portal?.helperServices?.geocode;if(!e)return[];return e.map(e=>{if(!1===e.placefinding)return;const t=P(e.url)&&w(e.url)?{url:j}:null,s=E.fromJSON({...e,...t}),r=s.url;if(P(r)||C(r)||G(r)){const e=s.outFields??["Addr_type","Match_addr","StAddr","City"],t=(s.placeholder||this.messages?.placeholder)??"",r="number"==typeof s.defaultZoomScale?s.defaultZoomScale:2500;s.singleLineFieldName="SingleLine",s.outFields=e,s.placeholder=t,s.defaultZoomScale=r}return s.singleLineFieldName?s:void 0}).filter(o)}_destroyFeatureLayers(){this._createdFeatureLayers.forEach(e=>e?.destroy()),this._createdFeatureLayers=[]}_getLayerSources(e,t){const s=this.view?.map;return e.map(e=>{const r=s.findLayerById(e.id);if(!r)return;const o=this._getLayerJSON(e),i=R.fromJSON(o);return i.placeholder=t,this._getLayer(r,o).then(e=>{i.layer=e}),i}).filter(o).toArray()}_getTableSources(e,t){const s=this.view?.map;return e.map(e=>{if(!e.id)return;const r=s.findTableById(e.id);if(!r)return;const o=this._getLayerJSON(e),i=R.fromJSON(o);return i.placeholder=t,this._getLayer(r,o).then(e=>{i.layer=e}),i}).filter(o).toArray()}_convertApplicationProperties(){const e=this.view?.map,t=e?.applicationProperties?.viewing?.search;if(!t)return[];const{enabled:s,hintText:r,layers:o,tables:i}=t;if(!s)return[];return[...this._getLayerSources(o,r),...this._getTableSources(i,r)]}async _getSubLayer(e,t){if(await e.load(),!e.allSublayers)throw new Error;const s=e.allSublayers.find(e=>e.id===t.subLayer);if(!s)throw new Error;const r=await(s.createFeatureLayer?.());if(!r)throw new Error;return this._createdFeatureLayers.push(r),r}async _getBuildingSubLayer(e,t){await e.load();const s=e.allSublayers.find(e=>e.id===t.subLayer);if("building-component"!==s?.type)throw new Error;if(await s.load(),null==s.associatedLayer)throw new Error;return await s.associatedLayer.load(),s}async _getLayer(e,t){if("feature"===e.type||"scene"===e.type||"csv"===e.type||"geojson"===e.type||"ogc-feature"===e.type||"subtype-group"===e.type)return e;if("map-image"===e.type)try{return await this._getSubLayer(e,t)}catch(s){const t=new i("search:create-featurelayer","Could not create a FeatureLayer from the MapImageLayer",{layer:e});return a.getLogger(this).error(t),null}return"building-scene"===e.type?this._getBuildingSubLayer(e,t):null}_getLayerJSON(e){return"function"==typeof e.toJSON?e.toJSON():e}_updateDefaultSources(){const{defaultSources:e,includeDefaultSources:t}=this;this._destroyFeatureLayers(),e.removeAll(),t&&e.addMany([...this._convertApplicationProperties(),...this._convertHelperServices()])}_abortGoTo(){this._gotoController&&this._gotoController.abort(),this._gotoController=null}_clear(){this._abortGoTo(),this._set("resultCount",null),this._set("results",null),this._set("suggestions",null),this._set("suggestionCount",null),this._set("selectedResult",null),this._set("selectedSuggestion",null),this.emit("search-clear")}_suggestTimer(e,t){const s=null!=e?e:this.suggestionDelay;return c(s,null,t?.signal)}_createLocationForSearch(e){return e instanceof s&&e.geometry?S(e.geometry):e instanceof y?e:Array.isArray(e)&&2===e.length?new y({longitude:e[0],latitude:e[1]}):null}_createSuggestionForSearch(e){if(e&&M(e,"key")&&M(e,"text")&&M(e,"sourceIndex"))return e;const t=this._createLocationForSearch(e),s="string"==typeof e?e:this.searchTerm,{selectedSuggestion:r,selectedResult:o}=this,i=!e&&r&&o,l=i&&r.key===o.key&&r.sourceIndex===o.sourceIndex,a=i&&r.location;return l||a?r:{location:t,text:t?"":s,sourceIndex:null,key:null}}_getFirstResult(e){return n(e,({results:e})=>e?.[0])??null}async _selectFirstResult(e){return this.autoSelect&&e?this.select(e):null}async _suggestImmediate(e,t){await this.when();const s=await this._getSuggestionsFromSources(e,t);if(t?.signal?.aborted)return null;const r={activeSourceIndex:this.activeSourceIndex,searchTerm:e??"",numResults:0,numErrors:0,errors:[],results:[]};return this._formatResponse(r,s),r}_formatSourceResponse(e,t,s){const r=t?.value||[],o=t?.error,i=this.allSources.at(s);if(o){const t={sourceIndex:s,source:i,error:o};e.errors.push(t),a.getLogger(this).error(o),e.numErrors++}else{const t={sourceIndex:s,source:i,results:r};e.results.push(t),e.numResults+=r.length}}_formatResponse(e,t,s){if(t)if(e.activeSourceIndex===k){const r=s&&M(s,"sourceIndex")&&-1!==s.sourceIndex?s.sourceIndex:void 0;t.forEach((t,s)=>{const o=void 0!==r?r:s;this._formatSourceResponse(e,t,o)})}else this._formatSourceResponse(e,t[0],e.activeSourceIndex)}async _getResultsFromSources(e,t){const{allSources:s}=this,r=!e.location&&M(e,"sourceIndex")?e.sourceIndex:this.activeSourceIndex,o=[];if(!s.length){const e=new i("search:no-sources-defined","At least one source is required.",{allSources:s});throw a.getLogger(this).error(e),e}return r===k?s.forEach((s,r)=>{o.push(this._getResultsFromSource(e,r,t))}):o.push(this._getResultsFromSource(e,r,t)),u(o)}async _getSuggestionsFromSources(e,t){const{allSources:s,activeSourceIndex:r}=this,o=[];if(!s.length){const e=new i("suggest:no-sources-defined","At least one source is required.",{allSources:s});throw a.getLogger(this).error(e),e}return r===k?s.forEach((s,r)=>{o.push(this._getSuggestionsFromSource(e,r,t))}):o.push(this._getSuggestionsFromSource(e,r,t)),u(o)}async _getResultsFromSource(e,t,s){const r=null!=t?this.allSources.at(t):null;if(!r)return null;const{location:o=null}=e,i=this.view?.spatialReference??J,l=M(r,"maxResults")?r.maxResults:this.maxResults,a=!!(r instanceof R&&M(r,"exactMatch"))&&r.exactMatch,{view:n}=this;return r.getResults?.({exactMatch:a,location:o,maxResults:l,sourceIndex:t,spatialReference:i,suggestResult:e,view:n},s)}async _getSuggestionsFromSource(e,t,s){const r=this.allSources.at(t);if(!r)return null;e??="";const o=M(r,"suggestionsEnabled")?r.suggestionsEnabled:this.suggestionsEnabled,i=e?.length,l=M(r,"minSuggestCharacters")?r.minSuggestCharacters:this.minSuggestCharacters;if(o&&e.trim()&&i>=l){const o=this.view?.spatialReference||J,i=M(r,"maxSuggestions")?r.maxSuggestions:this.maxSuggestions,{view:l}=this,a=!!(r instanceof R&&M(r,"exactMatch"))&&r.exactMatch;return r.getSuggestions?.({view:l,sourceIndex:t,suggestTerm:e,spatialReference:o,maxSuggestions:i,exactMatch:a},s)}return null}_getLayerSourcePopupTemplate(e){const{layer:t}=e;if(t)return M(e,"popupTemplate")?e.popupTemplate:t.popupTemplate}_getSourceIndexOfResult(e){return n(this.results??[],({results:t,sourceIndex:s})=>{const r=t?.includes(e);return r?s:null})??null}async _goToSearchResult(e){this._abortGoTo();const t=new AbortController;this._gotoController=t;const s={target:{target:e},options:{signal:t.signal}};e||(s.options.animate=!1),await this.callGoTo(s),this._gotoController=null}_getDefaultSymbol(e){const{defaultSymbols:t}=this,s=e.feature?.geometry;if(null==s)return null;switch(s.type){case"point":case"multipoint":return t.point;case"polyline":return t.polyline;case"extent":case"polygon":return t.polygon;default:return null}}_removeHighlight(){this.removeHandles(V)}async _getLayerView(e){const{view:t}=this;if(!e||!t)return null;const{layer:s,sourceLayer:r}=e,o=s??r;return o&&"building-component"!==o.type&&"subtype-sublayer"!==o.type?(await t.when(),t.whenLayerView(o)):null}_highlightFeature(e){const{graphic:t,layerView:s}=e,{attributes:r,layer:o,sourceLayer:i}=t,l=o??i,{objectIdField:a}=l,n=(a&&r?.[a])??null,u=s.highlight(n??t);this.addHandles(u,V)}_setResultFloor(e){const{view:t}=this,s=e.feature?.attributes,r=e.feature?.sourceLayer;if(r&&"floorInfo"in r&&r?.floorInfo?.floorField&&s){const e=s[r.floorInfo.floorField];t?.emit("select-result-floor",e)}}};e([d()],B.prototype,"_searching",void 0),e([d()],B.prototype,"_updatingPromise",void 0),e([d({readOnly:!0,value:null})],B.prototype,"activeSource",null),e([d()],B.prototype,"activeSourceIndex",null),e([d()],B.prototype,"allPlaceholder",null),e([d({readOnly:!0})],B.prototype,"allSources",null),e([d()],B.prototype,"autoNavigate",void 0),e([d()],B.prototype,"autoSelect",void 0),e([d({type:r})],B.prototype,"defaultPopupTemplate",null),e([d({readOnly:!0})],B.prototype,"defaultSources",void 0),e([d()],B.prototype,"defaultSymbols",void 0),e([d()],B.prototype,"includeDefaultSources",void 0),e([d()],B.prototype,"locationEnabled",null),e([d()],B.prototype,"maxInputLength",void 0),e([d()],B.prototype,"maxResults",void 0),e([d()],B.prototype,"maxSuggestions",void 0),e([d()],B.prototype,"messages",void 0),e([d()],B.prototype,"minSuggestCharacters",void 0),e([d({readOnly:!0})],B.prototype,"placeholder",null),e([d()],B.prototype,"popupEnabled",void 0),e([d({type:r})],B.prototype,"popupTemplate",void 0),e([d({type:v})],B.prototype,"portal",void 0),e([d()],B.prototype,"resultCount",void 0),e([d()],B.prototype,"resultGraphicEnabled",void 0),e([d({readOnly:!0})],B.prototype,"resultGraphic",void 0),e([d({readOnly:!0})],B.prototype,"resultLocation",void 0),e([d({readOnly:!0})],B.prototype,"results",void 0),e([d({readOnly:!0})],B.prototype,"selectedSuggestion",void 0),e([d()],B.prototype,"searchAllEnabled",void 0),e([d({readOnly:!0})],B.prototype,"selectedResult",void 0),e([d()],B.prototype,"searchTerm",null),e([d({type:F})],B.prototype,"sources",void 0),e([d({readOnly:!0})],B.prototype,"state",null),e([d()],B.prototype,"suggestionDelay",void 0),e([d()],B.prototype,"suggestionCount",void 0),e([d({readOnly:!0})],B.prototype,"suggestions",void 0),e([d()],B.prototype,"suggestionsEnabled",void 0),e([d({readOnly:!0})],B.prototype,"updating",null),e([d()],B.prototype,"view",void 0),e([d()],B.prototype,"clear",null),B=e([m("esri.widgets.Search.SearchViewModel")],B);const Q=B;export{Q as default};