-
-
Notifications
You must be signed in to change notification settings - Fork 628
Expand file tree
/
Copy pathDesktopShell.tsx
More file actions
2623 lines (2532 loc) · 114 KB
/
Copy pathDesktopShell.tsx
File metadata and controls
2623 lines (2532 loc) · 114 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
// @refresh reset
import { useAppStore, type GeoLibreLayer } from "@geolibre/core";
import type { FeatureCollection } from "geojson";
import type { MapController, MapDiagnosticEvent } from "@geolibre/map";
import { MapCanvas, setExternalDeckLayerOrderHandler } from "@geolibre/map";
import { useTranslation } from "react-i18next";
import {
addRasterToMap,
prepareRasterControl,
applyRasterLayerOrder,
DECK_VIZ_PLUGIN_ID,
DIRECTIONS_PLUGIN_ID,
EFFECTS_PLUGIN_ID,
endLayerGeometryEdit,
GEO_EDITOR_PLUGIN_ID,
getGeometryEditTargetLayerId,
openRasterLayerPanel,
getRightPanel,
restoreDeckViz,
restoreDirections,
restoreReverseGeocode,
REVERSE_GEOCODE_PLUGIN_ID,
restoreEffects,
restoreLidarLayers,
restorePlanetaryComputerLayers,
reattachSun,
reattachRouteAnimation,
reattachFlightSimulator,
restoreRasterLayers,
restoreThreeDTilesLayers,
restoreVectorLayers,
setBookmarkLabels,
setLocalRasterFileReader,
setLocalRasterPicker,
setNonTiledRasterHandler,
setKmlFileImportHandler,
setTerrainMeasureLabels,
setViewStateLabels,
startLayerGeometryEdit,
subscribeGeometryEdit,
TIME_SLIDER_PLUGIN_ID,
VIEWER_BLOCKED_PLUGIN_IDS,
} from "@geolibre/plugins";
import { convertGeoTiffToCog, isTiff, readGeoTiffInfo } from "@geolibre/processing";
import {
type CSSProperties,
type DragEvent,
type PointerEvent as ReactPointerEvent,
lazy,
Suspense,
useCallback,
useEffect,
useRef,
useState,
useSyncExternalStore,
} from "react";
import { createPortal } from "react-dom";
import { BROWSER_PANEL_ID, useRegisterBrowserPanel } from "../../hooks/useRegisterBrowserPanel";
import { COMMENTS_PANEL_ID, useRegisterCommentsPanel } from "../../hooks/useRegisterCommentsPanel";
import { CommentsPanel } from "../comments/CommentsPanel";
import { CommentMapOverlay } from "../comments/CommentMapOverlay";
import { useCommentTool } from "../comments/useCommentTool";
import { AddCommentDialog } from "../comments/AddCommentDialog";
import { openRightPanel } from "@geolibre/plugins";
import { getIsMobileViewport } from "../../hooks/useIsMobileViewport";
import { useProjectFileActions } from "../../hooks/useProjectFileActions";
import { useProjectHistory } from "../../hooks/useProjectHistory";
import {
isRasterFileName,
isTauri,
loadDroppedPhotoFiles,
loadDroppedPhotoPaths,
loadDroppedRasterFiles,
loadDroppedRasterPaths,
pickLocalRasterFiles,
readRasterFileAtPath,
isLoadedImageOverlay,
isLoadedKmlSuperOverlay,
isLoadedModel,
loadDroppedVectorFiles,
loadDroppedVectorPaths,
type DroppedRaster,
} from "../../lib/tauri-io";
import { buildKmlModelLayer } from "../../lib/kml-model-layer";
import { isPhotoDropFileName, type GeotaggedPhotoResult } from "../../lib/geotagged-photos";
import type { LargeVectorDataset } from "../../lib/duckdb-vector-guard";
import { PANEL_RESIZE_END_EVENT, PANEL_RESIZE_START_EVENT } from "../../lib/panel-resize";
import i18n from "../../i18n";
import {
addOsmPbfLayers,
isOsmPbfFileName,
loadOsmPbf,
osmPbfBaseName,
OsmPbfTooLargeError,
OSM_PBF_SIZE_WARN_BYTES,
} from "../../lib/osm-pbf-loader";
import { restoreLocalFileLayers } from "../../lib/restore-local-layers";
import {
createAppAPI,
getPluginManager,
useExternalPluginsReady,
usePluginRegistry,
useProjectPluginTrust,
useSwipeSplitViewExclusivity,
useTimeSliderAutoClose,
} from "../../hooks/usePlugins";
import { registerKmlSuperOverlayProtocol } from "../../lib/kml-super-overlay";
import { registerMbtilesProtocol } from "../../lib/mbtiles";
import { hasReverseGeocodeConsent } from "../../lib/reverse-geocode-consent";
import { hasKnowledgeCardConsent, recordKnowledgeCardConsent } from "../../lib/knowledge-consent";
import { wikipediaLang } from "../../lib/knowledge";
import { registerXyzTileProtocol } from "../../lib/xyz-url";
import { useEmbedBridge } from "../../hooks/useEmbedBridge";
import { useRasterIdentify } from "../../hooks/useRasterIdentify";
import {
useAutoCollapsedPanel,
useReplaceLayersPanelId,
useReplaceStylePanelId,
useRightPanelState,
} from "../../hooks/useRightPanels";
import { BoundsRestrictionIndicator } from "./BoundsRestrictionIndicator";
import { CollaborationStatusBadge } from "./CollaborationStatusBadge";
import { CollaborateDialog } from "./CollaborateDialog";
import { useCollaboration } from "../../hooks/useCollaboration";
import { MapModeBanner } from "./MapModeBanner";
import { QuickAnalysisBanner } from "./QuickAnalysisBanner";
import { PixelTimeSeriesControl } from "./PixelTimeSeriesControl";
import { MapLegendPanel } from "../legend/MapLegendPanel";
import { RasterSubsetPanel } from "./RasterSubsetPanel";
import { BasemapExtractPanel } from "./BasemapExtractPanel";
import { TerrainSettingsDialog } from "./TerrainSettingsDialog";
import { MapContextMenu } from "./MapContextMenu";
import { KnowledgeCardPanel, type KnowledgePlace } from "./KnowledgeCardPanel";
import { KnowledgeCardConsentDialog } from "./KnowledgeCardConsentDialog";
import { MapGrid } from "./MapGrid";
import { RemoteCursorsOverlay } from "./RemoteCursorsOverlay";
import { useCommandBridge } from "../../hooks/useCommandBridge";
import { useEmbedApi } from "../../hooks/useEmbedApi";
import { useJupyterRelay } from "../../hooks/useJupyterRelay";
import { appendDiagnostic, useDiagnosticsSnapshot } from "../../lib/diagnostics";
import { SectionErrorBoundary, SilentErrorBoundary } from "../common/error-boundaries";
import { AttributeTable } from "../panels/AttributeTable";
import { RasterAttributeTable } from "../panels/RasterAttributeTable";
import { BrowserPanel } from "../panels/BrowserPanel";
import { LayerPanel } from "../panels/LayerPanel";
import { ViewerLayerPanel } from "../panels/ViewerLayerPanel";
import { FloatingPanels } from "../panels/FloatingPanels";
import { SunPanel } from "../panels/SunPanel";
import { RouteAnimationPanel } from "../panels/RouteAnimationPanel";
import { FlightSimulatorPanel } from "../panels/FlightSimulatorPanel";
import {
PluginRightPanel,
PLUGIN_PANEL_DEFAULT_WIDTH,
clampPluginPanelWidth,
} from "../panels/PluginRightPanel";
import { StylePanel } from "../panels/StylePanel";
import { SharedSidebar } from "../panels/SharedSidebar";
import { Layers, SlidersHorizontal } from "lucide-react";
import { StoryMapComposeBar } from "../storymap/StoryMapComposeBar";
import { StoryMapPanel } from "../storymap/StoryMapPanel";
import { StoryMapPresenter } from "../storymap/StoryMapPresenter";
import { DiagnosticsDialog } from "./DiagnosticsDialog";
import { FileNamePromptDialog } from "./FileNamePromptDialog";
import { ProjectPluginTrustDialog } from "./ProjectPluginTrustDialog";
import { ProjectHistoryDialog } from "./ProjectHistoryDialog";
import { ProjectRecoveryDialog } from "./ProjectRecoveryDialog";
import { StatusBar } from "./StatusBar";
import { TopToolbar } from "./TopToolbar";
import type { LayoutOptions } from "../../hooks/useLayoutOptions";
import type { ThemeMode } from "../../hooks/useThemeMode";
import type { ProjectUrlLoadState } from "../../hooks/useProjectUrlLoader";
/**
* Confirm loading a vector source whose feature count tripped the loader's
* large-dataset guard. Mirrors the OSM PBF drop guard's blocking
* `window.confirm` (see the handlers below): a `false` return aborts that one
* file's load without affecting the rest of a multi-file drop.
*/
/**
* Sample count (width × height × bands) above which in-browser COG conversion
* gets an extra "this may be slow / memory-intensive" confirmation. The
* converter reads the whole raster into memory as f64, so ~40M samples is
* roughly where the transient allocation starts to be felt.
*/
const LARGE_RASTER_SAMPLE_LIMIT = 40_000_000;
function confirmLargeVectorDataset({ name, featureCount }: LargeVectorDataset) {
return window.confirm(
i18n.t("toolbar.item.largeVectorDesc", {
name,
count: featureCount.toLocaleString(),
}),
);
}
const ProcessingDialog = lazy(() =>
import("../processing/ProcessingDialog")
.then((module) => ({
default: module.ProcessingDialog,
}))
.catch((error) => {
// A failed chunk load (network error, corrupted bundle) would otherwise
// throw during render and unmount the whole shell. Fall back to a
// no-op component so the rest of the app stays interactive.
console.error("Failed to load ProcessingDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/ProcessingDialog").ProcessingDialog;
return { default: Fallback };
}),
);
const ConversionDialog = lazy(() =>
import("../processing/ConversionDialog")
.then((module) => ({
default: module.ConversionDialog,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load ConversionDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/ConversionDialog").ConversionDialog;
return { default: Fallback };
}),
);
const StyleManagerPanel = lazy(() =>
import("../panels/StyleManagerPanel")
.then((module) => ({
default: module.StyleManagerPanel,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load StyleManagerPanel", error);
const Fallback = (() =>
null) as unknown as typeof import("../panels/StyleManagerPanel").StyleManagerPanel;
return { default: Fallback };
}),
);
const VectorToolsDialog = lazy(() =>
import("../processing/VectorToolsDialog")
.then((module) => ({
default: module.VectorToolsDialog,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load VectorToolsDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/VectorToolsDialog").VectorToolsDialog;
return { default: Fallback };
}),
);
const ModelBuilderDialog = lazy(() =>
import("../processing/ModelBuilderDialog")
.then((module) => ({
default: module.ModelBuilderDialog,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load ModelBuilderDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/ModelBuilderDialog").ModelBuilderDialog;
return { default: Fallback };
}),
);
const NetworkToolsDialog = lazy(() =>
import("../processing/NetworkToolsDialog")
.then((module) => ({
default: module.NetworkToolsDialog,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load NetworkToolsDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/NetworkToolsDialog").NetworkToolsDialog;
return { default: Fallback };
}),
);
const StatisticsToolsDialog = lazy(() =>
import("../processing/StatisticsToolsDialog")
.then((module) => ({
default: module.StatisticsToolsDialog,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load StatisticsToolsDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/StatisticsToolsDialog").StatisticsToolsDialog;
return { default: Fallback };
}),
);
const ProcessingHistoryDialog = lazy(() =>
import("../processing/ProcessingHistoryDialog")
.then((module) => ({
default: module.ProcessingHistoryDialog,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load ProcessingHistoryDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/ProcessingHistoryDialog").ProcessingHistoryDialog;
return { default: Fallback };
}),
);
const SelectByExpressionDialog = lazy(() =>
import("../selection/SelectByExpressionDialog")
.then((module) => ({
default: module.SelectByExpressionDialog,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load SelectByExpressionDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../selection/SelectByExpressionDialog").SelectByExpressionDialog;
return { default: Fallback };
}),
);
const SelectByLocationDialog = lazy(() =>
import("../selection/SelectByLocationDialog")
.then((module) => ({
default: module.SelectByLocationDialog,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load SelectByLocationDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../selection/SelectByLocationDialog").SelectByLocationDialog;
return { default: Fallback };
}),
);
const GeocodeDialog = lazy(() =>
import("../processing/GeocodeDialog")
.then((module) => ({
default: module.GeocodeDialog,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load GeocodeDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/GeocodeDialog").GeocodeDialog;
return { default: Fallback };
}),
);
const RasterToolsDialog = lazy(() =>
import("../processing/RasterToolsDialog")
.then((module) => ({
default: module.RasterToolsDialog,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load RasterToolsDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/RasterToolsDialog").RasterToolsDialog;
return { default: Fallback };
}),
);
const SegmentationDialog = lazy(() =>
import("../processing/SegmentationDialog")
.then((module) => ({
default: module.SegmentationDialog,
}))
.catch((error) => {
console.error("Failed to load SegmentationDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/SegmentationDialog").SegmentationDialog;
return { default: Fallback };
}),
);
const ObjectDetectionDialog = lazy(() =>
import("../processing/ObjectDetectionDialog")
.then((module) => ({
default: module.ObjectDetectionDialog,
}))
.catch((error) => {
console.error("Failed to load ObjectDetectionDialog", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/ObjectDetectionDialog").ObjectDetectionDialog;
return { default: Fallback };
}),
);
const SegmentEverythingPanel = lazy(() =>
import("../processing/SegmentEverythingPanel")
.then((module) => ({
default: module.SegmentEverythingPanel,
}))
.catch((error) => {
console.error("Failed to load SegmentEverythingPanel", error);
const Fallback = (() =>
null) as unknown as typeof import("../processing/SegmentEverythingPanel").SegmentEverythingPanel;
return { default: Fallback };
}),
);
const SqlWorkspacePanel = lazy(() =>
import("../panels/SqlWorkspacePanel")
.then((module) => ({
default: module.SqlWorkspacePanel,
}))
.catch((error) => {
// Same chunk-load fallback rationale as ProcessingDialog above.
console.error("Failed to load SqlWorkspacePanel", error);
const Fallback = (() =>
null) as unknown as typeof import("../panels/SqlWorkspacePanel").SqlWorkspacePanel;
return { default: Fallback };
}),
);
const NotebookPanel = lazy(() =>
import("../panels/NotebookPanel")
.then((module) => ({
default: module.NotebookPanel,
}))
.catch((error) => {
// Same chunk-load fallback rationale as the dialogs above.
console.error("Failed to load NotebookPanel", error);
const Fallback = (() =>
null) as unknown as typeof import("../panels/NotebookPanel").NotebookPanel;
return { default: Fallback };
}),
);
const AssistantPanel = lazy(() =>
import("../panels/AssistantPanel")
.then((module) => ({
default: module.AssistantPanel,
}))
.catch((error) => {
// Same chunk-load fallback rationale as the dialogs above.
console.error("Failed to load AssistantPanel", error);
const Fallback = (() =>
null) as unknown as typeof import("../panels/AssistantPanel").AssistantPanel;
return { default: Fallback };
}),
);
const DashboardPanel = lazy(() =>
import("../panels/DashboardPanel")
.then((module) => ({
default: module.DashboardPanel,
}))
.catch((error) => {
// Same chunk-load fallback rationale as the dialogs above.
console.error("Failed to load DashboardPanel", error);
const Fallback = (() =>
null) as unknown as typeof import("../panels/DashboardPanel").DashboardPanel;
return { default: Fallback };
}),
);
const PythonConsolePanel = lazy(() =>
import("../panels/PythonConsolePanel")
.then((module) => ({
default: module.PythonConsolePanel,
}))
.catch((error) => {
// Same chunk-load fallback rationale as the dialogs above.
console.error("Failed to load PythonConsolePanel", error);
const Fallback = (() =>
null) as unknown as typeof import("../panels/PythonConsolePanel").PythonConsolePanel;
return { default: Fallback };
}),
);
interface DesktopShellProps {
layoutOptions: LayoutOptions;
projectUrlLoadState?: ProjectUrlLoadState;
themeMode: ThemeMode;
onToggleThemeMode: () => void;
}
function hasDroppedFiles(event: DragEvent<HTMLElement>): boolean {
return Array.from(event.dataTransfer.types).includes("Files");
}
function fileNameFromPath(path: string): string {
return path.split(/[/\\]/).pop() ?? path;
}
function layerNameFromPath(path: string): string {
return fileNameFromPath(path).replace(/\.[^.]+$/, "") || "Vector Layer";
}
type ImportedVectorLayer = Awaited<ReturnType<typeof loadDroppedVectorFiles>>[number];
const DEFAULT_SIDE_PANEL_WIDTH = 320;
const MIN_SIDE_PANEL_WIDTH = 180;
const MAX_SIDE_PANEL_WIDTH = 560;
// Width of a side panel's collapsed rail (`md:w-11` = 2.75rem). The Style panel
// stays mounted (collapsed) beside the notebook, so its rail still occupies this
// much of the row when computing the map/notebook 50/50 split.
const COLLAPSED_PANEL_RAIL_WIDTH = 44;
// The notebook panel hosts a full Jupyter UI, so it needs far more room than
// the layer/style side panels.
const DEFAULT_NOTEBOOK_PANEL_WIDTH = 480;
const MIN_NOTEBOOK_PANEL_WIDTH = 320;
const MAX_NOTEBOOK_PANEL_WIDTH = 1100;
function clamp(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, value));
}
// Seed width for the Layers/Style side panels. The full default would let two
// open panels crowd out the map on narrow desktop windows (two 320px panels
// leave only 128px at the 768px `md` breakpoint), so cap the initial width at
// ~30% of the viewport. The cap only lowers the width below ~1067px (where 30%
// of the viewport drops under the default); wider windows get the full default.
// Users can still drag up to MAX_SIDE_PANEL_WIDTH either way.
function initialSidePanelWidth(): number {
if (typeof window === "undefined") return DEFAULT_SIDE_PANEL_WIDTH;
const cap = Math.round(window.innerWidth * 0.3);
return clamp(cap, MIN_SIDE_PANEL_WIDTH, DEFAULT_SIDE_PANEL_WIDTH);
}
type ShellStyle = CSSProperties &
Record<"--layer-panel-width" | "--style-panel-width" | "--notebook-panel-width", string>;
export function DesktopShell({
layoutOptions,
projectUrlLoadState,
themeMode,
onToggleThemeMode,
}: DesktopShellProps) {
const { t } = useTranslation();
const shellRef = useRef<HTMLDivElement>(null);
const verticalResizeGuideRef = useRef<HTMLDivElement>(null);
// Push the translated bookmark labels into the framework-agnostic plugins
// package (which can't call t() itself). Done here rather than in TopToolbar
// so it still applies when the toolbar is hidden (e.g. `?maponly`), where the
// BookmarkControl overlay is still present.
useEffect(() => {
setBookmarkLabels({
captureStateLabel: t("bookmark.captureStateLabel"),
captureStateTooltip: t("bookmark.captureStateTooltip"),
exportLabel: t("bookmark.export"),
exportSelectedLabel: t("bookmark.exportSelected"),
exportAllLabel: t("bookmark.exportAll"),
newFolderLabel: t("bookmark.newFolder"),
defaultFolderName: t("bookmark.defaultFolderName"),
});
setViewStateLabels({ title: t("viewState.panelTitle") });
setTerrainMeasureLabels({
title: t("terrainMeasure.title"),
surfaceDistance: t("terrainMeasure.surfaceDistance"),
surfaceArea: t("terrainMeasure.surfaceArea"),
elevationGainLoss: t("terrainMeasure.elevationGainLoss"),
elevationRange: t("terrainMeasure.elevationRange"),
meanSlope: t("terrainMeasure.meanSlope"),
computing: t("terrainMeasure.computing"),
partialData: t("terrainMeasure.partialData"),
});
}, [t]);
// The map's Fullscreen control maximizes the map *canvas* (it calls
// requestFullscreen on the map container). Chromium promotes that element to
// the browser top layer, so the toolbar and side panels are hidden for free.
// WebKit (the Tauri desktop webview) does not: it grows the map container to
// fill the window but leaves the surrounding chrome painted around and on top
// of it (opengeos/GeoLibre#611). Mirror the fullscreen state onto the shell as
// `data-map-fullscreen` so CSS can hide that chrome on every engine, leaving a
// clean map-only view. document.fullscreenElement is set even on WebKit.
useEffect(() => {
const shell = shellRef.current;
if (!shell) return;
const sync = () => {
const fsEl =
document.fullscreenElement ??
(document as Document & { webkitFullscreenElement?: Element | null })
.webkitFullscreenElement ??
null;
shell.toggleAttribute("data-map-fullscreen", !!fsEl && shell.contains(fsEl));
};
document.addEventListener("fullscreenchange", sync);
document.addEventListener("webkitfullscreenchange", sync);
sync();
return () => {
document.removeEventListener("fullscreenchange", sync);
document.removeEventListener("webkitfullscreenchange", sync);
};
}, []);
// Teardown for an in-progress panel resize, so a pointercancel or an unmount
// mid-drag still detaches the global listeners and restores document.body.
const activeResizeCleanupRef = useRef<(() => void) | null>(null);
useEffect(() => () => activeResizeCleanupRef.current?.(), []);
const mapControllerRef = useRef<MapController | null>(null);
const projectHistory = useProjectHistory(mapControllerRef);
const [projectHistoryOpen, setProjectHistoryOpen] = useState(false);
// The place shown in the Wikipedia knowledge card, or null when it is closed.
// `pendingKnowledgePlace` holds the target while the one-time consent notice
// is open, so it can be applied only after the user acknowledges it.
const [knowledgePlace, setKnowledgePlace] = useState<KnowledgePlace | null>(null);
const [pendingKnowledgePlace, setPendingKnowledgePlace] = useState<KnowledgePlace | null>(null);
const [knowledgeNoticeOpen, setKnowledgeNoticeOpen] = useState(false);
// Open a knowledge card for a clicked point, gating the first lookup behind a
// one-time privacy notice since it sends the coordinate to Wikipedia.
const handleExplorePlace = useCallback((lat: number, lng: number) => {
if (hasKnowledgeCardConsent()) {
setKnowledgePlace({ lat, lng });
} else {
setPendingKnowledgePlace({ lat, lng });
setKnowledgeNoticeOpen(true);
}
}, []);
const confirmKnowledgeConsent = useCallback(() => {
recordKnowledgeCardConsent();
setKnowledgeNoticeOpen(false);
setKnowledgePlace(pendingKnowledgePlace);
setPendingKnowledgePlace(null);
}, [pendingKnowledgePlace]);
// Stable identity (mapControllerRef is a ref) so the card's openNearby
// useCallback, which depends on this, keeps its memoization across renders.
const handleKnowledgeFlyTo = useCallback((lat: number, lon: number) => {
mapControllerRef.current?.flyTo({
center: [lon, lat],
zoom: Math.max(mapControllerRef.current?.getMap()?.getZoom() ?? 12, 14),
});
}, []);
// The COG/WMS/XYZ layer whose bounding-box subset is being extracted in the
// floating Extract Subset panel, or null when that panel is closed.
const [rasterSubsetLayer, setRasterSubsetLayer] = useState<GeoLibreLayer | null>(null);
// Whether that layer still exists in the store; subscribe to the derived
// boolean (not the whole layers array) so this large component only re-renders
// when it flips. Close the panel if its layer is removed, matching how
// LayerPanel clears its own per-layer dialog state.
const rasterSubsetLayerExists = useAppStore((s) =>
rasterSubsetLayer ? s.layers.some((layer) => layer.id === rasterSubsetLayer.id) : true,
);
useEffect(() => {
if (rasterSubsetLayer && !rasterSubsetLayerExists) {
setRasterSubsetLayer(null);
}
}, [rasterSubsetLayer, rasterSubsetLayerExists]);
// The Offline Basemap Extract panel is a non-modal floating panel over the
// map (so the map stays interactive for drawing a bbox), mounted here beside
// the Raster Subset panel and opened from the Add Data menu in the toolbar.
const [basemapExtractOpen, setBasemapExtractOpen] = useState(false);
const dragDepthRef = useRef(0);
const dropMessageTimeoutRef = useRef<number | null>(null);
const materializingRef = useRef(false);
const togglingGeometryEditRef = useRef(false);
const addGeoJsonLayer = useAppStore((s) => s.addGeoJsonLayer);
const addImageOverlayLayer = useAppStore((s) => s.addImageOverlayLayer);
const addTileLayer = useAppStore((s) => s.addTileLayer);
const addLayerGroup = useAppStore((s) => s.addLayerGroup);
const { isActive: isPluginActive, toggle: togglePlugin } = usePluginRegistry();
const addLayer = useAppStore((s) => s.addLayer);
const projectGeneration = useAppStore((s) => s.projectGeneration);
const pythonConsoleOpen = useAppStore((s) => s.ui.pythonConsoleOpen);
const setPythonConsoleOpen = useAppStore((s) => s.setPythonConsoleOpen);
const sqlWorkspaceOpen = useAppStore((s) => s.ui.sqlWorkspaceOpen);
const setSqlWorkspaceOpen = useAppStore((s) => s.setSqlWorkspaceOpen);
// Register the Browser as a movable/dockable right panel; its body is portaled
// into a dedicated content host (below) that the dock slots adopt.
useRegisterBrowserPanel();
useRegisterCommentsPanel();
// One shared project-file-actions instance for both the toolbar and the
// Browser panel, so their "open recent" calls coordinate their aborts (two
// instances would race). Lifted here for the same reason as `collaboration`.
const projectFiles = useProjectFileActions(mapControllerRef);
const notebookOpen = useAppStore((s) => s.ui.notebookOpen);
const storymapPresenting = useAppStore((s) => s.ui.storymapPresenting);
// A plugin panel docks at one of four positions beside the Layers/Style
// panels and the user steps it between them; the built-in panel on the docked
// side collapses to its rail while the plugin panel is expanded next to it
// (issue #712). The panel's width is owned here (per app instance) and shared
// across the dock slots, so a user resize survives moving the panel without a
// module-level global (which would leak across embeds).
const autoCollapsedPanel = useAutoCollapsedPanel();
// When set, a plugin panel is docked in a shared-rail mode and takes over the
// Style (right) or Layers (left) sidebar surface (issue #765).
const replaceStylePanelId = useReplaceStylePanelId();
const replaceLayersPanelId = useReplaceLayersPanelId();
const [pluginPanelWidth, setPluginPanelWidth] = useState(PLUGIN_PANEL_DEFAULT_WIDTH);
// The active plugin panel's content lives in this one host element (created
// once per app instance). The active dock slot adopts it via appendChild, so
// moving the panel between docks relocates the same DOM and preserves the
// plugin's state. `contents` keeps it transparent to layout.
const [pluginContentEl] = useState(() => {
const el = document.createElement("div");
el.className = "contents";
return el;
});
// A second, dedicated host for the Browser panel's React portal (below). Kept
// separate from pluginContentEl so the imperative plugin-render effect's
// `replaceChildren` can never wipe the portal-managed DOM, and vice versa.
const [browserContentEl] = useState(() => {
const el = document.createElement("div");
el.className = "contents";
return el;
});
// A third, dedicated host for the Comments panel's React portal.
const [commentsContentEl] = useState(() => {
const el = document.createElement("div");
el.className = "contents";
return el;
});
const rightPanelState = useRightPanelState();
const activePanelId = rightPanelState.activeId;
const replaceStylePanelIds = rightPanelState.visibleIds.filter(
(id) => rightPanelState.panelDocks[id] === "replace-style",
);
const replaceLayersPanelIds = rightPanelState.visibleIds.filter(
(id) => rightPanelState.panelDocks[id] === "replace-layers",
);
const activePanel = activePanelId ? getRightPanel(activePanelId) : undefined;
// The plugins in VIEWER_BLOCKED_PLUGIN_IDS paint drawing and editing controls
// onto the map, which the read-only viewer preset cannot hide the way it
// hides React chrome, so they are deactivated outright. This has to run more
// than once: `restoreProjectState` activates whatever a loaded project lists
// in `projectPlugins.activePluginIds` with no viewer awareness, so every
// project load — the initial `?url=` one and any later `loadProject` embed
// command — can put them back. It is a callback rather than an effect of its
// own so the restore effect below can re-assert it *after* restoring, which
// effect ordering alone would not guarantee.
const enforceViewerPlugins = useCallback(() => {
if (!layoutOptions.viewer) return;
const manager = getPluginManager();
for (const id of VIEWER_BLOCKED_PLUGIN_IDS) {
if (!manager.isActive(id)) continue;
// `isActive` is true from the moment activation starts, so a plugin that
// mounts behind a dynamic import (GeoAgent) is "active" with no control
// yet: deactivating now would tear down nothing and the mount would land
// straight after. Wait for it, then re-check — a failed mount rolls the
// active flag back on its own, so there is nothing left to do.
const pending = manager.pendingActivation(id);
if (pending) {
void pending.then(() => {
if (manager.isActive(id)) manager.deactivate(id, createAppAPI(mapControllerRef));
});
continue;
}
manager.deactivate(id, createAppAPI(mapControllerRef));
}
}, [layoutOptions.viewer, mapControllerRef]);
useEffect(() => {
enforceViewerPlugins();
}, [enforceViewerPlugins]);
// The dock slots adopt whichever host owns the active panel's content: the
// Browser's dedicated portal host, the Comments dedicated portal host, or the shared imperative plugin host.
const dockContentEl =
activePanelId === BROWSER_PANEL_ID
? browserContentEl
: activePanelId === COMMENTS_PANEL_ID
? commentsContentEl
: pluginContentEl;
// Render the active panel into the shared host once; re-run when its
// registration is replaced (re-registration refresh) but not on dock/collapse
// changes. Keyed on the render function identity so that a plugin
// re-registering the same id with a new render function tears down the old
// render and calls the new one, but title resolution (which returns a new
// object each call) does not cause spurious re-runs.
useEffect(() => {
const host = pluginContentEl;
if (layoutOptions.viewer) {
host.replaceChildren();
return;
}
if (!activePanelId || !activePanel) return;
let cleanup: void | (() => void);
try {
cleanup = activePanel.render(host);
} catch (error) {
console.error(`Right panel "${activePanelId}" render() threw.`, error);
}
return () => {
try {
cleanup?.();
} catch (error) {
console.error(`Right panel "${activePanelId}" cleanup threw.`, error);
}
host.replaceChildren();
};
// `activePanel` is intentionally narrowed to `activePanel?.render`:
// getRightPanel returns a fresh clone each call, so the whole object would
// re-run this effect on every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activePanelId, activePanel?.render, layoutOptions.viewer, pluginContentEl]);
// Reset the shared width to the panel's default when a new panel activates
// (keyed on activePanelId only, so a user resize survives re-registration).
useEffect(() => {
const panel = activePanelId ? getRightPanel(activePanelId) : undefined;
if (!panel) return;
setPluginPanelWidth(clampPluginPanelWidth(panel.defaultWidth ?? PLUGIN_PANEL_DEFAULT_WIDTH));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activePanelId]);
const assistantOpen = useAppStore((s) => s.ui.assistantOpen);
const dashboardOpen = useAppStore((s) => s.ui.dashboardOpen);
const geometryEditLayerId = useSyncExternalStore(
subscribeGeometryEdit,
getGeometryEditTargetLayerId,
);
const [isDraggingFiles, setIsDraggingFiles] = useState(false);
const [mapReadyGeneration, setMapReadyGeneration] = useState(0);
const [dropMessage, setDropMessage] = useState<string | null>(null);
const [dropError, setDropError] = useState<string | null>(null);
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
const diagnostics = useDiagnosticsSnapshot();
const externalPluginsReady = useExternalPluginsReady(mapControllerRef);
// Gate plugin URLs carried inside an opened project behind an explicit trust
// decision before any of their code is fetched or imported (#1062).
const projectPluginTrust = useProjectPluginTrust();
// Keep Layer Swipe and split view mutually exclusive (#844): entering a
// multi-pane grid turns the swipe slider off.
useSwipeSplitViewExclusivity(mapControllerRef);
// Close a binding-opened Time Slider once the last temporal layer is gone
// (#1512), so the dock does not linger over a map with no timeline.
useTimeSliderAutoClose(mapControllerRef);
// Live-collaboration session. Owned here (rather than in TopToolbar) so both
// the Collaborate dialog and the on-canvas status badge share one socket, and
// so the dialog stays mounted in toolbar-hidden layouts.
const collaboration = useCollaboration(mapControllerRef);
const commentTool = useCommentTool({ mapControllerRef, collaboration });
const [showResolvedComments, setShowResolvedComments] = useState(false);
const collaborateDialogOpen = useAppStore((s) => s.ui.collaborateDialogOpen);
const setCollaborateDialogOpen = useAppStore((s) => s.setCollaborateDialogOpen);
// When opened via a `?collab=<code>` share link, auto-open the Collaborate
// dialog (which prefills the code) so the recipient only picks a name and
// joins, instead of having to find the Project menu first.
useEffect(() => {
if (!collaboration.enabled) return;
if (new URLSearchParams(window.location.search).get("collab")) {
setCollaborateDialogOpen(true);
}
}, [collaboration.enabled, setCollaborateDialogOpen]);
// Sync the project with an embedding host (the GeoLibre Jupyter widget) over
// postMessage. Inert when the app is not embedded.
useEmbedBridge(mapControllerRef);
// Request/reply + event channel backing the Python scripting API (live
// queries, processing, map events). Also inert when not embedded.
useCommandBridge(mapControllerRef);
// Runtime postMessage API for a third-party host page that frames the app
// (fly to a record, highlight it, open a tool; selection/view/tool events back
// out). Off unless the deployment configured GEOLIBRE_EMBED_ORIGINS.
useEmbedApi(mapControllerRef);
// Same scripting surface, reached over the desktop Jupyter server's relay, so
// a kernel driven from an EXTERNAL client (VS Code's Jupyter extension) can
// control the map too. Inert until that server is running.
useJupyterRelay(mapControllerRef);
// Routes the Layers-panel Identify action to the raster pixel inspector for
// COG layers (read band values on click). Inert until a COG is identified.
useRasterIdentify();
const [layerPanelWidth, setLayerPanelWidth] = useState(initialSidePanelWidth);
const [stylePanelWidth, setStylePanelWidth] = useState(initialSidePanelWidth);
const [notebookPanelWidth, setNotebookPanelWidth] = useState(DEFAULT_NOTEBOOK_PANEL_WIDTH);
// Opening the notebook (Processing → Jupyter Notebook) splits the workspace
// 50/50 between the map and the notebook: we size the notebook to half of the
// space it shares with the map (the row width minus the layer panel and the
// Style panel's collapsed rail, when shown), while the Style panel collapses
// to that rail (see `autoCollapse` below). Fire only on the closed→open
// transition so a later manual resize is preserved.
const notebookWasOpenRef = useRef(notebookOpen);
useEffect(() => {
const wasOpen = notebookWasOpenRef.current;
notebookWasOpenRef.current = notebookOpen;
if (!notebookOpen || wasOpen) return;
const shellWidth = shellRef.current?.getBoundingClientRect().width ?? 0;
if (shellWidth <= 0) return;
const layerWidth = layoutOptions.layerPanelVisible ? layerPanelWidth : 0;
const styleRailWidth = layoutOptions.stylePanelVisible ? COLLAPSED_PANEL_RAIL_WIDTH : 0;
const half = Math.round((shellWidth - layerWidth - styleRailWidth) / 2);
// Honor the same min/max bounds as the drag-resize handler so the auto-size
// and manual-resize paths cannot diverge (an ultrawide shell would otherwise
// initialize past MAX, a width the user could never drag back to).
setNotebookPanelWidth(clamp(half, MIN_NOTEBOOK_PANEL_WIDTH, MAX_NOTEBOOK_PANEL_WIDTH));
}, [
notebookOpen,
layoutOptions.layerPanelVisible,
layoutOptions.stylePanelVisible,
layerPanelWidth,
]);
const deferPanelResize = isTauri();
const shellStyle: ShellStyle = {
"--layer-panel-width": `${layerPanelWidth}px`,
"--style-panel-width": `${stylePanelWidth}px`,
"--notebook-panel-width": `${notebookPanelWidth}px`,
};
const clearDropMessageLater = useCallback(() => {
if (dropMessageTimeoutRef.current !== null) {
window.clearTimeout(dropMessageTimeoutRef.current);
}
dropMessageTimeoutRef.current = window.setTimeout(() => {
dropMessageTimeoutRef.current = null;
setDropMessage(null);
setDropError(null);
}, 4000);
}, []);
const ensureLayerGeojsonFromSource = useCallback(async (layerId: string) => {
const layer = useAppStore.getState().layers.find((candidate) => candidate.id === layerId);
if (!layer || layer.geojson) return;
const sourceIds = layer.metadata.sourceIds;
const sourceId = Array.isArray(sourceIds) ? sourceIds[0] : undefined;
if (typeof sourceId !== "string") return;
const source = mapControllerRef.current?.getMap()?.getSource(sourceId) as
| { getData?: () => Promise<unknown> }
| undefined;
if (!source || typeof source.getData !== "function") return;
try {
const data = await source.getData();
if (
data &&
typeof data === "object" &&
(data as { type?: string }).type === "FeatureCollection"
) {
useAppStore.getState().updateLayer(layerId, { geojson: data as FeatureCollection });
}
} catch {
// Best effort; startLayerGeometryEdit will fail and surface an error.
}
}, []);
const handleToggleGeometryEdit = useCallback(
async (layerId: string) => {
const appAPI = createAppAPI(mapControllerRef);
if (getGeometryEditTargetLayerId() === layerId) {
await endLayerGeometryEdit(appAPI, { save: true });
return;
}
// Guard against concurrent invocations: this handler awaits before it sets
// the session target, so two rapid clicks could otherwise both pass the
// check above and race into startLayerGeometryEdit for different layers.
if (togglingGeometryEditRef.current) return;
togglingGeometryEditRef.current = true;
// Clear any stale error from a previous failed attempt.
setDropError(null);
try {
// Add Vector Layer (geojson-mode) layers keep their features in a
// MapLibre source rather than in `layer.geojson`. Read them back once so
// the editor has features to load. (Plain geojson layers already have
// `geojson`.)
await ensureLayerGeojsonFromSource(layerId);
const manager = getPluginManager();
if (!manager.isActive(GEO_EDITOR_PLUGIN_ID)) {
manager.activate(GEO_EDITOR_PLUGIN_ID, appAPI);
if (!manager.isActive(GEO_EDITOR_PLUGIN_ID)) {
setDropError(
"Could not activate the geometry editor. Try again once the map has fully loaded.",
);
clearDropMessageLater();
return;
}
}
const started = await startLayerGeometryEdit(appAPI, layerId);
if (!started) {
setDropError(
"Could not start geometry editing for this layer. Its data may still be loading.",
);
clearDropMessageLater();
}
} finally {
togglingGeometryEditRef.current = false;
}
},
[clearDropMessageLater, ensureLayerGeojsonFromSource],
);
const handleCancelGeometryEdit = useCallback(() => {
void endLayerGeometryEdit(createAppAPI(mapControllerRef), { save: false });
}, []);
const handleMaterializeDuckDBLayer = useCallback(
async (layer: GeoLibreLayer) => {
// Guard against concurrent triggers (double-click, or two layers in quick
// succession) so we do not add duplicate materialized layers.
if (materializingRef.current) return;
const query = typeof layer.metadata.query === "string" ? layer.metadata.query : null;
if (!query) {
setDropError("This DuckDB layer has no stored query to materialize.");
clearDropMessageLater();
return;
}
materializingRef.current = true;
setDropError(null);
setDropMessage("Materializing DuckDB layer...");
try {
// The query is the layer's own stored SQL from the user's project; it is
// intentionally run unrestricted against the in-memory DuckDB instance.
// Import the DuckDB-WASM engine lazily here, not at module load: a static
// import would pull the heavy `@duckdb/duckdb-wasm` chunk into the app's
// boot graph (DesktopShell is eagerly imported by App), which then has to
// load before the shell renders. That broke the offline cold boot — the
// chunk is runtime-cached, not precached, so a cache miss failed the boot
// and the map never mounted (see e2e/pwa.spec.ts). Loading it on first
// materialize keeps DuckDB out of the offline-critical boot path.
const { runSqlQuery } = await import("../../lib/sql-workspace");
const result = await runSqlQuery(query, useAppStore.getState().layers);
if (!result.geojson) {
throw new Error("The query did not return a geometry column.");
}