@arcgis/core
Version:
ArcGIS Maps SDK for JavaScript: A complete 2D and 3D mapping and data visualization API
6 lines (5 loc) • 17.9 kB
JavaScript
/*
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/4.32/esri/copyright.txt for details.
*/
import{_ as t}from"../../chunks/tslib.es6.js";import e from"../../request.js";import{isSome as s}from"../../core/arrayUtils.js";import i from"../../core/Collection.js";import o from"../../core/Error.js";import{JSONMap as a}from"../../core/jsonMap.js";import{clone as r}from"../../core/lang.js";import l from"../../core/Loadable.js";import{isAbortError as n}from"../../core/promiseUtils.js";import p from"../../core/ReactiveMap.js";import{watch as m,initial as u}from"../../core/reactiveUtils.js";import{createScreenPoint as h}from"../../core/screenUtils.js";import{unitType as d,convertUnit as c,getMetersPerUnitForSR as y,inchesPerMeter as f}from"../../core/unitUtils.js";import{property as T}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import{subclass as v}from"../../core/accessorSupport/decorators/subclass.js";import w from"../../geometry/Extent.js";import _ from"../../geometry/SpatialReference.js";import{formatDate as I,convertDateFormatToIntlOptions as g}from"../../intl/date.js";import{getLanguage as O}from"../../intl/locale.js";import b from"../../portal/Portal.js";import x from"../../portal/PortalQueryParams.js";import{reArcGISOnlineDomain as P}from"../../portal/support/urlUtils.js";import{execute as S,getTasks as E}from"../../rest/print.js";import{formatJsonMap as U}from"../../rest/support/fileFormat.js";import{fromJSON as L}from"../../rest/support/layoutTemplate.js";import j from"../../rest/support/PrintParameters.js";import C from"../../rest/support/PrintTemplate.js";import{getExtent as k}from"../../views/2d/viewpointUtils.js";import{ViewEventPriorities as H}from"../../views/input/InputManager.js";import F from"../../views/overlay/BoxOverlayItem.js";import D from"./CustomTemplate.js";import A from"./TemplateOptions.js";import{fetchLayoutTemplateInfos as R}from"./utils.js";const W=[30,144,255,255],M=[237,211,23,255],z=[216,48,32,255],V=new Set(["GISProfessionalStdUT","GISProfessionalAdvUT"]),q=/(\/GPServer\/).+/i,G=new a({inch:"inches",foot:"feet",yard:"yards",mile:"miles","nautical-mile":"nautical-miles",millimeter:"millimeters",centimeter:"centimeters",decimeter:"decimeters",meter:"meters",kilometer:"kilometers"}),B=i.ofType(D);function J(t){t.layoutOptions??={},t.layoutOptions.customTextElements??=[];const e="date";if(!t.layoutOptions.customTextElements.find((t=>e in t))){const{customTextElements:e}=t.layoutOptions;let s=I(Date.now(),g("short-date"));"ar"===O()&&(s=""+s),e.push({date:s})}}function N(t,e,s){if(!e)return;!(e.visible===s)&&t.layoutOptions&&(t.layoutOptions.elementOverrides?t.layoutOptions.elementOverrides[e.name]={visible:s}:t.layoutOptions.elementOverrides={[e.name]:{visible:s}})}let $=class extends l{constructor(t){super(t),this._serviceTemplateCustomTextElements=null,this._templateIdToCustomTemplate=new p,this._isFreeHand=!1,this._freeHandWidth=0,this._freehandHeight=0,this._asyncPrintTaskUrl=null,this._layoutInfoTaskUrl=null,this._customLayoutOptions=null,this.allowedFormats="all",this.allowedLayouts="all",this.browseTemplates=new B,this.defaultTemplates=new B,this.error=null,this.extraParameters=null,this.includeDefaultTemplates=!0,this.outSpatialReference=null,this.portal=b.getDefault(),this.portalTemplateIds=[],this.printServiceTemplates=new B,this.defaultTemplate=null,this.showPrintAreaEnabled=!1,this.printServiceUrl=null,this.printTimeout=12e4,this.templatesInfo=null,this.updateDelay=1e3,this.view=null,this.templateCustomTextElements=null,this.templateOptions=new A}initialize(){this.addHandles([m((()=>[this.showPrintAreaEnabled,this.view]),(()=>{this.showPrintAreaEnabled?this._enablePrintPreview():(this.removeHandles("overlay-handler"),this.view?.overlay?.removeItem(this._getOverlayItem()))})),m((()=>[this.templateOptions.layout,this.templateOptions.layoutItem]),(()=>{this.loaded&&this._processTemplateOptions()}))])}destroy(){this.removeHandles("overlay-handler"),this.view&&(this._overlayItem&&(this.view.overlay?.removeItem(this._overlayItem),this._overlayItem.destroy(),this._overlayItem=null),this.view=null)}get effectivePrintServiceUrl(){return this.printServiceUrl??null}get effectiveTemplateCustomTextElements(){if(!this._serviceTemplateCustomTextElements)return{};const t=r(this._serviceTemplateCustomTextElements);return this.templateCustomTextElements&&Object.keys(this.templateCustomTextElements).forEach((e=>{const s=t[e];if(s){const t=this.templateCustomTextElements?.[e];s.forEach((e=>{const[s]=Object.entries(e)[0];t?.forEach((t=>{const[i,o]=Object.entries(t)[0];s===i&&(e[s]=o)}))}))}})),Object.freeze(t)}get state(){return"loading"===this.loadStatus?"initializing":"failed"===this.loadStatus||this.error?"error":"loaded"===this.loadStatus&&this.view?.ready?"ready":"disabled"}async load(t){return this.addResolvingPromise(this._loadResources(t).catch((t=>this.error=t))),this}async print(t){const{view:e,extraParameters:s,updateDelay:i,outSpatialReference:a}=this;if(!e)throw new o("print:view-required","view is not set");J(t);const r=this._getOverlayItem(),l=t.scalePreserved||!this.showPrintAreaEnabled?void 0:k(new w,e.viewpoint,"map-only"===t.layout?[t.exportOptions.width,t.exportOptions.height]:[r.boxWidth,r.boxHeight]),n=new j({view:e,template:t,extent:l,extraParameters:s,updateDelay:i,outSpatialReference:a});try{const e=!!t.layoutItem?.id&&(this.portalTemplateIds.includes(t.layoutItem.id)||this.browseTemplates.some((e=>e.layoutItem?.id===t.layoutItem?.id)));return await S(e&&this._asyncPrintTaskUrl?this._asyncPrintTaskUrl:this.effectivePrintServiceUrl,n,{timeout:this.printTimeout})}catch(p){throw new o("print:export-error","An error occurred while exporting the web map.",{error:p})}}toPrintTemplate({attributionEnabled:t,author:e,copyright:s,customTextElements:i,dpi:a,forceFeatureAttributes:r,format:l,height:n,id:p,includeTables:m,layout:u,layoutItem:h,legendEnabled:d,northArrowEnabled:c,scale:y,scaleBarEnabled:f,scaleEnabled:T,title:v,width:w}){if(!u&&!h)throw new o("print:layout-required","layout is not set");const _=new C({attributionVisible:t,forceFeatureAttributes:r,format:l,includeTables:m,layout:u,layoutItem:h,layoutOptions:{authorText:e||"",copyrightText:s||"",customTextElements:i,titleText:v||""},outScale:y??0,scalePreserved:T});if(w&&(_.exportOptions.width=w),n&&(_.exportOptions.height=n),a&&(_.exportOptions.dpi=a),_.layoutOptions){d||(_.layoutOptions.legendLayers=[]);const t=this.getLayoutTemplateById(p)?.mapSurroundInfoOptions;if(t){const e=t.northArrow;for(const t of e)N(_,t,c);const s=t.scaleBar;for(const t of s)N(_,t,f);const i=t.legend;for(const t of i)N(_,t,d)}}return _}getLayoutTemplateById(t){return t?this._templateIdToCustomTemplate.get(t):null}async addPortalTemplate(t){if(!this.portal||!t?.id)return;try{t.loaded||await t.load()}catch{return void this.applyTemplate(this.defaultTemplate)}const e=new D({type:"browse-template",layoutInfoTaskUrl:this._layoutInfoTaskUrl,label:t.title,layoutItem:t});this._templateIdToCustomTemplate.set(e.id,e),this.browseTemplates.add(e)}removePortalTemplate(t){t.layoutItem&&this.templateOptions.id===t.layoutItem.id&&(this.defaultTemplate?this.applyTemplate(this.defaultTemplate):this.templateOptions.reset()),this.browseTemplates.remove(t),this._templateIdToCustomTemplate.delete(t.id)}async applyTemplate(t){if(!t)return void this.templateOptions.reset();!t.layout||!this.templatesInfo||this.templatesInfo.layout.choiceList.includes(t.layout)||(this.defaultTemplate?t=this.defaultTemplate:this.templateOptions.reset());const e=t.layout||t.layoutItem?.id,s=e?this.templateCustomTextElements?.[e]:void 0;if(await this.templateOptions.applyTemplate(t,{customTextElements:s,customLayoutOptions:this._customLayoutOptions}),e&&this._serviceTemplateCustomTextElements&&!this._serviceTemplateCustomTextElements[e]&&t.layoutTemplateInfo?.layoutOptions?.customTextElements){const s=r(this._serviceTemplateCustomTextElements);s[e]=t.layoutTemplateInfo.layoutOptions.customTextElements,this._serviceTemplateCustomTextElements=Object.freeze(s)}}async _loadResources(t){if(this.destroyed)return;await this._loadUrls(t);const[e,s]=await Promise.all([this._getLayoutToLayoutTemplateInfos(t),this._getPrintServiceTemplatesInfo(t)]);await this._loadAllTemplates(e,s,t),this._processPrintServiceTemplatesInfo(s),await this._processTemplateOptions(),this._updateOverLayItem()}async _processTemplateOptions(){const{layout:t,layoutItem:e}=this.templateOptions;if("map-only"!==t&&!this.templateOptions.id)if(this._customLayoutOptions={legend:this.templateOptions.legendEnabled,northArrow:this.templateOptions.northArrowEnabled,scaleBar:this.templateOptions.scaleBarEnabled},e?.id){try{e.loaded||await e.load()}catch{return void this.applyTemplate(this.defaultTemplate)}let t=this._templateIdToCustomTemplate.get(e.id);t||(t=new D({label:e.title,layoutItem:e,layoutInfoTaskUrl:this._layoutInfoTaskUrl}),this._templateIdToCustomTemplate.set(t.id,t)),await this.applyTemplate(t)}else if(t){const t=this.defaultTemplates.find((t=>t.layout===this.templateOptions.layout))??this.printServiceTemplates.find((t=>t.layout===this.templateOptions.layout));await this.applyTemplate(t??this.defaultTemplate)}}async _loadPortal(t){try{await this.portal.load(t)}catch(e){throw new o("print:could-not-load-portal","Cannot load print resource information from portal",{error:e,url:this.effectivePrintServiceUrl})}}async _loadUrls(t){if(this.printServiceUrl)this._set("effectivePrintServiceUrl",this.printServiceUrl),await this._updateLayoutInfoTaskUrl(this.effectivePrintServiceUrl);else{await this._loadPortal(t);const{printTask:e,asyncPrintTask:s,layoutInfoTask:i}=this.portal?.helperServices??{};this._set("effectivePrintServiceUrl",e?.url),this._asyncPrintTaskUrl=s?.url,await this._updateLayoutInfoTaskUrl(i?.url||this.effectivePrintServiceUrl)}const e=this.effectivePrintServiceUrl?.toLowerCase().split("/");if(!e?.includes("gpserver"))throw new o("print:invalid-print-service-url","Can't fetch print templates information from provided URL",{url:this.effectivePrintServiceUrl})}async _updateLayoutInfoTaskUrl(t,e){if(!t)return;const s=(await E(t,e)).find((t=>t.includes("Get Layout Templates Info")));s&&(this._layoutInfoTaskUrl=t.replace(q,`$1${encodeURI(s)}`))}_getPortalDefaultTemplates(t,e){return this.portal?.helperServices?.printTask?.templates?.filter((t=>"map_only"!==t.layout.toLowerCase()&&(!e||e.includes(L(t.layout)))))?.map((e=>{const s=D.fromJSON(e);if(s.type="default-template",s.layoutInfoTaskUrl=this._layoutInfoTaskUrl,s.layout){const e=t.get(s.layout);e&&s.setLayoutTemplateInfo(e)}return s}))??[]}async _getPortalCustomTemplates(t){if(this.printServiceUrl||!this.portal)return[];const{layoutGroupQuery:e,user:s}=this.portal,i=P.test(this.portal.url),o=s?.userLicenseTypeId,a=o&&V.has(o);if(!e||i&&!a)return[];const r=new x({query:e,disableExtraQuery:!0}),l=await this.portal.queryGroups(r,t);if(!l.total)return[];const n=l.results[0],p=new x({num:100,query:"type:Layout",sortField:n.sortField,sortOrder:n.sortOrder??void 0}),m=(await n.queryItems(p,t)).results;if(!m.length)return[];return m.map((t=>(this.portalTemplateIds.push(t.id),new D({type:"default-template",label:t.title,layoutItem:t,layoutInfoTaskUrl:this._layoutInfoTaskUrl}))))}async _loadAllTemplates(t,e,s){let i=!1;const o=e?.layout?.choiceList;if(this.includeDefaultTemplates&&this.portal&&!this.printServiceUrl){const e=this._getPortalDefaultTemplates(t,o);i=!!e.length,this.defaultTemplates.addMany(e);const a=await this._getPortalCustomTemplates(s);this.defaultTemplates.addMany(a);for(const t of this.defaultTemplates)this._templateIdToCustomTemplate.set(t.id,t)}i||t.forEach(((t,e)=>{if(!o||o.includes(e)){const s=new D({type:"print-service-template",layout:e,layoutInfoTaskUrl:this._layoutInfoTaskUrl});s.setLayoutTemplateInfo(t),this.printServiceTemplates.add(s),this._templateIdToCustomTemplate.set(s.id,s)}}))}_processPrintServiceTemplatesInfo(t){this._set("templatesInfo",t);const e=t?.layout?.defaultValue;if(e&&"map-only"!==e){const t=this.defaultTemplates.find((t=>t.layout===e))??this.printServiceTemplates.find((t=>t.layout===e))??this.defaultTemplates.at(0)??this.printServiceTemplates.at(0);this._set("defaultTemplate",t)}}async _getLayoutToLayoutTemplateInfos(t){const e=await R(this._layoutInfoTaskUrl,void 0,t),s=new Map,i={};for(const o of e){const t=L(o.layoutTemplate);s.set(t,o),i[t]=o.layoutOptions.customTextElements}return this._serviceTemplateCustomTextElements=Object.freeze(i),s}async _getPrintServiceTemplatesInfo(t){let s;try{({data:s}=await e(this.effectivePrintServiceUrl,{...t,query:{f:"json"},timeout:this.printTimeout}))}catch(l){throw n(l)?l:new o("print:unavailable-service-info","Can't fetch templates info from service",{error:l})}const{parameters:i}=s,a=i.find((({name:t})=>"Format"===t)),r=i.find((({name:t})=>"Layout_Template"===t));return{format:this._getFormat(a),layout:this._getLayout(r)}}_getFormat(t){const e="all"===this.allowedFormats?t.choiceList:t.choiceList.filter((t=>"string"!=typeof this.allowedFormats&&this.allowedFormats.some((e=>new RegExp(`\\b${e}\\b`,"i").test(t))))),i=(e.length?e:t.choiceList).map((t=>U.fromJSON(t))).filter(s),o=U.fromJSON(t.defaultValue),a=i.some((t=>new RegExp(`\\b${o}\\b`,"i").test(t)))?o:i[0];return{choiceList:i,defaultValue:a}}_getLayout(t){const e=t.choiceList.filter((t=>"map_only"!==t.toLowerCase())),i="all"===this.allowedLayouts?e:e.filter((t=>this.allowedLayouts.includes(L(t)))),o=(i.length?i:e).map(L).filter(s),a=L(t.defaultValue),r=o.includes(a)?a:o.find((t=>/(?=.*letter)(?=.*landscape)/i.test(t)))??o.find((t=>/(?=.*a4)(?=.*landscape)/i.test(t)))??o[0];return{choiceList:o,defaultValue:r}}_getOverlayItem(){return this._overlayItem||(this._overlayItem=new F({strokeDash:[5],strokeWidth:2,strokeColor:[30,144,255,255]})),this._overlayItem}_enablePrintPreview(){if(!this.view?.overlay)return;const t=this.templateOptions,e=this._getOverlayItem();this.addHandles([m((()=>[t.width,t.height,t.scaleEnabled,t.scale,t.layout,t.layoutItem,t.id,t.state,this.view?.scale,this.view?.size,this.view?.state.paddedViewState.size,this.view?.state.padding,this.loaded]),(()=>this._updateOverLayItem()),u),this.view?.on("drag",["Shift"],(t=>this._handleDrag(t)),H.WIDGET),this.view?.on("key-down",["Escape"],(()=>this._resetDrag()),H.WIDGET)],"overlay-handler"),this.view.overlay.addItem(e)}_updateOverLayItem(){if(!this.view)return;const t=this.templateOptions,e=this._getOverlayItem(),s=t.layoutItem?.id??t.layout,i=this.view,o=i.spatialReference,[a,r]=i.state.paddedViewState.size,l=i.state.padding;let n=0,p=0;if("map-only"===s)null!=t.width&&null!=t.height&&(n=t.width,p=t.height);else if(s){const e=t.id?this._templateIdToCustomTemplate.get(t.id):null,{webMapFrameSize:s,pageUnits:i}=e?.layoutTemplateInfo??{};let l=!1;if(s&&i)if(this._isFreeHand){const t=s[0]/s[1];n=this._freeHandWidth,p=this._freehandHeight,n>p?p=n/t:n=p*t}else{const t=G.fromJSON(i.toLowerCase()),e=o.unit;d(t)===d(e)?(n=c(s[0],t,e),p=c(s[1],t,e)):(l=!0,n=s[0],p=s[1])}if(!this._isFreeHand)if(t.scaleEnabled&&t.scale){const e=l?Math.min(a/n,r/p):y(o)*f*t.dpi;n*=e,p*=e}else if(0===n||0===p)n=a,p=r;else{const t=(a-.1*a)/n,e=(r-.1*r)/p,s=Math.min(t,e);n*=s,p*=s}}const{scaleEnabled:m,scale:u}=t,h=m&&u?u/this.view.scale:1;if(e.boxWidth=n*h||a,e.boxHeight=p*h||r,l&&(e.padding=l),e.backgroundWidth=a??0,e.backgroundHeight=r??0,"loading"===this.loadStatus)e.strokeColor=M;else if("loaded"===this.loadStatus)switch(this.templateOptions.state){case"pending":e.strokeColor=M;break;case"ready":e.strokeColor=W;break;case"error":e.strokeColor=z}}_resetDrag(){this._isFreeHand=!1,this._updateOverLayItem()}_handleDrag(t){switch(t.action){case"start":this._start();break;case"update":this._update(t);break;case"end":this._end()}t.stopPropagation()}_start(){this._isFreeHand=!0}_update(t){const e=this._getOverlayItem(),{x:s,y:i}=t,{x:o,y:a}=t.origin;s>o?(e.x=o,e.boxWidth=s-o):(e.x=s,e.boxWidth=o-s),i>a?(e.y=a,e.boxHeight=i-a):(e.y=i,e.boxHeight=a-i)}_end(){const t=this._getOverlayItem();if(!this.view||null==t.x||null==t.y)return;const e=this.view,s=e.toMap(h(t.x+.5*t.boxWidth,t.y+.5*t.boxHeight));t.x=null,t.y=null,e.goTo({center:s}),this._freeHandWidth=t.boxWidth,this._freehandHeight=t.boxHeight,"map-only"===this.templateOptions.layout&&(this.templateOptions.width=this._freeHandWidth,this.templateOptions.height=this._freehandHeight),this.templateOptions.scale=this.view.scale,this._updateOverLayItem()}};t([T()],$.prototype,"_serviceTemplateCustomTextElements",void 0),t([T()],$.prototype,"_templateIdToCustomTemplate",void 0),t([T()],$.prototype,"allowedFormats",void 0),t([T()],$.prototype,"allowedLayouts",void 0),t([T({type:B})],$.prototype,"browseTemplates",void 0),t([T({type:B})],$.prototype,"defaultTemplates",void 0),t([T()],$.prototype,"error",void 0),t([T()],$.prototype,"extraParameters",void 0),t([T()],$.prototype,"includeDefaultTemplates",void 0),t([T({readOnly:!0})],$.prototype,"effectivePrintServiceUrl",null),t([T()],$.prototype,"effectiveTemplateCustomTextElements",null),t([T({type:_})],$.prototype,"outSpatialReference",void 0),t([T({type:b})],$.prototype,"portal",void 0),t([T()],$.prototype,"portalTemplateIds",void 0),t([T({type:B})],$.prototype,"printServiceTemplates",void 0),t([T({readOnly:!0})],$.prototype,"defaultTemplate",void 0),t([T()],$.prototype,"showPrintAreaEnabled",void 0),t([T()],$.prototype,"printServiceUrl",void 0),t([T()],$.prototype,"printTimeout",void 0),t([T({readOnly:!0})],$.prototype,"state",null),t([T({readOnly:!0})],$.prototype,"templatesInfo",void 0),t([T()],$.prototype,"updateDelay",void 0),t([T()],$.prototype,"view",void 0),t([T()],$.prototype,"templateCustomTextElements",void 0),t([T({type:A})],$.prototype,"templateOptions",void 0),$=t([v("esri.widgets.Print.PrintViewModel")],$);const Q=$;export{Q as default};