-
-
Notifications
You must be signed in to change notification settings - Fork 628
Expand file tree
/
Copy pathusePlugins.ts
More file actions
1487 lines (1423 loc) · 60.7 KB
/
Copy pathusePlugins.ts
File metadata and controls
1487 lines (1423 loc) · 60.7 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 {
clearExternalNativePaintBridge,
setExternalNativePaintBridge,
useAppStore,
} from "@geolibre/core";
import {
addRasterToMap,
addZarrRasterLayer,
buildSelectorTimeBinding,
queryZarrLayer,
registerTemporalLayer,
unregisterTemporalLayer,
isTimeSliderIdle,
TIME_SLIDER_PLUGIN_ID,
type TemporalLayerAdapter,
setZarrLayerSelector,
setZarrLocalStoreProvider,
maplibreAnnotationsPlugin,
maplibreBasemapControlPlugin,
maplibreComponentsPlugin,
maplibreDeckGlVizPlugin,
maplibreDirectionsPlugin,
maplibreElevationProfilePlugin,
maplibreEffectsPlugin,
getEffectsSettings,
setEffectsSettings,
type EffectsSettings,
maplibreEarthdataGisPlugin,
SKETCHES_SOURCE_KIND,
setEarthdataCogSaver,
maplibreEnviroAtlasPlugin,
maplibreEsriWaybackPlugin,
maplibreFemaWmsPlugin,
maplibreGeoAgentPlugin,
maplibreGeoEditorPlugin,
maplibreLayerControlPlugin,
maplibreNasaEarthdataPlugin,
maplibreNationalMapPlugin,
maplibreOpenAerialMapPlugin,
maplibreArcGisHubPlugin,
maplibreCkanPlugin,
maplibreSocrataPlugin,
maplibreStacCatalogsPlugin,
maplibreSourceCoopPlugin,
maplibreNaturalEarthPlugin,
maplibreHuggingFacePlugin,
maplibreGeoLensPlugin,
maplibreOvertureMapsPlugin,
queryOvertureFeatures,
maplibreGraticulePlugin,
maplibreH3Plugin,
maplibreS2Plugin,
maplibreA5Plugin,
maplibreDggridPlugin,
maplibreDggalPlugin,
maplibreOlcPlugin,
maplibreGeohashPlugin,
maplibreTilecodePlugin,
maplibreCloudsPlugin,
maplibrePrecipitationPlugin,
maplibreMapillaryPlugin,
maplibreReverseGeocodePlugin,
maplibreStreetViewPlugin,
maplibreSunPlugin,
maplibreRouteAnimationPlugin,
flightSimulatorPlugin,
maplibreSwipePlugin,
SWIPE_PLUGIN_ID,
maplibreTimelapsePlugin,
maplibreTimeSliderPlugin,
setTimelapseVideoSaver,
maplibreUsgsLidarPlugin,
PluginManager,
registerRightPanel,
unregisterRightPanel,
openRightPanel,
collapseRightPanel,
closeRightPanel,
getActiveRightPanel,
setActiveRightPanelDock,
getActiveRightPanelDock,
registerToolbarMenu,
unregisterToolbarMenu,
registerFloatingPanel,
unregisterFloatingPanel,
openFloatingPanel,
closeFloatingPanel,
getOpenFloatingPanels,
} from "@geolibre/plugins";
import type { MapController } from "@geolibre/map";
import type {
GeoLibreCogLayerOptions,
GeoLibreDeckGL,
GeoLibreExternalNativeLayerRegistration,
GeoLibreFileDialogOptions,
GeoLibreMapControlPosition,
GeoLibreSelection,
GeoLibreTileLayerOptions,
GeoLibreWmsLayerOptions,
GeoLibreZarrLayerOptions,
GeoLibreZarrQueryGeometry,
GeoLibreZarrQueryOptions,
GeoLibreZarrQuerySelector,
} from "@geolibre/plugins";
import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { readDir, readFile } from "@tauri-apps/plugin-fs";
import type { RefObject } from "react";
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { bundledPluginManifestPaths } from "virtual:bundled-plugins";
import {
installWebPluginArchive,
listInstalledWebPlugins,
loadExternalPlugins,
reloadExternalUrlPlugin,
resolvePluginAssetUrlForLoadedPlugin,
uninstallWebPlugin,
unloadFilesystemPlugin,
unloadRemovedUrlPlugins,
type InstalledWebPlugin,
} from "../lib/external-plugins";
import { appendDiagnostic } from "../lib/diagnostics";
import { pickZarrDirectory, zarrDirectoryPickerSupported } from "../lib/zarr-directory-picker";
import { openExternalLink } from "../lib/open-external";
import { fetchUrlBytes } from "../lib/native-http";
import {
dedupeVectorUrlFetch,
isBlockedUrlError,
vectorDownloadFileName,
} from "../lib/vector-url-fetch";
import { partitionProjectPluginManifestUrls } from "../lib/plugin-trust";
import { setTimeSliderOpenedByBinding, shouldCloseTimeSliderDock } from "../lib/time-slider-dock";
import { createWmsTileUrl, normalizeWmsVersion } from "../components/layout/add-data/helpers";
import { createExternalNativeStoreLayer } from "../lib/external-native-layer";
import { mergeStringLists } from "../lib/string-lists";
import {
browserSaveFallsBackToDownload,
openLocalDataFileWithFallback,
pickVectorFilesWithSidecars,
readVectorFileWithSidecars,
saveBinaryFileWithFallback,
saveTextFileWithFallback,
} from "../lib/tauri-io";
import { useDesktopSettingsStore } from "./useDesktopSettings";
import { ensureFileExtension, useFileNamePrompt } from "./useFileNamePrompt";
const RASTER_PROXY_PATH = "/__geolibre_raster_proxy";
/**
* Translate the public {@link GeoLibreTileLayerOptions} into the option bag
* passed straight to `store.addTileLayer(name, opts, ...)`, dropping
* `beforeLayerId` (which the store takes as a separate positional argument).
* The remaining keys mix source-level fields (tileSize, bounds, ...) and
* layer-level ones (visible, opacity); the store reads each by name.
*/
function tileLayerStoreOptions(options?: GeoLibreTileLayerOptions) {
if (!options) return {};
const { beforeLayerId: _beforeLayerId, ...rest } = options;
return rest;
}
/** Records a plugin failure in the diagnostics panel without crashing the app. */
function reportPluginError(pluginId: string, action: string, error: unknown): void {
const normalized = error instanceof Error ? error : new Error(String(error));
appendDiagnostic({
category: "runtime",
level: "error",
message: `Plugin "${pluginId}" failed to ${action}: ${normalized.message}`,
detail: normalized.stack,
source: `plugin:${pluginId}`,
});
}
interface TauriRuntimeWindow extends Window {
__TAURI_INTERNALS__?: unknown;
}
const manager = new PluginManager();
manager.registerAll([
maplibreLayerControlPlugin,
maplibreGeoEditorPlugin,
maplibreAnnotationsPlugin,
maplibreBasemapControlPlugin,
// The web service plugins (WEB_SERVICE_PLUGIN_IDS) are grouped into the
// "Web Services" submenu, rendered where the first of them appears in this
// order.
maplibreFemaWmsPlugin,
maplibreNasaEarthdataPlugin,
maplibreEnviroAtlasPlugin,
maplibreNationalMapPlugin,
maplibreEarthdataGisPlugin,
maplibreOpenAerialMapPlugin,
maplibreArcGisHubPlugin,
maplibreSocrataPlugin,
maplibreCkanPlugin,
maplibreStacCatalogsPlugin,
maplibreSourceCoopPlugin,
maplibreNaturalEarthPlugin,
maplibreHuggingFacePlugin,
maplibreGeoLensPlugin,
maplibreEsriWaybackPlugin,
maplibreTimeSliderPlugin,
maplibreTimelapsePlugin,
maplibreOvertureMapsPlugin,
maplibreGeoAgentPlugin,
maplibreUsgsLidarPlugin,
maplibreStreetViewPlugin,
maplibreMapillaryPlugin,
maplibreElevationProfilePlugin,
maplibreSwipePlugin,
maplibreGraticulePlugin,
// The DGGS grid plugins (grouped into the Plugins menu's "DGGS" submenu,
// rendered where the first of them appears in this order).
maplibreH3Plugin,
maplibreS2Plugin,
maplibreA5Plugin,
maplibreDggridPlugin,
maplibreDggalPlugin,
maplibreOlcPlugin,
maplibreGeohashPlugin,
maplibreTilecodePlugin,
maplibreCloudsPlugin,
maplibrePrecipitationPlugin,
maplibreEffectsPlugin,
maplibreSunPlugin,
maplibreRouteAnimationPlugin,
flightSimulatorPlugin,
maplibreDirectionsPlugin,
maplibreReverseGeocodePlugin,
maplibreDeckGlVizPlugin,
maplibreComponentsPlugin,
]);
// The Timelapse plugin records the map to a video blob but cannot depend on
// the app's Tauri I/O helpers, so the save step (native dialog under Tauri,
// download in the browser) is injected here once at startup.
setTimelapseVideoSaver((blob, { defaultName, extension, mimeType }) =>
saveBinaryFileWithFallback(blob, {
defaultName,
filters: [{ name: "Video", extensions: [extension] }],
browserTypes: [
{
description: "Video",
accept: { [mimeType.split(";")[0]]: [`.${extension}`] },
},
],
mimeType,
}),
);
// The Earthdata GIS plugin exports an ArcGIS service as a plain GeoTIFF but
// cannot re-encode it: ArcGIS has no COG output (`format=cog` falls back to
// PNG, and `format=tiff` returns a tiled file with no overviews), and the
// plugins package owns neither the COG encoder nor the app's file dialogs. Both
// are injected here once at startup, mirroring setTimelapseVideoSaver.
setEarthdataCogSaver(async (geoTiffBytes, defaultName) => {
// Imported on demand so the COG encoder's WASM is only fetched when a user
// actually downloads one.
const { convertGeoTiffToCog } = await import("@geolibre/processing");
const cogBytes = await convertGeoTiffToCog(geoTiffBytes);
const saved = await saveBinaryFileWithFallback(cogBytes, {
defaultName,
filters: [{ name: "Cloud Optimized GeoTIFF", extensions: ["tif"] }],
browserTypes: [{ description: "Cloud Optimized GeoTIFF", accept: { "image/tiff": [".tif"] } }],
mimeType: "image/tiff",
});
return saved !== null;
});
// The Zarr panel can open a store from a folder on disk, but reading a folder
// needs a filesystem API the plugins package does not have, so the picker is
// injected here the same way. Registered only where a folder dialog exists (the
// desktop app, or a browser with the File System Access API); elsewhere the
// panel shows no Browse folder button rather than one that cannot deliver.
if (zarrDirectoryPickerSupported()) {
setZarrLocalStoreProvider(pickZarrDirectory);
}
// Forget that a binding opened the Time Slider dock as soon as the plugin goes
// inactive by any route (#1512), so a later manual activation is not mistaken
// for a binding-opened one and closed out from under the user.
let timeSliderWasActive = false;
manager.subscribe(() => {
const active = manager.isActive(TIME_SLIDER_PLUGIN_ID);
if (active === timeSliderWasActive) return;
timeSliderWasActive = active;
if (!active) setTimeSliderOpenedByBinding(false);
});
let externalPluginsLoaded = false;
let externalPluginsLoadPromise: Promise<void> | null = null;
let externalPluginsLoadKey: string | null = null;
let externalPluginLoadIssues = new Map<string, string>();
const externalPluginsListeners = new Set<() => void>();
const EMPTY_PLUGIN_MANIFEST_URLS: string[] = [];
export function getPluginManager(): PluginManager {
return manager;
}
export function getExternalPluginLoadIssues(): ReadonlyMap<string, string> {
return externalPluginLoadIssues;
}
export function subscribeToExternalPluginLoads(listener: () => void): () => void {
// Shares the ready-state listener set so marketplace rows update for both
// successful loads and per-plugin load issues.
externalPluginsListeners.add(listener);
return () => externalPluginsListeners.delete(listener);
}
// Upgrade an installed external plugin in place by re-fetching its manifest URL
// and re-registering the published version. Used by the marketplace's Update
// action.
export async function upgradeExternalPlugin(
manifestUrl: string,
mapControllerRef: RefObject<MapController | null>,
): Promise<void> {
await reloadExternalUrlPlugin(manager, manifestUrl, createAppAPI(mapControllerRef));
}
// Install a plugin from a local `.zip` archive (desktop only). The Rust backend
// validates the archive and copies it into GeoLibre's app-data plugins
// directory so it persists across restarts; the plugins directory is then
// re-scanned so the new plugin loads without a reload. A reinstall of an
// already-loaded plugin id is unloaded first so the updated archive replaces it
// instead of being skipped by the loaded-source dedup. Returns the installed
// plugin id.
export async function installPluginArchive(
sourcePath: string,
mapControllerRef: RefObject<MapController | null>,
): Promise<string> {
if (!isTauriRuntime()) {
throw new Error("Installing plugin archives requires the desktop app.");
}
const pluginId = await invoke<string>("install_external_plugin_archive", {
sourcePath,
});
const app = createAppAPI(mapControllerRef);
// The archive was overwritten in place for a reinstall; drop the loaded copy
// so the forced re-scan re-registers the updated version under the same id.
unloadFilesystemPlugin(manager, pluginId, app);
const desktopSettings = useDesktopSettingsStore.getState().desktopSettings;
await ensureExternalPluginsLoadedWithSettings(desktopSettings, app, {
force: true,
});
return pluginId;
}
// Install a plugin from an uploaded `.zip` in the browser (web build). The
// archive is unpacked and validated client-side, registered immediately, and
// persisted in IndexedDB so it reloads on the next visit. On desktop, use
// installPluginArchive instead (it copies the zip onto disk via the backend).
// Returns the installed plugin id.
export async function installPluginArchiveFromFile(
fileName: string,
bytes: Uint8Array,
mapControllerRef: RefObject<MapController | null>,
): Promise<string> {
return installWebPluginArchive(manager, fileName, bytes, createAppAPI(mapControllerRef));
}
// Uninstall a plugin that was installed from a file in the browser.
export async function uninstallPluginArchiveFromFile(
pluginId: string,
mapControllerRef: RefObject<MapController | null>,
): Promise<void> {
await uninstallWebPlugin(manager, pluginId, createAppAPI(mapControllerRef));
}
// List plugins installed from a file (browser IndexedDB), for the Manage
// Plugins UI. Returns an empty list on desktop and where IndexedDB is absent.
export function listPluginArchivesFromFile(): Promise<InstalledWebPlugin[]> {
return listInstalledWebPlugins();
}
export function usePluginRegistry() {
useSyncExternalStore(
(listener) => manager.subscribe(listener),
() => manager.getVersion(),
() => manager.getVersion(),
);
return {
plugins: manager.list(),
isActive: (id: string) => manager.isActive(id),
getMapControlPosition: (id: string) => manager.getMapControlPosition(id),
getProjectState: () => manager.getProjectState(),
toggle: (id: string, appApi: ReturnType<typeof createAppAPI>) => {
const before = JSON.stringify(projectPluginStateSnapshot());
// Layer Swipe and split view are mutually exclusive comparison modes:
// stacking the swipe slider over a multi-pane grid fragments the
// workspace (#844). The reverse direction (entering split view turns
// swipe off) is handled by useSwipeSplitViewExclusivity.
const collapseGridForSwipe = id === SWIPE_PLUGIN_ID && !manager.isActive(id);
// Plugin controls are imperative MapLibre code, so a throw here escapes
// React's error boundaries. Contain it so one bad plugin can't break the
// toggle handler — surface it in diagnostics instead. Return without
// persisting so a half-applied failure is not written to the project.
try {
manager.toggle(id, appApi);
} catch (error) {
// Known limitation: if toggle throws after a partial mutation (e.g. the
// control attached but a later step failed), the in-memory PluginManager
// state may be inconsistent. Project persistence is protected by the
// early return below; in-memory state is not rolled back.
reportPluginError(id, "toggle", error);
return;
}
// Collapse the grid only once swipe actually activated, so a failed
// activation (a throw above, or addMapControl returning false) leaves the
// user's split-view layout intact. Done synchronously before React flushes
// effects so useSwipeSplitViewExclusivity sees the single-pane grid and
// doesn't undo the activation it just allowed.
// Relies on maplibre-swipe activating synchronously (activate returns
// false/undefined, never a Promise). PluginManager.activate marks a plugin
// active optimistically and only rolls back async failures via
// watchAsyncActivation, so isActive() would read true here before an async
// mount confirms — revisit this guard if swipe ever gains a dynamic import.
if (collapseGridForSwipe && manager.isActive(id)) {
const { mapLayout, setMapGrid } = useAppStore.getState();
if (mapLayout.rows * mapLayout.cols > 1) setMapGrid(1, 1);
}
persistProjectPluginState(before);
},
setMapControlPosition: (
id: string,
appApi: ReturnType<typeof createAppAPI>,
position: GeoLibreMapControlPosition,
) => {
const before = JSON.stringify(projectPluginStateSnapshot());
try {
manager.setMapControlPosition(id, appApi, position);
} catch (error) {
reportPluginError(id, "reposition", error);
return;
}
persistProjectPluginState(before);
},
getEffectsSettings,
// Live preview: push the appearance change straight to the engine for an
// instant redraw, but do NOT persist. A color-picker drag or slider scrub
// fires this every frame, so keeping persistence out avoids marking the
// project dirty and sweeping Zustand subscribers on every pixel of movement.
previewEffectsSettings: (next: Partial<EffectsSettings>) => {
// Contained like toggle/reposition: setEffectsSettings drives imperative
// canvas code (engine.applySettings) that can throw and escape React's
// error boundaries; surface it in diagnostics instead of crashing.
try {
setEffectsSettings(next);
} catch (error) {
reportPluginError(maplibreEffectsPlugin.id, "preview-effects", error);
}
},
// Commit: called once when an edit gesture ends (slider release, color
// input blur, reset, or the submenu closing). Persists only when the
// appearance actually differs from what the project already holds, so a
// no-op gesture does not flag the project dirty.
commitEffectsSettings: () => {
try {
const storedSettings =
useAppStore.getState().projectPlugins?.settings?.[maplibreEffectsPlugin.id];
const currentSettings = maplibreEffectsPlugin.getProjectState?.();
if (JSON.stringify(storedSettings ?? null) === JSON.stringify(currentSettings ?? null)) {
return;
}
useAppStore.getState().setProjectPlugins(projectPluginStateSnapshot());
} catch (error) {
reportPluginError(maplibreEffectsPlugin.id, "commit-effects", error);
}
},
};
}
// Built-in plugins are registered at module load so the toolbar can render
// plugin menu items on the first pass. This hook additionally kicks off the
// external plugin scan and reports whether it has finished.
export function useExternalPluginsReady(
mapControllerRef: RefObject<MapController | null>,
): boolean {
const desktopSettings = useDesktopSettingsStore((state) => state.desktopSettings);
useEffect(() => {
// mapControllerRef is a stable ref object, so it is intentionally not a
// dependency; createAppAPI dereferences .current lazily.
//
// Project-supplied plugin URLs are intentionally NOT loaded here: the scan
// only ever fetches/imports the user's installed URLs (desktop settings) and
// the bundled drop-ins. Untrusted project URLs are surfaced by
// useProjectPluginTrust and only reach this scan after the user trusts them
// (which adds them to desktopSettings and re-runs this effect). See #1062.
void ensureExternalPluginsLoadedWithSettings(desktopSettings, createAppAPI(mapControllerRef));
}, [desktopSettings]);
return useSyncExternalStore(
(listener) => {
externalPluginsListeners.add(listener);
return () => externalPluginsListeners.delete(listener);
},
() => externalPluginsLoaded,
() => externalPluginsLoaded,
);
}
export interface ProjectPluginTrustState {
/**
* Project-supplied plugin manifest URLs awaiting the user's trust decision.
* Empty when the opened project references no untrusted plugins (its URLs are
* already installed or bundled), which is the common case for a user's own
* saved projects.
*/
pendingUrls: string[];
/**
* Trust every pending URL: add it to the persisted desktop settings so it is
* installed like any marketplace/manual plugin. This re-runs the external
* plugin scan (via useExternalPluginsReady's settings dependency), which is
* what actually fetches and imports the now-trusted plugins.
*/
trust: () => void;
/** Dismiss the prompt for this session without loading or persisting anything. */
dismiss: () => void;
}
/**
* Gate the plugin manifest URLs carried inside an opened project behind an
* explicit user trust decision (#1062).
*
* When a project is opened, its `plugins.manifestUrls` are compared against the
* user's installed URLs and the bundled drop-ins. Any URL that is neither is
* "untrusted" and is surfaced here so the shell can show a trust prompt before
* the plugin's code is ever fetched or imported. Trusting persists the URLs to
* desktop settings (which loads them); dismissing loads nothing and persists
* nothing. A per-session dismissed set keeps a declined URL from re-prompting
* on every render or when another project references the same URL.
*/
export function useProjectPluginTrust(): ProjectPluginTrustState {
const projectManifestUrls = useAppStore(
(state) => state.projectPlugins?.manifestUrls ?? EMPTY_PLUGIN_MANIFEST_URLS,
);
const trustedManifestUrls = useDesktopSettingsStore(
(state) => state.desktopSettings.pluginManifestUrls,
);
const [dismissedUrls, setDismissedUrls] = useState<ReadonlySet<string>>(() => new Set());
const pendingUrls = useMemo(() => {
const { untrusted } = partitionProjectPluginManifestUrls(
projectManifestUrls,
trustedManifestUrls,
bundledPluginManifestUrls(),
);
return untrusted.filter((url) => !dismissedUrls.has(url));
}, [projectManifestUrls, trustedManifestUrls, dismissedUrls]);
const trust = useCallback(() => {
if (pendingUrls.length === 0) return;
const current = useDesktopSettingsStore.getState().desktopSettings;
useDesktopSettingsStore.getState().setDesktopSettings({
...current,
pluginManifestUrls: mergeStringLists(current.pluginManifestUrls, pendingUrls),
});
}, [pendingUrls]);
const dismiss = useCallback(() => {
if (pendingUrls.length === 0) return;
setDismissedUrls((previous) => {
const next = new Set(previous);
for (const url of pendingUrls) next.add(url);
return next;
});
}, [pendingUrls]);
return { pendingUrls, trust, dismiss };
}
/**
* Enforces mutual exclusivity between Layer Swipe and split view (#844). The two
* are competing comparison tools: overlaying the swipe slider on a multi-pane
* grid fragments the workspace, so whenever the grid becomes multi-pane the
* Layer Swipe control is deactivated. The reverse direction (activating swipe
* collapses the grid to a single map) lives in `usePluginRegistry().toggle`.
*
* Mounted once near the app root so it covers every way into split view — the
* View menu, loading a project, or a plugin — not just the toolbar item.
*/
export function useSwipeSplitViewExclusivity(
mapControllerRef: RefObject<MapController | null>,
): void {
const paneCount = useAppStore((state) => state.mapLayout.rows * state.mapLayout.cols);
useEffect(() => {
if (paneCount <= 1 || !manager.isActive(SWIPE_PLUGIN_ID)) return;
// Deactivate via the manager and persist, mirroring usePluginRegistry's
// toggle so the project records swipe as off and a stray throw from the
// imperative control can't escape React.
const before = JSON.stringify(projectPluginStateSnapshot());
try {
manager.toggle(SWIPE_PLUGIN_ID, createAppAPI(mapControllerRef));
} catch (error) {
reportPluginError(SWIPE_PLUGIN_ID, "toggle", error);
return;
}
persistProjectPluginState(before);
}, [paneCount, mapControllerRef]);
}
// Manifest URLs for plugins baked into the build under public/plugins/<id>/.
// Resolved against the app origin and base so they fetch same-origin on both
// the web build and the desktop build (which serves the same frontend from
// tauri://localhost, allowed by `connect-src 'self'`). These are injected at
// load time rather than stored in Settings, so a baked-in plugin always loads
// and cannot be removed by the user. The URL loader skips the scheme allow-list
// applied to user/project URLs, so the desktop tauri:// origin is accepted.
export function bundledPluginManifestUrls(): string[] {
if (typeof window === "undefined") return [];
// Resolve against a base that always ends in "/" so a non-trailing-slash
// BASE_URL (e.g. "/geolibre") cannot mangle the path into "/geolibreplugins".
const base = import.meta.env.BASE_URL.endsWith("/")
? import.meta.env.BASE_URL
: `${import.meta.env.BASE_URL}/`;
return bundledPluginManifestPaths.map(
(path) => new URL(path, new URL(base, window.location.href)).href,
);
}
function ensureExternalPluginsLoadedWithSettings(
desktopSettings: ReturnType<typeof useDesktopSettingsStore.getState>["desktopSettings"],
app: ReturnType<typeof createAppAPI>,
options?: { force?: boolean },
): Promise<void> {
// Only the user's installed URLs (desktop settings) and the bundled drop-ins
// are auto-loaded. Project-supplied URLs are deliberately excluded here so
// opening a project never fetches or imports third-party plugin code; they
// reach this scan only after the user trusts them, at which point they are in
// desktopSettings.pluginManifestUrls (see useProjectPluginTrust / #1062).
const bundledManifestUrls = bundledPluginManifestUrls();
const pluginManifestUrls = mergeStringLists(
bundledManifestUrls,
desktopSettings.pluginManifestUrls,
);
const loadKey = JSON.stringify({
additionalPluginDirectories: desktopSettings.additionalPluginDirectories,
pluginManifestUrls,
});
// `force` re-scans even when the merged settings are unchanged. Installing a
// zip writes a new archive into the app-data plugins directory without
// touching the settings that make up loadKey, so the cache-key short-circuits
// below would otherwise skip loading the freshly installed plugin.
if (!options?.force && externalPluginsLoaded && externalPluginsLoadKey === loadKey) {
return Promise.resolve();
}
if (!options?.force && externalPluginsLoadPromise && externalPluginsLoadKey === loadKey) {
return externalPluginsLoadPromise;
}
externalPluginLoadIssues = new Map();
notifyExternalPluginsListeners();
setExternalPluginsLoaded(false);
externalPluginsLoadKey = loadKey;
// Serialize scans: loadExternalPlugins reads and writes module-level state
// (the loaded-plugin map) across awaits, so two in-flight scans could both
// pass the dedup check and double-register the same plugin. Waiting for the
// previous scan (which never rejects) keeps at most one scan running.
const previousLoad = externalPluginsLoadPromise ?? Promise.resolve();
const loadPromise = previousLoad
.then(() => {
// Unregister URL plugins whose manifest URL was removed from the merged
// list (e.g. uninstalled from the marketplace) so the Plugins menu updates
// and any active control is torn down without a reload. This runs after
// the previous scan settles so a plugin whose load was still in flight is
// already recorded and can be removed.
const unloaded = unloadRemovedUrlPlugins(manager, pluginManifestUrls, app);
if (unloaded.length) {
console.info(`Unloaded external GeoLibre plugins: ${unloaded.join(", ")}`);
}
return loadExternalPlugins(
manager,
desktopSettings.additionalPluginDirectories,
pluginManifestUrls,
// Only manifests fetched from the bundled drop-in URLs may use
// activeByDefault (they are baked into the build, hence trusted).
{ bundledManifestUrls },
);
})
.then((result) => {
externalPluginLoadIssues = new Map(
result.issues.map((issue) => [issue.sourceUrl ?? issue.archiveName, issue.message]),
);
notifyExternalPluginsListeners();
if (result.loadedPluginIds.length) {
console.info(
`Loaded external GeoLibre plugins from ${result.pluginSources.join(
", ",
)}: ${result.loadedPluginIds.join(", ")}`,
);
}
for (const issue of result.issues) {
console.warn(`Skipped external plugin archive '${issue.archiveName}': ${issue.message}`);
}
})
.catch((error) => {
console.warn("Could not load external GeoLibre plugins.", error);
})
.finally(() => {
// A settings change can start a new load while this one is in flight.
// Only the load that still owns the current key may mark plugins ready.
if (externalPluginsLoadKey !== loadKey) return;
// A forced re-scan (install) chains a second load onto this one under the
// SAME key, so guard the clear by identity: only null the slot when it
// still points at this promise, never at the newer in-flight load.
if (externalPluginsLoadPromise === loadPromise) {
externalPluginsLoadPromise = null;
}
setExternalPluginsLoaded(true);
});
externalPluginsLoadPromise = loadPromise;
return loadPromise;
}
/**
* Bind a layer's internal time dimension to the Time Slider: persist the
* binding on the layer's metadata (mirroring how a vector layer's `TimeBinding`
* is stored, so it survives a project round-trip) and open the dock if it is not
* already showing.
*
* Shared by the Layers panel's "Bind to Time Slider" action and the plugin API's
* `registerTemporalLayer(..., { bind: true })`, so both write the same thing.
*
* @param layerId - The store layer to bind.
* @param adapter - Its temporal adapter, whose time values set the timeline range.
* @param mapControllerRef - Used to build the app API when activating the dock.
* @returns True when the layer was bound; false when its time axis holds no
* usable timestamp, or the layer is gone.
*/
export function bindTemporalLayer(
layerId: string,
adapter: TemporalLayerAdapter,
mapControllerRef?: RefObject<MapController | null>,
): boolean {
const binding = buildSelectorTimeBinding(adapter.dimension ?? "time", adapter.getTimeValues(), {
granularity: adapter.granularity,
displayUnits: adapter.displayUnits,
});
if (!binding) return false;
const store = useAppStore.getState();
const layer = store.layers.find((item) => item.id === layerId);
if (!layer) return false;
store.updateLayer(layerId, {
metadata: { ...layer.metadata, timeBinding: binding },
// A selector binding replaces whatever was on the layer before. Drop any
// transient filter a previous vector binding left behind, or it would keep
// hiding features alongside the adapter (matching what the vector bind
// dialog does when it commits).
timeFilter: undefined,
});
activateTimeSliderForBinding(mapControllerRef);
return true;
}
/**
* Open the Time Slider dock because a layer was just bound to it, and remember
* that the binding is what opened it so {@link useTimeSliderAutoClose} may close
* it again when the last binding goes away (#1512).
*
* A no-op when the dock is already showing — including when the user opened it
* themselves, which deliberately leaves the "opened by a binding" flag false so
* their dock is never taken away underneath them.
*
* Call this **after** the binding has been written to the layer's metadata, so
* the dock adopts it on activation.
*
* @param mapControllerRef - Used to build the app API for activation.
*/
export function activateTimeSliderForBinding(
mapControllerRef?: RefObject<MapController | null>,
): void {
if (manager.isActive(TIME_SLIDER_PLUGIN_ID)) return;
const before = JSON.stringify(projectPluginStateSnapshot());
try {
manager.activate(TIME_SLIDER_PLUGIN_ID, createAppAPI(mapControllerRef));
} catch (error) {
// Plugin controls are imperative MapLibre code, so a throw here would escape
// React's error boundaries. Contain it, exactly as usePluginRegistry.toggle
// does, and leave the project state unwritten.
reportPluginError(TIME_SLIDER_PLUGIN_ID, "toggle", error);
return;
}
setTimeSliderOpenedByBinding(manager.isActive(TIME_SLIDER_PLUGIN_ID));
persistProjectPluginState(before);
}
/**
* Close a binding-opened Time Slider once it has nothing left to drive (#1512).
*
* `activatePlugin` / `registerTemporalLayer({ bind: true })` open the dock when
* the first temporal layer appears, but nothing closed it again when the last
* one went away by a route other than the Layers panel's explicit "Unbind"
* action — removing the bound layer, or a plugin swapping a temporal dataset for
* a single-period one. The dock then lingered over the map, implying a timeline
* no layer has.
*
* Only a dock opened *by* a binding is closed; one the user opened from the
* Plugins menu stays put. `isTimeSliderIdle` additionally keeps it open while
* the dock's own raster sources or a KML `<TimeSpan>` overlay remain, since the
* dock is the only way to reach those.
*
* Mounted once near the app root so it covers every way a binding can
* disappear, not just the Layers panel.
*/
export function useTimeSliderAutoClose(mapControllerRef: RefObject<MapController | null>): void {
useEffect(() => {
// Subscribed rather than selected from the store so no component re-renders
// on every layer edit just to run this check.
const check = () => {
if (!shouldCloseTimeSliderDock(manager.isActive(TIME_SLIDER_PLUGIN_ID), isTimeSliderIdle)) {
return;
}
const before = JSON.stringify(projectPluginStateSnapshot());
try {
// Deactivating prunes the dock's own store layers, which re-enters this
// subscription; those passes find the dock already idle-and-closing and
// the plugin's own deactivate is a no-op once its control is gone.
manager.deactivate(TIME_SLIDER_PLUGIN_ID, createAppAPI(mapControllerRef));
} catch (error) {
reportPluginError(TIME_SLIDER_PLUGIN_ID, "toggle", error);
return;
}
persistProjectPluginState(before);
};
check();
return useAppStore.subscribe(check);
}, [mapControllerRef]);
}
function readPluginSelection(): GeoLibreSelection {
const state = useAppStore.getState();
const layer = state.layers.find((item) => item.id === state.selectedLayerId);
if (!layer || state.selectedFeatureIds.length === 0) {
return { layerId: state.selectedLayerId, features: [] };
}
const selected = new Set(state.selectedFeatureIds);
const features = (layer.geojson?.features ?? []).filter((feature, index) =>
selected.has(String(feature.id ?? index)),
);
return { layerId: state.selectedLayerId, features };
}
export function createAppAPI(mapControllerRef?: RefObject<MapController | null>) {
const store = useAppStore.getState();
// Captured so methods that delegate to plugin helpers taking the AppAPI
// itself (e.g. addCogLayer -> addRasterToMap) can pass `api`. Only read
// when those methods are called, which is always after assignment.
const api = {
setBasemap: (url: string) => store.setBasemapStyleUrl(url),
addGeoJsonLayer: (name: string, data: GeoJSON.FeatureCollection, sourcePath?: string) => {
const id = store.addGeoJsonLayer(name, data, sourcePath);
return id;
},
listLayers: () =>
useAppStore.getState().layers.map(({ id, name, type, visible, opacity }) => ({
id,
name,
type,
visible,
opacity,
})),
getLayerFeatures: (layerId: string) => {
const layer = useAppStore.getState().layers.find((item) => item.id === layerId);
if (!layer) throw new Error(`No layer with id "${layerId}"`);
return layer.geojson?.features ?? [];
},
getSelectedFeatures: () => readPluginSelection().features,
getSelectedLayerId: () => useAppStore.getState().selectedLayerId,
getDrawnFeatures: () =>
useAppStore
.getState()
.layers.flatMap((layer) =>
layer.metadata.sourceKind === SKETCHES_SOURCE_KIND ? (layer.geojson?.features ?? []) : [],
),
onSelectionChange: (callback: (selection: GeoLibreSelection) => void) =>
useAppStore.subscribe((state, previous) => {
if (
state.selectedLayerId !== previous.selectedLayerId ||
state.selectedFeatureIds !== previous.selectedFeatureIds
) {
callback(readPluginSelection());
}
}),
addTileLayer: (name: string, url: string, options?: GeoLibreTileLayerOptions) =>
store.addTileLayer(
name,
{ type: "xyz", tiles: [url], url, ...tileLayerStoreOptions(options) },
options?.beforeLayerId ?? null,
),
// Intentionally identical to addTileLayer except for the layer `type`.
// XYZ and WMTS tile templates render through the same syncRasterTileLayer
// path; the distinct type only changes how the layer is labelled/stored,
// so the two helpers share an implementation by design (not a copy-paste).
addWmtsLayer: (name: string, url: string, options?: GeoLibreTileLayerOptions) =>
store.addTileLayer(
name,
{ type: "wmts", tiles: [url], url, ...tileLayerStoreOptions(options) },
options?.beforeLayerId ?? null,
),
addWmsLayer: (name: string, options: GeoLibreWmsLayerOptions) => {
const { beforeLayerId, url, layers, styles, format, transparent, version, ...tileOptions } =
options;
// TypeScript enforces these, but an untyped JS plugin can pass "" — an
// empty endpoint yields a relative GetMap URL that resolves against the
// app origin and passes the store's empty-tile guard, persisting a layer
// that only 404s. Reject at the API boundary instead.
if (!url) {
throw new Error("addWmsLayer: options.url must be a non-empty string.");
}
if (!layers) {
throw new Error("addWmsLayer: options.layers must be a non-empty string.");
}
const tileSize = tileOptions.tileSize ?? 256;
const resolvedStyles = styles ?? "";
const resolvedFormat = format ?? "image/png";
const resolvedTransparent = transparent ?? true;
const resolvedVersion = normalizeWmsVersion(version);
// Mirror setMapProjection's unrecognized-value warning so a typo'd
// version from an untyped JS plugin is visible instead of silently
// coerced. Valid shorthand in a recognized 1.x family (e.g. "1.3") is
// not warned about — it normalizes cleanly.
if (
version !== undefined &&
(typeof version !== "string" || !/^1\.\d/.test(version.trim()))
) {
console.warn(
`[GeoLibre] addWmsLayer: unsupported WMS version "${String(
version,
)}"; using "${resolvedVersion}".`,
);
}
const tileUrl = createWmsTileUrl({
endpoint: url,
layers,
styles: resolvedStyles,
format: resolvedFormat,
transparent: resolvedTransparent,
tileSize,
version: resolvedVersion,
});
return store.addTileLayer(
name,
{
type: "wms",
tiles: [tileUrl],
url,
// Persist the WMS request parameters so the layer round-trips through
// a saved project, mirroring the Add Data dialog's WMS source.
source: {
layers,
styles: resolvedStyles,
format: resolvedFormat,
transparent: resolvedTransparent,
version: resolvedVersion,
},
...tileOptions,
},
beforeLayerId ?? null,
);
},
// Unlike the tile helpers above, a COG is read client-side by the shared
// raster control. Besides keeping every COG path on one renderer, this is
// what mirrors the layer as `maplibre-gl-raster`, making the full Raster
// symbology section available in the Style panel.
addCogLayer: (name: string, url: string, options?: GeoLibreCogLayerOptions) => {
const bands = options?.bands
?.split(",")
.map((value) => Number(value.trim()))
.filter((value) => Number.isInteger(value) && value > 0);
const range =
options?.rescaleMin !== undefined && options.rescaleMax !== undefined
? ([options.rescaleMin, options.rescaleMax] as [number, number])
: undefined;
return addRasterToMap(api, url, {
name,
// STAC assets are already COGs with an HTTP(S) range-readable URL.
// Render them directly through the GPU COG engine; the WASM tiler is
// intended for local files and can leave remote programmatic layers
// registered without producing pixels.
defaults: { engine: "maplibre-gl-raster" },
state: {
...(bands?.length ? { bands, mode: bands.length >= 3 ? "rgb" : "single" } : {}),
...(options?.colormap !== undefined ? { colormap: options.colormap } : {}),
...(range ? { rescale: [range] } : {}),
...(options?.nodata !== undefined ? { nodata: options.nodata } : {}),
...(options?.opacity !== undefined ? { opacity: options.opacity } : {}),
},
...(options?.beforeLayerId ? { beforeId: options.beforeLayerId } : {}),
});
},
// Zarr goes through the components plugin's shared @carbonplan/zarr-layer
// control for the same reason as addCogLayer: the host owns the renderer, so
// a plugin does not bundle (and fail to activate) a second copy.
addZarrLayer: (name: string, url: string, options: GeoLibreZarrLayerOptions) =>
addZarrRasterLayer(api, {
url,