-
-
Notifications
You must be signed in to change notification settings - Fork 626
Expand file tree
/
Copy pathPrintLayoutDialog.tsx
More file actions
3256 lines (3182 loc) · 135 KB
/
Copy pathPrintLayoutDialog.tsx
File metadata and controls
3256 lines (3182 loc) · 135 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
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
DEFAULT_LEGEND_CONFIG,
getVectorColorRamp,
useAppStore,
VECTOR_COLOR_RAMPS,
} from "@geolibre/core";
import { loadMarkerSvgImage, type MapController } from "@geolibre/map";
import { GRATICULE_LABEL_LAYER_ID } from "@geolibre/plugins";
import {
Button,
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
Input,
Label,
Select,
Separator,
Slider,
Textarea,
} from "@geolibre/ui";
import {
ArrowDown,
ArrowUp,
Check,
ChevronLeft,
ChevronRight,
ClipboardCopy,
Crop,
Eye,
EyeOff,
FileImage,
FileText,
Plus,
RefreshCw,
RotateCcw,
Trash2,
} from "lucide-react";
import {
computeScaleRatio,
drawLayout,
PAPER_SIZES,
resolvePageSize,
type BodyCorner,
type CustomSize,
type LayoutOptions,
type Orientation,
type PaperSizeId,
type SizeUnit,
} from "../../lib/print-layout";
import {
buildChartBlock,
buildTableBlock,
DEFAULT_TABLE_COLUMNS,
DEFAULT_TABLE_ROWS,
layerRows,
MAX_TABLE_ROWS,
rowsWithinBounds,
type ChartBlockType,
} from "../../lib/print-data-blocks";
import {
categoricalColumns,
numericColumns,
type BarAggregation,
type ChartRow,
} from "../../lib/attribute-charts";
import {
clearPrintExtent,
drawPrintExtent,
setPrintExtentVisible,
showPrintExtent,
type PrintExtent,
} from "../../lib/print-extent";
import {
applyLegendConfig,
buildLegend,
captureMapImage,
copyLayoutToClipboard,
exportAtlasPdf,
exportAtlasPngZip,
exportLayoutPdf,
exportLayoutPng,
legendEditorRows,
reorderLegendEntry,
setLegendItemLabel,
toggleLegendItemHidden,
type CapturedMap,
} from "../../lib/print-layout-export";
import {
atlasEntryName,
buildAtlasPages,
buildLineAtlasPages,
collectAtlasFeatures,
hasLineGeometry,
MAX_LINE_ATLAS_PAGES,
expandBounds,
listAtlasFields,
parseAtlasFilter,
stripAtlasTokens,
substituteAtlasTokens,
type AtlasBounds,
type AtlasFeatureInfo,
type AtlasPage,
type AtlasTokenContext,
} from "../../lib/print-atlas";
interface PrintLayoutDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
mapControllerRef: React.RefObject<MapController | null>;
}
/** Common industry scale denominators offered as quick presets (GH #522). */
const SCALE_PRESETS = [500, 1000, 2500, 5000, 10000, 25000, 50000, 100000];
/** Bounds (px) for the draggable controls column inside the dialog. */
const CONTROLS_MIN_WIDTH = 260;
const CONTROLS_MAX_WIDTH = 560;
const CONTROLS_DEFAULT_WIDTH = 320;
function sanitizeFilename(name: string): string {
// Keep letters and digits from any script (\p{L}\p{N}) so non-Latin project
// names are not stripped to the fallback.
const cleaned = name
.trim()
.replace(/[^\p{L}\p{N} _-]+/gu, "")
.replace(/\s+/g, "-");
return cleaned || "map-layout";
}
interface ToggleFieldProps {
id: string;
label: string;
checked: boolean;
disabled?: boolean;
onChange: (next: boolean) => void;
}
/** A labelled checkbox row for toggling a map element on or off. */
function ToggleField({ id, label, checked, disabled, onChange }: ToggleFieldProps) {
return (
<label
htmlFor={id}
className={`flex items-center gap-2 text-sm ${
disabled ? "cursor-default opacity-50" : "cursor-pointer"
}`}
>
<input
id={id}
type="checkbox"
className="h-4 w-4 accent-primary"
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
/>
{label}
</label>
);
}
/**
* Print Layout composer dialog: captures the current map view and composes it
* with a title, legend, scale bar, north arrow, and footer onto a chosen paper
* or screen size, then exports the result to PNG or PDF.
*/
export function PrintLayoutDialog({
open,
onOpenChange,
mapControllerRef,
}: PrintLayoutDialogProps) {
const { t } = useTranslation();
const layers = useAppStore((s) => s.layers);
const projectName = useAppStore((s) => s.projectName);
const legendConfig = useAppStore((s) => s.legend);
const setLegendConfig = useAppStore((s) => s.setLegend);
// Follow the map's scale-bar unit preference so the printed bar matches the
// on-screen one (metric / imperial / nautical).
const scaleUnit = useAppStore((s) => s.preferences.map.scaleUnit);
const [title, setTitle] = useState("");
const [subtitle, setSubtitle] = useState("");
const [titlePlacement, setTitlePlacement] = useState<"outside" | "inside">("outside");
const [titleAlign, setTitleAlign] = useState<"left" | "center" | "right">("center");
const [paperSize, setPaperSize] = useState<PaperSizeId>("a4");
const [orientation, setOrientation] = useState<Orientation>("landscape");
const [customWidth, setCustomWidth] = useState(1280);
const [customHeight, setCustomHeight] = useState(720);
const [customUnit, setCustomUnit] = useState<SizeUnit>("px");
const [showTitle, setShowTitle] = useState(true);
const [showSubtitle, setShowSubtitle] = useState(true);
const [showLegend, setShowLegend] = useState(true);
const [showScaleBar, setShowScaleBar] = useState(true);
const [showNorthArrow, setShowNorthArrow] = useState(true);
const [navigationGrouped, setNavigationGrouped] = useState(true);
const [showFooter, setShowFooter] = useState(false);
const [footerText, setFooterText] = useState("");
const [showDate, setShowDate] = useState(true);
const [dateText, setDateText] = useState("");
const [showAttribution, setShowAttribution] = useState(true);
const [pageMargin, setPageMargin] = useState<"normal" | "narrow" | "none">("normal");
const [showPageBorder, setShowPageBorder] = useState(false);
const [pageBorderColor, setPageBorderColor] = useState("#111827");
const [pageBorderWidth, setPageBorderWidth] = useState(2);
// Map frame (the border around the map body). Width is a 0–10 scale; 0 hides
// the frame. Defaults match the original hardcoded hairline (GH #749).
const [mapBorderColor, setMapBorderColor] = useState("#9ca3af");
const [mapBorderWidth, setMapBorderWidth] = useState(1);
const [mapBackground, setMapBackground] = useState("#e5e7eb");
// Draft for the free-form hex field; only complete #RGB / #RRGGBB values are
// committed to mapBackground (which also drives <input type="color"> and the
// canvas fillStyle), so a half-typed "#" never corrupts the layout colour.
const [mapBackgroundDraft, setMapBackgroundDraft] = useState("#e5e7eb");
const commitMapBackground = useCallback((value: string) => {
setMapBackgroundDraft(value);
if (/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(value.trim())) {
setMapBackground(value.trim());
}
}, []);
// Native colorbar composed in the dialog (GH follow-up).
const [showColorbar, setShowColorbar] = useState(false);
const [colorbarRamp, setColorbarRamp] = useState("viridis");
const [colorbarMin, setColorbarMin] = useState("0");
const [colorbarMax, setColorbarMax] = useState("100");
const [colorbarLabel, setColorbarLabel] = useState("");
const [colorbarOrientation, setColorbarOrientation] = useState<"vertical" | "horizontal">(
"vertical",
);
// Bar length as a percentage of the body width/height.
const [colorbarLength, setColorbarLength] = useState(34);
// User-defined legend composed in the dialog (like Controls -> Legend).
const [showCustomLegend, setShowCustomLegend] = useState(false);
const [customLegendTitle, setCustomLegendTitle] = useState("Legend");
const [customLegendEntries, setCustomLegendEntries] = useState<
{ id: string; label: string; color: string }[]
>([
{ id: "cl-1", label: "Class 1", color: "#2563eb" },
{ id: "cl-2", label: "Class 2", color: "#16a34a" },
]);
const [customLegendPosition, setCustomLegendPosition] = useState<
"top-left" | "top-right" | "bottom-left" | "bottom-right"
>("top-left");
const customLegendId = useRef(2);
const [legendDict, setLegendDict] = useState("");
const [legendDictError, setLegendDictError] = useState<string | null>(null);
// Replace the legend items from a `{ label: color }` dictionary, matching the
// Controls -> Legend "Import from Dictionary" format.
const importLegendDict = useCallback(() => {
let parsed: unknown;
try {
parsed = JSON.parse(legendDict);
} catch {
setLegendDictError(t("printLayout.customLegend.importError"));
return;
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
setLegendDictError(t("printLayout.customLegend.importError"));
return;
}
const entries = Object.entries(parsed as Record<string, unknown>).map(([label, color]) => ({
id: `cl-${++customLegendId.current}`,
label,
color: String(color),
}));
if (entries.length === 0) {
setLegendDictError(t("printLayout.customLegend.importError"));
return;
}
setCustomLegendEntries(entries);
setLegendDictError(null);
}, [legendDict, t]);
// Default away from the bottom-right nav duo and top-left legend.
const [colorbarPosition, setColorbarPosition] = useState<
"top-left" | "top-right" | "bottom-left" | "bottom-right"
>("top-right");
// Data blocks: attribute table + chart composed on the page (GH #1324).
const [showDataTable, setShowDataTable] = useState(false);
const [tableLayerId, setTableLayerId] = useState("");
const [tableTitle, setTableTitle] = useState("");
// Explicitly checked columns; empty = the layer's first few fields.
const [tableColumns, setTableColumns] = useState<string[]>([]);
const [tableSortField, setTableSortField] = useState("");
const [tableSortDesc, setTableSortDesc] = useState(false);
const [tableMaxRows, setTableMaxRows] = useState(DEFAULT_TABLE_ROWS);
const [tablePosition, setTablePosition] = useState<BodyCorner>("bottom-left");
const [tableFilterToPage, setTableFilterToPage] = useState(true);
const [showDataChart, setShowDataChart] = useState(false);
const [chartLayerId, setChartLayerId] = useState("");
const [chartTitle, setChartTitle] = useState("");
const [chartType, setChartType] = useState<ChartBlockType>("bar");
const [chartCategoryField, setChartCategoryField] = useState("");
const [chartAggregation, setChartAggregation] = useState<BarAggregation>("count");
const [chartValueField, setChartValueField] = useState("");
// Top-right by default: the scale bar + north arrow duo occupies the
// bottom-right corner out of the box.
const [chartPosition, setChartPosition] = useState<BodyCorner>("top-right");
const [chartFilterToPage, setChartFilterToPage] = useState(true);
// Cartographic title block ("stempel") fields (GH #522).
const [showInfoBlock, setShowInfoBlock] = useState(false);
const [author, setAuthor] = useState("");
const [projectNumber, setProjectNumber] = useState("");
const [crs, setCrs] = useState("");
const [revision, setRevision] = useState("");
// Custom print extent drawn on the map (GH #523).
const [captureMode, setCaptureMode] = useState<"viewport" | "extent">("viewport");
const [extentBbox, setExtentBbox] = useState<PrintExtent | null>(null);
const [drawingExtent, setDrawingExtent] = useState(false);
// Atlas / map series: one page per coverage-layer feature (GH #1291).
const [atlasEnabled, setAtlasEnabled] = useState(false);
const [atlasLayerId, setAtlasLayerId] = useState("");
// Coverage strategy: one page per feature, or pages tiling the layer's line
// features in fixed-length stretches (GH #1291 follow-up).
const [atlasCoverage, setAtlasCoverage] = useState<"features" | "line">("features");
const [atlasSegmentKm, setAtlasSegmentKm] = useState("20");
const [atlasNameField, setAtlasNameField] = useState("");
const [atlasExtentMode, setAtlasExtentMode] = useState<"margin" | "scale">("margin");
const [atlasMarginPct, setAtlasMarginPct] = useState(10);
const [atlasScale, setAtlasScale] = useState("50000");
const [atlasSortField, setAtlasSortField] = useState("");
const [atlasSortDescending, setAtlasSortDescending] = useState(false);
const [atlasFilter, setAtlasFilter] = useState("");
const [atlasFilenamePattern, setAtlasFilenamePattern] = useState(
"{atlas.pagenumber}-{atlas.name}",
);
const [atlasIndex, setAtlasIndex] = useState(0);
// True while the atlas is driving the live map (stepping or exporting), so
// the stepper and export buttons cannot start a second, overlapping drive.
const [atlasBusy, setAtlasBusy] = useState(false);
const [atlasProgress, setAtlasProgress] = useState<{
current: number;
total: number;
} | null>(null);
// Set when the last atlas capture had to clamp a fixed scale to the map's
// zoom limits, mirroring the manual scale flow's out-of-range notice.
const [atlasScaleNotice, setAtlasScaleNotice] = useState<string | null>(null);
// The map's actual visible bounds after the last atlas capture, keyed by
// page index. The data blocks' page-extent filter prefers this over the
// page's nominal bounds: in fixed-scale mode the zoom correction changes
// the rendered extent away from the fitted feature box (GH #1324).
const [atlasViewBounds, setAtlasViewBounds] = useState<{
index: number;
bounds: AtlasBounds;
} | null>(null);
// Mirror of atlasActive (derived further down) for the dialog-open effect,
// which is declared before those derivations exist.
const atlasActiveRef = useRef(false);
const [captured, setCaptured] = useState<CapturedMap | null>(null);
// "contain" when a graticule is active, so its edge labels are not trimmed by
// the default "cover" crop; "cover" (fill the frame) otherwise.
const [mapFit, setMapFit] = useState<"cover" | "contain">("cover");
const [exporting, setExporting] = useState(false);
// Brief "Copied" confirmation on the clipboard button (GH #773).
const [copied, setCopied] = useState(false);
const copiedTimeoutRef = useRef<number | null>(null);
const [error, setError] = useState<string | null>(null);
const previewRef = useRef<HTMLCanvasElement | null>(null);
const previewBoxRef = useRef<HTMLDivElement | null>(null);
const wasOpenRef = useRef(false);
// Set while the dialog is hidden to let the user draw on the map, so the
// close handler does not tear down the in-progress extent box.
const drawingRef = useRef(false);
// Aborts an in-progress draw when the dialog unmounts mid-drag.
const drawAbortRef = useRef<AbortController | null>(null);
// A pending "recapture once the map is idle" handler (from applyScale), kept
// so any newer capture can cancel it before it overwrites a fresh result.
const idleRecaptureRef = useRef<(() => void) | null>(null);
// Tears down an in-progress dialog/splitter resize drag (removes the window
// pointer listeners) if the dialog unmounts mid-drag.
const resizeCleanupRef = useRef<(() => void) | null>(null);
// True while the scale input has focus, so two-way sync does not overwrite
// what the user is typing.
const scaleFocusedRef = useRef(false);
const [scaleDraft, setScaleDraft] = useState("");
// Inline notice shown when a requested scale can't be reached at the map's
// zoom limits, so a clamped result is never silently swallowed (GH #743).
const [scaleNotice, setScaleNotice] = useState<string | null>(null);
// Fallback timer that forces a recapture if the map's "idle" event is delayed
// or never fires (e.g. WebKit throttling the occluded map canvas behind the
// dialog), so a scale change is never silently dropped (GH #743).
const idleFallbackRef = useRef<number | null>(null);
// Width of the left controls column; dragged via the splitter handle.
const [controlsWidth, setControlsWidth] = useState(CONTROLS_DEFAULT_WIDTH);
// Mirror of controlsWidth so the resize handler can read the latest start
// width without listing it as a dep (which would recreate the callback every
// RAF tick during a drag).
const controlsWidthRef = useRef(controlsWidth);
controlsWidthRef.current = controlsWidth;
// Explicit dialog size once the user drags the corner grip (null = the
// default responsive size). The dialog element, for reading its live size.
const dialogRef = useRef<HTMLDivElement>(null);
const [dialogSize, setDialogSize] = useState<{
width: number;
height: number;
} | null>(null);
// Resize the whole dialog from its bottom-right grip. The dialog is centred
// via a -50% transform, so the right/bottom edges move by half the size
// change; growing by 2x the pointer delta keeps the grip under the cursor.
const startDialogResize = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
event.preventDefault();
event.stopPropagation();
event.currentTarget.setPointerCapture?.(event.pointerId);
const el = dialogRef.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const startX = event.clientX;
const startY = event.clientY;
const startW = rect.width;
const startH = rect.height;
let next = { width: startW, height: startH };
let frame: number | null = null;
const prevCursor = document.body.style.cursor;
const prevSelect = document.body.style.userSelect;
document.body.style.cursor = "nwse-resize";
document.body.style.userSelect = "none";
const onMove = (e: PointerEvent) => {
next = {
width: Math.max(480, Math.min(window.innerWidth - 16, startW + (e.clientX - startX) * 2)),
height: Math.max(360, Math.min(window.innerHeight - 16, startH + (e.clientY - startY) * 2)),
};
if (frame !== null) return;
frame = window.requestAnimationFrame(() => {
frame = null;
setDialogSize(next);
});
};
const cleanup = () => {
window.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerup", onUp);
window.removeEventListener("pointercancel", onUp);
if (frame !== null) window.cancelAnimationFrame(frame);
document.body.style.cursor = prevCursor;
document.body.style.userSelect = prevSelect;
resizeCleanupRef.current = null;
};
const onUp = () => {
cleanup();
setDialogSize(next);
};
resizeCleanupRef.current = cleanup;
window.addEventListener("pointermove", onMove);
window.addEventListener("pointerup", onUp);
window.addEventListener("pointercancel", onUp);
}, []);
// Drag the splitter between the controls column and the preview. Mirrors the
// shell's panel-resize idiom: pointer capture so the drag survives leaving the
// handle, RAF-throttled width updates, and a col-resize body cursor.
const startSplitterResize = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
event.preventDefault();
event.currentTarget.setPointerCapture?.(event.pointerId);
const startX = event.clientX;
const startWidth = controlsWidthRef.current;
let nextWidth = startWidth;
let frame: number | null = null;
const prevCursor = document.body.style.cursor;
const prevSelect = document.body.style.userSelect;
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
const onMove = (e: PointerEvent) => {
nextWidth = Math.max(
CONTROLS_MIN_WIDTH,
Math.min(CONTROLS_MAX_WIDTH, startWidth + e.clientX - startX),
);
if (frame !== null) return;
frame = window.requestAnimationFrame(() => {
frame = null;
setControlsWidth(nextWidth);
});
};
const cleanup = () => {
window.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerup", onUp);
window.removeEventListener("pointercancel", onUp);
if (frame !== null) window.cancelAnimationFrame(frame);
document.body.style.cursor = prevCursor;
document.body.style.userSelect = prevSelect;
resizeCleanupRef.current = null;
};
const onUp = () => {
cleanup();
setControlsWidth(nextWidth);
};
resizeCleanupRef.current = cleanup;
window.addEventListener("pointermove", onMove);
window.addEventListener("pointerup", onUp);
window.addEventListener("pointercancel", onUp);
}, []);
const isCustom = paperSize === "custom";
const paperOptions = useMemo(() => PAPER_SIZES.filter((p) => p.group === "paper"), []);
const screenOptions = useMemo(
() => PAPER_SIZES.filter((p) => p.group === "screen" && p.id !== "custom"),
[],
);
const baseLegend = useMemo(() => buildLegend(layers), [layers]);
const legend = useMemo(
() => applyLegendConfig(baseLegend, legendConfig),
[baseLegend, legendConfig],
);
const editorRows = useMemo(
() => legendEditorRows(baseLegend, legendConfig),
[baseLegend, legendConfig],
);
// Custom SVG markers must be drawn into legend swatches, but drawLayout is
// synchronous while decoding an SVG is not, so preload them here (keyed by the
// swatch marker's svg string) and hand drawLayout the ready images -- like the
// captured map image. The key is a JSON array of the sorted sources: it
// round-trips losslessly (SVG markup and URLs contain spaces/newlines) and,
// being stable, avoids reloading on unrelated legend edits (labels, hidden
// flags).
const markerSvgKey = useMemo(() => {
const sources = new Set<string>();
for (const entry of baseLegend) {
for (const sw of entry.swatches) {
if (sw.marker?.shape === "custom" && sw.marker.svg) sources.add(sw.marker.svg);
}
}
return JSON.stringify(Array.from(sources).sort());
}, [baseLegend]);
const [markerIcons, setMarkerIcons] = useState<Map<string, HTMLImageElement>>(new Map());
useEffect(() => {
const sources = JSON.parse(markerSvgKey) as string[];
if (sources.length === 0) {
setMarkerIcons((prev) => (prev.size === 0 ? prev : new Map()));
return;
}
let cancelled = false;
void Promise.all(
sources.map(async (src) => [src, await loadMarkerSvgImage(src)] as const),
).then((pairs) => {
if (cancelled) return;
const next = new Map<string, HTMLImageElement>();
for (const [src, img] of pairs) if (img) next.set(src, img);
setMarkerIcons(next);
});
return () => {
cancelled = true;
};
}, [markerSvgKey]);
const entryIdsInOrder = useMemo(
() => editorRows.filter((r) => r.kind === "entry").map((r) => r.layerId),
[editorRows],
);
const moveEntry = useCallback(
(layerId: string, direction: "up" | "down") => {
setLegendConfig(reorderLegendEntry(legendConfig, entryIdsInOrder, layerId, direction));
},
[legendConfig, entryIdsInOrder, setLegendConfig],
);
const recapture = useCallback(
(clipOverride?: PrintExtent | null) => {
const map = mapControllerRef.current?.getMap();
if (!map) {
setError(t("printLayout.errors.mapNotReady"));
setCaptured(null);
return;
}
// Cancel any pending post-zoom idle capture: this fresh capture supersedes
// it, so it must not fire later and overwrite the result (e.g. a viewport
// recapture clobbering an extent the user drew while tiles were loading).
if (idleRecaptureRef.current) {
map.off("idle", idleRecaptureRef.current);
idleRecaptureRef.current = null;
}
if (idleFallbackRef.current !== null) {
window.clearTimeout(idleFallbackRef.current);
idleFallbackRef.current = null;
}
// An explicit override wins (used right after drawing, before state has
// settled); otherwise clip to the stored extent only in extent mode.
const clip =
clipOverride !== undefined ? clipOverride : captureMode === "extent" ? extentBbox : null;
// An active graticule draws coordinate labels at the map edges; fit the
// captured map with "contain" so the page crop does not trim them.
setMapFit(map.getLayer(GRATICULE_LABEL_LAYER_ID) ? "contain" : "cover");
// Hide the extent box while reading the drawing buffer so its outline is
// never baked into the captured image.
setPrintExtentVisible(map, false);
try {
setCaptured(captureMapImage(map, clip));
setError(null);
} catch {
setError(t("printLayout.errors.captureFailed"));
setCaptured(null);
} finally {
setPrintExtentVisible(map, true);
}
},
[mapControllerRef, t, captureMode, extentBbox],
);
// Capture the map and seed defaults only on the closed -> open transition, so
// a background project-name change while the dialog is open does not replace
// the snapshot the user is composing.
useEffect(() => {
const map = mapControllerRef.current?.getMap();
if (open && !wasOpenRef.current) {
setError(null);
// Clear any out-of-range scale notice from a prior session: the dialog is
// hidden (not unmounted) on close, so it would otherwise persist into the
// next open even though no scale was just attempted (GH #743).
setScaleNotice(null);
// Same reasoning for the clipboard "Copied" flag: a copy made just before
// the dialog was closed (within the 2s window) would otherwise re-open
// still showing the confirmation (GH #773).
if (copiedTimeoutRef.current !== null) {
window.clearTimeout(copiedTimeoutRef.current);
copiedTimeoutRef.current = null;
}
setCopied(false);
setTitle((prev) => prev || (projectName ?? "").trim());
setDateText((prev) => prev || new Date().toLocaleDateString());
// Re-show a previously drawn extent box while composing.
if (map && extentBbox) showPrintExtent(map, extentBbox);
// With an active atlas persisting from a prior session, skip the plain
// viewport capture: the atlas auto-drive effect recaptures the current
// page on this same transition, and the extra capture would flash an
// incorrect preview first.
if (!atlasActiveRef.current) recapture();
} else if (!open && wasOpenRef.current && !drawingRef.current) {
// Closing for good (not to draw): take the extent box off the map.
if (map) clearPrintExtent(map);
}
wasOpenRef.current = open;
}, [open, projectName, recapture, mapControllerRef, extentBbox]);
// Clean up if the dialog unmounts: abort an in-progress draw (so its window
// listeners are torn down and it does not setState on an unmounted component)
// and take the extent box off the map.
useEffect(
() => () => {
drawAbortRef.current?.abort();
// Tear down an in-progress resize drag so its window listeners don't leak.
resizeCleanupRef.current?.();
if (idleFallbackRef.current !== null) {
window.clearTimeout(idleFallbackRef.current);
idleFallbackRef.current = null;
}
if (copiedTimeoutRef.current !== null) {
window.clearTimeout(copiedTimeoutRef.current);
copiedTimeoutRef.current = null;
}
const map = mapControllerRef.current?.getMap();
if (map) {
if (idleRecaptureRef.current) {
map.off("idle", idleRecaptureRef.current);
idleRecaptureRef.current = null;
}
clearPrintExtent(map);
}
},
[mapControllerRef],
);
const customSize = useMemo<CustomSize | null>(
() => (isCustom ? { width: customWidth, height: customHeight, unit: customUnit } : null),
[isCustom, customWidth, customHeight, customUnit],
);
const options = useMemo<LayoutOptions>(
() => ({
title,
subtitle,
paperSize,
orientation,
customSize,
showTitle,
showSubtitle,
titlePlacement,
titleAlign,
showLegend,
showScaleBar,
scaleUnit,
showNorthArrow,
navigationGrouped,
showFooter,
footerText,
showDate,
dateText,
showAttribution,
pageMargin,
showPageBorder,
pageBorderColor,
pageBorderWidth,
mapBorderColor,
mapBorderWidth,
mapBackground,
colorbar: showColorbar
? {
colors: getVectorColorRamp(colorbarRamp).colors,
// Treat a blank/invalid field as 0 explicitly (Number("abc") is NaN,
// which would otherwise flow into a degenerate gradient).
min: Number.isFinite(Number(colorbarMin)) ? Number(colorbarMin) : 0,
max: Number.isFinite(Number(colorbarMax)) ? Number(colorbarMax) : 0,
label: colorbarLabel,
orientation: colorbarOrientation,
position: colorbarPosition,
lengthPct: colorbarLength,
}
: null,
customLegend: showCustomLegend
? {
title: customLegendTitle,
entries: customLegendEntries.map((e) => ({
label: e.label,
color: e.color,
})),
position: customLegendPosition,
}
: null,
showInfoBlock,
author,
projectNumber,
crs,
revision,
infoLabels: {
author: t("printLayout.info.author"),
project: t("printLayout.info.project"),
crs: t("printLayout.info.crs"),
scale: t("printLayout.info.scale"),
revision: t("printLayout.info.revision"),
},
legend,
legendTitle: legendConfig.title,
legendGroupByLayer: legendConfig.groupByLayer,
legendFormatNote: (count: number) => t("printLayout.legend.moreItems", { count }),
markerIcons,
metersPerPixel: captured?.metersPerPixel ?? 0,
mapPixelRatio: captured?.pixelRatio ?? 1,
bearingDeg: captured?.bearingDeg ?? 0,
mapImage: captured?.image ?? null,
mapImageWidth: captured?.width ?? 0,
mapImageHeight: captured?.height ?? 0,
mapFit,
}),
[
title,
subtitle,
paperSize,
orientation,
customSize,
showTitle,
showSubtitle,
titlePlacement,
titleAlign,
showLegend,
showScaleBar,
scaleUnit,
showNorthArrow,
navigationGrouped,
showFooter,
footerText,
showDate,
dateText,
showAttribution,
pageMargin,
showPageBorder,
pageBorderColor,
pageBorderWidth,
mapBorderColor,
mapBorderWidth,
mapBackground,
showColorbar,
colorbarRamp,
colorbarMin,
colorbarMax,
colorbarLabel,
colorbarOrientation,
colorbarPosition,
colorbarLength,
showCustomLegend,
customLegendTitle,
customLegendEntries,
customLegendPosition,
showInfoBlock,
author,
projectNumber,
crs,
revision,
legend,
legendConfig,
markerIcons,
captured,
mapFit,
t,
],
);
// Current representative fraction (1:N), and whether scale is meaningful for
// the chosen page (only physical paper carries a true cartographic scale).
const isMmPage = resolvePageSize(options).unit === "mm";
const currentRatio = useMemo(() => computeScaleRatio(options), [options]);
// ---- Atlas (map series) derivations (GH #1291) ----
// Only vector layers whose features are loaded in the store can drive an
// atlas; tile-backed layers have no per-feature geometry to iterate.
const atlasLayers = useMemo(
() => layers.filter((l) => (l.geojson?.features?.length ?? 0) > 0),
[layers],
);
const atlasLayer = useMemo(
() => atlasLayers.find((l) => l.id === atlasLayerId) ?? null,
[atlasLayers, atlasLayerId],
);
// The per-vertex geometry walk runs once per coverage layer; sort/filter
// edits below only re-iterate these lightweight per-feature records.
const atlasFeatureInfos = useMemo(
() => (atlasLayer?.geojson ? collectAtlasFeatures(atlasLayer.geojson) : []),
[atlasLayer],
);
// Field names come from ALL features (once per layer, cheap over the
// precomputed records), so sparse attributes past any sample window still
// appear in the name/sort selectors.
const atlasFields = useMemo(() => listAtlasFields(atlasFeatureInfos), [atlasFeatureInfos]);
// Reparse (and rebuild the page list below) off React's deferred lane, so
// typing in the filter box does not synchronously re-iterate a large
// coverage layer on every keystroke.
const deferredAtlasFilter = useDeferredValue(atlasFilter);
// null = malformed expression: surface the error and fall back to no filter,
// so a half-typed condition never blanks the whole page list.
const atlasFilterPredicate = useMemo(
() => parseAtlasFilter(deferredAtlasFilter),
[deferredAtlasFilter],
);
// How many features can seed along-a-line coverage (used to message an
// empty series and to hide the mode for point/polygon-only layers).
const atlasLineFeatureCount = useMemo(
() =>
atlasLayer?.geojson
? atlasLayer.geojson.features.filter((f) => hasLineGeometry(f.geometry)).length
: 0,
[atlasLayer],
);
// Segment length rides the deferred lane like the filter: re-segmenting a
// long line on every keystroke would jank the input.
const deferredSegmentKm = useDeferredValue(atlasSegmentKm);
const atlasPages = useMemo(
() =>
atlasCoverage === "line"
? atlasLayer?.geojson
? buildLineAtlasPages(atlasLayer.geojson, {
segmentKm: Number(deferredSegmentKm),
nameField: atlasNameField || undefined,
filter: atlasFilterPredicate ?? undefined,
})
: []
: buildAtlasPages(atlasFeatureInfos, {
nameField: atlasNameField || undefined,
sortField: atlasSortField || undefined,
sortDescending: atlasSortDescending,
filter: atlasFilterPredicate ?? undefined,
}),
[
atlasCoverage,
atlasLayer,
deferredSegmentKm,
atlasFeatureInfos,
atlasNameField,
atlasSortField,
atlasSortDescending,
atlasFilterPredicate,
],
);
const atlasPageCount = atlasPages.length;
// Order + membership signature of the series: changes when sorting or
// filtering reshuffles which feature sits at each page, but not when only
// the display names do (a name-field switch must not re-drive the map).
const atlasDriveKey = useMemo(() => atlasPages.map((p) => p.sourceIndex).join(","), [atlasPages]);
// The stored index can go stale when a filter/sort change shrinks the list.
const clampedAtlasIndex = Math.min(atlasIndex, Math.max(0, atlasPageCount - 1));
const currentAtlasPage = atlasEnabled ? (atlasPages[clampedAtlasIndex] ?? null) : null;
const atlasActive = atlasEnabled && atlasPageCount > 0;
atlasActiveRef.current = atlasActive;
const atlasFilterValid = atlasFilterPredicate !== null;
const atlasScaleValid = atlasExtentMode !== "scale" || Number(atlasScale) > 0;
// A floor (not just > 0) keeps a mistyped tiny length from cutting a long
// line into an enormous synchronous page list.
const atlasSegmentValid = atlasCoverage !== "line" || Number(atlasSegmentKm) >= 0.1;
// atlasPages is built from the *deferred* filter/segment values; block the
// export while an edit is still catching up so a quick click can never
// export the previous configuration's pages.
const atlasDeferredPending =
atlasFilter !== deferredAtlasFilter ||
(atlasCoverage === "line" && atlasSegmentKm !== deferredSegmentKm);
// A visible-but-invalid filter, a blank fixed scale, or a blank segment
// length must block the export: proceeding would silently export all
// features / arbitrary extents while the user is looking at an error.
const atlasConfigBlocked =
atlasEnabled &&
(!atlasFilterValid || !atlasScaleValid || !atlasSegmentValid || atlasDeferredPending);
const atlasTokenCtx = useMemo<AtlasTokenContext | null>(
() =>
currentAtlasPage
? {
name: currentAtlasPage.name,
pageNumber: clampedAtlasIndex + 1,
total: atlasPageCount,
properties: currentAtlasPage.properties,
}
: null,
[currentAtlasPage, clampedAtlasIndex, atlasPageCount],
);
// ---- Data blocks: attribute table + chart on the page (GH #1324) ----
// Any layer with loaded features qualifies (the same eligibility as an atlas
// coverage layer: the extent filter needs per-feature geometry).
const tableLayer = useMemo(
() => atlasLayers.find((l) => l.id === tableLayerId) ?? null,
[atlasLayers, tableLayerId],
);
const chartLayer = useMemo(
() => atlasLayers.find((l) => l.id === chartLayerId) ?? null,
[atlasLayers, chartLayerId],
);
const tableFields = useMemo(
() => (tableLayer?.geojson ? listAtlasFields(tableLayer.geojson.features) : []),
[tableLayer],
);
const chartFields = useMemo(
() => (chartLayer?.geojson ? listAtlasFields(chartLayer.geojson.features) : []),
[chartLayer],
);
const tableAllRows = useMemo(
() => (tableLayer?.geojson ? layerRows(tableLayer.geojson) : []),
[tableLayer],
);
const chartAllRows = useMemo(
() => (chartLayer?.geojson ? layerRows(chartLayer.geojson) : []),
[chartLayer],
);
// Per-feature bounds for the page-extent filter, walked once per layer so
// stepping/exporting an N-page atlas does not redo the vertex walk N times
// (the same precompute pattern the atlas page builder uses).
const tableFeatureInfos = useMemo(
() => (tableLayer?.geojson ? collectAtlasFeatures(tableLayer.geojson) : []),
[tableLayer],
);
const chartFeatureInfos = useMemo(
() => (chartLayer?.geojson ? collectAtlasFeatures(chartLayer.geojson) : []),
[chartLayer],
);
const chartCategoricalFields = useMemo(
() => categoricalColumns(chartAllRows, chartFields),
[chartAllRows, chartFields],
);
const chartNumericFields = useMemo(
() => numericColumns(chartAllRows, chartFields),
[chartAllRows, chartFields],
);
// Category options prefer detected low-cardinality fields but fall back to
// every field, so an unusual layer can still be charted.
const chartCategoryOptions =
chartCategoricalFields.length > 0 ? chartCategoricalFields : chartFields;
// Effective selections: the first suitable field stands in until the user
// picks one, so enabling a block gives instant feedback.
const effectiveCategoryField =
chartCategoryField && chartFields.includes(chartCategoryField)
? chartCategoryField
: (chartCategoryOptions[0] ?? "");
const effectiveValueField =
chartValueField && chartNumericFields.includes(chartValueField)
? chartValueField
: (chartNumericFields[0] ?? "");
const chartNeedsValueField = chartType === "line" || chartAggregation !== "count";
const effectiveTableColumns = useMemo(() => {
const chosen = tableColumns.filter((c) => tableFields.includes(c));
return chosen.length > 0 ? chosen : tableFields.slice(0, DEFAULT_TABLE_COLUMNS);
}, [tableColumns, tableFields]);
// Margin applied when fitting an atlas page's bounds, shared by the real
// fit in captureAtlasPage and the pre-capture approximation below so the
// two can never desync (fixed-scale mode fits tight and re-zooms after).
const atlasFitMarginPct = atlasExtentMode === "margin" ? atlasMarginPct : 0;
// The extent a data block's "only features on the page" filter tests
// against, before the page's real capture is available: the atlas page's
// fitted bounds, or the drawn print extent when that is what the capture
// clips to. Plain viewport captures don't filter. Once a page has actually
// been captured, the map's true visible bounds override this approximation
// (the viewBounds handed to rowsForBlock/buildBlocksFromRows) — the fit
// expands the box on one axis for the page aspect, and fixed-scale mode
// re-zooms after fitting.
const dataFilterBounds = useCallback(
(page: AtlasPage | null): AtlasBounds | null => {
if (page) return expandBounds(page.bounds, atlasFitMarginPct);
if (captureMode === "extent" && extentBbox) return extentBbox;
return null;
},
[atlasFitMarginPct, captureMode, extentBbox],
);