-
-
Notifications
You must be signed in to change notification settings - Fork 628
Expand file tree
/
Copy pathprint-layout.ts
More file actions
2317 lines (2198 loc) · 79.4 KB
/
Copy pathprint-layout.ts
File metadata and controls
2317 lines (2198 loc) · 79.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Print layout composer rendering.
*
* Pure, framework-free drawing helpers that compose a captured map image with
* cartographic furniture (title, legend, scale bar, north arrow, footer) onto a
* 2D canvas at a paper page size. The same {@link drawLayout} function backs
* both the on-screen preview (small canvas) and the high-resolution export
* (PNG / PDF), so the preview is faithful to the output.
*/
import {
drawMarkerPath,
formatRoundNum,
getRoundNum,
scaleDenomination,
type MapScaleUnit,
type MarkerShape,
} from "@geolibre/core";
export type PaperSizeId =
| "a4"
| "a3"
| "letter"
| "legal"
| "tabloid"
| "fullhd"
| "hd"
| "uhd4k"
| "square"
| "custom";
export type Orientation = "portrait" | "landscape";
/** How a size's width/height are expressed: physical millimetres or screen pixels. */
export type SizeUnit = "mm" | "px";
export interface PaperSize {
id: PaperSizeId;
label: string;
/** Width in {@link unit}, in portrait orientation (width ≤ height). */
width: number;
/** Height in {@link unit}, in portrait orientation. */
height: number;
unit: SizeUnit;
/** Grouping used by the size dropdown: physical paper vs digital screen. */
group: "paper" | "screen";
}
/**
* Selectable output sizes. Physical paper formats are expressed in their
* portrait millimetre dimensions; digital/screen presets are expressed in
* pixels, also stored portrait-first so the shared orientation swap applies.
* The "Custom…" entry is a placeholder whose real dimensions come from
* {@link LayoutOptions.customSize}.
*/
export const PAPER_SIZES: PaperSize[] = [
{
id: "a4",
label: "A4 (210 × 297 mm)",
width: 210,
height: 297,
unit: "mm",
group: "paper",
},
{
id: "a3",
label: "A3 (297 × 420 mm)",
width: 297,
height: 420,
unit: "mm",
group: "paper",
},
{
id: "letter",
label: "Letter (8.5 × 11 in)",
width: 215.9,
height: 279.4,
unit: "mm",
group: "paper",
},
{
id: "legal",
label: "Legal (8.5 × 14 in)",
width: 215.9,
height: 355.6,
unit: "mm",
group: "paper",
},
{
id: "tabloid",
label: "Tabloid (11 × 17 in)",
width: 279.4,
height: 431.8,
unit: "mm",
group: "paper",
},
{
id: "fullhd",
label: "Full HD (1920 × 1080 px)",
width: 1080,
height: 1920,
unit: "px",
group: "screen",
},
{
id: "hd",
label: "HD (1280 × 720 px)",
width: 720,
height: 1280,
unit: "px",
group: "screen",
},
{
id: "uhd4k",
label: "4K UHD (3840 × 2160 px)",
width: 2160,
height: 3840,
unit: "px",
group: "screen",
},
{
id: "square",
label: "Square (1080 × 1080 px)",
width: 1080,
height: 1080,
unit: "px",
group: "screen",
},
{
id: "custom",
label: "Custom…",
width: 1280,
height: 720,
unit: "px",
group: "screen",
},
];
export function getPaperSize(id: PaperSizeId): PaperSize {
return PAPER_SIZES.find((p) => p.id === id) ?? PAPER_SIZES[0];
}
/** A page size already resolved for a specific orientation. */
export interface ResolvedPageSize {
width: number;
height: number;
unit: SizeUnit;
}
/** Custom user-defined dimensions, used when {@link LayoutOptions.paperSize} is "custom". */
export interface CustomSize {
width: number;
height: number;
unit: SizeUnit;
}
/** CSS reference pixels per millimetre (96 dpi), used to bridge px ↔ mm sizes. */
const PX_PER_MM_96 = 96 / 25.4;
/**
* Resolve the effective page dimensions for a layout, applying the orientation
* swap to preset sizes. Custom sizes are taken verbatim (the dialog disables the
* orientation control for them) so the numbers the user typed are honoured.
*/
export function resolvePageSize(opts: {
paperSize: PaperSizeId;
orientation: Orientation;
customSize?: CustomSize | null;
}): ResolvedPageSize {
if (opts.paperSize === "custom") {
const c = opts.customSize;
if (c && c.width > 0 && c.height > 0) {
return { width: c.width, height: c.height, unit: c.unit };
}
return { width: 1280, height: 720, unit: "px" };
}
const paper = getPaperSize(opts.paperSize);
return opts.orientation === "landscape"
? { width: paper.height, height: paper.width, unit: paper.unit }
: { width: paper.width, height: paper.height, unit: paper.unit };
}
/** Convert a resolved page size to millimetres (screen px treated as 96 dpi). */
export function pageMm(size: ResolvedPageSize): {
widthMm: number;
heightMm: number;
} {
if (size.unit === "mm") return { widthMm: size.width, heightMm: size.height };
return {
widthMm: size.width / PX_PER_MM_96,
heightMm: size.height / PX_PER_MM_96,
};
}
/**
* Convert a resolved page size to output pixels at the given dpi. Pixel-unit
* sizes are exact (dpi is ignored); millimetre sizes scale by dpi/25.4.
*/
export function pagePx(size: ResolvedPageSize, dpi: number): { width: number; height: number } {
if (size.unit === "px") {
return { width: Math.round(size.width), height: Math.round(size.height) };
}
const pxPerMm = dpi / 25.4;
return {
width: Math.round(size.width * pxPerMm),
height: Math.round(size.height * pxPerMm),
};
}
/**
* A point layer's marker, carried on its legend swatch so the legend can draw
* the actual marker (a built-in shape recolored, or a custom SVG icon) instead
* of a plain color square. Mirrors the map's marker sprite (`prepareMarker` in
* `@geolibre/map`).
*/
export interface LegendMarker {
/** Built-in shape, or `"custom"` for an SVG icon in {@link svg}. */
shape: MarkerShape;
/** Fill color for a built-in shape (ignored for `"custom"`). */
color: string;
/**
* Raw SVG markup or a URL, set only when {@link shape} is `"custom"`. Doubles
* as the lookup key into {@link LayoutOptions.markerIcons}.
*/
svg?: string;
}
/** A single swatch in a legend entry (one color, with an optional label). */
export interface LegendSwatch {
color: string;
label?: string;
/**
* When set, the swatch represents a point marker: the legend draws the marker
* (see {@link LegendMarker}) in place of the {@link color} square, falling
* back to the square if a custom SVG icon has not been preloaded.
*/
marker?: LegendMarker;
/**
* Circle radius in map pixels for a proportional-symbol row. When set, the
* legend draws a filled circle instead of a color square (scaled to fit the
* legend box, keeping ratios across the entry).
*/
size?: number;
}
export interface LegendEntry {
/** Stable identifier of the source layer (used to key user customizations). */
id: string;
name: string;
swatches: LegendSwatch[];
}
/** Corner of the map body a composed panel is anchored to. */
export type BodyCorner = "top-left" | "top-right" | "bottom-left" | "bottom-right";
/**
* Resolved, drawable data for the chart block (GH #1324). Like the colorbar's
* `colors`, everything here is already computed by the dialog (aggregation,
* top-N capping, colors) so this drawing code stays data-only.
*/
export type DataChartData =
| {
kind: "bar";
bars: { label: string; value: number; color: string }[];
/** Largest bar value (>= 0), for scaling. */
maxValue: number;
/** Smallest bar value; negative when sum/mean produce negatives. */
minValue: number;
/**
* Categories dropped past the top-N cap, drawn as a "+N more" note so
* the chart is never silently incomplete (the pie folds its remainder
* into an "(other)" slice instead).
*/
truncated?: number;
}
| {
kind: "pie";
slices: { label: string; value: number; color: string }[];
/** Sum of every slice value (> 0). */
total: number;
}
| {
kind: "line";
/** Finite values plotted against original row order (gaps skipped). */
points: { index: number; value: number }[];
min: number;
max: number;
/** Total row count, so x spans the full feature order. */
length: number;
color: string;
};
export interface LayoutOptions {
title: string;
subtitle: string;
paperSize: PaperSizeId;
orientation: Orientation;
/** Explicit dimensions used when {@link paperSize} is "custom". */
customSize?: CustomSize | null;
showTitle: boolean;
/** Whether the subtitle line is drawn (independent of {@link showTitle}). */
showSubtitle?: boolean;
/** Where the title/subtitle render: above the map (default) or overlaid inside it. */
titlePlacement?: "outside" | "inside";
/** Horizontal alignment of the title/subtitle text. */
titleAlign?: "left" | "center" | "right";
showLegend: boolean;
showScaleBar: boolean;
/**
* Unit system the scale bar labels distances in: `"metric"` (km/m/cm),
* `"imperial"` (mi/ft), or `"nautical"` (nmi). Follows the project's map
* preference so the printed bar matches the on-screen bar. Defaults to
* `"metric"` when omitted.
*/
scaleUnit?: MapScaleUnit;
showNorthArrow: boolean;
/**
* Group the north arrow directly above the scale bar in the lower-right
* corner (the cartographic "navigation duo"). When false they fall back to
* isolated anchors: north arrow top-right, scale bar bottom-right.
*/
navigationGrouped?: boolean;
/**
* Cartographic "title block" (stempel) drawn as a bordered panel in the
* bottom-right corner. When present, the scale bar + north arrow relocate to
* the bottom-left so they never sit under the block. GH #522.
*/
showInfoBlock?: boolean;
/** Map author or organization line of the info block. */
author?: string;
/** Project / reference number line of the info block. */
projectNumber?: string;
/** Coordinate reference system line of the info block (e.g. "EPSG:4326"). */
crs?: string;
/** Revision / version status line of the info block (e.g. "Rev 01"). */
revision?: string;
/**
* Row labels for the info block. Supplied (translated) by the dialog; English
* fallbacks are used when omitted so the framework-free drawing code stays
* i18n-agnostic, like the legend title and north "N".
*/
infoLabels?: {
author?: string;
project?: string;
crs?: string;
scale?: string;
revision?: string;
};
showFooter: boolean;
footerText: string;
/** Draw the production date (right side of the footer row). */
showDate?: boolean;
/** The formatted date string drawn when {@link showDate} is true. */
dateText?: string;
/** Draw the "Created with GeoLibre" attribution (left side of the footer row). */
showAttribution?: boolean;
/** Attribution text; defaults to "Created with GeoLibre" when omitted. */
attributionText?: string;
/** Outer page padding preset: full margins, narrow, or borderless. */
pageMargin?: "normal" | "narrow" | "none";
/** Draw a customizable border around the whole page (useful for PNG export). */
showPageBorder?: boolean;
pageBorderColor?: string;
/** Page border thickness on a 1–10 scale (relative to page size). */
pageBorderWidth?: number;
/**
* Colour of the map frame (the border drawn around the map body). Defaults to
* a neutral grey when omitted. GH #749.
*/
mapBorderColor?: string;
/**
* Map frame thickness on a 0–10 scale (relative to page size); 0 hides the
* frame. Defaults to 1 (the original hairline). GH #749.
*/
mapBorderWidth?: number;
/**
* Fill colour drawn behind the map image. Shows through wherever the capture
* is transparent (most visibly the area around the sphere in globe
* projection). Defaults to a light grey.
*/
mapBackground?: string;
/**
* An optional colorbar composed in the Print Layout (independent of any on-map
* colorbar control), drawn crisply at export resolution at the chosen corner.
* `colors` are the gradient stops (low value first), resolved from a named
* ramp by the dialog so this drawing code stays data-only.
*/
colorbar?: {
colors: readonly string[];
min: number;
max: number;
label?: string;
orientation: "horizontal" | "vertical";
position: "top-left" | "top-right" | "bottom-left" | "bottom-right";
/** Bar length as a percentage of the body's width (horizontal) or height
* (vertical). Defaults to 34. */
lengthPct?: number;
} | null;
/**
* A user-defined legend composed in the Print Layout (independent of the
* layer-derived {@link legend}), drawn as a bordered panel at the chosen
* corner -- the equivalent of a Controls -> Legend control, but native to the
* layout so it stays crisp.
*/
customLegend?: {
title?: string;
entries: { label: string; color: string }[];
position: "top-left" | "top-right" | "bottom-left" | "bottom-right";
} | null;
/**
* An attribute-table block composed in the Print Layout (GH #1324): rows of a
* vector layer's attributes drawn as a bordered panel at the chosen corner.
* Cell text is already resolved to display strings (and, for an atlas page,
* already filtered to the page extent) by the dialog, so this drawing code
* stays data-only.
*/
dataTable?: {
title?: string;
/** Column headers, in display order. */
columns: string[];
/** Row cells as display strings, aligned with {@link columns}. */
rows: string[][];
/**
* How many source rows the dialog's row limit already dropped. Rows the
* renderer additionally hides to fit the body height are added to this
* count in a "+N more" note under the table.
*/
truncated?: number;
/**
* Translated formatter for the note (e.g. `(n) => t("moreRows", {count:
* n})`). A function rather than preformatted text because the final count
* depends on the canvas geometry; falls back to English "+N more" when
* omitted, like the drawing code's other i18n fallbacks.
*/
formatNote?: (count: number) => string;
position: BodyCorner;
} | null;
/**
* A chart block composed in the Print Layout (GH #1324): a bar, pie, or line
* chart of a vector layer's attributes, drawn crisply at export resolution
* at the chosen corner.
*/
dataChart?: {
title?: string;
position: BodyCorner;
data: DataChartData;
/**
* Translated formatter for the bar chart's "+N more" truncation note;
* falls back to English when omitted (like the table's formatter).
*/
formatNote?: (count: number) => string;
} | null;
legend: LegendEntry[];
/** Heading drawn above the legend entries. */
legendTitle: string;
/**
* When true, multi-class entries show a per-layer heading above their
* classes; when false, classes are listed flat without the layer heading.
*/
legendGroupByLayer: boolean;
/**
* Translated formatter for the legend's "+N more" note, drawn when the class
* rows do not fit the map body; falls back to English when omitted (like the
* table's and chart's formatters).
*/
legendFormatNote?: (count: number) => string;
/**
* Preloaded custom-SVG marker icons for legend swatches, keyed by the
* swatch marker's `svg` string ({@link LegendMarker.svg}). Loading SVGs is
* async, but {@link drawLayout} is synchronous, so the caller resolves them
* up front (like {@link mapImage}) and passes them here; a marker whose icon
* is missing falls back to a plain color square.
*/
markerIcons?: ReadonlyMap<string, CanvasImageSource>;
/** Ground metres per source-image pixel at the map centre. */
metersPerPixel: number;
/** Device pixels per CSS pixel in the captured map image. */
mapPixelRatio?: number;
/** Map bearing in degrees clockwise from north. */
bearingDeg: number;
/** The captured map image (already composited). */
mapImage: CanvasImageSource | null;
/** Intrinsic width of {@link mapImage} in pixels. */
mapImageWidth: number;
/** Intrinsic height of {@link mapImage} in pixels. */
mapImageHeight: number;
/**
* How the captured map fills the body. "cover" (default) scales to fill and
* crops the overflow; "contain" fits the whole image inside the body without
* cropping, leaving {@link mapBackground} margins on the shorter axis. Used so
* an active graticule's edge labels are not trimmed by the cover crop.
*/
mapFit?: "cover" | "contain";
}
const PAGE_BACKGROUND = "#ffffff";
const INK = "#111827";
const MUTED = "#6b7280";
const BORDER = "#9ca3af";
/** Resolved presence of the optional title/footer content, shared by the body
* geometry computation and the drawing pass so they never disagree. */
interface ContentFlags {
showSubtitle: boolean;
hasTitleText: boolean;
hasSubtitleText: boolean;
hasTitleBlock: boolean;
titleInside: boolean;
attributionText: string | false;
footerText: string | false;
dateText: string | false;
hasFooterRow: boolean;
}
function resolveContentFlags(opts: LayoutOptions): ContentFlags {
const titleInside = opts.titlePlacement === "inside";
const showSubtitle = opts.showSubtitle ?? true;
const hasTitleText = opts.showTitle && opts.title.trim().length > 0;
const hasSubtitleText = showSubtitle && opts.subtitle.trim().length > 0;
// Attribution is opt-out (on unless explicitly disabled), deliberately unlike
// the other new booleans: GH #526 wants a pre-checked "Created with GeoLibre"
// credit so it survives a user replacing the footer text.
const attributionText =
opts.showAttribution !== false && (opts.attributionText ?? "Created with GeoLibre").trim();
const footerText = opts.showFooter && opts.footerText.trim();
const dateText = (opts.showDate && (opts.dateText ?? "").trim()) || false;
return {
showSubtitle,
hasTitleText,
hasSubtitleText,
hasTitleBlock: hasTitleText || hasSubtitleText,
titleInside,
attributionText,
footerText,
dateText,
hasFooterRow: Boolean(attributionText || footerText || dateText),
};
}
/** Geometry of the map body and the furniture scale unit for a given page. */
interface BodyRect {
unit: number;
margin: number;
bodyX: number;
bodyY: number;
bodyW: number;
bodyH: number;
}
/**
* Compute the map body rectangle for a page of {@link W}×{@link H} pixels,
* reserving room for an outside title block (top) and the footer row (bottom).
* Shared by {@link drawLayout} and {@link computeScaleRatio} so the preview, the
* export, and the reported 1:N scale are all derived from the same geometry.
*/
function computeBodyRect(opts: LayoutOptions, W: number, H: number): BodyRect {
const unit = Math.min(W, H) / 100;
const marginScale = opts.pageMargin === "none" ? 0 : opts.pageMargin === "narrow" ? 0.5 : 1;
const margin = unit * 5 * marginScale;
const f = resolveContentFlags(opts);
let bodyTop = margin;
if (f.hasTitleBlock && !f.titleInside) {
const titleSize = unit * 4.5;
const subtitleSize = unit * 2.4;
let y = margin + titleSize;
if (f.hasSubtitleText) y += subtitleSize * 1.4;
bodyTop = y + unit * 3;
}
let bodyBottom = H - margin;
if (f.hasFooterRow) {
const footSize = unit * 2.2;
bodyBottom = H - margin - footSize * 1.8;
}
bodyTop = Math.min(bodyTop, bodyBottom - unit * 10);
return {
unit,
margin,
bodyX: margin,
bodyY: bodyTop,
bodyW: W - margin * 2,
bodyH: Math.max(unit * 10, bodyBottom - bodyTop),
};
}
/**
* Aspect ratio of the map frame after page margins, outside titles, and the
* footer row reserve their space. Atlas camera fitting uses this ratio so the
* feature remains visible after the captured live map is cover-cropped into
* the print frame.
*/
export function mapBodyAspectRatio(opts: LayoutOptions): number {
const page = resolvePageSize(opts);
const rect = computeBodyRect(opts, page.width, page.height);
const ratio = rect.bodyW / rect.bodyH;
return Number.isFinite(ratio) && ratio > 0 ? ratio : page.width / page.height;
}
/**
* Cover-scale of a captured map image into the body rectangle: the factor that
* fills the body (cropping overflow), matching the draw in {@link drawLayout}.
*/
function coverScaleFor(
bodyW: number,
bodyH: number,
imgW: number,
imgH: number,
fit: "cover" | "contain" = "cover",
): number {
if (imgW <= 0 || imgH <= 0) return 1;
// "cover" scales to the larger ratio (fills, crops overflow); "contain" scales
// to the smaller ratio (fits entirely, no crop).
return fit === "contain"
? Math.min(bodyW / imgW, bodyH / imgH)
: Math.max(bodyW / imgW, bodyH / imgH);
}
/**
* The representative fraction (the N in "1:N") the layout currently renders at:
* how many ground millimetres each paper millimetre spans. Returns 0 when the
* scale is not meaningful (a pixel/screen size, or no captured map), so callers
* can hide the scale control.
*
* The value is independent of the resolution the page is rasterized at (the
* body and cover scale grow together with the canvas), so a nominal reference
* canvas is used here.
*/
export function computeScaleRatio(opts: LayoutOptions): number {
const page = resolvePageSize(opts);
if (page.unit !== "mm") return 0;
if (
!opts.mapImage ||
opts.mapImageWidth <= 0 ||
opts.mapImageHeight <= 0 ||
!(opts.metersPerPixel > 0) ||
!Number.isFinite(opts.metersPerPixel)
) {
return 0;
}
const aspect = page.width / page.height;
const refLong = 1000;
const W = aspect >= 1 ? refLong : refLong * aspect;
const H = aspect >= 1 ? refLong / aspect : refLong;
const rect = computeBodyRect(opts, W, H);
const coverScale = coverScaleFor(
rect.bodyW,
rect.bodyH,
opts.mapImageWidth,
opts.mapImageHeight,
opts.mapFit ?? "cover",
);
const outputMpp = opts.metersPerPixel / (coverScale || 1);
const mmPerPx = pageMm(page).widthMm / W;
if (!(mmPerPx > 0)) return 0;
const ratio = (outputMpp * 1000) / mmPerPx;
return Number.isFinite(ratio) && ratio > 0 ? ratio : 0;
}
/**
* Draw the full page layout onto a canvas. The canvas pixel dimensions define
* the render resolution; all furniture is scaled relative to the page so the
* preview and the export look identical.
*
* @param canvas - Destination canvas; its width/height are taken as the page
* size in pixels.
* @param opts - Layout content and options.
*/
export function drawLayout(canvas: HTMLCanvasElement, opts: LayoutOptions): void {
const ctx = canvas.getContext("2d");
if (!ctx) return;
const W = canvas.width;
const H = canvas.height;
// Scale furniture relative to the page's shorter side so output looks the
// same at any resolution / paper size. The body rectangle and unit come from
// the shared geometry helper so the on-screen scale matches the export.
const { unit, margin, bodyX, bodyY, bodyW, bodyH } = computeBodyRect(opts, W, H);
const {
hasTitleText,
hasSubtitleText,
hasTitleBlock,
titleInside,
attributionText,
footerText,
dateText,
hasFooterRow,
} = resolveContentFlags(opts);
const titleAlign = opts.titleAlign ?? "center";
ctx.save();
ctx.fillStyle = PAGE_BACKGROUND;
ctx.fillRect(0, 0, W, H);
// X anchor + canvas textAlign for the chosen title alignment.
const titleX = titleAlign === "left" ? margin : titleAlign === "right" ? W - margin : W / 2;
// --- Title block (outside the map) -------------------------------------
if (hasTitleBlock && !titleInside) {
const titleSize = unit * 4.5;
const subtitleSize = unit * 2.4;
let y = margin + titleSize;
if (hasTitleText) {
ctx.fillStyle = INK;
ctx.font = `600 ${titleSize}px system-ui, -apple-system, sans-serif`;
ctx.textAlign = titleAlign;
ctx.textBaseline = "alphabetic";
ctx.fillText(opts.title.trim(), titleX, y, W - margin * 2);
}
if (hasSubtitleText) {
y += subtitleSize * 1.4;
ctx.fillStyle = MUTED;
ctx.font = `400 ${subtitleSize}px system-ui, -apple-system, sans-serif`;
ctx.textAlign = titleAlign;
ctx.fillText(opts.subtitle.trim(), titleX, y, W - margin * 2);
}
}
// --- Footer row --------------------------------------------------------
if (hasFooterRow) {
const footSize = unit * 2.2;
const baselineY = H - margin - footSize * 0.6;
ctx.fillStyle = MUTED;
ctx.font = `400 ${footSize}px system-ui, -apple-system, sans-serif`;
ctx.textBaseline = "middle";
// Give each of the three slots a third of the printable width so a long
// left attribution cannot visually bleed into the centred footer text.
const slotMax = (W - margin * 2) / 3;
if (attributionText) {
ctx.textAlign = "left";
ctx.fillText(attributionText, margin, baselineY, slotMax);
}
if (footerText) {
ctx.textAlign = "center";
ctx.fillText(footerText, W / 2, baselineY, slotMax);
}
if (dateText) {
ctx.textAlign = "right";
ctx.fillText(dateText, W - margin, baselineY, slotMax);
}
}
// --- Map body ----------------------------------------------------------
// The body rectangle is computed by computeBodyRect (which already clamps the
// top so a tall title block plus footer on a very small page can never push
// the map area below the footer).
ctx.save();
ctx.beginPath();
ctx.rect(bodyX, bodyY, bodyW, bodyH);
ctx.clip();
ctx.fillStyle = opts.mapBackground ?? "#e5e7eb";
ctx.fillRect(bodyX, bodyY, bodyW, bodyH);
// Draw the map image. "cover" (default) fills the body and crops the overflow;
// "contain" fits the whole image without cropping (used for a graticule so its
// edge labels are not trimmed), leaving background margins on the shorter axis.
// Guard the draw: a tainted/broken capture must not abort the whole layout,
// otherwise a single bad basemap (e.g. cross-origin OpenTopo tiles) would wipe
// out every cartographic element too, not just the map image.
let coverScale = 1;
if (opts.mapImage && opts.mapImageWidth > 0 && opts.mapImageHeight > 0) {
coverScale = coverScaleFor(
bodyW,
bodyH,
opts.mapImageWidth,
opts.mapImageHeight,
opts.mapFit ?? "cover",
);
const drawW = opts.mapImageWidth * coverScale;
const drawH = opts.mapImageHeight * coverScale;
const dx = bodyX + (bodyW - drawW) / 2;
const dy = bodyY + (bodyH - drawH) / 2;
try {
ctx.drawImage(opts.mapImage, dx, dy, drawW, drawH);
} catch {
// Leave the grey placeholder; the rest of the layout still renders.
}
}
ctx.restore();
// Body border (the map frame). Colour and thickness are user-customizable; a
// thickness of 0 hides the frame entirely (GH #749). The thickness is a 0–10
// scale relative to the page so it reads the same at any export resolution.
const mapBorderScale = Math.max(0, Math.min(10, opts.mapBorderWidth ?? 1));
const mapBorderWidth = mapBorderScale > 0 ? Math.max(1, unit * 0.2 * mapBorderScale) : 0;
if (mapBorderWidth > 0) {
ctx.strokeStyle = opts.mapBorderColor ?? BORDER;
ctx.lineWidth = mapBorderWidth;
ctx.strokeRect(bodyX, bodyY, bodyW, bodyH);
}
// --- Title block (inside the map) --------------------------------------
// Overlaid at the top of the map body with a translucent backing for legibility.
if (hasTitleBlock && titleInside) {
ctx.save();
ctx.beginPath();
ctx.rect(bodyX, bodyY, bodyW, bodyH);
ctx.clip();
const titleSize = unit * 4;
const subtitleSize = unit * 2.2;
const padY = unit * 2;
// Seed the baseline at the first line that is actually drawn: when the title
// is hidden, the subtitle takes the top slot rather than being pushed a full
// title-height down (which dropped it below the backing rect). GH #526.
let y = bodyY + padY + (hasTitleText ? titleSize : subtitleSize);
const insetX = unit * 2;
const tx =
titleAlign === "left"
? bodyX + insetX
: titleAlign === "right"
? bodyX + bodyW - insetX
: bodyX + bodyW / 2;
const blockH =
padY * 2 +
(hasTitleText ? titleSize : 0) +
(hasSubtitleText ? (hasTitleText ? subtitleSize * 1.6 : subtitleSize * 1.2) : 0);
// Keep the translucent backing clear of the map frame so it does not wash
// out the dark border line at the top/left/right edges (GH #748). strokeRect
// centres the stroke on the body edge, so only its inner half (lineWidth/2)
// intrudes into the body; inset the fill by exactly that so it starts at the
// frame's inner edge with no gap and no overlap.
const frameInset = mapBorderWidth / 2;
ctx.fillStyle = "rgba(255,255,255,0.7)";
ctx.fillRect(
bodyX + frameInset,
bodyY + frameInset,
bodyW - frameInset * 2,
// Top shifted down by frameInset; shrink the height to keep the bottom
// edge at bodyY + blockH (which sits inside the body, off any frame line).
blockH - frameInset,
);
if (hasTitleText) {
ctx.fillStyle = INK;
ctx.font = `600 ${titleSize}px system-ui, -apple-system, sans-serif`;
ctx.textAlign = titleAlign;
ctx.textBaseline = "alphabetic";
ctx.fillText(opts.title.trim(), tx, y, bodyW - insetX * 2);
}
if (hasSubtitleText) {
// Only advance past the title line when one was drawn.
if (hasTitleText) y += subtitleSize * 1.4;
ctx.fillStyle = MUTED;
ctx.font = `400 ${subtitleSize}px system-ui, -apple-system, sans-serif`;
ctx.textAlign = titleAlign;
ctx.fillText(opts.subtitle.trim(), tx, y, bodyW - insetX * 2);
}
ctx.restore();
}
const inset = unit * 2;
// Metres per pixel in the *output* image after cover scaling.
const outputMpp = opts.metersPerPixel / (coverScale || 1);
const hasScale = opts.showScaleBar && outputMpp > 0 && Number.isFinite(outputMpp);
// Representative fraction (1:N) from the shared, resolution-independent helper
// so the scale bar, the info block, and the dialog's scale input all agree.
// It is only non-zero for physical paper sizes with a captured map.
const scaleRatio = computeScaleRatio(opts);
// --- Info block (cartographic title block / "stempel", bottom-right) ----
// Rendered only when the toggle is on AND there is at least one row to show
// (a metadata field or an available scale). With the toggle on but every
// field empty and no scale (e.g. a screen-size page), nothing is drawn rather
// than an empty box; the dialog still shows the input fields to fill in.
const infoLines = buildInfoLines(opts, scaleRatio);
const hasInfoBlock = (opts.showInfoBlock ?? false) && infoLines.length > 0;
if (hasInfoBlock) {
ctx.save();
ctx.beginPath();
ctx.rect(bodyX, bodyY, bodyW, bodyH);
ctx.clip();
drawInfoBlock(ctx, bodyX + bodyW - inset, bodyY + bodyH - inset, infoLines, unit);
ctx.restore();
}
const navGrouped = opts.navigationGrouped ?? true;
const groupNav = navGrouped && opts.showNorthArrow && hasScale;
// When the info block occupies the bottom-right corner, move the scale bar +
// north arrow to the bottom-left so they never sit under the block.
const navOnLeft = hasInfoBlock;
const navAnchorX = navOnLeft ? bodyX + inset + bodyW * 0.28 : bodyX + bodyW - inset;
// --- Scale bar + north arrow ------------------------------------------
let scaleTopY = bodyY + bodyH - inset;
if (hasScale) {
scaleTopY = drawScaleBar(
ctx,
navAnchorX,
bodyY + bodyH - inset,
bodyW * 0.28,
outputMpp,
unit,
scaleRatio,
opts.scaleUnit ?? "metric",
);
}
if (opts.showNorthArrow) {
const arrowRadius = unit * 2.6;
const discRadius = arrowRadius * 1.5;
if (groupNav) {
// Stack the north arrow directly above the scale bar (the "navigation duo").
drawNorthArrow(
ctx,
navAnchorX - discRadius,
scaleTopY - unit * 1.4 - discRadius,
arrowRadius,
opts.bearingDeg,
unit,
);
} else {
// Isolated fallback: top-right corner inside the map.
const topExtent = arrowRadius + unit * 2.4;
const arrowMargin = unit * 3;
drawNorthArrow(
ctx,
bodyX + bodyW - arrowMargin - discRadius,
bodyY + arrowMargin + topExtent,
arrowRadius,
opts.bearingDeg,
unit,
);
}
}
// --- Legend (top-left inside the map) ---------------------------------
// Clip to the map body so a legend with many layers cannot overflow onto the
// footer or off the page.
let legendHeight = 0;
if (opts.showLegend && opts.legend.length > 0) {
ctx.save();
ctx.beginPath();
ctx.rect(bodyX, bodyY, bodyW, bodyH);
ctx.clip();
legendHeight = drawLegend(ctx, bodyX + inset, bodyY + inset, opts.legend, unit, {
title: opts.legendTitle,
groupByLayer: opts.legendGroupByLayer,
markerIcons: opts.markerIcons,
// Legend sizes are stored in MapLibre CSS pixels. The capture is in
// device pixels and is then fitted into the page body, so apply both
// transforms to make the legend symbols match their map counterparts.
mapSymbolScale: Math.max(0, (opts.mapPixelRatio ?? 1) * coverScale),
maxHeight: bodyH - inset * 2,
formatNote: opts.legendFormatNote,
});
ctx.restore();
}
// --- Corner panels (colorbar, custom legend, table, chart) ------------
// Panels sharing a corner stack toward the body centre instead of drawing
// on top of each other (e.g. colorbar + chart, both defaulting top-right).
// The ledger tracks the vertical space already claimed per corner; the info
// block still owns the bottom-right, so panels aimed there relocate to the
// top-right first (the original colorbar rule, GH #522).
const stackGap = unit * 1.2;
const cornerUsed: Record<BodyCorner, number> = {
// The layer-derived legend always occupies the top-left corner when shown;
// seed the ledger so a panel aimed there stacks below it.
"top-left": legendHeight > 0 ? legendHeight + stackGap : 0,
"top-right": 0,
"bottom-left": 0,
"bottom-right": 0,
};
const resolveCorner = (position: BodyCorner): BodyCorner =>
hasInfoBlock && position === "bottom-right" ? "top-right" : position;
const drawCornerPanel = (
position: BodyCorner,
draw: (corner: BodyCorner, stackOffset: number) => number,
) => {
const corner = resolveCorner(position);
ctx.save();
ctx.beginPath();
ctx.rect(bodyX, bodyY, bodyW, bodyH);
ctx.clip();
const height = draw(corner, cornerUsed[corner]);
ctx.restore();
cornerUsed[corner] += height + stackGap;
};
if (opts.colorbar && opts.colorbar.colors.length >= 2) {
const colorbar = opts.colorbar;
drawCornerPanel(colorbar.position, (corner, stackOffset) =>
drawColorbar(
ctx,
{ ...colorbar, position: corner },
bodyX,
bodyY,
bodyW,
bodyH,
unit,
stackOffset,
),
);
}
if (opts.customLegend && opts.customLegend.entries.length > 0) {
const customLegend = opts.customLegend;
drawCornerPanel(customLegend.position, (corner, stackOffset) =>
drawCustomLegend(
ctx,
{ ...customLegend, position: corner },
bodyX,