• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

geosolutions-it / MapStore2 / 12882591459

21 Jan 2025 08:07AM UTC coverage: 77.203% (+0.07%) from 77.13%
12882591459

Pull #10712

github

web-flow
Merge e1da172c8 into d3d0ee6c5
Pull Request #10712: Enhancing User Session #10657

30454 of 47261 branches covered (64.44%)

145 of 185 new or added lines in 15 files covered. (78.38%)

432 existing lines in 29 files now uncovered.

37881 of 49067 relevant lines covered (77.2%)

35.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.0
/web/client/plugins/Print.jsx
1
/*
2
 * Copyright 2016, GeoSolutions Sas.
3
 * All rights reserved.
4
 *
5
 * This source code is licensed under the BSD-style license found in the
6
 * LICENSE file in the root directory of this source tree.
7
 */
8

9
import './print/print.css';
10

11
import head from 'lodash/head';
12
import castArray from "lodash/castArray";
13
import isNil from "lodash/isNil";
14
import assign from 'object-assign';
15
import PropTypes from 'prop-types';
16
import React from 'react';
17
import { PanelGroup, Col, Glyphicon, Grid, Panel, Row } from 'react-bootstrap';
18
import { connect } from '../utils/PluginsUtils';
19
import { createSelector } from 'reselect';
20

21
import { setControlProperty, toggleControl } from '../actions/controls';
22
import { configurePrintMap, printError, printSubmit, printSubmitting, addPrintParameter } from '../actions/print';
23
import Message from '../components/I18N/Message';
24
import Dialog from '../components/misc/Dialog';
25
import printReducers from '../reducers/print';
26
import printEpics from '../epics/print';
27
import { printSpecificationSelector } from "../selectors/print";
28
import { layersSelector, rawGroupsSelector } from '../selectors/layers';
29
import { currentLocaleSelector } from '../selectors/locale';
30
import { mapSelector, scalesSelector } from '../selectors/map';
31
import { mapTypeSelector } from '../selectors/maptype';
32
import { normalizeSRS, convertDegreesToRadian } from '../utils/CoordinatesUtils';
33
import { getMessageById } from '../utils/LocaleUtils';
34
import { defaultGetZoomForExtent, getResolutions, mapUpdated, dpi2dpu, DEFAULT_SCREEN_DPI, getScales, reprojectZoom } from '../utils/MapUtils';
35
import { getDerivedLayersVisibility, isInsideResolutionsLimits } from '../utils/LayersUtils';
36
import { has, includes } from 'lodash';
37
import {additionalLayersSelector} from "../selectors/additionallayers";
38
import { MapLibraries } from '../utils/MapTypeUtils';
39

40
/**
41
 * Print plugin. This plugin allows to print current map view. **note**: this plugin requires the  **printing module** to work.
42
 * Please look at mapstore documentation about how to add and configure the printing module in your installation.
43
 *
44
 * It also works as a container for other plugins, usable to customize the UI of the parameters dialog.
45
 *
46
 * The UI supports different targets for adding new plugins:
47
 *  - `left-panel` (controls/widgets to be added to the left column, before the accordion)
48
 *  - `left-panel-accordion` (controls/widgets to be added to the left column, as subpanels of the accordion)
49
 *  - `right-panel` (controls/widgets to be added to the right column, before the buttons bar)
50
 *  - `buttons` (controls/widgets to be added to the right column, in the buttons bar)
51
 *  - `preview-panel` (controls/widgets to be added to the printed pdf preview panel)
52
 *
53
 * In addition it is also possibile to use specific targets that override a standard widget, to replace it
54
 * with a custom one. They are (in order, from left to right and top to bottom in the UI):
55
 *  - `name` (`left-panel`, `position`: `1`)
56
 *  - `description` (`left-panel`, `position`: `2`)
57
 *  - `outputFormat` (`left-panel`, `position`: `3`)
58
 *  - `projection` (`left-panel`, `position`: `4`)
59
 *  - `layout` (`left-panel-accordion`, `position`: `1`)
60
 *  - `legend-options` (`left-panel-accordion`, `position`: `2`)
61
 *  - `resolution` (`right-panel`, `position`: `1`)
62
 *  - `map-preview` (`right-panel`, `position`: `2`)
63
 *  - `default-background-ignore` (`right-panel`, `position`: `3`)
64
 *  - `submit` (`buttons`, `position`: `1`)
65
 *  - `print-preview` (`preview-panel`, `position`: `1`)
66
 *
67
 * To remove a widget, you have to include a Null plugin with the desired target.
68
 * You can use the position to sort existing and custom items.
69
 *
70
 * Standard widgets can be configured by providing an options object as a configuration property
71
 * of this (Print) plugin. The options object of a widget is named `<widget_id>Options`
72
 * (e.g. `outputFormatOptions`).
73
 *
74
 * You can customize Print plugin by creating one custom plugin (or more) that modifies the existing
75
 * components with your own ones. You can configure this plugin in `localConfig.json` as usual.
76
 *
77
 * It delegates to a printingService the creation of the final print. The default printingService
78
 * implements a mapfish-print v2 compatible workflow. It is possible to override the printingService to
79
 * use, via a specific property (printingService).
80
 *
81
 * It is also possible to customize the payload of the spec sent to the mapfish-print engine, by
82
 * adding new transformers to the default chain.
83
 *
84
 * Each transformer is a function that can add / replace / remove fragments from the JSON payload.
85
 *
86
 * @class Print
87
 * @memberof plugins
88
 * @static
89
 *
90
 * @prop {boolean} cfg.useFixedScales if true the printing scale is constrained to the nearest scale of the ones configured
91
 * in the config.yml file, if false the current scale is used
92
 * @prop {object} cfg.overrideOptions overrides print options, this will override options created from current state of map
93
 * @prop {boolean} cfg.overrideOptions.geodetic prints in geodetic mode: in geodetic mode scale calculation is more precise on
94
 * printed maps, but the preview is not accurate
95
 * @prop {string} cfg.overrideOptions.outputFilename name of output file
96
 * @prop {object} cfg.mapPreviewOptions options for the map preview tool
97
 * @prop {string[]} cfg.ignoreLayers list of layer types to ignore in preview and when printing, default ["google", "bing"]
98
 * @prop {boolean} cfg.mapPreviewOptions.enableScalebox if true a combobox to select the printing scale is shown over the preview
99
 * this is particularly useful if useFixedScales is also true, to show the real printing scales
100
 * @prop {boolean} cfg.mapPreviewOptions.enableRefresh true by default, if false the preview is not updated if the user pans or zooms the main map
101
 * @prop {object} cfg.outputFormatOptions options for the output formats
102
 * @prop {object[]} cfg.outputFormatOptions.allowedFormats array of allowed formats, e.g. [{"name": "PDF", "value": "pdf"}]
103
 * @prop {object} cfg.projectionOptions options for the projections
104
 * @prop {object[]} cfg.projectionOptions.projections array of available projections, e.g. [{"name": "EPSG:3857", "value": "EPSG:3857"}]
105
 * @prop {object} cfg.overlayLayersOptions options for overlay layers
106
 * @prop {boolean} cfg.overlayLayersOptions.enabled if true a checkbox will be shown to exclude or include overlay layers to the print
107
 *
108
 * @example
109
 * // printing in geodetic mode
110
 * {
111
 *   "name": "Print",
112
 *   "cfg": {
113
 *       "overrideOptions": {
114
 *          "geodetic": true
115
 *       }
116
 *    }
117
 * }
118
 *
119
 * @example
120
 * // Using a list of fixed scales with scale selector
121
 * {
122
 *   "name": "Print",
123
 *   "cfg": {
124
 *       "ignoreLayers": ["google", "bing"],
125
 *       "useFixedScales": true,
126
 *       "mapPreviewOptions": {
127
 *          "enableScalebox": true
128
 *       }
129
 *    }
130
 * }
131
 *
132
 * @example
133
 * // restrict allowed output formats
134
 * {
135
 *   "name": "Print",
136
 *   "cfg": {
137
 *       "outputFormatOptions": {
138
 *          "allowedFormats": [{"name": "PDF", "value": "pdf"}, {"name": "PNG", "value": "png"}]
139
 *       }
140
 *    }
141
 * }
142
 *
143
 * @example
144
 * // enable custom projections for printing
145
 * "projectionDefs": [{
146
 *    "code": "EPSG:23032",
147
 *    "def": "+proj=utm +zone=32 +ellps=intl +towgs84=-87,-98,-121,0,0,0,0 +units=m +no_defs",
148
 *    "extent": [-1206118.71, 4021309.92, 1295389.0, 8051813.28],
149
 *    "worldExtent": [-9.56, 34.88, 31.59, 71.21]
150
 * }]
151
 * ...
152
 * {
153
 *   "name": "Print",
154
 *   "cfg": {
155
 *       "projectionOptions": {
156
 *          "projections": [{"name": "UTM32N", "value": "EPSG:23032"}, {"name": "EPSG:3857", "value": "EPSG:3857"}, {"name": "EPSG:4326", "value": "EPSG:4326"}]
157
 *       }
158
 *    }
159
 * }
160
 *
161
 * @example
162
 * // customize the printing UI via plugin(s)
163
 * import React from "react";
164
 * import {createPlugin} from "../../utils/PluginsUtils";
165
 * import { connect } from "react-redux";
166
 *
167
 * const MyCustomPanel = () => <div>Hello, I am a custom component</div>;
168
 *
169
 * const MyCustomLayout = ({sheet}) => <div>Hello, I am a custom layout, the sheet is {sheet}</div>;
170
 * const MyConnectedCustomLayout = connect((state) => ({sheet: state.print?.spec.sheet}))(MyCustomLayout);
171
 *
172
 * export default createPlugin('PrintCustomizations', {
173
 *     component: () => null,
174
 *     containers: {
175
 *         Print: [
176
 *             // this entry add a panel between title and description
177
 *             {
178
 *                 target: "left-panel",
179
 *                 position: 1.5,
180
 *                 component: MyCustomPanel
181
 *             },
182
 *             // this entry replaces the layout panel
183
 *             {
184
 *                 target: "layout",
185
 *                 component: MyConnectedCustomLayout,
186
 *                 title: "MyLayout"
187
 *             },
188
 *             // To remove one component, simply create a component that returns null.
189
 *             {
190
 *                 target: "map-preview",
191
 *                 component: () => null
192
 *             }
193
 *         ]
194
 *     }
195
 * });
196
 * @example
197
 * // adds a transformer to the printingService chain
198
 * import {addTransformer} from "@js/utils/PrintUtils";
199
 *
200
 * addTransformer("mytranform", (state, spec) => Promise.resolve({
201
 *      ...spec,
202
 *      custom: "some value"
203
 * }));
204
 */
205

206
function overrideItem(item, overrides = []) {
×
207
    const replacement = overrides.find(i => i.target === item.id);
698✔
208
    return replacement ?? item;
698✔
209
}
210

211
const EmptyComponent = () => {
1✔
212
    return null;
×
213
};
214

215
function handleRemoved(item) {
216
    return item.plugin ? item : {
698!
217
        ...item,
218
        plugin: EmptyComponent
219
    };
220
}
221

222
function mergeItems(standard, overrides) {
223
    return standard
234✔
224
        .map(item => overrideItem(item, overrides))
698✔
225
        .map(handleRemoved);
226
}
227

228
function filterLayer(layer = {}) {
×
229
    // Skip layer with error and type cog
230
    return !layer.loadingError && layer.type !== "cog";
33✔
231
}
232

233
export default {
234
    PrintPlugin: assign({
235
        loadPlugin: (resolve) => {
236
            Promise.all([
17✔
237
                import('./print/index'),
238
                import('../utils/PrintUtils')
239
            ]).then(([printMod, utilsMod]) => {
240

241
                const {
242
                    standardItems
243
                } = printMod.default;
17✔
244

245
                const {
246
                    getDefaultPrintingService,
247
                    getLayoutName,
248
                    getPrintScales,
249
                    getNearestZoom
250
                } = utilsMod;
17✔
251
                class Print extends React.Component {
252
                    static propTypes = {
17✔
253
                        map: PropTypes.object,
254
                        layers: PropTypes.array,
255
                        capabilities: PropTypes.object,
256
                        printSpec: PropTypes.object,
257
                        printSpecTemplate: PropTypes.object,
258
                        withContainer: PropTypes.bool,
259
                        withPanelAsContainer: PropTypes.bool,
260
                        open: PropTypes.bool,
261
                        pdfUrl: PropTypes.string,
262
                        title: PropTypes.string,
263
                        style: PropTypes.object,
264
                        mapWidth: PropTypes.number,
265
                        mapType: PropTypes.string,
266
                        alternatives: PropTypes.array,
267
                        toggleControl: PropTypes.func,
268
                        onBeforePrint: PropTypes.func,
269
                        setPage: PropTypes.func,
270
                        onPrint: PropTypes.func,
271
                        printError: PropTypes.func,
272
                        configurePrintMap: PropTypes.func,
273
                        getLayoutName: PropTypes.func,
274
                        error: PropTypes.string,
275
                        getZoomForExtent: PropTypes.func,
276
                        minZoom: PropTypes.number,
277
                        maxZoom: PropTypes.number,
278
                        usePreview: PropTypes.bool,
279
                        mapPreviewOptions: PropTypes.object,
280
                        syncMapPreview: PropTypes.bool,
281
                        useFixedScales: PropTypes.bool,
282
                        scales: PropTypes.array,
283
                        ignoreLayers: PropTypes.array,
284
                        defaultBackground: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
285
                        closeGlyph: PropTypes.string,
286
                        submitConfig: PropTypes.object,
287
                        previewOptions: PropTypes.object,
288
                        currentLocale: PropTypes.string,
289
                        overrideOptions: PropTypes.object,
290
                        items: PropTypes.array,
291
                        addPrintParameter: PropTypes.func,
292
                        printingService: PropTypes.object,
293
                        printMap: PropTypes.object
294
                    };
295

296
                    static contextTypes = {
17✔
297
                        messages: PropTypes.object,
298
                        plugins: PropTypes.object,
299
                        loadedPlugins: PropTypes.object
300
                    };
301

302
                    static defaultProps = {
17✔
303
                        withContainer: true,
304
                        withPanelAsContainer: false,
305
                        title: 'print.paneltitle',
306
                        toggleControl: () => {},
307
                        onBeforePrint: () => {},
308
                        setPage: () => {},
309
                        onPrint: () => {},
310
                        configurePrintMap: () => {},
311
                        printSpecTemplate: {},
312
                        getLayoutName: getLayoutName,
313
                        getZoomForExtent: defaultGetZoomForExtent,
314
                        pdfUrl: null,
315
                        mapWidth: 370,
316
                        mapType: MapLibraries.OPENLAYERS,
317
                        minZoom: 1,
318
                        maxZoom: 23,
319
                        usePreview: true,
320
                        mapPreviewOptions: {
321
                            enableScalebox: false,
322
                            enableRefresh: false
323
                        },
324
                        syncMapPreview: true,
325
                        useFixedScales: false,
326
                        scales: [],
327
                        ignoreLayers: ["google", "bing"],
328
                        defaultBackground: ["osm", "wms", "empty"],
329
                        closeGlyph: "1-close",
330
                        submitConfig: {
331
                            buttonConfig: {
332
                                bsSize: "small",
333
                                bsStyle: "primary"
334
                            },
335
                            glyph: ""
336
                        },
337
                        previewOptions: {
338
                            buttonStyle: "primary"
339
                        },
340
                        style: {},
341
                        currentLocale: 'en-US',
342
                        overrideOptions: {},
343
                        items: [],
344
                        printingService: getDefaultPrintingService(),
345
                        printMap: {}
346
                    };
347

348
                    state = {
17✔
349
                        activeAccordionPanel: 0
350
                    }
351

352
                    UNSAFE_componentWillMount() {
353
                        this.configurePrintMap();
17✔
354
                    }
355

356
                    UNSAFE_componentWillReceiveProps(nextProps) {
357
                        const hasBeenOpened = nextProps.open && !this.props.open;
43✔
358
                        const mapHasChanged = this.props.open && this.props.syncMapPreview && mapUpdated(this.props.map, nextProps.map);
43✔
359
                        const specHasChanged = (
360
                            nextProps.printSpec.defaultBackground !== this.props.printSpec.defaultBackground ||
43✔
361
                                nextProps.printSpec.additionalLayers !== this.props.printSpec.additionalLayers
362
                        );
363
                        if (hasBeenOpened || mapHasChanged || specHasChanged) {
43✔
364
                            this.configurePrintMap(nextProps);
1✔
365
                        }
366
                    }
367

368
                    getAlternativeBackground = (layers, defaultBackground, projection) => {
17✔
369
                        const allowedBackground = head(castArray(defaultBackground).map(type => ({
10✔
370
                            type
371
                        })).filter(l => this.isAllowed(l, projection)));
10✔
372
                        if (allowedBackground) {
5!
373
                            return head(layers.filter(l => l.type === allowedBackground.type));
5✔
374
                        }
375
                        return null;
×
376
                    };
377

378
                    getItems = (target) => {
17✔
379
                        const filtered = this.props.items.filter(i => !target || i.target === target);
234✔
380
                        const merged = mergeItems(standardItems[target], this.props.items)
234✔
381
                            .map(item => ({
698✔
382
                                ...item,
383
                                target
384
                            }));
385
                        return [...merged, ...filtered]
234✔
386
                            .sort((i1, i2) => (i1.position ?? 0) - (i2.position ?? 0));
488✔
387
                    };
388
                    getMapConfiguration = () => {
17✔
389
                        const map = this.props.printingService.getMapConfiguration();
66✔
390
                        return {
66✔
391
                            ...map,
392
                            layers: this.filterLayers(map.layers, this.props.useFixedScales ? map.scaleZoom : map.zoom, map.projection)
66✔
393
                        };
394
                    };
395
                    getMapSize = (layout) => {
17✔
396
                        const currentLayout = layout || this.getLayout();
58!
397
                        return {
58✔
398
                            width: this.props.mapWidth,
399
                            height: currentLayout && currentLayout.map.height / currentLayout.map.width * this.props.mapWidth || 270
116!
400
                        };
401
                    };
402
                    getPreviewResolution = (zoom, projection) => {
17✔
403
                        const dpu = dpi2dpu(DEFAULT_SCREEN_DPI, projection);
66✔
404
                        const roundZoom = Math.round(zoom);
66✔
405
                        const scale = this.props.useFixedScales
66✔
406
                            ? getPrintScales(this.props.capabilities)[roundZoom]
407
                            : this.props.scales[roundZoom];
408
                        return scale / dpu;
66✔
409
                    };
410
                    getLayout = (props) => {
17✔
411
                        const { getLayoutName: getLayoutNameProp, printSpec, capabilities } = props || this.props;
58✔
412
                        const layoutName = getLayoutNameProp(printSpec);
58✔
413
                        return head(capabilities.layouts.filter((l) => l.name === layoutName));
58✔
414
                    };
415

416
                    renderWarning = (layout) => {
17✔
417
                        if (!layout) {
58!
418
                            return <Row><Col xs={12}><div className="print-warning"><span><Message msgId="print.layoutWarning"/></span></div></Col></Row>;
×
419
                        }
420
                        return null;
58✔
421
                    };
422
                    renderItem = (item, opts) => {
17✔
423
                        const {validations, ...options } = opts;
704✔
424
                        const Comp = item.component ?? item.plugin;
704✔
425
                        const {style, ...other} = this.props;
704✔
426
                        const itemOptions = this.props[item.id + "Options"];
704✔
427
                        return <Comp role="body" {...other} {...item.cfg} {...options} {...itemOptions} validation={validations?.[item.id ?? item.name]}/>;
704✔
428
                    };
429
                    renderItems = (target, options) => {
17✔
430
                        return this.getItems(target)
176✔
431
                            .map(item => this.renderItem(item, options));
588✔
432
                    };
433
                    renderAccordion = (target, options) => {
17✔
434
                        const items = this.getItems(target);
58✔
435
                        return (<PanelGroup accordion activeKey={this.state.activeAccordionPanel} onSelect={(key) => {
58✔
436
                            this.setState({
×
437
                                activeAccordionPanel: key
438
                            });
439
                        }}>
440
                            {items.map((item, pos) => (
441
                                <Panel header={getMessageById(this.context.messages, item.cfg?.title ?? item.title ?? "")} eventKey={pos} collapsible>
116!
442
                                    {this.renderItem(item, options)}
443
                                </Panel>
444
                            ))}
445
                        </PanelGroup>);
446
                    };
447
                    renderPrintPanel = () => {
17✔
448
                        const layout = this.getLayout();
58✔
449
                        const map = this.getMapConfiguration();
58✔
450
                        const options = {
58✔
451
                            layout,
452
                            map,
453
                            layoutName: this.props.getLayoutName(this.props.printSpec),
454
                            mapSize: this.getMapSize(layout),
455
                            resolutions: getResolutions(map?.projection),
456
                            onRefresh: () => this.configurePrintMap(),
16✔
457
                            notAllowedLayers: this.isBackgroundIgnored(this.props.layers, map?.projection),
458
                            actionConfig: this.props.submitConfig,
459
                            validations: this.props.printingService.validate(),
460
                            rotation: !isNil(this.props.printSpec.rotation) ? convertDegreesToRadian(Number(this.props.printSpec.rotation)) : 0,
58!
461
                            actions: {
462
                                print: this.print,
463
                                addParameter: this.addParameter
464
                            }
465
                        };
466
                        return (
58✔
467
                            <Grid fluid role="body">
468
                                {this.renderError()}
469
                                {this.renderWarning(layout)}
470
                                <Row>
471
                                    <Col xs={12} md={6}>
472
                                        {this.renderItems("left-panel", options)}
473
                                        {this.renderAccordion("left-panel-accordion", options)}
474
                                    </Col>
475
                                    <Col xs={12} md={6} style={{textAlign: "center"}}>
476
                                        {this.renderItems("right-panel", options)}
477
                                        {this.renderItems("buttons", options)}
478
                                        {this.renderDownload()}
479
                                    </Col>
480
                                </Row>
481
                            </Grid>
482
                        );
483
                    };
484

485
                    renderDownload = () => {
17✔
486
                        if (this.props.pdfUrl && !this.props.usePreview) {
58!
487
                            return <iframe src={this.props.pdfUrl} style={{visibility: "hidden", display: "none"}}/>;
×
488
                        }
489
                        return null;
58✔
490
                    };
491

492
                    renderError = () => {
17✔
493
                        if (this.props.error) {
58✔
494
                            return <Row><Col xs={12}><div className="print-error"><span>{this.props.error}</span></div></Col></Row>;
2✔
495
                        }
496
                        return null;
56✔
497
                    };
498

499
                    renderPreviewPanel = () => {
17✔
500
                        return this.renderItems("preview-panel", this.props.previewOptions);
2✔
501
                    };
502

503
                    renderBody = () => {
17✔
504
                        if (this.props.pdfUrl && this.props.usePreview) {
60✔
505
                            return this.renderPreviewPanel();
2✔
506
                        }
507
                        return this.renderPrintPanel();
58✔
508
                    };
509

510
                    render() {
511
                        if ((this.props.capabilities || this.props.error) && this.props.open) {
60!
512
                            if (this.props.withContainer) {
60!
513
                                if (this.props.withPanelAsContainer) {
60!
514
                                    return (<Panel className="mapstore-print-panel" header={<span><span className="print-panel-title"><Message msgId="print.paneltitle"/></span><span className="print-panel-close panel-close" onClick={this.props.toggleControl}></span></span>} style={this.props.style}>
×
515
                                        {this.renderBody()}
516
                                    </Panel>);
517
                                }
518
                                return (<Dialog start={{x: 0, y: 80}} id="mapstore-print-panel" style={{ zIndex: 1990, ...this.props.style}}>
60✔
519
                                    <span role="header"><span className="print-panel-title"><Message msgId="print.paneltitle"/></span><button onClick={this.props.toggleControl} className="print-panel-close close">{this.props.closeGlyph ? <Glyphicon glyph={this.props.closeGlyph}/> : <span>×</span>}</button></span>
60!
520
                                    {this.renderBody()}
521
                                </Dialog>);
522
                            }
523
                            return this.renderBody();
×
524
                        }
525
                        return null;
×
526
                    }
527
                    addParameter = (name, value) => {
17✔
528
                        this.props.addPrintParameter("params." + name, value);
3✔
529
                    };
530
                    isCompatibleWithSRS = (projection, layer) => {
17✔
531
                        return projection === "EPSG:3857" || includes([
42!
532
                            "wms",
533
                            "wfs",
534
                            "vector",
535
                            "graticule",
536
                            "empty",
537
                            "arcgis"
538
                        ], layer.type) || layer.type === "wmts" && has(layer.allowedSRS, projection);
539
                    };
540
                    isAllowed = (layer, projection) => {
17✔
541
                        return this.props.ignoreLayers.indexOf(layer.type) === -1 &&
45✔
542
                            this.isCompatibleWithSRS(normalizeSRS(projection), layer);
543
                    };
544

545
                    isBackgroundIgnored = (layers, projection) => {
17✔
546
                        const background = head((layers || this.props.layers)
124!
547
                            .filter(layer => layer.group === "background" && layer.visibility && this.isAllowed(layer, projection)));
73!
548
                        return !background;
124✔
549
                    };
550
                    filterLayers = (layers, zoom, projection) => {
17✔
551
                        const resolution = this.getPreviewResolution(zoom, projection);
66✔
552

553
                        const filtered = layers.filter((layer) =>
66✔
554
                            layer.visibility &&
40✔
555
                            isInsideResolutionsLimits(layer, resolution) &&
556
                            this.isAllowed(layer, projection)
557
                        );
558
                        if (this.isBackgroundIgnored(layers, projection) && this.props.defaultBackground && this.props.printSpec.defaultBackground) {
66✔
559
                            const defaultBackground = this.getAlternativeBackground(layers, this.props.defaultBackground);
5✔
560
                            if (defaultBackground) {
5!
561
                                return [{
×
562
                                    ...defaultBackground,
563
                                    visibility: true
564
                                }, ...filtered];
565
                            }
566
                            return filtered;
5✔
567
                        }
568
                        return filtered;
61✔
569
                    };
570

571
                    configurePrintMap = (props) => {
17✔
572
                        const {
573
                            map: newMap,
574
                            capabilities,
575
                            configurePrintMap: configurePrintMapProp,
576
                            useFixedScales,
577
                            currentLocale,
578
                            layers,
579
                            printMap,
580
                            printSpec
581
                        } = props || this.props;
34✔
582
                        if (newMap && newMap.bbox && capabilities) {
34!
583
                            const selectedPrintProjection = (printSpec && printSpec?.params?.projection) || (printSpec && printSpec?.projection) || (printMap && printMap.projection) || 'EPSG:3857';
34!
584
                            const printSrs = normalizeSRS(selectedPrintProjection);
34✔
585
                            const mapProjection = newMap.projection;
34✔
586
                            const mapSrs = normalizeSRS(mapProjection);
34✔
587
                            const zoom = reprojectZoom(newMap.zoom, mapSrs, printSrs);
34✔
588
                            const scales = getPrintScales(capabilities);
34✔
589
                            const printMapScales = getScales(printSrs);
34✔
590
                            const scaleZoom = getNearestZoom(zoom, scales, printMapScales);
34✔
591
                            if (useFixedScales) {
34✔
592
                                const scale = scales[scaleZoom];
8✔
593
                                configurePrintMapProp(newMap.center, zoom, scaleZoom, scale,
8✔
594
                                    layers, newMap.projection, currentLocale, useFixedScales);
595
                            } else {
596
                                const scale = printMapScales[zoom];
26✔
597
                                configurePrintMapProp(newMap.center, zoom, scaleZoom, scale,
26✔
598
                                    layers, newMap.projection, currentLocale, useFixedScales);
599
                            }
600
                        }
601
                    };
602

603
                    print = () => {
17✔
604
                        this.props.setPage(0);
8✔
605
                        this.props.onBeforePrint();
8✔
606
                        this.props.printingService.print({
8✔
607
                            layers: this.getMapConfiguration()?.layers,
608
                            scales: this.props.useFixedScales ? getPrintScales(this.props.capabilities) : undefined,
8✔
609
                            bbox: this.props.map?.bbox
610
                        })
611
                            .then((spec) =>
612
                                this.props.onPrint(this.props.capabilities.createURL, { ...spec, ...this.props.overrideOptions })
6✔
613
                            )
614
                            .catch(e => {
UNCOV
615
                                this.props.printError("Error in printing:" + e.message);
×
616
                            });
617
                    };
618
                }
619

620
                const selector = createSelector([
17✔
621
                    (state) => state.controls.print && state.controls.print.enabled || state.controls.toolbar && state.controls.toolbar.active === 'print',
60!
622
                    (state) => state.print && state.print.capabilities,
60✔
623
                    printSpecificationSelector,
624
                    (state) => state.print && state.print.pdfUrl,
60✔
625
                    (state) => state.print && state.print.error,
60✔
626
                    mapSelector,
627
                    layersSelector,
628
                    additionalLayersSelector,
629
                    scalesSelector,
630
                    (state) => state.browser && (!state.browser.ie || state.browser.ie11),
60!
631
                    currentLocaleSelector,
632
                    mapTypeSelector,
633
                    (state) => state.print.map,
60✔
634
                    rawGroupsSelector
635
                ], (open, capabilities, printSpec, pdfUrl, error, map, layers, additionalLayers, scales, usePreview, currentLocale, mapType, printMap, groups) => ({
60✔
636
                    open,
637
                    capabilities,
638
                    printSpec,
639
                    pdfUrl,
640
                    error,
641
                    map,
642
                    layers: [
643
                        ...getDerivedLayersVisibility(layers, groups).filter(filterLayer),
UNCOV
644
                        ...(printSpec?.additionalLayers ? additionalLayers.map(l => l.options).filter(
×
645
                            l => {
646
                                const isVector = l.type === 'vector';
×
647
                                const hasFeatures = Array.isArray(l.features) && l.features.length > 0;
×
UNCOV
648
                                return !l.loadingError && (!isVector || (isVector && hasFeatures));
×
649
                            }
650
                        ) : [])
651
                    ],
652
                    scales,
653
                    usePreview,
654
                    currentLocale,
655
                    mapType,
656
                    printMap
657
                }));
658

659
                const PrintPlugin = connect(selector, {
17✔
660
                    toggleControl: toggleControl.bind(null, 'print', null),
661
                    onPrint: printSubmit,
662
                    printError: printError,
663
                    onBeforePrint: printSubmitting,
664
                    setPage: setControlProperty.bind(null, 'print', 'currentPage'),
665
                    configurePrintMap,
666
                    addPrintParameter
667
                })(Print);
668
                resolve(PrintPlugin);
17✔
669
            });
670
        },
UNCOV
671
        enabler: (state) => state.print && state.print.enabled || state.toolbar && state.toolbar.active === 'print'
×
672
    },
673
    {
674
        disablePluginIf: "{state('mapType') === 'cesium' || !state('printEnabled')}",
675
        Toolbar: {
676
            name: 'print',
677
            position: 7,
678
            help: <Message msgId="helptexts.print"/>,
679
            tooltip: "printbutton",
680
            icon: <Glyphicon glyph="print"/>,
681
            exclusive: true,
682
            panel: true,
683
            priority: 1
684
        },
685
        BurgerMenu: {
686
            name: 'print',
687
            position: 2,
688
            tooltip: "printToolTip",
689
            text: <Message msgId="printbutton"/>,
690
            icon: <Glyphicon glyph="print"/>,
691
            action: toggleControl.bind(null, 'print', null),
692
            priority: 3,
693
            doNotHide: true
694
        },
695
        SidebarMenu: {
696
            name: "print",
697
            position: 3,
698
            tooltip: "printbutton",
699
            text: <Message msgId="printbutton"/>,
700
            icon: <Glyphicon glyph="print"/>,
701
            action: toggleControl.bind(null, 'print', null),
702
            doNotHide: true,
703
            toggle: true,
704
            priority: 2
705
        }
706
    }),
707
    reducers: {print: printReducers},
708
    epics: {...printEpics}
709
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc