@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
751 lines (750 loc) • 41 kB
JavaScript
import { html as uHtml } from 'uhtml';
import PrintManager from './tools/PrintManager.js';
import PrintMaskManager from './tools/printMaskManager.js';
import { toDegrees, toRadians } from 'ol/math.js';
import { unByKeyAll } from '../../tools/utils/olutils.js';
import { padNumber } from 'ol/string.js';
import GirafeHTMLElement from '../../base/GirafeHTMLElement.js';
import Layer from '../../models/layers/layer.js';
/** 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 {
templateUrl = null;
styleUrls = null;
template = () => {
return uHtml `<style>
.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,a:visited{color:var(--link-color)} spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}} spin-wait{0%{transform:rotate(0)}7%{transform:rotate(360deg)}to{transform:rotate(360deg)}}.gg-spin{animation-name:spin;animation-duration:2s;animation-timing-function:linear;animation-iteration-count:infinite}.gg-spin-wait{animation-name:spin-wait;animation-duration:10s;animation-timing-function:linear;animation-iteration-count:infinite}::-webkit-scrollbar{width:5px}::-webkit-scrollbar-thumb{background:#999}button,input,select,textarea{font:inherit}.gg-button,.gg-select,.gg-input,.gg-textarea{background-color:var(--bkg-color);color:var(--text-color);border:var(--app-standard-border);box-sizing:border-box;cursor:pointer;border-radius:3px;outline:0;margin:0;padding:0 0 0 .5rem;display:inline-block}.gg-label{background-color:var(--bkg-color);color:var(--text-color);border:none;align-items:center;margin:0;padding:0;display:flex}.gg-button,.gg-select,.gg-input,.gg-label{min-height:calc(var(--app-standard-height) / 1.5)}.gg-textarea{max-height:initial;resize:vertical;height:6rem;padding:.5rem;line-height:1.3rem}.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-grad1);background-color:var(--bkg-color-grad2)}.gg-button:disabled{background-color:var(--bkg-color-grad1);color:var(--text-color-grad2);cursor:not-allowed;border:none}.gg-button:disabled img{filter:opacity(.6)}.gg-input:disabled,.gg-select:disabled,.gg-textarea:disabled{background-color:var(--bkg-color-grad1);color:var(--text-color-grad2);cursor:not-allowed}.gg-button>img{vertical-align:middle}.gg-icon-button{color:var(--text-color);cursor:pointer;background-color:#0000;border:none;flex-direction:column;justify-content:center;align-items:center;padding:0;display:flex}.gg-icon{justify-content:center;align-items:center;display:flex}.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{width:calc(var(--app-standard-height) - 1.5rem);margin:0}.gg-big-withtext span{font-variant:small-caps;padding:0 1rem;font-size:.9rem}.gg-medium,.gg-medium-withtext{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);flex-direction:row}.gg-medium img{width:calc(var(--app-standard-height) / 2.4);margin:0}.gg-medium-withtext img{width:calc(var(--app-standard-height) / 2.4);margin-left:.5rem}.gg-medium-withtext span{padding:0 1rem 0 .5rem;font-size:.9rem}.gg-small,.gg-small-withtext{min-width:calc(var(--app-standard-height) / 2);min-height:calc(var(--app-standard-height) / 2);max-height:calc(var(--app-standard-height) / 2);flex-direction:row}.gg-small img{width:calc(var(--app-standard-height) / 3);margin:0}.gg-small-withtext img{width:calc(var(--app-standard-height) / 3);margin-left:.5rem}.gg-small-withtext span{padding:0 .5rem 0 .3rem;font-size:.9rem}.gg-button:hover:not(:disabled),.gg-select:hover:not(:disabled),.gg-input:hover:not(:disabled),.gg-textarea:hover:not(:disabled),.gg-icon-button:hover:not(:disabled){background-color:var(--bkg-color-grad1)}.gg-opacity{opacity:.5}.gg-opacity:hover{opacity:1;background-color:#0000}.gg-tabs{cursor:pointer;grid-auto-flow:column;padding-bottom:1rem;font-size:1rem;display:grid}.gg-tab{border:none;border-bottom:var(--app-standard-border);cursor:pointer;color:var(--text-color);background:0 0;padding:.5rem}.gg-tab.active{border-bottom:solid 1px var(--text-color)}.girafe-button-big,.girafe-button-large,.girafe-button-small,.girafe-button-tiny{color:var(--text-color);background-color:#0000;border:none;flex-direction:column;display:flex}.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()}.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{height:2rem;margin:.3rem}.girafe-button-large span{height:2rem;margin:.3rem;line-height:2rem}.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{text-align:left;text-overflow:ellipsis;width:100%;overflow:hidden}.girafe-button-tiny{align-items:center;width:1rem;height:1rem;padding:0}.girafe-button-tiny img{overflow:hidden}.girafe-onboarding-theme{background-color:var(--bkg-color)!important;color:var(--text-color)!important}.girafe-onboarding-theme button{background-color:var(--bkg-color)!important;color:var(--text-color)!important;text-shadow:none!important}.girafe-onboarding-theme button.driver-popover-close-btn{z-index:10000}.tippy-box{background-color:var(--bkg-color)!important;border:var(--app-standard-border)!important}.tippy-content{color:var(--text-color)!important}.tippy-arrow{color:var(--bkg-color)!important}.tippy-box[data-theme~=error]{background-color:var(--error-color);white-space:pre-line}div.tippy-box[data-theme=image-popup]{border:var(--app-standard-border)!important;& div.tippy-content{background-color:var(--bkg-color)!important;& img{max-width:20rem;max-height:20rem}}& div.tippy-arrow{color:var(--bkg-color)!important}}
</style><style>
#panel{min-width:20rem;height:100%;overflow:auto}#content{background:var(--bkg-color);color:var(--text-color);margin:0;padding:1.5rem}#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;gap:.5rem;display:flex}#rotationSlider{width:0}#rotationNumber{flex-grow:0;width:4rem}#content #export-pdf{float:right;margin-top:1rem}#content button{background-color:var(--bkg-color);color:var(--text-color);border:solid 1px var(--text-color);cursor:pointer;border-radius:3px;outline:0}#content button:hover{background-color:var(--bkg-color-grad2)}#content #print-list{margin-top:5rem}#print-list .print-item{border:solid 1px var(--text-color);color:var(--text-color);margin-top:.5rem;padding:.5rem;position:relative}#print-list .print-item .container{text-align:unset;border:none;width:100%;display:inline}#print-list .print-item .cancel{cursor:pointer;color:var(--text-color-grad1);background-color:#0000;border:none;position:absolute;top:.5rem;right:.5rem}.print-item .cancel i:before{content:"uf00d"}.print-item .cancel:hover{border-color:var(--text-color);color:var(--text-color)}.print-item i.status{float:left;text-align:center;width:3rem;margin-right:1rem}.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{margin-right:.5rem;position:absolute;bottom:0;right:0}#custom-scale{color:var(--text-color);flex-flow:wrap;justify-content:flex-start;align-items:center;display:flex}#custom-scale .svg-info{margin-left:.5rem}#custom-scale>div{align-items:center;width:100%;display:flex}.gg-custom-scale{justify-content:flex-end}.warning{border-top:1px solid #333;border-bottom:1px solid #333;margin-top:1rem;margin-bottom:1rem;padding:.5rem}.warning h3{margin:0 0 1rem;font-size:1rem}.warning span{display:block}
</style>
<style>${this.customStyle}</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.context.configManager.Config.print?.customScale === true ? '' : 'hidden'}" value="custom">Manual entry</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"><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>${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>${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"><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}" value="${this.getCapabilitiesAttribute(attrName)?.default}"></div>`; })}<div class="${this.hasRestrictedLayers ? 'warning' : 'hidden'}"><h3 i18n="Warning: Private Layers are active">Warning: Private Layers are active</h3><span i18n="Private layers are enabled and will be printed."></span> <span i18n="The generated document may contain sensitive data."></span> <span i18n="Please review or disable them before printing."></span></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 class="time">${printItem.time}</button></div>`)}</div></div></div></div>
${this.htmlUnsafe(this.feedbackTemplateHtml ?? '')}`;
};
isPanelVisible = false;
panelTitle = 'print-panel';
panelTogglePath = 'interface.printPanelVisible';
default_dpi = 96;
default_scale = 10000;
default_resolution = 100;
default_format = 'pdf';
eventsCallbacks = [];
eventKeys = [];
printManager;
printList = [];
printUrl;
capabilities;
configAttributeNames = [];
printMaskManager;
isWithCapabilitiesComponentSetup = false;
hasErrorFetchingCapabilities = false;
showCustomScale = false;
attributeNames = [];
printFormats = [];
layouts = [];
selectedLayout;
scales = [];
dpis = [];
hasRestrictedLayers = false;
constructor() {
super('print');
}
connectedCallback() {
super.connectedCallback();
this.render();
}
/**
* Render the component regarding its visibility.
* Fetch the print capabilities at first rendering, then render the print mask too and register to events.
*/
render() {
if (this.isPanelVisible) {
this.renderComponent();
}
else {
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 the selected scale in the state and update the mask.
*/
onScaleChanged(event) {
if (this.context.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);
}
/**
* On pressing enter take the value from the event target (input)
* and set the selected scale in the state and update the mask.
*/
onCustomScaleTyped(evt) {
const value = parseInt(evt.target?.value);
if (evt.key !== 'Enter' || !value) {
return;
}
this.state.print.scale = value;
this.printMaskManager?.zoomToScale(this.state.print.scale);
this.render();
}
/**
* @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.context.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.context.mapManager,
i18nManager: this.context.i18nManager,
state: this.state,
scale: this.getSelectedScale() ?? this.default_scale,
printResolution: this.context.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.context.mapManager.getMap(), this.context.stateManager);
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();
}
}
/**
* 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.context.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();
}
}));
this.eventsCallbacks.push(this.subscribe(/layers\.layersList\..*\.activeState/, () => {
this.verifyRestrictedLayers();
this.render();
}));
}
verifyRestrictedLayers() {
const allLayers = this.context.layerManager.getFlattenedLayerTree(this.state.layers.layersList);
this.hasRestrictedLayers = allLayers.find((l) => l instanceof Layer && l.active && l.restricted) !== undefined;
}
/**
* Set the visibility of the panel.
* @private
*/
togglePanel(visible) {
this.isPanelVisible = visible;
this.verifyRestrictedLayers();
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.context.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.fetchCapabilities();
this.initFromCapabilities();
if (!this.capabilities) {
this.hasErrorFetchingCapabilities = true;
}
}
/**
* @returns the fetched print capabilities or undefined in case of error.
* @private
/*/
async fetchCapabilities() {
const printUrl = this.context.configManager.Config.print?.url;
if (printUrl) {
this.printUrl = printUrl.endsWith('/') ? printUrl.slice(0, -1) : printUrl;
}
let capabilities = undefined;
try {
const fetchOptions = { referrer: '' };
if (this.context.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.context.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.context.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.context.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.context.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();
}
if (this.hasRestrictedLayers) {
let comment = '';
if (customAttributes['comments']) {
comment = customAttributes['comments'];
}
comment += `\n${this.context.i18nManager.getTranslation('Warning: This document may contain sensitive data.')}`;
customAttributes['comments'] = comment;
}
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.context.mapManager,
i18nManager: this.context.i18nManager,
state: this.state,
scale: this.getSelectedScale() ?? this.default_scale,
printResolution: this.context.mapManager.getMap().getView().getResolution() ?? this.default_resolution,
pageSize: this.state.print.pageSize ?? [],
dpi: this.getSelectedDpi() ?? this.default_dpi
},
...this.context.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.context.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.context.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;