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

geosolutions-it / MapStore2 / 13456178088

21 Feb 2025 11:49AM UTC coverage: 76.734% (+0.05%) from 76.688%
13456178088

Pull #10813

github

web-flow
Merge 7ffa6d126 into 1e493c5d2
Pull Request #10813: Fix #10805 JAXBException while updating an existing dashboard

31263 of 48901 branches covered (63.93%)

5 of 8 new or added lines in 2 files covered. (62.5%)

318 existing lines in 24 files now uncovered.

38808 of 50575 relevant lines covered (76.73%)

34.46 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 {string[]} cfg.excludeLayersFromLegend list of layer names e.g. ["workspace:layerName"] to exclude from printed document
105
 * @prop {object[]} cfg.projectionOptions.projections array of available projections, e.g. [{"name": "EPSG:3857", "value": "EPSG:3857"}]
106
 * @prop {object} cfg.overlayLayersOptions options for overlay layers
107
 * @prop {boolean} cfg.overlayLayersOptions.enabled if true a checkbox will be shown to exclude or include overlay layers to the print
108
 *
109
 * @example
110
 * // printing in geodetic mode
111
 * {
112
 *   "name": "Print",
113
 *   "cfg": {
114
 *       "overrideOptions": {
115
 *          "geodetic": true
116
 *       }
117
 *    }
118
 * }
119
 *
120
 * @example
121
 * // Using a list of fixed scales with scale selector
122
 * {
123
 *   "name": "Print",
124
 *   "cfg": {
125
 *       "ignoreLayers": ["google", "bing"],
126
 *       "useFixedScales": true,
127
 *       "mapPreviewOptions": {
128
 *          "enableScalebox": true
129
 *       }
130
 *    }
131
 * }
132
 *
133
 * @example
134
 * // restrict allowed output formats
135
 * {
136
 *   "name": "Print",
137
 *   "cfg": {
138
 *       "outputFormatOptions": {
139
 *          "allowedFormats": [{"name": "PDF", "value": "pdf"}, {"name": "PNG", "value": "png"}]
140
 *       }
141
 *    }
142
 * }
143
 *
144
 * @example
145
 * // enable custom projections for printing
146
 * "projectionDefs": [{
147
 *    "code": "EPSG:23032",
148
 *    "def": "+proj=utm +zone=32 +ellps=intl +towgs84=-87,-98,-121,0,0,0,0 +units=m +no_defs",
149
 *    "extent": [-1206118.71, 4021309.92, 1295389.0, 8051813.28],
150
 *    "worldExtent": [-9.56, 34.88, 31.59, 71.21]
151
 * }]
152
 * ...
153
 * {
154
 *   "name": "Print",
155
 *   "cfg": {
156
 *       "projectionOptions": {
157
 *          "projections": [{"name": "UTM32N", "value": "EPSG:23032"}, {"name": "EPSG:3857", "value": "EPSG:3857"}, {"name": "EPSG:4326", "value": "EPSG:4326"}]
158
 *       }
159
 *    }
160
 * }
161
 *
162
 * @example
163
 * // customize the printing UI via plugin(s)
164
 * import React from "react";
165
 * import {createPlugin} from "../../utils/PluginsUtils";
166
 * import { connect } from "react-redux";
167
 *
168
 * const MyCustomPanel = () => <div>Hello, I am a custom component</div>;
169
 *
170
 * const MyCustomLayout = ({sheet}) => <div>Hello, I am a custom layout, the sheet is {sheet}</div>;
171
 * const MyConnectedCustomLayout = connect((state) => ({sheet: state.print?.spec.sheet}))(MyCustomLayout);
172
 *
173
 * export default createPlugin('PrintCustomizations', {
174
 *     component: () => null,
175
 *     containers: {
176
 *         Print: [
177
 *             // this entry add a panel between title and description
178
 *             {
179
 *                 target: "left-panel",
180
 *                 position: 1.5,
181
 *                 component: MyCustomPanel
182
 *             },
183
 *             // this entry replaces the layout panel
184
 *             {
185
 *                 target: "layout",
186
 *                 component: MyConnectedCustomLayout,
187
 *                 title: "MyLayout"
188
 *             },
189
 *             // To remove one component, simply create a component that returns null.
190
 *             {
191
 *                 target: "map-preview",
192
 *                 component: () => null
193
 *             }
194
 *         ]
195
 *     }
196
 * });
197
 * @example
198
 * // adds a transformer to the printingService chain
199
 * import {addTransformer} from "@js/utils/PrintUtils";
200
 *
201
 * addTransformer("mytranform", (state, spec) => Promise.resolve({
202
 *      ...spec,
203
 *      custom: "some value"
204
 * }));
205
 */
206

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

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

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

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

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

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

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

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

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

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

351
                    state = {
17✔
352
                        activeAccordionPanel: 0
353
                    }
354

355
                    UNSAFE_componentWillMount() {
356
                        this.configurePrintMap();
17✔
357
                    }
358

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

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

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

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

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

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

502
                    renderPreviewPanel = () => {
17✔
503
                        return this.renderItems("preview-panel", this.props.previewOptions);
2✔
504
                    };
505

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

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

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

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

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

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

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

663
                const PrintPlugin = connect(selector, {
17✔
664
                    toggleControl: toggleControl.bind(null, 'print', null),
665
                    onPrint: printSubmit,
666
                    printError: printError,
667
                    onBeforePrint: printSubmitting,
668
                    setPage: setControlProperty.bind(null, 'print', 'currentPage'),
669
                    configurePrintMap,
670
                    addPrintParameter
671
                })(Print);
672
                resolve(PrintPlugin);
17✔
673
            });
674
        },
UNCOV
675
        enabler: (state) => state.print && state.print.enabled || state.toolbar && state.toolbar.active === 'print'
×
676
    },
677
    {
678
        disablePluginIf: "{state('mapType') === 'cesium' || !state('printEnabled')}",
679
        Toolbar: {
680
            name: 'print',
681
            position: 7,
682
            help: <Message msgId="helptexts.print"/>,
683
            tooltip: "printbutton",
684
            icon: <Glyphicon glyph="print"/>,
685
            exclusive: true,
686
            panel: true,
687
            priority: 1
688
        },
689
        BurgerMenu: {
690
            name: 'print',
691
            position: 2,
692
            tooltip: "printToolTip",
693
            text: <Message msgId="printbutton"/>,
694
            icon: <Glyphicon glyph="print"/>,
695
            action: toggleControl.bind(null, 'print', null),
696
            priority: 3,
697
            doNotHide: true
698
        },
699
        SidebarMenu: {
700
            name: "print",
701
            position: 3,
702
            tooltip: "printbutton",
703
            text: <Message msgId="printbutton"/>,
704
            icon: <Glyphicon glyph="print"/>,
705
            action: toggleControl.bind(null, 'print', null),
706
            doNotHide: true,
707
            toggle: true,
708
            priority: 2
709
        }
710
    }),
711
    reducers: {print: printReducers},
712
    epics: {...printEpics}
713
};
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