@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
1,043 lines (1,032 loc) • 44.6 kB
JavaScript
import { html as uHtml } from 'uhtml';
import PrintManager from './tools/PrintManager';
import PrintMaskManager from './tools/printMaskManager';
import { toDegrees, toRadians } from 'ol/math';
import MapManager from '../../tools/state/mapManager';
import I18nManager from '../../tools/i18n/i18nmanager';
import { unByKeyAll } from '../../tools/utils/olutils';
import { padNumber } from 'ol/string';
import GirafeHTMLElement from '../../base/GirafeHTMLElement';
/** Represents the status of a printing process. */
var PrintStatus;
(function (PrintStatus) {
PrintStatus[PrintStatus["Started"] = 0] = "Started";
PrintStatus[PrintStatus["Success"] = 1] = "Success";
PrintStatus[PrintStatus["Errored"] = 2] = "Errored";
})(PrintStatus || (PrintStatus = {}));
/**
* Print panel component.
* Read print capabilities and generate options from it.
* Be able to print the content on the map, based on the layer tree and the OL map.
* Have actions on the print mask and on the map (rotation).
*/
class PrintComponent extends GirafeHTMLElement {
constructor() {
super('print');
Object.defineProperty(this, "template", {
enumerable: true,
configurable: true,
writable: true,
value: () => {
return uHtml `<style>
*{font-family:Arial,sans-serif}.hidden{display:none!important}.gg-rotate90{transform:rotate(90deg)}.gg-rotate180{transform:rotate(180deg)}.gg-rotate270{transform:rotate(270deg)}img{filter:var(--svg-filter)}img.legend-image{filter:var(--svg-map-filter);background:var(--svg-legend-bkg)}div{scrollbar-width:thin}a{color:var(--link-color)}a:visited{color:var(--link-color)} spin{from{transform:rotate(0)}to{transform:rotate(360deg)}} spin-wait{0%{transform:rotate(0)}7%{transform:rotate(360deg)}100%{transform:rotate(360deg)}}.gg-spin{animation-name:spin;animation-duration:2s;animation-iteration-count:infinite;animation-timing-function:linear}.gg-spin-wait{animation-name:spin-wait;animation-duration:10s;animation-iteration-count:infinite;animation-timing-function:linear}::-webkit-scrollbar{width:5px}::-webkit-scrollbar-thumb{background:#999}.gg-button,.gg-input,.gg-select,.gg-textarea{background-color:var(--bkg-color);color:var(--text-color);outline:0;border-radius:3px;border:var(--app-standard-border);display:inline-block;box-sizing:border-box;padding:0 0 0 .5rem;margin:0;cursor:pointer}.gg-label{background-color:var(--bkg-color);color:var(--text-color);border:none;display:inline-block;padding:0;margin:0}.gg-button,.gg-input,.gg-label,.gg-select{min-height:calc(var(--app-standard-height)/ 1.5);max-height:calc(var(--app-standard-height)/ 1.5);line-height:calc(var(--app-standard-height) / 1.5)}.gg-textarea{padding:.5rem;height:6rem}.gg-input{cursor:text}.gg-checkbox{accent-color:var(--text-color);width:1.2rem}.gg-range{accent-color:var(--text-color)}.gg-button{padding:0 .5rem}.gg-button.active{border:solid 1px var(--text-color-grad2);background-color:var(--text-color-grad2);color:var(--bkg-color)}.gg-button:disabled{background-color:#d3d3d3;color:grey;border:none;cursor:not-allowed}.gg-button>img{vertical-align:middle}.gg-icon-button{border:none;background-color:transparent;display:flex;flex-direction:column;color:var(--text-color);padding:0;align-items:center;justify-content:center;cursor:pointer}.gg-big,.gg-big-withtext{min-width:var(--app-standard-height);min-height:var(--app-standard-height);max-height:var(--app-standard-height)}.gg-big img,.gg-big-withtext img{margin:0;width:calc(var(--app-standard-height) - 1.5rem)}.gg-big-withtext span{font-size:.9rem;font-variant:small-caps;padding:0 1rem}.gg-medium,.gg-medium-withtext{flex-direction:row;min-width:calc(var(--app-standard-height)/ 1.2);min-height:calc(var(--app-standard-height)/ 1.2);max-height:calc(var(--app-standard-height)/ 1.2)}.gg-medium img{margin:0;width:calc(var(--app-standard-height)/ 2.4)}.gg-medium-withtext img{margin-left:.5rem;width:calc(var(--app-standard-height)/ 2.4)}.gg-medium-withtext span{font-size:.9rem;padding:0 1rem;padding-left:.5rem}.gg-small,.gg-small-withtext{flex-direction:row;min-width:calc(var(--app-standard-height)/ 2);min-height:calc(var(--app-standard-height)/ 2);max-height:calc(var(--app-standard-height)/ 2)}.gg-small img{margin:0;width:calc(var(--app-standard-height)/ 3)}.gg-small-withtext img{margin-left:.5rem;width:calc(var(--app-standard-height)/ 3)}.gg-small-withtext span{font-size:.9rem;padding:0 .5rem;padding-left:.3rem}.gg-button:hover,.gg-icon-button:hover,.gg-input:hover,.gg-select:hover,.gg-textarea:hover{background-color:var(--bkg-color-grad1)}.gg-opacity{opacity:.5}.gg-opacity:hover{background-color:transparent;opacity:1}.gg-tabs{display:flex;justify-content:left;margin:.5rem auto 0;border-bottom:1px solid grey;cursor:pointer;height:2rem;align-items:end;gap:1rem;margin-bottom:1rem}.gg-tab{border:none;background:0 0;cursor:pointer;padding:.5rem;color:var(--text-color)}.gg-tab.active{border-bottom:solid 2px var(--text-color-grad2);font-weight:600}.girafe-button-big,.girafe-button-large,.girafe-button-small,.girafe-button-tiny{border:none;background-color:transparent;display:flex;flex-direction:column;color:var(--text-color)}.girafe-button-big:hover,.girafe-button-large:hover,.girafe-button-small:hover,.girafe-button-tiny:hover{background-color:var(--bkg-color-grad1);cursor:pointer}.girafe-button-big.dark,.girafe-button-large.dark,.girafe-button-small.dark,.girafe-button-tiny.dark{background-color:var(--bkg-color);filter:invert(1)}.girafe-button-big{width:var(--app-standard-height);height:var(--app-standard-height);align-items:center;padding:1rem}.girafe-button-big img{overflow:hidden}.girafe-button-large{flex-direction:row}.girafe-button-large img{margin:.3rem;height:2rem}.girafe-button-large span{line-height:2rem;height:2rem;margin:.3rem}.girafe-button-small{min-width:calc(var(--app-standard-height)/ 2);height:calc(var(--app-standard-height)/ 2);align-items:center;padding:.5rem}.girafe-button-small img{overflow:hidden}.girafe-button-small span{width:100%;text-align:left;overflow:hidden;text-overflow:ellipsis}.girafe-button-tiny{width:1rem;height:1rem;align-items:center;padding:0}.girafe-button-tiny img{overflow:hidden}
</style><style>
#panel{height:100%;overflow:auto;min-width:20rem}#content{background:var(--bkg-color);color:var(--text-color);padding:1.5rem;margin:0}#content .message{text-align:center;width:100%}#content .message *{margin:.25rem}.option{margin-top:.5rem;display:flex}.option label{width:40%}.option label:after{content:' :'}.option input,.option select,.option textarea{flex-grow:1}.option input.gg-checkbox{flex-grow:0}.rotation{flex-grow:1;display:flex;gap:.5rem}#rotationSlider{width:0}#rotationNumber{width:4rem;flex-grow:0}#content #export-pdf{float:right;margin-top:1rem}#content button{background-color:var(--bkg-color);color:var(--text-color);border-radius:3px;outline:0;border:solid 1px var(--text-color);cursor:pointer}#content button:hover{background-color:var(--bkg-color-grad2)}#content #print-list{margin-top:5rem}#print-list .print-item{position:relative;padding:.5rem;margin-top:.5rem;border:solid 1px var(--text-color);color:var(--text-color)}#print-list .print-item .container{border:none;display:inline;text-align:unset;width:100%}#print-list .print-item .cancel{cursor:pointer;position:absolute;top:.5rem;right:.5rem;color:var(--text-color-grad1);border:none;background-color:transparent}.print-item .cancel i:before{content:'\uf00d'}.print-item .cancel:hover{border-color:var(--text-color);color:var(--text-color)}.print-item i.status{margin-right:1rem;float:left;width:3rem;text-align:center}.print-item:has(.success):hover{background-color:var(--bkg-color-grad2);cursor:pointer}.print-item i.status::before{line-height:3rem;display:block}.print-item p{line-height:1.3rem}.print-item p.time{position:absolute;bottom:0;right:0;margin-right:.5rem}#custom-scale{color:var(--text-color);display:flex;flex-direction:row;flex-wrap:wrap;justify-content:flex-start;align-items:center}#custom-scale .svg-info{margin-left:.5rem}#custom-scale>div{display:flex;width:100%;align-items:center}.gg-custom-scale{justify-content:flex-end}
</style>
<div id="panel">
<div id="content">
<div class="${this.getRenderState() === 'loading' ? '' : 'hidden'}">
<div class="message">
<div i18n="Connecting to the print server, please wait."></div>
<img alt="loading-icon" src="icons/loading.svg" class="gg-spin" />
</div>
</div>
<div class="${this.getRenderState() === 'error' ? '' : 'hidden'}">
<div class="message" i18n="The print server is unavailable. Please, try later."></div>
</div>
<div class="${this.getRenderState() === 'setup' ? '' : 'hidden'}">
<div class="option">
<label for="layout" i18n="Layout" class="gg-label">Layout</label>
<select id="layout" class="gg-select" onchange="${(evt) => this.onLayoutChanged(evt)}">
${this.layouts.map((layout) => uHtml `
<option i18n="${layout.name}" ?selected="${this.selectedLayout?.name === layout.name}" value="${layout.name}">
${layout.name}
</option>
`)}
</select>
</div>
<div class="option gg-custom-scale">
<label for="scale" i18n="Scale" class="gg-label">Scale</label>
<select id="scale" class="gg-select" onchange="${(evt) => this.onScaleChanged(evt)}">
${this.scales.map((scale) => uHtml `
<option ?selected="${this.getSelectedScale() === scale}" value="${scale}">
<span>1 : </span><span i18n="${scale}" i18nFn="formatNumber">${scale}</span>
</option>
`)}
<option
i18n="Manual entry"
class="${this.configManager.Config.print.customScale === true ? '' : 'hidden'}"
value="custom">
Manual entry
</option>
</select>
</div>
<div class="${this.showCustomScale === true ? 'option' : 'hidden'}">
<div id="custom-scale">
<label for="scale" i18n="Custom scale" class="gg-label">Custom scale</label>
<div>
<span>1 : </span
><input
class="gg-input"
type="number"
min="10"
onkeypress="${(evt) => this.onCustomScaleTyped(evt)}" />
<span class="svg-info" tip="Press 'Enter' to apply" tip-placement="top"
><img alt="Info" src="icons/info.svg"
/></span>
</div>
</div>
</div>
<div class="option">
<label for="format" i18n="Format" class="gg-label">Format</label>
<select id="format" class="gg-select" onchange="${(evt) => this.onFormatChanged(evt)}">
${this.printFormats.map((format) => uHtml `
<option ?selected="${this.getSelectedFormat() === format}" value="${format}">${format.toUpperCase()}</option>
`)}
</select>
</div>
${this.dpis.length < 2 ? null : uHtml `
<div class="option">
<label for="dpi" class="gg-label">DPI</label>
<select id="dpi" class="gg-select" onchange="${(evt) => this.onDpiChanged(evt)}">
${this.dpis.map((dpi) => uHtml `
<option ?selected="${this.getSelectedDpi() === dpi}" value="${dpi}">${dpi}</option>
`)}
</select>
</div>
`}
<div class="option">
<label for="rotationSlider" i18n="Rotation" class="gg-label">Rotation</label>
<div class="rotation">
<input
id="rotationSlider"
class="gg-range"
type="range"
min="-180"
max="180"
step="1"
value="${this.getRotation()}"
oninput="${(evt) => this.onInputRotationChanged(evt)}" />
<input
id="rotationNumber"
class="gg-input"
type="number"
min="-180"
max="180"
step="1"
value="${this.getRotation()}"
oninput="${(evt) => this.onInputRotationChanged(evt)}" />
</div>
</div>
<!-- prettier is breaking this line because it breaks just after the return -->
<!-- prettier-ignore -->
${this.attributeNames.map((attrName) => {
if (this.getAttributeInputType(attrName) === 'number') {
return uHtml `
<div class="option">
<label for="${attrName}" i18n="${this.attrNameForI18n(attrName)}" class="gg-label">${attrName}</label>
<input
id="${attrName}"
type="number"
class="gg-input"
value="${this.getCapabilitiesAttribute(attrName)?.default}" />
</div>
`;
}
if (this.getAttributeInputType(attrName) === 'checkbox') {
return uHtml `
<div class="option">
<label for="${attrName}" i18n="${this.attrNameForI18n(attrName)}" class="gg-label">${attrName}</label>
<input
id="${attrName}"
type="checkbox"
class="gg-checkbox"
?checked="${this.getCapabilitiesAttribute(attrName)?.default}" />
</div>
`;
}
if (this.getAttributeInputType(attrName) === 'textarea') {
return uHtml `
<div class="option">
<!-- prettier-ignore -->
<textarea
id="${attrName}"
class="gg-textarea"
i18n="${this.attrNameForI18n(attrName)}"
placeholder="${attrName}">${this.getCapabilitiesAttribute(attrName)?.default}</textarea>
</div>
`;
}
return uHtml `
<div class="option">
<input
id="${this.attrNameForI18n(attrName)}"
class="gg-input"
i18n="${attrName}"
placeholder="${attrName}"
type="text"
value="${this.getCapabilitiesAttribute(attrName)?.default}" />
</div>
`;
})}
<button id="export-pdf" class="gg-button" onclick="${() => this.print()}" i18n="Print">Print</button>
<div id="print-list">
${this.printList.map((printItem) => uHtml `
<div id="${printItem.id}" class="print-item" title="${printItem.elementTitle}">
<button class="cancel" tabindex="0" onclick="${() => this.onCancelPrintElementClicked(printItem.id)}">
<img alt="close-icon" src="icons/close.svg" />
</button>
<button class="container" tabindex="0" onclick="${() => this.onPrintElementClicked(printItem.id)}">
<img
alt="loading-icon"
src="icons/loading.svg"
class="${printItem.status === PrintStatus.Started ? 'gg-spin' : 'hidden'}" />
<img
alt="loading-icon"
src="icons/download.svg"
class="${printItem.status === PrintStatus.Success ? '' : 'hidden'}" />
<img
alt="loading-icon"
src="icons/error.svg"
class="${printItem.status === PrintStatus.Errored ? '' : 'hidden'}" />
<p>
<span i18n="${printItem.selectedLayoutName}">${printItem.selectedLayoutName}</span>
<span>(</span><span>${printItem.selectedFormat.toUpperCase()}</span><span>)</span>
</p>
<p class="time">${printItem.time}</p>
</button>
</div>
`)}
</div>
</div>
</div>
</div>
`;
}
});
Object.defineProperty(this, "default_dpi", {
enumerable: true,
configurable: true,
writable: true,
value: 96
});
Object.defineProperty(this, "default_scale", {
enumerable: true,
configurable: true,
writable: true,
value: 10000
});
Object.defineProperty(this, "default_resolution", {
enumerable: true,
configurable: true,
writable: true,
value: 100
});
Object.defineProperty(this, "default_format", {
enumerable: true,
configurable: true,
writable: true,
value: 'pdf'
});
Object.defineProperty(this, "i18nManager", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "mapManager", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "eventsCallbacks", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "eventKeys", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "printManager", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "printList", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "printUrl", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "capabilities", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "configAttributeNames", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "printMaskManager", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "visible", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
Object.defineProperty(this, "isWithCapabilitiesComponentSetup", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
Object.defineProperty(this, "hasErrorFetchingCapabilities", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
Object.defineProperty(this, "showCustomScale", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
Object.defineProperty(this, "attributeNames", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "printFormats", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "layouts", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "selectedLayout", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "scales", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "dpis", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
this.mapManager = MapManager.getInstance();
this.i18nManager = I18nManager.getInstance();
}
connectedCallback() {
this.render();
this.registerVisibilityEvents();
}
/**
* Render the component regarding its visibility.
* Fetch the print capabilities at first rendering, then render the print mask too and register to events.
*/
render() {
this.visible ? this.renderComponent() : this.renderEmptyComponent();
}
/**
* @returns {string} The render state.
* - 'error' if there was an error fetching the capabilities.
* - 'setup' if the capabilities have been set up.
* - 'loading' if the capabilities are being fetched.
*/
getRenderState() {
if (this.hasErrorFetchingCapabilities) {
return 'error';
}
if (this.capabilities) {
return 'setup';
}
return 'loading';
}
/**
* Update the values relative to the layout (attributes, scales, etc.)
* Set scale and print format in the state.
* Renders the panel with new info.
*/
onLayoutChanged(event) {
const eventValue = event.target?.value;
this.selectedLayout = this.getCapabilitiesLayout(eventValue);
const clientInfo = this.getClientInfo();
this.updateScales(clientInfo);
this.updateDpis(clientInfo);
this.updateAvailableAttributes();
this.state.print.pageSize = [clientInfo.width, clientInfo.height];
this.render();
}
/**
* Set selected scale in the state and update the mask.
*/
onScaleChanged(event) {
this.printMaskManager?.setManuallySelectedScale(false);
if (this.configManager.Config.print.customScale) {
if (event.target?.value === 'custom') {
this.showCustomScale = true;
this.render();
return;
}
this.showCustomScale = false;
this.render();
}
this.state.print.scale = parseInt(event.target?.value);
this.printMaskManager?.zoomToScale(this.state.print.scale);
this.printMaskManager?.setManuallySelectedScale(false);
}
onCustomScaleTyped(evt) {
// Only when the user presses the Enter key.
if (evt.key === 'Enter') {
const value = parseInt(evt.target?.value);
if (value) {
this.state.print.scale = value;
this.printMaskManager?.zoomToScale(this.state.print.scale);
this.render();
this.printMaskManager?.setManuallySelectedScale(true);
}
}
}
/**
* @Returns the current print scale.
*/
getSelectedScale() {
return this.state.print.scale;
}
/**
* @Returns the current print format value.
*/
getSelectedFormat() {
return this.state.print.format;
}
/**
* @Returns the current print dpi value.
*/
getSelectedDpi() {
return this.state.print.dpi;
}
/**
* Set selected print format.
*/
onFormatChanged(event) {
this.state.print.format = event.target?.value;
}
/**
* Set selected dpi format.
*/
onDpiChanged(event) {
const value = event.target?.value;
this.state.print.dpi = value ? parseInt(value) : this.default_dpi;
}
/**
* @returns {number} The rotation angle in degrees, from the map.
*/
getRotation() {
return toDegrees(this.mapManager.getMap().getView().getRotation());
}
/**
* Sync both rotation inputs and update the map rotation value.
*/
onInputRotationChanged(event) {
const element = event.target;
this.setRotation(element);
}
/**
* @returns The matching attribute in the selected "capabilities" layout.
*/
getCapabilitiesAttribute(attributeName) {
const attributes = this.selectedLayout?.attributes ?? [];
return attributes.find((attr) => attr.name === attributeName);
}
/**
* Used to know the matching HTML element.
* @returns An arbitrary type based on the matching "capabilities" attribute.
*/
getAttributeInputType(attributeName) {
const attribute = this.getCapabilitiesAttribute(attributeName);
if (attribute?.name === 'comments')
return 'textarea';
if (attribute?.type === 'Number')
return 'number';
if (attribute?.type === 'LegendAttributeValue')
return 'checkbox';
if (attribute?.type === 'Boolean')
return 'checkbox';
return 'text';
}
/**
* Legacy fix for attrName i18n.
*/
attrNameForI18n(attrName) {
if (attrName === 'legend')
return 'Legend';
return attrName;
}
/**
* Prints the current map state regarding every print options.
* Can add datasource (based on selection) and a legend.
* The status will be tracked until finished.
*/
print() {
const customAttributes = this.getCustomAttributes();
const spec = this.printManager?.encode({
mapManager: this.mapManager,
i18nManager: this.i18nManager,
state: this.state,
scale: this.getSelectedScale() ?? this.default_scale,
printResolution: this.mapManager.getMap().getView().getResolution() ?? this.default_resolution,
pageSize: this.state.print.pageSize ?? [],
dpi: this.getSelectedDpi() ?? this.default_dpi,
layout: this.selectedLayout?.name ?? '',
format: this.getSelectedFormat() ?? this.default_format,
customAttributes
});
if (!spec) {
console.error('Unable to create print spec');
return;
}
this.printManager?.requestReport(this.printUrl ?? '', spec).then((result) => this.trackPrintStatus(result));
}
/**
* On print element clicked:
* - Download it on success
* - Do nothing otherwise element.
*/
onPrintElementClicked(itemId) {
const printItem = this.getPrintElement(itemId);
if (printItem?.status !== PrintStatus.Success) {
return;
}
window.open(printItem.downloadUrl, '_blank');
}
/**
* Removes the print element with the specified itemId from the printList array.
* Cancel the print if is it not finished.
*/
onCancelPrintElementClicked(itemId) {
const itemIndex = this.printList.findIndex((printItem) => printItem.id === itemId);
if (itemIndex < 0) {
return;
}
const printItem = this.printList[itemIndex];
if (printItem.status === PrintStatus.Started) {
this.printManager?.cancelReport(this.printUrl, printItem.id);
}
this.printList.splice(itemIndex, 1);
this.render();
}
/**
* Renders the component by calling the necessary methods.
* @private
*/
renderComponent() {
super.render();
this.renderComponentCapabilitiesPart();
super.girafeTranslate();
}
/**
* Renders the component capabilities part, like the mask and the capabilities related elements.
* Loads the capabilities and the initial config if not already loaded.
* @private
*/
async renderComponentCapabilitiesPart() {
if (this.capabilities) {
// We have loaded capabilities, then renders it normally.
if (!this.isWithCapabilitiesComponentSetup) {
this.setupWithCapabilitiesComponent();
}
this.printMaskManager?.setPossibleScales(this.scales);
return;
}
// If we don't have capabilities and no error (not tried to load them), then load them.
if (!this.hasErrorFetchingCapabilities) {
await this.initComponentConfig();
// Render again with capabilities options or error.
this.render();
}
// Otherwise, does nothing ("on error" state).
}
/**
* Setup "visible" component (with capabilities) related functions.
* Do not update things related to the panel itself (that would need another render()).
* @private
*/
setupWithCapabilitiesComponent() {
this.updateInputRotationFromMap();
this.state.print.maskVisible = true;
this.printMaskManager = new PrintMaskManager(this.mapManager.getMap());
this.printMaskManager?.setPossibleScales(this.scales);
this.setupPrintManager();
this.registerEvents();
this.isWithCapabilitiesComponentSetup = true;
}
/**
* Renders an empty component when it's not visible.
* Destroy not-visibility related events.
* @private
*/
renderEmptyComponent() {
this.hasErrorFetchingCapabilities = false;
this.isWithCapabilitiesComponentSetup = false;
this.printMaskManager?.destroy();
unByKeyAll(this.eventKeys);
this.eventKeys.length = 0;
this.unsubscribe(this.eventsCallbacks);
this.eventsCallbacks.length = 0;
this.renderEmpty();
}
/**
* Sets up the print manager if it doesn't already exist.
* @private
*/
setupPrintManager() {
if (!this.printManager) {
this.printManager = new PrintManager();
}
}
/**
* Event about visibility that must be always listened by this component, even hidden.
* @private
*/
registerVisibilityEvents() {
this.subscribe('interface.printPanelVisible', (_oldValue, newValue) => this.togglePanel(newValue));
}
/**
* Listen events that must be listened if the print panel is visible.
* @private
*/
registerEvents() {
// Prevent feature selection in the map
this.registerInteractionListener('map.select', true);
const view = this.mapManager.getMap().getView();
this.eventKeys.push(view.on('change:rotation', () => {
this.updateInputRotationFromMap();
}));
this.eventsCallbacks.push(this.subscribe('print.scale', (_oldVal, newVal) => {
const scaleElement = this.shadow.querySelector('#scale');
scaleElement.value = newVal;
}));
this.eventsCallbacks.push(this.subscribe('oauth.status', async (_oldValue, newValue) => {
if (newValue === 'loggedIn' || newValue === 'loggedOut') {
await this.initComponentConfig();
this.render();
}
}));
}
/**
* Set the visibility of the panel.
* @private
*/
async togglePanel(visible) {
this.visible = visible;
this.render();
}
/**
* Update the input rotation value from the map rotation value.
*/
updateInputRotationFromMap() {
const rotationInputElement = this.shadow.querySelector('#rotationSlider');
let rotation = Math.round(this.getRotation());
if (rotation > 180) {
rotation -= 360;
}
if (rotation < -180) {
rotation += 360;
}
this.setRotation(rotationInputElement, rotation);
}
/**
* Sync both rotation inputs and update the map rotation value (except if the value is
* provided, meaning the map already has the right rotation).
* @private
*/
setRotation(rotationInputElement, mapRotationValue = null) {
const slider = rotationInputElement.parentElement?.querySelector('#rotationSlider');
const number = rotationInputElement.parentElement?.querySelector('#rotationNumber');
const rotation = mapRotationValue ?? parseInt(rotationInputElement.value);
slider.value = `${rotation}`;
number.value = `${rotation}`;
if (!mapRotationValue) {
this.mapManager.getMap().getView().setRotation(toRadians(rotation));
}
}
/**
* @returns The URL to fetch the print capabilities.
* @private
*/
getCapabilitiesUrl() {
return this.printUrl + '/capabilities.json';
}
/**
* @returns a pending or finished PrintElement by id.
* @private
*/
getPrintElement(itemId) {
return this.printList.find((element) => element.id === itemId);
}
/**
* Load the application config and then fetch the capabilities and initialize the print.
* @private
*/
async initComponentConfig() {
await this.loadConfig();
await this.fetchCapabilities();
this.initFromCapabilities();
if (!this.capabilities) {
this.hasErrorFetchingCapabilities = true;
}
}
/**
* @returns the fetched print capabilities or undefined in case of error.
* @private
/*/
async fetchCapabilities() {
this.printUrl = this.configManager.Config.print.url;
if (this.printUrl.endsWith('/')) {
this.printUrl = this.printUrl.slice(0, -1);
}
let capabilities = undefined;
try {
const fetchOptions = { referrer: '' };
if (this.configManager.Config.oauth || this.state.oauth.status === 'loggedIn') {
fetchOptions.credentials = 'include';
}
const response = await fetch(this.getCapabilitiesUrl(), fetchOptions);
capabilities = await response.json();
}
catch (error) {
console.error(error);
}
this.capabilities = capabilities;
return capabilities;
}
/**
* Init the print component default values with the print capabilities.
* @private
*/
initFromCapabilities() {
if (!this.capabilities) {
return;
}
const printLayouts = this.capabilities?.layouts ?? [];
if (!printLayouts.length) {
console.error("Can't print without any configured print layouts.");
this.capabilities = undefined;
return;
}
const config = this.configManager.Config.print;
this.initLayouts();
const selectedLayout = this.getCapabilitiesLayout(config.defaultLayout ?? '');
this.selectedLayout = selectedLayout ?? printLayouts[0];
this.initFormats();
const clientInfo = this.getClientInfo();
this.updateScales(clientInfo);
this.updateDpis(clientInfo);
this.state.print.pageSize = [clientInfo.width, clientInfo.height];
if (config.attributeNames) {
this.configAttributeNames = config.attributeNames;
}
this.updateAvailableAttributes();
}
/**
* Initializes the print formats and default selected format based on the configuration.
* @private
*/
initFormats() {
const config = this.configManager.Config.print;
const printFormats = config.formats;
this.printFormats = PrintComponent.filterValidPrintFormats(printFormats, this.capabilities?.formats);
const defaultFormat = config.defaultFormat;
const validFormat = PrintComponent.getValidDefaultFormat(this.printFormats, defaultFormat);
this.state.print.format = validFormat ?? this.default_format;
}
/**
* Whitelist the available layouts with the config.print.layouts, or allows every of them.
* @private
*/
initLayouts() {
const availableLayouts = this.capabilities?.layouts;
const configLayouts = this.configManager.Config.print.layouts;
this.layouts = PrintComponent.filterValidLayouts(availableLayouts, configLayouts);
}
/**
* @returns The capabilities layout with the specified name, or undefined if not found.
*/
getCapabilitiesLayout(layoutName) {
return this.layouts.find((layout) => layout.name === layoutName);
}
/**
* Set the available print scales for this layout.
* The available scales are whitelisted with the config.print.scales (if any).
* @private
*/
updateScales(clientInfo) {
this.scales = PrintComponent.filterValidScales(clientInfo.scales, this.configManager.Config.print.scales);
this.printMaskManager?.setPossibleScales(this.scales);
}
/**
* Updates the available DPIs and current selected dpi value based on the provided client info.
* @private
*/
updateDpis(clientInfo) {
this.dpis = clientInfo.dpiSuggestions;
const currentDpi = this.getSelectedDpi() ?? 0;
if (!this.dpis.includes(currentDpi) || currentDpi > clientInfo.maxDpi) {
this.state.print.dpi = this.dpis.length ? this.dpis[0] : this.default_dpi;
}
}
/**
* Updates the available print/panel attributes based on the selected layout and the wanted attribute names.
* @private
*/
updateAvailableAttributes() {
const layoutAttributes = this.selectedLayout?.attributes ?? [];
this.attributeNames = this.configAttributeNames.filter((attrName) => {
if (layoutAttributes.some((layoutAttr) => layoutAttr.name === attrName)) {
return true;
}
console.warn(`Configured attribute "${attrName}" does not exist in layout "${this.selectedLayout?.name}"`);
});
}
/**
* @returns The ClientInfo config object from the current selected layout.
* @private
*/
getClientInfo() {
const mapAttribute = this.getCapabilitiesAttribute('map');
if (!mapAttribute) {
console.error('No map client info in the current layout');
}
return mapAttribute.clientInfo;
}
/**
* @returns The capabilities attribute default value or the matching selected value in this print panel.
* @private
*/
getCapabilitiesAttributeValue(attrName) {
const attribute = this.getCapabilitiesAttribute(attrName);
if (!attribute) {
return '';
}
const type = this.getAttributeInputType(attrName);
const input = this.shadow.querySelector(`#${attrName}`);
if (type === 'checkbox') {
const checked = input?.checked ?? attribute.default ?? false;
return `${checked}`;
}
const value = input?.value ?? attribute.default;
return value ? `${value}` : '';
}
/**
* @returns An object that contains the custom attributes to print the map.
*/
getCustomAttributes() {
const customAttributes = this.getAttributesAndValue();
if (this.getCapabilitiesAttributeValue('legend') === 'true') {
const legend = this.encodeLegend();
if (legend) {
customAttributes['legend'] = legend;
}
}
if (this.getCapabilitiesAttribute('datasource')) {
customAttributes['datasource'] = this.selectedFeaturesToDatasource();
}
return customAttributes;
}
/**
* @returns An object containing the configured wanted attributes to print with their corresponding attribute values.
* @private
*/
getAttributesAndValue() {
return this.attributeNames
.filter((attrName) => attrName !== 'legend')
.reduce((attributeObj, attrName) => {
attributeObj[attrName] = this.getCapabilitiesAttributeValue(attrName);
return attributeObj;
}, {});
}
/**
* @returns The encoded legend or null if empty or if encoding fails.
*/
encodeLegend() {
const options = {
...{
mapManager: this.mapManager,
i18nManager: this.i18nManager,
state: this.state,
scale: this.getSelectedScale() ?? this.default_scale,
printResolution: this.mapManager.getMap().getView().getResolution() ?? this.default_resolution,
pageSize: this.state.print.pageSize ?? [],
dpi: this.getSelectedDpi() ?? this.default_dpi
},
...this.configManager.Config.print.printLegend
};
return this.printManager?.encodeLegend(options) || null;
}
/**
* Set an initial print status element and track the state of the linked print task.
* @private
*/
trackPrintStatus(result) {
const id = result.ref;
const date = new Date(Date.now());
const time = padNumber(date.getHours(), 2) + ':' + padNumber(date.getMinutes(), 2);
this.printList.push({
id,
time,
selectedFormat: this.getSelectedFormat() ?? this.default_format,
selectedLayoutName: this.selectedLayout?.name ?? '',
title: this.getCapabilitiesAttributeValue('title') || id,
status: PrintStatus.Started
});
this.render();
this.printManager
?.getDownloadUrl(this.printUrl ?? '', result, 2000)
.then((downloadUrl) => this.printFinished(id, downloadUrl))
.catch((error) => this.printError(id, error));
}
/**
* On print finished update the print element with the status and the download url.
* @private
*/
printFinished(itemId, downloadUrl) {
const printItem = this.getPrintElement(itemId);
if (!printItem) {
return;
}
printItem.status = PrintStatus.Success;
printItem.downloadUrl = downloadUrl;
this.render();
}
/**
* On print errored update the print element with the status and the error info.
* @private
*/
printError(itemId, error) {
const printItem = this.getPrintElement(itemId);
if (!printItem) {
return;
}
printItem.status = PrintStatus.Errored;
printItem.elementTitle = error;
this.render();
}
/**
* @returns An array of MFPPrintDatasource objects representing the selected features.
*/
selectedFeaturesToDatasource() {
const center = this.mapManager.getMap().getView().getCenter() ?? [0, 0];
const scale = this.getSelectedScale() ?? -1;
const pageSize = this.state.print.pageSize ?? [];
const extent = this.printManager?.getExtent(pageSize, scale, center) || [0, 0, Infinity, Infinity];
const selectedFeatures = this.state.selection.selectedFeatures ?? [];
return PrintManager.getPrintDatasourceFromSelectedFeatures(selectedFeatures, extent, this.i18nManager);
}
/**
* Get the print formats based on the configuration.
* Removes formats not proposed in the available formats.
* @static
*/
static filterValidPrintFormats(configFormats, availableFormats) {
configFormats = configFormats ?? [];
return configFormats.filter((format) => {
if (availableFormats?.includes(format)) {
return true;
}
console.warn(`Format ${format} is not supported.`);
return false;
});
}
/**
* @returns a valid default format from an array of print formats.
* @static
*/
static getValidDefaultFormat(printFormats, defaultFormat) {
if (defaultFormat) {
if (printFormats.includes(defaultFormat)) {
return defaultFormat;
}
console.warn('Configured format does not exist: ', defaultFormat);
}
return printFormats.length ? printFormats[0] : undefined;
}
/**
* Whitelist the availableLayouts with the given layouts, or allows every of them.
* @static
*/
static filterValidLayouts(availableLayouts, layouts) {
if (!layouts || layouts.length <= 0) {
return availableLayouts ?? [];
}
// Alerts user if a configured layout doesn't exist.
layouts.forEach((layoutName) => {
if (!availableLayouts?.find((layout) => layout.name === layoutName)) {
console.warn('Configured layout does not exist: ', layoutName);
}
});
// Filter availableLayouts with the given layouts.
return availableLayouts?.filter((layout) => layouts.includes(layout.name)) ?? [];
}
/**
* Whitelist the availableScales with the given scales, or allows every of them.
* @static
*/
static filterValidScales(availableScales, scales) {
if (!scales || scales.length <= 0) {
return availableScales;
}
scales.forEach((scale) => {
if (availableScales.find((availableScale) => availableScale === scale)) {
console.warn('Configured scale does not exist: ', scale);
}
});
// Filter availableScales with the given scales.
return availableScales?.filter((scale) => scales.includes(scale));
}
}
export default PrintComponent;